text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
ICMake Part 3 In addition to the operators of the C programming language, icmake recognizes some `special' operators. These are: The `younger' operator is used to compare two strings which represent filenames. An expression using younger is evaluated to non-zero or zero and may be used in a condition. The operator `newer' is an alias for younger. The expression using the younger operator yields non-zero if a file with the name represented by the left operand is more recent than the file represented by the right operand. E.g., the following code prints a message if file main.c is more recent than main: if ("main.c" newer "main") printf ("main.c is more recent than main\n"); The `older' operand compares two files and yields non-zero if the file represented by the left operand is older than the file represented by the right operand. When the date of a file is compared using older or younger and when no file with such a name is present, then the age of the file is assumed to be infinite. A consequence of this implementation is that as in the following code example, a message is displayed if “try” does not exist: if ("try.c" younger "try") printf ("try.c should be compiled!!\n"); Though icmake does not allow the use of operators on different types, it is possible to convert one type into another. The conversion of a type into another type is referred to as a `type cast'. Type casts are denoted by a type name in parentheses before the operand which should be converted, e.g., (int)x converts the operand x to integer representation. Type casts are not allowed on all types. For example, a list variable cannot be converted to int. The following type casts are permitted: An integer may be cast to string. For example: string stringvar; stringvar = (string) 14; // now, stringvar is "14" A string may be cast to int. This is the reverse action of the type cast shown in the listing above. A string may be cast to a list. This may be particularly useful when filenames should be added to or removed from a list, e.g., in the listing below, the filename “main.c” (a string) is removed from the list cfiles: list cfiles; // cfiles is set to hold a list of cfiles = makelist ("*.c"); // all filenames with extension .c cfiles -= (list) "main.c"; // filename main.c is removed from // the list Note that the string “main.c” must be converted to a list type to allow the subtraction from the list. Other typecasts, specifically from a string to an ascii-representation, can be realized through specialized functions (see, e.g., the function ascii() in the next section). Built into icmake is a number of functions which may be used to perform special operations, such as scanning a directory for files, displaying information, etc.. Here, all built-in functions are described. arghead: int arghead(string): This function sets the argument head to string. The `argument head' is used with the functions exec() and execute(), described below. argtail: int argtail(string): This function sets the argument tail to string. The `argument tail' is used with the functions exec() and execute(), described below. ascii: int ascii(string): This function returns the ascii-number of the first character in the string, supplied as argument, e.g., ascii(“A”) returns 65. ascii: string ascii(int): The overloaded function, which expects an int argument, returns a string representation of a numeric ascii number. e.g., ascii(65) returns “A”. change_base: string change_base (string, string): This function changes the basename in the string which is supplied as its first argument to the basename which is supplied as second argument. The string with the changed basename is returned. Example: string name; name = change_base ("main.c", "test"); // name now is "test.c" change_ext: string change_ext(string, string): This function changes the extension in the string which is supplied as its first argument to the extension which is supplied as second argument. The modified string is returned. The extension (the second argument) may be specified as an empty string (“”); in this case change_ext() removes the extension. Also, the extension may be specified as one dot (”.“); in this case change_ext() removes the extension but leaves the dot. Example: char name; name = change_ext ("main.c", "o"); // name now is "main.o" name = change_ext (name, ""); // name now is "main" name = change_ext (name, "."); // name now is "main." change_path: string change_path(string, string): This function changes the path in the string which is supplied as its first argument to the path which is supplied as second argument. Example: string name; // name is now "/bin/prog" name = change_path ("c:/usr/local/bin/prog", "/bin"); name = change_path (name, ""); // name is now "prog" chdir: string chdir(int, string): This function changes the current working directory to the supplied name. The first int argument may be P_CHECK or P_NOCHECK. This argument is optional. When absent, P_CHECK is assumed. Failure to change the working directory with the presence of P_CHECK leads to the termination of icmake process. However, on completion of the icmake process the original directory is always restored. A string containing the new working directory, always ending in a directory separator, is returned. The string argument may terminate in a final slash. The returned string can be used to inspect whether the requested directory is reached, given that the modifier P_NOCHECK is supplied as first argument. Two special string arguments are recognized by chdir(): a. A directory argument which consists of one dot (i.e., the string ”.“) realizes a `change' to the current directory. The return value is then a string holding the current working directory. b. A directory argument which is an empty string (i.e., the string ”“) will not produce a directory change. Instead, the directory from which icmake was started originally is returned. Example: // print the current working directory printf("Current dir: ", chdir ("."), "\n"); chdir ("/usr/bin"); // change to directory /usr/bin // print startup directory printf ("Startup dir: ", chdir (""), "\n"); cmdhead: int cmdhead(string): This function sets the command head to string. The `command head' is used with the functions exec() and execute(), described below. cmdtail: int cmdtail(string): This function sets the command tail to string. The `command tail' is used with the functions exec() and execute(), described below. echo: int echo(int): This function determines whether, before the execution of a command, the command will be displayed. The argument of the function determines the displaying mode: when zero, displaying is suppressed; else, commands are displayed before execution. Two predefined constants are available for use as an argument to echo(): the constants ON and OFF. The values of these constants are, respectively, 1 and 0. Initially, echoing is on. Example: echo (ON); // commands will be displayed echo (OFF); // commands will not be displayed element: string element(int, list): This function retrieves a string from a list. The order number of the name in the list is given by the first argument. Note that this index is zero-based, i.e., the first element in the list has index 0. The last element in the list has index sizeoflist(list) - 1. Example: list l; string n; int i; l = makelist ("*.c"); for (i = 0; i < sizeoflist (l); i++) if (element (i, l) newer "main") printf ("Source file ", element (i, l), " is more recent than main\n"); element: string element(int, string): This function retrieves a substring of one character from the string given as its second argument. The character which is returned is found in the second (string) argument at the offset position specified in the first (int) argument. This index is zero-based: the first character of the string has index 0. Example: string s; int count; i; count = 0; s = "Hello world"; for (i = 0; element(i, s); i++) count++; printf("String '", s, "' contains ", count, " characters.\n"); exec: int exec(int, following arguments are the arguments which should be passed to the called program. These arguments may be ints, lists or strings. Each command is composed of the program name (the second argument), followed by the current setting of the command head (see cmdhead(), followed by all arguments and terminated with the command tail (see cmdtail()). Each argument to the command is prefixed with the argument head (see arghead()) and postfixed by the argument tail (see argtail()). execute: int execute(int, string, string, string, ..., string, third argument is the command head (a string). This string is used as first argument to the program name. The string may be empty (i.e., ”“), in which case no command head is used. d. The fourth argument is the argument head (a string). This string is prefixed to all following arguments. The string may be empty, in which case no argument head is used. e. The following arguments are the arguments which should be passed to the called program. These arguments may be ints, lists or strings. f. The next to the last argument is the argument tail (a string). This string is postfixed to each argument passed to the called program. The string may be empty, in which case no argument tail is used. g. The last argument is the command tail (a string). The command run by the execute() function is postfixed with this string. The string may be empty, in which case no command tail is used. After execution, execute() resets the command head, command tail, argument head and argument tail to empty strings. Both the exec() and execute() functions terminate the making process if error checking is turned on (mode flag P_CHECK) and if the run command exits with a non-zero exit value. If error checking is off, the exit status of the child process is returned. exists: int exists(string): This function tests if a file exists. The file name is supplied as argument. A non-zero value is returned when the file exists; else, zero is returned. if (exists ("main.c")) printf ("file main.c found\n"); else printf ("file main.c not found\n"); fgets: list fgets(string, int): This function reads a line of text from the file whose name is given as its first (string) argument. Reading starts at the offsetposition specified in the second (int) argument. A list is returned, containing as its first element the string which was read, including the final newline character (as it is returned by the C++ function fgets()). The second element of the returned list contains the string representation of the offset of the file after the line was read. This string can be cast to an int. Example: // showing the file info.doc on the screen: int offset; list l; for ( offset = 0; l = fgets("info.doc", offset); offset = (int)element(1, l) ) printf(element(0, l)); fprintf: int fprintf(string, ...): This function appends information to the file whose name is given as its first string argument. The remaining arguments define the information which is written to the file. The information is always appended to an existing file, which is opened in textmode. fprintf() acts analogously to printf() (see below), but the information is written to file rather than to screen. The arguments beyond the first argument of fprintf() define the information to print and may be ints, lists or strings. Example: fprintf ("file.txt", 1, " line written to file.txt\n"); get_base: string get_base(string): This function returns the basename of the filename stored in the string argument. The empty string is returned if the argument contains no basename. This happens when a disk or a root directory is specified in string. It may also happen if the syntax rules for a filename specification are violated. Example: // prints 'main' printf(get_base ("/path/main.c")); // prints 'No basename: ' printf("No basename: ", get_base ("/")); getch: string getch(): This function returns one character as a ministring. The character is read from the standard input stream (usually the keyboard). Under Unix, this function waits until a key and the enter key are pressed. Example: printf(getch()); // prints a character // (or an empty string) get_ext: string get_ext(string): This function returns the extension in the string argument of the function. The empty string is returned if the argument does not contain an extension. Example: printf(get_ext ("/path/main.c")); // prints 'c' printf(get_ext ("main")); // returns empty string get_path: string get_path(string): This function returns the path stored in the string argument of the function. An empty string is returned if string does not contain a disk specifier. The function returns the longest possible pathname which can be derived from the string argument. Example: printf(get_path ("/path/main.c")); // prints '/path/' get_path ("main.c"); // returns an empty string getpid: int getpid(): This function returns the process number of the currently executing icmake program. Example: // this function kills the current process.. // analogous to exit() void harakiri() { exec ("kill", "-9", getpid ()); } // this function returns a name for a temporary file // based on the process ID number file names are, // e.g., "/tmp/_TMPFILE.1256" string tempfilename () { return ("/tmp/" + "_TMPFILE." + (string)getpid()); } gets: string gets(): This function returns the return value of the C function gets() as a string. The function accepts character, including backspaces allowing corrections, until the enter-key is pressed. The entered characters are returned in a string. Example: printf(gets()); // prints a string // (or an empty string) makelist: list makelist(int, string): This function makes a list of strings, representing filenames which match the expanded form of its argument. The arguments are an optional int, specifying the type of directory entries to search for, and a string specifying the file mask. The returned list may hold zero or more names. The first int argument specifies the type of entries to search for. It may be O_FILE (when searching for files), O_DIR (when searching for directories) or O_SUBDIR (when searching for subdirectories). The difference between the searching for directories and the searching for subdirectories lies in the fact that the current directory, denoted by ”.“, and the parent directory, denoted by ”..“, are not considered subdirectories but are considered directories. This argument may be absent, in which case O_FILE is assumed. A fourth type is O_ALL. When this type is given, makelist() searches for all directory entries irrespective of their type; e.g., under DOS, hidden and system files are matched as well as normal files or (sub)directories. The behavior of makelist() is dependent on the used platform, e.g., to search for all files or (sub)directories under DOS, the file mask ”*.*“ must be given. The file mask ”*“ will fail to find files or (sub)directories with an extension. Furthermore, makelist() behaves under DOS similar to the C run-time functions _dos_findfirst() and _dos_findnext(); e.g., makelist(O_DIR, ".") returns a list containing the name of the current directory. In a similar vein, the filemask ”*“ will, under Unix, fail to find files or (sub)directories starting with a dot. Example: list l; l = makelist ("*.c"); printf ("All found *.c files are: ", l, "\n"); l = makelist (O_SUBDIR, "*"); printf ("All found subdirectories are: ", l, "\n"); makelist: The function makelist(), furthermore, has overloaded versions. These, apart from a first optional int indicating the type of entries to search for, expect three arguments. The arguments of these versions are a (string) mask; a comparison operator which must be younger, newer or older; and a (string) referencefile. The function returns a list of files matching the mask which are older or newer than the referencefile. An optional first int argument, which specifies the type of directory entry (O_FILE, O_DIR or O_SUBDIR) may be present. Example: list l; l = makelist ("*.c", newer, "libprog.a"); printf ("All .c files newer than libprog.a are: ", l, "\n"); printf: int printf(int, ...): This function displays information. The arguments define the information to print and may be ints, lists or strings. A list is printed as a series of all its elements with spaces in between. putenv: void putenv(string): This function may be used to set environment variables during the execution of icmake programs. The environment variables remain active during the complete icmake run. Example: main() { putenv("term=vt320"); // set variable system("set"); // show settings } sizeof: int sizeof(list): This function performs the same action as sizeoflist(). sizeoflist: int sizeoflist(list): This function determines the number of names held in a list. Example: list l; int i; list = makelist ("*.c"); i = sizeoflist (l); printf ("There are ", i, " names in the list.\n"); stat: list stat(int, string): This function attempts to retrieve file attributes of the file specified by the second string argument. The first int argument may be P_CHECK or P_NOCHECK. When absent, P_CHECK is assumed. The making process is aborted when stat() fails to retrieve file attributes and when P_CHECK is given for the first argument. The returned list holds the following information: a. The first element is a string representation of the mode of the file or directory. This string can be converted to an int where the following bits represent the modes: The bit S_IFDIR is set when the entry is a directory. The bit S_IFCHR is set when the entry is a character-special. The bit S_IFREG is set when the entry is a regular file. The bit S_IREAD is set when the entry is readable. The bit S_IWRITE is set when the entry is writeable. The bit S_IEXEC is set when the entry is executable. The second element is the file size, also represented as a string. strlen: int strlen(string): This function returns the number of characters in the string which is supplied as its argument. Its working is analogous to the function strlen() in C. strlwr: string strlwr(string): This function returns a copy of the string which is supplied as argument in lower case. strupr: string strupr(string): This function returns a copy of the string which is supplied as argument in upper case. strtok: list strtok (string, string): This function parses the first string in substrings, separated from each other by the separators specified in the second string. Each substring is an element of the returned list. If no separators are specified (i.e., the second string is empty), the individual characters of the first string become the elements of the returned list. Example: list l; int i; l = strtok("Hello-world\n", "-"); printf("Two elements: ", l, "\n"); l = strtok("Hello-world\n", ""); printf("A string of ", sizeof(l), " characters\n"); substr: int substr(string, string) This function searches for the string which is given as the second argument in the string given as first argument. The position where the second string occurs in the first string is returned. The value -1 is returned when the second string does not occur in the first string. system: int system(int, string): This function activates the operating system's command interpreter to run the command defined by the argument. The string holds the command to execute and, if needed, its arguments. The first argument specifies whether a failure of the system() function should terminate the making process. The value of this int may be P_CHECK or P_NOCHECK. This argument may be absent, in which case P_CHECK is assumed. The return value of system() is zero when the command could successfully be executed. A return value which is not zero can be received by the makefile only when P_NOCHECK is given as first argument. system() succeeds if the command could be executed and if the return value of the command itself is
http://www.linuxjournal.com/article/2776?quicktabs_1=2
CC-MAIN-2015-32
refinedweb
3,247
66.33
Search Criteria Package Details: swift-bin 5.0-1 Dependencies (8) - clang (clang-assert, clang-pypy-stm, clang-polly-svn, clang39, clang-trunk, clang38, clang-lw-git, llvm-git) - icu62 - libbsd (libbsd-git) - libutil-linux (util-linux-aes, libutil-linux-selinux) - libxml2 (libxml2-linenum, libxml2-git) - python2 (pypy19, stackless-python2) - patchelf (make) - rpmextract (rpm-org) (make) Required by (5) - sourcekitten (requires swift-language) - sourcekitten (requires swift-language) (make) - swen - swift-protobuf-git (requires swift-language) - swiftlint (requires swift-language) Sources (2) - - Latest Comments 1 2 3 4 5 6 ... Next › Last » eschwartz commented on 2019-03-03 02:13 There's no explicit rule against it, but I do think it is sort of ugly and it's not exactly good practice... you can see how it caused a mess here... generally multiple packages building towards the same software are supposed to provide unique use cases that aren't handled by other variants yet, and typically -bin packages will repackage an upstream binary on the rationale that it is the version which is tested and supported by upstream -- and is usually standalone, without requiring external dependencies. If this is just a matter of build times, I'm genuinely curious why it isn't a superior alternative, to simply host an unofficial repository containing a built version of the package. I think it would probably be a good idea to keep in mind that, whether accidental or not, manipulating the ld.so.conf path is always, without exception, a potential sledgehammer... and must therefore be treated with thoughtful care. It has the power to override /usr/lib, no less than installing an LD_LIBRARY_PATH or LD_PRELOAD to /etc/profile.d/ The ncurses breakage I can understand how it might not have been foreseen. But symlinking ICU is just wrong, every time someone does a partial update of their system and someone suggests symlinking the upgraded library soname, the support staff needs to yet again explain how this is a horrible idea and the whole reason sonames change is because they are incompatible, etc. etc. etc... and then there is a package which installs and relies on something like this??? Even if it did not leak into the global namespace and risk silently corrupting peoples' ICU-using applications, I would feel obligated to point out that swift itself would be using incompatible ICU symbols. ... The corrupted soname may be because of and is generally disappointing that patchelf doesn't perform as expected, but actually in retrospect I'm not sure you can modify an ELF to extend the size of a DT_NEEDED tag at all... not that this is useful insight when using it to exchange a single character in a NEEDED field for e.g. libalpm.so.11.0.1 (libcurl.so.4 -> libcurl.so.5) results in ldconfig: file ./libalpm.so.11.0.1 is truncated All things considered symlinks into a private RPATH may indeed be the best option, but I would still advise you to link to ln -s ../../${lib}w.so.6 rather than risk swift breaking whenever ncurses 7 becomes a thing. ... As long as the package has been fixed so it no longer stops peoples' systems from booting (albeit two weeks after the issue was reported), I guess I'm not going to force a deletion request for it. But as I said above, I guess I don't really see why it wouldn't be a better solution to host a prebuilt repository instead. refi.64 commented on 2019-03-02 19:04 Okay, package updated, apologies for the initramfs mess. I separated the exported libraries outside the ldconfig paths and triple-checked them to make sure nothing was unintentionally seeping in. Is there a set rule for this? It's not in the AUR guidelines, and until swift maybe gets in community, not everyone wants to spend the time compiling it. I will admit I did not realize icu62 was on the AUR. I know about patchelf --replace-needed, but it breaks ldconfig due to a glibc bug. I did some research and was finally able to track it down and report it, but until then I had to use hacks to keep the ncurses symlinks out of the ldconfig path. I will also admit, the system breakage was...very, very bad, but at the same time it was a complete accident due to the ldconfig paths. It's not as if I intentionally took a hammer to everyone's systems. Swift takes a really freaking long time to build, and not everyone who wants to build it might be able to. I'll happily take this down if we get Swift in community, but until then this does prove useful for some people. eschwartz commented on 2019-02-28 22:46 Unfortunately, this now means that the package is a lie, as a -bin package that does not actually use the upstream "Official binary builds" has no excuse to exist. It is also the source of a very major problem -- you have done vastly inappropriate things to the ld loader in order to lie about the binaries, introducing deadly libicu symlinks to the entire user ecosystem rather than depending on for the incompatible libraries that don't work at all. And rather than assassinating peoples' initramfs with broken and inadvisable ncurses breakage, you should have used patchelf --replace-needed to redirect the ncurses linkage. But this is precisely why it is completely wrong to create -bin packages for open-source code that merely download some other linux distribution's unofficial builds. There is zero utility of using this over the one that builds, properly, from source. The only reason -bin packages make sense at all is when upstream developers provide standalone binaries that are meant to work out of the box and which they test against for source code regressions. None of that is the case here -- Fedora doesn't build statically against icu or ncurses, so you end up breaking not only the package, but also peoples' systems, trying to sledgehammer it into working. ... Anyway, give me one reason why this package should not be deleted. s3lph commented on 2019-02-21 21:54 Yes, Removing this line from swift-lang.confand running ldconfigfixes the issue; /usr/lib/libncursesw.so.6is used again for the initramfs. refi.64 commented on 2019-02-20 21:09 s3lph: Oh wow, that's really bad... Does it work if you remove /usr/lib/swift/linux from /etc/ld.so.conf.d/swift-lang.conf when building the initramfs ? s3lph commented on 2019-02-19 00:35 The latest version (4.2.1-1) for some reason breaks my boot process after the next mkinitcpioafter installation. /usr/lib/swift/linux/libncursesw.so.6seems to be put into the initramfs instead of /usr/lib/libncursesw.so.6. However, /usr/lib/swift/linuxdoes not seem to end up in the library search path in the initramfs, and my lvm volumes can't be activated since the pvscanbinary used by the lvm2hook is linked against libncursesw.so.6, which is not found. Running pvscanwith a manually preloaded /usr/lib/swift/linux/libncursesw.so.6in the recovery shell followed by manually mounting the rootfs allowed me to continue booting. Uninstalling this package followed by a mkinitcpioresolves the issue. refi.64 commented on 2019-02-12 02:38 The package has finally been updated! In addition, the Fedora Swift binaries are now used over the Ubuntu ones, which means that no more ld hacks are needed, and the amount of ugly changes to the binaries has been significantly dropped. Unfortunately, this also means that there is now stuff /usr/libexec; I tried removing it, but I haven't gotten it to work yet. davidgarfias commented on 2019-01-17 01:33 To install swift 4.2.1 all you need to do is to edit the PKGBUILD. Change the version to 4.2.1. Also change the SHA256 sum to 4a17bef7b02bb6480cd72282fd67463c12131bad013b79bc721c8cb2a5b83fd1. grawlinson commented on 2018-11-10 02:01 Just curious, is there any siginificant difference between the Ubuntu 16.04 and 18.04 releases? I've managed to compile 4.2.1 using the 18.04 releases, so it should be safe to update. lf-araujo commented on 2018-08-22 22:34 Dear @refi.64, since last update in Manjaro, this is not working anymore. Even after reinstallation, the error I get after trying to run swift is: *** stack smashing detected ***: <unknown> terminated
https://aur.archlinux.org/packages/swift-bin/
CC-MAIN-2019-18
refinedweb
1,414
53.31
Subprocess in Python is a module used to run new codes and applications by creating new processes. It lets you start new applications right from the Python program you are currently writing. So, if you want to run external programs from a git repository or codes from C or C++ programs, you can use subprocess in Python. You can also get exit codes and input, output, or error pipes using subprocess in Python. How to Start a Process in Python? To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument. In the example below, you will use Unix’s cat command and example.py as the two parameters. The cat command is short for ‘concatenate’ and is widely used in Linux and Unix programming. It is like “cat example.py.” You can start any program unless you haven’t created it. from subprocess import Popen, PIPE process = Popen(['cat', 'example.py'], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() print(stdout) Output: In the above code, the process.communicate() is the primary call that reads all the process’s inputs and outputs. The “stdout” handles the process output, and the “stderr” is for handling any sort of error and is written only if any such error is thrown. What Is the Subprocess Call()? Subprocess in Python has a call() method that is used to initiate a program. The syntax of this subprocess call() method is: subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) Parameters of Subprocess Call() The call() method from the subprocess in Python accepts the following parameters: - args: It is the command that you want to execute. You can pass multiple commands by separating them with a semicolon (;) - stdin: This refers to the standard input stream’s value passed as (os.pipe()) - stdout: It is the standard output stream’s obtained value - stderr: This handles any errors that occurred from the standard error stream - shell: It is the boolean parameter that executes the program in a new shell if kept true Return Value of the Call() Method from Subprocess in Python The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception. Now, use a simple example to call a subprocess for the built-in Unix command “ls -l.” The ls command lists all the files in a directory, and the -l command lists those directories in an extended format. import subprocess subprocess.call(["ls", "-l"]) Output: As simple as that, the output displays the total number of files along with the current date and time. What is Save Process Output (stdout) in Subprocess in Python? The save process output or stdout allows you to store the output of a code directly in a string with the help of the check_output function. The syntax of this method is: subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) As you can see, the function accepts the same parameters as the call() method except for one additional parameter, which is: - universal_newlines: It is a boolean parameter that opens the files with stdout and stderr in a universal newline when kept true The method also returns the same value as the call() function. Now, look at a simple example again. This time you will use Linux’s echo command used to print the argument that is passed along with it. You will store the echo command’s output in a string variable and print it using Python’s print function. import subprocess s = subprocess.check_output(["echo", "Hello World!"]) print(s) Output: Example of Using Subprocess in Python Let’s combine both the call() and check_output() functions from the subprocess in Python to execute the “Hello World” programs from different programming languages: C, C++, and Java. You will first have to create three separate files named Hello.c, Hello.cpp, and Hello.java to begin. After making these files, you will write the respective programs in these files to execute “Hello World!” Let’s begin with our three files. Code to Include in Hello.c File Create a Hello.c file and write the following code in it. #include<stdio.h> int main() { printf("C says Hello World!"); // returning with 0 is essential to call it from Python return 0; } If you are not familiar with the terms, you can learn the basics of C programming from here. Code to Write in Hello.cpp File After the Hello.c, create Hello.cpp file and write the following code in it. #include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; cout << "C++ says Hello World! Values are:" << a << " " << b; return 0; } Here, this demo has also used integer variables to store some values and pass them through the stdin parameter. If you are not familiar with the terms, you can learn the basics of C++ programming from here. Code to Write in Hello.java File Use the following code in your Hello.java file. class Hello{ public static void main(String args[]){ System.out.print("Java says Hello World!"); } } If you are not familiar with the terms, you can learn the basics of Java programming from here. Code to Write in Main.py File to Execute Subprocess in Python Once you have created these three separate files, you can start using the call() and output() functions from the subprocess in Python. Here’s the code that you need to put in your main.py file. import subprocess import os def C_Execution(): # storing the output s = subprocess.check_call("gcc Hello.c -o out1;./out1", shell = True) print(", return code", s) def Cpp_Execution(): # creating a pipe to child process data, temp = os.pipe() # writing inputs to stdin and using utf-8 to convert it to byte string os.write(temp, bytes("7 12\n", "utf-8")); os.close(temp) # storing output as a byte string s = subprocess.check_output("g++ Hello.cpp -o out2;./out2", stdin = data, shell = True) # decoding to print a normal output print(s.decode("utf-8")) def Java_Execution(): # storing the output s = subprocess.check_output("javac Hello.java;java Hello", shell = True) print(s.decode("utf-8")) # Driver functions if __name__=="__main__": C_Execution() Cpp_Execution() Java_Execution() Output: Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer Summing It Up In this article, you have learned about subprocess in Python. You can now easily use the subprocess module to run external programs from your Python code. The two primary functions from this module are the call() and output() functions. Once you practice and learn to use these two functions appropriately, you won’t face much trouble creating and using subprocess in Python. If you are a newbie, it is better to start from the basics first. You can refer to Simplilearn’s Python Tutorial for Beginners. The tutorial will help clear the basics and get a firm understanding of some Python programming concepts. After the basics, you can also opt for our Online Python Certification Course. The certification course comes with hours of applied and self-paced learning materials to help you excel in Python development. If you are on the other hand looking for a free course that allows you to explore the fundamentals of Python in a systematic manner - allowing you the freedom to decide whether learning the language is indeed right for you, you could check out our Python for Beginners course or Data Science with Python course. Delivered via SkillUp by Simplilearn, these courses and many others like them have helped countless professionals learn the fundamentals of today’s top technologies, techniques, and methodologies and decide their career path, and drive ahead towards success. Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, ASAP!
https://www.simplilearn.com/tutorials/python-tutorial/subprocess-in-python
CC-MAIN-2021-39
refinedweb
1,367
65.52
active styles using NavLinkby Sai gowtham1min read NavLink It is used to style the active routes so that user knows on which page he or she is currently browsing on the website. What is the difference between NavLink and Link? The Link component is used to navigate the different routes on the site. But NavLink is used to add the style attributes to the active routes. In our routing app, we have three routes which are [home, /users, /contact] Let’s style them using NavLink. We need to add a new prop called activeClassName to the NavLink component so that it applies that class whenever the route it is active. index.css .active{ color:red; } index.js import React from 'react' import ReactDOM from 'react-dom' import './index.css' import { Route, NavLink, BrowserRouter as Router, Switch, } from 'react-router-dom' import App from './App' import Users from './users' import Contact from './contact' import Notfound from './notfound' const routing = ( <Router> <div> <ul> <li> <NavLink exact Home </NavLink> </li> <li> <NavLink activeClassName="active" to="/users"> Users </NavLink> </li> <li> <NavLink activeClassName="active" to="/contact"> Contact </NavLink> </li> </ul> <hr /> <Switch> <Route exact path="/" component={App} /> <Route path="/users" component={Users} /> <Route path="/contact" component={Contact} /> <Route component={Notfound} /> </Switch> </div> </Router> ) ReactDOM.render(routing, document.getElementById('root')) Now you can see a red color is applied to the active routes.
https://reactgo.com/reactrouter/navlink/
CC-MAIN-2020-16
refinedweb
228
65.01
CGTalk > Software Specific Forums > Autodesk 3ds max > 3dsMax SDK and MaxScript > Treeview.verticalScroll? PDA View Full Version : Treeview.verticalScroll? PEN 09-16-2009, 08:05 PM Looks like I can't get or set values for the vertical scroll for a treeView. Is this the case? Would a work around be placing it in a control that I can and then affect the height of the treeView as nodes are added? I want to be able to control the scrolling. denisT 09-16-2009, 08:32 PM do you have any reason for not setting tv.topnode instead of scrolling vscroll? PEN 09-16-2009, 08:45 PM Ya I need to to scroll with another scroll bar. Have you ever wanted to run naked through a thorn bush? Well this project is making me think that would be less painful. I just slapped both of the controls that I need to work with in ScrollableControls. How ever this means that I need to manage the height of the control inside to set the scroll bar. Is there a way to force the height of a control to always equal the height of it's contents? PEN 09-16-2009, 09:34 PM Here is the nightmare to date. Looks just like it was a month ago eh. Well it is a whole lot different under the hood. denisT 09-17-2009, 08:21 PM there is no easy way to scroll tree view and update its view. but you can do it with c# /* C# using System; using System.Windows.Forms; public class TreeViewScrollBars { private const int SB_HORZ = 0; private const int SB_VERT = 1; [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern int GetScrollPos(IntPtr hWnd, int nBar); [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern int SetScrollPos(IntPtr hWnd, int nBar, int pos, bool redraw); private int GetScrollBars(TreeView tv, int nBar) { return GetScrollPos((IntPtr)tv.Handle, nBar); } private int SetScrollBars(TreeView tv, int nBar, int pos) { tv.BeginUpdate(); SetScrollPos((IntPtr)tv.Handle, nBar, pos, true); tv.EndUpdate(); return GetScrollBars(tv, nBar); } public int GetVScrollPos(TreeView tv) { return GetScrollBars(tv, SB_VERT); } public int SetVScrollPos(TreeView tv, int pos) { return SetScrollBars(tv, SB_VERT, pos); } public int GetHScrollPos(TreeView tv) { return GetScrollBars(tv, SB_HORZ); } public int SetHScrollPos(TreeView tv, int pos) { return SetScrollBars(tv, SB_HORZ, pos); } } */ fn treeViewScroll = ( source = "" source += "using System;\n" source += "using System.Windows.Forms;\n" source += "public class TreeViewScrollBars\n" source += "{\n" source += " private const int SB_HORZ = 0;\n" source += " private const int SB_VERT = 1;\n" source += " [System.Runtime.InteropServices.DllImport(\"user32.dll\")]\n" source += " private static extern int GetScrollPos(IntPtr hWnd, int nBar);\n" source += " [System.Runtime.InteropServices.DllImport(\"user32.dll\")]\n" source += " private static extern int SetScrollPos(IntPtr hWnd, int nBar, int pos, bool redraw);\n" source += "\tprivate int GetScrollBars(TreeView tv, int nBar) { return GetScrollPos((IntPtr)tv.Handle, nBar); }\n" source += " private int SetScrollBars(TreeView tv, int nBar, int pos)\n" source += " {\n" source += " tv.BeginUpdate();\n" source += " SetScrollPos((IntPtr)tv.Handle, nBar, pos, true);\n" source += " tv.EndUpdate();\n" source += " return GetScrollBars(tv, nBar);\n" source += " }\n" source += " public int GetVScrollPos(TreeView tv) { return GetScrollBars(tv, SB_VERT); }\n" source += " public int SetVScrollPos(TreeView tv, int pos) { return SetScrollBars(tv, SB_VERT, pos); }\n" source += " public int GetHScrollPos(TreeView tv) { return GetScrollBars(tv, SB_HORZ); }\n" source += " public int SetHScrollPos(TreeView tv, int pos) { return SetScrollBars(tv, SB_HORZ, pos); }\n" source += "}\n" csharpProvider = dotnetobject "Microsoft.CSharp.CSharpCodeProvider" compilerParams = dotnetobject "System.CodeDom.Compiler.CompilerParameters" compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compilerParams.GenerateInMemory = on compilerResults = csharpProvider.CompileAssemblyFromSource compilerParams #(source) compilerResults.CompiledAssembly.CreateINstance "TreeViewScrollBars" ) scr = treeViewScroll() you will get methods: showmethods scr .<System.Boolean>Equals <System.Object>obj .[static]<System.Boolean>Equals <System.Object>objA <System.Object>objB .<System.Int32>GetHashCode() .<System.Int32>GetHScrollPos <System.Windows.Forms.TreeView>tv .<System.Type>GetType() .<System.Int32>GetVScrollPos <System.Windows.Forms.TreeView>tv .[static]<System.Boolean>ReferenceEquals <System.Object>objA <System.Object>objB .<System.Int32>SetHScrollPos <System.Windows.Forms.TreeView>tv <System.Int32>pos .<System.Int32>SetVScrollPos <System.Windows.Forms.TreeView>tv <System.Int32>pos .<System.String>ToString() Kramsurfer 09-21-2009, 07:06 PM Thanks Denis ! This c# compile in maxscript is just insane... I see there's a VB namespace too... just not enough time in the day to explore the possibilities! I needed the same thing for a ListView... just change four characters and voila! Thanks again! denisT 09-21-2009, 09:08 PM I needed the same thing for a ListView... just change four characters and voila! Thanks again! I'm surprised because my code shouldn't work for ListView. BeginUpdate >...> EndUpdate for ListView resets a scrollbar's position. How do you update ListView? Kramsurfer 09-21-2009, 09:28 PM ahhh. You are correct.. I only need to read the position of the Hscroll bar so I'd know which column was being clicked on... setting the scrollbar positions has no effect as you expected.... I thought the one of the main points of .net was API consistency.. nice to see these work diffferently... :-\ denisT 09-21-2009, 09:46 PM I only need to read the position of the Hscroll bar so I'd know which column was being clicked on... is not easer to use ColumnClick event? Kramsurfer 09-21-2009, 10:41 PM That only updates when you click the column header... it should be ColumnHeaderClick Event, clicking on an object in list does not fire this event... This usage was a conversion of something I didn't write from the old ActiveX listview, I probably should have went to a grid controller, but didn't want to get that involved with getting this script into 2009 x64. Thanks for your thoughts.. I've been jumping in and out of so many GUI API's the past two years, (Adobe, Andriod, wxPython, .net) , it's become impossible for me to keep it all straight... denisT 09-21-2009, 10:51 PM on any click event for listview you can get item and its subitem. (all that you need to know is the mouse position) item = lv.GetItemAt arg.x arg.y sub = item.getSubItemAt arg.x arg.y Kramsurfer 09-21-2009, 11:12 PM yup.. but that mouse position is relative to the control.. So if you scroll horizontally you get a Mouse X value relative to the control's position, one then needs to add the scroll position... which works perfect.. CGTalk Moderation 09-21-2009, 11:12 PM This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum. vBulletin v3.0.5, Copyright ©2000-2015, Jelsoft Enterprises Ltd.
http://forums.cgsociety.org/archive/index.php/t-807574.html
CC-MAIN-2015-06
refinedweb
1,125
58.69
This is a bit of a continuation to my older post on the matter of migrating C-style for-loops from other languages to Haxe, expanding with some new things I've learnt since then. Similar to some older solutions, this involves a bit of a macros, but both the macros and the results got cleaner. First, let's look at the "everything is complicated" use case again: for (var i = 0; i < 10; i++) { if (i == 3) i++; if (i == 5) continue; trace(i); } Due to mix of iterator modification and iteration skipping, it would previously be quite a trouble, requiring manual handling of each case (or coping with weird macro-made code). Now, however... cfor(var i = 0, i < 10, i++, { if (i == 3) i++; if (i == 5) continue; trace(i); }); You can clearly say that this smells of macro, but let's look at the resulting code: var i = 0; while (i < 10) { if (i == 3) i++; if (i == 5) { i++; continue; } trace(i); i++; } That is pretty good, isn't it? Conversion is automatic, there is no additional code, and it retains readability as well! And all it took was using the regular (otherwise faulty) approach while replacing continue statements with blocks containing the "afterthought" and the actual statement. And the macros handling this is not too scary either: static macro function cfor(init, cond, post, expr) { #if !display var func = null; func = function(expr:haxe.macro.Expr) { return switch (expr.expr) { case EContinue: macro { $post; $expr; } case EWhile(_, _, _): expr; case ECall(macro cfor, _): expr; case EFor(_): expr; case EIn(_): expr; default: haxe.macro.ExprTools.map(expr, func); } } expr = func(expr); #end return macro { $init; while ($cond) { $expr; $post; } }; } The first part of the function does the replacement trick described while being cautious to note replace anything in sub-loops on accident. Then there's the actual restructuring of function arguments into a block with a loop. "fast method access" is accomplished by simply importing the method from a class. import Utils.cfor; While this approach still does not exactly "feel like home", it is simple, portable, and transparent in whether it works or not (unlike @:metadata, which fails silently if the macros did not execute), so I think it's a worthy substitute for the time being. It is also worth mentioning that this approach is largely inspired by Patrick Le Clec'h's "hacking haxe" repository, which in particular has a commit that adds a similar thing on the language level (and with convetional syntax - example). So the absence of the C-style for loops in Haxe is likely not a technical problem but a conscious choice of exclusion. Of course, it's just convenience. But so are the commonly-discussed short lambdas. Or many of numerous existing language features. Development tools are all about convenience, and convenience is why one gets chosen over another. This is why we don't program things in assembly, you see? Pingback: Haxe: Shorthand expression matching
https://yal.cc/haxe-some-cleaner-c-style-for-loops/
CC-MAIN-2019-13
refinedweb
504
58.32
Mono for Android Xamarin, which specializes in building tools that let developers build mobile apps in C#, has taken that idea one step further with Xamarin.iOS. Developers working with Xamarin MonoTouch have been stuck with developing on a Macintosh and working with MonoDevelop. This hasn't been a bad thing. The Apple iOS SDK only runs on the Mac, so this requirement hasn't been a major limiting factor in iOS development. Unfortunately, .NET and C# developers are used to using Visual Studio. Microsoft has spent a lot of time, effort and money to make Visual Studio the premier software development tool in existence. Xamarin Inc. has heard from those developers who want to integrate Visual Studio with iOS development. On Feb. 20, Xamarin introduced Xamarin.iOS for Visual Studio. This plug-in allows developers using Visual Studio to write iPhone and iPad applications for the iPhone using the Microsoft .NET Framework and C#. Configuration and Setup When I first discussed this product with some developers, their feedback was: "Great! Now we don't need Macs for iPhone development!" Unfortunately, that's not quite how the product works. Here are the basics: Xamarin has produced an installation guide for Xamarin.iOS. Figure 1 shows the communication at a high level. Start by creating a project, as shown in Figure 2. Once a project's been created, you can see it in Solution Explorer, as shown in Figure 3. The files are similar to those in MonoDevelop. I'll examine some code written in Xamarin.iOS. Listing 1 creates a UIButton, displays that button and handles the button's touch events. Listing 1. Creating a button in Xamarin.iOS and handling the button's events. using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace TestSingleView_App1 { public partial class TestSingleView_App1ViewController : UIViewController { UIButton uib; int count = 0; public TestSingleView_App1ViewController() : base("TestSingleView_App1ViewController", null) { } public override void DidReceiveMemoryWarning() { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning(); // Release any cached data, images, etc. that aren't in use. } public override void ViewDidLoad() { base.ViewDidLoad(); float width = UIScreen.MainScreen.ApplicationFrame.Width; float delta = 20f; float buttonWidth = width - ( 2 * delta ); float buttonHeigth = 2 * delta; RectangleF r = new RectangleF( delta, delta, buttonWidth, buttonHeigth); // uib = UIButton.FromType(UIButtonType.RoundedRect); uib = UIButton.FromType(UIButtonType.RoundedRect); // uib = new UIButton(UIButtonType.RoundedRect); uib.Frame = r; uib.SetTitle("Click Me", UIControlState.Normal); //uib.BackgroundColor = UIColor.White; uib.SetTitleColor(UIColor.Black, UIControlState.Normal); uib.TouchUpInside += uib_TouchUpInside; this.View.AddSubview(uib); // this.View.BackgroundColor = UIColor.White; // Perform any additional setup after loading the view, typically from a nib. } void uib_TouchUpInside(object sender, EventArgs e) { string countString = String.Format("{0} clicks", ++count); uib.SetTitle(countString, UIControlState.Normal); }); } } } The output of the code in Listing 1 is shown in Figure 4. It shows Visual Studio 2012 running in a VM on a Mac, working with the Mac build server and running the iOS simulator. Note that running in a VM is not a requirement, and is shown here for example purposes only. Issues, Real and Imagined In conversations with fellow developers, several questions have come up regarding Xamarin.iOS. I'll attempt to answer some of the most common ones. Industry Opinions To gain a larger perspective on Xamarin.iOS, I sought feedback from other developers. The following are responses from Martin Bowling, a .NET developer who's very active with iOS and MonoTouch; Brent Schooley, a .NET developer who works at Infragistics as a technical evangelist; and Colin Eberhardt, CTO of ShinobiControls. What are your thoughts on Xamarin.iOS for Visual Studio for developers? How does this help developers? Schooley: Xamarin.iOS for Visual Studio is a big boon for developers who are currently working day-to-day in Visual Studio. There's a comfort level that comes from working in the tool you're familiar with. For the many developers that rely on productivity-enhancing add-ons -- such as ReSharper -- Xamarin.iOS for Visual Studio represents a welcome addition to an already stellar product. Developing iOS applications in Visual Studio will be the easiest way to integrate TFS [Team Foundation Server] workflows into the process as well. Also, the ability to work on native cross-platform applications that include iOS, Android, Windows Phone and Windows Store versions all within the same IDE within Windows is something that can't be matched by other cross-platform solutions. Bowling: Allowing me to utilize the Visual Studio ecosystem that I've used for more than 15 years as a .NET developer is great. In addition to that, reaching out and including traditional Windows-based developers is a welcome addition to the C#/ iOS development community. How does Xamarin.iOS affect the developer ecosystem? What's the effect on third-party developers? Schooley: Demand for mobile applications within the enterprise is definitely growing. We hear this common message all the time here at Infragistics. Because many of these enterprises already have .NET developers who are familiar working with Visual Studio, the addition of being able to target iOS with Visual Studio means less training costs for tooling. For enterprises that are heavily reliant on TFS and related workflows, this support is even more important. I think the component store is a huge boost for control vendors as well. This will definitely be the easiest platform to sell iOS controls due to the tight integration within the tools. Being able to provide quick-start material right alongside the components makes communicating how easy the components are to use a breeze. It's also great to have the API docs accessible from the component page as well. Eberhardt: As a provider of UI components I've always been a little disappointed by the Xcode Interface Builder. It doesn't offer any way for us to add our controls to the IDE "assets," so we can't interactively design a UI with anything other than Apple controls, which is a great shame. In contrast, Visual Studio provides a lot of extension points for third-party control and tool providers. You can add wizards, design-time data and more. I've made use of this in the past on previous projects. In fact, the extensibility of Visual Studio in general far exceeds that of Xcode. This provides a wealth of opportunity. What are your thoughts on the new Xamarin 2.0 products announced for developers? Schooley: The new Xamarin 2.0 products are a big step forward for cross-platform mobile developers. The new Xamarin Studio IDE has a fresh look and feel with fantastic performance and usability. It has really come a long way from where MonoDevelop was. The Visual Studio integration for iOS enables C# developers to build native cross-platform applications in the tool they're most familiar with. The component store is a big addition for developers. Finding components with MonoTouch bindings has been a somewhat difficult process for the average developer in the past. Now, component builders (both vendors like Infragistics and indie devs) can add their free and paid controls to the Xamarin component store, and have them be easily discoverable by anyone building with Xamarin. It's hard not to mention the new pricing structure, as well. The addition of a free Starter tier should bring many more developers to this growing ecosystem. Bowling: The biggest thing for me is the inclusion of the free edition. I think this is great for the community, and we'll really see the C# mobile development community grow. Developers no longer have to make an investment to participate. I'm also looking forward to the add-on store and being able to have some great ready-to-use components.
https://visualstudiomagazine.com/articles/2013/04/01/ios-development.aspx
CC-MAIN-2020-50
refinedweb
1,277
50.63
@SuppressWarnings("unchecked") public String sendHttpPost (String url, String queryString) throws Exception { String result = null; try { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.setQueryString(queryString); client.executeMethod(post); result = post.getResponseBodyAsString(); post.releaseConnection(); } catch (Exception e) { throw new Exception("post failed", e); } return result; }. In my Maven 2 I included the ServletTester using the following repository and dependency information. I always use Maven 2 as allows other developers to quickly set up their IDE and download all required JARs. If you don't use Maven, you will need to manually download all of the dependencies. <repositories> <repository> <id>codehaus-release-repo</id> <name>Codehaus Release Repo</name> <url></url> </repository> </repositories> ... <dependency> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-servlet-tester</artifactId> <version>6.1.6</version> <scope>test</scope> </dependency> With this in place the next step was writing the JUnit test cases. For me I wanted to initialize the servlet-container once, then run a set of tests against it. In JUnit 4 you can use the @BeforeClass and @AfterClass annotations to mark methods that should be executed before and after all of the tests. public class HttpPostServiceTest { private static ServletTester tester; private static String baseUrl; /** * This kicks off an instance of the Jetty * servlet container so that we can hit it. * We register an echo service that simply * returns the parameters passed to it. */ @BeforeClass public static void initServletContainer () throws Exception { tester = new ServletTester(); tester.setContextPath("/"); tester.addServlet(EchoServlet.class, "/echo"); baseUrl = tester.createSocketConnector(true); tester.start(); } /** * Stops the Jetty container. */ @AfterClass public static void cleanupServletContainer () throws Exception { tester.stop(); } } The code highlighted in blue is where we start an instance of the server. I created a new instance of the ServletTester, setting the context path and adding a servlet mapping. This alone does not bind the server to a port, for that you need to call createSocketConnector(true), which binds the server to a local port and returns the URL. The port used will be a high unused port. I save an instance of the ServletTester so that I can stop the service in the @AfterClass block, and I save the baseUrl so that I can target it in my tests. The servlet I added to the container I called EchoServlet. This servlet simply echos the parameters passed to it. public class EchoServlet extends GenericServlet { @SuppressWarnings("unchecked") @Override public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Map<String, String[]> params = new TreeMap<String, String[]>(request.getParameterMap()); out.println("SIZE=" + params.size()); for (Entry<String, String[]> entry : params.entrySet()) { out.println(entry.getKey() + ":::" + StringUtils.join(entry.getValue(), ",")); } } } The servlet takes the parameter map and creates a TreeMap out of it. The TreeMap is needed so that the parameter names are returned in sorted order. Being able to predict the order of the returned keys is required in order to test against the output of the servlet. To finish things up, I just needed to write a unit test. @Test public void testPost () throws Exception { PostService svc = new PostService(); String res = svc.sendHttpPost(baseUrl + "/echo", "foo=bar&baz=%25%26%3D%2F"); String[] resList = StringUtils.split(res, "\n"); assertEquals(3, resList.length); assertEquals("SIZE=2", resList[0].trim()); assertEquals("foo:::bar", resList[1].trim()); assertEquals("baz:::%&=/", resList[2].trim()); } After that, run the test and watch it work. 31 comments: Your instructions worked beautifully for me. I know there is a way to use the servlet filters as well though i was not able to get it working. Would appreciate if you could provide any insight on that too.. Thanks! Ajanta, you can use Spring-Mock for that... even if you aren't using Spring. Filter filter = new MyFilter(); MockHttpServletRequest req = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse res = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); filter.doFilter(req, res, chain); After the filter executed you can use the methods on the mock request/response objects to see verify that the filter did what it was supposed to do. I am not sure where this library is listed on the Spring site, but you can download it from the Maven repository here,. Hey, thanks for your quick response, I think ServletTester also provides a addFilter method and I tried using that but it didn't work. Have you used that? No, I haven't tried the addFilter for ServletTester (yet), but I expect that would work well. In my case though it is easier/better to use mock object for filter testing because I can set/inspect things in the mock objects that I couldn't do without bending over backwards in a server environment. Have you ever tried the apache cactus framework? Erik, nope, never used Cactus. I have heard about it, and probably looked at the site once or twice, but never got around to actually trying it. I just took a look at the Quick Start guide and see one thing that immediately turns me off of using it, the part where it asks me to install Tomcat. *I* don't have a problem installing Tomcat, but requiring that my developers do this adds time to getting them up to speed on a project... And asking my clients to do this is too much to ask. My goal is that any developer or client can take the source or a project and run "mvn test" to automatically download and run the tests. I want Maven to be the only tool that needs to be required to test, compile, and package the app. Of course... I don't know much about Cactus, so maybe I am making an incorrect assumption Hi, I'm looking at using the new Jetty ServletTester utilities for unit testing servlets. I'm stuck attempting to mock out a HttpSession for any servlets that require one. Any ideas? Damian, You are looking for ideas on how to mock HTTPSession without using a servlet container? Check out spring-mock, it has all of that stuff and is well maintained. JARs from Maven repo: Random article: Robert, Damian, A shameless plug... another way you can now "mock" Servlet API objects for out-of-container testing is using my own "ObMimic" library. This provides plain-Java classes that cover the whole Servlet API for precisely this purpose. It covers all of the Servlet API's interfaces and abstract classes (including HttpSession), and completely implements all of their methods. It does this with plain Java objects that are fully configurable, fully inspectable, and have some additional features to help in testing (e.g. record/examine the Servlet API calls made to each object, report any ambiguous or questionable Servlet API calls, switch between Servlet 2.3, 2.4, 2.5). Because there are no unsupported or incomplete Servlet API methods it can handle even complex use of the API (e.g. request-dispatcher "forwards" and "includes", listener notifications, servlet mappings, filter chains etc), and as a result you can use it not only for pure "unit" testing but also for testing more extensive paths through your code, framework code, and other libraries. As of May/June 2008 this is in private "beta" release, but if you want to take a look at it just let me know and we'll set you up. For more details, see my recent blog posting. Mike, > A shameless plug Shameless plugs are welcome... just as long as it is on topic. > As of May/June 2008 this is in > private "beta" release, but if you > want to take a look at it just let > me know I am interested, but don't currently have any projects on my plate right now that need this. If something does come up, you can definitely expect to hear from me. Thanks for letting me(us) know about this. Hi, a very nice tutorial.Please correct the font color of the code. Its appears nearly invisible as font is of white color in white background. Thanks Hi Robert. Thanks for sharing your experience. Basically, the ServletTester works well, but I faced the following problem and maybe you can help me: Can you tell me which values you take for the contextPath and the DocumentBase? For both there are setters and getters, but using a contextpath like "/webapp" doesn't works when resources are to be loaded. For example, when using servlet-methods like "getServletContext().getRealPath("WEB-INF/classes")", which work when used inside a "stand-alone" container, return null when used with the ServletTester. Thanks and best regards, Reza (from germany ;-) ). Himanshu, it should be better now. Thanks for mentioning it. That's good now n legible. Well despite repeated attempts your tutorial never worked for me and I,ve to satisfy with spring mock objects Indeed, saved me some time. Thanks! But, the blue font color is not optimal, too. With black background it appears blurry. > Anonymous said... > using a contextpath like > "/webapp" doesn't works when > resources are to be loaded. I really don't know. This example wasn't meant to load resources. If I needed to do that, for instance if I needed to pass a test XML file back to the caller, I would just use File to open/read the file then simply print it to the response object. Hi Robert, The tutorial is great. I just wonder if you know of a way by which I can add a servlet instance to ServletTester rather than passing the servlet class. My servlet object should receive a db storage object in its constructor and thus I need to instantiate the servlet before passing it to ServletTester. However, it seems like when testing a servlet you can only pass the servlet class to ServletTester and let it instantiate the servlet. This causes null pointer exceptions in my case which is causing problem. Do you have any idea or suggestion on how this can be solved? thanks a lot Nima, sorry, I don't know how you might do that without either changing the ServletTester or the servlet. Thanks Robert. Your post helped me successfully set up a testing servlet context with Jetty. Something that 5 Spring books and 10 Java books and lotsa searching on the Internet failed to do! Hi, I tried this, but I couldnt figure out where the class PostService comes from? What is the package of that class? Or which dependency/maven-coordinate do I need to include? > PostService svc = new PostService(); Hi, I tried to get this working, but where does that PostService class come from? What package/dependency do I need? > PostService svc = new PostService(); PostService would be your code that you are trying to test. It could be called anything, and could use any API to make the HTTP call. In this case it is also a reference to the sendHttpPost() method that was at the top of the post, which just happens to live in a class called PostService (which is not shown). The PostService.sendHttpPost() method (from the top of the post) uses commons-httpclient 3.1, but like I said, your service could use any API that you needed to use. Hope that helps. Just so you know this fits more under the umbrella of integration testing. Typically to "Unit Test" that the class is working correctly you'd simply expose enough of your inner workings of your class to your testing framework to verify that the calls to the integration point (the HTTP client library you're using in this case) are correctly configured. By attempting to ensure that the dependency you're using is actually working correctly you are in effect verifying that another class is doing something. So you're no longer testing a unit. How can i write a junit test for a servlet that instantiates a class and then processes request to the server by getting the servlet time back. And then generates a response back to server with DATA. eg like so [ response.getOutputstream().println(DATA + (new DATE()); @Anonymous, I'm not sure I understand the question. Does it boil down to "how do I test a date value?" For tests that involve dates I typically make use of JodaTime classes instead of java.util.Date.. JodaTime is a lot better than what comes with the JDK, and also allows you to freeze time. // set and freeze time DateTimeUtils.setCurrentMillisFixed(millis); This allows you to not only freeze time but also allows you to test specific time periods that require additional testing. E.g. DST, new years, millennium bug. After you have tested that the servlet returned the exact time that you froze time at you can then reset/unfreeze it. DateTimeUtils.setCurrentMillisSystem(); JodaTime classes also allow conversion to/from java.util.Date. So if your code relies on java.util.Date you could mix the two, using JodaTime for constructing a new Date. E.g. "Date d = new DateTime().toDate()" instead of "Date d = new Date()". Again... if I understand the question correctly. I want to write a unit test for doing the following service to the servlet. This is a rough idea what the service is doing : response.setContentType("text/html"); StringBuffer responseBuf = new StringBuffer(); List valueList = new ArrayList(); // iterate through the valueList for (Values ItemValue : valueList) { responseBuf.append((String.valueOf(ItemValue.getStartTime() + "" + (String.valueOf(ItemValue.getEndTime() ); } response.getOutputStream().println("" +(new Date().getTime()) + responseBuf.toString()); response.getOutputStream().close(); Awesome post, thank U so much! PS: Cactus made me mad today, I'm glad to drop it :) How to set values in Request Attributes. ServletTester has setAttribute which sets all the values Attribute to context. not to the request object..Is there any way to set this value? In my Servlet I am accessing like this request.getAttribute("name"); Hi Robert, Please share the jar details for this class. PostService svc = new PostService(); I have used this repository and dependency in in pom.xml codehaus-release-repo Codehaus Release Repo ... org.mortbay.jetty jetty-servlet-tester 6.1.6 test Can't see your code samples, the background color is killing it.
http://blog.mental.ninja/2007/12/testing-servlets-with-junit.html
CC-MAIN-2019-43
refinedweb
2,343
65.62
SMS installation on Windows 2003 SP1. - From: "Mr Paul" <inscope@xxxxxxxxxxxx> - Date: 18 Dec 2006 21:45:22 -0800 I am in a corporate environment where the SQL team is separate to the SMS team and the server team only controls part of the AD forest. I am trying to install SMS 2003 onto Windows Server 2003 SP1. The install finishes, but in the SMSSetup.log file I have several entries right at the end as follows: <12-19-2006 12:17:22> Couldn't reload group, DDE error =4009 <12-19-2006 12:17:23> Couldn't reload group, DDE error =4009 <12-19-2006 12:17:24> Couldn't reload group, DDE error =4009 Ironically I then get the message: <12-19-2006 12:17:25> SMS Setup completed successfully! When I try to open up the SMS Admin console it takes a long time trying to connect to the \\servername\root\sms\site_NIW namespace and then the connection times out and fails. I have found several articles regarding WMI and DCOM issues. I have set the DCOM permissions back to SP0. I have put the computer account in the SMS_SiteSystemToSQLConnection_NIW group. I know that I do not have permission on the System\System Management container in AD (it is controlled by another service provider), but I would have thought that I would still be able to open the SMS console without having written the AD record. Is this feeling correct? Any assistance would be appreciated. Paul. . - Prev by Date: Re: Collection Membership issues - Next by Date: Problem with image packages - Previous by thread: SMS 2003 and Aproduct called DeepFreeze - Next by thread: Problem with image packages - Index(es):
http://www.tech-archive.net/Archive/SMS/microsoft.public.sms.setup/2006-12/msg00041.html
crawl-002
refinedweb
281
60.14
Bert Bos | Can you typeset a book with CSS? eBooks & i18n: Richer Internationalization for eBooks (2nd W3C Workshop on Electronic Books and the Open Web Platform) Tokyo, Japan, 4 June 2013 At some stage in its production, a book, magazine or e-book consists of (X)HTML or XML … and maybe MathML (or HTML5), PNG, JPEG, SVG, audio, video and metadata Can you then use CSS to typeset it? … for paper, for PDF, for an e-book or for the Web But on closer look the answer has to be no. Although our HTML and PNG were standard, we had to do a number of tricks to get the layout needed for a real book: e.g., we used TeX for the hyphenation and we used a number of proprietary extensions in the formatter. (We used Prince.) In fact, Michael Day, the man behind that formatter, on several occasions enhanced the software specifically for us. People who are making books still rely on such tricks and proprietary extensions in the software they use. Why can't CSS typeset books? But the demand on CSS is increasing … so let's assume we want to extend CSS Why is that? Our, i.e, the CSS Working Group's, excuse has always been that (1) CSS was designed only for simple layouts and meant to be easy to use, and there was XSL (XSLT and XSL-FO) for advanced publications, especially for print; and (2) several of the requirements of book publishing are actually quite difficult to solve. It takes time to understand them, acquire the expertise, analyze the solutions, test them… But the demand on CSS is increasing, especially now that XSL-FO development has stopped and we don't know when and if it can restart. And so it is time to look seriously if CSS can acquire the needed functionality, and if so, how.. But, for the purpose of this talk, let's assume that we want to add functionality to CSS and let's look at some examples of requirements and the solutions that have been proposed for them, if any. Other lists (more complete than this talk) My list, in progress List of CSS features required for paged media XSL WG, 2008 Extensible Stylesheet Language (XSL) Requirements Version 2.0 JLTF, 2012 Requirements for Japanese Text Layout I've started collecting requirements in a document (List of CSS features required for paged media). It is still rather unstructured and incomplete, but contains already enough to give a sense of the size of the task in front of us, even if we don't do it (all) in CSS. Although not all the requirements in the list are only for paged media, many of them are more important in paginated renderings than in a scrolling display, and thus it seems useful to refer to them collectively under that theme. The XSL WG collected a list of requirements for XSL-FO 2 in 2008. There are many requirements on that list that aren't in mine yet and that also have to be considered for CSS at some point. Original, simplifying assumption for CSS: In simple layouts, the style mostly follows the mark-up But: extensible to document-independent regions if necessary later (@-rules…) When we designed CSS, we made the simplifying assumption that, at least in a single-column scrolling layout, the bulk of the style closely follows the mark-up structure. And so we concentrated on that. The fundamental model of CSS is to take the document tree and add style to every element and only to elements: a bit of margin, a color, a font, maybe a list number, etc. Where typography required style that didn't follow the semantics, we thought we would add some ad-hoc exceptions (such as 'first-line' and 'first-letter') or just ignore it. We did, however, build in a way to extend CSS later, if necessary, with ways to create visual structures that were independent of the document tree. The primary hooks for such extensions in CSS are the so-called at-rules (or @-rules). E.g., already in 1996, even before we standardized CSS level 1, we published a note about possible ways to add page templates to CSS. (In ways too complicated to explain here, driven by the browser wars at the time, that note led eventually to the inclusion of “absolute positioning” in CSS level 2, a feature that has very little to do with the original idea and that finally nobody liked; but such is history.) Of course, even in simple documents, typography already doesn't always follow the mark-up structure. E.g., if you decide to mark-up foreign words ( <span lang=de>Buch</span>) and then the designer decides to typeset such foreign words in italic ( [lang] {font-style: italic}), then you will have a problem if the foreign word is followed by punctuation, because, for reasons of aesthetics, the punctuation should then also be italic. We decided to just ignore that problem. But as soon as you want to do more interesting layouts, the assumption starts to hold less and less. In a book, there are, e.g., running headers and footers. They do not correspond to any element in the document, even if the content is often derived from the document in some way. Other examples are tables of contents and indexes. They are likewise derived from the document, but you would typically want them to be created by the computer, not by the author. And even though they aren't elements in the document, you want to be able to style them. Very simple – positioned in page margins, fixed strings and counters Simple – ditto, plus text copied from elements Early draft, proprietary extensions Special elements – to be used as running headers No proposals yet Copies of elements – copy structure, different style Early draft (css3-layout) Not in the margin – complex page templates Looks simple enough, but the best we can do so far is: … integral ∫0bxp dx when… Let's look a bit more closely at running headers. We found that we could, with the at-rules I mentioned before and a single predefined page template, provide something that was at the same time flexible enough for quite a number of books and simple enough to be understood by most people. This became the css3-page module (CSS Paged Media Module Level 3). You can put text in various places around the edge of each page, differently on left and right pages, even extract some text from the document for that purpose to some extent, and style the text, also to a limited extent. What are those limits? And what if we need more? The text in the running headers can consist of fixed text (the same throughout the document), text copied from elements in the document and counters (generated numbers, such as page numbers) or a mixture of those. You cannot manipulate the copied text (modify it, do calculations on it). There are a total of thirteen boxes and each box has only one style (a single font, a single color, etc.) They have just enough freedom in their placement and size that you can sometimes combine two of them in the same spot, but not more than that. Actually, the possibility to copy text from elements isn't in css3-page, but in css3-gcpm (CSS Generated Content for Paged Media Module), which is only a Working Draft, but there are experimental implementations of that feature and I expect that it will become a standard eventually. Sometimes the content of a running header is neither constant throughout the document nor a copy of some heading in the document. This may happen in technical manuals, for example, where the running headers act a bit like section headings to structure the text, except that they aren't printed in the middle of the page, but only at the top and repeated on every page of that section. The title element in HTML is also an element that is normally not displayed in-line, but can be used for a running header. (However, it has no sub-structure.) The already mentioned css3-gcpm contains a proposal for designating elements as “running elements.” Such elements can have mark-up (child elements) and be styled, allowing for running headers that aren't limited to a single line of text in a single style anymore. This, however, is no more than an early proposal and what it will turn into when we seriously start to discuss it I can't predict. The Prince formatter that I mentioned earlier has a similar feature with a different syntax. I'm interested in hearing what people who used it think of it. For people who know XSL-FO: the CSS proposals have similarities to the retrieve-marker element in XSL-FO and it may be worth looking more at how that element works. In some books the running header is “just” a literal copy of some section header, but those headings have sub-parts. E.g., the heading may have mathematics in it (even just a superscript), or contain bidi-text that requires explicit mark-up (direction overrides). In such cases, applying a single style to the whole of the copied running header is not sufficient. The different parts of the header need different styles. The running header looks simple, but it contains a math formula. A quick survey (not at all scientific) among a couple of mathematicians showed that about a quarter to a third of the math books in their possession contain at least one such running header. Which is enough to conclude that we cannot ignore this requirement, especially now that HTML5 contains math. There is, as far as I know, no proposal yet for how to handle this in CSS. Even css3-gcpm only mentions it as an open issue. I wrote in my list of requirements that a solution will probably require a CSS selector that distinguishes an element based on where it is used, maybe with a pseudo-class (':original', ':copy'). There is work in CSS on a generic solution for styling elements based on the region they are in, rather than their position in the document. So far that doesn't handle running headers, but that may come. The simple, predefined page template that CSS offers (in css3-page) is only good enough if the running headers and footers are along the edges of the page, outside the page body. You can cheat a bit with their margins and make them overlap the page body, but if you want, e.g., a page number right in the middle of the page, you'll need another kind of page template. The existing proposals for how to make such page templates are based on the idea of dividing the page into regions along imaginary grid lines. Each region can either be part of a “flow” of text or be a running header with repeating text (or remain empty, of course). E.g., css3-layout (CSS Template Layout Module) contains this example. (This is from the Editors' Draft, although page-based templates as such are mentioned in the latest published Working Draft, running headers are not.) @page { grid: "t1" 1.2em /* space for 1st running header */ "t2" 1.2em /* space for 2nd running header */ "." 2em /* 2em of empty space */ "*" /* page body */ } ::slot(t1) { content: string(chapter); color: red; text-align: center } ::slot(t2) { content: string(section); color: green; text-align: center } This uses the 'string()' syntax from css3-gcpm, which only allows a single style for the whole string, but the point of the example is to show that you can define arbitrarily many regions for running headers (here just two), give them names (here t1 and t2) and position them anywhere on a grid (here a simple grid with four rows and one column). E.g., to put the same two running headers side by side at the bottom, the grid template would be changed to this grid of three rows by two columns: @page { grid: "* * " /* page body */ ". . " 2em /* 2em of empty space */ "t1 t2" 1.2em /* two regions side by side */ } (This syntax is the compact, shorthand form, which is meant for advanced users. Beginners may want to use the longhand, which uses three separate properties.) To put a page number in region t2, the syntax is then the same as for the predefined page templates, with '::slot(t2)' replacing the name of the predefined region: ::slot(t2) { content: counter(page); color: green } Before we look at another one of the requirements in detail, let's quickly list a few that I don't have time for in this talk. Footnotes are a vast subject. In the simplest case we have one type of footnotes numbered consecutively throughout the document and they are inserted at the bottom of the page. Even then the complication is already that a footnote should preferably be on the same page as the word it belongs to, but that isn't always possible. And you may want a horizontal rule above the footnotes, but only if there actually is a footnote. It gets more complicated with numbering per page, which requires multiple passes (which may not converge), with multiple types of footnotes, numbered separately, with footnotes positioned under columns instead of under the page, and with marginal notes. A subtle issue is also to make sure the footnote number is immediately after the word it belongs to, even if the mark-up has a space between that word and the footnote… css3-gcpm contains some early ideas for footnotes in CSS and there are proprietary extensions in some software. Hypertext has active links: you click on them and within two or three seconds the computer shows you what they refer to. But in a book you have to find the target of the link yourself. For that purpose, they usually contain a page number or a section number. That number is usually generated automatically, because the author doesn't know the number when he writes the text, and indeed it may be different in different printings of the same book. Ideas for relevant CSS properties are in css3-gcpm and there are also proprietary extensions in some programs. A variant of such a link occurs when a text is split over non-consecutive pages, e.g., an article starts on the front page of a newspaper and continues on page 4. The author doesn't know where the break occurs, probably doesn't know on what page the article continues, so this link also has to be inserted by the computer. Maybe you want these references to be more fancy (more natural, in a way) and replace “see page 3” if it occurs on page 2 by “see the next page.” Or use words: “page three” or even ordinals: “see the third bullet”… When a page break occurs, especially if the rest of the text is not on the next page, but in some box elsewhere, it is useful to automatically insert some text, such as “continued on page 3.” There is a proposed 'text-overflow' property in css3-ui that can insert a fixed text when a box overflows, but it is not clear if that applies to page breaks and it cannot currently insert a page number either. CSS provides for floating content, which is content that is not shown inline, but somewhere off to the side, but still near to the text it relates to. In paged media, it is usual to float not to the side, but to the top or bottom of the page. In some cases you don't care if it is on the same page or the next one, and sometimes you do. In case content floats to the side, you may want to float it to the outside edge, away from the spine of the book. And if you have columns, you may want the float either to go to the edge of the page or to the edge of the current column. Because the choice for left or right is made by the computer, the typographer cannot know whether he should set a left or a right margin on the floating content. Maybe properties 'margin-inside' and 'margin-outside' are needed, whose values are added to the left and right margins as appropriate. For this also, there are ideas in css3-gcpm and there are proprietary extensions in programs such as Prince. (In fact, these ideas were already described in internal memos in 1996, but books weren't an important target for CSS back then.) If you refer to a floating illustration, you might want to refer to “the figure below” or “the figure on the next page” depending on where the figure ends up. Floats, especially if they are images, need not be rectangular and you may want text to wrap around them tightly. Also, if you make a page template, even if it is based on a grid, you may want some of the regions not to be rectangular. A pair of drafts, css3-exclusion (CSS Exclusions Module Level 3) and css-shapes (CSS Shapes Module Level 3) contain proposals for this. I already mentioned page templates, but css3-layout also defines element-based templates, because you may want the content of one element (typically a large element, such as a DIV, but not necessarily) to be laid out in a somewhat tabular fashion. Absolute positioning doesn't allow easy alignment and tables can only lay out contents in a fixed order, but templates have neither restriction. Element-based templates aren't just useful in paged media, of course. But in paged media you often have to work with fixed heights, which means in turn that you can align things to the middle of a column or to the bottom. E.g., you may want four news articles in four columns side by side but aligned at the bottom rather than the top. This scan from a magazine shows an example. Note that the text is aligned at the top and at the bottom, by stretching the space between the last and last but one paragraph: This magazine page has four columns, each with one article consisting of: a photo (the four photos have different sizes but are aligned at their bottoms), a heading (of different sizes also, aligned at their tops), a first paragraph, a variable amount of space and a second paragraph that is aligned to the bottom of the column. css3-layout contains proposals for grid templates and for alignment of content inside the regions of that grid, but only to align all the content of a region to one side (the same model and syntax as for table cells). However, in css3-box (only in the editors' draft at the moment: CSS basic box model) there are some ideas for stretching margins as in the scan above. The method is similar to what is used in css3-flexbox (CSS Flexible Box Layout Module), but the syntax differs, because the syntax of css3-flexbox cannot be used in normal, flowing text. Aside: CSS's modules for alignment of elements in GUIs,, in particular css3-flexbox and css3-grid-layout, at first sight look as if they could be used for documents as well. css3-grid-layout and css3-layout indeed use some of the same properties. But css3-flexbox and css3-grid-layout only allow to align single elements, not flows of multiple elements. In other words, they require the mark-up to be modified based on the desired layout. (Which is OK for GUIs, because there the mark-up is part of the style, sometimes called the “skin.”) Also, they have no concept of chained regions, which is necessary to allow content that starts in one region and continues in another. Sometimes some table in a book is so wide that it needs two pages, or a headline in a newspaper is so important that it needs to span from the left edge of the left page to the right edge of the right page. It is not as simple as formatting the content on a page of double the size, because there is the spine of the book and you cannot print too close to it. You also don't want half a word on the left page and the other half on the right page. I know of no proposals for specifying page spreads in CSS. The table of content can usually be generated in a separate stage, after the author finished writing the text and before the style is applied. Only the page numbers have to be filled in during the formatting (which may in theory require multiple passes). But in case you ship an electronic version of the book, rather than paper, you may still want the ToC to be generated at the “client side” so as to ship as small and clean a source document as possible. You could use XSLT or JavaScript, but it could also be added to CSS (although there are no proposals for actual syntax, as far as I know). Good-looking line breaks are important even in scrolling displays, but when reading from paper the user cannot make the text a little wider or narrower, so it is more important that the line breaks are right. Finding the optimal balance between hyphenation, looser or tighter setting, and difference in the amount of space in neighboring lines can be difficult in some cases. If the display is also interactive, the designer might want to give hints about how much time the computer may spend searching for a solution. Some typographers will go as far as modifying the letters slightly: making the letters a fraction of a point narrower is invisible to the human eye, but may be enough to fit one more letter on the line and avoid an ugly hyphen. Or squeeze or stretch the line height a tiny bit such that the page can fit one more line or one line less, and avoid a nasty page break. (Line height adjustment is sometimes referred to a “feathering” or “text feathering.”) Leaders and tabulation are also not exclusive to paged media. Tabulation is subtly different from tables, in that contents is aligned to a “tab stop” but isn't contained in a cell and can continue on the same line past the next tab stop and even wrap to the next line. Here is an example, approximated in ASCII: Hotel . . . . . . . . . . . . 375.55 Travel . . . . . . . . . . 1460.10 Miscellaneous, including presents and tips . . . . . . . . . . 84 Total . . . . . . . . . . . 1918.65 Ph. Fogg CSS can almost do this example, with the leaders in css3-gcpm (which are officially still a draft, but seem quite stable). The “almost” refers to the fact that the numbers in this example aren't aligned at the start or the end, but at the decimal point, a feature the current leaders do not provide. A little more complex still is a tabular rendering with more than one tab stop: Coffee USD 2.00 Tea USD 1.75 Train EUR 67.50 Hotel (including Berlin and Paris) EUR 450.00 An old proposal handled this, but it was abandoned (in 2005) in favor of the easier, but less powerful, model currently in css3-gcpm. In an interactive display, there are usually things outside the “viewport” (as CSS calls it) that somehow depend on the document shown inside. The title is usually visible somewhere (in a menu, as a window title, in a list of bookmarks or history, etc.), but other things possibly also. E.g., PDF viewers have a bookmark menu with useful entry points into the document (section headings, important topics), which are based on information provided by the author as part of the document. One proposal (in css3-ui) also provides an icon for the document, to be used, e.g., in search results or in bookmarks. If the document is displayed in an interactive viewer, certain actions, such as following a hyperlink or turning a page, could be styled as animations by the designer, in order to show that there are different kinds of links or different kinds of pages. E.g., in a complex document, the designer might want to use a spatial metaphor to distinguish different kinds of navigation: the next section is “behind” the current one, the next page is “to the right” of the current one. The style sheet need only contain some hints and if the viewer supports the corresponding animations, it will do its best to show the relations to the reader. Some ideas are in css3-gcpm. Poems and computer code are often printed with line numbers in the margin, for easier reference. The typical method for poems is to number every fifth line, while computer programs are usually numbered at every line. Other parameters are whether to count empty lines and whether to start counting with 1 on every page. There are different kinds of copyfitting. The typographer might want to estimate the number of pages a book will have and choose a different font if the book would become too thick or too thin. But maybe more interesting for CSS is copyfitting on a smaller scale: choose a font size so that a given text fills a given space, or select a different set of style rules altogether if that makes the text fit better, or the other way round: select the text among a set of variants provided by the author that best fits the available space or that avoids an ugly line break. Typical places where you might want to vary the font size are headings. Some newspapers especially try to make headings that are exactly as wide as the column. Probably there should be a minimum font size as well, because if the text is very long, it is better to wrap it than to ask the reader to use a magnifier. If the space is only constrained in the width, the font size is chosen such that the text fits on one line, unless that makes the font smaller than the minimum size. The second and subsequent lines may each get different font sizes. If the space is constrained in height as well, font size is the same on all lines and the last line need not be full. In this case the line height may optionally be made flexible, so that the last line aligns to the bottom. A couple more requirements without going into details: It is common in books to start a chapter on an odd-numbered page (i.e., a right page in English, a left page in vertical Japanese). That means there may be an empty page after when the previous chapter ends on an odd page. You may want to do something with such pages: suppress the page number, add the text “this page intentionally left blank” or some such. The css3-page module has a page selector for such pages. When viewing documents on a screen, it is normally the user and the device that together determine the page size, but when printing a book, the size of the pages is normally specified in the style sheet. css3-page has a property for that. (See also the section on crop marks above.) When printing pages, they are often printed on larger sheets of paper and then cut. CSS level 2 already defined crop marks and cross marks. The style sheet may also be the right place to specify how far outside the edge of the page content should be printed (page bleed), to compensate for slight inaccuracy when the pages are cut. This proposed by css3-gcpm. There are no proposals yet for how to specify that a text should have a change bar in the margin. Scribbling notes in a paper book does not involve CSS, but annotating a book in an interactive reader may involve some CSS to select and style those annotations. CSS has drop caps and large initials since level 2, but there is very little control over how they look. A drop cap should normally be aligned at the bottom with the baseline of some line. E.g., a large drop cap might sit on the baseline of the 6th line of the paragraph. In CSS level 2, this is a question of trial and error for the designer. There are some proposals for how to make the alignment explicit. There is a draft module (css3-ruby) for typesetting ruby annotations with CSS, but it is progressing slowly. The work done until 2003 was found to lack some necessary features. (Another presentation in this workshop, by Yasuki Ikeuchi of ACCESS CO., LTD., will talk about requirements on ruby.) The user may want to listen to (part of) an e-book instead of reading it on the screen. There is a CSS module for speech synthesis: css3-speech. The module currently has Candidate Recommendation status. It does not deal with specifying pronunciation. If words shouldn't be pronounced using the built-in rules of the speech synthesizer, th epronunciation has to be specified in the document, but there is no standard for that yet. text-align: top; float: top; table-caption-side: right… vertical-align: 0.2em= 0.2em to the right; margins collapse left-right; margin: autocenters vertically… Some languages are always written vertically, others, such as Japanese, can be written horizontally or vertically, but are more often written vertically in paged media. The css3-writing-modes module (CSS Writing Modes Module Level 3) proposes properties for switching between vertical and horizontal and for the text effects that only occur in vertical, such as rotated letters and combining narrow horizontal letters into a single letter-like box (“tate-chu-yoko”). But other modules are affected, too. Vertical text changes the interpretation of some properties, e.g.: 'line-height' is interpreted effectively as a line width; 'text-align' acquires new 'top' and 'bottom' keywords; 'direction: rtl' for Hebrew or Arabic inside vertical text is interpreted to mean bottom-to-top. Others are unchanged, e.g.: 'margin-left' is still on the left, the '@top-left' box for running headers is still on the top left, '@page :left' still selects the left-hand page. Vertical text, such as for Japanese, has been worked on in CSS since early 1999, i.e., during the development of CSS level 2. That makes it one of the oldest unsolved problems, after page templates. A different model was tried in 2001-2003 and even reached Candidate Recommendation status. Microsoft implemented it. But, like the first attempt, it was found to be insufficient. Since December 2010 the WG is developing its third model. Hopefully this will be the right one. (In the mean time, the Japanese Layout Task Force had published its report, which is of great help, at least for Japanese.) Some styles only possible during formatting: Simplistic foo, 7, 7, 7, 15, 16, 16, 16, 17–19 Collapse ranges foo, 7, 7, 15–19, 16 Keep most important foo, 7, 15–19, 16 Requirements still unclear No proposals yet At first sight, an alphabetic index can be generated before the formatting phase, just like the table of contents, based on the mark-up of indexable terms in the document. Only the page numbers need to be filled in later. But the resulting index may not be quite what typographers want. E.g., if a term occurs twice on the same page, the typographer wants to have the option of only listing that page number once; or if a term occurs on three successive pages (“4, 5, 6”), he might want to indicate that by a range (“4–6”); or if the defining instance and a mere mention occur on the same page, he might want to suppress the latter. All these improvements can only be done after the page numbers have been established, i.e., by the formatter itself. XSL has properties for this, but nobody has proposed a method for CSS so far. The alternative (which I suspect many publishers use) is to reserve a certain number of pages for the index, format the rest of the book, and then have somebody make an index by hand, hoping that it will fit in those reserved pages. That works for a paper book, it doesn't work in an e-book, where the page numbers depend on the viewer. Ideas for CSS properties (from 1999) never published MathML for CSS Profile – subset approximated with CSS Some requirements: I mentioned above that running headers sometimes contain mathematical formulas, but in fact support for mathematics in CSS is all but nonexistent. The inclusion of MathML in HTML5 is good news for publishing. TEX creates beautiful books, but it doesn't have the semantics of HTML or MathML, and it doesn't work so well for e-books. (It's about time: the first demo of math in HTML I saw already in 1995, in Darmstadt at the third Web conference…) Until now, you could only combine MathML with XHTML by means of namespaces, but that leads at most to a syntactically valid document, not to a standard format with defined semantics, which can be supported by software. Unfortunately, despite initial efforts by the CSS WG and the Math WG towards a draft in 1999, the CSS WG never managed to publish a Working Draft for mathematical typography. The Math WG, in order to help support of HTML5, analyzed the existing CSS and published a sample style sheet, together with the subset of MathML that could at least be rendered in a readable way. But to do proper math renderering, and to support the rest of MathML, CSS needs new kinds of boxes (values for the 'display' property) for built-up formulas, properties for stretching operators, properties for baseline alignment, properties for line breaking in formulas, etc. (A Digital Publishing Interest Group may in the future help the CSS WG and other WGs by providing publishing expertise) In summary, it is not possible to make books or e-books with standard CSS. CSS isn't even up to the level of XSL-FO 1 yet. On the other hand, there are proprietary extensions, in EPUB and in various products, that at least show that CSS can be extended. Neither those extensions nor any of the other ideas that have been proposed have received a lot of scrutiny. Adding them to CSS is going to take time. Indeed, one may ask if it wouldn't be quicker to make a new style language, not required to be backwards compatible with CSS and from the start designed to handle complex layouts and typography without compromises. I have collected an initial list of requirements and started looking at how they might be solved within CSS, but that list is far from complete. E.g., there is also the longer list that the XSL WG collected a few years ago for XSL-FO 2 and that hasn't been looked at from the point of view of CSS at all. It is likely that most things on that list will also have to be turned into technology and standardized. Now is the time to think about how we want to standardize a technology for typesetting books, magazines and e-books. Should it be based on CSS? On XSL? RDF? something else? How many parts should it have: one, as is typical with CSS? Two as for XSLT and XSL-FO? More? At the same time we should continue collecting requirements and use cases. There was expertise in the XSL WG and we are at risk of losing it. Hopefully we can create an Interest Group for digital publishing, which can help the CSS WG and other groups in their work. To Lead the Web to its full potential To Anticipate the Trends To Increase your company value Join W3C or contact: Naomi Yoshizawa Bert Bos <bert@w3.org> GPG fingerprint: 7744 0204 52A5 14D9 147D 2A13 2D7A E420 184B 5BA4 Can you typeset a book with CSS? At first sight, the answer seems obviously yes. The book Cascading Style Sheets, designing for the Web, which Håkon Lie and I wrote back in 2005 (for the 3rd edition), was written in valid, clean HTML, with images in PNG, and a CSS style sheet to turn it into “camera-ready” PDF for the printers. And now, in 2013, publishers are using CSS every day to make books.
http://www.w3.org/Talks/2013/0604-CSS-Tokyo/
CC-MAIN-2014-52
refinedweb
6,118
65.56
There are many applications requiring a search for a particular element. Searching refers to finding out whether a particular element is present in the list. The method that we use for this depends on how the elements of the list are organized. If the list is an unordered list, then we use linear or sequential search, whereas if the list is an ordered list, then we use binary search. The search proceeds by sequentially comparing the key with elements in the list, and continues until either we find a match or the end of the list is encountered. If we find a match, the search terminates successfully by returning the index of the element in the list which has matched. If the end of the list is encountered without a match, the search terminates unsuccessfully. Example #include <stdio.h> #define MAX 10 void lsearch(int list[],int n,int element) { int i, flag = 0; for(i=0;i<n;i++) if( list[i] == element) { printf(" The element whose value is %d is present at position %d in list\n", element,i); flag =1; break; }); lsearch(list,n,element); getchar(); return 0; } Explanation - In the best case, the search procedure terminates after one comparison only, whereas in the worst case, it will do n comparisons. - On average, it will do approximately n/2 comparisons, since the search time is proportional to the number of comparisons required to be performed. - The linear search requires an average time proportional to O(n) to search one element. Therefore to search n elements, it requires a time proportional to O(n2). - We conclude that this searching technique is preferable when the value of n is small. The reason for this is the difference between n and n2 is small for smaller values of n.
https://www.loopandbreak.com/searching-techniques-linear-or-sequential-search/
CC-MAIN-2021-25
refinedweb
299
59.53
Print python objects like a boss Project description dumpit List all python object attributes with descriptions Installation pip install dumpit Usage from dumpit import pdumpit, fdumpit my_object = ... # Print object to standard output pdumpit(my_object) #Print object to standard output in vertical view pdumpit(my_object, view_='vertical') # vertical | table # Export object to string as text my_var = fdumpit(my_object) # Disable colors in terminal output pdumpit(my_object, colors=False) # False | terminal # Enable colors in string output my_var = fdumpit(my_object, colors='terminal') # Show dunder methods (magic methods) pdumpit(my_object, all_=True) Changelog 0.6.0 Fixed in 0.6.0 - all_ parameter default value is now False - code formatting 0.5.0 Fixed in 0.5.0 - Python 3 compatibility 0.4.2 Fixed in 0.4.2 - Dependency version changed: Click 6.7 -> Click 7.0 0.4.1 Fixed in 0.4.1 - Dunder methods description formatting and new lines. 0.4.0 Added in 0.4.0 - Descriptions for every objects attribute. - Separate dunders from other attributes. 0.3.0 Added in 0.3.0 - Analyse is now view. - Table view support: Print object contents in table view in terminal. - Warnings: Prints warnings in terminal if unknown coloring or view is used. 0.2.0 Added 0.2.0 - Coloring support: Terminal colors for object attributes. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/dumpit/0.6.0/
CC-MAIN-2022-05
refinedweb
244
53.68
Ashupriya - 1of 1 vote How to stop recursion stack as soon as we find a result. e.g. in a Tree recurion where the Order of the algo is O(n) and suppose we find the result just after 4 calls, can we empty the recursion stack and stop the ececution right away... - 0of 0 votes How to merge the 2 BST, in 1) O(n) in 2) O(log n) ? I know its not ethical to [1... I know its not ethical to [1] take help from the internet [2] refer your own code (written earlier) in a telephonic interview But due to the very nature of the telephonic interviews, is it also granted from the interviewer's side to take help? Should n't the telephonic rounds be replaced with video confrencings? I know its a debatable topic, but would like to hear other's opinion... void MirrorAlternateWrapper(Node root){ if( root != null){ mirrorAlternate(root, 0); } } void mirrorAlternate(Node root, int level){ if(root == null) return; mirrorAlternate(root.left, level+1); mirrorAlternate(root.right, level+1); if(level %2 == 0){ Node temp = root.right; root.right = root.left; root.left = temp; } } And there are many other ways like Greedy to find the sub otimal solution of this problem in O(N) itself for unsorted array also. This problem is called Easiest hard problem... Its really LOL !!! @Anonymous : This question is similar to partition problem, see the article ... en.wikipedia.org/wiki/Partition_problem In this algo, the probability of generating each valid number is not same ... the numbers next to the blacklisted numbers are having double the chance than others This is an NP-Complete problem in itself, and it can not be solved in O(n) for un-sorted array if array is sorted then it can be done in O(n) It looks interesting but due to the linear structure of the bt. The searching an element is On... And doing so for n elements of list b... The total complexiety is On^2 [1] Random variable being generated and used in some way in the code, some of the random number might cause the test to fail [2] Loading an external library [3] contacting the server may get timeout sometime and pass some other times [3.1] Or any other kind of network related problem might occur on and off [4] Race conditions [5] Memory leaks [6] The state of the code might depend on some other process's output and that may cause a failure sometime [7] Use of extern variables which are set by other processes [8] Use of shared memory locations [9] Faulty RAM, (hardware problem) [10] Multithreading [11] When the code is using Singleton design pattern, unit testing is difficult for singleton as the state of the functions using singleton class's object may not be deterministic. [12] Rarely though, but it can be due to a bug in the IDE being used eg Eclipse... sometime we need to restart the Eclipse and program starts working fine again public void greyCode(int n) { int totalN = (int) Math.pow(2,n); for (int i = 0; i < totalN; i++) { int greyCode = i ^ (i / 2); System.out.println(greyCode); intToBinary(greyCode); // Converts the num to binary pattern } } Had we knew the location of the car, we could have reached there in finite constant time, refer the question again No I mean O(logN) and not O(NlogN) if you see the logic carefully, we are doing less than n recurssive calls, each step tries to calculate 2 powers, Moreover Recursion is generally not O(N Log N).... I also liked the approach below by Raju: Can we use hash table to build up the Stack with Keys as incremental value(1,2,3,...etc.,) and kee track of Top pointer and due to hash table it is dynamic as well. @Ryan: Slight modification in your code and now it will run in O(logN) time.... see the changed code below public static int Power(int base, int expo){ if(expo == 0) return 1; if(expo == 1) return base; if(expo%2==0) return (Power(base*base,expo/2); else return base*Power(base*base,(expo-1)/2); } Note 1: we are using 64 Bits notation : It means maximum 64 bits can be on for a given number so the fib. num < 64 are 1,2,3,5,8,13,21,34,55 Initialize a lookup table with these numbers or we can use a hash table as well for O(1) lookup. n = higherNumber while(n ^ lowerNumber !=0) { int noOfBits = countBits(n); // Using bit wise operators this can be done in O(c) time, where c is the number of bits set in n. Hence constant time operation if(presentInLookUpTable(noOfBits)) { System.out.println(n); } n--; } An operating system crash commonly occurs when a hardware exception occurs that cannot be handled. Operating system crashes can also occur when internal sanity-checking logic within the operating system detects that the operating system has lost its internal self-consistency. Simple solution : public void rotateArrayLikeSTLRotate(int[] arr) throws Exception { if(arr != null && arr.length > 1) { int len = arr.length; int mid = (len-1)/2; int start = 0; int end = len - 1; for (int i = 0; i <= mid; i++) { //Swap i th element with end-mid+i th element int temp = arr[i]; arr[i] = arr[end - mid + i]; arr[end - mid + i] = temp; } } else { throw new Exception("Invalid input parameters"); } } Formally, for every integer n such that 0 <= n < last - first, the element *(first + n) is assigned to *(first + (n + (last - middle)) % (last - first)). Rotate returns first + (last - middle). Another way to solve this could be: Create a hashmap for the given strings with key as "FirstLetter Number LastLetter" for example a4t (addict) and when a query comes we can simply look into this hash map Inheritance is a bad choice here, go for composition, Since "Tiger is A lion" is not true, Don't use Inheritance, I simple meant that: Since the interviewer knows that the candidate can refer some help, so should the interviewer ask the questions which are not copy-able, like it happens in open book exams? or should he simple allow the candidate to refer the help. We can have a Signal class, which is inherited by vehicle Signal and Pedestrian Signal. Signal{ LED Timer } Class SignalManager{ VehicleSingnal[4]; PedestrianSingnal[8]; doWork() { while ( true) switch on the signals in roundrobin fashion } } Question says Body and not BodyPart, this design is good I agree, but not in the limits of the question conditions We can also think of to implement a ChainOfResponsibility design pattern , where a employee would be let go through all the dept, Once the work with one dept is complete, it will automatically send the employee to the next dept. We can apply the observer pattern in the ScoreCard Updation, Decorator pattern in providing the telecast/ webcast mechanism... I read some where that AVL trees can be merged in O(logN) time, but could not find out the algo, Also treaps (see wikipedia page on Treaps) can be merged/split in O(LogN) time.... Still no concrete algo)); class Node <T>{ public T data; public Node<T> next; public Node<T> nextLarge; // To point the next large element in the list Node (T t) { data = t; } } public Node<T> applicationOfMergeSort(Node<T> head) { if(head == null || head.next == null) return head; else { Node<T> slow = head; Node<T> fast = head; //Split while(fast.next != null) { fast = fast.next; if(fast.next != null) fast = fast.next; else break; slow = slow.next; } Node<T> List1 = head; Node<T> List2 = slow.next; Node<T> copyL2 = List2; slow.next = null; // Split complete // Recursively Split and then merge until we reach a list of sizes 1 List1 = applicationOfMergeSort(List1); List2 = applicationOfMergeSort(List2); //Since List1 will ultimately hold the result of merging do lets reset the head to point to List1, //head will be returned as a result of this function head = List1; //Merge Node<T> prev = null; while(List1 != null && List2!= null) { if((Integer) List1.data < (Integer) List2.data) { prev = List1; List1 = List1.nextLarge; } else { Node<T> nextList2 = List2.nextLarge; List2.nextLarge = List1; if(prev == null) { head = List2; } else { prev.nextLarge = List2; } prev = List2; List2 = nextList2; } } if(List2 != null) prev.nextLarge = List2; // Merging Complete // Now make the connection of next pointers, broken earlier in the split step slow.next = copyL2; return head; } } What if you had no control at the time of the list creation? this wont work,... I have a solution based on the hash map, but that handles only 1 type of mal pointer out of 2 possible cases, The solution below solves the case when there is a loop in list... 1-2-3 4-5-6-null, 3 points to 1 start traversing the list and make a hash map as below and look for collision if there is a collision then there is a bad pointer 1 Null 2 1 3 2 now comes 1 again and collision occurs... But another case: 1-2-3 4-5-6-null, 3 points to 5 is not solvable here as we do not have a reference to 4... This method needs the list to be traversed 3 times, Just wondering can we not do it in single pass...? Since you have calculated the lengths, move the longer list's head by (|l1-l2|) nodes, and then just handle the case of equal lengths with carry at the head of longer list ... it will save some un wanted code if this the query is going to be repetitive, then one time activity would fetch the results in O(1) time... For every point i create a hash <distance(i , j), point j> and check if there is a value exists for the given node with given distance d... Make a graph like structure for all the pages, and then keep count of the inDegree of the nodes, the node with highest in degree is the one linked to most of the pages We can calculate the 2nd order of the adjMatrix, this would not only give the paths of length 2 but also the No of 2-length paths possible between i and j.... Divide the file in N chunks, of 10,000 (e.g.) lines each store the offset of these N chunks in another file / in memory. For the last chunk, also count the line numbers (Let say have K line) in it, if it is less than 10,000 then store this information as well Generate a number randomly between 1 to N, and open this chunk, by seeking to that position in that file. Now generate another number between 1 and 10,000 and return taht line, in case of the last chunk generate the number between 1 and K, and return that line.... I can not understand how is the mirrorAlt function is mirroring at alternate levels- Ashupriya July 15, 2013
https://careercup.com/user?id=13396670
CC-MAIN-2018-26
refinedweb
1,832
65.76
EBook::MOBI - create an ebook in the MOBI format. You are at the right place here if you want to create an ebook in the so called MOBI format (somethimes also called PRC format or Mobipocket). This is a software library for the perl programming language. If you plan to create a typical ebook you probably will need most of the methods provided by this module. So it might be a good idea to read all the descriptions in the methods section, and also have a look at this example here. Paste and run. use EBook::MOBI; my $book = EBook::MOBI->new(); $book->add_mhtml_content("hello world"); $book->make(); $book->save(); You should then find a file book.mobi in your current directory. Because the input in this example is from the same file as the code, and this text-file is utf-8, we enable utf-8 and we will have no problems. use utf8; Then we create an object and set some information about the book. # Create an object of a book use EBook::MOBI; my $book = EBook::MOBI->new(); # give some meta information about this book $book->set_filename('./data/my_ebook.mobi'); $book->set_title ('Read my Wisdome'); $book->set_author ('Alfred Beispiel'); $book->set_encoding(':encoding(UTF-8)'); Input can be done in several ways. You can always work directly with the format itself. See EBook::MOBI::Converter for more information about this format. # lets create our own title page! $book->add_mhtml_content( " <h1>This is my Book</h1> <p>Read my wisdome.</p>" ); $book->add_pagebreak(); To help you with the format use EBook::MOBI::Converter. The above would then look like this: my $c = EBook::MOBI::Converter->new(); $book->add_mhtml_content( $c->title('This is my Book', 1, 0) ); $book->add_mhtml_content( $c->paragraph('Read my wisdome') ); $book->add_mhtml_content( $c->pagebreak() ); At any point in the book you can insert a table of content. # insert a table of contents after the titlepage $book->add_toc_once(); $book->add_pagebreak(); The preferred way for your normal input should be the add_content() method. It makes use of plugins, so you should make sure there is a plugin for your input markup. my $POD_in = "=head1 Title\n\nSome text.\n\n"; # add the books text, which is e.g. in the POD format $book->add_content( data => $POD_in, driver => 'EBook::MOBI::Driver::POD', driver_options => { pagemode => 1}, ); After that, some small final steps are needed and the book is ready. # prepare the book (e.g. calculate the references for the TOC) $book->make(); # let me see how this mobi-format looks like $book->print_mhtml(); # ok, give me that mobi-book as a file! $book->save(); # done Give a string which will appear in the meta data of the format. This will be used e.g. by ebook-readers to determine the books name. $book->set_title('Read my Wisdome'); Give a string which will appear in the meta data of the format. This will be used e.g. by ebook-readers to determine the books author. $book->set_author('Alfred Beispiel'); The book will be stored under the name and location you pass here. When calling the save() method the file will be created. $book->set_filename('./data/my_ebook.mobi'); If you don't use this method, the default name will be 'book.mobi'. If you don't set anything here, :encoding(UTF-8) will be default. $book->set_encoding(':encoding(UTF-8)'); Only two encodings are supported by the mobiperl driver: UTF-8 or ISO-8859-1. ASCII is treated the same as ISO-8859-1. If any other encodings are passed in, the module will raise an error. Please see for the syntax of your encoding keyword. If you use use hardcoded strings in your program, use utf8; should be helping. _content() method. $book->add_mhtml_content( " <h1>This is my Book</h1> <p>Read my wisdome.</p>" ); If you indent the 'h1' tag with any whitespace, it will not appear in the TOC (only 'h1' tags directly starting and ending with a newline are marked for the TOC). This may be usefull if you want to design a title page. There is a module EBook::MOBI::Converter which helps you in creating this format. See it's documentation for more information. If you are passing your own text to add_mhtml_content rather than using a converter you will need to: a) encode the text according to your chosen encoding, eg call Encode::encode_utf8; b) ensure that any HTML entities such as '<' in your text are replaced, eg by calling HTML::Entities::encode_entities. Use this method if you have your content in a specific markup format. See below for details to the arguments supported by this method. $book->add_content( data => $data_as_string, driver => $driver_name, driver_options => {plugin_option => $value} ); The method uses a plugin system to transform your format into an ebook. If you don't find a plugin for your markup please write one and release it under the namespace EBook::MOBI::Driver::$YourMarkup. Details for the options of this method: A string, containing your text for the ebook. The name of the module which parses your data. If this value is not set, the default is EBook::MOBI::Driver::POD. You are welcome to add your own driver for your markup of choice! Pass a hash ref here, with options for the plugin. This options may be different for each plugin. Use this method to seperate content and give some structure to your book. $book->add_pagebreak();. Only 'h1' tags starting and ending with a newline char will enter the TOC. $book->add_toc_once(); By default, the toc is called 'Table of Contents'. You can change that label by passing it as a parameter: $book->add_toc_once( 'Summary' ); This method can only be called once. If you call it twice, the second call will not do anything. You only need to call this one before saving, if you have used the add_toc_once() method. This will calculate the references, pointing from the TOC into the content. $book->make();('result to var'); Put the whole thing together as an ebook. This will create a file, with the name and location you gave with set_filename(). $book->save(); In this process it will also read images and store them into the ebook. So it is important, that the images are readable at the path you provided before. Reset the object, so that all the content is purged. Helpful if you like to make a new book, but are to lazy to create a new object. (e.g. for testing) $book->reset(); You can just ignore this method if you are not interested in debugging! Pass a reference to a debug subroutine and enable debug messages. sub debug { my ($package, $filename, $line) = caller; print "$package\t$_[0]\n"; } $book->debug_on(\&debug); Or shorter: $book->debug_on(sub { print @_; print "\n" }); Stop debug messages and erease the reference to the subroutine. $book->debug_off(); EBook::MOBI::Driver::POD is a plugin for Perls markup language POD. Please see its docs for more information and options. EBook::MOBI::Driver::Example is an example implementation of a simple plugin. It is only useful for plugin writers, as an example. Please see its docs for more information and options. Since v0.56 there is a change to the image behaviour. If you like to include images or pictures into your ebook you now should install the module EBook::MOBI::Image. This code is no more with the main module, to reduce dependencies to image libraries (not everybody need to add images). It depends on your input plugin, how you can add images to your book. For POD, see the special syntax described in EBook::MOBI::Driver::POD. For adding manually in MHTML, see EBook::MOBI::Converter. Shortcut for lazy guys: The conclusion of reading EBook::MOBI::Driver::POD will be that you can add images via the POD-driver as following: $book->add_content( data => '=for image /my/camel.jpg This is a Camel.', driver => 'EBook::MOBI::Driver::POD', driver_options => { pagemode => 0, head0_mode => 0 } ); If you don't want to use the POD driver for adding images then you should read the section WHAT IS MHTML? in the module EBook::MOBI::Converter (as said already). But this needs some effort. EBook::MOBI::MobiPerlis coming from MobiPerl. For information about this code, please visit This program is free software; you can redistribute it and/or modify it under the same terms of Artistic License 2.0. Boris Däppen <bdaeppen.perl@gmail.com>
http://search.cpan.org/~borisd/EBook-MOBI-0.72/lib/EBook/MOBI.pm
CC-MAIN-2017-09
refinedweb
1,401
66.13
T_SND(3N) T_SND(3N) NAME t_snd - send normal or expedited data over a connection SYNOPSIS #include <<tiuser.h>> int t_snd(fd, buf, nbytes, flags) int fd; char *buf; unsigned nbytes; int flags; DESCRIPTION t_snd() sends either normal or expedited data. fd identifies the local transport endpoint over which data should be sent, buf points to the user data, nbytes specifies the number of user data bytes to be sent, and flags specifies any optional flags described below. By default, t_snd() operates synchronously and may wait if flow control restrictions prevents data acceptance by the local transport provider when the call is made. However, if O_NDELAY is set (using t_open(3N) or fcntl()), t_snd() executes asynchronously, and fails immediately if there are flow control restrictions. On success, t_snd() returns the byte total accepted by the transport provider. This normally equals the bytes total specified in nbytes. If O_NDELAY is set, it is possible that the transport provider will accept only part of the data. In this case, t_snd() will set T_MORE for the data that was sent (see below) and returns a value less than nbytes. If nbytes is zero, no data is passed to the provider; t_snd() returns zero. If T_EXPEDITED is set in flags, the data is sent as expedited data, subject to the interpretations of the transport provider. T_MORE indicates to the transport provider that the transport service data unit (TSDU), or expedited transport service data unit (ETSDU), is being sent through multiple t_snd() calls. In these calls, the T_MORE flag indicates another t_snd() is to follow; the end of TSDU (or ETSDU) is identified by a t_snd() call without the T_MORE flag. T_MORE allows the sender to break up large logical data units, while preserving their boundaries at the other end. The flag does not imply how the data is packaged for transfer below the transport interface. If the transport provider does not support the concept of a TSDU as indicated in the info argument on return from t_open(3N) or t_getinfo(3N), the T_MORE flag is meaningless. The size of each TSDU or ETSDU must not exceed the transport provider limits as returned by t_open(3N) or t_getinfo(3N). Failure to comply results in protocol error EPROTO. See TSYSERR below. If t_snd() is issued from the T_IDLE state, the provider may silently discard the data. If t_snd() is issued from any state other than T_DATAXFER or T_IDLE the provider generates a EPROTO error. RETURN VALUES On success, t_snd() returns the number of bytes accepted by the trans- port provider. On failure, it returns -1 and sets t_errno to indicate the error. ERRORS TBADF The specified file descriptor does not refer to a transport endpoint. TFLOW O_NDELAY was set, but the flow control mechanism prevented the transport provider from accepting data at this time. TNOTSUPPORT This function is not supported by the underlying transport provider. TSYSERR The function failed due to a system error and set errno to indicate the error. SEE ALSO t_open(3N), t_rcv(3N) 21 January 1990 T_SND(3N)
http://modman.unixdev.net/?sektion=3&page=t_snd&manpath=SunOS-4.1.3
CC-MAIN-2017-30
refinedweb
505
53.61
/* Convenience header for conditional use of GNU <libintl.h>. Copyright (C) 1995-1998, 2000GETTEXT_H #define _LIBGETTEXT_H 1 /* NLS can be disabled through the configure --disable-nls option. */ #if ENABLE_NLS /* Get declarations of GNU message catalog functions. */ # include <libintl.h> #else /* Solaris /usr/include/locale.h includes /usr/include/libintl.h, which chokes if dcgettext is defined as a macro. So include it now, to make later inclusions of <locale.h> a NOP. We don't include <libintl.h> as well because people using "gettext.h" will not include <libintl.h>, and also including <libintl.h> would fail on SunOS 4, whereas <locale.h> is OK. */ #if defined(__sun) # include <locale.h> #endif /* Many header files from the libstdc++ coming with g++ 3.3 or newer include <libintl.h>, which chokes if dcgettext is defined as a macro. So include it now, to make later inclusions of <libintl.h> a NOP. */ #if defined(__cplusplus) && defined(__GNUG__) && (__GNUC__ >= 3) # include <cstdlib> # if (__GLIBC__ >= 2) || _GLIBCXX_HAVE_LIBINTL_H # include <libintl.h> # endif #endif /* Disabled NLS. The casts to 'const char *' serve the purpose of producing warnings for invalid uses of the value returned from these functions. On pre-ANSI systems without 'const', the config.h file is supposed to contain "#define const". */ # define gettext(Msgid) ((const char *) (Msgid)) # define dgettext(Domainname, Msgid) ((const char *) (Msgid)) # define dcgettext(Domainname, Msgid, Category) ((const char *) (Msgid)) # define ngettext(Msgid1, Msgid2, N) \ ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) # define dngettext(Domainname, Msgid1, Msgid2, N) \ ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) # define dcngettext(Domainname, Msgid1, Msgid2, N, Category) \ ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) # define textdomain(Domainname) ((const char *) (Domainname)) # define bindtextdomain(Domainname, Dirname) ((const char *) (Dirname)) # define bind_textdomain_codeset(Domainname, Codeset) ((const char *) (Codeset)) #endif /* A pseudo function call that serves as a marker for the automated extraction of messages, but does not call gettext(). The run-time translation is done at a different place in the code. The argument, String, should be a literal string. Concatenated strings and other string expressions won't work. The macro's expansion is not parenthesized, so that it is suitable as initializer for static 'char[]' or 'const char[]' variables. */ #define gettext_noop(String) String #endif /* _LIBGETTEXT_H */
http://opensource.apple.com/source/text_cmds/text_cmds-71/sort/gettext.h
CC-MAIN-2015-22
refinedweb
368
53.27
Java Generics – Get one step closer to become a Java Expert! Suppose we have to make a list of human beings living in society. It doesn’t matter whether it’s a child, teen or adult. All that matters is they should be human. In such cases, we will not categorize them and will group them as a “Human Being”. Similarly in Java when we store data we focus on the content and not datatype and that’s where Generics are used. Java Generics is a programming-language feature that allows for the definition and use of generic methods and generic types. Today in this Java tutorial, we are going to study the Generics in Java and it’s Class with multiple parameters. We will also discuss various features and functions of generics in Java. At last, we will learn how to use generics in Java to improve the quality of the code with the help of examples. Java Generics Java introduced the concept of Generics since Java 5 (J2SE 5) to deal with compile-time type checking and removing the risk of ClassCastException that was common while working with collection classes. Generics in Java is one of the most important features introduced since Java 5. The term Generics in Java represents a set of features in a language, that relates to defining and using the generic methods and types. In Java, Generic methods and types are different from regular methods and types. They differ from each other as generic methods have type parameters. We can see Java Generics as the templates in C++. Using Java Generics, we can use the wrapper classes like Integer, String, Double, etc and user-defined types as the parameters to classes, methods, and interfaces. We can utilize the generics for any kind. For example, classes like HashSet, ArrayList, HashMap, etc use the Java Generics very well. Need for Java Generics Java Generics allow us to write a single method that could be able to perform operations in various types of objects that support that method. Using Java Generic classes and methods, programmers can specify a set of related methods with a single/generic method declaration, or with a single class declaration. For example, the Java Generics concept allows us to write a generic method for sorting an array of different types of objects, like to invoke the generic method with Character arrays, Integer arrays, String arrays, Double arrays and so on to sort the array elements. Moreover, Java Generics provide compile-time type safety that allows the programmers to catch invalid types or faults during compilation. Get to know more about Java Array in detail with Techvidvan. Java Generic Classes A generic class is a class that can refer to any type. To create a generic class of a specific type, we put the T type parameter. The angular brackets <> are used to specify parameter types in Java generic class creation. Dive a little deep into the concept of Classes in Java to clear your basics. Let’s discuss a simple example to create and use the generic class. Creating a Generic Class The declaration of a generic class is similar to a non-generic class declaration, the only difference is that the generic class name is followed by a type parameter section. The following code shows the creation of a generic class. class MyGenClass<T> { T obj; void add(T obj) { this.obj=obj; } T getObj() { return obj; } } Here, the type T indicates that it can refer to any type of class like Integer, String, Double, Character, and Employee, etc. The specified type of class will store and retrieve the data of the same type. Note: In Parameter type, we cannot use primitives data types like ‘int’,’char’ or ‘double’, etc. Using a Generic Class class TestGenerics3 { public static void main(String args[]) { MyGenClass<Integer> myObj = new MyGenClass<Integer>(); myObj.add(18); //myObj.add("TechVidvan"); //Compile-time error System.out.println(myObj.getObj()); } } Output: Code to understand Generic Classes: package com.techvidvan.javagenerics; // We use < > to specify Parameter type class MyGenericClass<T> { // Declaring an object of type T T obj; // constructor MyGenericClass(T obj) { this.obj = obj; } public T getObject() { return this.obj; } } class GenericClassDemo { public static void main (String[] args) { //Using Generic class for Integers MyGenericClass <Integer> intObj = new MyGenericClass<Integer>(15); System.out.println(intObj.getObject()); //Using Generic class for String MyGenericClass<String> stringObj = new MyGenericClass<String>("TechVidvan"); System.out.println(stringObj.getObject()); } } Output: TechVidvan Using Multiple type Parameters in Generic Classes We can also use multiple parameters of different types in a generic class, that is, the parameter type section of a generic class can have more than one type of parameter separated by commas. These classes are known as parameterized classes since they accept more than one parameter. Code to illustrate multiple type Parameters in Generic Classes: package com.techvidvan.javagenerics; class Test<T, U> { T obj1; // An object of type T U obj2; // An object of type U // constructor Test(T obj1, U obj2) { this.obj1 = obj1; this.obj2 = obj2; } // To print objects of T and U public void getObject() { System.out.println(“String value: “ +obj1); System.out.println(“Integer value: ” +obj2); } } class Main { public static void main (String[] args) { Test <String, Integer> obj = new Test<String, Integer>("TechVidvan", 15); obj.getObject(); } } Output: Integer value: 15 Type Parameters The type parameter’s naming conventions are crucial for learning generics thoroughly. The common type parameters are as follows: - T – Type - E – Element - K – Key - N – Number - V – Value Java Generic Methods We can declare a single generic method and we can call this method with arguments of different types. The compiler handles each method call appropriately according to the types of the arguments passed to the generic method. Rules to define Generic Methods - There should be a type parameter section in all generic method declarations, delimited by angular brackets <> that precede the method’s return type. - If there is more than one parameter in the parameter list then each type parameter should be separated by commas. - We can also use the type parameters to declare the return type and let them act as placeholders for the types of arguments passed to the generic method, called as actual type arguments. - The method body of a generic method is declared similar to any other non-generic method. - The type parameter in a method can represent only reference types, non-primitive types like int, double and char. Get familiar with the concept of Data types in Java in detail with Techvidvan. Code to understand Generic Methods: package com.techvidvan.javagenerics; public class GenericMethodDemo { // defining generic method printArray public static < E > void printArray( E[] inputArray ) { // Displaying array elements for(E element : inputArray) { System.out.printf("%s ", element); } System.out.println(); } public static void main(String args[]) { // Create arrays of Integer, Double and Character Integer[] intArray = { 10, 20, 30, 40, 50 }; Double[] doubleArray = { 1.2, 2.5, 4.6, 7.8 }; Character[] charArray = { 'T', 'e', 'c', 'h', 'V', 'i', 'd', 'V', 'a', 'N' }; System.out.println("Array integerArray contains:"); printArray(intArray); // pass an Integer array System.out.println("\nArray doubleArray contains:"); printArray(doubleArray); // pass a Double array System.out.println("\nArray characterArray contains:"); printArray(charArray); // pass a Character array } } Output: 10 20 30 40 50 Array doubleArray contains: 1.2 2.5 4.6 7.8 Array characterArray contains: T e c h V i d V a n What is not allowed to do with Java Generics? Now, we will discuss some tasks that are not allowed to do in Java Generics. So let’s examine each of them. a) You can’t have a static field of type In your generic class, you can not define a static generic parameterized member. Any attempt to do so will generate a compile-time error. The error will be like: Cannot make a static reference to the non-static type T. public class GenericClass<T> { private static T member; //This is not allowed } b) You can not create an instance of T We can also not create an object of T. Any attempt to do so will fail with an error: Cannot instantiate the type T. For example, public class GenericClass<T> { public GenericClass() //Constructor created { new T(); //Not Allowed } } c) We can’t use primitive data types with Generics declaration We can’t declare generic expressions like List or Map <int, double>. But, we can use the wrapper classes in place of primitive data types and then use the primitives while passing the actual values. Auto-boxing converts these primitive types to their respective wrapper classes. final HashMap<int> id = new HashMap<>(); //Not allowed final HashMap<Integer> id = new HasMap<>(); //Allowed d) You can’t create Generic exception class We can’t pass an instance of generic type along with exception being thrown. This is not allowed in Java. For example, the following line causes an error. // causes compiler error public class GenericClass<T> extends Exception {} When you try to do this, you will get an error message like this: The generic class GenericException may not subclass java.lang.Throwable. Advantages of Java Generics Applications that make use of Java Generics have several benefits over the non-generic code. Some of them are as follows – 1. Code Reuse We can create a generic strategy or a class or an interface once and use it for any type we need and for any number of times. For better understanding, you must explore the concept of Java Interface in detail. 2. Sort Safety It is better to know the faults and issues in your code at compile-time rather than at run-time. Java Generics enables you to detect the faults at compile-time than at runtime. Suppose, you need to make an ArrayList that stores the name of undergraduate students and if by mistake, software engineer includes an integer in place of a string, compiler permits it. However, when we try to gain this information from ArrayList, it causes issues at runtime. class Test { public static void main(String[] args) { // Creating an ArrayList with String specified ArrayList <String> al = new ArrayList<String> (); al.add("Sachin"); al.add("Rahul"); //Type Casting is required String s1 = (String)al.get(0); String s2 = (String)al.get(1); String s3 = (String)al.get(2); } } 3. Individual Type Casting isn’t required In the above case, if we don’t use Java generics, at that point, we need to typecast the ArrayList each time we recover information from it. It is a major headache to typecast at each recovery. If we utilize the Java generics in our code, then we need not do typecasting at each recovery. The below code shows this concept: class Test { public static void main(String[] args) { // Creating an ArrayList with String specified ArrayList <String> al = new ArrayList<String> (); al.add("Sachin"); al.add("Rahul"); // Typecasting is not needed String s1 = al.get(0); String s2 = al.get(1); } } 4. Implementing non-generic algorithms We can perform the calculations that work on various sorts of items by utilizing generics in Java, and they are type-safe as well. Summary To use Java Generics for achieving type-safety, the whole collection framework was re-written. With this, we come to the end of our article on Java Generics. In this article, we learned the basic concept of Java Generics along with its classes, methods, and uses. We also covered some advantages and need for Generics in Java with examples. That was all about Java Generics. I hope this article helped you in understanding the concept of Java Generics. Happy Learning 🙂
https://techvidvan.com/tutorials/java-generics/
CC-MAIN-2020-16
refinedweb
1,933
54.52
I'm trying to make a deck of cards using c programming. I want it so the computer will ask me for a number from 1-52 and each of the numbers will correspond to a card. I've got as far as the program printing every card but I have no idea how to make a card "whole". I have all the numbers and all the suits but they are in no way attached, they just print up at together. Can anyone help please. All this does is print each number 4 times and cycles through the suits.All this does is print each number 4 times and cycles through the suits.Code: #include <stdio.h> int main(void) { char value[14][6]={"Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace"}; char suit[4][9]= {"Hearts", "Diamonds", "Clubs", "Spades"}; int i=0; int j=0; for (i=0; i<13; i++){ for (j=0; j<4; j++){ printf("The %s of %s\n\n", value[i], suit[j]); } } system("pause"); } Also I'm relatively new to c programming so if possible could the programming be kept at a level easy to understand. Thanks!
http://cboard.cprogramming.com/c-programming/150288-deck-cards-easy-understand-program-printable-thread.html
CC-MAIN-2015-48
refinedweb
199
78.59
I switched to ionic3, but it gives me error wherever I used ionic storage from @ionic/storage in my code. It says that supplied parameters do not match any signature of call target wherever I had used “Storage.get()” and “Storage.set()” functions… Earlier they were working fine with ionic2. I guess they changed the arguments of these functions… Please help me out in this. iOnic 3 is not a new framework they just updated to Angular 4. So they didn’t changed the iOnic storage functionality. Can you share your code? And have you followed the upgrade guide? Yes I followed the upgrade guide… The code I am using is: import { Storage } from ‘@ionic/storage’; new Storage().set(‘anyKey’, ‘anyValue’); new Storage().get(‘anyKey’).then(value => { //code }); Error I am getting is: Typescript Error Supplied parameters do not match any signature of call target. You should inject the storage in your constructor. And you should also user the method this.storage.ready().then(); to be sure your storage is ready. And use a separate provider class for your storage methods. import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; @Injectable() export class DataServiceProvider { constructor(private storage: Storage) { } setShowPresentation(value: boolean) { return this.storage.set('showPresentation', value); } getShowPresentation() { return this.storage.get('showPresentation'); } } By returning the method you can always call the .then() method to check if it worked correctly. Yes injecting storage in constructor solved my problem… I used this.storage.set() & this.storage.get()…Thank you for it… But earlier it worked fine with ionic2… Now I need to change this line everywhere in my whole project… And yes, I’ll make a provider class as you said… Just tell me one more thing, is switching to ionic 3 when it is in its beta version a good idea? I’ll have a production app on ionic 3… They released iOnic 3.1 stable last week so it is out of beta I had no problems with m project’s after the update This breaking change was necessary in order to facilitate including only the native plugin shims that you are actually using. A well worthwhile tradeoff in my opinion. Thank you
https://forum.ionicframework.com/t/problem-with-ionic-storage-in-ionic3/86224
CC-MAIN-2022-27
refinedweb
365
57.98
Menus Plugin Dependency: compile "org.grails.plugins:menus:1.7" Summary Description Menus Plugin DescriptionThe menus plugin allows for the creation, maintenance and display of a menu and its sub-menus (to an arbitrary depth) by defining option records in a database table. A breadcrumb trail is displayed on menu pages for moving back through the menu hierarchy and can also be placed on 'target' pages in your application. A 'return to the menu' button can also be placed on pages in your application to allow the end user to return to the menu system. InstallationExecute the following from your application directory: The system is internationalized using two message bundles: menus.properties and menuOptions.properties which are copied to the i18n directory of your application on installation/update of the plugin overwriting any files of the same name. The menu.properties file is used by the menus plugin itself. The menuOptions.properties file is for you to internationalize the texts of menus you create and contains instructions to that end. Also, a menu subdirectory is created in the views directory of your application and a display.gsp menu display page created there. You may tailor the display.gsp page to suit your own needs. A new image called menu.png is added to the web-app/images/skin directory of your application so that pages of your application can have a 'return to the menu' button displayed on them. A crumb.png image file is copied to the images directory of your application. Finally, the plugin creates a single database domain called Menu which is used to hold the options you create.After installation of the plugin, the Menu table in your database should have a unique index on the 'menu_path' column and a non-unique index on the 'parent' column but, since Hibernate may or may not create these indices, you are advised to check that they exist otherwise performance may suffer. grails install-plugin menus UsageThe components of the plugin are in a package called org.grails.plugins.menus and any class that wishes to access the components directly must include the following: The menus plugin comes with a complete set of CRUD screens that assume you are using a layout called main. You define your menu structure using these screens and you may optionally internationalize your menu texts either using the menuOptions properties bundle or the database system if you have the localizations plugin installed.Once you have your menu structure defined, you can display the menu using a URL such as add a 'return to the menu' button to a page of your application, add the following line (split over multiple lines below only for formatting purposes here) to your GSP. The line would typically be added right after the equivalent definition of the 'home' button: import org.grails.plugins.menus.* You might also wish to add the following definition to your css.main style sheet along with the existing definitions of the other buttons used by the scaffold: <span class="menuButton"><g:link <g:message</g:link></span> If you wish an application page to have a breadcrumb trail of the menu options selected rather (or possibly in addition to) a 'return to the menu' button described previously, then add the following line to your application GSP pages: .menuButton a.menu { background: url(../images/skin/menu.png) center left no-repeat; color: #333; padding-left: 25px; } The display of the breadcrumbs will include the page of your application that was executed and, by default, this will be an active (clickable) link. If you would like it to be inactive (so that it does not re-display the page selected from the menu) then add an active="false" attribute to the <g:optionCrumbs/> tag. If you wish to change the image used to separate crumbs, use an attribute in the optionCrumbs tag such as image="/images/myImage.png".The page that actually displays menus also uses a breadcrumb trail so that the user can move backwards through the menu hierarchy. Consequently, even if you do not intend to use breadcrumb trails on your own application pages, you would probably want to add lines similar to the following to your main.css style sheet in order to format the menu display page itself: <div class="crumbs"><g:optionCrumbs/></div> Since, using the standard Grails scaffolding structure, a user can jump from any page in an application to the home page (index.gsp in the web-app directory), it is a good idea to reset the menu system so that the next time the user goes to the menu display page, it is the main menu that will be displayed as opposed to any last sub-menu page they may have used. To do this, include the following tag in your index.gsp home page: <g:menuReset/>. .crumbs { margin: 20px 0px 20px 0px; color: #666 } .crumb { border: 1px solid #aaa; background: #eee; padding: 2px 4px 2px 4px; } .options li { font-size: 13px; padding-bottom: 4px; }
http://grails.org/plugin/menus
CC-MAIN-2016-22
refinedweb
837
50.77
Two weekends ago, something rare happened. Thirteen people, sharing only a common interest in math, joined together from India, the Middle-East, England, Canada and the United States to solve real math problems. As might be expected, most of them dropped out before the end of the first-ever Mathathon weekend. Nonetheless, the four active participants, aided by two or three less active observers, solved some very real problems. Perhaps there has never been an all-virtual math hackathon devoted to solving problems carefully prepared ahead of time not to be exercises but to be “real” problems, whose solutions were only dreamt of by their authors. It was, in fact, a high bar, and many participants may have been deterred either by the narrow focus or the difficulty of the problems. However, one of the principles of Public Invention, the hosting non-profit, is to Keep It Real — to never do “fake” problems. Since our motto is “Invent in the public, for the public,” all of our code and math is freely shared under open licenses in a freely available GitHub repo. I’m grateful to all those who supported this idea, however briefly, during the weekend. We used Slack and Zoom as our fundamental cooperation tools. When we do this again, we will plan better to deal with time-zone differences. The focus was chains of triangles and tetrahedra glued edge-to-edge or face-to-face together — simplex chains. Although narrow, this field of study is quite well-motivated by structural engineering and robotics. Such objects are inherently interesting to engineers, for two reasons. Firstly, they are inherently rigid and strong for their weight. Secondly, it is easy to build something made out of a limited number of parts, and if every member in a frame is the same length, manufacturing it is comparatively easy. Twenty years ago, building robots completely out of tetrahedra was proposed by Prof. Sanderson of Rensselaer Polytechnic and his students, motivated by applications in space exploration. I attempted to introduce all of this on Friday night, but as any student of math knows, it takes a little commitment to understand even the statement of any real problem. David Jeschke, my co-host, and I had prepared a two-dimensional interactive web page, a “playground”, that lets anyone with a smattering of JavaScript investigate certain problems, the first of which fell to a collaboration of Nathan, Sanchi and myself on Saturday morning. The playground allowed a snippet of code to be tested by graphically drawing it. With some noodling instigated by Sanchi and with a major contribution from Nathan, we found a simple way to tile the plane. Sanchi later solved additional problems, the creation of spirals, on her own. David, meanwhile, worked on a solution I would later expand into 3D: he built an algorithm that would follow any parametric curve in 2D with a chain of equilateral triangles. So, in a stroke, he built a barrel vault and a gothic arch, in theory constructible only out of rods of exactly the same length. At the same time, this produced a passable solution to a problem I called “Bresenham’s problem”, that of efficiently building a truss from any one point in a straight line to another. Obviously, this allows nearly arbitrary regular trusses to be designed. Nathan and I worked on an analogous 3D playground at the same time. We got a similar ability to build chains of tetrahedra out of simple snippets of code. On Saturday evening. I was rather surprised to see this working. More interesting to me was the fact, which I still find startling, that every periodic “generator” produce a helix. (A ring and a line are both degenerate forms of a helix.) I would never have predicted this, though I have since created a proof of it, and have been spending the 10 days since the Mathathon investigating the math of this phenomena. At first I sought an analytic formula for the helix based on the properties of the short chain periodically stacked; I now have a numerical, but not closed-form analytic, solution (thanks to Mathematica)! One of the exciting things about math, of course, is that I may be wrong — maybe I am in error, or maybe Euler solved this 250 years ago or something. Or, just maybe, the Mathathon identified a truly new publishable observation. The playground allowed and allows striking visual rendering of short snippets. We in fact created a menagerie of complex shapes from simple codes. I hacked the playground to render 100 chains at a time, to test different parameterizations of generators. It was a playful time. But there were many stated problems to solve, of varying gravity and difficulty. I advanced the 3D playground by taking David’s basic 2D work and extending it to 3D, which, a day after the formal close of the Mathathon, allowed me to build a tight “cone”, an object I had not expected. (The 3D playground is not exactly user-friendly at present; contact me for assistance if you wish to use it.) Meanwhile, Nathan, Sanchi, and Goz had sought objects from the pre-Mathathon set of problems, and Nathan found patterns for constructing several of import. These included an “almost flat” sawtooth, a strikingly tight (though slightly self-intersecting) squarish “vase” container, and above all, a torus. Here is the snippet of JavaScript Sanchi used to create the spiral below: (n) => { if (n > 94) return “S”; var k = n + 1; var h = Math.floor(Math.sqrt(k/3)); var j = k — h * h * 3; if (j == 0) return “R”; else if (j == 1) return “L”; return (j % (2 * h + 1) % 2 == 0) ? “L” : “R”; } I had specifically asked several questions about toruses, such as what was the smallest possible By mere chance, I have found a regular torus which was “almost” perfect, in that it almost came around to meet itself nicely in a ring. Nathan, by some intuition I will never understand, observed that allowing one length in every other tetrahedron to alternate, allowed the torus to be perfectly round, and to meet itself perfectly, forming a hexagonal central hole. Using a length of 1 for the regular edge length as a convenience, the length of the 6th edge (of the 6 forming two new tetrahedra) of the torus was 0.95, or 19/20ths. I erroneously jumped to the conclusion that we had found a simple rational length with completed the torus, which would have been very surprising. Although astoundingly close to 19/20th, it is if fact probably irrational, and Nathan proved this later. It turns out that Nathan had in fact identified a means of making toruses of any diameter, with a hole of a triangle, a square, a pentagon, etc. In a sense, these are “new” shapes, which may never have been constructed or identified before. Combined with the ability to parametrically generate chains, we, the participants of the Mathathon, had, in fact answered many of the originally posed questions. As always in mathematics, coming up with interesting questions is of equal importance to answering them, and I added many new questions to our evolving technical paper on the basis of what we learned. I personally continue to work in the light on the mathematics of the helix created by stacks of similar objects. In the end, the Mathathon was a resounding success in what was accomplished, and a great disappointment in the number of people who participated. We sought to give a positive cooperative learning and working experience on real math problems to as many students as possible. In fact, we did, I think — to two. I am loosely starting to think about holding a continuation of this event, with the problems reorganized around what was learned and the new issued discovered, in the early summer. Thanks to all who helped promote this event, especially David Jeschke, Twitter users @MathGarden (Sunil Singh) and @Jamesgrime (Dr. James Grime) and Stephanie Liu. read original article here
https://coinerblog.com/the-story-of-a-public-cooperative-mathathon-29ea5f4ff538/
CC-MAIN-2019-26
refinedweb
1,337
59.84
I want to write a function that determines if a sublist exists in a larger list. list1 = [1,0,1,1,1,0,0] list2 = [1,0,1,0,1,0,1] #Should return true sublistExists(list1, [1,1,1]) #Should return false sublistExists(list2, [1,1,1]) If you are sure that your inputs will only contain the single digits 0 and 1 then you can convert to strings: def sublistExists(list1, list2): return ''.join(map(str, list2)) in ''.join(map(str, list1)) This creates two strings so it is not the most efficient solution but since it takes advantage of the optimized string searching algorithm in Python it's probably good enough for most purposes. If efficiency is very important you can look at the Boyer-Moore string searching algorithm, adapted to work on lists. A naive search has O(n*m) worst case but can be suitable if you cannot use the converting to string trick and you don't need to worry about performance.
https://codedump.io/share/FUv1RnwnrYVq/1/check-for-presence-of-a-sublist-in-python
CC-MAIN-2016-50
refinedweb
168
56.29
do/while loop with output error message problem[code]cin.ignore()[/code] used with no arguments becomes [code]cin.ignore(1, EOF)[/code], as it has ... basic exception handlingThank you. I guess I was taking exception-being-thrown for granted. do/while loop with output error message problemGreat. Yes, the return 0 is there just to finish the main function, which off course doesn't make a... do/while loop with output error message problemtry this: [code] #include <iostream> #include <cmath> #include <complex> #include <iomanip> using na... basic exception handlingI'm trying to understand exception handling, and I'm testing this simple code: [code] #include <...
http://www.cplusplus.com/user/Marcos_Modenesi/
CC-MAIN-2016-30
refinedweb
105
61.43
Agenda See also: IRC log <Stuart> :-) <DanC> SKW: one recent change to agenda; any other mods? <DanC> minutes 6 Sep <DanC> RESOLVED to approve minutes 6 Sep (2007/09/06 18:55:56) <DanC> PROPOSED: to meet again 27 Sep, Rhys to scribe <ht> Regrets for 2007-09-27 <DanC> RESOLVED: to meet 27 Sep (scribe to be confirmed) <DanC> Revision: 1.14 $ of $Date: 2007/09/11 09:54:43 <DanC> SKW: Monday part of the meeting will stop at 5pm sharp if we're to take up the offer regarding a social event <DanC> HT notes weather merits warm clothing <DanC> SKW: monday morning scribe? <DanC> HT: OK, I'll scribe Monday 17 Sep AM <DanC> Rhys: regrets 27 Sep [?] <ht> For wind and weather forecasts, I recommend <ht> There are weather stations for both Southampton and St. Catherine's Point <DanC> . ACTION-33 Henry: revise URNsAndRegistries-50 finding in response to F2F discussion <DanC> HT: my work on that got preempted; sorry. <DanC> HT: yes, I saw Chime's comments. <DanC> HT: the was news to me; thanks <Noah_Bangalore> I'm afraid I really need to go. FYI, I made some limited progress on the plane on the way over in reading both the terminology and strategies parts of Dave's versioning drafts. Whether I'll be able to wrap them in an email before the F2F is not clear, but I'll certainly try. <Noah_Bangalore> See you Monday. <Stuart> Thanks noah... <Noah_Bangalore> Actually I'm interested in this one, I'll stay a bit. <DanC> DC: our position on contentTypeOverride-24 is: if it says text/plain, it's text/plain <ht> ScribeNick: HT NM: By "ask for an image" do you mena in the accept header? DC: No, rather where the GET comes from, i.e. the markup around the link ... I can't remember whether the HTML 5 spec says anything about accept header ... I then thought about the overlap with HTTP ... and drafted an internet draft containing the sniffing rules ... which was enough to get Roy Fielding to join the HTML WG ... and some substantive discussion is now happening ... Ian Hickson says that having spent two years trying to do the right thing, and losing ... He believes that any browser that doesn't sniff will lose market share ... Fielding disagrees ... Hickson has in the past suggested the TAG would have more credibility if they reopened the finding and added orange cones, that is, "in practice" exceptions <Zakim> Noah_Bangalore, you wanted to noodle a bit on accept headers vs. <img> tags SW: I've always understood that the mime type as delivered is a statement of server intent, and that doesn't _entirely_ determine what client use must be NM: What would a new story be, if the HTML WG gets their (currently specced) way? If they add an accept header, that makes some sense but if _not_, I'm really worried -- it means you're interpreting the outcome of a protocol on the basis of something _outside_ the protocol SW: Should we actually open this up? <Noah_Bangalore> I'll try to clarify a bit what Henry scribed (you can fold this in when editing minutes of you like). <timbl_> I wouldlike to push back on the HTML WG TVR: I'm not sure this is a good idea, on the grounds that we've already opened up the HTML issue, and we don't yet know what the result will be <Zakim> DanC, you wanted to concur with TVR about the risk here <Noah_Bangalore> What I was trying to say was: it was asserted that the semantics HTML 5 wants is something like "if the link was from an <img> tag, then make different assumptions about whether the returned representation is an image, regardless of Content-Type". TVR: Until we know that the HTML WG will succeed, I'm concerned about putting even more of WebArch at risk <Noah_Bangalore> What bothers me about that is that not only is that different from HTTP as specified today, you can't even specify it in terms of information that's visible at the HTTP level. <timbl_> Who at microsoft is the person who has to make that decision? <Rhys> I agree with Raman DC: This is an issue which makes me worry about the viabililty of the HTML WG -- Ian Hickson's position is that we can't do anything that the major browsers won't come on board with. Roy Fielding's view is that that means abdicating responsiblity, and just standardise other folks bugs DO: I agree that this is not in the whole community's interest ... We had a less than completely successful attempt to do better in the Web Services area, I don't think we should roll over here as well TBL: It's true that if we can't get the big vendors to change their minds, we're in a mess. I think the right answer is for the TAG to convince them to try to make their browser help users do better ... I'm prepared to put some efforts into make this happen ... For example, browsers should warn users when show cleaned-up source on Show Source or when they have to sniff ... Important to get this right _now_ -- this morning we were talking about video, and for a number of practical reasons, content negotiation between the two major approaches is going to be _very_ important ... and this is going to happen again and again, so we _should_ take up the challenge and try to persuade Firefox and IE and so on <Zakim> DanC, you wanted to report a bit of hope for a mozilla build with an option to make bogus mime types visible to the user, and meanwhile, a fairly serious proposal to reduce the <DanC> TVR: Sniffing is a slippery slope to disaster DC: HTTP WG is thinking about restarting at IETF ... fixing bugs, issues list, no WG yet but close ... Larry Masinter has filed an issue to deprecate content negotiation ... Julian Reshke said he'd like a configuration option which said "show me the true mime type" ... That seemed like a hopeful sign <timbl_> ... application/xml;dammit DC: There has also been discussion [where?] of replacing or down-grading or ??? the Content-Type: header, e.g. application/xmlDamnIt <timbl_> I don't see at all how that will solve the problem that ISPs don't allow folks to control the MIME heders SW: So reopening means strengthening our arguments, or considering changing our position? <Noah_Bangalore> +1 to reopen DC: Could go either way <Noah_Bangalore> or at least a strong concur <DanC> DC, Tim, Dorchard, Noah... SW: In favour of reopening: 4 <Rhys> Rhys doesn't have a strong view SW: Abstain: HST, SW, RL ... Opposed: TVR <timbl_> +1 TBL: Do we have to reopen the issue to discuss it? TVR: I'd like to discuss it, but not change it <Zakim> ht, you wanted to say enforcement <DanC> (if we just want to re-assert our position, I don't think we need to re-open it.) <Noah_Bangalore> I'm discouraged. For years we've asked ourselves whether the time is right to tell the story of the new parts of the web, like SemWeb, in an AWWW vol 2. Now it feels like we're deciding how much of V1 to withdraw. Sigh. HT: I think it's always in order to discuss how to best promote TAG findings DC: Not opening it says we're not listening <Noah_Bangalore> Not that I'm against openning the issue, just discouraged that we need to. TVR: Opening it says we were wrong <Noah_Bangalore> I also don't think that openning an issue signals a change. It signals a careful recheck, I think. DO: I guess opening it is sensible because it gives us a clean way to discuss, have actions, etc. ... There's a precedent in what we did with xxx-7 <Noah_Bangalore> I do have to go now. See you in Southampton. Good night! DO: So if we reopen and say "We're doing this because there's new information, and we want to track that and interact appropriately" <DanC> +1 re-open (I think the economics of the issue merits re-opening it) SW: Asking again -- should the TAG reopen the issue TVR: What does opening it mean? HST: That it stays open until we close it or abandon it <timbl_> TBL: yes SW: In favour: DC, DO, TBL Abstain: HST, TVR, RL DO: If we're not going to open this, we shouldn't talk about it HST: What about opening a new issue on "How do we deal with the fact that the HTML WG is heading down a road that is incompatible with our finding on respectMediaType-??? TVR: I like that DC: I could live with it, but I think it's odd DO: Same here -- it seems like a heavy burden on our process SW: Proposal to reopen fails -- only three in favour <DanC> ScribeNick: DanC <ht> HST observes that there _was_ a majority in favour of talking about this matter. . . SKW: proposal to re-open issue 24 didn't carry; other proposals are welcome. enough for today... <timbl_> ________________________________________________________ DO: [something] was accepted... 45 min... ... panel... with Q&A... <= 5 ppl... maybe 4... <Stuart> ok it's written as: The Importance URI based Extensibility DO: on the panel should be advocates of short strings as used in microformats, somebody from HTML 5, etc. <Stuart> but the that seems to be different words for what has also been called distributed extensibility DO: not sure if my role is just recruiting panelists, or MC, or participant, or what... <Rhys> I think it's fine for the MC also to be a participant in the panel. TVR: goal of the panel? q_ TVR: goal of the panel? this is clearly a long-running discussion. DO: re-inforce our message in support of decentralized language evolution DanC: goal is at least getting more of the community up to speed, if not achieving a whole lot of novel technical progress on the panel itself TVR: ok, outreach makes sense SKW makes suggestion to mitigate the risk that presentations would use all the time ((diversion back to ftf logistics; SKW notes Monday PM 5pm stop time)) ((yes, pick up XMLversioning at 3:30pm Monday)) ((same time window on Tues harder to predict, but agenda calls for Tag Soup)) <ht> ScribeNick: ht DC: I'm still interested in the thread on forward/backward compatibility definitions <DanC> ACTION-4 on Dan Connolly to Review definitions of partial understanding, backward compatible, and forward compatible [DONE] DC: Mark DeGraaw [sp?] has recently raised a real use case here, coming from HL7 DO: I've tried to add definitions, based on information, but that did not find favor <DanC> DanC: my review (Fri, 24 Aug 2007 16:57:37 -0500) said "I don't find this appealing; looks like an open research problem". DO said "let's not formalize it that deeply" which seems ok, perhaps, to me and Noah... as long as it doesn't come up in the practical examples in the scenarios part DO: Since I can't take it any further, I suggested dropping it ... I'm also interested in Mark DeGraaw's work, since there's a clear indication there of the value that success here would provide <DanC> DanC: Marc de Graauw is working on a formalism; I found it somewhat interesting as an academic exercise, but much moreso now that he's pointed out that it's grounded in a real-world scenario: HL7 SW: HST, any input? HST: I know of no solutions from the Computational Linguistics side <DanC> ACTION-27 on Dan Connolly to ask Mimasa and Mark Birbeck about feasability of using substitution groups in XHTML modularization, cc public-xml-versioning [DONE] DC: I asked, I didn't get a satisfactory answer ... Subst Groups are designed for distributed extensibility <scribe> scribenick: danc HT: I'm up to speed here... I read the modularization [of XHTML] spec... (which see ACTION-15 ) <ht> HT: indeed, substitution groups are a great mechanism for distributed extensibility; I explain how... ... a couple problems, 1 minor and 1 major... ... putting things in multiple substitution groups isn't allowed in XSD-the-REC; it is in XSD-work-in-progress... <timbl_> "clean subsetting"? HT: but they [XHTML] have another goal, that substitution groups don't do: "clean subsetting" ... substitution groups are bottom-up, which is why they're great for decentralized extensiblitiy... ... but XHTML modularization is also top-down; I dunno how to do that with substitution groups ... I hope somebody finds a work-around DC: this "clean subsetting" ... not sure I understand the motivation... HT: you need it to build XHTML 1.1 out of modules [DanC isn't able to grok that right away] DO: this is an interesting point on the design of XSD 1.1 ... seems like XHTML is an important use case for XSD [my understanding is that XHTML is _not_ widely regarded as an important use case for XSD] (ACTION-15 is done to my satisfaction. ACTION-15 on Henry S. Thompson to Review XHTML Modularization ) HT: I'd be more interested in addressing that requirement in XSD 1.1 if I could see a clear design. DC: DO, seen my msg about SMIL? Subject: lots of SMIL namespaces, revisited [XMLVersioning-41 / ISSUE-41] Date: Fri, 31 Aug 2007 12:52:24 -0500 DO: yes; saw that; been working on something related... ACTION-34 on Stuart Williams to Look at the difference between QNAME in XML and SPARQL [DONE] SKW: SPARQL uses "abbrevited names" which are similar to QNames, but not quite the same. [summarizing ] DanC: recent RDFa designs seem to not use CURIEs in the href attribute, but only in new attributes some investigation into current status of curie, RDFa drafts, inconclusive... <ht> scribenick: ht <DanC> Issue contentTypeOverride-24 (ISSUE-24) DC: TBL asked the question: Who makes decisions about this sort of thing for the vendors? ... We're planning a f2f of the HTML WG for the Tech Plenary week ... and we are hoping that there will be real technical representation from all the vendors <timbl_> "sensitive mode" TBL: I don't know what a non-obtrusive way to improve the media-type problem <Rhys> 'view problems' in the same sense as 'view source'? <timbl_> TBL: I think showing only a clean XML version of veiw sourcfe for copy/paste is non-destrictive DC: The best suggestion I've seen was to allow the "This is my content, show me problems rather than fixing me silently" <timbl_> Firefox > Tools > Error Console DC: Roy Fielding is taking the HTML WG discussion seriously, but I don't know how far Ian Hickson has yet succeeded in changing his mind ... Who knows how to make a private build of Firefox? None of the people who do on the WG have stepped up so far. . . DCandTVR: Boris Zbarsky seems like the best bet. . . <timbl_> web.mit.edu/bzbarsky/www/ This is scribe.perl Revision: 1.128 of Date: 2007/02/23 21:38:13 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/HST, SW/HST, SW, RL/ Succeeded: s/[missed first example]/show cleaned-up source on Show Source/ Found ScribeNick: HT Found ScribeNick: DanC Found ScribeNick: ht Found ScribeNick: danc Found ScribeNick: ht Inferring Scribes: HT, DanC Scribes: HT, DanC ScribeNicks: HT, DanC WARNING: No "Present: ... " found! Possibly Present: DC DCandTVR DO DanC Dave_Orchard HST Ht LMM NM Noah_Bangalore P0 P2 PROPOSED Raman Rhys SKW SW Stuart Subject TBL TVR TimBL WG-to-be application conneg dammit deprecating dorchard has hint introduce mime note scribenick suggested that timbl_ to trackbot-ng type xml: Date not understood: Fri, 31 Aug 2007 12:52:24 -0500 Got date from IRC log name: 13 Sep 2007 Guessing minutes URL: People with action items:[End of scribe.perl diagnostic output]
http://www.w3.org/2007/09/13-tagmem-minutes.html
CC-MAIN-2015-35
refinedweb
2,672
65.76
Opened 3 years ago Closed 2 years ago Last modified 2 years ago #21239 closed Bug (fixed) Closing connection inside atomic block breaks atomicity Description Closing the connection inside an atomic block rolls back queries up to that point, but doesn't prevent subsequent queries from reconnecting and getting committed. An exception should be raised in this situation in one of three places: - connection.close() - or on the next reconnection attempt - or on the next query execution attempt Testcase (currently failing): def test_connection_closed_inside_atomic (self): with self.assertRaises(transaction.TransactionManagementError): with transaction.atomic(): Reporter.objects.create(first_name="Tom") connection.close() Reporter.objects.create(first_name="Jerry") # here Jerry exists but Tom doesn't Change History (10) comment:1 Changed aaugustin comment:3 Changed 3 years ago by akaariai Can you skip the test on sqlite? It seems good enough that CI will catch errors here. comment:4 Changed 3 years ago by aaugustin In the current code, I have included a comment that explains that I have chosen to allow calling close() within an atomic block to make it easy to dispose of a database connection regardless of its state. At some point Django needs a method that kills the database connection regardless of its state. Even if this method isn't called close(), as soon as it's documented, it'll have this problem. I see two ways to deal with this: 1) Document not to call close() within an atomic block. In practice, what's the use case for doing that? 2) Close the connection then raise an exception; however, this is going to create additional problems, because atomic will attempt to rollback to savepoints that don't exist anymore. Currently I'm leaning towards option 1. However, there's another ticket about what happens when the server closes the connection during a transaction, and it may require changes that will make it easy to support option 2. comment:5 Changed 3 years ago by akaariai Possible option 3) - if a connection is closed inside atomic() block, prevent queries until atomic block is exited. So, something like: with atomic(): with atomic(): Model.objects.get(...) connection.close() Model.objects.get(...) # Raises exception about invalid transaction state Model.objects.get(...) # Still raises exception about invalid transaction state I am *not* saying this is the way forward. This likely requires some complex code, and that doesn't seem worth it. If this happens to be easy (which would be a surprise), then it seems like a good candidate to consider. comment:6 Changed 3 years ago by aaugustin - Severity changed from Release blocker to Normal Interesting idea. I'd really like to couple this fix with the "connection dropped" fix. Regardless of which side drops the connection Django's should most likely behave identically. As agreed on IRC, we'll downgrade this to "normal" severity. I'll temporarily add a warning in the docs. comment:7 Changed 2 years ago by aaugustin - Has patch set comment:8 Changed 2 years ago by Aymeric Augustin <aymeric.augustin@…> - Resolution set to fixed - Status changed from assigned to closed I can't include a test to validate this behavior, because the test suite needs a constantly open connection when running with an in-memory SQLite database.
https://code.djangoproject.com/ticket/21239
CC-MAIN-2016-22
refinedweb
540
52.9
sysctl — read/write system parameters Synopsis #include <unistd.h> #include <linux/sysctl.h> int _sysctl(struct __sysctl_args *args); Note: There is no glibc wrapper for this system call; see Notes. Description Do not use this system call! See Notes. The _sysctl() call reads and/or writes kernel parameters. For example, the hostname, or the maximum number of open files. The argument has the form struct __sysctl_args { int *name; /* integer vector describing variable */ int nlen; /* length of this vector */ void *oldval; /* 0 or address where to store old value */ size_t *oldlenp; /* available room for old value, overwritten by actual size of old value */ void *newval; /* 0 or address of new value */ size_t newlen; /* size of new value */ }; This call does a search in a tree structure, possibly resembling a directory tree under /proc/sys, and if the requested item is found calls some appropriate routine to read or modify the value. Return Value Upon successful completion, _sysctl() returns 0. Otherwise, a value of -1 is returned and errno is set to indicate the error. Errors - EACCES,. - ENOTDIR name was not found. Conforming to This call is Linux-specific, and should not be used in programs intended to be portable. A sysctl() call has been present in Linux since version 1.3.57. It originated in 4.4BSD. Only Linux has the /proc/sys mirror, and the object naming schemes differ between Linux and 4.4BSD, but the declaration of the sysctl() function is the same in both. Notes Glibc does not provide a wrapper for this system call; call it using syscall(2). Or rather... don't call it: use of this system call has long been discouraged, and it is so unloved that it is likely to disappear in a future kernel version. Since Linux 2.6.24, uses of this system call result in warnings in the kernel log. Remove it from your programs now; use the /proc/sys interface instead. This system call is available only if the kernel was configured with the CONFIG_SYSCTL_SYSCALL option. Bugs The object names vary between kernel versions, making this system call worthless for applications. Not all available objects are properly documented. It is not yet possible to change operating system by writing to /proc/sys/kernel/ostype. Example #define _GNU_SOURCE #include <unistd.h> #include <sys/syscall.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <linux/sysctl.h> int _sysctl(struct __sysctl_args *args ); #define OSNAMESZ 100 int main(void) { struct __sysctl_args args; char osname[OSNAMESZ]; size_t osnamelth; int name[] = { CTL_KERN, KERN_OSTYPE }; memset(&args, 0, sizeof(struct __sysctl_args)); args.name = name; args.nlen = sizeof(name)/sizeof(name[0]); args.oldval = osname; args.oldlenp = &osnamelth; osnamelth = sizeof(osname); if (syscall(SYS__sysctl, &args) == -1) { perror("_sysctl"); exit(EXIT_FAILURE); } printf("This machine is running %*s\n", osnamelth, osname); exit(EXIT_SUCCESS); } See Also proc(5) Colophon This page is part of release 5.04 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Referenced By proc(5), sctp(7), syscalls(2). The man page _sysctl(2) is an alias of sysctl(2).
https://dashdash.io/2/sysctl
CC-MAIN-2022-27
refinedweb
524
67.76
In the first select you must have column with alias A Select col1 as a [...] from [a] inner join [b] on a.[] = b.[] where [] Union All Select [] from [a] inner join [b] on a.[] = b.[] where [] Union All Select [] from [a] inner join [b] on a.[] = b.[] where [] Union All Select [] from [a] inner join [b] on a.[] = b.[] where [] order by a This should do the trick: temp_array = @products.group_by(&:name) @filtered_products = temp_array.map do |name, products| products.sort{ |p1, p2| p2.revision <=> p1.revision }.first end Don't hesitate to ask details if you need ;) In normal queries, sort is processed first, then skip, and then limit, no matter in which order you add them to your cursor object. The aggregation framework will execute the $sort, $skip and limit operators in their order of appearance in the pipeline. There's no direct way to use $near or $nearSphere and sort by another field, because both of these operators already sort the results of doing a find(). When you sort again by 'date', you're re-sorting the results. What you can do, however, is grab results from the $nearSphere incrementally, and sort each set of results. For example: function sortByDate(a, b) { return a.date - b.date; } // how many results to grab at a time var itersize = 10; // this will hold your final, two-way sorted results var sorted_results = new Array(); for (var i=0, last=db.coll.count(); i<last-itersize; i+=itersize) { var results = db.coll.find( {"date":{$gte:date}, // longitude, then latitude "location":[lng, lat]} ).skip(i).limit(itersiz There is a sort and slice operator that can be used in conjunction when you push the messages into the document arrays: They keep your array sorted and limited respectively. I don't think it's possible with one query. But you can get all B you want with aggregate and then query database for that B: db.test1.aggregate( [ {$group: {_id: "$B", count: {$sum:1}}}, {$match: {count:1}} ] ) will return you all B for which there only one record in your collection. I don't think that the Aggregation framework is the right choice here. I would just do a straight 'find'. There is a Find class and nested Find.Builder class for constructing the more complex queries. import static com.allanbank.mongodb.builder.QueryBuilder.where; import com.allanbank.mongodb.MongoClient; import com.allanbank.mongodb.MongoCollection; import com.allanbank.mongodb.MongoFactory; import com.allanbank.mongodb.MongoIterator; import com.allanbank.mongodb.bson.Document; import com.allanbank.mongodb.builder.Find; import com.allanbank.mongodb.builder.Sort; public class StackOverFlow { // SELECT * FROM collect // WHERE time >= input1 AND userId = input2 // ORDER BY time DESC // LIMIT 30 public static void query(long input1, String input2) { MongoCl example (prints 0 if found, otherwise 1): set /a path_check=0 echo %PATH% | findstr /i "C:\Windows\System32;" 2>NUL || set /a path_check=1 echo %path_check% To be honest, I'm not entirely sure why this is happening - it's a Sphinx issue though, not Thinking Sphinx (so I've added the Sphinx tag). A work-around is to wrap both search options in double-quotes: fields << %q{(@description "#{params[:oiloiliness]}" | "#{params[:oiloiliness].gsub(/[^0-9A-Za-z]/, '')}" )} Also: you may want to consider adding hyphen to your list of ignore_chars via config/thinking_sphinx.yml. If Hazard is blank or 'Y' then you can use MAX() and GROUP BY to get your desired output: SELECT SHPMNT_NO, TOT_WEIGHT, MAX(HAZARD) 'HAZARD' FROM YourTable GROUP BY SHPMNT_NO, TOT_WEIGHT This will also work if Hazard is 'Y' or 'N'. You would need to add a continuation to all of the tasks, 1-4, with the error handling case to allow an error in any of them to call that function. For convenience you could create a method to add the same continuation to a collection of tasks. Here's one (feel free to add others for the other overloads of ContinueWith as needed): public static IEnumerable<Task> ContinueWith(this IEnumerable<Task> tasks , Action<Task> continuation, TaskContinuationOptions options) { return tasks.Select(task => task.ContinueWith(continuation, options)) .ToList();//important for this ToList to be here; //we want the continuations to be added now, not when the result is iterated } This allows you to write: var errorTasks = new[]{task, task2, task3, task4} .C You can create a method, and place it in CellColorChanger class: private boolean checkCondition(){ return /* whatever condition like: */ (row == 2 && column == 2) || (row == 6 && column == 1) || (row == 1 && column == 2) || (row == 4 && column == 1); } Call this function on passed CellColorChanger object, whenever you want the condition to be re-evaluated. << 'conditions' => 'id < '.$upline['User']['group_id'] should be 'conditions' => array( 'id < '.$upline['User']['group_id'] ) Also 'conditions' => 'id > '.$upline['User']['tgame_master_id'] should be 'conditions' => array( 'id > '.$upline['User']['tgame_master_id'] ) May this help you: Replace your query with these lines.. public Cursor query(int id){ return myDataBase.query("question", null,"_id = "+id+ " AND " + "chek ="+number,null, null, null, null); keep space between the double quotes in And :" And " otherwise the string will be Example: _id=3And check =9 Should be pretty straightforward : from table left outer join.... where (Condition A IS NULL) OR (condition A AND condition B) UPDATED: For your conditions: where (a.column is null) or (a.column='123' and c.column='456') It will include a a row if it's a.column is null or if bot a.column and c.column have valid values.(); }); If your result.sum_adt_out attribute is a string, your test will fail. Also note that <> has been deprecated in Python, use != instead to test inequality. Your template, simplified and with calling float() on the value first to ensure that it is numeric, then becomes: <td style="text-align: right;" tal:define="sum_adt_out python:float(result.sum_adt_out)"> <span tal:condition="sum_adt_out" tal:content="python:'%.1f' % (float(result.sum_cenmn)/sum_adt_out,)">currentindex</span> <span tal:0.0</span> </td> bool isRightType = true; if(isRightType == false) { const string msg = "Für diesen Control-Typ wird die falsche Basisklasse verwendet!"; throw new Exception(msg); } You're hardcoding isRightType to true, then immediately testing for false. There's no execution path for the if statement to be true and execute. A regex is not a good tool to use for this. You can do all you need by splitting and parsing the string: (see it run) class Main { public static void main (String[] args) throws java.lang.Exception { String inputString = "1,4,6,22,88,105:22"; int min = 1; int max = 105; String[] splitString = inputString.split("[,:]"); for (String part : splitString) { int parsedInt = Integer.parseInt(part); if (parsedInt < min || parsedInt > max) throw new Exception("Invalid"); } System.out.println("Yay it's ok!"); } } I don't think it is possible. I do think you are mistaken when you say that you would be testing implementation, instead of intent in your example. When you write a test, you test whether what comes out matches your expectation. Creating a user is something completely different than returning error messages. In my opinion it would be strange to say: when I do this, I expect this, or that, or that, or that to happen. In my opinion you should write one test, that tests whether a user is created when you send the correct parameters, and another test that deals with what happens when a user tries to send illegal parameters.') All credit to Jerry, for his answer: ^(?:(?![AEIOU])[A-Z]{2}|[A-Z]{3,10})$ Explanation: ^ = "start of string", and $ = "end of string". This is useful for preventing false matches (e.g. a 10-character match from an 11 character input, or "MR" matching in "AMRXYZ"). (?![AEIOU]) is a negative look-ahead for the characters A,E,I,O and U - i.e. the regex will not match if the text contains a vowel. This is only applied to the first half of the conditional "OR" (|) regex, so vowels are still allowed in longer matches. The rest is fairly obvious, based on what you've already demonstrated an understanding about regex in your question above. One explanation is that you have some partner ids where the substring starts with a 0. In the first case, the query is doing an integer comparison. A string like '0a' evaluates to "0" as an integer. This is equal to 0, so they are filtered out. In the second case, the query is doing a string comparison. A string like '0a' is different from '', so these pass the filtering clause. The union should do just fine, for example for your first example (this will work only if tables a, b and c have similar column order and types): select a.* from a left join b on a.id=b.id where b.id=:MY_PARAMETER UNION select c.* from c where c.id=:Another_Parameter and not exists(select a.* from a left join b on a.id=b.id where b.id=:MY_PARAMETER) UNION select b.* from b where not exists (select c.* from c where c.id=:Another_Parameter and not exists(select a.* from a left join b on a.id=b.id where b.id=:MY_PARAMETER)) and not exists (select a.* from a left join b on a.id=b.id where b.id=:MY_PARAMETER) In order to build more effective query, I need more specific example. SELECT a.* FROM a INNER JOIN b ON a.id = b.id WHERE b.id = :MY_PARAMETER UNION SELECT a.* FROM a INNER JOIN b ON I wouldn't use user_tags.user_id as part of the join condition. Just do specify both conditions in the where clause to make your intent clearer. But to answer your question, yes you would need to de-dupe tags with DISTINCT if one tags.id can be associated to many user_tags.tag_id SELECT DISTINCT tags.* FROM tags JOIN user_tags ON tags.id = user_tags.tag_id WHERE user_tags.user_id = 2 OR user_tags.owner_id = 2 LIMIT 0,30
http://www.w3hello.com/questions/Sorting-with-condition-in-mongodb
CC-MAIN-2018-17
refinedweb
1,642
68.16
Content: Nowadays most modern business application development projects use object technology such as C# or Java to build application software and relational databases to store the data. But it is not true that we don't have the other options; there are many applications built with procedural languages such as COBOL and many systems will use object databases or XML databases to store data. So here comes object relational (O/R) Mapping, but for that we need to understand two things: the process of mapping objects to relational databases and how to implement those mappings. In this article the term "mapping" for entity framework in ASP.Net MVC3 will be used to refer to how objects and their relationships are mapped to the tables and relationships between them in a database i.e. SQL Server 2005 and SQL Server 2008. Now suppose in your ASP.Net MVC3 application you have 2 Model classes: Route Class Drop Point Class The Route class is for trips of a particular distance. For e.g. Mumbai to Delhi is a Route Class. The DropPoint Class means in that particular (Mumbai Delhi train route) which are the stations. Now each route has a specified number of drop points. So we have a one-to-many relationship with the Route class and the Drop Point class. Now here is the Route class definition with Properties: public class Route { public int RouteId { get; set; } [Required(ErrorMessage = "RouteName is required")] public string RouteName { get; set; } [Required(ErrorMessage = "RouteNumber is required")] [StringLength(15, ErrorMessage = "RouteNumber Name Not exceed more than 15 words")] public string RouteNumber { get; set; } #region 1->m Relation between Route and DropPoint public virtual List<DropPoint> DropPoint_List { get; set; } #endregion } Now here is the Drop Pont class definition with Properties: public class DropPoint [ScaffoldColumn(false)] public int DropPointId { get; set; } [Required(ErrorMessage = "DropPointName is required")] public string DropPointName { get; set; } public string NewDropPointName { get; set; } #region m->1Relation between Route [DisplayName("Route")] public virtual Route Route { get; set; } #endregion Now here the Million dollar question is: in these two classes, how can we make the relationship. Now in the Route Class you will see we have a list of DropPoint classes. Because for each Route we have multiple DropPoints (1->m relationship). Similarly in the Route class we see that we have a property "public int RouteId { get; set; }". (This actually acts as a foreign key of the Route class). And we also have a Property of the Class "Route": public virtual Route Route { get; set; } See here we have to give that virtual keyword before the class "route". The reason why we write the property of the class "Route" in here is because class "DropPoint" also has the many to one relationship with Class route. So now we have a relation between two classes. So when we plug these 2 classes with the entity framework there are two classes that will become the two tables with relationships in the database. Now here I have written the code by how you will make these classes with tables by using entity framework. For that you have to add a reference to "entityframework.dll". I have attached the DLL here. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using CabAutomationSystem.Models; namespace CabAutomationSystem.DatabaseContext { public class CabDbContext : DbContext public DbSet<Route> Route { get; set; } public DbSet<DropPoint> DropPoint { get; set; } } Here the "Dbset" is the database set. Conclusion: So in this article we have seen how to map the two classes with object class mapping concept and also with the help of the Entity Framework how to make the two relationship classes with tables. ©2016 C# Corner. All contents are copyright of their authors.
http://www.c-sharpcorner.com/uploadfile/b19d5a/object-class-mapping-in-Asp-Net-mvc3-using-entity-framework/
CC-MAIN-2016-30
refinedweb
624
62.17
pass scjp 5.0 86% Today i took SCJP 5.0 exam today and passed with 86%; I just want to say that God Bless You all for Your posts which were every helpful to me. I grateful also to javabeat.net, Marcus Green, Kathy and Bert and My friend Sir Max for their online resources. It took me 4 months to prepare with a lot of pressure from work. [ July 17, 2007: Message edited by: ikenna okpala ] SCJP 5.0, SCWCD 1.4, SCBCD 5.0, SCEA 5.0, OCP:AD "there is no traffic in the extra mile..." Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch Getting someone to think and try something out is much more useful than just telling them the answer. Java Platform, Enterprise Edition 6 Web Services Developer Certified Expert Exam Study Guide and Quiz Exam 1Z0-810: Upgrade to Java SE 8 Programmer Study Guide and Quiz public class Thanks{ public static void main(String [] ikenna){ StringBuilder st = new StringBuilder("Thanks a million"); for(int x = 0; x<1000000; x++){ System.out.println(st); } } } SCJP 5.0, SCWCD 1.4, SCBCD 5.0, SCEA 5.0, OCP:AD "there is no traffic in the extra mile..." Home of Java Skills SCJP 5.0, SCBCD, SCEA mock exams Ranch Hand Enthuware - Best Mock Exams and Questions for Oracle Java Certifications Quality Guaranteed - Pass or Full Refund! Sheriff i had already finished reading 1.4 but i decided to take 1.5 (Tiger). even i just recieved my kit on monday. well this is my prayer for you and the rest God bless you all and may your days be long and not grow short. SCJP 5.0, SCWCD 1.4, SCBCD 5.0, SCEA 5.0, OCP:AD "there is no traffic in the extra mile..."
https://coderanch.com/t/141314/certification/pass-scjp
CC-MAIN-2016-50
refinedweb
300
78.55
Process groups are a feature of Unix systems to group related processes under a common identifier, known as the PGID. Using the PGID, one can look for these related process and send signals in unison to them. This is typically used by shell interpreters to manage processes. For example, let’s launch a shell command that puts two sleep invocations in the background (those with the 10- and 20-second delays) and then sleeps the direct child (with a 5-second delay)—while also putting the whole invocation in the background so that we can inspect what’s going on: $ /bin/sh -c 'sleep 10 & sleep 20 & sleep 5' & [1] 799 $ ps -o pid,pgid,command PID PGID COMMAND 612 612 -zsh 799 799 /bin/sh -c sleep 10 & sleep 20 & sleep 5 800 799 sleep 10 801 799 sleep 20 802 799 sleep 5 803 803 ps -o pid,pgid,command In the output of ps, we can observe two interesting things: first, the PGID column has the value 799 for all processes that belong to that invocation; and second, there is one process with the same PID as PGID. That process is known as the process group leader and corresponds to the command we typed. As we covered in the previous post, Bazel’s process-wrapper helper tool uses process groups as a mechanism to terminate the process it directly spawns (e.g. a test program) and any other subprocesses that this first process might have spawned (e.g. helper tools run by the test program). In essence, the process wrapper does setgpid(getpid(), getpid()) immediately before the call to exec(3) to place its direct child in a new process group—just as the shell example above did—and then uses this handle to terminate the whole group at once with kill(-PGID, SIGKILL). But you must remember that kill(2) just posts the signal to the given process(es). There is no guarantee that the signal was delivered and handled once kill(2) returns. The signal is processed at a later time (or maybe not at all, if the signal can be and is ignored)—and if the process is blocked in the kernel, whatever thing it is doing may be allowed to complete before the signal takes effect. Which poses a problem: the Bazel process wrapper is supposed to abide by the contract that, once it terminates, the command given to it has also terminated. If the process wrapper did not wait for all of its descendent processes to fully terminate, we would violate that contract and we would experience very difficult-to-diagnose race conditions. All hypotheticals… right? Well, no, because the process wrapper does not actually wait for the process group to complete, so we have a bug (#10245). Stay calm though, because the bug is extremely hard to hit (we use SIGKILL, not SIGTERM), and it’s only a correctness issue if you are playing with my new --experimental_local_lockfree_output feature combined with dynamic execution. So… how do we actually wait for all processes in the same process group to terminate? Let’s start by looking at the documentation of waitpid(2). Quoting the macOS 10.15 manual page, we’ll see: The pidparameter specifies the set of child processes for which to wait. If pidis -1, the call waits for any child process. If pidis 0, the call waits for any child process in the process group of the caller. If pidis greater than zero, the call waits for the process with process id pid. If pidis less than -1, the call waits for any process whose process group id equals the absolute value of pid. (Emphasis mine.) That sounds promising! It sounds like, if we just do waitpid(-PGID, NULL, 0) repeatedly until we get ECHILD, we’ll wait for all subprocesses in the group after we have sent them the termination signal. Let’s try! Build this sample program, which is intended to spawn the command given as arguments: #include <sys/wait.h> #include <assert.h> #include <err.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> // Convenience macro to abort quickly if a syscall fails with -1. // // Not great error handling, but better have some than none given that you, the // reader, might be copy/pasting this into real production code. #define CHECK_OK(call) if (call == -1) err(EXIT_FAILURE, #call); int main(int argc, char** argv) { if (argc < 2) { errx(EXIT_FAILURE, "Must provide a program name and arguments"); } int fds[2]; CHECK_OK(pipe(fds)); pid_t pid; CHECK_OK((pid = fork())); if (pid == 0) { // Enter a new process group for all of our descendents. CHECK_OK(setpgid(getpid(), getpid())); // Tell the parent that we have successfully created the group. CHECK_OK(close(fds[0])); CHECK_OK(write(fds[1], "\0", sizeof(char))); CHECK_OK(close(fds[1])); // Execute the given program now that the environment is ready. execv(argv[1], argv + 1); err(EXIT_FAILURE, "execv"); } // Wait until the child has created its own process group. // // This is a must to prevent a race between the parent waiting for the // group and the group not existing yet, and is the only safe way to do so. CHECK_OK(close(fds[1])); char dummy; CHECK_OK(read(fds[0], &dummy, sizeof(char))); CHECK_OK(close(fds[0])); // Wait for the direct child to finish. We do this separately to collect // and propagate its exit status. int status; CHECK_OK(waitpid(pid, &status, 0)); // And now wait for any other process in the group to terminate, as the // documentation claims. while (waitpid(-pid, NULL, 0) != -1) { // Got a child. Wait for more. } assert(errno == ECHILD); return WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE; } and then run it against the same sample command we used in the previous post: $ ./wait-all /bin/sh -c '/bin/sh -c "sleep 5; echo 2" & echo 1' 1 $ 2 Uh oh… Notice that wait-all exits quickly and that the subprocess that prints 2 remains, printing this a few seconds later. Not good. What the documentation for waitpid(2) quoted above fails to mention—and I haven’t been able to find this documented anywhere—is that this call only waits for direct children processes with the given PGID. It will do nothing for grandchildren processes. And this makes sense if you think about how the wait(2) family of system calls work internally. What these calls do is block until the process receives a SIGCHLD. This signal is only sent from a child process to its parent when the child changes its status; there is no transitive forwarding of signals—hence why waitpid(2) cannot wait for grandchildren. So how do we fix this? Well… there is no good answer to this question as the solution varies across platforms. And, in fact, it may not be possible to implement at all (correctly) in some, though we can obtain a good approximation. We’ll dive into the possible alternatives for Linux and macOS in the next posts, which will help us fix the bug that currently exists in Bazel’s process wrapper. See the followup posts with Linux-specific and macOS-specific details.
https://jmmv.dev/2019/11/wait-for-process-group.html
CC-MAIN-2022-21
refinedweb
1,185
61.16
Unzip! Unsnap! AHHHH!! Our business object is naked. It is time to strip applications of complex UIs and give users direct access to the business objects. The concept is simple: write behaviorally complete business model objects and use generic views and controllers. Thus, if a business model object supports a public behavior, then the user has access to that behavior. So why do we need naked objects? Chances are you have struggled to truly understand the Model-View-Controller (MVC) pattern. Why is this? The concepts are easy, right? The Model contains the core business logic; the View is responsible for displaying a given model's data; the Controller controls the interactions between the model and the view, typically through event notification. Of course, anyone who has worked with Swing knows that the View and Controller are often combined in the same component. For example, a JTable has a model, but is also both the view and controller. Business logic can end up in all three layers, too, which violates the DRY principle (Don't Repeat Yourself). JTable We are going to build a simple address book using the Naked Objects framework. An address book works nicely because it fits into the naked objects philosophy and, of course, it is easy to understand. You may download the example application here. Our first requirement is that our address book may contain zero or more people. Here is the first iteration of our naked Person: package com.briancoyner.naked.addressbook; import org.nakedobjects.object.AbstractNakedObject; public class Person extends AbstractNakedObject { // You must implement this method, which comes from the base class, before // the class compiles. We'll talk more about this in a bit. public Title title() { return null; } } The Naked Objects framework requires that all naked objects implement the NakedObject interface. To keep things simple, we can extend from AbstractNakedObject. The AbstractNakedObject provides the base functionality that makes up a naked object, allowing us to focus on the business problem, which is creating a simple address book. Any object that is "naked" can be seen by the user. We will see how to expose objects to an application later in the article. Now that our Person is naked, we need to add a few attributes and provide a way to modify them. This is accomplished using strict naming conventions and specific Naked Objects framework classes. Let's add a few attributes: first name, last name, and birthdate. NakedObject AbstractNakedObject package com.briancoyner.naked.addressbook; import org.nakedobjects.object.AbstractNakedObject; import org.nakedobjects.object.value.Date; import org.nakedobjects.object.value.TextString; public class Person extends AbstractNakedObject { private final TextString firstName; private final TextString lastName; private final Date birthdate; public Person() { firstName = new TextString(); lastName = new TextString(); birthdate = new Date(); } public final TextString getFirstName() { return firstName; } public final TextString getLastName() { return lastName; } public final Date getBirthdate() { return birthdate; } public Title title() { return null; } } Our Person object now has a first name, last name, and birthdate. This is plenty for now. You should have noticed that we did not use a java.lang.String or StringBuffer. Instead, we used an org.nakedobjects.object.value.TextString. TextStrings are mutable objects used by the Naked Objects framework to manipulate string values and tell the framework to create a text field for the view (we will see this in a bit). Also, it is considered good form to mark attributes, whose reference never changes, as final. java.lang.String StringBuffer org.nakedobjects.object.value.TextString TextString Each mutable attribute requires that you provide a corresponding "getter" method. The framework locates all "getters" using reflection, and based on the return type, builds the correct UI component. The first and last names are simple text fields, and the birthdate is a text field with date-parsing behavior. Labels are generated automatically, too, by stripping the "get" from each "getter" method and putting a space between characters that differ in capitalization. You may have noticed that Person does not contain "setter" methods. The reason is simple: TextStrings are mutable, so there is no reason to change the instance. There are times when a "setter" is appropriate. For example, a person can only wear one pair of shoes at time. One day they may wear tennis shoes, the next day, sandals. A "setter", in this example, is needed to change a person's shoes. In addition to "getters" and "setters", there are numerous methods that the framework looks for, using reflection. We will examine a few key methods later in the article. Person Diagram 1. Our naked person We did not code anything GUI-specific. We simply created a business object, and the Naked Objects framework, using reflection, created the Person view. Remember that if our object supports it, the user gets it. Diagram 2 shows a quick view of some of the built-in Naked Object types. For details on these types beyond what is presented in the examples in this article, please consult the Naked Objects documentation. Diagram 2. Example types Now that we have seen how to create a simple naked object, let's turn our attention to unit testing. The Naked Objects framework provides a very slick way to unit test our objects. Here is the start of our test fixture: package com.briancoyner.naked.addressbook; import org.nakedobjects.object.NakedClass; import org.nakedobjects.testing.View; import org.nakedobjects.testing.NakedTestCase; import java.util.Calendar; public class TestPerson extends NakedTestCase { /** * Yes, you must supply a constructor. Hopefully the next version of the * Naked Objects framework will use JUnit 3.8.1. */ public TestPerson(String name) { super(name); } protected void setUp() throws Exception { // initialize an object store, otherwise a null pointer exception // is thrown when trying to create a new View instance. init(); registerClass(Person.class); } } This code should look very familiar if you have worked with JUnit. The only exception is a Naked Object's test fixture extends NakedTestCase. This is a base class that extends from junit.framework.TestCase, and provides several convenience methods to register objects and set up an object store. We will talk more about object stores later. Let's test getting and setting the Person's attributes. NakedTestCase junit.framework.TestCase public void testPersonAttributes() { Person person = new Person(); person.getFirstName().setValue("Brian"); person.getLastName().setValue("Coyner"); // Note that the Naked Object Date starts with 1 (1 = Jan, 12 = Dec). // This is different than java.util.Calendar. person.getBirthdate().setValue(1900, 9, 22); assertEquals("First Name.", "Brian", person.getFirstName().stringValue()); assertEquals("Last Name.", "Coyner", person.getLastName().stringValue()); Calendar calendar = Calendar.getInstance(); calendar.set(1900, Calendar.SEPTEMBER, 22, 0, 0, 0); calendar.set(Calendar.MILLISECOND, 0); assertEquals("Birthdate.", calendar.getTime(), person.getBirthdate().dateValue()); } Once again, if you are familiar with how to write tests, then this test should be fairly straightforward. There are a few things to mention, though, before we continue. First, remember that our person does not contain any "setters". The Naked Objects framework only requires "setters" if an instance of an object can be changed. TextString objects are mutable, so we simply retrieve the TextString and change the value. This is somewhat different than a lot of APIs we are used to. Here, we simply retrieve a reference to a TextString object that holds the first name, and change the value. person.getFirstName().setValue("Brian"); Let's remove the deep chaining to see what is going on. TextString firstName = person.getFirstName(); firstName.setValue("Brian"); Second, the Naked Object's Date uses slightly different values for representing months. The Naked Object's Date starts months at 1 (1=Jan., 12=Dec.). The java.util.Calendar starts months at 0 (0=Jan., 11=Dec.). Date java.util.Calendar One of the most impressive and powerful features of the Naked Objects framework is the use of Views. Views represent the "graphical" equivalent of an object, but without the object visible on the screen. This allows us to test our objects and their interactions without special scripting or complex GUI-testing frameworks. Here is how we can test our Person using Naked Object views. public void testPersonView() { String viewName = NakedClass.getNakedClass(Person.class).getPluralName(); View person = getClassView(viewName).newInstance(); person.fieldEntry("First Name", "Brian"); person.fieldEntry("Last Name", "Coyner"); person.fieldEntry("Birthdate", "1/12/1999"); person.assertFieldContains("First Name", "Brian"); person.assertFieldContains("Last Name", "Coyner"); // The Naked Object's Date object converts the date to this format person.assertFieldContains("Birthdate", "Jan 12, 1999"); } Testing views requires understanding how the framework locates objects (views) and their fields. The first few lines of this test retrieve the person view. All views are retrieved using the plural name. If you were to print out the plural name for our Person you would see "Persons". Obviously, we would like to have the plural name be "People". We will see how to do this at the end of the article. To specify field names, you must break apart the "getter" methods. For example, getFirstName() becomes "First Name". Simply remove "get" and put a space between characters that differ in capitalization. A View also provides various assert methods. Our test asserts that the given fields contain the correct values. getFirstName() View assert Remember that every naked object must implement a method that returns back a title. This method comes from the AbstractNakedObject base class and looks like this: public abstract Title title(); And here is how we might implement it: public Title title() { String title = ""; // stringValue() returns null if the value is not specified. if (!firstName.isEmpty()) { title += firstName.stringValue(); } if (!lastName.isEmpty()) { title += (title.length() > 0) ? " " + lastName.stringValue() : lastName.stringValue(); } return new Title(title); } Titles show up at the top of each object's window (next to the icon). You can set a title to anything you like. Just make sure it is descriptive enough for a user to understand the object. Diagram 3. Person with a title Pages: 1, 2 Next Page » View all java.net Articles.
http://today.java.net/pub/a/today/2003/07/15/nakedaddress.html
crawl-002
refinedweb
1,649
59.19
64 replies on 5 pages. Most recent reply: Jan 30, 2012 1:07 PM by Steve Carmeli I just saw Joe Darcy's JDK 7 in a Nutshell talk (9.5 minutes) from O'Reilly OSCON Java 2011. The new features he talked about were a bit of type inference so that you no longer have to repeat yourself in some of the most egregious ways the language formerly forced us to, and switching on String. If this had happened 12 years ago, I would have felt like the language was on the right track, trying to make things easier and cleaner for the programmer. Instead, I feel like we got over a decade of being told why all the choices made in Java were the best way and that we should just accept and love them (and many did). Only now, after years of dissatisfaction that led to more succinct and powerful languages on the JVM, do we finally start seeing some of these fundamental improvements. But it seems like they only happened under extreme duress after a lot of resistance. And perhaps these features might be helpful, but I can't see them stemming the flow away from Java towards other JVM languages for those that no longer want to struggle with the limitations of Java. For example, in Scala the decision to use type inference is at the core of the language, not an afterthought. So defining an object is about as clean a process as you could hope for. Adding a little inferencing in Java 7 doesn't make a dent by comparison. With Scala's pattern matching, you can switch on pretty much anything. Someone who is frustrated by the limitations of switching on integral values is not going to see enough of an improvement via string switching. It's nice that Java is making these improvements. Java made some fundamental shifts in the programming world -- before Java everyone believed that virtual machines and garbage collectors would never be practical, for example. But it seems to me that the world started moving on awhile ago. The productivity and financial benefits of languages like Scala, Groovy, JRuby, Jython and numerous other JVM languages are getting harder and harder to resist. val (minors, adults) = people partition (_.age < 18) > val (minors, adults) = people partition (_.age < 18) > val startingWithA = people filter (_.name.startsWith("A")) val names = people map (_.name) def isMinor(age: Int): Boolean = { // oh so complex majority rules } val (minors, adults) = people partition (p => isMinor(p.age)) public boolean isMinor(int age) { // oh so complex majority rules } List<Person> minors = new LinkedList<Person>(); List<Person> adults = new LinkedList<Person>(); for (p : people) { if (isMinor(p.age)) minors.add(p); else adults.add(p); }
http://www.artima.com/forums/flat.jsp?forum=106&thread=332347
CC-MAIN-2016-44
refinedweb
459
62.48
Making flashblock work again; and why HTML5 video doesn't work in Firefox Back in December, I wrote about Problems with Firefox 35's new deprecation of flash, and a partial solution for Debian. That worked to install a newer version of the flash plug-in on my Debian Linux machine; but it didn't fix the problem that the flashblock program no longer works properly on Firefox 35, so that clicking on the flashblock button does nothing at all. A friend suggested that I try Firefox's built-in flash blocking. Go to Tools->Add-ons and click on Plug-ins if that isn't the default tab. Under Shockwave flash, choose Ask to Activate. Unfortunately, the result of that is a link to click, which pops up a dialog that requires clicking a button to dismiss it -- a pointless and annoying extra step. And there's no way to enable flash for just the current page; once you've enabled it for a domain (like youtube), any flash from that domain will auto-play for the remainder of the Firefox session. Not what I wanted. So I looked into whether there was a way to re-enable flashblock. It turns out I'm not the only one to have noticed the problem with it: the FlashBlock reviews page is full of recent entries from people saying it no longer works. Alas, flashblock seems to be orphaned; there's no comment about any of this on the main flashblock page, and the links on that page for discussions or bug reports go to a nonexistent mailing list. But fortunately there's a comment partway down the reviews page from user "c627627" giving a fix. Edit your chrome/userContent.css in your Firefox profile. If you're not sure where your profile lives, Mozilla has a poorly written page on it here, Profiles - Where Firefox stores your bookmarks, passwords and other user data, or do a systemwide search for "prefs.js" or "search.json" or "cookies.sqlite" and it will probably lead you to your profile. Inside yourprofile/chrome/userContent.css (create it if it doesn't already exist), add these lines: @namespace url(); @-moz-document domain("youtube.com"){ #theater-background { display:none !important;}} Now restart Firefox, and flashblock should work again, at least on YouTube. Hurray! Wait, flash? What about HTML5 on YouTube? Yes, I read that too. All the tech press sites were reporting week before last that YouTube was now streaming HTML5 by default. Alas, not with Firefox. It works with most other browsers, but Firefox's HTML5 video support is too broken. And I guess it's a measure of Firefox's increasing irrelevance that almost none of the reportage two weeks ago even bothered to try it on Firefox before reporting that it worked everywhere. It turns out that using HTML5 video on YouTube depends on something called Media Source Extensions (MSE). You can check your MSE support by going to YouTube's HTML5 info page. In Firefox 35, it's off by default. You can enable MSE in Firefox by flipping the media.mediasource preference, but that's not enough; YouTube also wants "MSE & H2.64". Apparently if you care enough, you can set a new preference to enable MSE & H2.64 support on YouTube even though it's not supported by Firefox and is considered too buggy to enable. If you search the web, you'll find lots of people talking about how HTML5 with MSE is enabled by default for Firefox 32 on youtube. But here we are at Firefox 35 and it requires jumping through hoops. What gives? Well, it looks like they enabled it briefly, discovered it was too buggy and turned it back off again. I found bug 1129039: Disable MSE for Firefox 36, which seems an odd title considering that it's off in Firefox 35, but there you go. Here is the dependency tree for the MSE tracking bug, 778617. Its dependency graph is even scarier. After taking a look at that, I switched my media.mediasource preference back off again. With a dependency tree like that, and nothing anywhere summarizing the current state of affairs ... I think I can live with flash. Especially now that I know how to get flashblock working. [ 17:08 Feb 09, 2015 More tech/web | permalink to this entry | comments ]
http://shallowsky.com/blog/tags/flash/
CC-MAIN-2015-35
refinedweb
729
73.37
Hi, YOU should ask the company's payroll dept. but yes, if this is a US company and you are a US citizen they should be withholding normal payroll taxes (especially since you are not an expatriate) I'm not sure I understand the comment, accepted a job in a foreign country, if the US is a doemestic US corporation and you are working from the US ... IS there something I'm missing? Just want to e sure we're on the same page here) Sorry for the typo there ... Meant to say if the "company" is a US domestic corporation .... (which simply means incorporated and domiciled in the US) at all ... Lane Sorry, I didn't even know there was a chat mode. It's a small start-up company without a payroll dept. yet. Their actual offices and all business is done abroad. They just happen to be incorporated in a U.S. state. I will be working on projects in the foreign country, and will often travel there, but will also be working from home. I think I am the only U.S. employee they have, all others are from the foreign country, so it's not their regular practice to do U.S. withholding. I just need to see if it will apply to me. Hi,A couple of follow-up questions.(1) Will you be an independent contractor or an employee (given that you are NOT working on-site) this may be VERY simple by treating this as an independent contractor, rather than as an employee:(You have a very good case of filing your taxes this way because they are not controlling your workplace)In this scenario, you simply file a schedule C, as an attachment to your tax return and report the income (actually profit, after any non-reimbursed expenses), which will flow to line 12 of your tax return (business income or loss).Schedule C (Form 1040)And you'll notice on Schedule that it says "If a profit, enter on both Form 1040, line 12 (or Form 1040NR, line 13) and on Schedule SE, line 2."Schedule SE (Form 1040)Schedule SE is where you'll pay the social security and Medicare tax.IF you are certain, that you will be categorized as an EMPLOYEE, then the answer depends on a couple of things:See this from IRS: In general, U.S. social security and Medicare taxes continue to apply to wages for services you perform as an employee outside of the United States if one of the following applies:. Form 2032, Contract Coverage Under Title II of the Social Security Act(PDF), is used by American employers to extend social security coverage to U.S. citizens and residents working abroad for foreign affiliates of the American employers. Coverage under an agreement in effect on or after June 15, 1989, cannot be terminated. Social security tax does not apply to the value of meals and lodging provided to you for the convenience of your employer and excluded from your income. Under aTotal. Sorry, for the data-dump, but maybe this will get us to the pace where we can have a efficient conversation.Lane I think you raised more questions than I even knew about. The foreign country is the Netherlands, which looks like has a Totalization Agreement with the U.S. So presumably I would not have to pay social security in both locations. The original plan was to be counted as an employee, since the Netherlands has very employee-friendly laws compared to the U.S. However, it seems like the tax situation might get exceedingly complicated, which could be solved by being an independent contractor. So, does all this change if the company I work for decides to incorporate itself in the Netherlands?
http://www.justanswer.com/tax/81pjd-just-accepted-job-foreign-country-however-company.html
CC-MAIN-2015-11
refinedweb
635
60.24
In part I of this series, you saw how we made a simple mobile app in the Corona framework that responds to a "bump" like action (called a "thump") to send a message to another mobile device. The communication between the two mobile devices occurs between an intermediary server process that matches two "thumped" devices by both timestamp and distance. In this tutorial, we will setup the intermediary server process with Ruby on Rails. Let's start by creating our project. Since we will be using the geokit plugin to help with our geospatial calculations, we have to create this project in Rails 2.3.5 as the plugin is not 3.0 compatible. After logging into your server/hosting account (in our case we're using Heroku), type the following: mkdir thump-server cd thump-server/ rails . remove public/index.html The above statements will create a directory and start a new rails project inside of it. If you have 3.0 installed on your development machine, you might need to install RVM and create a separate gemset for this project. However, doing this is outside the scope of the tutorial. Now let's install the geokit plugin. script/plugin install git://github.com/andre/geokit-rails.git Once this completes, we need to add our gem to the project inside the Rails::Initializer.run do |config| block of our environment.rb file: config.gem "geokit" Now that this plugin has been added to the project, we need to run a rake command to make sure all the required gems are installed in our system. rake gems:install Geokit relies on the database to do some rather sophisticated distance calculations. Because of this, the default SQLite database that a rails project comes with will not work. Geokit requires that we use either a mysql or postgres db to store our data. Even though heroku uses postgres by default, it is more common for development machines to have mysql installed. The beauty of using Rails and ActiveRecord is that it doesn't matter. We can develop our app with MySQL and it will work seamlessly with postgres. mysql -u root create database thumpserver; Now we'll update our database.yml file to point at our newly created development database "thumpserver". development: adapter: mysql database: thumpserver user: root socket: /tmp/mysql.sock pool: 5 timeout: 5000 Finally our project creation process is complete. We can start coding the logic inside our thumpserver. Rails has a simple generator method that creates a REST based resource for data CRUD. If that last sentence didn't make any sense, I suggest you google "rails restful resources" to find out more. Essentially with one command we can create a database table, model, controller and routes inside the project. ./script/generate resource thump deviceid:string lat:decimal lng:decimal message:string received:boolean Our resource is called thump, so by generating it in this fashion, it will be available at the url /thump once our server is running. We specified 5 fields to be created for our database table: deviceid: the mobile device's UID lat: latitude provided by the location service lng: longitude message: the message that will be transmitted to the users who have thumped received: this is a boolean to mark once a message has been received so it can't be sent again Rails will "automagically" create timestamp fields called created_at and updated_at. We will use created_at later on in our example. When we generated our resource, a rails database migration file was created in the "db" folder of the project. The filename should appear to be something like this: TIMESTAMP_create_thumps.rb We need to modify this file to ensure that our location can be stored with enough decimal places. To do this simply replace these two lines: t.decimal :lat t.decimal :lng With the following lines: t.decimal :lat, :precision=>8, :scale=>8 t.decimal :lng, :precision=>8, :scale=>8 This will ensure that our latitude and longitude fields can contain at most 8 decimal places. Also, to avoid having the "received" field in our database be NULL, we need to add a setting so that it's value is false by default. Again we can do this by replacing this line: t.boolean :received With this line: t.boolean :received, :default=>false Now that our migration is setup, we can run the rake command that will actually create the table inside the database: rake db:migrate To take inputs for our data, we will be using the "create" action in our thump controller. In addition to this, we need a "search" action that will take some parameters and search through the database to match the two thumped devices. We need to modify our routes.rb in the config directory to respond to the URL /thump/search on a GET request. We can do this by replacing this line: map.resources :thumps With this line map.resources :thumps, :collection => { :search => :get } Next up, let's add the following lines to our thump.rb file inside app/models. acts_as_mappable validates_presence_of :lat, :lng, :deviceid The first line makes our model "mappable". This gives us some extra query methods to help calculate the distance between two coordinate sets. The next line adds some simple validations to our thump data model to ensure that when we get a thump message it contains the proper fields. Finally, we get to create our actions for creating and searching data in our controller. Thanks to the beauty and simplicity of ActiveRecord, our "create" action is rather simple: def create Thump.create!(params[:thump]) render(:json=>{:success=>true}) rescue render(:json=>{:success=>false}) end In the case that our validations fail, we will return a json object with :success=>false. In part III of the tutorial we will expand our mobile app to account for this. Our search "action" is slightly more complex as it uses some of the query helpers from geokit: def search thump = Thump.find( :first, :origin => [params[:thump][:lat],params[:thump][:lng]], :conditions=>["deviceid != ? AND received = ?",params[:thump][:deviceid], false], :order=>'distance asc, created_at desc' ) raise unless(thump) thump.update_attribute(:received,true) render(:json=>{:success=>true, :message=>thump.message}) rescue render(:json=>{:success=>false}) end Let's break this down: thump = Thump.find( :first, :origin => [params[:thump][:lat],params[:thump][:lng]], :conditions=>["deviceid != ? AND received = ?",params[:thump][:deviceid], false], :order=>'distance asc, created_at desc' ) Essentially we are querying for our "thump" match in the database. A device will send along its own latitude and longitude which will be our origin point. Our conditions ensure that we don't accidentally find our own device by excluding our own deviceid from the result set. We also only want to search thumps where the "received" field is false. To find the closest match in both distance and time, we will order our results by distance between the 2 points in ascending order (i.e. closest) and time created or created_at in descending order to find the most recent. It is obviously an unlikely event that there will be any conflicting "thumps" for our test app, but this kind of query could hold up to a multi-user application if we wanted it to. raise unless(thump) thump.update_attribute(:received,true) render(:json=>{:success=>true, :message=>thump.message}) The raise command will bump our code progression into the rescue block which will return :success=>false if we can't find a matching thump. This will ensure that our mobile app will at least receive something back in the event of an error. If the object does exist, we will set the "received" field to true to ensure that this message will not be matched in a subsequent data request. Our render statement will return a JSON object that the device receiving the "thump" will interpret. To test this out, we can run a command in the Rails console to create a sample record with an origin point of New York City: Thump.create(:deviceid=>"B", :lat=>40.7141667, :lng=>-74.0063889, :message=>"B") In order to get a "thump" match, or a successful return, we can first start our server on the default port 3000: ./script/server And then hit the following URL:[deviceid]=A&thump[lat]=40.7141667&thump[lng]=-74.0063889 If all goes well, the browser should display the following: {"message":"B","success":true} This simulates a device called "A" receiving a "thump" message from device B. And there we have it! Next Time. . . Stayed tuned for part III of this series, where we will push the server app to Heroku and upgrade our mobile app to communicate with the server. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/sharing-data-with-gestures-rails-heroku-setup--mobile-5485
CC-MAIN-2020-16
refinedweb
1,466
64.51
Use pre-trained CNN for the State Farm Kaggle competition A workbook with fast.ai lessons 3-4 if you want to read about free video downloader like vidmate apk click here With a small train data size and sufficient training time, you can always adjust the train data to 100% accuracy. Apply the VGG16 model with finetune default of fast.ai on distracted pilot detection competition data from Kaggle State Farm, we use the following parameters: batch_size = 60 epochs = 200 train data size = 100 images belonging to 10 classes size of validation data = 50 images belonging to 10 classes Weight decrease = 0.0 Learning rate = 0.001 Optimizer = Adam Decrease in learning rate = 0.0 Abandonment = 0.5 on two fully connected layers (4096 neurons, activation = ReLu) No batch standardization Around the 180 epochs, you can see the line accuracy = 1 go through a red dot, which means reaching an exact accuracy of 100% for training data. However, it is clear that we have an overcapacity, the validation accuracy is only 0.5. To estimate the cost in time with training in a complete data set and a VGG16 model (except that the last layer is replaced and that only the dense layers are trainable), I apply the following parameters: batch_size = 60 train data size = 17943 images belonging to 10 classes (take 20% of the original train data as validation) size of validation data = 4481 images belonging to 10 classes Weight decrease = 0.0 Learning rate = 0.001 Optimizer = Adam Decrease in learning rate = 0.0 Abandonment = 0.5 on two fully connected layers (4096 neurons, activation = ReLu) No batch standardization It takes about 10 minutes to train the neural network at a time! So if I have to check 10 learning rates, 10 weight decreases, 3 dropout rates, 3 momentum (or decreasing learning rate), 3 lot sizes, 2 optimizers, it will take about (assuming that 'no grid search here) (10 + 10 + 3 + 3 + 3 + 2) * 10 = 310 minutes ~ 5 hours for a single period. As a general rule, we would like to run each parameter longer, for example 10 epochs, which means 50 hours of training! And 10 eras are probably not long enough! It’s too long for me to find the optimal settings. I need to use less data in less time to find a meaningful approximation of the parameters. In addition, there are 79,726 images under test, it takes about 30 minutes to generate predictions for them. Anyway, here is the graph of the accuracy compared to the times for this race. We can say that the validation precision is better than the train precision, this could indicate an under-adjustment because we applied the stall. By submitting this model to Kaggle, I got a score of 1.55869, ranking around 675 in Kaggle’s private ranking. While there are a few ideas we can try to improve the validation error (for example, reduce regularization), it’s best to follow a systematic process to tackle the problem. Since we are only forming dense layers here, we should probably remove the convolutional layers to speed up the formation. To save time in training and fine-tuning the hyper-parameters, I tried to use the pre-formed VGG16 model here. First, load the original VGG16 model Then delete all the layers after the last flattened part of the convolutional layer, i.e. after this layer _________________________________________________________________flatten_2 (Flatten) (None, 25088) 0 ================================================= == ========================== I then made predictions on train data, validation data and test data with the scale model. The resulting characteristics (shape: 25088x1 for each entry) are the entries of my new model (see below) on the photos of State Farm. I then created a minimal network fully connected with 1 hidden dense layer (which has only one neuron) and with softmax as the output layer. from keras.models import Sequentialfrom keras.layers.core import Flatten, Dense, Dropout, Lambdafrom keras.layers import BatchNormalizationfrom keras.optimizers import SGD, RMSprop, Adamlr = 0.001statefarm_model = Sequential () statefarm_model.add ‘relu’, input_shape = (25088,))) statefarm_model.add (Dense (10, activation = ‘softmax’)) statefarm_model.compile (optimizer = Adam (lr = lr), loss = ‘categorical_crossentropy’, metrics = [’ precision ']) statefarm_model.summary () _________________________________________________________________ Layer (type) Param
https://discuss.pytorch.org/t/use-pre-trained-cnn-for-state-farm-kaggle-competition/65553
CC-MAIN-2022-33
refinedweb
691
54.73
Modules may be imported into a database, either by reading directly from a file or by passing the module data to be parsed directly, using the import subcommand. Any errors or warnings that are generated during parsing will be logged to the file channel configured for the database (see Logging Compiler Messages). % dbcmd import option value ?option value ...? dbcmd option value 1if the data was parsed successfully (i.e., either there were no errors during the parse or any errors that occurred were "recoverable"). 0if the data was not parsed successfully (i.e., one or more non-recoverable errors occurred). If any module fails to be parsed successfully, then all imported data is discarded, including the file record its self if the -inoption (see below) was not specified. The SMITHY_MIB_PATH environment variable can be set to a list of paths (delimited by semicolon on Windows or colon on other platforms) to be searched for the specified file when the import command is given a relative path that is not found. For example, if set in the environment outside Tcl (csh syntax): setenv SMITHY_MIB_PATH /usr/share/mibs:$HOME/mibs With the above setting, given a relative file name like IF-MIB.mib, the SDK will first attempt to find ./IF-MIB.mib, then /usr/share/mibs/IF-MIB.mib, and finally $HOME/mibs/IF-MIB.mib, choosing the first file match found. -errors variable -filename path -in recordName @File#, where #is an integer suffix that uniquely identifies the file within its database. If this property is unspecified, then a new file record will be created to hold the imported records. -rawdata text -warnings variable -yylineno value % smilib import -filename /path/to/module.mib \ -errors errCount -warnings warnCount 1 % smilib log "$errCount error(s), $warnCount warning(s)" 0 error(s), 0 warning(s) % smilib import -filename /path/to/module.xml \ -errors errCount -warnings warnCount 1 % smilib log "$errCount error(s), $warnCount warning(s)" 0 error(s), 0 warning(s) % set channel [open "example.mib" r] % set rawData [read $channel] % close $channel % set file [smilib new -file -filename "example.mib"] % smilib import -rawdata $rawData -in $file 1
http://www.muonics.com/Docs/MIBSmithy/DevGuide/smilib-import.php
CC-MAIN-2020-40
refinedweb
354
56.15
In this tutorial we will be covering: - Using Define's to return values - Adding Parameters to your defines - How to include using the #include function - Using the preprocessor's if statements 1. Using Defines to return values. This is the primary function of a define, a macro that tells the compiler this is what I want this value to be. But, how do I use the #define macro? #define <define name> <value> Replace <define name> with a name of your choice, for example DRIPPING_TAP (Note that there can't be spaces), and <value> to a value of your choice. This value can be a string, integer, float, double, hex, etc value etc. But for now we are just going to use 1. Example 1.1: #define DRIPPING_TAP 1 Now that we have our define, we may as well use it or that would be retarded Example 1.2: #define DRIPPING_TAP 1 int main() { if(DRIPPING_TAP) // If DRIPPING_TAP is true { printf("It is true."); } } Try experimenting with different values and ways they can be used, you'll be suprised how powerful the #define function really is. 2. Adding Parameters to your defines. In this section we will learn how to use our define blocks like a function. Using defines as a function generally more efficient as everything is handled by the preprocessor. The beauty of this is it doesn't require any forward declarations, and takes less memory. We can use bitwise operations for if statements, and make use of C++'s operators effectively. Here is an example of a max() macro: #define max(a,b) a > b ? a : b In English: If a more than b equals true return a, else return b. This function checks two numbers, and returns the biggest one. Say we have 3 variables called x, y and z. This is what it would look like before preprocessing. z = max(x,y); This is what it would look like after preprocessing. z = x > y ? x : y; Lets look at another macro. #define IsNumberOdd(val) val % 2 We make the val parameter like any other function, and use the modulus sign to get the remainder of a division by 2. And because a number can only be either odd or even, you can use that for this two. Example 2.1 will demonstrate how you can make your code more clear. Example 2.1 #define NUMBER_ODD 1 #define NUMBER_EVEN 0 #define IsNumberOdd(val) val % 2 int main() { int Number = 100; if(IsNumberOdd(Number) == NUMBER_ODD) printf("%d is odd.", Number); else if(IsNumberOdd(Number) == NUMBER_EVEN) printf("%d is even.", Number); } 3. Including a file Many beginners get stuck into thinking that they need to place there include files in the default directory. The most general way of including a file is #include <..>, but you can choose to include a file inside your project's directory with the almighty preprocessor. #include ".." will set it so the compiler will look in the project's directory not the default one. 4. Using the preprocessor's if statements. The preprocessor has a lot of useful ways of testing values. Here is an example of how you can check if the computer is running windows. int main() { #if defined(WIN32) print("Windows"); #else print("Not windows"); #endif } There are a lot of other useful definitions out there, and I hope you have learnt at least something about the preprocessor from this tutorial.
http://www.dreamincode.net/forums/topic/35780-introduction-to-the-preprocessor/
CC-MAIN-2016-50
refinedweb
569
64.71
Celebrating Another Year of TypeScript Today on October 1st, 2019 TypeScript is passing its 7th birthday. We get a lot of mileage out of TypeScript at YouView; we’ve been using it to build the latest version of our UI for over 4 years and have amassed over a hundred thousand lines of TypeScript code. To celebrate the language’s success, what better way to look back to where it all began and at how TypeScript has grown. Setting The Scene As the de facto language of the web, JavaScript (despite its marred reputation) was spreading and codebases were growing. Developers were resigning themselves to needing some way of creating JavaScript. Seeing that not even the ubiquitous JQuery would save them from writing questionable code, people were open to new languages and tools that might make coding a bit more pleasant. One such example of an alternative language is Coffeescript, a compile-to-JavaScript language with nice syntactic sugars, which was beginning to reach peak popularity. These alternatives each came with their own pros and cons, and even other teams at Microsoft were weighing in with their 2 cents (and taking a slight pot-shot at Google while they did so):. Enter TypeScript After two years of internal development inside Microsoft, Version 0.8 of TypeScript was announced on 1st October, 2012, hosted on the (now defunct) codeplex. At release, the following quote was emblazoned over the TypeScript Homepage: TypeScript is a language for application-scale JavaScript development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source. A critical promise from the very beginning is that your JavaScript code is already TypeScript. By creating a superset rather than a completely new language, Microsoft were reaching out to developers who were already knee-deep in large JavaScript codebases. Just drop this tool into your workflow, and some problems will be solved. The quickstart guide posted alongside the initial release showcases some headline features (types annotations, interfaces and ES6 classes) as well as examples demonstrating how it would catch bugs: While the example above looks (and compiles) like the TypeScript you know today, the feature-set at the time was much more limited. Major type-system features were yet to appear, such as Generics which wouldn’t show up until v0.9 in June 18th, 2013 around 8 months later. For what it’s worth, the error messages have improved since then as well. Reception Upon release it wasn’t immediately clear how powerful and popular TypeScript would become. You can get a cheap laugh looking back now at comments on the initial posts, such as this one posted just 12 minutes after the release on the 53 minute introductory video: I’ll go on record as saying this is almost the dumbest idea ever. We already have a strongly typed language that can compile to idiomatic JavaScript. It’s called C#. Or Java. Or Lisp. Or C++. There was plenty of praise for Microsoft’s new offering, but while it is funny to look back with hindsight on comments like this it does help highlight how many were skeptical of yet another tool professing to solve JavaScript’s woes. Unsurprisingly for Microsoft at the time, another notable point was the lack of solid editor support outside of the Visual Studio ecosystem: Developers use MacOS and Linux workstations to write the bulk of the code, and deploy to Linux servers.. Miguel De Icaza’s blog (October 1st, 2012) Early Steps Coming up on a year after the initial v0.8 release, Microsoft dropped v0.9 into our laps with generics and enums being among the big-ticket features. During this early period in TypeScript’s life, releases were sporadic and small updates often targeted areas such as compiler performance and editor improvements. Release details for v1.0 (released April 2nd, 2014) contain a surprising lack of language features, instead inviting community contributions to the project. In response to user feedback TypeScript’s development was migrated from the Microsoft-owned Codeplex to (then independent) GitHub around around 3 months later, where it remains to this day. AtScript Around this time Google had cottoned on to some of TypeScript’s growing reputation and at ng-conf Europe in October 2014 they announced a new Language of their own: AtScript. In a pleasingly recursive fashion, AtScript would be a superset of TypeScript. Their goals were to add on features like annotations (later to become decorators) and introspection to help create a language that would be used to build Angular 2.0. Alas AtScript was short-lived, and on March 15th, 2015 Microsoft and Google announced they would be joining forces to integrate AtScript’s features into the core TypeScript language. Future Features, Now In addition to the language features added in the 1.x versions, TypeScript also began giving developers early access to future JavaScript syntax. Taking async/await as an example, initial support was included in TypeScript 1.6 (16th September, 2015), improved in version 1.7 and fully supported in v2.1 (8th November, 2016) ahead of its inclusion in major browsers or official release in ES2017. Nowadays the team behind TypeScript will wait until the TC39 proposal has reached Stage 3. TC39 (short for Technical Committee 39) is the group responsible for managing which features make it into new versions of JavaScript (more formally known as ECMAScript) and the TypeScript team actively take part in the committee. Some notable exceptions to the Stage 3 rule are some of the features promised to help replace the now abandoned AtScript. Decorators were included in v1.5 (20th July, 2015) and improved in v1.7 (30th November, 2015), however support for them has remained locked behind “experimental” compiler flags. The TC39 proposal has languished in Stage 2 for a while now, but has recently received renewed focus so watch this space. Modern Process TypeScript’s v2.0 release on 22nd September, 2016 could be considered the start of TypeScript’s modern era. Following this the release cadence has sped up and evened out, with at least 5 minor releases annually in the time since. V2.0 was accompanied by another big change, the release of @types packages on npm. Prior to this if you wanted type definitions (essentially header files) for a third-party library there were a couple of options: Hope that the library had been distributed with the .d.ts files inside the package; or install a tool like TSD or its successor Typings to in turn grab them from the definitelytyped repository. Microsoft decided to sweep these definition files en masse into npm under the @types namespace. This is still primarily populated by the community-driven definitelytyped repository (which now lists an impressive 6000+ libraries supported) but has removed the need for extraneous tools in favour of ones developers typically already have installed. Counter to Microsoft’s past reputation, much of the process surrounding TypeScript’s development now happens in the open with community involvement. Skimming through the torrent of daily Github issues (totalling over 23000 at the time of writing) you can find meeting minutes about the language’s progress tagged under “Design Notes” or “Planning”, and the roadmap and design goals are easily accessible on the wiki. Success and Spread Over the years TypeScript has risen to be one of the most popular languages around. In Github’s 2018 Octoverse report TypeScript ranked as the 3rd fastest growing language, and the latest RedMonk language rankings placed TypeScript at number 10: Three years ago at this time, TypeScript had just broken through to #26 after languishing in the thirties for years. This quarter […] the JavaScript superset capped off one of the more remarkable growth stories we have ever seen in these rankings, placing in the top ten for the first time after surging to #12 last quarter. […] The ubiquity of JavaScript coupled with the optional safety offered by TypeScript has proven to be a winning combination, and vaulted it directly into rare territory. At this point TypeScript forms the foundation for a significant set of major projects: Angular, Redux, RxJS, MobX, InversifyJS, VsCode and GitHub’s desktop client all use the language at their core; and Deno (a fledgling hopeful successor to node) will support it by default. Much of TypeScript’s success can be attributed to how discreetly it can work its way into JavaScript projects. A recent Microsoft blog post outlines how developers can “Upgrade to TypeScript Without Anybody Noticing”. Users of the text editor VSCode will already be getting compiler hints and Intellisense for dependencies on their JavaScript without necessarily realising TypeScript is the tool powering it all (a feature which unintentionally DDoS-ed npm upon release). Looking to the future In their latest roadmap the TypeScript team outline a holistic set of goals: - Types on every desk, in every home, for every JS developer - Productivity through strong tooling - Approachability and UX - Community engagement - Infrastructure and engineering systems For a bigger picture, the language’s Design Goals wiki page lists the goals and “non-goals” that shape the language. In terms of language features, much of the exciting stuff entering the language will be coming by way of the TC39 group, for example optional chaining and the pipeline operator. By design, any progress in the JavaScript ecosystem feeds directly into the TypeScript language. For the developer community there is no indication that TypeScript will stop growing in popularity. Two years ago prominent community member Basarat posted an article comparing TypeScript to other JavaScript++ solutions and proclaimed “TypeScript Won”. At the time this stance attracted its fair share of critics, but as time has passed it is getting harder and harder to disagree. TypeScript at YouView There are traces of TypeScript at YouView as far back as May 2015, where it was initially being used in the overhaul of the user interface on set-top boxes; the previous iteration of which was built in Flash. At the time TypeScript certainly wasn’t the safest bet, it was in the early v1’s and alternatives were more mature. One positive that swayed our decision was how familiar the generated JavaScript code was to the original TypeScript source, compared to CoffeeScript and Dart, which made it easier to debug and understand. YouView’s new look launched in November 2016 and since then we have continued to use TypeScript, keeping up to date with compiler releases and trying to adopt the latest best practices as they have evolved. Our UI runs as ES5 JavaScript in a webpage on top of a TV video feed, but in addition to running in the browser, the language has begun to spread out from our core product and begun infiltrating cloud services, test tools and build tools; bringing some additional reliability to our other projects running on node. An often overlooked benefit of adding types to the codebase is the metadata that it adds. We have leveraged this in tooling like codemods and our own homegrown compile-time dependency injection system. One of our engineers has even managed to implement a 4-bit VM using the type system alone. If you love TypeScript, TV or Technology check us out at youview.com!
https://medium.com/youview-engineering/celebrating-8-years-of-typescript-e4b1482f3ba0
CC-MAIN-2021-49
refinedweb
1,877
57.5
- Ton_yao Pogi - About C++ and Game Programming - Linker error - Line Drawing Algorithm - Sound Question - Linker Errors in OpenGL - Extracting color from 32-bit pixel... - Structs vs. Classes, Memory Usage - pointers, arrays. - alternate rendering loop - Card game help - I want to learn openGL......... but - Making .X files in 3D Studio Max 7 - newbie looking for hints on first audio program... - Were to Start Your Game Programming Carrer - Problem with glaux.h - Where to begin...? - OpenGL Headers?? - My Window Class - why it seems like the redbook is not compatible with MSVC++ 6? - Should I learn a FULL language first? - pls help me in the openGL redbook - I use XP, MSDEVC++......... - C++ String Tokenizer - Are shaders faster than fixed functionality - #include <gl\glaux.h> not working!!! - What's a portable graphics library? - Game over ? - Where should I start? - DX pixel drawing - modding a game. - Need help with gravity engine - Path Choice Questions - Is there a way... - MD2 woes - Question on 3D engine - Text-Based Game Help - rotating to a target direction - MUD help... - Are namespaces a good idea? - GDI sprite (Win32 API) - Pre-computed normals not working - Modeling/Animations in games - what do the pro's do?? - Creating a map engine. - wadawada?!? - Free 3D Modeler!!! - SDL question... - Pong AI? - Start of updated terrain engine
http://cboard.cprogramming.com/sitemap/f-6-p-43.html
CC-MAIN-2014-41
refinedweb
211
70.19
GoFly - Paragliding/hangliding/gliding Altimeter-variometer From Your Car Navigation Introduction: GoFly - Paragliding/hangliding/gliding Altimeter-variometer From Your Car Navigation > Short film with my 3rd version of device. Step 1: How This Project Works . Step 2: What We Need? 2. Arduino Microcontroller board (look at your local Radioshack or SparkFun.com). You can start with ful size board, but if You feel confortable with small Arduino Mini and Nano board after some experience I think is a better choice. 3. Pressure sensor board Those are very sensitive devices (resolution is about 25cm of altitude change) bt ou have to use some good algorithms to filter noise from those sensors. 4. Good rechargeable batteries are very important. I think eneloops are one of the best on the market and using rechargeable is also environmental friendly :) 5. To be able to program Arduino boards we need USB-serial programming interface (or cable). 6. Good to have is 6xAA or 4xAA battery enclosure. I used 4xAA but later I found 6xAA battery enclosure 7. To be able to connect arduino with PNA navigation we need 5 wire angle usb cable (available at argentdata.com) 8. To here some sound we need small speaker (available also at Radioshack.com) 9. And the last most important part is enclosure. You can find those at Digikey.com or Mouser.com. Remember that enclosure has to be big enough to fit batteries, arduino board, pressure sensor and speaker. Check out my project site to find out more about parts, ideas and ways you can do that. Step 3: Unlocking PNA Device... On the beginning I'm not responsible for any damage of Your device. Always do backup. Keep manufacturer recovery software/CD/DVD in case of emergency. Do some research first about unlocking navigation devices. Remember You will loose Your warranty. Unlocking software (this software will let you enable hidden Windows CE environment). Unlock is based on some scripts and DOWNLOAD M400_LK8000_UNLOCK_16.11.2011v.zip DOWNLOAD MIO_S501_S401_LK8000_UNLOCK_16.11.2011v.zip This Mio unlock version is prepared for Mio S501/S401 (with Navman map folder) and M400 (not tested personally by me) This Mio unlock contain LK8000 v2.2e, S-E part of USA maps, paragliders polars and USA airspace maps. There is also device manager to quick check under which serial port GPS unit works, mp3 player to play some music during parawaiting, desktop rotating app for LK8000. All software is free. You can access to system files using files explorer (extra apps and games are not part of the unlock software). LK8000 and all necessary files for unlock software are installed on build in memory (not SD card). You can put extra programs, and other files to SD card if You want to. (Mio S-devices have integrated SD card slot) Anytime You can upgrade LK8000 just overwriting LK8000 folder, but always keep your profile and setting files to avoid setting up LK8000 again from the beginning. This unlock is tested only on Mio S501/S401. I don't know how this unlock will work on others Mios. There are small differences between different Mio models (folders structure, backlight control, etc.) so I AM NOT RESPONSIBLE if you'll brick your Mio. At Mio support website I found recovery software (SmartST_S501_v6_10_0056.exe) for my Mio S501 to bring Mio device to manufacture state (software recovers all folders content). Because I was playing a lot with files, I had to recover my mio few times before I finished Unlock software. It is good to have this recovery software and backup You entire data from Mio memory before You attempt to do some changes. Of course You need also Mio user application to recover Your maps. How to install unlock: Preparing: 1. Backup Your entire memory content from Your mio to Your harddrive. If something will go wrong, You can always recover mio system drive do original state. One important file during unlock is changed so after unlock if You do not have backup there will be only hard way to recover Your Mio to manufacture state. The most important thing is to have usb connectivity. I've never lost usb, but I've read that some folks bricked mio forever. Installing: 2. Connect Mio using usb to Your computer. Restart Mio. You should get usb connectivity and removable media should show up on Your computer. 3. Download and Unpack S501_LK8000_UNLOCK software to Your computer 4. Copy all folders to Your Mio S501 memory, During copy process some files have to be overwritten. All files must be copy direct to the root folder of mio memory. 5. Turn off the device into the reset position, wait a few seconds and then switch on again (Hard Reset) 6. After 10-30 seconds You should get new nice looking mio desktop :) with GoFly wallpaper. 7. USB connection works only if You connect Mio to usb cable first and do hard reset. If You are familiar with folders, settings files, some scripting, I think after few short nights You should be able to move this unlock software to any m,s-series mio... Good luck. Step 4: How to Build This Project? 1. Some explanation to schematic - I used speaker instead of piezo to get louder sound. Also put small transistor to make amplifier. Up there is windy sometimes... - In that scenario I used full size Arduino board, but feel free to use other Atmega328 based arduino boards. - To save some money I used pressure sensor without breakoutboard. It was really hard to solder this microchip, so buy pressure sensor board, it is much easier... - To enable Serial Interface inside PNA device You have to short Pin 4 and Pin 5 inside usb port. Check cables colors with pins before You start soldering - Integrated voltage regulator on Arduino Pro board let You use voltage range from 3.7 to 12 volts. - As You can see, battery pack is providing power to Arduino and to PNA device over USB port. -Of course we need power switch between power source and device. You can use different switches to turn on/off power and which can easly fit Your enclosure. 3. After some investigation, plastic enclosure with battery slot is not good. Better option will be to buy enclosure with bigger battery door. 4. Velcro tape is doing really nice job. Also use some piece of rope to make Your project more handy and harder to loose during flight. 5. Assembled and ready to fly. As You can see, even without PNA navigation, GoFly project is still full functional sound variometer device Step 5: Programming Your Arduino... So finally we have project ready to put some code inside. How to setup programming environment? You can find everything on this page. Program listing. You need Arduino 1.0 environment to compile this program. You also need few extra libraries. I did some programming long time ago (over 10 years ago) so this program is not perfect. Based on what I found on the internet, some learning, trying and references websites. There is a lot of comments to let You understand how this program is working. /* Arduino Vario by Jaros, 2012 (dedicated to atmega328 based arduinos) Part of the "GoFly" Arduino board creates NMEA like protocol with variometer output and beping sound. LK8000 EXTERNAL INSTRUMENT SERIES 1 - NMEA SENTENCE: LK8EX1 VERSION A, 110217 $LK8EX1,pressure,altitude,vario,temperature,battery,*checksum Field 0, raw pressure in hPascal:hPA*100 (example for 1013.25 becomes 101325) no padding (987.25 becomes 98725, NOT 098725) If no pressure available, send 999999 (6 times 9) If pressure is available, field 1 altitude will be ignored Field 1, altitude in meters, relative to QNH 1013.25 If raw pressure is available, this value will be IGNORED (you can set it to 99999 but not really needed)!(if you want to use this value, set raw pressure to 999999) This value is relative to sea level (QNE). We are assuming that currently at 0m altitude pressure is standard 1013.25.If you cannot send raw altitude, then send what you have but then you must NOT adjust it from Basic Setting in LK. Altitude can be negative. If altitude not available, and Pressure not available, set Altitude to 99999. LK will say "Baro altitude available" if one of fields 0 and 1 is available. Field 2, vario in cm/s If vario not available, send 9999. Value can also be negative. Field 3, temperature in C , can be also negative.If not available, send 99 Field 4, battery voltage or charge percentage.Cannot be negative.If not available, send 999. Voltage is sent as float value like: 0.1 1.4 2.3 11.2. To send percentage, add 1000. Example 0% = 1000. 14% = 1014 . Do not send float values for percentages. Percentage should be 0 to 100, with no decimals, added by 1000! Credits: (1) //bmp085 library (2) //more about bmp085 and average filter (3) //helpfull tone library to make nice beeping without using delay (4) //how to make loud piezo speaker (5) //everything because of that (6) //huge thanks for Vario algorithm (7) //how to measure battery level using AVR ucontroller */ #include <Wire.h> //i2c library #include <BMP085.h> //bmp085 library, download from url link (1) #include <Tone.h> //tone library, download from url link (3) #include<stdlib.h> //we need that to use dtostrf() and convert float to string ///////////////////////////////////////// ///////////////////////////////////////// variables that You can test and try short speaker_pin1 = 8; //arduino speaker output - short speaker_pin2 = 9; //arduino speaker output + float vario_climb_rate_start = 0.4; //minimum climb beeping value(ex. start climbing beeping at 0.4m/s) float vario_sink_rate_start = -1.1; //maximum sink beeping value (ex. start sink beep at -1.1m/s) #define SAMPLES_ARR 6 //define moving average filter array size (2->30), more means vario is less sensitive and slower #define UART_SPEED 9600 //define serial transmision speed (9600,19200, etc...) ///////////////////////////////////////// ///////////////////////////////////////// BMP085 bmp085 = BMP085(); //set up bmp085 sensor Tone tone_out1; Tone tone_out2; long Temperature = 0; long Pressure = 101325; float Altitude; int Battery_Vcc = 0; //variable to hold the value of Vcc from battery const float p0 = 101325; //Pressure at sea level (Pa) unsigned long get_time1 = millis(); unsigned long get_time2 = millis(); unsigned long get_time3 = millis(); boolean thermalling = false; int my_temperature = 1; char altitude_arr[6]; //wee need this array to translate float to string char vario_arr[5]; //wee need this array to translate float to string int samples=40; int maxsamples=50; float alt[51]; float tim[51]; float beep; float Beep_period; static long k[SAMPLES_ARR]; static long Averaging_Filter(long input); static long Averaging_Filter(long input) // moving average filter function { long sum = 0; for (int i = 0; i < SAMPLES_ARR; i++) { k[i] = k[i+1]; } k[SAMPLES_ARR - 1] = input; for (int i = 0; i < SAMPLES_ARR; i++) { sum += k[i]; } return ( sum / SAMPLES_ARR ) ; } void play_welcome_beep() //play only once welcome beep after turning on arduino vario { for (int aa=300;aa<=1500;aa=aa+100) { tone_out1.play(aa,200); // play beep on pin 8 (note,duration) tone_out2.play(aa+3,200); // play beep on pin 9 (note,duration), it is louder if we move aplitude phase delay(100); } for (int aa=1500;aa>=100;aa=aa-100) { tone_out1.play(aa,200); // play beep on pin 8 (note,duration) tone_out2.play(aa+3,200); // play beep on pin 8 (note,duration) delay(100); } } long readVcc() // function to read battery value - still in developing phase {() // setup() function to setup all necessary parameters before we go to endless loop() function { Serial.begin(UART_SPEED); // set up arduino serial port Wire.begin(); // lets init i2c protocol tone_out1.begin(speaker_pin1); // piezo speaker output pin8 - tone_out2.begin(speaker_pin2); // piezo speaker output pin9 + bmp085.init(MODE_ULTRA_HIGHRES, p0, false); // BMP085 ultra-high-res mode, 101325Pa = 1013.25hPa, false = using Pa units // this initialization is useful for normalizing pressure to specific datum. // OR setting current local hPa information from a weather station/local airport (QNH). play_welcome_beep(); //everything is ready, play "welcome" sound } void loop(void) { float tempo=millis(); float vario=0; float N1=0; float N2=0; float N3=0; float D1=0; float D2=0; bmp085.calcTruePressure(&Pressure); //get one sample from BMP085 in every loop long average_pressure = Averaging_Filter(Pressure); //put it in filter and take average Altitude = (float)44330 * (1 - pow(((float)Pressure/p0), 0.190295)); //take new altitude in meters //Serial.println(Battery_Vcc); for(int cc=1;cc<=maxsamples;cc++){ //samples averaging and vario algorithm alt[(cc-1)]=alt[cc]; tim[(cc-1)]=tim[cc]; }; alt[maxsamples]=Altitude; tim[maxsamples]=tempo; float stime=tim[maxsamples-samples]; for(int cc=(maxsamples-samples);cc<maxsamples;cc++){ N1+=(tim[cc]-stime)*alt[cc]; N2+=(tim[cc]-stime); N3+=(alt[cc]); D1+=(tim[cc]-stime)*(tim[cc]-stime); D2+=(tim[cc]-stime); }; vario=1000*((samples*N1)-N2*N3)/(samples*D1-D2*D2); if ((tempo-beep)>Beep_period) // make some beep { beep=tempo; if (vario>vario_climb_rate_start && vario<15 ) { Beep_period=350-(vario*5); tone_out1.play((1000+(100*vario)),300-(vario*5)); //when climbing make faster and shorter beeps tone_out2.play((1003+(100*vario)),300-(vario*5)); thermalling = true; //ok,we have thermall in our hands } else if ((vario < 0 ) && (thermalling == true)) //looks like we jump out the thermall { //Beep_period=200; // play_siren(); //oo, we lost thermall play alarm thermalling = false; } else if (vario< vario_sink_rate_start){ //if you have high performace glider you can change sink beep to -0.95m/s ;) Beep_period=200; tone_out1.play(300,340); tone_out2.play(303,340); thermalling = false; } } if (millis() >= (get_time2+1000)) //every second get temperature and battery level { bmp085.getTemperature(&Temperature); // get temperature in celsius from time to time, we have to divide that by 10 to get XY.Z my_temperature = Temperature/10; Battery_Vcc =(readVcc()/42)+1000; // get voltage and prepare in percentage get_time2 = millis(); } if (millis() >= (get_time3+333)) //every 1/3 second send NMEA output over serial port { String str_out = //combine all values and create part of NMEA data string output String("LK8EX1"+String(",")+String(average_pressure,DEC)+ String(",")+String(dtostrf(Altitude,0,0,altitude_arr))+String(",")+ String(dtostrf((vario*100),0,0,vario_arr))+String(",")+String(my_temperature,DEC)+String(",")+String(Battery_Vcc,DEC)+String(",")); unsigned int checksum_end,ai,bi; // Calculating checksum for data string for (checksum_end = 0, ai = 0; ai < str_out.length(); ai++) { bi = (unsigned char)str_out[ai]; checksum_end ^= bi; } //creating now NMEA serial output for LK8000. LK8EX1 protocol format: //$LK8EX1,pressure,altitude,vario,temperature,battery,*checksum Serial.print("$"); //print first sign of NMEA protocol Serial.print(str_out); // print data string Serial.print("*"); //end of protocol string Serial.println(checksum_end,HEX); //print calculated checksum on the end of the string in HEX get_time3 = millis(); } } //The End Step 6: What Next... Last thing to do is setup LK8000, to be able to understand what Arduino is saying. Also we have to setup few things to meet our flying requirements. All details how to setup LK8000 software are available on my project website Step 7: New Ideas... Step 8: And Another One... Third approach using Arduino mini boards. After some changes inside original Mio enclosure You can fit everything inside and make really nice, handy Altitude/Variometer for Paragliding / Hangliding / Glider pilots. THANKS everyone for Your time. Jarek Somebody can share this code with me, please? Thanks!! Do you have a good instructioin for beginners to put the code and libaries on an aduino nano board. What is "roughe code" ?? Hello the mio m400 is'nt really easy to find in my country. Do you have a list of other GPS PNA compatible? by the way, thanks for your great job! Please contact me at goflyinstruments@gmail.com if use v1.0 or later arduino compiler.please change the tone.cpp #include to #include Hi Jaros, I've built my own flying computer based on your creation (the one with arduino pro mini inside the mio M400) i've encountered some troubles to keep usb connection between pc and PNA. my solution: using a sliding switch on/on (with two line), i used a line for pin 5 to switch on/off the arduino (as you ) and a line for pin 4 to connect to pin 5 (grnd on the Mio). when i switch on , arduino is powered and pin 4 and 5 are shorted. An other problem comes from usb connector. we must have D+/D- connected from usb connector on arduino Rxt/Tx0. This connection is permanent an may cause errors when connecting the Mio to a PC. My solution is to insert a Zener diode on each wire to stop data coming from the Pc to the arduino when we are using Mio in car mode and not in the Lk8000 mode. jpg hope to be clear enough. Do you make these? I just started PPG lessons I live in KY and I am a firefighter so no electronic skills at all....... Thanks for the video looks awesome! matt.true1@gmail.com Thank you, Jarek for the unique design of this device. I'll be one of the first testers of this project in Russia :)
http://www.instructables.com/id/GoFly-paraglidinghanglidinggliding-altimeter-v/
CC-MAIN-2017-51
refinedweb
2,818
65.62
Introduction Working with a modern JavaScript using a React as the front-end framework comes with its own problems. You want to focus on building and releasing/shipping the application for the user rather than spending too much time configuring and managing code-splitting, determining the content loading architecture, and bundling them together in order to serve it as a web application. Next.js is a promising React framework that targets above-mentioned problems and is often advertised as a zero-configuration framework for React applications. Often, when you are releasing a public app or a website, you need to render the content for search engines to optimize your website. Next.js tend to solve this problem too by handling server-side rendering for you. Pre-requisites To continue with this tutorial, you will need the following: - npm installed on your machine. - Knowledge of ES6 JavaScript features such anonymous arrow functions =>, import and export statements, async/await and so on. - ReactJS Features Some of the important features NextJS has: - Hot Code Reloading: Next.js reloads the page when it detects any change saved to disk - Automatic Routing: any URL is mapped to the filesystem. Just put files in the pages folder -, not more. - Dynamic Components: you can import JavaScript modules and React Components dynamically. Installation & Getting Started Next.js supports all the major platforms: Linux, macOS, Windows. You can install it using npm. npm install next react react-dom Then, to get started add the following script in your package.json file. { "scripts": { "dev": "next" } } If you run the below command. npm run dev The script will raise an error complaining about not finding the pages folder. This is the only thing that Next.js requires to run. Create an empty pages folder. Then, run the npm run dev command again, as Next.js will start up a server on. If you go to that URL now, you will be greeted by a friendly 404 page, with a nice clean design. Our First Page In the pages folder create an index.js file with a simple React component. export default () => ( <div> <p>Hello World!</p> </div> ); If you visit, this component will automatically be rendered. Next.js uses a declarative pages structure, which is based on the filesystem structure. Anything inside pages directory is considered as a page to be rendered. Hot Reloading Note that you did not have to restart the npm process to load the page. Next.js does this for you under the hood. To prove this further, create a second page in the pages directory called contact.js. export default () => ( <div> <p> <a href="mailto:[email protected]">Contact Me</a> </p> </div> ); If you now visit from your browser to this page will be rendered. Client-side Rendering Navigating inside the website, client-side rendering is key to speed up the page load and improve the user experience. Next.js provides a Link component you can use to build links. Try linking the two pages above. Modify index.js file to reflect new changes. import Link from 'next/link'; export default () => ( <div> <p>Hello World!</p> <Link href="/contact"> <a>Contact me!</a> </Link> </div> ); First, we imported the Link API module from Next.JS and then we used it inline in the midst of our content by making a placeholder for it with the {‘ ‘} syntax. The <Link> component is a Higher Order Component and supports only a couple arguments such as href (and href argument itself supports arguments like query strings and the like) and as for URL masking. The underlying component, in this case, an <a> tag supports other props like style and onClick. Now go back to the browser and try this link. On clicking, the Contact page loads immediately without a page refresh. This is client-side navigation which is working correctly. The complete support for the History API, which means that the users back button would not break. CSS-in-JS Next.js by default provides support for styled-jsx, which is a CSS-in-JS solution provided by the same development team, but you can use whatever library you prefer, like Styled Components. Open, contact.js file and modify it accordingly. export default () => ( <div> <p> <a href="mailto:[email protected]">Contact Me</a> </p> <style jsx>{` p { font-family: 'Helvetica Neue'; } a { text-decoration: none; color: orange; } a:hover { opacity: 0.6; } `}</style> </div> ); Styles are scoped to the component, but you can also edit global styles adding global to the style element. export default () => ( <div> <p> <a href="mailto:[email protected]">Contact Me</a> </p> <style jsx global>{` body { font-family: 'Benton Sans', 'Helvetica Neue'; margin: 2em; } h2 { font-style: italic; color: #373fff; } `}</style> </div> ); Deploying Creating a production-ready copy of the application, without source maps or another development tooling that is unneeded in the final build, is easy. At the beginning of this tutorial, you created a package.json file with the scripts as content. Now just add the following content to package.json. { "scripts": { "dev": "next", "build": "next build", "start": "next start" } } You can prepare your app by running npm run build and npm run start in that order. The company behind Next.js provides an awesome hosting service for Node.js applications, called Now. Yes,. Next.js tries to solve the problem as a framework by increasing development speed, taking of care of tooling, and bundling the application files behind the scenes. Rest is your effort with a mixture of imagination and curiosity of what you can build using it. The sole purpose of this tutorial was to give you quick start as learning a new framework can overwhelming at first and make you understand the basic concepts behind it for you to use it to build your next application. this article needs quite a bit of editing
https://blog.eduonix.com/web-programming-tutorials/getting-started-nextjs/
CC-MAIN-2021-17
refinedweb
973
65.32
Position Paper for the W3C Workshop on Binary Interchange of XML Information Item Sets. Submitted by Margaret Green, Ontonet . 1. What work has your organization done in this area? Ontonet has implemented the XML Infoset, the DOM2 Core as a view onto that Infoset implementation, and a partial implementation of XQuery that queries the Infoset and returns sequences of DOM nodes as its results. Fulfilling both with an eye to efficient exchange of document infosets is a design criterion. The next version will include PSVI and Infoset Exchange. We are actively working on the binary exchange know. We are researching compression now. 2. What goals do you believe are most important in this area? Reducing bandwidth usage is the primary goal. Eliminating redundant parsing is a secondary goal. Doing this without creating another logical model is our design goal. 3. What sort of documents have you studied the most? We test documents of varied size, with and without namespaces, DTD and XML Schema. 4. What sorts of applications did you have in mind? Processing by intermediaries is especially important -- SOAP intermediaries. XML Database replication and XQuery results are important uses. 5. If you implemented something, how did you ensure that internationalization and accessibility were not compromised? The SAX parsing is augmented with pre-processing to obtain the prolog from the source. Success at this is limited; some input streams don’t enable this. Our implementation platform is Java. To the extent Java succeeds with international character sets, so we succeed. 6. How does your proposal differ from using gzip on raw XML? Ontonet wants to exchange the XML Infoset. We intend to optimize our implementation to support compressible structure, namespace, and content section by learning lessons from XMILL. 7. Does your solution work with any XML? How is it affected by choice of Schema language? Our next version includes Post Schema Validation Infoset (PSVI) information. Currently we augment SAX parsing with pre-processing to preserve in-line DTD declarations. If Relax NG can be exposed with SAX2 parsing we could incorporate it. 8. How important to you are random access within a document, dynamic update and streaming, and how do you see a binary format as impacting these issues? Our database supports random access to information items, transactions, and update. The binary format is for exchange. The format should enable stream processing by intermediaries.
http://www.w3.org/2003/08/binary-interchange-workshop/24-ontonet-BinaryInfosetPositionPaper.html
CC-MAIN-2016-44
refinedweb
394
51.34
Okay, I am a new student (to Java--well programming in general) and the first assignment we have is to create a program that computes the future value of an investment based on three user inputs (principle deposit, interest rate, and length of term in years). First of all, I am at a loss as how to assign variable that are not constant. Principle, rate, and term are set to whatever the user decides to input when prompted. But that is the least of my problems. I just keep getting error code after error code when building the file. I am not asking anyone to tell me what the solution to my problems are, as I want to do my own work... but I would like help with walking me through the process of debugging the program.. maybe through examples that are similar or something. I am aware that programming is the easy part, its the debugging that is challenging. Here is my program... /** * HW02_jsn.java * Jacqualyn Nelson * 2009/1/16 * * Calculate the future value of an investment paying compound interest annually */ import java.util.Scanner; public class HW02_jsn { Scanner input = new Scanner(System.in); public static void main(String[] args) { // call splash() // input principle, rate, years // display calcFV (principle, rate, years) System.out.println("What was the amount of the principle deposit? "); double profit = scan.nextDouble(); System.out.println("What is the annual interest rate? "); double rate = scan.nextDouble(); System.out.println("What is the term of the investment in years? "); int years = input.nextInt(); } public static void splash() { System.out.println("This program calculates an approximation of the future value of an investment based on these three variables:"); System.out.println("The amount of the principle deposit"); System.out.println("The amount of the annual interest rate"); System.out.println("The term of the investment in years"); } public static double calcFV(double p, double r, int t) { double value1 = p; // assign the variable p to principle double value2 = r; // assign the variable r to rate int value3 = t; // assign the variable t to years int calcFV(double p, double r, int t) { int fv = p * Math.pow( (1.0 + r/100), t); return fv; } System.out.println("Your investment will be worth approximately: " + calcFV(p, r, t) ); } } // end HW02_jsn I very much appreciate any and all feedback!
https://www.daniweb.com/programming/software-development/threads/169094/stumped-on-java-homework
CC-MAIN-2020-24
refinedweb
389
57.98
Simple Video pipeline reading from multiple files¶ Goal¶ In this example, we will go through the creation of a pipeline using the VideoReader operator. The pipeline will return the output of VideoReader: a batch of sequences. These sequences are an arbitrary number of frames (images). The difference being that images are or dimension HWC whereas sequences are of dimension FHWC. For more information on the VideoReader parameters, please look at the documentation reference. To make it clearer, let’s look at how we can obtain these sequences and how to use them! Setting up¶ First let’s start with the imports: [2]:264 video and distributed under the Create Common license. Let’s split it into 10s clips in order to check how VideoReader handles mutliple video files.. [3]: print(os.listdir(os.environ['DALI_EXTRA_PATH'])) ['image_info.txt', 'LICENSE', 'README.rst', 'db', '.gitattributes', '.git', 'NVIDIA_CLA_v1.0.1.docx'] Then we can set the parameters that will be use in the pipeline. The count parameter will define how many frames we want in each sequence sample. We can replace video_directory with any other directory containing video container files recognized by FFmpeg. [4]: batch_size=2 sequence_length=8 initial_prefetch_size=16 video_directory = os.path.join(os.environ['DALI_EXTRA_PATH'], "db", "video", "sintel", "video_files") video_files=[video_directory + '/' + f for f in os.listdir(video_directory)] shuffle=True n_iter=6 Running the pipeline¶ We can then define a minimal Pipeline that will output directly the VideoReader outputs: [5]: class VideoPipe(Pipeline): def __init__(self, batch_size, num_threads, device_id, data, shuffle): super(VideoPipe, self).__init__(batch_size, num_threads, device_id, seed=16) self.input = ops.VideoReader(device="gpu", filenames=data, sequence_length=sequence_length, shard_id=0, num_shards=1, random_shuffle=shuffle, initial_fill=initial_prefetch_size) def define_graph(self): output = self.input(name="Reader") return output at each iteration. [6]: pipe = VideoPipe(batch_size=batch_size, num_threads=2, device_id=0, data=video_files, shuffle=shuffle) pipe.build() for i in range(n_iter): pipe_out = pipe.run() sequences_out = pipe_out[0].as_cpu().as_array() print(sequences_out.shape) (2, 8, 720, 1280, 3) (2, 8, 720, 1280, 3) (2, 8, 720, 1280, 3) (2, 8, 720, 1280, 3) (2, 8, 720, 1280, 3) (2, 8, 720, 1280, 3) Visualizing the results¶ The previous iterations seems to have the yield batches of the expected shape. But let’s visualize the results to be [7]: pipe_out = pipe.run() sequences_out = pipe_out[0].as_cpu().as_array() We will use matplotlib to display the frames we obtained in the last batch. [8]: %matplotlib inline from matplotlib import pyplot as plt import matplotlib.gridspec as gridspec [9]: def show_sequence(sequence): columns = 4 rows = (sequence_length + 1) // (columns) fig = plt.figure(figsize = (32,(16 // columns) * rows)) gs = gridspec.GridSpec(rows, columns) for j in range(rows*columns): plt.subplot(gs[j]) plt.axis("off") plt.imshow(sequence[j]) Let’s check a second sequence: [11]: pipe_out = pipe.run() sequences_out = pipe_out[0].as_cpu().as_array() show_sequence(sequences_out[1]) And a third one… [12]: pipe_out = pipe.run() sequences_out = pipe_out[0].as_cpu().as_array() show_sequence(sequences_out[0])
https://docs.nvidia.com/deeplearning/dali/master-user-guide/docs/examples/sequence_processing/video/video_reader_simple_example.html
CC-MAIN-2021-04
refinedweb
485
51.04
Apr 13, 2012 02:52 PM|BoxheadMonkey|LINK I am trying to set up a data connection to an Oracle database using asp.net System.Data.Oracle. My dev machine is running Windows 7 64bit with VS 2008 Pro. The web server which will run the final site runs Windows Server 2008r2 64bit. I have trawled the web for what drivers i require etc and there is SO much information i am completely lost as to what I need to do! Where do I get the required Oracle drivers from the dev machine and live server and which versions do i require? How do I install them and what additional steps do I require? What gotchas do I need to be aware of? Thanks for any assistance :) Contributor 2881 Points Apr 13, 2012 03:37 PM|BoxheadMonkey|LINK I am getting this error on my dev machine: ORA-12154: TNS:could not resolve the connect identifier specified Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.OracleClient.OracleException: ORA-12154: TNS:could not resolve the connect identifier specified Source Error: Because I don't have Oracle installed I don't have a tnsnames file which I think I need? Member 308 Points Apr 14, 2012 12:11 AM|ruipedromachado|LINK hi BoxheadMonkey ---------------------------------------------------------------------------------------------------------------------------------------------------- REQUISITS ---------------------------------------------------------------------------------------------------------------------------------------------------- VS2008/2010 does not matter; .net >v2; oracleclient ( i would suggest version 10); ----this would be enought to connect from any client machine to any oracle DB. ----on your project add "System.Data.OracleClient" reference and namespace. (it will complain that its obsulete , but it works perfect) ----also note that you should check your connection via command prompt with the command C:\tnsping whatever . where whatever is the -----name of your oracle alias in your TNSNAMES file. ---------------------------------------------------------------------------------------------------------------------------------------------------- EXAMPLE ---------------------------------------------------------------------------------------------------------------------------------------------------- at this point all you need to do is connect ....EX: oracleconnect a = new oracleconnect(); a.connectionstring = "User ID=(oracleuser);Password=(oraclepass);Data Source=(oracle_tns_alias_from_tnsnames)"; a.open(); ----at this point you should be connected. ----note that all that the "System.Data.OracleClient" needs is the OCI.DLL from the oracleclient so you can or not use the TNSNAME.ora file ----you could setup your connectionstring directly with the TNSNAME address information and this way not use the TNSNAMES.ora. ----if you notice .....its a block from the TNSNAMES.ORA file :) ----EX : "User ID=oracleuser;Password=oraclepass" + ";Data Source=" + "(DESCRIPTION = " + " (ADDRESS = (PROTOCOL = TCP)(HOST = ip_address_of_host_db)(PORT = 1521)) " + " (CONNECT_DATA = " + " (SERVER = DEDICATED) " + " (SID = whatever) " + " ) " + ")"; ----------------------------------------------------------------------------------------------------------------------------------------------------- as for your extra info i would say ..... you already have oracle client or server instaled ( since oracleserver instalation also includes the client module ) becouse other wise it would say OCI.DLL missing or something like that . ---TNS:could not resolve the connect identifier specified ---means on normal circunstancies that i would have a problem on the connectionstring/TNSNAMES 1- check (SID = whatever) your SID name 2 - checl HOST = ip_address_of_host_db your db host. ( can you ping it ? can you tnsping it? ) ...... well thats about it. its very simple from a .net point of view.....the hard part its with oracle network configuration it self. Member 308 Points Apr 30, 2012 09:15 AM|ruipedromachado|LINK check tnsname.ora 7 replies Last post May 01, 2012 04:49 PM by BoxheadMonkey
http://forums.asp.net/p/1792609/4946408.aspx?Re+Basic+steps+for+Oracle+data+access+connection
CC-MAIN-2013-48
refinedweb
558
58.28
the test that stumped them all Most of us are not Donald Knuth, and indeed need to test our software. That is even true for my hobby projects - when I offer software for use by others, it's a matter of craftmanship to deliver the best software possible. It's very hard to foresee all the possible environments (architecture, compiler, library version, ...) where my software might be run. But at least, I can minimize the number of programming errors by testing things as much as possible. The trouble with testing, however, is that it is dead boring. I hate doing boring things -- life is just too short. So, I want to do my testing in the least boring way possible -- I'd like to be able to simply run: $ make test and have that go through all my test cases, and report any failures. The idea is that if it is so easy to run tests, you might actually do so, and make sure your software is working according to plan. When doing a release, it is so easy to forget something really obvious, for which you get embarrasing bug reports... Running some automated tests gives some peace of mind when doing a release. gtestSince 2.16, the GLib library offers a unit-testing framework called GTest (note, this is not to be confused with Google Test, sometimes also called GTest). GTest is not much different from, say, check, but it's part of GLib and integrates nicely with it. I have started to use it for mu, and I am quite happy with it. Here, I will not go into the details of actually writing test cases, but talk about how to integrate GTest with your code. For the best results, you'd probably want to integrate it with your build system. I am using autotools. The overall setup is that for all my directories with code, there is a subdirectory tests/ which contains the test code. Those test cases are unit-tests, which test one function or a couple of them combined. Now, of course it's a lot easier when your code is written in such a way that makes this easy[1]. In addition to the per-directery tests/, there is also a top-level tests/, which tests the whole software workflow. In the case of mu, this means that the tests will index some test messages, fill a database with that, and then run some test queries against this database. When all of that works correctly, I am quite confident that my software is not totally broken. autotoolsNow, let's discuss how you can integrate GTest with your code; this is inspired by the way GTK+ does it these days. First, here is gtest.mk, a file in the top of my source tree, that I include in all Makefile.ams that require GTest support: TEST_PROGS= test: all $(TEST_PROGS) @ test -z "$(TEST_PROGS)" || gtester -l --verbose $(TEST_PROGS); \ test -z "$(SUBDIRS)" || \ for subdir in $(SUBDIRS); do \ test "$$subdir" = "." || \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $@ ) || exit $? ; \ done .PHONY: test This blob adds a test target to various Makefiles, which will run the gtester program (part of GTest) with your test programs. In my configure.ac I have: # g_test was introduced in glib 2.16 PKG_CHECK_MODULES(g_test,glib-2.0 >= 2.16, [have_gtest=yes],[have_gtest=no]) AM_CONDITIONAL(MU_HAVE_GTEST, test "x$have_gtest" = "xyes") if test "x$have_gtest" = "xno"; then AC_MSG_WARN([You need GLIB version >= 2.16 to build the unit tests]) fi With this, I make sure that my code also works with older versions of GLib; the unit tests will only work with newer versions, of course. With this, you'll have a symbol MU_HAVE_GTEST that you can use in your Makefile.am; for example, in index/Makefile.am, I have: include $(top_srcdir)/gtest.mk SUBDIRS= . if MU_HAVE_GTEST SUBDIRS += tests endif [....] As you can see, it includes gtest.mk mentioned above, and (conditionally) add tests/ as a subdirectory to visit.The unit tests are in this subdirectory. Note that by explicitly setting SUBDIRS to '.' first, we ensure that first we build the code in index, before we go to tests/. unit testsBelow is a simple example unit test program; it only uses a small subset of GTest. You can further organize your test cases (see GTestSuite and GTestCase) and see Fixtures, which setup the testing environment. I don't use those, but they might be useful for others. In general, I am only using a small subset; check out the GTest-documentation to find out more. Anyway, here are some simple test cases: #include <glib.h> #include "my-code-to-test.h" static void test_num_str (void) { char *str; g_assert_cmpstr (str = my_num_str(1001),==,"one thousand and one"); g_free (str); g_assert_cmpstr (str = my_num_str(-1),==,"minus one"); g_free (str); } static void test_warning (void) { /* no complex roots: my_sqrt(-1) should * return MY_SQRT_ERROR and issue a g_warning; the * g_warning will trigger the process to fail, * which is what we're expecting */ if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDERR)) g_assert (my_sqrt (-1) == MY_SQRT_ERROR); g_test_trap_assert_failed (); } int main (int argc, char *argv[]) { g_test_init (&argc, &argv, NULL); g_test_add_func ("/mytests/test-add", test_add); g_test_add_func ("/mytests/test-warning", test_warning); return g_test_run (); } Now, we can run our tests with: $ make test (Note that the test cases are fork()ed, and you can actually write a test case where it passes if an abort or even a segfault occurs.) For mu-0.4 I get the following output: [...] make[1]: Entering directory `/home/djcb/src/mu-0.4/tests' TEST: test-index-search... (pid=15553) /all/test-query01: OK /all/test-query02: OK /all/test-query03: OK /all/test-query04: OK /all/test-query05: OK /all/test-query06: OK /all/test-query07: OK /all/test-stats01: OK PASS: test-index-search make[1]: Leaving directory `/home/djcb/src/mu-0.4/tests' Nice and easy; if you're less lucky, you might get something like: make[1]: Entering directory `/home/djcb/src/mu-0.4/tests' TEST: test-index-search... (pid=16024) /all/test-query01: ** ERROR:test-index-search.c:117:query_01: assertion failed (mu_msg_sqlite_get_subject(row) == "this can't be right"): ("Re: What does 'run' do in cperl-mode?" == "this can't be right") FAIL GTester: last random seed: R02S2d24e3907b0c62e6a008e891f401fedf /bin/bash: line 5: 16023 Terminated gtester --verbose test-index-search make[1]: Leaving directory `/home/djcb/src/mu-0.4/tests' With that, all we need to do is fix the bug and test again... rinse-lather-repeat. Using GTest, it's really easy to run test cases. In general I try to keep my software pass the tests at the end of every programming session. Now, this does not work when I do big changes, but after stabilizing things again, I make sure all test cases pass, both old and new. parting thoughtsOne thing still missing from GTest is some way to see the code coverage, i.e. to see which part of the code are covered by tests. I think it should be possible to do this using gcov, but it'd be nice if someone automated that a bit. Another issue is that for effective use, you will need something like the setup described here. One can hardly expect someone new to Unix-development to figure this out by themselves... but of course, we cannot really blame GTest for that. Hopefully my setup helps a bit to setup non-boring testing (even though it might be a bit boring in itself...). There are real-life examples of this in both mu and GTK+. And finally, if you find any inaccuracies, please let me know -- there are no unit tests for blog entries to save me from mistakes... [1] Now, a discussion of how to write easily testable functions deserves its own blog entry, but there are some general things to keep in mind. Keep your functions short, limit the number of parameters, avoid global variables, limit side-effects to only a few functions, etc. In other words, use the lessons learnt from functional programming languages. And as a nice side-effect (ha!), such functions tend to be much less error-prone in the first place. Syndicated 2008-11-11 17:26:00 (Updated 2008-11-11 17:32:07) from djcb
http://www.advogato.org/person/djcb/diary/160.html
CC-MAIN-2016-44
refinedweb
1,368
72.26
On Fri, Nov 14, 2008 at 8:37 PM, STINNER Victor <report@bugs.python.org> wrote: > .. but we can create new methods like: > datetime.fromepoch(seconds, microseconds=0) # (int/long, int) While 1970 is the most popular epoch, I've seen 1900, 2000 and even 2035 (!) being used as well. Similarly, nanoseconds are used in high resolution time sources at least as often as microseconds. This makes fromepoch() ambiguous and it is really unnecessary because it can be written as epoch + timedelta(0, seconds, microseconds). > datetime.toepoch() -> (seconds, microseconds) # (int/long, int) I would much rather have divmod implemented as you suggested in issue2706 . Then toepoch is simply def toepoch(d): x, y = divmod(d, timedellta(0, 1)) return x, y.microseconds
https://bugs.python.org/msg75904
CC-MAIN-2022-05
refinedweb
122
57.98
Problem Formulation You create images in the Tag Image File Format (TIFF). You want to add custom metadata to the image such as the location or other context information important for post-processing. How can you accomplish this? Solution - Install and import the library tiffile. - Use the tiffile.imsave()function to store the file at a given location. - As arguments, use the filename as the first positional argument, the image as the second positional argument. - Then add your custom metadata as a string for the keyword argument description. - You can now retrieve the metadata by calling the one-liner tifffile.TiffFile(filename).pages[0].tags["ImageDescription"].value. Here’s an example that is a bit more readable: import json import numpy as np import tifffile image = np.random.randint(0, 255, size=(100, 100), dtype=np.uint8) filename = 'your_file.tif' # Create custom description my_description = "I recorded this image on Mars" # Write the file tifffile.imsave( filename, image, description = my_description ) # Read the file frames = tifffile.TiffFile(filename) page = frames.pages[0] # Print file description print(page.tags["ImageDescription"].value) You can try this example in our interactive Jupyter Notebook in your browser to test if this is what you need: I hope you liked this short tutorial! If you want to boost your Python skills on autopilot, check out my free email academy: We have cheat sheets! 😉.
https://blog.finxter.com/whats-the-best-way-to-save-image-metadata-alongside-a-tiff/
CC-MAIN-2022-21
refinedweb
226
51.85
Improve the performance of ASP.NET MVC applications by taking advantage of the Velocity distributed cache. In this tip, I also explain how you can use Velocity as a distributed session state provider. The best way to improve the performance of an ASP.NET MVC application is by caching. The slowest operation that you can perform in an ASP.NET MVC application is database access. The best way to improve the performance of your data access code is to avoid accessing the database at all. Caching enables you to avoid accessing the database by keeping frequently accessed data in memory. Because ASP.NET MVC is part of the ASP.NET framework, you can access the standard ASP.NET System.Web.Caching.Cache object from your ASP.NET MVC applications. The standard ASP.NET Cache object is a powerful class. You can use the Cache object to cache data in memory for a particular period of time, create dependencies between items in the cache and the file system or a database table, and create complicated chains of dependencies between different items in the cache. In other words, you can do a bunch of fancy things with the standard ASP.NET Cache object. The one limitation of the standard ASP.NET Cache object is that it runs in the same process as your web application. It is not a distributed cache. The same ASP.NET Cache cannot be shared among multiple machines. If you want to share the same ASP.NET Cache among multiple machines, you must duplicate the cache for each machine. The standard ASP.NET Cache works great for web applications running on a single server. But what do you do when you need to maintain a cluster of web servers? For example, you want to scale your web application to handle billions of users. Or, you don’t want to reload the data in the cache when a server fails. In situations in which you want to share the same cache among multiple web servers, you need to use a distributed cache. In this tip, I explain how you can use the Microsoft distributed cache (code-named Velocity) with an ASP.NET MVC application. Setting up and using Velocity is surprisingly easy. Switching from the standard ASP.NET Cache to the Velocity distributed cache is surprisingly painless. I’m also going to explain how you can use Velocity as a session state provider. Velocity enables you to use ASP.NET session state even when you are hosting an MVC application on a cluster of web servers. You can use Velocity to store session state in the distributed cache. Installing and Configuring Velocity As I write this, Velocity is not a released product. It is still in the Community Technology Preview state of its lifecycle. However, you can download Velocity and start experimenting with it now. The main website for all information on Velocity is located at the following address: You can download Velocity by following a link from this web page. Installing Velocity is a straightforward process. You need to install Velocity on each server where you want to host the cache (each cache server). The cache is distributed across these servers. Before you install Velocity on any of the cache servers, you need to create one file share in your network that is accessible to all of the cache servers. This file share will contain the cache configuration file (ClusterConfig.xml). The cache configuration file is an XML file that is used to configure the distributed cache. During this Beta period, you must give the Everyone account Read and Write permissions to the file share that contains the configuration file. Right-click the folder, select the Properties menu option and select the Security tab. Click the Edit button, click the Add button, and enter the Everyone account and click the OK button. Make sure that the Everyone account has Read and Write permissions. When you run the installation program for Velocity (see Figure 1), you will be asked to enter the following information: · Cluster Configuration Share – This is the path to the folder share that we just created. · Cluster Name – The name of the cluster. Enter any name that you want here (for example, MyCacheCluster). · Cluster Size – The number of cache servers that you expect to use in this cluster. · Service Port Number – The port that your application uses to communicate with the cache server (needs to be unblocked from your firewall). · Cluster Port Number — The port that the cache servers use to communicate with each other. Velocity uses this port number and an additional port located plus one port higher (both of these ports need to be unblocked from your firewall). · Max Server Memory – The maximum amount of memory used by Velocity on this server. Figure 1 – Installing Velocity After you install Velocity on each of the servers, you must configure firewall exceptions for Velocity on each server. If you don’t, then communication with Velocity will be blocked. You can create a firewall exception for the DistributedCache.exe program name or you can create the firewall exceptions for each port number (port 22233, port 22234, and port 22235). Using the Velocity Administration Tool You manage Velocity through a command line administration tool which you can open by selecting Start, All Programs, Microsoft Distributed Cache, Administration Tool (see Figure 2). Figure 2 – The Velocity Administration Tool The Administration Tool supports the following important commands (these commands are case sensitive): · start cluster – Starts Velocity for each cache server in the cluster · stop cluster – Stops Velocity for each cache server in the cluster · create cache – Creates a new named cache · delete cache – Deletes an existing cache · list host – Lists all of the cache servers in the cluster · list cache – Lists all of the caches configured in the cache cluster · show hoststats <cache server>:<cache port>– Lists statistics for a particular cache server The first thing that you will want to do after installing Velocity is to start up the cache cluster. Enter the following command: start cluster Using Velocity with an ASP.NET MVC Application After you have Velocity up and running, you can build an ASP.NET MVC application that uses the Velocity cache. In order to use Velocity in a project, you will need to add references to the following assemblies: · CacheBaseLibrary.dll · ClientLibrary.dll You can find these assemblies in the Program FilesMicrosoft Distributed Cache folder on any machine where you installed Velocity. You can copy these assemblies from the cache server to your development server. You also need to modify your ASP.NET MVC application’s web configuration (web.config) file. Add the following section handler to the <configSections> section: <section name="dcacheClient" type="System.Configuration.IgnoreSectionHandler" allowLocation="true" allowDefinition="Everywhere"/> Next, add the following section anywhere within your configuration file (outside of another section): <dcacheClient deployment="simple" localCache="false"> <hosts> <!--List of hosts --> <host name="localhost" cachePort="22233" cacheHostName="DistributedCacheService" /> </hosts> </dcacheClient> You might need to change one value here. This section lists one cache host with the name localhost. In other words, the MVC application will contact the cache server on the local computer. If the cache server is located somewhere else on your network, you’ll need to change name to point at the right server. Adding and Retrieving Items from the Cache Using the Velocity distributed cache is very similar to using the normal ASP.NET cache. You can use the following methods to add, retrieve, and remove items from the distributed cache: · Add() – Adds a new item to the distributed cache. If an item with the same key already exists then an exception is thrown. · Get() – Gets an item with a certain key from the distributed cache. · Put () – Adds a new item to the distributed cache. If an item with the same key already exists then the item is replaced. · Remove() – Removes an existing item from the distributed cache. Let’s look at a concrete sample. The MVC controller in Listing 1 uses the distributed cache to cache a set of Movie database records. Listing 1 – HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.Caching; using Tip39.Models; using System.Diagnostics; using System.Web.Configuration; using System.Web.Hosting; using System.Data.Linq.Mapping; using System.Data.Linq; namespace Tip39.Controllers { [HandleError] public class HomeController : Controller { private DataContext _dataContext; private Table<Movie> _table; public HomeController() { // Get connection string var conString = WebConfigurationManager.ConnectionStrings["Movies"].ConnectionString; // Get XML mapping source var url = HostingEnvironment.MapPath("~/Models/Movie.xml"); var xmlMap = XmlMappingSource.FromUrl(url); // Create data context _dataContext = new DataContext(conString, xmlMap); _table = _dataContext.GetTable<Movie>(); } public ActionResult Index() { // Try to get movies from cache var factory = new CacheFactory(); var cache = factory.GetCache("default"); var movies = (List<Movie>)cache.Get("movies"); // If fail, get movies from db if (movies != null) { Debug.WriteLine("Got movies from cache"); } else { movies = (from m in _table select m).ToList(); cache.Put("movies", movies); Debug.WriteLine("Got movies from db"); } // Display movies in view return View("Index", movies); } } } The Index() method returns all of the rows from the movies database table. First, the method attempts to retrieve the records from the cache. If that fails, the records are retrieved from the database and added to the cache. The Index() method calls Debug.WriteLine() to write messages to the Visual Studio Console window. When the records are retrieved from the distributed cache, this fact is reported. When the records are retrieved from the database, this fact is also reported (see Figure 2). Figure 2 – Using the Visual Studio Console to track cache activities You also can use the Velocity Administration Tool to monitor the distributed cache. Executing the following command displays statistics on the distributed cache: show hoststats server name:22233 Replace server name with the name of your cache server (unfortunately, localhost does not work). When you run this command, you get super valuable statistics on the number of items in the cache, the size of the cache, the number of times a request has been made against the cache, and so on (see Figure 3). Figure 3 – Cache Statistics The Index() method in Listing 1 first creates an instance of the CacheFactory class. The CacheFactory class is used to retrieve a particular cache from the distributed cache. Velocity can host multiple named caches. You can group different data into different caches. Think of each named cache like a separate database. When you first install Velocity, you get one named cache named “default”. In Listing 1, the CacheFactory is used to retrieve the “default” cache. Next, the Cache.Get() method is used to retrieve the movie database records from the cache. The first time the Index() method is invoked, the Get() method won’t return anything because there won’t be any data in the distributed cache. If the Get() method fails to return any database records from the cache then the records are retrieved from the actual database. The records are added to the distributed cache with the help of the Put() method. Notice that the Cache stores and retrieves items as untyped objects. You must cast items retrieved from the cache to a particular type before using the items in your code. Most likely, when using the distributed cache in a production application, you’ll create a strongly typed wrapper class around the distributed cache. Also, be aware that the distributed cache survives across Visual Studio project rebuilds. If you want to clear the distributed class while developing an application that interacts with the cache, execute this sequence of commands from the Velocity Administration Tool: stop cluster start cluster What can be Cached? You can add any serializable class to the distributed cache. That means that you can add any class that is marked with the [Serializable] attribute (all of the dependent classes of a serializable class must also be serializable). The Home controller in Listing 1 uses LINQ to SQL to grab database records from the database. You must be careful when using LINQ to SQL with the distributed cache since, depending on how you create your LINQ to SQL classes, the classes won’t be serializable. If you use the Object Relational Designer to generate your LINQ to SQL classes then your LINQ to SQL classes will not be serializable. To work around this problem, I built my LINQ to SQL classes by hand. The Movie.cs class is contained in Listing 2. Listing 2 – ModelsMovie.cs using System; namespace Tip39.Models { [Serializable] public class Movie { public int Id { get; set; } public string Title { get; set; } public string Director { get; set; } public DateTime DateReleased { get; set; } } } Notice that the Movie class includes a [Serializable] attribute. The XML mapping file in Listing 3 is used in the HomeController constructor to initialize the LINQ to SQL DataContext. This XML mapping file maps the Movie class and its properties to the Movies table and its columns. Listing 3 – ModelsMovie.xml <?xml version="1.0" encoding="utf-8" ?> <Database Name="MoviesDB" xmlns=""> <Table Name="Movies" Member="Tip39.Models.Movie"> <Type Name="Tip39.Models.Movie"> <Column Name="Id" Member="Id" IsPrimaryKey="true" IsDbGenerated="true"/> <Column Name="Title" Member="Title" /> <Column Name="Director" Member="Director" /> <Column Name="DateReleased" Member="DateReleased" /> </Type> </Table> </Database> One other warning about using LINQ to SQL with the distributed cache. Realize that a LINQ to SQL query is not actually executed against the database until you start iterating through the query results. Make sure that you add the results of a LINQ to SQL query, instead of the query itself, to the cache. In the Index() method in Listing 1, the movie records are added to the cache with the following two lines of code: movies = (from m in _table select m).ToList(); cache.Put("movies", movies); Notice that the ToList() method is called on the LINQ to SQL query. Calling the ToList() method forces the query to be executed against the database so that the actual results are assigned to the movies variable instead of the LINQ to SQL query expression. Using Velocity as a Session State Provider By default, the ASP.NET framework stores session state in the same process as your ASP.NET MVC application. Storing session state in-process provides you with the best performance. However, this option has one huge drawback. You can’t host your ASP.NET MC application on multiple web servers when using in-process session state. The ASP.NET framework provides you with two alternatives to in-process session state. You can store your session state information with a state server (a Windows service) hosted on a machine in your network. Or, you can store your session state information in a SQL Server database. Both of these options enable you to create a central session state server so that you can scale your ASP.NET MVC application up to use multiple web servers. There are disadvantages associated with using either the state server or the SQL Server approach to storing session state. The first option, the state server approach, is not very fault tolerant. The second option, the SQL Server option, is not very fast (each request made against your MVC application causes a database query to be executed to retrieve session state for the current user). Velocity provides you with a better option for storing out-of-process session state. You can store your state information in the Velocity distributed cache. Unlike the state server approach, the distributed cache is fault tolerant. Unlike the SQL Server approach, the Velocity cache is entirely in-memory so it is comparatively fast. Imagine that you want to keep count of the number of times that a particular user has visited a web page (see Figure 4). You can store a count of visits in session state. The Counter controller in Listing 4 maintains a count of visits with an item in session state named count. Figure 4 — Keeping count of page views Listing 4 – CounterController.cs using System.Web.Mvc; namespace Tip39.Controllers { public class CounterController : Controller { public ActionResult Index() { var count = (int?)Session["count"] ?? 0; count++; Session["count"] = count; return View("Index", count); } } } By default, the Counter controller will use in-process session state. If we want to use the Velocity session state store then we need to modify our web configuration (web.config) file. You need to add the <sessionState> information in Listing 5 within the <system.web> section. Listing 5 – Session Configuration for Velocity <sessionState mode="Custom" customProvider="dcache"> <providers> <add name="dcache" type="System.Data.Caching.SessionStoreProvider"/> </providers> </sessionState> After you make this change to the web configuration file, session state information is stored in the distributed cache instead of in-process. You can verify that the Counter controller is using the distributed cache by using the Velocity Administration Tool. Executing the following command will display how many times the distributed cache has been accessed: show hoststats server name:22233 Each time the Counter controller Index() action method is invoked, the Total Requests statistic is incremented by two: once for reading from session state and once for writing to session state. See Figure 5. Figure 5 – Seeing Total Requests Notice that you can start using the Velocity session state store without changing a single line of code in your existing application. You can switch session state providers entirely within the web configuration file. This means that you can initially build your application to use in-process session state and switch to the Velocity session state provider in the future without experiencing a single tingle of pain. Summary In this tip, I’ve provided you with a brief introduction to the Velocity distributed cache. I demonstrated how you can use the distributed cache in the context of an ASP.NET MVC application to store database records across multiple requests. I also showed you how to take advantage of the Velocity session state provider to store session state in the distributed cache. In this tip, I’ve only provided the most basic introduction to Velocity. There are many features of Velocity that I have not discussed. For example, Velocity supports a locking mechanism. You can use either optimistic or pessimistic locking when working with Velocity to prevent concurrency violations. You also can use Velocity to tag and search items that you add to the cache. Even though this was a brief introduction, I hope that I have provided enough detail to prompt you to experiment with Velocity in your ASP.NET MVC applications. No numbers? (performance wise) You made the comment, “each time you retrieve an item from session state causes a database query to be executed”. This is not true. For session state the entire session is loaded when the application event AcquireRequestState is raised. When the application event ReleaseRequestState, the session state is persisted (if dirty). The main performance issue with SQL Server session state is that the entire session is loaded on every request even if not referenced. That is why on the Page directive you can add EnableSessionState=”false”. I think you may have gotten confused with the profile provider which will load profile properties on demand. For each property you reference, it will perform a round trip to the database. @Phil – Thanks for the correction, you are absolutely right. I misspoke. ggh Very well done Stephen. In a world of regergitated (and resyndicated) content, you manage to remain fresh. I’ve been very interested in Velocity for a little while now for non-web applications… I didn’t realize how easily it snapped into ASP.NET (I should have figured). Thanks again for another great post. -Timothy Isn’t the one file share a single point of failure. If high availability is important, where can you put the configuration file so that if you lose the server that is sharing the file, you won’t lose the cache? @High Availability – Yes, the file share is a single point of failure. The docs hint that this is something that will change before the final release. I found this great Linq to SQL serializer class here on codeproject.com sql.codeproject.com/…/linqsqlserialization.aspx For those who wish to serialize their linqSQL classes and use them in web services etc etc. Would be great for this project as well @dswatik – That’s a really interesting article. Thanks for the reference to it. hopefully velocity ctp2 will be faster then it runs with ctp 1. my tests shown me that memcache is almoast 3 times faster. it was mentioned before, how does this belong to MVC actually? thank you for the “tip” though Great post! One learns a lot from this post. I write a blog on ASP.NET Cache and found your article quite useful. Keep up the good work! Velocity maybe a promising prospect but for now it is only in its CTP phase. Why not take a look at NCache and others while we wait? By their own admission Velocity is in its infancy and has a long way to go before it can challenge the prevalent solutions. I still not understand.. now i can see diferrent reading from database and cache..so thanks a lot. I’ve a question on the performance, , I found it will be 400 times comparing with system.web.cache, is it true? Ya really very useful information is given. Its really very helpful for MVC developers. NFD SD F RW W Great article, though – thanks! bh It looks like DataContextExtensions.cs line 45 of the Save method should pass the primaryKeyName through to Update. Nice Great Articles! Real helpful for new MVC starters Thanks thank you for sharing such a beautiful articles, Keep it up3
http://stephenwalther.com/archive/2008/08/28/asp-net-mvc-tip-39-use-the-velocity-distributed-cache
CC-MAIN-2014-42
refinedweb
3,622
57.77
In part one of the "ASP.NET for PHP Developers" tutorial, we learned the basics of ASP.NET and the C# language. Part two builds on that foundation, and introduces some more advanced features and techniques to take your ASP.NET pages to the next level. Before you Start... Ensure you have read and completed the examples in part 1 of the tutorial. We'll be building on that application here. It's also worth stressing that you need a good grasp of object oriented programming (OOP) to continue. And Before I Start... I mentioned in part 1 of the tutorial that there are two flavours of ASP.NET available: - ASP.NET WebForms: the original framework allowing developers to create web applications using many of the same techniques used in .NET Windows desktop applications - ASP.NET MVC: a newer framework offering Model-View-Controller architecture and more control over client-side code However I don't use either of those, but rather a third approach of my own devising. That's for several reasons: - When I started writing serious ASP.NET applications I retained my high standards of HTML output learned when writing PHP. If the page didn't validate I felt dirty. There are a lot of developers who feel the same. ASP.NET WebForms gave, at the time, awful markup for many of the standard controls, so I had to come up with another solution. Adding runat="server"to HTML elements offered many of the advantages of true ASP.NET controls, but gave me full control over the HTML that was outputted. Things improved, and are looking even better for ASP.NET 4.0. - I saw lots of examples of ASP.NET code where it was obvious the developer didn't care about the resulting HTML. Perhaps they were Windows desktop application developers making the jump to the web, maybe they had never hand-coded HTML. Whatever the reason, I determined I would not be one of them. - Quite a few of the standard ASP.NET controls relied entirely on JavaScript which is, to be frank, unforgivable for public websites (in the UK web accessibility is a legal requirement). For example, the evil javascript:__doPostBackfunction is a perfect way to make your website impossible to use for a large proportion of the web audience - oh, and search engines as well. - I wanted to use my own choice of JavaScript library (initially Prototype, but then jQuery, now officially supported by ASP.NET). If I had to use the ASP.NET framework JavaScript library it would have made that more difficult. - So why not ASP.NET MVC? Well, it wasn't around when I started writing ASP.NET applications, and even if it was it would have been another hurdle to jump to get anything to work. Learning the .Net framework and C# language was challenging enough! So you can see why I chose this "roll-your-own" approach. As ASP.NET matured and I discovered new features, I started to integrate those into my applications, and I fully expect that over time I'll be doing more of that. So, let's take our ASP.NET application to the next level. Master Pages My second favourite feature of ASP.NET (after turning HTML controls into server controls) is master pages. A master page is a template file you can use to encapsulate HTML you use in multiple pages. For example, your master page could contain the header, menu and footer of your pages, while your normal .aspx pages contain the actual content on that page. let's look at an example web page: You can see the parts which are used on multiple pages highlighted in green. The content which changes for each page in the site is highlighted in red. Master pages allow us to split up the code for these two sections into multiple files. If you've used templates in your PHP applications (for example Wordpress has header.php, footer.php and sidebar.php) you'll see how great master pages are. Creating a master page So let's create a master page. In the Solution view create a new directory in your ASP.NET application called "Master_Pages". In that directory create a new master page by right-clicking on the Master_Pages folder, selecting "Add > New file" then selecting "Master Page with Code Behind" and call it "DefaultMaster". Your new master page will be created and you'll see the "DefaultMaster.master", "DefaultMaster.master.cs" and "DefaultMaster.master.designer.cs" files in the Master_Pages folder. Open the "DefaultMaster.master" and "DefaultMaster.master.cs" files. The code-behind file (.cs) for the master page (.master) works exactly the same as the code-behind file for an .aspx page. The first thing to note is master pages do not inherit from System.Web.UI.Page like .aspx pages do. Instead they inherit from System.Web.UI.MasterPage. Here's the default code for the code-behind. using System; using System.Web; using System.Web.UI; namespace WebApplication1 { public partial class DefaultMaster : System.Web.UI.MasterPage { } } And for the .master file itself: <%@ Master <html> <head> <title>DefaultMaster</title> </head> <body> <div id="container"> <form runat="server"> <asp:contentplaceholder </form> </div> </body> </html> Because we're not using the WebForms model, let's quickly remove the tags for the <form runat="server"> element. You should be getting used to page declarations (the <%@ Page ... %> bit in .aspx pages) by now, so the <%@ Master ... %> declaration will come as no surprise. What is different in this code is a new control: <asp:contentplaceholder>. <asp:contentplaceholder This content placeholder is where the content from your .aspx pages will be inserted. You can have as many of these in a .master page as you like. Referencing your master page Let's go back to our normal .aspx page and make some edits. The first thing to do is remove the <html>, <head> and <body> tags, as they will now be in the master page. That leaves: <%@ PageThis is the text</h1> Now we need to specify what content to place in the content placeholder. We do that by specifying where the master page is, and wrapping our content in an asp:Content control, like this: <%@ Page <h1 id="headertext" runat="server">This is the text</h1> </asp:Content> There's a couple of things to note here. Firstly the Page declaration has an additional attribute of "MasterPageFile" with a value of "~/Master_Pages/DefaultMaster.master". In ASP.NET "~" means the root of the application, the rest of that path just points to our master page. Secondly you see the new asp:Content control has an attribute of "ContentPlaceHolderID" with a value of "contentPlaceHolder", which is the "id" attribute of our <asp:contentplaceholder>. Running the application will give you: Checking the source code of the page proves that the master page (.master) and content page (.aspx) have been seamlessly integrated together. Now you see why I love master pages so much. A more complex master page We can push master pages a lot further than this simple example. Let's have a go at building something that looks more like a real web application, starting with the master page. Firstly we'll add some more content placeholders and a few server-side controls: <%@ Master <html> <head> <title><asp:contentplaceholder</title> <script src="scripts/jquery.min.js"></script> <asp:contentplaceholder <link rel="stylesheet" href="styles/default.css"></link> <asp:contentplaceholder </head> <body> <div id="container"> <h1 id="sitename" runat="server"></h1> <ul id="menu"> <li><a href="about.aspx">About me</a></li> <li><a href="services.aspx">My services</a></li> <li><a href="contact.aspx">Contact me</a></li> </ul> <div id="content"> <asp:contentplaceholder </div> <div id="footer"> <p id="copyright" runat="server"></p> </div> </div> </body> </html> And in the code-behind file for our master page we'll put: using System; using System.Web; using System.Web.UI; using System.Configuration; namespace WebApplication1 { public partial class DefaultMaster : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { sitename.InnerHtml = ConfigurationSettings.AppSettings["SiteName"]; copyright.InnerHtml = ConfigurationSettings.AppSettings["CopyrightNotice"] + DateTime.Now.Year.ToString(); } } } (I'll leave it as an exercise for you to add the SiteName and CopyrightNotice applications settings to web.config.) Now for our content page. We have four content placeholders we can use: PageTitle, PageJS, PageCSS and PageContent. Here's the code for the .aspx content page: <%@ Page <asp:Literal</asp:Literal> </asp:Content> <asp:Content <style type="text/css"> h1 { font-family: sans-serif; color: #090; } </style> </asp:Content> <asp:Content <h2>Welcome, one and all</h2> <p>This is my very first ASP.NET website, working with a master page!</p> </asp:Content> And the code-behind for our .aspx content page: using System; using System.Web; using System.Web.UI; using System.Configuration; namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Title.Text = "Welcome to my first ASP.NET Website"; } } } A couple of new things to notice here. Firstly I haven't used the PageJS content placeholder at all - it's quite OK to leave it out entirely (of course nothing will be rendered to the page for that area). Secondly I've introduced another ASP.NET control, namely <asp:Literal>, which we'll take a quick look at now. The Literal control The Literal control is very useful when you want to render something to the page without any extra markup. For example, a lot of the time it's fine to use: <span id="message" runat="server"></span> message.InnerHtml = "This is the message" Gives: <span id="message">This is the message</span> But if you don't want the span tags at all, for example for the page <title>, you need the Literal control. Setting the "Text" property of the Literal control renders just that text to the page: <asp:Literal</asp:Literal> message.Text = "This is the message"; Gives: This is the message The completed master and content page So running our application should give us this: This is really just scratching the surface, as it's possible to have multiple master pages (even nested master pages!). You can also set the master page programatically (but this needs to be done in the Page_Init event, as Page_Load is too late in the page lifecycle). There's lots more detail about MasterPages on the MSDN site. Custom Classes It's possible to create custom classes in your application, just like you would in PHP. Let's create a security class by right-clicking the root of your application and selecting "Add > New file" then choosing "Empty class" from the "General" section and calling it "Security". The code for your new class looks like this: using System; namespace WebApplication1 { public class Security { public Security() { } } } I'll throw a bit more code into this file: using System; using System.Web; namespace WebApplication1 { public class Security { public bool IsLoggedIn; public Security() { CheckSession(); } private void CheckSession() { if (HttpContext.Current.Session["loggedin"] != null && HttpContext.Current.Session["loggedin"] == "true") { IsLoggedIn = true; } else { IsLoggedIn = false; } } } } Pretty simple so far. The only new thing is the use of HttpContext.Current.Session rather than just Session, that's because HttpContext.Current is implicit in an .aspx web page, but not in a standalone class. In our Default.aspx.cs code-behind file we write: protected void Page_Load(object sender, EventArgs e) { Security security = new Security(); if (security.IsLoggedIn) { Title.Text = "Welcome back, you are logged in"; } else { Title.Text = "You are not logged in"; } } Which instantiates a new instance of the Security class names "security". Running the application shows this: As you're familiar with OOP you can see how this can be used to build large-scale web applications. The only other thing to say about custom classes is how to make them static. Here's the code for a static class: using System; using System.Web; namespace WebApplication1 { public static class Security { public static bool IsLoggedIn; public static void CheckSession() { if (HttpContext.Current.Session["loggedin"] != null && HttpContext.Current.Session["loggedin"] == "true") { IsLoggedIn = true; } else { IsLoggedIn = false; } } } } You can see there's no default method, as this class is never instantiated. I've also added the "static" keyword to the property and method, and I've made the CheckSession() method public. To use this static class we would write: protected void Page_Load(object sender, EventArgs e) { Security.CheckSession(); if (Security.IsLoggedIn) { Title.Text = "Welcome back, you are logged in"; } else { Title.Text = "You are not logged in"; } } Pretty simple, really. As you're fully aware of the advantages that OOP can give you for abstraction, encapsulation and inheritance you'll see how powerful this is. But if we're going to use objects, we really need some serious data to model in our objects. We need a database. Databases, Data Sources and Data Binding ASP.NET works really well with databases, but works the best with Microsoft SQL Server (not surprisingly). Even if your ASP.NET application is running on a Linux box, you can still connect to SQL Server on a Windows server to use as a datastore. I'll demonstrate that below, but as I'm writing this tutorial in Linux I will also demonstrate the use of MySQL as an ASP.NET database. To use MySQL you'll need the ADO.NET driver for MySQL - this excellent article helped me a lot. Database configuration The first thing to do is configure how to connect to our database server. You can do this in web.config, add this code inside the "configuration" section (the MySQL and SQL Server code should be pretty obvious). Note that these are standard connection strings. <connectionStrings> <add name="MySQL" connectionString="Server=mysqlserver;Database=aspnetdb1;User ID=root;Password=mypassword;Pooling=false"/> <add name="SQLServer" connectionString="Server=sqlserver;Database=aspnetdb1;User ID=sa;Password=myPassword;"/> </connectionStrings> I've also created a table called "users" with this code (this is for MySQL, minor edits will make it work in most other database systems): CREATE TABLE users ( id int NOT NULL AUTO_INCREMENT, username varchar(50) NOT NULL, password varchar(32) NOT NULL, email varchar(255) NOT NULL, PRIMARY KEY (id) ); To access your connection string you can use the ConfigurationManager class which we used in part 1 of the tutorial to access global configuration settings. Here's the code: string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString; Connecting and running a simple query So we're now ready to connect to our database and run a query. First, insert a couple of rows into the " users" table so we have something to query: insert into users (username, password, email) values ('User 1', 'user1password', 'user1@asp.net') We then need to ensure we reference the right assemblies. For MySQL make sure you have this at the top of your code-behind file: using System.Data; using MySql.Data.MySqlClient; Amd for SQL Server use this: using System.Data; using System.Data.SqlClient; A quick note about connecting to MySQL in Linux. I had a bit of trouble making my application compile when I first tried this. I did various searches but found no answer that worked for me. The error I got was "The type or namespace name `MySqlConnection' could not be found." which looked like the MySQL Connector wasn't installed properly. The fix (for me) was to manually add the reference by right-clicking the References folder in my application and going to "Edit references". I then found the MySQL.Data.dll file in the .Net Assembly tab and referenced it. I also had to then manually reference the System.Data and System.Configuration assemblies from the Packages tab. Hopefully you won't need to jump through these hoops. We now open a connection to our database like this for MySQL:"); } } And this for SQL Server: protected void Page_Load(object sender, EventArgs e) { // get the connection string string conn = ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString; // create a new SQL Server connection SqlConnection dbcon; using (dbcon = new SqlConnection(conn)) { // open the connection dbcon.Open(); // create the query string query = "SELECT username, email FROM users"; // create a new adapter between the connection and query SqlDataAdapter adapter = new SqlDataAdapter(query, dbcon); // create a new dataset to store the query results DataSet ds = new DataSet(); // fill the dataset with the results from the adapter, // the name of the dataset is "result" adapter.Fill(ds, "result"); } } See, pretty easy, and not a million miles away from the equivalent PHP code. There are a couple of bits in here I'll explain in some more depth. Firstly the using statement: using (something here) { ... } The object you set up in the brackets is automatically destroyed when your code leaves the end curly brace "}". This is a really useful structure to know about, so read all about it here. Secondly the DataSet. In the code above the results from the database query are fed into a DataSet, which is an object containing one or more tables, each table containing rows and columns. That means you can do useful things like: DataSet ds = new DataSet(); // we put some data from the database in the DataSet here... // get the number of tables int tables = ds.Tables.Count; // get the first table DataTable dt = ds.Tables[0]; // get the number of rows in the first table int rows = ds.Tables[0].Rows.Count; And there are many other goodies in the DataSet class. You can also loop rows, just like you do in PHP, like this: for (int x = 0; x < ds.Tables[0].Rows.Count; x++) { Response.Write(ds.Tables[0].Rows[x]["fieldname"].ToString() + <br />); } But there's a much better way to display simple loops, and that's using the Repeater control. Using repeaters and databinding First a confession. There are large ASP.NET applications I've written that use no ASP.NET controls except the Literal (which we looked at above) and the Repeater. The Repeater control allows you to "bind" data, for example from a DataSet, and display it in a looped manner. Firstly we need to add something to our database code above:"); // below is the new code... // set the DataSource of the repeater myRepeater.DataSource = ds; // bind the data myRepeater.DataBind(); } } And in the .aspx page we put: <asp:Repeater <HeaderTemplate> <table> <tr> <th>Username</th> <th>Email</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><%# Eval("username") %></td> <td><%# Eval("email") %></td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr class="alt"> <td><%# Eval("username") %></td> <td><%# Eval("email") %></td> </tr> </AlternatingItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> You can see what happens here. When the data is bound to the Repeater control the HeaderTemplate section is displayed. Then each row is displayed in the ItemTemplate and AlternatingItemTemplate sections (the names should give you a clue how they are displayed). Then finally the FooterTemplate section is displayed. Using this simple control gives you an easy way to display repeating data, with complete control over the resulting HTML - just like you would do in PHP. Here's the results (with some CSS for styling): As a Repeater will throw an Exception if an empty DataSet is bound to it, you need to check there is data to be bound first. A simple if statement will work, checking if there are tables in the DataSet and if the first table has rows: if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { myRepeater.DataSource = ds; myRepeater.DataBind(); } I think you'll agree that having a control which sets templating for repeating data as easily as that is a massive help to the developer. One thing to note with the Repeater control - if you bind a DataSet to it by default the first table is used. If you're using stored procedures instead of inline SQL to run commands against your database you can return multiple tables, meaning you can load several sets of data for use in a page at once. In that case you'd use code like this (to bind the second table in the DataSet to the Repeater): myRepeater.DataSource = ds.Tables[1]; myRepeater.DataBind(); Creating a data access class Let's pull the last couple of sections together and create a data access class that will simplify connecting to and running commands on your database. This code is for MySQL, but as you've seen the code for SQL Server is very similar. Create a new empty class called "DB" and paste this into the new file: using System; using System.Configuration; using System.Data; using MySql.Data.MySqlClient; namespace WebApplication1 { public class DB { private string ConnectionString; public DB() { // get the connection string this.ConnectionString = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString; } public DataSet Select(string query) { MySqlConnection dbcon; using (dbcon = new MySqlConnection(this.ConnectionString)) { // open the connection dbcon.Open(); // create a new adapter between the connection and query MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon); // create a new dataset to store the query results DataSet ds = new DataSet(); // fill the dataset with the results from the adapter, adapter.Fill(ds, "result"); // return the dataset return ds; } } public bool Execute(string query) { MySqlConnection dbcon; using (dbcon = new MySqlConnection(this.ConnectionString)) { // create a new SQL command on thie connection MySqlCommand command = new MySqlCommand(query, dbcon); // open the connection dbcon.Open(); // execute the query and return the number of affected rows int affectedrows = command.ExecuteNonQuery(); // there were no rows affected - the command failed if (affectedrows == 0) { return false; // the command affected at least one row } else { return true; } } } } } To use this in your code-behind file you'd put: DB db = new DB(); DataSet ds = db.Select("SELECT username, email FROM users"); if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { myRepeater.DataSource = ds; myRepeater.DataBind(); } This data access class introduces you to a new style of database connection syntax using the MySqlCommand class (SqlCommand for SQL Server) and the ExecuteNonQuery method. As the code says, the ExecuteNonQuery method executes a query and returns the number of affected rows. Very useful for INSERT, UPDATE and DELETE commands. Those of you with a good knowledge of Wordpress will see how this class is similar to the $wpdb global class in WP which offers methods like $wpdb->get_results("select * from table"); and $wpdb->query("delete * from table");. It would be easy for you to extend this data access class to have more useful properties and methods for your applications. User Controls So far we've used just two ASP.NET controls - Literal and Repeater - in honour of our aim to keep full control of the output HTML. But sometimes it's useful to encapsulate functionality for your own controls. ASP.NET allows you to create user controls with properties and methods all your own. These user controls can be thought of as discrete blocks of HTML that can be used inside a .aspx page, just like you'd include a separate file in a .php file. We're going to create a very simple control that displays a truncated link. Firstly add a new file of type "User control with code-behind file" and call it "ShortLink". You may notice the new file has an extension of .ascx, this is the extension for user controls. Open the .ascx file and you'll see this: <%@ Control Language="C#" Inherits="WebApplication1.ShortLink" %> Open the code-behind file (MyControl.ascx.cs) and you'll see this: using System; using System.Web; using System.Web.UI; namespace WebApplication1 { public partial class MyControl : System.Web.UI.UserControl { } } Now we're ready to create our user control. Paste this code into the .ascx.cs (code-behind) file (I won't explain this code, it's simple enough): using System; using System.Web; using System.Web.UI; namespace WebApplication1 { public partial class ShortLink : System.Web.UI.UserControl { public string Link; protected void Page_Load(object sender, EventArgs e) { // set the href attribute theLink.Attributes["href"] = Link; // declare the short link, replacing protocols string shortlink = Link.Replace("http://", "").Replace("https://", ""); // if the link is longer than 15 characters if (shortlink.Length > 15) { // show the first 6 and last 6 characters theLink.InnerHtml = shortlink.Substring(0, 6) + "..." + shortlink.Substring(shortlink.Length-6); } else { // show the full link theLink.InnerHtml = shortlink; } } } } Yes, user controls use the same Page_Load event handler that normal .aspx pages use. Now open the .ascx file and paste this into it: <%@ Control</a> Here you can see instead of a Page declaration we have a Control declaration, but the same Inherits property to bind it to the code-behind file. We also have a standard <a> element with the runat="server" property to make it a server-side control. To use this control in your page simply register a tag prefix (this can be anything) at the top of the page like this: <%@ Page Language="C#" MasterPageFile="~/Master_Pages/DefaultMaster.master" Inherits="WebApplication1.Default" %> <%@ Register TagPrefix="My" TagName="ShortLink" Src="ShortLink.ascx" %> Then use the control wherever you want to. To demonstrate this control I'm using two instances of it: <p><My:ShortLink</My:ShortLink></p> <p><My:ShortLink</My:ShortLink></p> The TagPrefix property is the first part of the control tag and the TagName the second part, separated by ":" - My:ShortLink. And this is the result: Here you can see that the public string property I declared in my ShortCode user control class ( public string Link;) can be set in a Link property of the control. You can have any number of properties and they can be of any type. You can only set string types in the control tag itself (i.e Link=""), as you can set the properties programatically from your code-behind file (like Link1.DatasetProperty = new DataSet();). There's one bit of code here which needs a little more explanation. Using a custom tag prefix Your user controls need to have their own tag prefix. In our example above this is "My", but of course it can be any simple string. In the example above the tag prefix was registered, so ASP.NET knew what to do when it encountered it, using a declaration at the top of the page: <%@ Register TagPrefix="My" TagName="ShortLink" Src="ShortLink.ascx" %> However it's possible to register your tag prefixes in your web.config file, so you don't have to do it on every page (as explained by Scott Guthrie - that's one blog you'll want to follow). Here's how, but before you rush in watch out for the error I got: Parser Error Message: The page '/Default.aspx' cannot use the user control '/ShortLink.ascx', because it is registered in web.config and lives in the same directory as the page. So put your user controls in a subfolder, for example "Controls". <?xml version="1.0"?> <configuration> <system.web> <pages> <controls> <add tagPrefix="My" src="~/Controls/ShortLink.ascx" tagName="ShortLink"/> </controls> </pages> </system.web> </configuration> You'll now want to put user controls everywhere. And the best thing about user controls is, because they are just like pages (without <html>, <head> and <body> tags) you can put anything you like in them. In fact it would be possible to write an entire application in user controls, including the relevent controls in your page depending on some parameters passed to it. Amazing. Compiling and Deploying As mentioned in part 1 of the tutorial, C# is a compiled language. Rather than PHP, which is compiled into language the computer can understand at runtime, C# is pre-compiled (or sometimes compiled on first run) and saved in assemblies for the computer to process. This means that C# is faster (yes, it's true, sorry), and that you can catch a lot of errors in your code *before* you try to run it. You've already seen that happening when we discussed errors above. However, it means you can't just drop your ASP.NET application on a server and expect it to run. It also means you can't do live hacking of your code-behind files in a running application. Deployment needs to be approached a little more methodically than in PHP. There are several other articles which do a much better job at explaining this than I would so I'll just link to them. Next Steps Hopefully between part 1 and this tutorial, you now have a much better idea of what ASP.NET is, and the advantages it can provide for developers. For further reading, you can check out some of my favourite places: - The official Microsoft ASP.NET site - Scott Guthrie's blog - Chris Love's blog - ASPAlliance.com - 15seconds.com - Elijah Manor's Twitter feed Finally, good luck!. I hope that you can do the same. - Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post Envato Market has a range of items for sale to help get you started.
http://code.tutsplus.com/tutorials/aspnet-for-php-developers-part-2--net-9429
CC-MAIN-2016-22
refinedweb
4,837
58.08
I am a beginner in python. I just installed a external packge in python 2.7 with setup.py. so when i type help(package1) i can see its help and installed But i am not able to use the functions in that package..can some one help me with it. Following are my questions 1. This is how my directory look like packag1>A B C D _init.py so my init.py looks like - Code: Select all import A import B import C import D __all__=["A", "B", "C", "D"] now when i go in directort A , I have three files __init__.py reflection.py timedepthconv.py relflection.py has many functions one of them is def oa(a,b,c,d,e)...and in __init__.py i can there is import oa with other functions.. Now my question 1.What is __init__.py file 2.How can i use function oa... I tried using import Package1 oa(1,2,3,4,5) but it says oa is not defined...I already installed the package in python then why its not recognzing the function thanks
http://www.python-forum.org/viewtopic.php?f=10&t=10531
CC-MAIN-2015-40
refinedweb
187
87.92
Update: Do read this entry, but I’ve written an update. At The Health Agency we’re currently switching to z3c.testsetup for our test setup needs. The nice thing is that you only need one test .py file that is found by your testrunner (I suggest tests/test_setup.py) with the following content: import z3c.testsetup test_suite = z3c.testsetup.register_all_tests('your.package.name') No more manual building of test suites with DocTestCases and so. Just add :doctest: to every README or .txt or docstring-in-your.py like this: .. :doctest: >>> print 4 4 For testing our libraries, simple python-level doctests are often enough. From time to time you need to call grokcore.component.grok('my.package') but that’s about it. The base package for our grok sites needs a more elaborate setup. And preferably a setup that is reusable in the grok sites that use it. Solution for more elaborate test setups: test layers. Zope.testing provides a layer mechanism. It took me some time to understand their use, but I think I’ve got it: You can tie a test to a layer. All tests that “are on the same layer” are run in one group. The layer can do setup before and after the layer’s tests are run. This means a layer is useful for setting up your zodb; an test sql database; some zcml setup. The layer can also do extra layer-specific setup/teardown for every individual test inside it. A layer that provides a zodb can thus arrange for a transaction.abort() to be done after every single test: test isolation. After an all-important from zope.app.testing.functional import FunctionalTestSetup, what my layer does is: In the setUp(), instantiate FunctionalTestSetup with our own ftesting.zcml. In the setUp(), grok a fixtures.py with a test site object, some test user folders, test adapters and so. This makes those grokked components available to every test on this layer. testSetUp() is the setup method that is called for every individual test. It calls FunctionalTestSetup’s setup that gives us a fresh clean ZODB. And it sets up a test grok site (of our own design) in the ZODB’s root. On both levels there’s the corresponding tear down method. Using layers is easy with z3c.testsetup: add a :layer: my.package.layer. One z3c.testsetup gotcha: it internally creates testcases, so it is hard to pass in globals to the testcase (unless you do it in one go for all the tests in the entire package, which wasn’t appropriate). The solution: call a setup method by adding :setup: my.package.globsetup to your doctest. globsetup(test) can append to the test.globs dictionary. I found it a bit dirty at first, but after using it for a while it smells OK. You set the globs explicitly in those doctests where you need it. In every doctest, it is clear which extra setup methods are called and thus it is easy to look up that method to see which globals are available. An alternative to this setup call is of course to do an from my.package.globs import * or something like that. Which seems a bit cleaner. Time for some experimentation. Oh, if someone knows how to set the globs from within a layer: please mail me. Comment by Jasper: grok < 1.0a4 contain z3c.testsetup 0.2.1, so make sure you pin it to a more recent release like):
https://reinout.vanrees.org/weblog/2009/05/18/test-setup.html
CC-MAIN-2022-21
refinedweb
582
69.38
import "firebase.google.com/go" Package firebase is the entry point to the Firebase Admin SDK. It provides functionality for initializing App instances, which serve as the central entities that provide access to various other Firebase services exposed from the SDK. Version of the Firebase Go Admin SDK. An App holds configuration and state common to all Firebase services that are exposed from the SDK. NewApp creates a new App from the provided config and client options. If the client options contain a valid credential (a service account file, a refresh token file or an oauth2.TokenSource) the App will be authenticated using that credential. Otherwise, NewApp attempts to authenticate the App with Google application default credentials. If `config` is nil, the SDK will attempt to load the config options from the `FIREBASE_CONFIG` environment variable. If the value in it starts with a `{` it is parsed as a JSON object, otherwise it is assumed to be the name of the JSON file containing the options. Auth returns an instance of auth.Client. Database returns an instance of db.Client to interact with the default Firebase Database configured via Config.DatabaseURL. DatabaseWithURL returns an instance of db.Client to interact with the Firebase Database identified by the given URL. Firestore returns a new firestore.Client instance from the package. InstanceID returns an instance of iid.Client. Messaging returns an instance of messaging.Client. Storage returns a new instance of storage.Client. type Config struct { AuthOverride *map[string]interface{} `json:"databaseAuthVariableOverride"` DatabaseURL string `json:"databaseURL"` ProjectID string `json:"projectId"` ServiceAccountID string `json:"serviceAccountId"` StorageBucket string `json:"storageBucket"` } Config represents the configuration used to initialize an App. Package firebase imports 15 packages (graph) and is imported by 18 packages. Updated 2018-12-06. Refresh now. Tools for package owners.
https://godoc.org/firebase.google.com/go
CC-MAIN-2018-51
refinedweb
296
50.84
Nested JSX elements In order for the code to compile, a JSX expression must have exactly one outermost element. In the below block of code the <a> tag is the outermost element. const myClasses = ( <a href=""> <h1> Sign Up! </h1> </a> ); JSX Syntax and JavaScript JSX is a syntax extension of JavaScript. It’s used to create DOM elements which are then rendered in the React DOM. A JavaScript file containing JSX will have to be compiled before it reaches a web browser. The code block shows some example JavaScript code that will need to be compiled. import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render(<h1>Render me!</h1>, document.getElementById('app')); Multiline JSX Expression A JSX expression that spans multiple lines must be wrapped in parentheses: ( and ). In the example code, we see the opening parentheses on the same line as the constant declaration, before the JSX expression begins. We see the closing parentheses on the line following the end of the JSX expression. const myList = ( <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> ); JSX syntax and HTML In the block of code we see the similarities between JSX syntax and HTML: they both use the angle bracket opening and closing tags ( <h1> and </h1>). When used in a React component, JSX will be rendered as HTML in the browser. const title = <h1>Welcome all!</h1> JSX attributes The syntax of JSX attributes closely resembles that of HTML attributes. In the block of code, inside of the opening tag of the <h1> JSX element, we see an id attribute with the value "example". const example = <h1 id="example">JSX Attributes</h1>; ReactDOM JavaScript library The JavaScript library react-dom, sometimes called ReactDOM, renders JSX elements to the DOM by taking a JSX expression, creating a corresponding tree of DOM nodes, and adding that tree to the DOM. The code example begins with ReactDOM.render(). The first argument is the JSX expression to be compiled and rendered and the second argument is the HTML element we want to append it to. ReactDOM.render( <h1>This is an example.</h1>, document.getElementById('app') ); Embedding JavaScript in JSX JavaScript expressions may be embedded within JSX expressions. The embedded JavaScript expression must be wrapped in curly braces. In the provided example, we are embedding the JavaScript expression 10 * 10 within the <h1> tag. When this JSX expression is rendered to the DOM, the embedded JavaScript expression is evaluated and rendered as 100 as the content of the <h1> tag. let expr = <h1>{10 * 10}</h1>; // above will be rendered as <h1>100</h1> The Virtual Dom React uses Virtual DOM, which can be thought of as a blueprint of the DOM. When any changes are made to React elements, the Virtual DOM is updated. The Virtual DOM finds the differences between it and the DOM and re-renders only the elements in the DOM that changed. This makes the Virtual DOM faster and more efficient than updating the entire DOM. JSX and conditional In JSX, && is commonly used to render an element based on a boolean condition. && works best in conditionals that will sometimes do an action, but other times do nothing at all. If the expression on the left of the && evaluates as true, then the JSX on the right of the && will be rendered. If the first expression is false, however, then the JSX to the right of the && will be ignored and not rendered. // All of the list items will display if // baby is false and age is above 25 const tasty = ( <ul> <li>Applesauce</li> { !baby && <li>Pizza</li> } { age > 15 && <li>Brussels Sprouts</li> } { age > 20 && <li>Oysters</li> } { age > 25 && <li>Grappa</li> } </ul> ); JSX className. // When rendered, this JSX expression... const heading = <h1 className="large-heading">Codecademy</h1>; // ...will be rendered as this HTML <h1 class="large-heading">Codecademy</h1> JSX conditionals JSX does not support if/else syntax in embedded JavaScript. There are three ways to express conditionals for use with JSX elements: - a ternary within curly braces in JSX - an ifstatement outside a JSX element, or - the &&operator. // Using ternary operator const headline = ( <h1> { age >= drinkingAge ? 'Buy Drink' : 'Do Teen Stuff' } </h1> ); // Using if/else outside of JSX let text; if (age >= drinkingAge) { text = 'Buy Drink' } else { text = 'Do Teen Stuff' } const headline = <h1>{ text }</h1> // Using && operator. Renders as empty div if length is 0 const unreadMessages = [ 'hello?', 'remember me!']; const update = ( <div> {unreadMessages.length > 0 && <h1> You have {unreadMessages.length} unread messages. </h1> } </div> ); Embedding JavaScript code in JSX Any text between JSX tags will be read as text content, not as JavaScript. In order for the text to be read as JavaScript, the code must be embedded between curly braces { }. <p>{ Math.random() }</p> // Above JSX will be rendered something like this: <p>0.88</p> JSX element event listeners In JSX, event listeners are specified as attributes on elements. An event listener attribute’s name should be written in camelCase, such as onClick for an onclick event, and onMouseOver for an onmouseover event. An event listener attribute’s value should be a function. Event listener functions can be declared inline or as variables and they can optionally take one argument representing the event. // Basic example const handleClick = () => alert("Hello world!"); const button = <button onClick={handleClick}>Click here</button>; // Example with event parameter const handleMouseOver = (event) => event.target.style.color = 'purple'; const button2 = <div onMouseOver={handleMouseOver}>Drag here to change color</div>; Setting JSX attribute values with embedded JavaScript When writing JSX, it’s common to set attributes using embedded JavaScript variables. const introClass = "introduction"; const introParagraph = <p className={introClass}>Hello world</p>; JSX empty elements syntax In JSX, empty elements must explicitly be closed using a closing slash at the end of their tag: <tagName />. A couple examples of empty element tags that must explicitly be closed include <br> and <img>. <br /> <img src="example_url" /> React.createElement() Creates Virtual DOM Elements The React.createElement() function is used by React to actually create virtual DOM elements from JSX. When the JSX is compiled, it is replaced by calls to React.createElement(). You usually won’t write this function yourself, but it’s useful to know about. // The following JSX... const h1 = <h1 className="header">Hello world</h1>; // ...will be compiled to the following: const h1 = React.createElement( 'h1', { className: 'header', }, 'Hello world' ); JSX key attribute In JSX elements in a list, the key attribute is used to uniquely identify individual elements. It is declared like any other attribute. Keys can help performance because they allow React to keep track of whether individual list items should be rendered, or if the order of individual items is important. <ul> <li key="key1">One</li> <li key="key2">Two</li> <li key="key3">Three</li> <li key="key4">Four</li> </ul>
https://www.codecademy.com/learn/fscp-react-part-i/modules/fecp-jsx/cheatsheet
CC-MAIN-2021-21
refinedweb
1,146
55.74
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives Hmm. No headers (<h1>, <h2>, etc.) allowed in here. Use COBOL-style level numbers to express an hierarchy of headers? 01 Semantics Ruby has mixins; Smalltalk does not. Mixins help much in design. Ruby permits adding methods to individual objects; in Smalltalk, all methods reside in classes. In Ruby, it is practical and somewhat useful to add methods dynamically; in Smalltalk, the practice is generally to treat the methods and classes as static. Ruby offers powerful macros in class definitions; Smalltalk offers no macros at all. 01 Syntax 02 Literals and Constructors and Destructors 03 Array Constructor Ruby offers a very convenient syntax for constructing an array from expressions for its elements. I think all modern Smalltalk implementations also support this, although it is relatively new in the history of the language. If a Smalltalker reading this knows of a Smalltalk implementation in commercial or wide use that doesn't support the syntax "{foo. bar. bletch}" (note that there are spaces after the periods here; these are sentence-end periods, not namespace-qualification periods) for constructing an array, equivalent to "(OrderedCollection new add: foo; add: bar; add: bletch) asArray", please add a comment to that effect. In array construction in Ruby, you can say something like "[foo, *bar]" to mean the array whose first element is given by the expression foo and the rest of whose elements are given by the array given by the expression bar. In straightforward Ruby not using the "*", this is "[foo] + bar" (+ is overloaded for concatenation in Ruby's library). In Smalltalk, it would be "(Array with: foo), bar", where the comma operator is used for concatenation in Smalltalk's library. Interestingly, the "*" syntax can also be used for destruction. You can say, for example [foo, *bar] = bletch where "=" is the assignment notation (discussed below) and bletch is an array of at least one element. Then foo will be set to the first element, and bar will be set to the rest. This example emulates Joy's "snoc" operator (cons spelled backward). See also, multiple assignment, below. Smalltalk has nothing like the conveniences offered by Ruby's prefix "*" notations. [foo, *bar] = bletch Ruby also lets you use the prefix "*" in argument lists to construct argument lists and in parameter lists to deconstruct argument lists. Perhaps as a Smalltalk advocate in regard to keyword arguments vs. positional arguments, however, I might not think this usage brings much to the party as an advantage of Ruby over Smalltalk. It does, in the Ruby context, bring something to the party, just as the equivalent construct in parameter lists in Lisp ("&REST") makes Lisp much more flexible. Who is to say whether positional parameters should be basic and keyword: value pairs should be packed up in a dictionary and passed as one of the positional arguments, or conversely, whether keyword parameters and arguments should be basic and if you want to pass a list you pack up the list as an array and pass it as one of the keyword arguments? Smalltalk takes one attitude and Ruby the other. Personally, I'm in favor of keywords. 03 Dictionary Constructor Ruby offers a very convenient syntax for constructing a dictionary (a dictionary is called a Dictionary in Smalltalk and (unfortunately) a Hash in Ruby; I'll use the term dictionary as the generic term). The constructor is short to write, and keys and values can come from any expressions. Example, "{:foo => :bar, :bletch => 3}", which in Smalltalk would be "Dictionary new at: #foo put: #bar; at: #bletch put: 3; yourself". Note how much shorter "{:foo => :bar, :bletch => 3}" is than "Dictionary new at: #foo put: #bar; at: #bletch put: 3; yourself". This leads to significant economy of writing, if you are passing around many constructed dictionaries, which in Web development, for example, tends to be done quite a bit. I'll preempt whoever is going to point out that much of the dictionary construction in Ruby is being done to overcome the lack of the keyword message call (discussed below), by saying that dictionaries have other uses than immediate use in a message call. Sometimes you would like to pack up the message and treat it as a whole. Oz/Mozart recognizes this as Ruby does (although details differ). 03 String Constructor Ruby offers a convenient syntax for constructing a string. Parts of the construct can be literal, and parts can invoke expressions for string values to be interpolated into the string under construction. Example: Ruby: "Hello, #{name}!" Smalltalk: 'Hello, ', name, '!' At first glance, the reader might not see much economy in the Ruby syntax over the example I gave in Smalltalk; however, if you are writing many constructions of strings from alternating literal and variable parts, the Ruby syntax becomes pretty convenient. I think it is less error-prone than a long sequence of concatenations given explicitly, with many literals interspersed. Moreover, experienced Smalltalkers know that abuse of the comma operator can lead to significant inefficiencies, where abuse consists of building up a long string (e. g., a report) via many concatenations. The Smalltalk library implements the comma operator inefficiently by copying over the string every time. Consequently, we get in the habit of writing an example like this this way: WriteStream new nextPutAll: 'Hello, '; nextPutAll: name; nextPutAll: '!'; contents (the semicolon is used in Smalltalk for the cascade syntax; it means send multiple messages to the same receiver). If Ruby's concatenation (uttered as "+") is ever found to be inefficient like Smalltalk's, I'm sure that what the language culture would lead to is making it work as efficiently as though implemented by Smalltalk's WriteStream, not to inventing a new class equivalent to that class in Smalltalk. The general attitude difference seems to prevail, that in Ruby it's more, write what you mean, and leave efficiency to the language (or library) implementation. "Hello, #{name}!" 'Hello, ', name, '!' WriteStream new nextPutAll: 'Hello, '; nextPutAll: name; nextPutAll: '!'; contents 03 Regular Expression Literal Ruby offers a very convenient syntax for expressing patterns over strings, i. e., regular expressions. It looks just like in the Unix "ed" line editor, with the pattern between slashes. Smalltalk has nothing of the kind, in its syntax. 03 Alternative Syntaxes for Literals Ruby has several other literal syntaxes for convenience, that Smalltalk does not. 02 Assignment operator Smalltalk's assignment operator is ":=", which looks unambiguously like assignment and not equality, which I consider very appropriate for an imperative language. The Ruby designer (who nevertheless I thank profusely (if he's reading this) for the good features of the language, which I think occur together in no other, so the combination of them makes for a helpful innovation, and for providing the first interpreter) erroneously chose to follow Fortran and its kin in using naked "=" for assignment. On the other hand, Ruby offers multiple assignment. You can swap two variables by saying "a, b = b, a". In this vein, see also the prefix "*" notations I mention above. Smalltalk does not have multiple assignment. Ruby offers convenient translations of assignment syntax into message calls. Smalltalk: "foo at: x put: y". Ruby: "foo[x] = y". You write what you mean, not how it is implemented. Smalltalk: "aircraft altitude: 3600"; Ruby: "aircraft.altitude = 3600". In each of these examples, Ruby translates the assignment into a call that can be fielded via the normal method dispatch mechanism. 02 Message-call syntax 03 Keyword Messages Smalltalk has keyword syntax for putting arguments (and parameters) in the middle of a selector; Ruby lacks this feature. I think this is one of the best contributions of Smalltalk to the history of programming languages. Keywords make a program much easier to read, I think, because they tell the reader the meaning and intent and significance of the parameters and arguments, in the sense of their participation in the design behind the program. In Smalltalk, the keywords contribute to the selector, so they participate in the message dispatch. This supports the writing of distinct methods for handling different cases of what data are available to construct or calculate some desired result. Ruby somewhat makes up for the lack of keyword message syntax with the dictionary constructor syntax. In fact, in the context of a message call, Ruby makes the syntax for specifying keyword-argument pairs even easier, almost comparable to Smalltalk's keywords. Let's look at an example. Consider, in Smalltalk: viewer cueMenuRoleNamed: aName forPage: aPage andLayout: aLayout In Ruby, we could write: viewer.cue_menu_role :role_name => a_name, :page => a_page, :layout => a_layout In this Ruby example, the programmer was able to omit the braces that would otherwise have to enclose (and form part of) the dictionary constructor because the dictionary is the last argument and the syntax allows that omission in that circumstance, as a notational convenience. Note how closely the Ruby example parallels the Smalltalk. But there is an important difference in the semantics here. In the Ruby example, the selector is only "cue_menu_role". If the "cue_menu_role" functionality is to operate with different combinations of given data in addition to the selection exemplified (role name, page, and layout), the method or methods that implement "cue_menu_role" will have to examine the argument list and distinguish the cases. In the Smalltalk example on the other hand, the selector is "cueMenuRoleNamed:forPage:andLayout:". The selector embodies the selection of available input data, so the method that implements it only has to deal with that case. In favor of the Ruby approach, on the other hand, is the fact that in Smalltalk, the order of the keywords matters, but in Ruby it does not. Usually in the English that the programmer is trying to get the reader to think of as the interpretation of the operation, the order doesn't matter, so for example, it's a nuisance to have to implement both ifTrue:ifFalse: and ifFalse:ifTrue:. However, I suppose there are counterexamples in the underlying English. Sometimes, order matters in English. So, in looking at keywordism as a whole as addressed in the two languages, I see some strength in Smalltalk in that the keywords are part of the selector, and that the use of keywords with message arguments right at the point where you want to trigger the dispatch is syntactically simple and easy. I see as weaknesses in Smalltalk that the order matters, and that it is not so easy to package up the collection of keyword-argument pairs as a message that can be treated as a whole. 03 Syntax Between Receiver and Selector, and Treatment of Juxtaposition in the Syntax In Ruby, you say "foo.bar"; in Smalltalk, it's "foo bar". The notation for a unary message call is cleaner in Smalltalk than it is in Ruby, because simple juxtaposition, I'd say, requires less mental effort to read, than the notation using the dot. Of course I don't have any cog-sci data about mental effort; I'm just saying that it feels cleaner to me. The syntax makes better use of juxtaposition in Smalltalk. In Ruby, juxtaposition has been used to separate selector from arguments. For example, "foo.bar bletch, baz" would mean what "foo.bar(bletch, baz)" means in Ruby. This is arguably not a terribly wasteful use of juxtaposition in Ruby's syntax. It makes for a clean, "command" look, especially in cases where the receiver is implicitly "self" (discussed below). "load 'foo.rb'", for example, looks cleaner than "load('foo.rb')". But the direction of development of Ruby seems to be away from a consistent use of juxtaposition in this way. If you write, for example, "foo (bar)", the complier might warn you that you ought to remove the space to anticipate the language's future. So, in summary about the dot and juxtaposition, I say that although the use of juxtaposition in a command like "load 'foo.rb'" is quite nice, Smalltalk rather than Ruby has made the better choice about where to harness simple juxtaposition in the syntax, in that Smalltalk grabs this for its basic message-call syntaxes, to separate receiver from selector. 03 Implicit Self In Ruby (as in the language Self, the pioneer in this regard, and from which the language Self gets its name), you can usually abbreviate message calls on "self" by omitting the mention of "self". For example, for "self.foo" you can write simply "foo". But in Smalltalk, you cannot abbreviate "self foo" by writing simply "foo". This makes a major economy in writing and reading Ruby code. 03 Strange Syntax for Blocks. 03 The Cascade Smalltalk has the cascade syntax, which Ruby lacks. Perhaps this lack is not as costly to Ruby programmers as it would be to Smalltalk programmers if the cascade syntax were dropped from Smalltalk, because in cases where the receiver is self, a cascade would buy nothing in Ruby because you can leave out the receiver in those cases anyway. 03 Special Characters Permitted in Selectors (speaking here of selectors other than "+", "*", and the like) Ruby permits "!" in selectors, which is useful to warn code readers that a functional style is not being used. Smalltalk allows only alphanumerics in its unary selectors and in the keywords of its keyword selectors (not counting the colon, which has a specific role in the syntax even though the jargon of discussion of Smalltalk usually speaks of the "keyword" as including the colon). Ruby also permits "?", but below, I argue that this doesn't help because I prefer Smalltalk's convention for choosing selectors indicating Boolean results. 02 Control Constructs Smalltalk's syntax includes no control constructs except the "^" (early return). Any kind of "if", "while", etc., are made by message calls using blocks. At least, syntactically they appear that way. As the Self designers point out, in reality you can't override ifTrue:ifFalse: unless the Smalltalk compiler resorts to the sophistication characteristic of the Self compiler. If you could, many programs would run too slowly because they are laced with much conditional code. But anyway, syntax-wise, the control constructs don't have their own syntax in Smalltalk, other than the "^". Ruby on the other hand, includes syntax for a number of common control constructs even though blocks (closures) are almost as convenient to express in Ruby as they are in Smalltalk (but not quite; sometimes you have to throw in an extra word to make the block an expression). When I was a religious Smalltalker, I might have laughed at languages with control constructs and praised Smalltalk for its syntactic simplicity in using pure object orientation to express the control constructs. But I can also see a Rubyist's point that these control structures are in common use in all imperative programming, so why not have the syntax make it straightforward for a programmer to just write what she means? It doesn't cost much. 02 Returned Value Mentioning "^" above reminds me, that in Smalltalk, if you don't explicitly write "^" with an expression (which means, return the value of the expression as the result of the call), a Smalltalk method returns "self" (I mean, what "self" means in the languages, not the string "self"). In Ruby (as in Lisp), the last expression in the method gives the value returned (absent an early return). This supports a functional mindset; I have written any number of methods that consist of just one expression. Also, it says that if you are not doing an early return, which is in fact a control construct that violates Dijkstra's structured programming, and that should stand out as a warning to readers, you don't have to write "return". I'm not saying I'm against early return; it can be very convenient and can contribute greatly to brevity. I'm saying, early return should stand out. In Ruby you can make it stand out by uttering "return" only in the case of early return. In Smalltalk, you have to write "^" something or you'll get "^ self". For any Smalltalker who argues in favor of the programming style that says a method (or rather the whole suite of methods implementing the same selector) should be either designed to return a value or to have a side effect but generally not both, I agree; sometimes I prefer that style. And Smalltalk's default supports that style. But in Ruby, you can, with ease and clarity and economy, stanch any accidental return of a value some other programmer might seize on, by just ending your method with "true", having it return the Boolean true to indicate success in achieving the desired side effect. I think Smalltalk's support of returning self by default is more costly than beneficial, because I think the two considerations in the paragraph just above outweigh the advantage of support for ask-or-tell-but-not-both-at-once style via the default. On edit: A comment below by user "renox" refers to a lesson from E, that there can be significant hazard of accidentally returning an object you don't want to. I accord that argument much weight, and I question the opinion I gave in my initial version of this section, strongly in favor of having the last expression be the returned value by default. Anyway, that is one of the differences between Ruby and Smalltalk, and it affects the flavor of the way they read, I find. 01 Declarations Smalltalk requires declaration of all local variables and instance variables. In Ruby, you introduce both simply by usage; Ruby does not require declarations for them. This makes a major economy in writing in Ruby. 01 Scope Ruby absolutely makes the wrong choice by denying the programmers any way, just in the syntax in a block of code as you could observe without looking outside the block, to specify a local variable scoped just to that block. You can write, for example, "foo" as the name of your variable, and you can limit its use to the block, and you can hope it will be scoped locally to the block. And indeed it will, if no one writes an assignment to "foo" above the block. In Smalltalk, you can easily declare a variable local to the block (although one or more older Smalltalk implementations would scope the variable wrongly at runtime; I hope all modern Smalltalk implementations have cleared this up). 01 Practices and the libraries 02 Choice of Selectors As reflected in the libraries used widely in the respective languages, Smalltalkers make better choices of message selectors than Rubyists make. For example, I like "isNil" better than "nil?", and "asString" better than "to_s" (which means, "to_string"; I'm nitpicking here about the "to" vs. "as" rather than about the abbreviation of "string" as "s"). All the question-mark selectors can be expressed in a more English-like way by using the conventions Smalltalkers have coalesced around, using "is", "includes", or other verbs. "as" selectors express a more functional attitude, and "to" selectors express a more imperative attitude. 02 Array Stores Smalltalkers choose on the basis of efficiency, whether to store a sequence of values in an OrderedCollection (for the non-Smalltalkers among the readers, note that in Smalltalk, "OrderedCollection" denotes a particular implementation, not a type -- not every ordered collection is an OrderedCollection) or an Array. Rubyists just use the Array type (it's a class, but it might as well be a type). If they need to add to the end of it, they just do. Smalltalkers use SortedCollection if they want their data sorted, and the class makes sure to keep the instance sorted through its history of mutations (by and large); rubyists just tell the array to sort itself when they want it sorted. So, in practices around arrays, the Ruby world looks simpler. Programmers face fewer choices, and fewer concepts to learn. You just write what you mean. 01 Private Methods Ruby enforces declared privacy of methods at runtime. Smalltalk implementations I used do not attempt this. If I recall correctly, Dolphin does. As a Smalltalker, I treated the software-engineering declaration that a method is private, simply with discipline, not looking for enforcement support from the language itself. Ruby backs away from enforcing method privacy when the call is indirect via "send", and taking advantage of this is the only way to do certain useful metaprogramming. I wish the relevant methods were public. Bottom line, maybe others will argue strongly for or against privacy enforcement; I guess it's not a big deal to me. 01 Development Environment Every Smalltalk implementation except the Gnu one offers a development environment where your data can be present along with your software to be modified. You can set up conditions very quickly and try out code, and examine it in any intermediate state of execution, and modify the code at any point, and so on, as pointed out elsewhere. No Ruby implementation so far offers this. Ruby practices depend on the file system as the repository for the software; Smalltalkers use the image. Either practice may fall back on a different repository for the real code repository for version control and sharing with other programmrs (Subversion, or Envy, or whatever), but I'm talking about the development environment here. Smalltalkers look at their code through the class browser. The source code seems to live in the environment along with the values of variables, etc. The practice with Ruby is to organize the code in a file system. I think Smalltalk has it all over Ruby in this regard. It's great to see the source code of any method instantly, and browse the senders or implementers of a given selector. 01 What the language environments could easily learn from each other I submit that Ruby could learn the class browser and browse senders and browse implementors and the whole image with the data and software being present at the same time, the easy debugging and incremental tracing and trying code on the fly and changing it on the fly, all that, from Smalltalk. And that Smalltalk could learn to put some macros in the class definitions. Just keep the source code for the class definition (excluding the methods), as one snippet of text (or maybe more that one, if you have a module system where different modules could contribute to the definition of "open" classes), keep that snippet of source code along with the class (or in modules if you go there), make it visible in the browsers, and every time it is touched, execute it again. Some practices would have to be added to both languages so for the generated consequences of running the macro calls in the class definition would not survive when you edit the definition. Yes, there are issues with how that affects existing instances of the classes, but the languages could solve that more or less the way Smalltalk handles schema evolution today. All the metaprogramming that Ruby supports that make those macros work well, plus the modules and mixins, and the adding methods to objects dynamically, I think that those could be added to Smalltalk without disrupting what Smalltalk already is and does. None of these changes would require touching a parser or a compiler in either language environment, nor the virtual machine that runs either language. Such changes fit with the basic class (or "behavior") model shared by the two languages. I suspect I could sit in a Smalltalk image right now and look at how Class and Metaclass and ClassDescription are subclassed off Behavior, go back to basic Behavior, subclass it differently and implement Ruby's modules, mixins, and the attachment of methods to objects, basically the same way Ruby does it. The languages as implemented have no fundamental difference in their virtual machines. Under the hood, Ruby puts all methods in behaviors just as Smalltalk does. She simply gives any object that has custom methods, a special "virtual" behavior (class), which inherits from the object's nominal class. Just as easy to do in Smalltalk. 01 Paid Work I am glad to see Ruby on the scene, because as a very Smalltalk-like language semantically, with even some advances over Smalltalk both in semantics and syntax, and as a language that judging by the count of ads on Monster and the like, is catching on somewhat in the corporate world as Smalltalk itself dies out, seems as though it might be the rescue vehicle for Smalltalk-like languages as a professional tool. A fine development to tide me over until the whole programming world switches to declarative programming (or dies out due to the end of oil, but that's another subject). 01 Web Support Ruby has Rails and Smalltalk has Seaside. These are not the same, so I understand. When I first came to Smalltalk several years ago, my primary language at the time was Ruby, and I latched onto many of the same things you mention here: the syntactic sugar like implicit self and string interpolation didn't bother me much (on balance I'm happier without it), but I really missed things like attr_accessor (what you're calling macros), singleton methods, and the module/mixin system. As you correctly point out, it's not very difficult to implement all of those in the Smalltalk runtime, and I immediately did this. To my surprise, however, although I had used these features frequently in Ruby, I never once used them in Smalltalk. I can't say for certain why not: all I can report with certainty is that, having the option, I chose not to. However, my best guess is that all of these things upset the delicate balance between dynamism and static analysis that make Smalltalk's tool support work so well. That is, by using them I was making the code writing experience better, but I was making the versioning, debugging, and code browsing experiences worse - effectively, I was bringing them down to Ruby's level, and negating a lot of the advantages that I had come to Smalltalk for in the first place. Welcome back to LtU Avi! Surely you mean "Welcome back" Surely. But this is a new member account, and the previous account hasn't been used for awhile... Thanks for the report; it's interesting to read the view of one traveling (or having traveled) in the opposite direction as I am between these languages. And I go to Ruby not because I think it is better than Smalltalk, but because there seem to be opportunities to get paid for programming in it (although currently I'm doing volunteer work full time). (Also, as for web support, Ruby has Rails and Smalltalk has Seaside. And I hear that Seaside bases itself on some weird continuation service or something like that. And I don't believe in continuations or control flow; I think everything should work sort of like in ToonTalk, via messages. And when you program in Rails, you can take pretty close to that viewpoint without going far wrong.) Now when you speak of static analysis in Smalltalk, that pretty much means "Browse Senders" and "Browse Implementors", right? Are you saying that both these browses get defeated when some of the senders and implementors of a given selector are methods generated by metacode and you can't see their source code or where they came from? I think when it comes to metacode or macros, and when it comes to passing around symbols that get interpreted, there are good practices and there are bad practices. Taking, for example, two strings that mean something, concatenating them together, and interning the result as a symbol, is an example of a class of practices I call "typographical programming" and I strongly oppose. I wonder whether the real cause of the defeat of Browse Senders and Browse Implementors (if indeed that's what you're referring to) is typographical programming, rather than the use of metaprograms per se. First off, those looking for Smalltalk vs. Ruby should see Ruby vs. Smalltalk, which I think you are seeing if you have reached this page. Second, the topic of Smalltalk and Ruby has come up on the Ruby vs. Python page. I'd like to try to draw to here the discussions from over there that touch on Smalltalk and not Python. In Comment 17411, "nat" says of Ruby and Python, "Both are slightly dynamic languages but not as much as LISP or Smalltalk (by which I mean that the language itself can be slightly programmed in itself).". As a Smalltalker turning Ruby user, I see it the other way around, and I cite the calls (macros as some of us have been calling them) common in ruby class definitions, that are executed when the class is read in, and that do metaprogramming such as whipping up methods and adding them to the class (maintainers do not see these whipped-up methods as part of the source code). And nat replied that Smalltalkers do that too these days, so I'm curious as to where they do that in their codebase, e. g., do they put the calls in some "initialize" method on the class side, or what? So I hope to pull that discussion over here because it's about Smalltalk vs. Ruby, not about Python vs. Ruby. In Comment 39221 in the Ruby vs. Python discussion, Noel mentions Ruby's "yield", which is part of the closure-argument exceptionalism in Ruby that I complain about above. Noel calls it cute. I responded with my objections to the exceptionalism. Nathan de Vries responds to my response, asking if it is really such a problem. I'm not sure what he means by "coupled". Anyway, I want to respond here rather than there, because my response mentions Smalltalk and not Python, so it is getting into Ruby vs. Smalltalk. So here goes. I just don't see what the exceptionalism brings to the party. Why not just pass the lambda the way Smalltalk and Lisp do (I mean, as a design consideration for Ruby the language and any future languages, not as a practice for a Ruby programmer to consider)? What I meant by "coupled" was this: def foo(&bar) yield end foo() { # the block is "coupled" to the calling of foo() } Versus this: def foo(bar) bar.call end block = lambda { # the block is defined elsewhere, and can be passed to foo() } foo(block) Like yourself, I'm unsure why calling a method and supplying a block doesn't call 'to_proc' ('&') and pass the proc as the last argument to the method, without the extra '&' syntax in the method definition. One benefit it does have is that you don't need to inspect the method foo() in order to work out if argument bar is being call()'d, yielded, or treated as another type altogether. [[03 String Constructor]] I agree that Ruby's string constructor is very nice for a programmer as it looks like a string instead of a concatenation of strings which is used for other language: it's much nicer visually. But it could be even better if it would allow some processing of the variable like in printf format string: puts "#08X{foo}"; would print foo as an hexadecimal number. [[02 Assignment operator [cut] erroneously chose to follow Fortran and its kin in using naked "=" for assignment.]] Either it's a tongue in cheek comment or it's pure flamebait: ':=' vs '=' is a mostly an subjective esthetic issue, so it's not an error to prefer one over the other! I prefer '=' instead of ':=' as 1) it's shorter! 2) it allows these nice notations: +=, -=, etc. Sure you could use :+= but it's ugly! [[02 Returned Value]] I strongly disagree with you that by default the latest value evaluated should be returned: programmers working on the E language have found that this lead to 'data leaks': programmers ofter forget to add a 'true' at the end and values which weren't supposed to be seen by the caller are then accessible because they happen to be the last one evaluated even though they weren't supposed to be (a big nono for them as they're working with capabilities). And '^' is short enough that it's not a big deal to add it even when you want to return x+1.. Thanks for pointing out the lesson from the E programmers. It seems very valid. I happen to believe in capabilities. Maybe for future languages with a notion like flow control (some commands get executed and others don't, according to the results of tests), the syntax should be "^" for return at the end of the method, and "return" (or even both, "return ^") for early return (skipping the rest of the commands) so the early return stands out visually. Or another approach would be to have the method declared at the beginning as to whether it is supposed to produce a side effect only (a "procedure"), or produce a returned value only (a "function"). The syntax could then be tailored for the difference. Or another approach would be to have the method declared at the beginning as to whether it is supposed to produce a side effect only (a "procedure"), or produce a returned value only (a "function") Do any LtUers know of any work related to adding effects systems to untyped languages? programmers working on the E language have found that this lead to 'data leaks' A problem which is largely mitigated with static typing, as the return type of the function is obvious. This is a great article, and I appreciate all of the thought that's gone into separating out the differences, small as they may be. But . . . With respect to your first point, Ruby -- and this is something very delicate that Ruby helps teach you about a pure OO system -- does not add methods to individual objects, because only classes store methods, and objects do not. When you dynamically add a method to an object, you are actually adding it to a small class, inserted into the inheritance tree right above the object itself. So it end up looking like Object > YourDefinedClass > YourDynamicClass > TheObjectInQuestion It's a lesson about class-based OO, not OO as a whole - see Self for a counterexample. Yes, when you look under Ruby's hood, you see the reality you're describing, that all methods live on behaviors (if I may use that term as a generalization of Ruby's Classes and Modules, and Smalltalk's Behaviors). Basically, classes and similar things, special objects that the virtual machine looks in to find the methods to execute. Programmers who write programs that modify programs do lift that hood and see what's underneath. But I contend that a useful additional viewpoint from which to describe Ruby is that of the casual programmer, the one who doesn't need to look under the hood. From that programmer's viewpoint, Ruby provides an easy syntax with the straightforward semantics of adding a method to an object like in Self. That is the effect of exercising that syntax for all intents and purposes as seen by that programmer. So, I say both viewpoints have their validity for different purposes, and I say that Ruby has an advantage over Smalltalk for providing the easy way to add a method that only responds in one receiver. This is yet another example where one language's pattern becomes another language's feature. Smalltalkers who want a single object that executes methods that no other object executes, resort to the Singleton pattern described by the Gang of Four. Are the semantics really simpler though? Ruby uses this same notion of "singleton method" for what in Smalltalk would be class-side methods. However, in this case there's potentially more than a single receiver that uses the method, since all subclasses of the class you defined the method on will also inherit it. I think that's easier to understand in terms of metaclasses (confusing as those can be to beginners) than as an inherited singleton-method, and I bet that experienced Ruby programmers reason about it in those "under the hood" terms regardless of what the documentation encourages you to do. But maybe that's just my Smalltalk bias. irb(main):068:0> foo = Object.new => #<Object:0x44104c0> irb(main):069:0> class << foo irb(main):070:1> def bar irb(main):071:2> "bletch" irb(main):072:2> end irb(main):073:1> end => nil irb(main):074:0> foo.bar => "bletch" irb(main):075:0> Object.new.bar NoMethodError: undefined method `bar' for #<Object:0x7ff91ecc> from (irb):75 from :0 The above example session from the interactive Ruby interpreter demonstrates attaching a method to an instance of Object. This method fields a "bar" message by answering "bletch". The example goes on to demonstrate that another instance of Object does not field the same selector. You may have seen examples of Rubyists doing this to classes, which makes much the effect of a class-side method. And somehow, the subclasses do inherit those.
http://lambda-the-ultimate.org/node/2606
CC-MAIN-2015-22
refinedweb
6,210
58.52
Using log4net in Web Applications Log4net is the package containing a dll. this dll contains a class logger, which is used to log the messages. It will help the programmer to. Log4naet will help you to collect errors in following ways: • FileAppender: Using this you can save messages in file • SMTPAppender: using this you can save the messages in mail • ADONetAppender: Using this you can save the messages in Database • EventLogAppender: this you can save the messages in Event Viewer In following example we are going to use ‘FileAppender’ mode which help us to print all messages in file. The file will be appended rather than overwritten each time when the logging initiated. Configuration and setup 1) Create your .net application 2) Log4Net consists of only one DLL. Download the DLL file from following link: (Please, remember to download log4net.dll file as per your .NET framework) 3) After downloading extract the file.add its reference in your Application Project. 4) Create a new config file in the root of your Application. Name it Log4Net.config and paste the following code into it. <" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <appendToFile value="true" /> <rollingStyle value="Date" /> <datePattern value="'.'yyyyMMdd'.log'" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %="Notify"> <!--Set level for this logger--> <level value="ALL" /> <appender-ref <appender-ref </logger> </log4net> </configuration> In this config file <file value="Log\[applicationname].log" /> It’s nothing but the path of log file which will be created in your root of Application 5) You will need to add the following line to AssemblyInfo.cs: [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] 5) To log the messages in code window • First we have to import the namespace log4net to use log class using log4net; • Create the object of Logger At the top of class ILog Log = LogManager.GetLogger("Notify"); • Once you’ve declared the logger, you can call one its logging methods. Log.Info("Page Loaded........."); using log4net; public partial class _Default : System.Web.UI.Page { ILog Log = LogManager.GetLogger("Notify"); protected void Page_Load(object sender, EventArgs e) { Log.Info("Page Loaded........."); Log.Error("Page Loaded........."); Log.Warn("Page Loaded........."); Log.Debug("Page Loaded........."); } } 6) There are different types for logs. So it’s all up to you whether you want to display log message as INFO or ERROR, WARN, DEBUG, INFO, etc. 7) For using log4net in Web applications/ Web Service same process can be followed for logging 8) Logging errors in single file: By giving same log file path we can log all errors (ie from win application / web service / web application) in a single file Locking and unlocking of that shared log file will be handled by following way in log4net.config. <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> This I already put up in our log4net.config file The goal for this blog is to not only inform the development community about using log4net in .NET applications, but also to provide an easy to use, step by step process for implementation. We hope that this article accomplished its goal, please feel free to leave any comments and we will do our best to get back to you..)
http://css.dzone.com/articles/using-log4net-web-applications
CC-MAIN-2013-20
refinedweb
530
56.35
C++ Find the Reverse of the Entered Number Hello Everyone! In this tutorial, we will learn how to Find the Reverse of the given Number, in the C++ programming language. The concept of finding the reverse of the entered number can be used to check for Palindrome. Code: #include <iostream> #include <math.h> using namespace std; //Returns the reverse of the entered number int findReverse(int n) { int reverse = 0; //to store the reverse of the given number int remainder = 0; //logic to compute the reverse of a number while (n != 0) { remainder = n % 10; //store the digit at the units place reverse = reverse * 10 + remainder; n /= 10; } return reverse; } int main() { cout << "\n\nWelcome to Studytonight :-)\n\n\n"; cout << " ===== Program to compute the Reverse of the entered number. ===== \n\n"; //variable declaration int n; int reverse = 0; //taking input from the command line (user) cout << " Enter a positive integer to find the reverse of : "; cin >> n; //Calling a method that returns the reverse of an entered number reverse = findReverse(n); cout << "\n\nThe entered number is " << n << " and it's reverse is :" << reverse; cout << "\n\n\n"; return 0; } Output: We hope that this post helped you develop better understanding of how to find the reverse of the given number, in C++. For any query, feel free to reach out to us via the comments section down below. Keep Learning : )
https://studytonight.com/cpp-programs/cpp-find-the-reverse-of-the-entered-number
CC-MAIN-2021-04
refinedweb
232
51.92
BC118 BLE Mate 2 Hookup Guide Introduction SparkFun's Bluetooth low energy (BLE) Mate 2 is a no-nonsense Bluetooth 4.0 (aka Bluetooth low energy or Bluetooth Smart) development board related to our Bluetooth Mate Silver and Bluetooth Mate Gold. The. As you can see, the BLE Mate 2 is a small board: 1.0" by 1.95" (25mm x 50mm). The six-pin header on the end opposite the module. You'll also notice that there are breakout holes available for all the pins on the BC118 module; we'll cover the use of those in a later section. Covered in this Tutorial: - Hardware hookup of the BLE Mate 2 - BC118 functionality - BLE Mate 2 library and example code Materials Used - Arduino Pro 5V - You could just as easily use the 3.3V version, or the Pro Mini, or (in fact) any board that supports serial communications. - BLE Mate 2 (natch) - Depending on what you want to do, you may need two of these. We'll demonstrate an example connecting to another BLE Mate 2 as well as providing some application examples showing how to connect to an iPhone or an Android device. - FTDI SmartBasic - The SmartBasic was designed for just this application--to allow an Arduino to be programmed while allowing the hardware serial port to be selectively attached to another serial device. It's not recommended that you use a software-controlled serial port for this application as the data flow from the BLE Mate 2 can easily overwhelm the buffer. - Snappable male header pins - You'll need to add pins to the SmartBasic and the BLE Mate 2 (if you want to plug the BLE Mate 2 into a breadboard). - 6- and 8-pin female headers - at a minimum. You'll want a 6-pin female for the BLE Mate and the SmartBasic and an 8-pin for the Pro. - Jumper wires - You really only need one of these, to connect the Arduino Pro to the OE line on the SmartBasic. Recommended Reading Before you go any further, you may want to review some of these other tutorials: - Loading an Arduino Library - There is a library available for the BC118 module on the BLE Mate 2 github repository, and this tutorial will explain how to load it. - Hexadecimal - A lot of the parameters used by the BC118 are in hexadecimal; brush up on what that means with this tutorial! - Bluetooth Basics - Learn some of the basics of how Bluetooth works. Hardware Overview Let's take a look at the BLE Mate 2 board. Front The image above has the major parts of the BLE Mate 2 labeled. We'll start with the front, since it's more interesting. We're just going to apply labels to things here; we'll discuss their full use on the next page. - 6-pin FTDI Basic compatible serial header - This header has the same pinout as that of an FTDI Basic board; it's meant to connect to a client device such as an Arduino Pro. If you want to connect it to an FTDI Basic board, you'll need to either make or buy a crossover adapter. We've provide two rows of pins to make multiple connections to these pins (e.g. to sniff the signals for troubleshooting) easier. - LED0 and LED1 - These LEDs display information about the current state of the module. These LEDs reflect the logical state of the module, and a reset of the module may be needed before the settings take effect. More on that later. - LEDs jumper - this jumper ships closed with solder; clear the jumper to disable the LEDs and save some current for low-power situations. - INP jumper - this jumper connects the voltage input pin on the 6-pin header to the 3.3V regulator on the BLE Mate 2. It can be cleared to remove the regulator from the circuit and save current. - REG jumper - clearing this jumper will break the connection between the output of the 3.3V regulator and the supply of the BC118 module. - GPIO headers - All the pins on the BC118 are broken out to these pins, as are power and ground. Back The back is much simpler. You'll note that all the pin labels are present on this side as well. The one thing that is really worth pointing out from this side is the keepout at the top of the board. You can see that the ground plane only extends so far up the PCB; for best performance, you should try and keep that area free of any metal when embedding the BLE Mate 2 in a project. Failing to do so may result in interference or a loss of signal strength. Hardware Connection This page will cover both general hardware connection for the BLE Mate 2 as well as specific information for this tutorial. 6-pin Serial Header The pinout on this header matches that of the FTDI Basic boards, so it can be used anywhere an FTDI basic can be. However, it's probably not fast enough to do any kind of wireless bootloading. - DTR - Connected only to the other DTR pad. This pin can be connected to PIO5 to provide a DTR output to the client device; that signal will be at a voltage determined by the supply voltage of the BC118 module and so may not be adequate to drive the reset signal on an Arduino. - RXI - Data IN from the client device. - TDO - Data OUT from the BC118 device. Shifted up to the level on the VCC pin of this header. - VCC - Connected to the INP jumper (see below). - CTS - Connected only to the other CTS pad. Can be connected to PIO6 to provide an RTS signal to the BC118. That signal must not exceed the supply voltage of the BC118 module. - GND - Negative supply rail for the entire module. GPIO Headers There are two 0.1" (2.54mm) headers along the sides of the module. These pins are 0.9" (22.5mm) apart, so they'll fit into a breadboard (although not a lot of space will be left outside the pins!) The currently useful pins on the BC118 module are all broken out to these headers; I'll go over what they do and what they can do. Here, I'll talk about commands and configuration parameters on the next page, but they will be referenced below. - **AIO2 **- By default, this is an analog input, which can be read by sending the command "AIO 2" to the module. The module will respond with the voltage on this pin, in mV. If the "ACFG" parameter is "ON", this pin will reflect the module's state: HIGH if the module is connected or LOW if the module is not. - AIO1 - Default function is same as AIO2. If the "ACFG" parameter is "ON", pulling this pin HIGH will enable transparent mode, causing data presented to the RX pin to be sent verbatim to any connected device. - AIO0 - Default function is same as AIO2. If "ACFG" is "ON", this pin determines the module's role at boot time. If the signal is HIGH, the module will boot into Central mode. If LOW, Peripheral mode. - P3 - GPIO3. Default is to either mirror from or mirror to another connected device. More on this later. - P4 - LED0 output. - P8 - By default, exit transparent mode. Can be configured as an IO pin for mirroring by setting the "GPIO" parameter to "OFF" - WK - Dependent upon the "WAKE" and "WLVL" parameters, this pin can be used to wake the device from hibernation. - VIN - This pin connects to the INP jumper. More on this below. - GND - Ground for the entire circuit. - P5 - When parameter "FCTR" is "ON", this will be a CTS output from the BC118. - P6 - When parameter "FCTR" is "ON", this will be an RTS input to the BC118. - P7 - GPIO7. See P3 above. - P11 - GPIO11. See P3 above. - P9 - LED1 output. - P10 - GPIO10. See P3 above. - P2 - Not currently enabled. - VDD - This pin ties directly to the supply rail of the BC118. It must be kept between 1.8V and 4.3V to avoid damage to the module. - GND - Ground for the entire circuit. LEDs As mentioned on the previous page, LEDs 0 and 1 provide some easily accessible feedback on the current state of the module. Here's a decoder ring for sorting out what they mean. Note: the LEDs will change to represent the current settings of the module when changing into scanning, advertising, or idle modes, but the module will not change state until the changes have been written to non-volatile memory and the module has been rebooted. LEDS Jumper This jumper disconnects the cathode side of the LEDs from the ground plane, disabling them and eliminating the few hundred microamps each one draws under normal circumstances. It ships closed by default. INP and REG Jumpers The INP jumper, pictured above, has four possible configurations but only three valid ones. This is the default mode, as it ships. In this mode, the input voltage from the VCC pin on the 6-pin header and the VIN pin on the GPIO header is routed to the 3.3V regulator. In this mode, the input side of the regulator is disconnected from all pins, and the module's supply is connected directly to the VIN pin and the VCC pin. In this situation, the voltage present on the input must be between 1.8V and 4.3V. That's within the range of a single-cell LiPo battery, but not of a 5V target board! It's probably a good idea to clear the REG jumper at this point, too; putting a voltage on the output of the regulator but not on the input is liable to cause odd behavior. The level shifting circuit is still active here, so if the data lines on your processor are at a higher voltage than the BC118 is being fed, communications will still work. With no solder on the jumper, you've completely disconnected the module from the VCC and VIN pins entirely. You'll need to provide power to the 3.3V pin on the GPIO header directly, with the same caveat as earlier regarding the voltage range. Again, you should clear the REG jumper. Finally, the fourth mode, which I'm not only going to include a picture of, it's so inappropriate: a big old solder glob covering all three pads. Don't do this. Seriously. It probably won't do anything bad, but it's not going to help your current consumption any, it may damage the regulator, and it will bypass the regulator. Just don't do it. BC118 Functionality While you can just skip over this page and go straight to the code example and library documentation, it's probably a good idea to at least skim it so you have some idea what's going on under the hood. Concepts The BC118 realizes a custom BLE profile, so you'll have to take that into account when developing an app for it. It also means you won't be able to easily connect it to any other BLE modules other than another BC118. Generally, when you change settings on the BC118, you need to write the settings to the onboard non-volatile memory and reset the module before they will take effect. When in doubt, write/reset--it's the only way to be sure. When the module boots in Central mode, it will immediately begin scanning and will scan until it reaches the timeout period (which may be never). To connect to a Peripheral devices, the BC118 must be in Central mode, and scanning. This makes programmatically detecting a successful connection difficult, as the acknowledgment of the connection is buried in a stream of detected devices. The BLE Mate 2 library takes care of that for you. Communication With the Module From the factory, the BC118 comes programmed to accept and transmit via the UART at 9600bps. There are two types of transactions the user can initiate with the module: Commands and setting/getting parameters. The BC118 expects a carriage return ('\r') at the end of a command string; if you send a newline ('\n')(which is frequently a standard practice in serial communications; the Arduino println() function sends "\n\r" at the end of the transmission), that will cause a receive error. All responses from the BC118 will be ended with "\n\r", however, which makes that a good string pattern to recognize for detecting responses from the module. If the module was unable to parse the string between the last two carriage returns into a command, it will respond with "ERR\n\r". At that point, the buffer is clear, and that fact can be a useful way to get to a known state for re-synchronizing user code with the buffer in the BC118. Finally, regarding "transparent" mode: it's possible to put the module into transparent mode, where it forwards data presented on the UART directly to the remote device, and forwards data received from the remote device directly to the UART. Unfortunately, once transparent mode has been activated, there's no escape sequence that can be sent across the UART to return to data mode. GPIO8 and AIO1 can be used to exit transparent mode, but only if that function has been enabled (by setting the parameters GPIO and ACFG to ON, respectively). If those parameters haven't been set, and transparent mode is entered, the only way out is to power cycle the module. Useful Commands Here's a list of useful commands. For more information, you can refer to the Melody Smart User Manual on the BlueCreation website. Commands will be presented with the command first, then parameters to be passed afterwards in parentheses after the command, but the parentheses are not part of the command. Optional parameters will be in brackets. A pipe ('|') will be used to separate "choose one of these" parameters. - ADV (ON|OFF) - Turn advertising on or off. While this can be toggled without error in Central mode, it will have no effect. - AIO (0|1|2) - Report the analog voltage, in mV, on the respective analog input pin. - CON [(BT ADDRESS) (TYPE)] **- **Device must be in scan mode for this command to work! If parameter ACON is '1', no parameter needs to be passed to this command and the module will connect to the first target that supports the Melody Smart protocol (i.e., another BC118 or an app you've written on a target device). Otherwise, BT ADDRESS should be the full 12-character hex address of the device to connect to, and type should be 0 for a public address (most common) or 1 for a private address. - DCN - Disconnect from remote device. Works in either peripheral or central mode. - HIB (timeout) - The "timeout" parameter should be an integer value between 1050 and 429496795, and represents the number of 1.024ms periods to elapse before the device emerges from hibernation. Restarting from hibernation is a clean reboot to stored settings. - GET (parameter) - Returns the value of (parameter), which can be any of the configuration parameters listed below. - RST - Resets the chip, loading all settings from non-volatile memory. - RTR - Restores all settings to factory defaults. - SCN (ON|OFF) - Enable or disable scanning. - SET (parameter)=(value) - No spaces around the equal sign! Set (parameter) to (value). Settings changed in this way will not persist through a reset or power cycle unless the WRT command is issued (see below). - SND (data) - Send a stream of binary data. At most, 20 characters can be sent when in Central mode and 125 in Peripheral mode, and the data must not contain a newline ('\r' or 0x0D) as that will trigger transmission. - STS - Return the status of the module. - VER - Return the version of Melody Smart on the current module, and the module's 12-character Bluetooth address. - WRT - Save the current settings to non-volatile memory, causing them to persist after a reset or power cycle. Note that many settings require a WRT/RST cycle to actually take effect! Parameters In addition to the commands listed above, there are some parameters governing the behavior of the module which can be set or checked via the SET and GET commands mentioned above. Here are some of the most important ones. - ACFG=(ON|OFF) - When OFF, AIO pins are available as analog inputs. When ON, they can be used for control and reporting (see the "Hardware Connection" page for details). - ACON=(ON|OFF) - When ON, the module will connect to the first discovered compatible device. This may not be the device you want to connect to! - ADVC=(ON|OFF) - When ON, the device advertises constantly if not connected. - ADVP=(SLOW|FAST) - Advertising rate. Using SLOW will consume less power but make connecting to the module slower. - ADVT=(timeout) - How long the device will advertise after advertising begins (either at boot or due to the ADV command). Values range from 0 (forever) to 4260, and are integer representations of seconds. - CENT=(ON|OFF) - Enable or disable Central mode. Must WRT/RST to make this take effect! - CCON=(ON|OFF) - Should the device scan/advertise upon disconnection? - CONP=(max_conn_int) (min_conn_int) (latency) (timeout) - Settings this device will send to a Central connecting to it. (max_conn_int) must be greater than (min_conn_int), and both must be between 6 and 3200 and represent the connection interval in units of 1.25ms each. They represent the longest and shortest intervals between which the Central device will ask for data. (latency) is in terms of connection intervals and represents the connection slave latency, which is the number of periods the Peripheral will ignore the Central if it has no new data. Finally (timeout) is the connection supervision timeout, the longest period the Central device should wait before declaring the link lost. It's an integer, in units of 10ms. Arduino Library Example If you haven't done so yet, download the .zip file of the BLE Mate 2 GitHub repository and install the Arduino library from the "Arduino/libraries" sub directory. The Example There's an example in the repository that can be accessed through the "Examples" menu in Arduino. It'll show you how to use all the various functions in the library to connect two BLE Mate 2 boards. First, connect your hardware like so... I've reproduced the code in its entirety below. language:c /**************************************************************** Code to demonstrate the use of the BC118 BLE module on the BLE Mate 2 board by SparkFun electronics. 15 Nov 2014 - Mike Hord, SparkFun Electronics Code developed in Arduino 1.0.6, on an Arduino Pro 5V, using a SparkFun SmartBasic board to multiplex uploading and serial output. ****************************************************************/ #include <SparkFun_BLEMate2.h> // You can also create a SoftwareSerial port object and pass that to the // BLEMate2 constructor; I don't recommend that because it's very possible // for the amount of traffic coming from the BC118 to overwhelm the fairly // shallow buffer of the SoftwareSerial object. BLEMate2 BTModu(&Serial); // This boolean determines whether we're going to do a central or peripheral // example with this code. boolean central = true; void setup() { pinMode(2, OUTPUT); // Control for the SmartBasic. If you look at the // bottom of the sketch, you'll see that I've added // functions called "selectBLE()" and "selectPC()" // to make it a little more obvious when I switch // between serial devices. Serial.begin(9600); // This is the BC118 default baud rate. selectBLE(); // Route serial data to the BC118. // Regarding function return values: most functions that interact with the // BC118 will return BLEMate2::opResult values. The possible values here // are: // REMOTE_ERROR - No remote devices exist. // INVALID_PARAM - You've called the function with an invalid parameter. // TIMEOUT_ERROR - The BC118 failed to respond to the command in a timely // manner; timely is redefined for each command. // MODULE_ERROR - The BC118 didn't like the command string it received. // This will probably only occur when you attempt to send // commands and parameters outside the built-ins. // SUCCESS - What it says. // Reset is a blocking function which gives the BC118 a few seconds to reset. // After a reset, the module will return to whatever settings are in // non-volatile memory. One other *super* important thing it does is issue // the "SCN OFF" command after the reset is completed. Why is this important? // Because if the device is in central mode, it *will* be scanning on reset. // No way to change that. The text traffic generated by the scanning will // interfere with the firmware on the Arduino properly identifying response // strings from the BC118. if (BTModu.reset() != BLEMate2::SUCCESS) { selectPC(); Serial.println("Module reset error!"); while (1); } // restore() resets the module to factory defaults; you'll need to perform // a writeConfig() and reset() to make those settings take effect. We don't // do that automatically because there may be things the user wants to // change before committing the settings to non-volatile memory and // resetting. if (BTModu.restore() != BLEMate2::SUCCESS) { selectPC(); Serial.println("Module restore error!"); while (1); } // writeConfig() stores the current settings in non-volatile memory, so they // will be in place on the next reboot of the module. Note that some, but // not all, settings changes require a reboot. It's probably in general best // to write/reset when changing anything. if (BTModu.writeConfig() != BLEMate2::SUCCESS) { selectPC(); Serial.println("Module write config error!"); while (1); } // One more reset, to make the changes take effect. if (BTModu.reset() != BLEMate2::SUCCESS) { selectPC(); Serial.println("Second module reset error!"); while (1); } selectBLE(); // NB!!!!!!!!!!!!! This write/reset thing is *really* important. // The status command (STS) and the LEDs *will* lie to you and tell you that // you are e.g. advertising or in central mode when in fact that is not the // case and the module still needs to be reset before that is actually true. // Okay, now we're unquestionably set to default settings. That means we're // set up as a peripheral device, advertising forever. You should be seeing // a blinking red LED on the BLE Mate. // At this point the example branches. Down one branch, we'll explore what it // means to go into central mode, find and connect to a BC118, send some // data, and disconnect. Down the other, we'll sit around waiting for // something (either another BC118 or a phone or something) to connect and // send us some data. if (central) { setupCentralExample(); } else { setupPeripheralExample(); } } void loop() { // Since I'm going to be reporting strings back over serial to the PC, I want // to make sure that I'm (probably) not going to be looking away from the BLE // device during a data receive period. I'll *guess* that, if more than 1000 // milliseconds has elapsed since my last receive, that I'm in a quiet zone // and I can switch over to the PC to report what I've heard. static String fullBuffer = ""; static long lastRXTime = millis(); if (lastRXTime + 1000 < millis()) { if (fullBuffer != "") { selectPC(); Serial.println(fullBuffer); selectBLE(); fullBuffer = ""; } } static String inputBuffer; if (central) { doCentralExample(); // We're going to go to this function and never come // back, since we want to do the central connection // demo just once. } else { // This is the peripheral example code. // When a remote module connects to us, we'll start to see a bunch of stuff. // Most of that is just overhead; we don't really care about it. All we // *really* care about is data, and data looks like this: // RCV=20 char max msg\n\r // The state machine for capturing that can be pretty easy: when we've read // in \n\r, check to see if the string began with "RCV=". If yes, do // something. If no, discard it. while (Serial.available() > 0) { inputBuffer.concat((char)Serial.read()); lastRXTime = millis(); } // We'll probably see a lot of lines that end with \n\r- that's the default // line ending for all the connect info messages, for instance. We can // ignore all of them that don't start with "RCV=". Remember to clear your // String object after you find \n\r!!! if (inputBuffer.endsWith("\n\r")) { if (inputBuffer.startsWith("RCV=")) { inputBuffer.trim(); // Remove \n\r from end. inputBuffer.remove(0,4); // Remove RCV= from front. fullBuffer += inputBuffer; inputBuffer = ""; } else { inputBuffer = ""; } } } } void setupCentralExample() { // We need to change some settings, first, to make this central mode thing // work like we want. // When ACON is ON, the BC118 will connect to the first BC118 it discovers, // whether you want it to or not. We'll disable that. BTModu.stdSetParam("ACON", "OFF"); // When CCON is ON, the BC118 will immediately start doing something after // it disconnects. In central mode, it immediately starts scanning, and // in peripheral mode, it immediately starts advertising. We don't want it // to scan without our permission, so let's disable that. BTModu.stdSetParam("CCON", "OFF"); // Turn off advertising. You actually need to do this, or the presence of // the advertising flag can confuse the firmware when the module is in // central mode. BTModu.BLENoAdvertise(); // Put the module in central mode. BTModu.BLECentral(); // Store these changes. BTModu.writeConfig(); // Reset the module. Write-reset is important here!!!!!! BTModu.reset(); // The module is now configured to connect to another external device. } void doCentralExample() { // We're going to tstart with an assumption of module error. That way, we // can easily check against the result while we're iterating. BLEMate2::opResult result = BLEMate2::MODULE_ERROR; // This while loop will continue to scan the world for addresses until it // finds some. Why? Why not? while(1) { selectBLE(); result = BTModu.BLEScan(2); if (result == BLEMate2::SUCCESS) { selectPC(); Serial.println("Success!"); break; } else if (result == BLEMate2::REMOTE_ERROR) { selectPC(); Serial.println("Remote error!"); } else if (result == BLEMate2::MODULE_ERROR) { selectPC(); Serial.println("Module error! Everybody panic!"); } } byte numAddressesFound = BTModu.numAddresses(); // BC118Address is where we'll store the index of the first BC118 device we // find. We'll know it because the address will start with "20FABB". By // starting at 10, we know when we've found something b/c it'll be 4 or less. byte BC118Address = 0; String address; selectPC(); Serial.print("We found "); Serial.print(numAddressesFound); Serial.println(" BLE devices!"); // We're going to iterate over numAddressesFound, print each address, and // check to see if each one belongs to a BC118. The first BC118 we find, // we'll connect to, but only after we report our address list. for (byte i = 0; i < numAddressesFound; i++) { BTModu.getAddress(i, address); Serial.println("Found address: " + address); if (address.startsWith("20FABB")) { BC118Address = i; } } selectBLE(); BTModu.connect(address); BTModu.sendData("Hello world! I can see my house from here! Whee!"); BTModu.disconnect(); delay(500); selectPC(); Serial.println("The End!"); while(1); } // The default settings are good enough for the peripheral example; just to // be on the safe side, we'll check the amICentral() function and do a r/w/r // if we're in central mode instead of peripheral mode. void setupPeripheralExample() { boolean inCentralMode = false; // A word here on amCentral: amCentral's parameter is passed by reference, so // the answer to the question "am I in central mode" is handed back as the // value in the boolean passed to it when it is called. The reason for this // is the allow the user to check the return value and determine if a module // error occurred: should I trust the answer or is there something larger // wrong than merely being in the wrong mode? BTModu.amCentral(inCentralMode); if (inCentralMode) { BTModu.BLEPeripheral(); BTModu.BLEAdvertise(); } // There are a few more advance settings we'll probably, but not definitely, // want to tweak before we reset the device. // The CCON parameter will enable advertising immediately after a disconnect. BTModu.stdSetParam("CCON", "ON"); // The ADVP parameter controls the advertising rate. Can be FAST or SLOW. BTModu.stdSetParam("ADVP", "FAST"); // The ADVT parameter controls the timeout before advertising stops. Can be // 0 (for never) to 4260 (71min); integer value, in seconds. BTModu.stdSetParam("ADVT", "0"); // The ADDR parameter controls the devices we'll allow to connect to us. // All zeroes is "anyone". BTModu.stdSetParam("ADDR", "000000000000"); BTModu.writeConfig(); BTModu.reset(); // We're set up to allow anything to connect to us now. } // Below this point are support functions for the SmartBasic. If you're not // using the SmartBasic, you can leave this part off. void selectPC() { Serial.flush(); digitalWrite(2, LOW); } void selectBLE() { Serial.flush(); digitalWrite(2,HIGH); } TL;DR Summary of Use - Make liberal use of the write() and reset() functions when changing settings. - Software serial is likely to be overwhelmed by the data from the BC118, so don't expect good results from it. - Don't forget that Serial writes/prints are non-blocking. The library functions are all blocking with timeouts, but if you multiplex the serial port you'll need to add Serial.flush()after non-library uses of the serial port to avoid writing non-command strings to the BC118. - The BC118 must be in scan mode to connect to a peripheral! Resources and Going Further Here's some more information to move you beyond this tutorial. - BlueCreation Product Page - This is the product page for the BC118 module. - Command Set Manual - This is for version 2.6, which should be on the modules we ship. - iOS App Example Source - Provided by BlueCreation - Android App Example Source - Provided by BlueCreation - iOS App in AppStore - Use this to update the firmware on the BC118. Note that updating the firmware may break the library, so use with care! - Android App on Google Play - Use this to update the firmware on the BC118. Note that updating the firmware may break the library, so use with care!
https://learn.sparkfun.com/tutorials/bc118-ble-mate-2-hookup-guide
CC-MAIN-2021-31
refinedweb
4,946
65.12
Java'da Analog Saat Örneği Introduction To keep track of date and time, there are many classes in Java containing date and time functions, I am talking about Calendar, GrerogianCalendar, Timestamp... In this tutorial, we will make a calendar with previous and next buttons to change month, and a combo box to change the year. It covers the basics about GUIs, tables, events and renderers. It is important you follow every step carefully and you understand before proceeding. Let's get started. Declaring the GUI components The first step in every GUI (and in any program anyway) is declaring the variables. We will need 8 visible components: the frame itself, the container, the next button, the previous button, the month's label, the calendar itself (which is a JTable), the label to choose the year and the year combo box itself. Why visible components? Well, there are 2 more components we need to make: the table model and the scrollpane for the table. Let's create our class called CalendarProgram: From now on, I assume you know what the above example means. If you don't, you will not be able to follow this tutorial, I recommend you take a basics tutorial about it. Now that our class is declared, we will declare static variables. This is done this way: The value field is optional, you could just declare the name. We will declare all our components, I will explain something after. By the way, we need some packages (declared in the following code): This is quite easy to understand (for now). We imported the packages and we declared the static variables (e.g. the GUI components). But there is a component, DefaultTableModel, which is invisible but useful. It will be the model the table will use. Every JTable must have a model in order to work. Make sure you understand fully the above code. Setting the Look and Feel Every Java program using a GUI (unless you want the ugly Java theme) must have a Look and Feel. This is a "theme" matching your operating system. Setting the theme is quite easy, paste this in your main void: Here you are done with the theme. This is a simple step to make your program nice-looking. You will have your program matching your OS (OS stands for Operating System). Creating the components You must understand the concept of "instantiating" an object. Instantiating an object is the same as creating it. This is done with the "new" keyword. Example: Every object has its own constructor (the method to create the object). Objects can have more than one possible constructor. The JLabel object takes a String as a parameter for the constructor, which will be the text to be displayed in the label. Let's create all the GUI components: Let's take a look at the constructors: JFrame: String - The text to be shown in the window's title bar. JLabel: String - The text to be shown in the label. JComboBox: None JButton: String - The text displayed in the button. DefaultTableModel: None JTable: DefaultTableModel - The model this table will use. JScrollPane: Any component - The component using this scrollpane. JPanel: Layout - The layout used in this panel. We have not instantiated the Container object. You will find out why. Preparing the frame The objects are instantiated, but nothing is functional for now. We have a few steps before. First, we must set the size of the window by invoking the setSize method of JFrame: Now we will use our Container: We did not instantiate the Container, and we already use it. Why? Some objects cannot be instantiated. This is weird but true. Next, we must set the layout of the frame. There are plenty layouts, but we will simply use the null layout, best of all. Here you go: Finally (optional but recommended) we will tell the program to quit when we click the X button: So let's put all this together: Setting the border of the panel Every JPanel is a container and should have a border. You know, the panels with a border around something... Well, this is done with a single statement: The setBorder(border) method of all components does the job. BorderFactory is a class that generated many different types of borders, up to you to find out! Adding the components to the Container We created all, and we are ready to build our GUI. We will first of all add the components to a Container (pane). This is done with the add method of the container. We added all the controls. Or alomst all. The table model and the table itself were not added, but the scrollpane was. It is simple: by adding the scrollpane, we automatically added the table contained in it and this also caused the model to be "added". All components are now in place, we must position them. Positionning the controls The setBounds method of all components will be used to set their position in the container (in this case, the container is pane). It takes four parameters: x, y, width, height. Simple enough. You will find out in this code: All right, nothing new here except one thing: lblMonth.getPreferredSize().width. This method returns the preferred size of a component (e.g. its default size). If the JLabel's text changes, its preferred size is also altered. We want in centered in the center of the calendar on the X axis so we get the middle point of the calendar on X (160) and we substract half the label's size, causing the label to be perfectly aligned with the calendar! Making the frame visible Add those two self-explanatory lines after your code: Useless to explain what they do. They both take a boolean as an argument. Now let's start the real fun! Getting the real month and year To show at startup the appropriate calendar, it would be great to know which month and year we are in. Remember we imported java.util.* before? That's here we will find its utility. The GregorianCalendar class contained in this package contains a big bunch of date and time functions. We will create a GregorianCalendar and get the info. If we instantiate (see definition above) this class without any parameters, the actual calendar is created, and this is what we are looking for. Let's do it: Now, the four integers we declared above are now used. The realMonth and realYear integers contain the real month and year. The currentYear and currentMonth variables contain the actual month/year we are viewing the calendar. Now, let the fun begin! We will populate the year combo box and show the calendar! Populating the combo box In this tutorial, we will be able to view the calendars from 100 years ago to 100 years in the future, but changing this is quite easy. First, let's populate the combo box (I assume you know how a for loop works): Something I haven't explained is here: String.valueOf(i). This simply returns a String which is equal to the String value of i. Simple enough. Test your application. The calendar is simply a dark gray rectangle, but the combo box is populated. We will prepare the calendar. Preparing the calendar Now the calendar is only a dark gray square, but let's make room for the numbers! We need 6 rows and 7 columns, for every day of the week. We need a white background (later we will make the week-end days appear red), a grid and headers for the week days. Let's add the headers: The loop will put all elements of the headers array (containing the days' names) as column headers. Now, we need to set the white background: This is needed because the area not covered with the cells does not belong to the JTable itself, so we can't just use tblCalendar.setBackground(color). This is very strange but it must be done the above way. Next thing: disallow column resizing/reordering. This is done a really simple way: Pretty self-explanatory. Now, we need to be able to select only one cell at a time to make it more realistic. Again, this is simple: I do not really need to explain this one. Finally, let's prepare a 7x6 calendar: These 3 methods do the job. Run your program. The only thing missing is the numbers! Let's add them. But just before, the full preparation code: Please note: it is mendatory that you put the loop to populate the combo box after the preparation of the table. Otherwise, the action listener of the combo box will be fired and since the table is not prepared the program will throw an error. It would be much better with the numbers! Let's go! Refreshing the calendar If you are still following this tutorial correctly (and I hope you do), you should have a blank calendar, only the numbers are missing. Create a method outside your main void: This will be called to refresh the calendar. In your main void, after your code, put: Back in the method we just created, we start by declaring an array containing the months' real names and we decide if the next/previous buttons should be enabled, depending if we reached our capacity (100 years ago or in the future, remember). Also, we create two integers, one to determine the number of days in that month and the other to determine the day of week of the first day of that month. Make sure the previous example is fully understood before proceeding. Now, remember the nod and som variables we declared, we will now assign values to them: Remember what I said above: the constructor of GregorianCalendar with no arguments is the actual date. But in this one we gave 3 arguments: the year, the month and the day (first of the month). The get methods will get the required informations, this is self-explanatory. Now, the refreshCalendar() method will be called more than once in the code execution, so we must clear all the calendar every time in order to draw the new one. This is done that way: Two for loops nested, and a new method: setValueAt. This takes 3 parameters: value, row and column. So the loop loops through all the cells and assigns a null value to all of them, causing the table to be cleared. Lastly, we are ready to draw the calendar, using this loop: Here's how your method should look by now: Run the program. Nice! You got the calendar! As stated above, we will make the weekend days appear red. This is now one of the most difficult things in Java programming: writing custom renderers! Let's dig in (or at least try). Writing the custom renderer This step is not mendatory but I recommend you learn it if you want to write other kinds of renderers later. First, we need to declare (again) the renderer outside our method: I hope you understand the "extends" concept. Now that this is declared, we declare the main method of it, which will apply the renderer: It is starting to make sense. As you have probably noticed, a few parameters can be read: row, column, value, and so on. We will see if the column is either 0 or 6 (sunday or saturday) and apply a red color. Also, the current day will appear blue: We finished our renderer! This was quite a simple one, now we need to apply it. In the refreshCalendar method, at the end, write: The setDefaultRenderer method applies the renderer to the table. The first parameter can be any class, it is not used (I don't even know why it exists). The second is the renderer. Now run the program. What a nice looking calendar! But since nothing in life is ever finished, we will create the actions for the buttons and the year combo. Registering action listeners Anywhere in the main void, add these self-explanatory lines: These are the events that will be triggered when the buttons will be clicked, or we will select an item in the year combo. Pretty easy, no? Anyway, here is the action for the prevous button: The code is simple: if we are in January (month 0), it goes to the month of December of the previous year. Else, it goes back one year. Then, the calendar is refreshed. Now here is the one for the next button, no explanation needed: The opposite of the previous listener. Now let's do the one for the combo box: Put these 3 action listeners outside your existing methond but in the main class. Run the program. Fine! Double-click on a cell. Oops, it is editable. We do not want this. How do we fix it? Find the line: Replace this line by: This is called method overriding. It simply overrides the exitsing method, making the cells uneditable. Now all our code is written! Putting it all together to work If you followed this tutorial correctly, you should get this: /*Contents of CalendarProgran.class */ //Import packages import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class CalendarProgram{ static JLabel lblMonth, lblYear; static JButton btnPrev, btnNext; static JTable tblCalendar; static JComboBox cmbYear; static JFrame frmMain; static Container pane; static DefaultTableModel mtblCalendar; //Table model static JScrollPane stblCalendar; //The scrollpane static JPanel pnlCalendar; static int realYear, realMonth, realDay, currentYear, currentMonth; public static void main (String args[]){ //Look and feel try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());} catch (ClassNotFoundException e) {} catch (InstantiationException e) {} catch (IllegalAccessException e) {} catch (UnsupportedLookAndFeelException e) {} //Prepare frame frmMain = new JFrame ("Gestionnaire de clients"); //Create frame frmMain.setSize(330, 375); //Set size to 400x400 pixels pane = frmMain.getContentPane(); //Get content pane pane.setLayout(null); //Apply null layout frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Close when X is clicked //Create controls lblMonth = new JLabel ("January"); lblYear = new JLabel ("Change year:"); cmbYear = new JComboBox(); btnPrev = new JButton ("<<"); btnNext = new JButton (">>"); mtblCalendar = new DefaultTableModel(){public boolean isCellEditable(int rowIndex, int mColIndex){return false;}}; tblCalendar = new JTable(mtblCalendar); stblCalendar = new JScrollPane(tblCalendar); pnlCalendar = new JPanel(null); //Set border pnlCalendar.setBorder(BorderFactory.createTitledBorder("Calendar")); //Register action listeners btnPrev.addActionListener(new btnPrev_Action()); btnNext.addActionListener(new btnNext_Action()); cmbYear.addActionListener(new cmbYear_Action()); //Add controls to pane pane.add(pnlCalendar); pnlCalendar.add(lblMonth); pnlCalendar.add(lblYear); pnlCalendar.add(cmbYear); pnlCalendar.add(btnPrev); pnlCalendar.add(btnNext); pnlCalendar.add(stblCalendar); //Set bounds pnlCalendar.setBounds(0, 0, 320, 335); lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 100, 25); lblYear.setBounds(10, 305, 80, 20); cmbYear.setBounds(230, 305, 80, 20); btnPrev.setBounds(10, 25, 50, 25); btnNext.setBounds(260, 25, 50, 25); stblCalendar.setBounds(10, 50, 300, 250); //Make frame visible frmMain.setResizable(false); frmMain.setVisible(true); //Get real month/year GregorianCalendar cal = new GregorianCalendar(); //Create calendar realDay = cal.get(GregorianCalendar.DAY_OF_MONTH); //Get day realMonth = cal.get(GregorianCalendar.MONTH); //Get month realYear = cal.get(GregorianCalendar.YEAR); //Get year currentMonth = realMonth; //Match month and year currentYear = realYear; //Add headers String[] headers = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; //All headers for (int i=0; i<7; i++){ mtblCalendar.addColumn(headers[i]); } tblCalendar.getParent().setBackground(tblCalendar.getBackground()); //Set background //No resize/reorder tblCalendar.getTableHeader().setResizingAllowed(false); tblCalendar.getTableHeader().setReorderingAllowed(false); //Single cell selection tblCalendar.setColumnSelectionAllowed(true); tblCalendar.setRowSelectionAllowed(true); tblCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //Set row/column count tblCalendar.setRowHeight(38); mtblCalendar.setColumnCount(7); mtblCalendar.setRowCount(6); //Populate table for (int i=realYear-100; i<=realYear+100; i++){ cmbYear.addItem(String.valueOf(i)); } //Refresh calendar refreshCalendar (realMonth, realYear); //Refresh calendar } public static void refreshCalendar(int month, int year){ //Variables String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; int nod, som; //Number Of Days, Start Of Month //Allow/disallow buttons btnPrev.setEnabled(true); btnNext.setEnabled(true); if (month == 0 && year <= realYear-10){btnPrev.setEnabled(false);} //Too early if (month == 11 && year >= realYear+100){btnNext.setEnabled(false);} //Too late lblMonth.setText(months[month]); //Refresh the month label (at the top) lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 180, 25); //Re-align label with calendar cmbYear.setSelectedItem(String.valueOf(year)); //Select the correct year in the combo box //Clear table for (int i=0; i<6; i++){ for (int j=0; j<7; j++){ mtblCalendar.setValueAt(null, i, j); } } //Get first day of month and number of days GregorianCalendar cal = new GregorianCalendar(year, month, 1); nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH); som = cal.get(GregorianCalendar.DAY_OF_WEEK); //Draw calendar for (int i=1; i<=nod; i++){ int row = new Integer((i+som-2)/7); int column = (i+som-2)%7; mtblCalendar.setValueAt(i, row, column); } //Apply renderers tblCalendar.setDefaultRenderer(tblCalendar.getColumnClass(0), new tblCalendarRenderer()); } static class tblCalendarRenderer extends DefaultTableCellRenderer{ public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column){ super.getTableCellRendererComponent(table, value, selected, focused, row, column); if (column == 0 || column == 6){ //Week-end setBackground(new Color(255, 220, 220)); } else{ //Week setBackground(new Color(255, 255, 255)); } if (value != null){ if (Integer.parseInt(value.toString()) == realDay && currentMonth == realMonth && currentYear == realYear){ //Today setBackground(new Color(220, 220, 255)); } } setBorder(null); setForeground(Color.black); return this; } } static class btnPrev_Action implements ActionListener{ public void actionPerformed (ActionEvent e){ if (currentMonth == 0){ //Back one year currentMonth = 11; currentYear -= 1; } else{ //Back one month currentMonth -= 1; } refreshCalendar(currentMonth, currentYear); } } static class btnNext_Action implements ActionListener{ public void actionPerformed (ActionEvent e){ if (currentMonth == 11){ //Foward one year currentMonth = 0; currentYear += 1; } else{ //Foward one month currentMonth += 1; } refreshCalendar(currentMonth, currentYear); } } static class cmbYear_Action implements ActionListener{ public void actionPerformed (ActionEvent e){ if (cmbYear.getSelectedItem() != null){ String b = cmbYear.getSelectedItem().toString(); currentYear = Integer.parseInt(b); refreshCalendar(currentMonth, currentYear); } } } } Run the program. Enjoy! Conclusion Well, we arrived at the end of this tutorial. This was a pretty complex one, do not worry if you do not fully understand it. But sooner or later, you will need to work with renderers. If you have any questions, contact me! Kaynak Dönem Ödevi 21,849
https://www.dijitalders.com/icerik/68/1689/masaustu_takvim_uygulamasi.html
CC-MAIN-2020-34
refinedweb
3,011
57.47
It does seem that there is always a new programming language to learn. I do wish that I had done some real programming courses when I was a student. My Physics degree from the 1990’s didn’t prepare me well for needing to write a lot of scripts which seem to get more complicated every month. I have been working on a project which requires a Linux virtual appliance be used to build a bunch of Linux VMs. I did start by looking at the option of running PowerCLI on Linux and quickly came to the conclusion that it was too soon for me to use that technology. So, I fell back to Python and the Python bindings for the VMware vSphere API called pyVmomi. This Python module allows me to interact with vCenter to get tasks done. What is pyVmomi? Hopefully, you know that VMware has a public API that you can use to interact with your vSphere environment. Along with the API, there are a variety of tools that integrate the API with particular programming languages. The one that I, and a lot of vSphere administrators, are familiar with is PowerCLI which turns the vSphere API into PowerShell cmdlets and objects. PyVmomi does the same thing, but for Python and (for me at least) not nearly as well. As we assess the usefulness of pyVmomi, remember that it far predates PowerShell and PowerCLI. A lot of the lessons learned on pyVmomi shaped the development of PowerCLI. Unfortunately, those lessons have not been back-ported to pyVmomi which requires that you know a lot about the vSphere API. While there is great documentation for PowerCLI, the pyVmomi documentation is a link to the vSphere API documentation, which in turn is very hard to read. There are a bunch of samples on GitHub, but pyVmomi is definitely not an easy tool to use. Getting Started The first thing is that you need Python installed, I have done all my work with Python 2.7, although Python 3 is more recent, it has some quite different syntax in places. Installing pyVmomi is a single line: pip install --upgrade pyvmomi I did this install as part of the Ansible playbook that does the rest of the appliance configuration for this Centos VM. Next, you will want to connect to a vCenter server: s = ssl.SSLContext(ssl.PROTOCOL_TLSv1) s.verify_mode = ssl.CERT_NONE try: c = SmartConnect(host=vchost, user=vcuser, pwd=vcpassword, sslContext=s) except: print("Failed to connect to vCenter at " + vchost) This yields a connection object, the next snippet retrieves the contents of that connection, lists out the data centers and selects the data center object that matches the data center name I already have. Finally it retrieves the VM folder object that corresponds to the data center. content = c.RetrieveContent() datacenters = [entity for entity in content.rootFolder.childEntity if hasattr(entity, 'vmFolder')] for dc in datacenters: if ( dc.name == dcname): datacenter = dc vmFolder = datacenter.vmFolder Next, I needed to retrieve every VM in that data center, using a function: def GetVMs(vmFolder): vms = vmFolder.childEntity for vm in vms: if hasattr(vm, 'childEntity'): GetVMs (vm) elif isinstance(vm, vim.VirtualApp): for c in vm.vm: if c not in myvmlist: myvmlist.append(c) myvmnamelist.append(c.name) else: if vm not in myvmlist: myvmlist.append(vm) myvmnamelist.append(vm.name) return GetVMs(vmFolder) Notice that the function calls itself for recursive search through multiple folders under the one I give it. The VM objects are listed in the global variable “myvmlist” and I can list their names with a simple loop: for vm in myvmlist: print (vm.name) That is enough for getting started, all of that code started as samples on the community sample repository and didn’t need any significant modification to fit my needs. Getting the rest of my script together took a bit more work, but that is a storey for another few blog posts. So, what else did you manage to do? I have managed to make do all of the VM manipulation that I wanted work in PyVmomi, although I don’t feel like I know a lot more about how to make it work than when I started. I plan to write blog posts about each of the parts that I got to work: - Create new VM - Add SCSI controller and hard drives to an existing VM - Set resource controls, particularly CPU and RAM reservations
http://demitasse.co.nz/2018/04/getting-started-with-pyvmomi/
CC-MAIN-2022-05
refinedweb
742
61.26
This article will dive into the new feature of pulling messages from Service Bus Queue. When a developer designs and build a bridge he/she can now choose two new sources i.e. Service Bus Queues and Topics. A Bridge with Azure BizTalk Services is a workflow that processes a message pulled from a source and delivered to a destination (see picture below). Figure 1 - BizTalk Services Bridge concepts. The ability to pull messages from Service Bus queues and topics increases the durability of a bridge solution. You can leverage the pub-sub mechanism of the topics and subscriptions. It is even possible to have multiple bridges pulling messages from different subscriptions and have them send to multiple destinations. A single bridge will not enable you to do that. Another benefit is that you as a developer will have more input channels for the bridge besides FTP, and HTTP (REST). Indirectly through the Service Bus Queues you could have support for AMQP. To explore the new capability of pulling message from the Service Bus we will explore the following scenario. A payroll company wants to offer a service in Azure BizTalk Services for organizations to send their payroll data for pay rolling. Organizations that like to outsource their pay rolling can connect to this service in Azure. Basically the organizations can send their payroll data to the service in any kind of format and structure they want. The payroll company will provide a bridge to provide connectivity to the source the organization pushes its data to. This can be FTP(S), HTTP or the Service Bus Queue or Topic (subscription). The data will be picked up from the source and processed to one unified format to be routed to a LOB system or database for a later pay roll run that the payroll company will do. Below you will find a diagram detailing the scenario. Figure 2 - Diagram of the payroll scenario. The solution will be a bridge for an organization that requires to push out its payroll data to the payroll company. In this case the data is pushed to a Service Bus Queue and the Bridge will pull the data from the queue, transform it to a format that enables a table operation in SQL Server on premise. To build this solution the following parts need to build, configured and/or created: Installed Templates Click BizTalk Services, then click BizTalk Service. Name Specify a name. Location Set this to a location on your computer. Create directory for solution Select this if you want this solution to have a separate folder in Windows Explorer. Table 1 - BizTalk Service Project specifications. Table 1 - BizTalk Service Project specifications. Figure 3 - Credentials for accessing the LOB Types. Figure 4 - LOB Target configuration Welcome screen/tab. Figure 5 - Specifying the settings for connecting to SQL Server database. Figure 6 - Operations tab for specification of operations on the LOB Target (SQL Server Object). Figure 7 - Specify the run time security settings for access to LOB Target (SQL Server). Figure 8 - LOB Relay settings. Service Bus Namespace Specify the Service Bus namespace on which the LOB relay endpoint is created. Service Bus Issuer Name Specify the issuer name for the Service Bus namespace Service Bus Issuer Secret Specify the issuer secret for the Service Bus namespace LOB Relay Path Enter a name for the relay. LOB Target Sub-path Enter a sub-path to make this target unique. Target runtime URL This read-only property displays the URL where the relay is deployed on Service Bus. This is the path where you could send a message to be inserted into the on-premises SQL Server. In the payroll scenario, this is where the bridge routes the message. Table 2 - Specifications for LOB Relay target. Table 2 - Specifications for LOB Relay target. Table 2 - Specifications for LOB Relay target. Figure 9 - Summary tab LOB Target. Figure 10 - LOB Target part as an application in IIS. When a LOB Target is created you can generate the schema(s) for specified operation(s). The following steps describe how to generate the schema for the insert operation: Figure 11 - Schema generation specifications and credentials. Figure 12 - LOB Schemas in BizTalk Service Project. In BizTalk Service project you can create the schema for the incoming request message containing the payroll data. The data is delivered per employee. The schema can be created as visualized by the screenshot below. Figure 13 - Payroll data schema. The following steps show how to transform the incoming request message (source) to a request message for LOB Target (destination): Figure 14 - Mapping between payroll schema (incoming message) and SQL table operation schema (Insert). Figure 15 - Specify the settings for Service Bus Queue source. Figure 17 - Specifying the Route Action to the destination. Figure 18 - Message flow for payroll data. Figure 19 - Specify the settings for deployment to the BizTalk Service. Figure 20 - Send message to the Service Bus Queue payroll using Microsoft Azure Service Bus Explorer. Figure 21 - Log of the sent message to the Service Bus Queue payroll. Figure 22 - Payroll data in SQL Server table Employee.
https://social.technet.microsoft.com/wiki/contents/articles/23612.azure-biztalk-services-pulling-messages-from-a-service-bus-queue.aspx
CC-MAIN-2019-22
refinedweb
852
57.27
- Overloaded Constructors The Date class provides a handful of constructors. It is possible and often desirable to provide a developer with more than one way to construct new objects of a class type. You will learn how to create multiple constructors for your class in this lesson. In the Date class, three of the constructors allow you to specify time parts (year, month, day, hour, minute, or second) in order to build a Date object for a specific date and time. A fourth constructor allows you to construct a date from an input String. A fifth constructor allows you to construct a date using the number milliseconds since the epoch. A final constructor, one that takes no parameters, constructs a timestamp that represents "now," the time at which the Date object was created. There are also many methods that allow getting and setting of fields on the Date, such as setHour, setMinutes, getDate, and getSeconds. The Date class was not designed to provide support for internationalized dates, however, so the designers of Java introduced the Calendar classes in J2SE 1.1. The intent was for the Calendar classes to supplement the Date class. The Calendar class provides the ability to work with dates by their constituent parts. This meant that the constructors and getters/setters in the Date class were no longer needed as of J2SE 1.1. The cleanest approach would have been for Sun to simply remove the offending constructors and methods. However, if Sun were to have changed the Date class, large numbers of existing applications would have had to have been recoded, recompiled, retested, and redeployed. Sun chose to avoid this unhappy circumstance by instead deprecating the constructors and methods in Date. This means that the methods and constructors are still available for use, but the API developers are warning you that they will remove the deprecated code from the next major release of Java. If you browse the Date class in the API documentation, you will see that Sun has clearly marked the deprecated methods and constructors. In this exercise, you will actually use the deprecated methods. You'll see that their use generates warnings from the compiler. Warnings are for the most part bad—they indicate that you're doing something in code that you probably should not be. There's always a better way that does not generate a warning. As the exercise progresses, you will eliminate the warnings using an improved solution. Here's the test to be added to CourseSessionTest. public void testCourseDates() { int year = 103; int month = 0; int date = 6; Date startDate = new Date(year, month, date); CourseSession session = new CourseSession("ABCD", "200", startDate); year = 103; month = 3; date = 25; Date sixteenWeeksOut = new Date(year, month, date); assertEquals(sixteenWeeksOut, session.getEndDate()); } You will need an import statement at the top of CourseSessionTest: import java.util.Date; This code uses one of the deprecated constructors for Date. Also of note are the odd-looking parameter values being passed to the Date constructor. Year 103? Month 0? The API documentation, which should be your first reference for understanding a system library class, explains what to pass in for the parameters. Specifically, documentation for the Date constructor says that the first parameter represents "the year minus 1900," the second parameter represents "the month between 0 and 11," and the third parameter represents "the day of the month between 1-31." So new Date(103, 0, 6) would create a Date representation for January 6, 2003. Lovely. Since the start date is so critical to the definition of a course session, you want the constructor to require the start date. The test method constructs a new CourseSession object, passing in a newly constructed Date object in addition to the department and course number. You will want to change the instantiation of CourseSession in the setUp method to use this modified constructor. But as an interim, incremental approach, you can instead supply an additional, overloaded constructor. The test finally asserts that the session end date, returned by getEndDate, is April 25, 2003. You will need to make the following changes to CourseSession in order to get the test to pass: - Add import statements for java.util.Date, java.util.Calendar, and java.util.GregorianCalendar; - add a getEndDate method that calculates and returns the appropriate session end date; and - add a new constructor that takes a starting date as a parameter. The corresponding production code: package studentinfo; import java.util.ArrayList; import java.util.Date; import java.util.Calendar; import java.util.GregorianCalendar; class CourseSession { private String department; private String number; private ArrayList<Student> students = new ArrayList<Student>(); private Date startDate; CourseSession(String department, String number) { this.department = department; this.number = number; } CourseSession(String department, String number, Date startDate) { this.department = department; this.number = number; this.startDate = startDate; } ... Date getEndDate() { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(startDate); int numberOfDays = 16 * 7 - 3; calendar.add(Calendar.DAY_OF_YEAR, numberOfDays); Date endDate = calendar.getTime(); return endDate; } } As I describe what getEndDate does, try to follow along in the J2SE API documentation for the classes GregorianCalendar and Calendar. In getEndDate, you first construct a GregorianCalendar object. You then use the setTime [6] method to store the object representing the session start date in the calendar. Next, you create the local variable numberOfDays to represent the number of days to be added to the start date in order to come up with the end date. The appropriate number is calculated by multiplying 16 weeks by 7 days per week, then subtracting 3 days (since the last day of the session is on the Friday of the 16th week). The next line: calendar.add(Calendar.DAY_OF_YEAR, numberOfDays); sends the add message to the calendar object. The add method in GregorianCalendar takes a field and an amount. You will have to look at the J2SE API documentation for Calendar—in addition to the documentation for Gregorian-Calendar—to fully understand how to use the add method. Gregorian-Calendar is a subclass of Calendar, which means that the way it works is tied tightly to Calendar. The field that represents the first parameter tells the calendar object what you are adding to. In this case, you want to add a number to the day of year. The Calendar class defines DAY_OF_YEAR as well as several other class constants that represent date parts, such as YEAR. The calendar now contains a date that represents the end date of the course session. You extract this date from the calendar using the getTime method and finally return the end date of the course session as the result of the method. You might wonder if the getEndDate method will work, then, when the start date is close to the end of the year. If that can possibly happen, it's time to write a test for it. However, the student information system you are writing is for a university that has been around for 200 years. No semester has ever begun in one year and ended in the next, and it will never happen. In short, you're not going to need to worry about it . . . yet. The second constructor will be short-lived, but it served the purpose of allowing you to quickly get your new test to pass. You now want to remove the older constructor, since it doesn't initialize the session start date. To do so, you will need to modify the setUp method and testCourseDates. You should also amend the creation test to verify that the start date is getting stored properly. package studentinfo; import junit.framework.TestCase; import java.util.ArrayList; import java.util.Date; public class CourseSessionTest extends TestCase { private CourseSession session; private Date startDate; public void setUp() { int year = 103; int month = 0; int date = 6; startDate = new Date(year, month, date); session = new CourseSession("ENGL", "101", startDate); } public void testCreate() { assertEquals("ENGL", session.getDepartment()); assertEquals("101", session.getNumber()); assertEquals(0, session.getNumberOfStudents()); assertEquals(startDate, session.getStartDate()); } ... public void testCourseDates() { int year = 103; int month = 3; int date = 25; Date sixteenWeeksOut = new Date(year, month, date); assertEquals(sixteenWeeksOut, session.getEndDate()); } } You can now remove the older constructor from CourseSession. You'll also need to add the getStartDate method to CourseSession: class CourseSession { ... Date getStartDate() { return startDate; } }
https://www.informit.com/articles/article.aspx?p=406343&seqNum=18
CC-MAIN-2021-43
refinedweb
1,377
55.95
I’ve created a pandas dataframe, from which I instanciated a ColumnDataSource for building a DataCube. My issue is: the DataCube sorts my data in a different way that both the dataframe and the source are sorted, and I didn’t find any kind of configuration to set this behaviour up. Sorting on DataCube Hi @diegospereira, the example in the examples directory seems to present the data sorted according to the order the columns are given in. I am not sure there is any different behavior that is configurable at present. In order to speculate about anything you would need to provide a minimal complete examples that could be run to see what you are seeing. Sure thing! This code reproduces what I’m facing: from bokeh.plotting import show, figure from bokeh.models import ColumnDataSource, TableColumn from bokeh.models.widgets.tables import (DataCube, GroupingInfo, SumAggregator, StringFormatter, NumberFormatter) import pandas as pd import numpy as np # sample data generation queries = [f'query{i}' for i in range(100)] pages = [f'page{i}' for i in range(20)] size = 1000 data = { 'page': np.random.choice(pages, size), 'query': np.random.choice(queries, size), 'impressions': np.random.randint(0, 1000, size) } output_notebook() df = pd.DataFrame(data) # These index are user just for sorting the dataframe index1 = df.groupby(['query'])['impressions'].agg(pd.Series.sum) index2 = df.groupby(['query', 'page'])['impressions'].agg(pd.Series.sum) df = (df .groupby(['query', 'page']) .agg({ 'impressions': pd.Series.sum })) for (query, page), val in index2.items(): df.loc[(query, page), 'sort1'] = index1[query] df.loc[(query, page), 'sort2'] = val df.sort_values(by=['sort1', 'sort2'], ascending=False, inplace=True) df.drop(['sort1', 'sort2'], axis=1, inplace=True) df.reset_index(inplace=True) source = ColumnDataSource(df) target = ColumnDataSource(data=dict(row_indices=[], labels=[])) str_formatter = StringFormatter(font_style='bold') num_formatter = NumberFormatter(format='0.[00]') pct_formatter = NumberFormatter(format='0.0[0]%') columns = [ TableColumn(field='page', title='Query', width=120, sortable=False, formatter=str_formatter), TableColumn(field='impressions', title='Impressões', width=40, sortable=False) ] grouping = [ GroupingInfo(getter='query', aggregators=[SumAggregator(field_='impressions')]) ] cube = DataCube(source=source, columns=columns, grouping=grouping, target=target, width=1000) show(cube) On the left, it is shown the DataCube result, on the right, the table from the same source: Is there a way to sort the DataCube rows the same way the source rows are sorted? @diegospereira Right, as I mentioned, it is sorting the first column by value, and since the the first column is strings, it is sorting lexicographically, means, e.g. “query19” is less then “query2”. So the results are exactly what I would expect. AFAIK there is not currently any way to modify or turn off this default sorting scheme. Longer term, you could make a GitHub issue to request some control over the sorting. Short term the only suggestion I have if for you to pad the numbers in the values with leading zeros. I.e., “query02” instead of “query2”. Then things will sort the way you want (if I understand what you want).
https://discourse.bokeh.org/t/sorting-on-datacube/4004
CC-MAIN-2019-43
refinedweb
498
50.33
Say I have created the following library of functions: public class MyClassFloat { float foo; float bar; function MyClassFloat() {} function UpdateBar() { bar = foo * 2.0f; } } public class MyClassVector3 { Vector3 foo; Vector3 bar; function MyClassVector3() {} function UpdateBar() { bar = Vector3.Scale( foo, new Vector3(2.0f,2.0f,2.0f) ); } } And so on, with Vector2 and Quaternion. Can I instead do: enum What( Float, Vector3 ) public class MyClass { What what; object foo; object bar; function MyClass( What w ) { what = w; if (w==What.Float) { foo = float foo; // not sure of syntax to cast an object as a new type? bar = float bar; } else if (w==What.Vector3) { foo = new Vector3 foo; bar = new Vector3 bar; } } function UpdateBar() { if (what==What.Float) { bar = foo * 2.0f; } else if (what==What.Vector3) { bar = Vector3.Scale( foo, new Vector3(2.0f,2.0f,2.0f) ); } } } ... in order to put them all into one generic class? Answer by sneftel · Jun 16, 2011 at 07:46 PM You can, yes, with some caveats. First of all, float is not itself a subclass of Object. System.Single, however, is. All primitive "value types" such as float have "reference type" versions, which inherit from Object and can be the subject of casting. These are known as "boxed" values. float Object System.Single Boxed values are immutable. You create one with, say, new Single(1.5f), and the returned object will always be equal to 1.5. If you want to change the value later, you do that by creating a new Single and assigning it to the same variable. Different object, different quantity, same variable. new Single(1.5f) Single C# has a lot of automatic support for boxing and unboxing values, such that you can assign them directly from value types (with the creation happening automatically, behind the scenes), and even implicitly cast from Object to value types (with the typechecking happening behind the scenes). More info is available here. Also, you don't really need the what member variable; you can just directly check the types of the objects that foo and bar point to. what foo bar Incidentally, though, a whole lot of the stuff you're doing there seems like it might be better handled by generics. What is your specific application here? You can do what you want to do the way you're doing it here (more or less), but you'll end up doing a whoooole lotta boilerplate code. There are most likely more straightforward Aha... I must have completely misunderstood the term Generics, I thought that's what object was! Thanks for pointing that out. So if I do the above with generics, I can create an instance with: $$anonymous$$yClass my = new $$anonymous$$yClass{float}(); ... or is it: $$anonymous$$yClass{Single} my = new $$anonymous$$yClass{Single}(); ??? Also, in the DoSomething() function, how do I check what type foo is, with generics? By the way I used curly brackets ins$$anonymous$$d of less than/more than as using the latter formatted something in the comment and didn't show. Well, that's how you instantiate a generic class, yes... though the type itself must also be qualified with the generic parameter. Of course, the class first needs to be written as a generic class. I think I'm getting it now! Just trying it out. For finding which type an instance is, I'm using: if (foo.GetType().FullName=="System.Single") but is FullName an inefficient method to use? Does it do any boxing/unboxing? This will probably be called many times, so is there a faster test? Answer by robinking · Jun 16, 2011 at 09:43 PM Ben 12's answer above has provided me with a direction to head in, but I've encountered one problem I can't figure out: public class Smooth<SM> { public SM target; public Smooth() {} public void Inc(float i) { if (target.GetType().FullName=="System.Single") { target++; } else if (target.GetType().FullName=="UnityEngine.Vector3") { target.x++; } } } The above (which I want to be able to instantiate as a float or a vector3) results in the following compile error: error CS1061: Type SM' does not contain a definition for x' and no extension method x' of type SM' could be found (are you missing a using directive or an assembly reference?) SM' does not contain a definition for x' of type In fact even just this method: void Set(float a) { target=a; } results in the error: Cannot convert type S$$anonymous$$' to float'... Surely generics allows for effecting changes in generic member variables? S$$anonymous$$' to You would have to cast target to a Vector3 as the generic type S$$anonymous$$ doesn't have an x. You can cast it like this: Vector3 target = (Vector3) (object) target; S$$anonymous$$ x Vector3 target = (Vector3) (object) target; C# generics aren't really meant to handle what you are doing. They are meant to reduce the number of times similar code is written but as you can see you are having to write the same code multiple times to handle the different types making the generic somewhat irrelevant. Only pointing this out because you might run into more issues in the future. Thanks Spencer. As you can see from the datestamp of the original question, it was a very much younger me that asked this! I understand generics (and indeed, polymorphism in general) a lot better now, and yes I wouldn't attack the problem I was trying to solve with generiating objects from a class? (C#) 1 Answer Creating instance of class that does not extend MonoBehaviour 1 Answer how can I make a box with flat cubes(which I want to call a 'tile')? and have each tile detect collision? 0 Answers How to use generic lists in C#? 1 Answer Problem with objects, their positions and casting in a loop 0 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/131020/can-i-use-generic-objects-as-variables-then-cast-t.html?sort=oldest
CC-MAIN-2022-21
refinedweb
981
65.01
Before anyone screams that this isn't the right topic. I'm experimenting with using digital stills cameras for time lapse. I've had this work well at both SD and HD but for those I used minimum compression JPEG files and could automate everything I wanted to do in Irfanview.. I'm now at the next level and am experimenting with 2K film res images that will eventually be tested out to 35mm. So, what's my problem? Well I'm not that good with batches or automating Photoshop and hope that there's someone here who can help me, it's really boring doing it all file at a time. I need to open a RAW file, apply RAW conversion to it, this corrects the colour and exposure, it means loading a pre-set that I've made, then I need to apply a shadow/highlight correction, this automatically opens with the right setting as I've saved it as the default, I then need to save the result as a TIFF file as Combustion doesn't recognize the Cineon files created by PS. Not that this is a problem at the moment as Combustion keeps falling over. The re-sizing down to 2048 is done by the RAW conversion. It's PS CS that I'm using. Cheers Geoff Boyle FBKS Director of Photography EU Based Well I'm not that good with batches or automating Photoshop...I need to >open a RAW file, apply RAW conversion to it Here's how you do it : First reset the palettes (Window->Workspace->Reset Palette Locations). Look for the Actions palette, third from top on the right side, tab in back. Click on the tab to bring it forward. Click on the "Create New Set" (folder) icon at the bottom of the palette and make one called "Geoff's Actions" or whatever. Then, with that selected, click on the "New Action" icon (next to the trash can) and call it "RAW-TIFF", don't worry about the other options, and click on the Record button. Now, train the action by opening and saving a file exactly the way you want it done, including DPI, bit depth, ICC tags, CC changes, etc., and the flavour of TIFF you want including byte order, LZW compression or not, etc. After closing the sample file, stop the recording (bottom of Actions palette), and quit Photoshop. Actions get saved on quit, and if you crash before quitting, it'll be lost. Restart Photoshop, and go to the File menu, File->Automate->Batch. Choose the correct Set and Action. The file paths get saved into the action, but can be overridden with the "Override Action Open Commands" so you can apply to it any directory available - your RAW interpretation will still be used. Set the Destination directory, overriding or not, and any name changes, then hit OK and run it. The only caveat is that the PS-CS UI can get stuck when changing context while running a batch on MacOSX. Use the Cmd->Tab program switcher rather than clicking on UI elements. Not that this is a problem at the moment as Combustion keeps falling >over. Use After Effects instead. I bet you'll be much happier. Tim Sassoon Sassoon Film Design Santa Monica, California I have just released a program which does batch-image-processing. It can do the exposure and color correction and save to the TIFF file, however, it cannot yet read the RAW conversion, but I can add that if somebody points me to the specs (as far as I know, there are different raw formats). Matthias Bürcher Editor Lausanne, Switzerland Geoff Boyle writes : I'm experimenting with using digital stills cameras for time lapse. Regrettably I can't help you with your Photoshop questions, Geoff... but I'm curious as to how you're handling your original exposures over long time spans. Are you metering and constantly re-setting manually? Relying on auto-exposure?.... Dan Drasin Producer/DP Marin County, CA I've been playing with digital time lapses for the last few years now - what I've found is that auto-exposure causes too much flicker and that the stuff that I shoot (mostly sunrises) needs to be on a constant aperture and exposure. Some of it involves guesswork - I set up in the dark, take a meter just before I start the sequence, and then pull the exposure down a few stops to allow for the extreme range. Number of stops depends, for instance, on whether the sunrise will be cloudy vs. clear (ie. higher range or lower). Here are some tests. The Honolulu1 sunrise merits some discussion - looking past the MPEG compression, you can still see the slight 'flicker' in the buildings due to cloud cover and radiosity bounces off of other buildings. It's almost an impossible phenomenon to eliminate completely, unless you take a rotoscoped median across 3 or 5 frames in order to 'smooth out' the exposure - but that starts to venture into visual effects territory.. Alan Chan I'm curious as to how you're handling your original exposures over long >time spans. Experimenting with finding a fixed exposure that works for me Just like I do with film. My present combination of 50EI, in camera ND, 85BPola, Harrison NBRA3 with F8 and 2.5 seconds seems to do the job. I like sequences that start dark and go to normal exposure then go dark! I have tried auto exposure and just don't like the effect. Cheers Geoff Boyle FBKS Director of Photography EU Based Matthias, Looks like you've got a mini-Shake brewing there! What's your development plan for this app? Looks very interesting indeed. Stu Maschwitz, chief nerd among other things, The Orphanage, SF/LA Looks like you've got a mini-Shake brewing there! What's your >development plan for this app? I have worked on several platforms including rayz which was bought by Apple in 2002 to be included in shake. As an editor, sometimes online editor and researcher I need a platform to test my algorithms. As rayz disappeared and after effects has a too complicated API, I decided to write a framework one of my own. it will grow with the needs of particular solutions on my or other peoples editing projects. I will add all my current algorithms and new as i develop them, the framework will is here now. It does, of course, not have the features and speed of shake (nor its price), but it has some unique features like pdf-rendering or mimikri. On my wish-list for the next steps is : >- better integration of alpha-channel (and maybe layers that you can save as a photoshop file) >- some kind of time-based processing (to allow interframe filtering) >- distributed rendering >- some kind of keyframed interface (timeline, but i am not very far with the concepts). >- a better graphics generator The biggest restriction for some time will be the 8bit-resolution. I could add support 10/16bit for many filters, but not for some that rely now on os-x interfaces and i would have to write completely from scratch. But it's fun. Matthias Bürcher Editor Lausanne, Switzerland The first results of my tests are on the web site, in case it helps anyone else... The sequences, a 320 * 240 Sorenson 3 QT file, a 720 * 576 DV file and a frame of DPX at 2048 * 1556, have been rendered from the original files in Combustion with the exception of the smallest file which was generated in Sorenson Squeeze from the DV file. The process was... capture RAW convert RAW to 16 bit TIFF and resize from 2546 to 2048 in Photoshop, a little shadow/highlight filtering was done at this stage import TIFF said : Render out to whichever file format I wanted, this took around 1 hour for >the 4 second DPX sequence on a 3.2Ghz P4 with 1Gb of memory, >Hyper thread enabled. A wonderfully useful conversion program, Graphic Converter (which is shareware),can be found at This program could possibly simplify your post process. Results look so far so good. Simon Higgins DP Sydney,Australia. Hi Geoff, Encouraging stuff. Have been toying with the idea of getting a G5 for a while now, the time lapse capability was one of the things which intrigued me, but couldn’t really find any real world information about it. Certainly seems a lot less painless than the experience I had recently with an intervalometer and a faulty Aaton LTR... What are you thoughts so far about the possible use of this or a similar system in a real production situation? Ross McWhannell DP/VFX. Leeds, UK Files have now been updated, black crush & white clip fixed. Cheers Geoff Boyle FBKS Director of Photography EU Based Simon Higgins wrote : wonderfully useful conversion program, Graphic Converter (which is >shareware),can be found at Yep, it's very useful. But do they make a Wintel version? Jeff Kreines What are you thoughts so far about the possible use of this or a similar >system in a real production situation? That's why I'm testing it. Seriously I can see it working well in situations where in the past I've used a second body for the TL sequences. Cheers Geoff Boyle FBKS Director of Photography EU Based A wonderfully useful conversion program, Graphic Converter (which is >shareware),can be found at > This program could possibly simplify your post process. Is this anything like "Xnview"? Jeffery Haas freelance editor, camera operator Dallas, Texas Seriously I can see it working well in situations where in the past I've >used a second body for the TL sequences. I am almost certainly being a bit premature in asking but, what I meant to say was, given what you have learned so far from your testing, what would you say you say were the pros and cons of using this approach compared to the 'traditional' way of doing it with a second body. I imagine cost and physical practicality being a plus and media capacity (barring tethering it to a laptop) being a minus. Any other thoughts (shooting & post)? Ross McWhannell DP/VFX. Leeds, UK Geoff Boyle writes : >capture RAW >convert RAW to 16 bit TIFF and resize from 2546 to 2048 in Photoshop, So, what was your intention in making the .dpx files? If you want to go out to 35mm, I would respectfully suggest not sending the service bureau white-clipped linear files, but rather, do a lin-log conversion from the RAW files, before color correction (with a log-lin view LUT), in order to maintain proper film gamma and extended highlight information, so that things like the flower petals don't flatten out and color-cast. Also, once you saw it on film, I bet you'd rethink the saturation boost. The 5245 graining is IMHO a waste of time unless you intend to match to film on HD output, i.e. no film-out, because, obviously, if you shoot it out to 5245 you'll get your grain for free! It's really only a technique for matching, and subtle graining rarely survives the film recorder anyway. For motion blur, we love ReVisionFX's RealSmart Motion Blur (plug-in for AE, FCP, C, PR, etc.), which does an optical flow analysis (pixel tracking) to construct the blur vectors. Tim Sassoon Sassoon Film Design Jeffery Haas wrote : >Is this anything like "Xnview"? Yes, very similar, and it appears that Xnview is freeware. Graphic Converter is about 50 bucks after the trial period expires. It has basic grading and softening controls. Simon Higgins DP > So, what was your intention in making the .dpx files? I've quoted the one line so you know which message I'm replying to. It's all an experiment at the moment, certainly I do intend to try going to film, no I won't add grain when I go that route or the saturation boost. I'm learning about LUT's give me a chance It's all a test to see whether it's worth going further, I think it is. Part of the idea is that I often fins myself in places that lend themselves to TL library stuff but all the kit is being used for the "real" shoot, this is a cheap and easy way for me to get the TL material for myself. I actually have the ReVision Motion Blur plug-in somewhere, I got it for Prem and didn't think about using it in Combustion, here goes.... If anyone feels like mailing me any LUT's that they think would be useful I'll be happy to use them and put them on the website, a lot of people are interested in this, probably just to SD or HD but you never know. Cheers Geoff Boyle FBKS Director of Photography EU Based Xnview is in the files section of the site. Has been for a long time. Cheers Geoff Boyle FBKS Director of Photography EU Based Geoff Boyle wrote: >I'm learning about LUT's give me a chance Perhaps Tim could write the official CML primer re LUTs? Jeff Kreines Jeff Kreines writes : >Perhaps Tim could write the official CML primer re LUTs? I'm sure Tim could write a fine primer on LUTs, but until he's done with that... The DI Guide on the Quantel website is a fantastic tutorial on DI and DI workflow (including LUTs,) available for free in PDF form. Not trying to do a plug here, as I do work for Quantel -- it is a genuinely great learning resource. Lucas Wilson ------------------- HD/2K Online Los Angeles >so that things like the flower petals don't flatten out and color-cast You'd be amazed by the luminance level of those foreground petals on the original files! They're a good 2 stops brighter than anything else in the scene. Cheers Geoff Boyle FBKS Director of Photography EU Based Lucas Wilson writes : >The DI Guide on the Quantel website is a fantastic tutorial on DI and DI >workflow (including LUTs,) available for free in PDF form. It's very good, and free, though a lot of product plugs. I gave out their Digital Fact Book for years to my Art Center students. The discussion of log, lin, Cineon, LAD, calibration, etc. is right on. Need to update it to reflect the DCI draft at least, IMHO. Tim Sassoon Sassoon Film Design "Going on a post-fast" Geoff, >Well I'm not that good with batches or automating Photoshop and hope >that there's someone here who can help me, it's really boring doing it all >file at a time Have you tried batching it with ImageMagick? Although not available yet, we have a batch tool coming in CinePaint too. Robin Rowe Hollywood, California
https://cinematography.net/edited-pages/PhotoshopHelp.htm
CC-MAIN-2022-21
refinedweb
2,492
69.41
do this? Please Help jsp help jsp help Hi i am doing my project in jsp.using netbeans 6 and mysql... it to war file? then how would i associate or include my mysql databases with it. so that my project can run independently in any server. plz help me. am so how to use image tag in jsp how to use image tag in jsp How to use image tag in JSP jsp help - JSP-Servlet jsp help In below code value got in text box using 'ID' Attribute ... I want to use that value in query to fetch related values in same page...:// Use of Connection Pooling - JSP-Servlet (); System.out.println(c); } } my problem is how can i use this bean class in jsp page. any body having idea please help me. thanks you  ...Use of Connection Pooling Dear Friends i want to use connection help me - JSP-Servlet help me how to open one compiled html file by clicking one button from j How to use encodeURL in jsp " Sessions in servlets Sessions in servlets What is the use of sessions in servlets? The servlet HttpSession interface is used to simulate the concept that a person's visit to a Web site is one continuous series of interactions How to use 'for' loop in jsp page? How to use 'for' loop in jsp page? This is detailed java code that shows how to use... of 'for' in JSP. use_for_loop.jsp objects in jsp Implicit objects in jsp are the objects... and are created at the conversion time of a jsp into a servlet. But we can pass them to our own method if we wish to use them locally in those functions JSP the following link:  ..., visit the following link: what are different implicit objects of jsp mplicit JSP how can we use beans in jsp how can we use beans in jsp JSP provides three tags to work with beans:- <jsp:useBean id="bean name... that defines the bean. <jsp:setProperty name = "id" property = "someProperty" value jsp and servlet jdbc .and how to use sessions for users. Please visit the following links: and servlet hello friends just want to create a jsp page: please help - JSP-Servlet problem how i make the query which send for class 1 to 10 , assume subject values... with others combox values. Here is JSP's files: display.jsp... To Year "> please help sessions management sessions management I have a problem with the session management of my applcation deployed in tomcat. in fact, my application allows only one... for your help jsp JSP entered name and password is valid HII Im developing a login page using jsp and eclipse,there are two fields username and password,I want to know that how can i check that thw entered name and password is valid,how can i Please Help - JSP-Servlet ,Let me try my hands on it.. The help i need is can u please tell me the procedure for how to bring my alert box in Home Page? Theoretical explaination jsp jsp sir i am trying to connect the jsp with oracle connectivity ,but i am facing some prblems please help me. 1)Import the packages... are using oracle oci driver,you have to use: Connection connection JSP - JSP-Servlet JSP page I want to use the variables and methods which i have declared in another JSP, because the same variables i have to use in each and every JSP page. How... u may help from this link: How to retrieve the dynamic html table content based on id and store it into mysql database? How to export the data from dynamic html table content to excel?Thanks in Advance.. Plz help me its urgent Use Of Form Bean In JSP Use Of Form Bean In JSP  ... about the procedure of handling sessions by using Java Bean. This section provides...;jsp:useBean id="user" class="roseindia.net.UserData" scope jsp - JSP-Servlet programing. And pls say how to introduse the session handling methods in jsp. Hi friend, I am sending a link. This link will help you. please visit for more information. How to use 'continue' keyword in jsp page ? How to use 'continue' keyword in jsp page... that shows how to use 'continue' keyword in jsp page. The continue statement skips...;/html> Save this code as a .jsp file named "use_continue jsp help - JSP-Servlet jsp help i want to add n remove rows dynamically and also want to add data in database in jsp .... Hi Friend, Try the following code: 1)table.jsp: Add/Remove dynamic rows in HTML table function how to execute this code - JSP-Servlet how to execute this code hi guys can any help me in executing this bank application, i need to use any database plz tell me step-to-step procedure for executing this,i need to create Use Session to Track User in JSP Use Session to Track User in JSP  ... and using session information with the help of session API. JSP provides an implicit... have created session_track_jsp.jsp page which will help you to understand how (a.jsp) containing input fields for all the 3 classes, and action of that jsp How to use radio button in jsp page How to use radio button in jsp page This is detailed java code how to use radio button in jsp code and display a message in another jsp page according How To Make Executable Jar File For Java P{roject - Java Beginners How To Make Executable Jar File For Java P{roject Hello Sir I want Help to make Executable File for java Project How I can Make it? Hi Friend, Try the following code: import java.io.*; import java.util.jar. Use Break Statement in jsp code Use Break Statement in jsp code  ...;H1>use break statement in jsp code</H1> <% double array... = 0; i < array.length; i++) { sum += array[i]; // use JSP search engine - JSP-Servlet me use GOOGLE API for search engine. I am developing applicatin in JSP. Can anybody help me how to use Google API. Thanks in advance...JSP search engine Hi! In my project i have a concept of search Use Compound Statement in JSP Code . The following jsp code will show you how to use compound statement. compound... Use Compound Statement in JSP Code  ...;); } %> </BODY> </HTML> Save this code as a .jsp convert system.out.print( p[ j ] + convert system.out.print( p[ j ] + how to display this on midlet? for( int j = 0; j < p.length; j++ ){ System.out.print( p[ j JSP - JSP-Servlet JSP how to make textbox,radiobutton,combo box mandatory for the user... Its all about your logic. To make any HTML component Mandatory, you can use client... ------------ Dipesh Bhavsar Hi friend, Code to help in solving How to upload file using JSP? How to upload file using JSP? Hi all, I m the beginner in JSP, I...; <tr><center><td colspan="2"><p align= "center"><...;td <p align="right"><INPUT TYPE="submit" VALUE="Send How to create and use custom error page in jsp How to create and use custom error page in jsp This is detailed java code how to create and use custom error page in jsp and display an error message. Before run How to use multiple declaration in jsp How to use multiple declaration in jsp JSP provide two ways to declare variables.... Example. <%! int number; %> In the jsp code given below,=" JavaScript with JSP | Working with JSP Sessions | JSP Cookies | Cookie... through JSP | Use Break Statement in jsp code | Use Compound Statement... mysql database through jsp | How To Page Refresh Using JavaScript
http://www.roseindia.net/tutorialhelp/comment/4303
CC-MAIN-2015-11
refinedweb
1,280
74.49
7. Entry Widgets in Tkinter By Bernd Klein. Last modified: 16 Dec 2021. Introduction. This means that the string cannot be seen in its entirety. The arrow keys can be used to move to the invisible parts of the string. If you want to enter multiple lines of text, you have to use the text widget. An entry widget is also limited to single font. The syntax of an entry widget looks like this: w = Entry(master, option, ... ) "master" represents the parent window, where the entry widget should be placed. Like other widgets, it's possible to further influence the rendering of the widget by using options. The comma separated list of options can be empty. The following simple example creates an application with two entry fields. One for entering a last name and one for the first name. We use Entry without options. import tkinter as tk) master.mainloop() The window created by the previous script looks like this: Okay, we have created Entry fields, so that the user of our program can put in some data. But how can our program access this data? How do we read the content of an Entry? To put it in a nutshell: The get() method is what we are looking for. We extend our little script by two buttons "Quit" and "Show". We bind the function show_entry_fields(), which is using the get() method on the Entry objects, to the Show button. So, every time this button is clicked, the content of the Entry fields will be printed on the terminal from which we had called the script. import tkinter as tk def show_entry_fields(): print("First Name: %s\nLast Name: %s" % (e1.get(), e2.get()))) tk.mainloop() The complete application looks now like this: Let's assume now that we want to start the Entry fields with default values, e.g. we fill in "Miller" or "Baker" as a last name, and "Jack" or "Jill" as a first name. The new version of our Python program gets the following two lines, which can be appended after the Entry definitions, i.e. "e2 = tk.Entry(master)": e1.insert(10, "Miller") e2.insert(10, "Jill") What about deleting the input of an Entry object, every time, we are showing the content in our function show_entry_fields()? No problem! We can use the delete method. The delete() method has the format delete(first, last=None). If only one number is given, it deletes the character at index. If two are given, the range from "first" to "last" will be deleted. Use delete(0, END) to delete all text in the widget. import tkinter as tk def show_entry_fields(): print("First Name: %s\nLast Name: %s" % (e1.get(), e2.get())) e1.delete(0, tk.END) e2.delete(0, tk.END) master = tk.Tk() tk.Label(master, text="First Name").grid(row=0) tk.Label(master, text="Last Name").grid(row=1) e1 = tk.Entry(master) e2 = tk.Entry(master) e1.insert(10, "Miller") e2.insert(10, "Jill")) master.mainloop() tk.mainloop() The next example shows, how we can elegantly create lots of Entry field in a more Pythonic way. We use a Python list to hold the Entry descriptions, which we include as labels into the application. import tkinter as tk fields = 'Last Name', 'First Name', 'Job', 'Country' def fetch(entries): for entry in entries: field = entry[0] text = entry[1].get() print('%s: "%s"' % (field, text)) def makeform(root, fields): entries = [] for field in fields: row = tk.Frame(root) lab = tk.Label(row, width=15, text=field, anchor='w') ent = tk.Entry(row) row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5) lab.pack(side=tk.LEFT) ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X) entries.append((field, ent)) return entries if __name__ == '__main__': root = tk.Tk() ents = makeform(root, fields) root.bind('<Return>', (lambda event, e=ents: fetch(e))) b1 = tk.Button(root, text='Show', command=(lambda e=ents: fetch(e))) b1.pack(side=tk.LEFT, padx=5, pady=5) b2 = tk.Button(root, text='Quit', command=root.quit) b2.pack(side=tk.LEFT, padx=5, pady=5) root.mainloop() If you start this Python script, it will look like this: Calculator We are not really writing a calculator, we rather provide a GUI which is capable of evaluating any mathematical expression and printing the result. import tkinter as tk from math import * def evaluate(event): res.configure(text = "Result: " + str(eval(entry.get()))) w = tk.Tk() tk.Label(w, text="Your Expression:").pack() entry = tk.Entry(w) entry.bind("<Return>", evaluate) entry.pack() res = tk.Label(w) res.pack() w.mainloop() Our widget looks like this: Interest Calculation The following formula can be used to calculate the balance Bk after k payments (balance index), starting with an initial balance (also known as the loan principal) and a period rate r: where rate = interest rate in percent, e.g. 3 % i = rate / 100, annual rate in decimal form r = period rate = i / 12 B0 = initial balance, also called loan principal Bk = balance after k payments k = number of monthly payments p = period (monthly) payment If we want to find the necessary monthly payment if the loan is to be paid off in n payments one sets Bn = 0 and gets the formula: where n = number of monthly payments to pay back the principal loan import tkinter as tk fields = ('Annual Rate', 'Number of Payments', 'Loan Principle', 'Monthly Payment', 'Remaining Loan') def monthly_payment(entries): # period rate: r = (float(entries['Annual Rate'].get()) / 100) / 12 print("r", r) # principal loan: loan = float(entries['Loan Principle'].get()) n = float(entries['Number of Payments'].get()) remaining_loan = float(entries['Remaining Loan'].get()) q = (1 + r)** n monthly = r * ( (q * loan - remaining_loan) / ( q - 1 )) monthly = ("%8.2f" % monthly).strip() entries['Monthly Payment'].delete(0, tk.END) entries['Monthly Payment'].insert(0, monthly ) print("Monthly Payment: %f" % float(monthly)) def final_balance(entries): # period rate: r = (float(entries['Annual Rate'].get()) / 100) / 12 print("r", r) # principal loan: loan = float(entries['Loan Principle'].get()) n = float(entries['Number of Payments'].get()) monthly = float(entries['Monthly Payment'].get()) q = (1 + r) ** n remaining = q * loan - ( (q - 1) / r) * monthly remaining = ("%8.2f" % remaining).strip() entries['Remaining Loan'].delete(0, tk.END) entries['Remaining Loan'].insert(0, remaining ) print("Remaining Loan: %f" % float(remaining)) def makeform(root, fields): entries = {} for field in fields: print(field) row = tk.Frame(root) lab = tk.Label(row, width=22, text=field+": ", anchor='w') ent = tk.Entry(row) ent.insert(0, "0") row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5) lab.pack(side=tk.LEFT) ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X) entries[field] = ent return entries if __name__ == '__main__': root = tk.Tk() ents = makeform(root, fields) b1 = tk.Button(root, text='Final Balance', command=(lambda e=ents: final_balance(e))) b1.pack(side=tk.LEFT, padx=5, pady=5) b2 = tk.Button(root, text='Monthly Payment', command=(lambda e=ents: monthly_payment(e))) b2.pack(side=tk.LEFT, padx=5, pady=5) b3 = tk.Button(root, text='Quit', command=root.quit) b3.pack(side=tk.LEFT, padx=5, pady=5) root.mainloop() Our loan calculator looks like this, if we start it with Python3:
https://python-course.eu/tkinter/entry-widgets-in-tkinter.php
CC-MAIN-2022-05
refinedweb
1,206
60.92
After completing the majority of the key mechanism for my vintage toy synthesiser, which I covered in my last blog post, I thought it was about time I cracked open the BeagleBone Black board and attempted to connect the key mech to it. Setting up the BBB for my preferred development language and environment, as well as getting the Arduino-to-BBB comms working, was a bit more complex than I thought it would be, nevertheless I have now got the BBB receiving key interaction data from the keyboard. This blog post covers the following main things: - Setting up the BBB to be tethered to a computer - Installing a BBB-compatible ARM cross-compiler on OS X - A method for developing C/C++ based software for the BBB, from writing code to testing compiled binaries - Enabling all UART/serial ports on the BBB, and writing software that reads from a connected serial device My Preferred Development Languages and Environment Professionally, and as a hobbyist, I mainly develop software using the C and C++ languages, which is what I plan to use when developing the BBB software for the vintage toy synthesiser. When it comes to developing software for Linux-based single-board computers such as the BBB, my preferred way of doing it is using a cross-compiler that allows me to develop and compile the software on my main computer running OS X, and then using something such as Secure Copy (scp) to transfers the binaries onto the target hardware. The majority of this blog post talks about the tools and methods used to get this environment set up. Tethering the BBB to a Computer As per the official BBB Getting Started guide, the most common way to use and and develop on the BBB is to connect it to a computer and use the network-over-USB access. This is done using the following simple steps: - Connect the BBB to your computer via USB - Wait for a new mass storage device to appear - On the mass storage device, open START.htm - Follow the provided instructions to install the needed drivers Once that has been done, possibly followed by a needed computer restart, you can now access your BBB through the 192.168.7.2 IP address. My preferred access method is to use Secure Shell (ssh) through a command line interface (CLI), using the command: ssh -l root 192.168.7.2 BBB-Compatible ARM Cross-Compiler for OS X It is entirely possible to develop software for the BBB directly on the board by accessing it over a network. However there are a couple of pitfalls here: - You're stuck using CLI programs which are not everyones preferred method of interacting with a computer, especially when it comes to text editing - When compiling your software you're limited to the power of the BBB which is probably not as great as your personal computer, making the process a lot slower - You'll be developing using Linux, which may not be your preferred OS to use The way around this is to develop the software on your personal computer, where you have a GUI and greater CPU/RAM specs, and then transfer it over to the BBB afterwards. The main obstacle in doing that though is the fact that the processor type and OS of your personal computer (most probably Windows or OS X running on an Intel or AMD processor) is probably different from that of the BBB (Linux running on an ARM processor), so you need to use a compiler/toolchain that will run on one type of system (the host) but build software to be run on another type of system (the target). This is known as a cross-compiler. The toolchain needed for cross compiling for the BBB is arm-linux-gnueabihf; which compared to the more-commonly used arm-linux-gnueabi has hardware FPU (Floating Point Unit) support which is needed for compiling for the BBB target. The arm-linux-gnueabihf cross-compiler toolchain is officially available for both Linux and Windows as a GCC-based compiler released by Linaro. For OS X there is an unofficial (but working) version of the Linaro toolchain available from here - this is the cross-compiler that I have installed and started using. My Preferred Development Method Now that I have my cross-compiler installed, I can start developing software for the BBB using my preferred environment and tools. This is my preferred development method, from writing code to testing the compiled binaries: - I write my code on OS X using a programming text editor - my personal favourites are Xcode and Sublime Text - I compile my code using a Terminalwindow with the one of the following command: For C code: /usr/local/linaro/arm-linux-gnueabihf/bin/arm-linux-gnueabihf-gcc [source file] -o [compiled binary name] For C++ code: /usr/local/linaro/arm-linux-gnueabihf/bin/arm-linux-gnueabihf-g++ [source file] -o [compiled binary name] - With the same Terminal window I copy the compiled binaries to the BBB using scp: scp [binary file] root@192.168.7.2:[destination directory] - Using a second Terminal Window which has a running ssh session logged into the BBB (see the Tethering...section above) I test running the binaries using the following command: ./[binary file] Eventually I will want my BBB software to start on boot, but I'll talk about that in a later blog post. Connecting the Key Mech Arduino via Serial Apart from the obvious Hello World program, the first application I have developed for the BBB is a simple program that reads serial data coming from the pianos key mech Arduino, displaying read bytes to the console. The BBB has six on-board serial ports - one that is coupled to the boards serial console, and five UART ports that can be found on the boards expansion headers. By default only the serial console port is enabled, so to use any of the other UARTs you must allow them to be enabled at boot. I did this by following the "Section 1" steps on this tutorial. Note that on my BBB the uEnv.txt file was in the /boot/ directory, not /boot/uboot/ as the tutorial suggests. Once this had been done, I connected the Arduino Pro Mini to the BBB using the following connections: - Arduino TX pin to BBB P9_26 pin (UART1 RX), for sending serial data from Arduino to BBB - Arduino GND pin to BBB P9_01 pin (a DGND pin), for allowing the Arduino to be powered by the BBB - Arduino RAW pin to BBB P9_03 pin (a VDD_3V3 pin), for powering the Arduino using the BBB The key mechanisms Arduino Pro Mini connected to the BeagleBone Black via the UART1 port Lastly I developed a small piece of code that opens the UART1 device file (/dev/ttyO0) and displays any byte it reads from it. You can see this code on my projects GitHub repo here, as well as below: #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <termios.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdbool.h> #include <errno.h> #define KEYBOARD_SERIAL_PATH "/dev/ttyO1" int main (void) { printf ("Running test_key_mech_input (v2)...\n"); int keyboard_fd; uint8_t keyboard_input_buf[1] = {0}; //========================================================== //Set up serial connection printf ("Setting up key mech serial connection...\n"); struct termios tty_attributes; // open UART1 device file for read/write keyboard_fd = open (KEYBOARD_SERIAL_PATH, O_RDWR); //if can't open file if (keyboard_fd < 0) { //show error and exit perror (KEYBOARD_SERIAL_PATH); return (-1); } tcgetattr (keyboard_fd, &tty_attributes); cfmakeraw (&tty_attributes); tty_attributes.c_cc[VMIN]=1; tty_attributes.c_cc[VTIME]=0; // setup bauds (key mech Arduino uses 38400) cfsetispeed (&tty_attributes, B38400); cfsetospeed (&tty_attributes, B38400); // apply changes now tcsetattr (keyboard_fd, TCSANOW, &tty_attributes); // set it to blocking fcntl (keyboard_fd, F_SETFL, 0); //========================================================== //Enter main loop, and just read any data that comes in over the serial port printf ("Starting reading data from key mech...\n"); while (true) { //attempt to read a byte from the serial device file int ret = read (keyboard_fd, keyboard_input_buf, 1); //if read something if (ret != -1) { //display the read byte printf ("Byte read from keyboard: %d\n", keyboard_input_buf[0]); } //if (ret) } ///while (true) return 0; } Next Steps Now that I have got the BBB up and running the next step is to start the development of the sound synthesis engine. This will involve developing some software that creates a simple controllable tone, as well as configuring the BBB to output the audio via one of its audio outputs.
https://www.element14.com/community/community/design-challenges/musictech/blog/2016/01/10/vintage-toy-synthesiser--getting-started-with-the-beaglebone-black
CC-MAIN-2019-09
refinedweb
1,414
50.09
SH7760/SH7763 integrated LCDC Framebuffer driver¶ 0. Overview¶ The SH7760/SH7763 have an integrated LCD Display controller (LCDC) which supports (in theory) resolutions ranging from 1x1 to 1024x1024, with color depths ranging from 1 to 16 bits, on STN, DSTN and TFT Panels. Caveats: Framebuffer memory must be a large chunk allocated at the top of Area3 (HW requirement). Because of this requirement you should NOT make the driver a module since at runtime it may become impossible to get a large enough contiguous chunk of memory. The driver does not support changing resolution while loaded (displays aren't hotpluggable anyway) Heavy flickering may be observed a) if you're using 15/16bit color modes at >= 640x480 px resolutions, b) during PCMCIA (or any other slow bus) activity. Rotation works only 90degress clockwise, and only if horizontal resolution is <= 320 pixels. - Files: drivers/video/sh7760fb.c include/asm-sh/sh7760fb.h Documentation/fb/sh7760fb.rst 1. Platform setup¶ - SH7760: Video data is fetched via the DMABRG DMA engine, so you have to configure the SH DMAC for DMABRG mode (write 0x94808080 to the DMARSRA register somewhere at boot). PFC registers PCCR and PCDR must be set to peripheral mode. (write zeros to both). The driver does NOT do the above for you since board setup is, well, job of the board setup code. 2. Panel definitions¶ The LCDC must explicitly be told about the type of LCD panel attached. Data must be wrapped in a "struct sh7760fb_platdata" and passed to the driver as platform_data. Suggest you take a closer look at the SH7760 Manual, Section 30. ( The following code illustrates what needs to be done to get the framebuffer working on a 640x480 TFT: #include <linux/fb.h> #include <asm/sh7760fb.h> /* * NEC NL6440bc26-01 640x480 TFT * dotclock 25175 kHz * Xres 640 Yres 480 * Htotal 800 Vtotal 525 * HsynStart 656 VsynStart 490 * HsynLenn 30 VsynLenn 2 * * The linux framebuffer layer does not use the syncstart/synclen * values but right/left/upper/lower margin values. The comments * for the x_margin explain how to calculate those from given * panel sync timings. */ static struct fb_videomode nl6448bc26 = { .name = "NL6448BC26", .refresh = 60, .xres = 640, .yres = 480, .pixclock = 39683, /* in picoseconds! */ .hsync_len = 30, .vsync_len = 2, .left_margin = 114, /* HTOT - (HSYNSLEN + HSYNSTART) */ .right_margin = 16, /* HSYNSTART - XRES */ .upper_margin = 33, /* VTOT - (VSYNLEN + VSYNSTART) */ .lower_margin = 10, /* VSYNSTART - YRES */ .sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, .vmode = FB_VMODE_NONINTERLACED, .flag = 0, }; static struct sh7760fb_platdata sh7760fb_nl6448 = { .def_mode = &nl6448bc26, .ldmtr = LDMTR_TFT_COLOR_16, /* 16bit TFT panel */ .lddfr = LDDFR_8BPP, /* we want 8bit output */ .ldpmmr = 0x0070, .ldpspr = 0x0500, .ldaclnr = 0, .ldickr = LDICKR_CLKSRC(LCDC_CLKSRC_EXTERNAL) | LDICKR_CLKDIV(1), .rotate = 0, .novsync = 1, .blank = NULL, }; /* SH7760: * 0xFE300800: 256 * 4byte xRGB palette ram * 0xFE300C00: 42 bytes ctrl registers */ static struct resource sh7760_lcdc_res[] = { [0] = { .start = 0xFE300800, .end = 0xFE300CFF, .flags = IORESOURCE_MEM, }, [1] = { .start = 65, .end = 65, .flags = IORESOURCE_IRQ, }, }; static struct platform_device sh7760_lcdc_dev = { .dev = { .platform_data = &sh7760fb_nl6448, }, .name = "sh7760-lcdc", .id = -1, .resource = sh7760_lcdc_res, .num_resources = ARRAY_SIZE(sh7760_lcdc_res), };
https://doc.kusakata.com/fb/sh7760fb.html
CC-MAIN-2022-21
refinedweb
475
56.86
In order to handle requests to your Async API, one of your containers must run a web server which is listening for HTTP requests on the port which is configured in the pod.port field of your API configuration (default: 8080). Requests will be sent to your web server via HTTP POST requests to the root path ( /). Your web server must respond with valid JSON (with the Content-Type header set to "application/json"). The response will remain queryable for 7 days. It is often important to implement a readiness check for your API. By default, as soon as your web server has bound to the port, it will start receiving traffic. In some cases, the web server may start listening on the port before its workers are ready to handle traffic (e.g. tiangolo/uvicorn-gunicorn-fastapi behaves this way). Readiness checks ensure that traffic is not sent into your web server before it's ready to handle them. There are two types of readiness checks which are supported: http_get and tcp_socket (see API configuration for usage instructions). A simple and often effective approach is to add a route to your web server (e.g. /healthz) which responds with status code 200, and configure your readiness probe accordingly: readiness_probe:http_get:port: 8080path: /healthz Your API pod can contain multiple containers, only one of which can be listening for requests on the target port (it can be any of the containers). The /mnt directory is mounted to each container's filesystem, and is shared across all containers. Each container in the pod requests its own amount of CPU, memory, GPU, and Inferentia resources. In addition, Cortex's dequeuer sidecar container (which is automatically added to the pod) requests 100m CPU and 100Mi memory. See docs for logging, metrics, and alerting. It is possible to use the Cortex CLI or client to interact with your cluster's APIs from within your API containers. All containers will have a CLI configuration file present at /cortex/client/cli.yaml, which is configured to connect to the cluster. In addition, the CORTEX_CLI_CONFIG_DIR environment variable is set to /cortex/client by default. Therefore, no additional configuration is required to use the CLI or Python client (which can be instantiated via cortex.client()). Note: your Cortex CLI or client must match the version of your cluster (available in the CORTEX_VERSION environment variable). It is possible to submit requests to Async APIs from any Cortex API within a Cortex cluster. Requests can be made to<api_name>, where <api_name> is the name of the Async API you are making a request to. For example, if there is an Async API named hello-world running in the cluster, you can make a request to it from a different API in Python by using: import requests# make a request to an Async APIresponse = requests.post("",json={"text": "hello world"},)# retreive a result from an Async APIresponse = requests.get("<id>") To make requests from your Async API to a Realtime, Batch, or Task API running within the cluster, see the "Chaining APIs" docs associated with the target workload type.
https://docs.cortex.dev/workloads/async/containers
CC-MAIN-2021-39
refinedweb
518
62.07
Let's say we have a simple async function that calls some remote data. We pass in our query and configuration object. To see an example of what can be passed through this request config see the Axios docs. My query in this case is just the url key in the config for example /user which could be an API end point. This function simply returns the data from axios (the actual response body from your endpoint). If we fail to get a response from our endpoint, the function is going to catch and we'll throw a console error. request.js export const fetchData = async (query, config ) => { try { const { data } = await axios.request({ method: 'get', url: encodeURI(query), ...config }); return data; } catch (e) { console.error('Could not fetchData', e); } }; Now let's create a new file request.spec.js we want to add two imports import mockAxios from 'axios'; import { fetchData } from '../request'; In order to test this we need to use a mocked version of Axios which is conveniently imported from the core library. We're now ready to write our test it('should call a fetchData function', done => { fetchData('/test', {}).then(response => { expect(response).toEqual({ data: {}, }); }); expect(mockAxios.request).toHaveBeenCalledWith({ method: 'get', url: '/test' }); expect(mockAxios.request).toHaveBeenCalledTimes(1); expect(consoleErrorSpy).not.toHaveBeenCalled(); done(); }); First we call then function with a test query and an empty config to ensure then test that our response is correct. Now we are testing mockAxios.request that it was called with the arguments we expected, that it was called only one time, and that our function did not throw an error. Finally we call the done() callback which let's just know our asynchronous operations are complete. Discussion (5) So I just want to say for future reference here: when you see 'import (somename) from "some-library", that gets whatever the default value is for that library. it will not matter what the name is, it will refer to the same default value EX: import axios from "axios" is the same as import mockAxios from "axios" but import {axios} from "axios" is not the same as import {mockAxios} from "axios mockAxios is not a module from the core axios library. This should not be working. Second this. This article is the worst type of BS I have seen in a long time. MockAxios should be a selft written implementation. Was scratching my head wondering how?! this could possibly work, then I saw your comment, lol 😂 bruuuuuuuuuuuuuuuuuuh ... read comments like half hour later
https://practicaldev-herokuapp-com.global.ssl.fastly.net/benweiser/testing-axios-requests-with-jest-25no
CC-MAIN-2021-49
refinedweb
421
56.76
By Jeff Silverman, jeffsilverm at gmail dot com I am doing this work as a classroom project for The University of Washington Python Programming class. Most of the material is in github.com. To get it, give the following commands: [ps37854]$ mkdir dpkt_doc [ps37854]$ cd dpkt_doc [ps37854]$ git init . Initialized empty Git repository in /home/jeffsilverm/commercialventvac/dpkt_doc/.git/ [ps37854]$ git pull git://github.com/jeffsilverm/dpkt_doc.git remote: Counting objects: 3, done. remote: Compressing objects: 100% (2/2), done. remote: Total 3 (delta 0), reused 0 (delta 0) Unpacking objects: 100% (3/3), done. From git://github.com/jeffsilverm/dpkt_doc * branch HEAD -> FETCH_HEAD [ps37854]$ dpkt is an ethernet packet decoding module. It was written by Dugsong. Fundemental to understanding how dpkt works is the fact that it decodes single network packets. This has two consequences: For example, if you are doing an HTTP GET operation, then probably the entire header will fit into 1500 bytes, which is the default message transfer unit (MTU) size of an ethernet and most modern wide area networks as well. However, if you are doing an HTTP POST operation with a lot of data moving from the client browser to the web server, dpkt will be able to parse many of the headers but not all of them. These problems I have tried to solve with software that sits on top of dpkt's low level interfaces. For example, decode_tcp_iterator_2.py implements a crude TCP stack on top of dpkt. jeffs@heavy:/usr$ find . -name "*dpkt*" -print ./share/doc/python-dpkt ./share/pyshared/dpkt ./share/pyshared/dpkt/dpkt.py ./share/pyshared/dpkt-1.6.egg-info ./share/python-support/python-dpkt.public ./lib/pymodules/python2.6/dpkt ./lib/pymodules/python2.6/dpkt/dpkt.py ./lib/pymodules/python2.6/dpkt/dpkt.pyc ./lib/pymodules/python2.6/dpkt-1.6.egg-info ls /usr/share/pyshared/dpkt ah.py dpkt.py icmp.py ntp.py rip.py stp.py ah.pyc dpkt.pyc icmp.pyc ntp.pyc rip.pyc stp.pyc aim.py dtp.py igmp.py ospf.py rpc.py stun.py aim.pyc dtp.pyc igmp.pyc ospf.pyc rpc.pyc stun.pyc arp.py esp.py __init__.py pcap.py rtp.py tcp.py arp.pyc esp.pyc __init__.pyc pcap.pyc rtp.pyc tcp.pyc asn1.py ethernet.py ip6.py pim.py rx.py telnet.py asn1.pyc ethernet.pyc ip6.pyc pim.pyc rx.pyc telnet.pyc bgp.py gre.py ip.py pmap.py sccp.py t bgp.pyc gre.pyc ip.pyc pmap.pyc sccp.pyc t cdp.py gzip.py ipx.py pppoe.py sctp.py tns.py cdp.pyc gzip.pyc ipx.pyc pppoe.pyc sctp.pyc tns.pyc crc32c.py h225.py loopback.py ppp.py sip.py tpkt.py crc32c.pyc h225.pyc loopback.pyc ppp.pyc sip.pyc tpkt.pyc dhcp.py hsrp.py mrt.py qq.py sll.py udp.py dhcp.pyc hsrp.pyc mrt.pyc qq.pyc sll.pyc udp.pyc diameter.py http.py netbios.py radius.py smb.py vrrp.py diameter.pyc http.pyc netbios.pyc radius.pyc smb.pyc vrrp.pyc dns.py icmp6.py netflow.py rfb.py ssl.py yahoo.py dns.pyc icmp6.pyc netflow.pyc rfb.pyc ssl.pyc yahoo.pyc This decodes an IPSEC authentication header. Insofar as I can tell, dpkt.ah will only work for IPSEC over IPv4. AOL instant messenger Address resolution protocol. If the ethernet packet has type ETH_TYPE_ARP, then an dpkt.ethernet.Ethernet object will have an arp attribute. Refer to decode_arp.py. The length of the hardware address. For Ethernet, this is 6 bytes. The operation. 1=request, 2=reply The protocol address length. For IPv4, this is 4. The upper layer protocol for which the ARP request is intended. For IPv4, this has the value 0x0800. The permitted values share a numbering space with those for ethertype. The source hardware address (SHA). This should be the same as the source ethernet address but doesn't have to be. If the SHA and the ethernet source address are different, then you might suspect somebody trying to poison your arp cache. However, there are legitimate reasons why they might be different, most of which are anacronisms these days. Just because the source ethernet address and the SHA are the same, doesn't mean that nobody is trying to poison your arp cache. The source protocol address. This will usually be an IPv4 address. You will never see an IPv6 address here, because IPv6 uses neighbor discovery protocol. The target hardware address. In an ARP request, this will be 0. In an ARP reply, it should be the same as the Ethernet source address, but it doesn't have to be. You don't see this very often any more, but there used to be ARP servers which would supply ARP replies for hosts too dumb to provide their own ARP replies. You can also use this field to poison an ARP cache. The target protocol address. This is the address that ARP is going to translate into a MAC address. The IPv4 hosts in the network listen for ARP requests, which are sent to the broadcast Ethernet address. When a host sees its own IP address in the tpa field, it knows it has to reply with an ARP reply. In general, DNS runs on top of UDP. DNS can run on top of TCP and will do so if the query is large and also if there is a zone transfer. Many of the values in these fields come from IANA. Insofar as I can tell, dpkt doesn't provide the AD bit. The AD bit is set if this response is authoritative according to the policies of the server. A caching name server is generally not authoritative. Name servers return answers that have character values outside of the range 33 to 126 decimal inclusive. I don't know why. Both dig and wireshark are able to decipher the strings properly. A list of answers. Each answer is an RR record. For a DNS query, this is an empty list. To get the results from the DNS query, you have to iterate over the list and decode each RR record. Class. For modern resolvers, this should always be 1. There were other classes defined in RFC 1035, but nobody uses them anymore. This is the canonical name of the thing being looked up. The response will be applicable to this cname. The name that was looked up, before translation to a canonical name, if any. This is either an Authority Record or an Additional Record. qr is 0 if this message is a query and 1 if this message is a response. The ID field is set by the DNS resolver when it makes a query. The ID field is also set by the nameserver when it responds to the query. That way, the resolver knows which query the response is in response to. A list of name servers for this domain. To decode this list, iterate over each entry in the list and decode as in dpt.dns.an The opcode is 0 a standard query (QUERY), 1 an inverse query (IQUERY) (obsoleted by RFC 3425), 2 a server status request (STATUS), 3 is unassigned, 4 is Notify (RFC 1996), 5 is update, defined by RFC 2136 qr is 0 if this message is a query and 1 if this message is a response. Contains the data payload of the ethernet packet. Contains the destination address of the ethernet packet as a 6 byte strings. 6 Byte Ethernet addresses can be converted to strings in format nn:nn:nn:nn:nn:nn with the code: def add_colons_to_mac( mac_addr ) : """This function accepts a 12 hex digit string and converts it to a colon separated string""" s = list() for i in range(12/2) : # mac_addr should always be 12 chars, we work in groups of 2 chars s.append( mac_addr[i*2:i*2+2] ) r = ":".join(s) # I know this looks strange, refer to return r add_colons_to_mac( binascii.hexlify(arp.sha) ) Returns a class which is something from the Ethernet Type field (Pdb) print eth._typesw.keys() [2048, 8192, 34916, 2054, 34827, 33079, 8196, 34525] (Pdb) print eth._typesw.values() [<class 'dpkt.ip.IP'>, <class 'dpkt.cdp.CDP'>, <class 'dpkt.pppoe.PPPoE'>, <class 'dpkt.arp.ARP'>, <class 'dpkt.ppp.PPP'>, <class 'dpkt.ipx.IPX'>, <class 'dpkt.dtp.DTP'>, <class 'dpkt.ip6.IP6'>] (Pdb) print eth.get_type(2048) <class 'dpkt.ip.IP'> (Pdb) print eth.get_type(34525) <class 'dpkt.ip6.IP6'> (Pdb) Another way to do the same thing is: import dpkt eth = dpkt.ethernet.Ethernet() print eth._typesw[2048] <class 'dpkt.ip.IP'> print eth._typesw[34525] <class 'dpkt.ip6.IP6'> print eth._typesw[33079] <class 'dpkt.ipx.IPX'> Contains the source address of the ethernet packet as a 6 byte string. To decode to ASCII, see dst, above. Returns the Ethernet type. For example, type 2048 (0x0800) is IPv4 and 34525 (0x86DD) is IPv6. For a complete list of Ethernet types, refer to To get a list of ethernet types that are supported by dpkt, refer to the code at get_type. This is spanning tree protocol. Objects for decoding HTTP. The message going from the client browser to the server is the request, the message going from the server to the client browser is the response. Create a dpkt.http.Reply object from the received string. The received string probably will include the body of the response and may be quite large. Use a module such as decode_tcp_iterator_2 to combine the payloads of several packets into a single received string. This is the numeric code that the server returns to the browser which describes the outcome of the request. Values in the range of 1xx are continuation, values in the range of 2xx are success, values in the range of 3xx are relocations, values in the range of 4xx are errors from the client, values in the range of 5xx are errors in the server. The status is just 3 digits, there is an explanation of the error that is returned in dpkt.htt.Reply.reason. The full list of status codes is given in RFC 2616 section 10. The reason is a brief explanation of the status code. According to RFC 2616 section 6.1.1 the reason is for human use only and has no significance to the protocol. The body is the payload of the HTTP response. Its type is given by value of content-type header, which is a MIME type as described in RFC 2045, RFC 2046, and RFC 2047. The list of MIME types is maintained by the Internet Assigned Numbers Authority (IANA). headers is a dictionary of the headers of the reply. The keys are the headers that are present, the values are the values of those headers. The list of allowed headers is given by RFC 2616 section 14. Create a dpkt.http.Request object from the received string. If the HTTP request method is POST, then this attribute will contain the input that is passed to the server. If the method is GET, then this attribute will be an empty string. This is a dictionary. The keys of the dictionary are the header fields that are present and the values of the dictionary are the values of the field. For example: (Pdb) print http_req.headers {'host': '', 'connection': 'Keep-Alive', 'accept': '*/*', 'user-agent': 'Wget/1.12 (linux-gnu)'} (Pdb) When doing an HTTP request, the client browser refers to the object with a method. The most common methods are GET and PUT. The difference between GET and PUT has to do with how arguments are passed from the client to the server. With a GET, the arguments are passed in the URI separated by & characters. With a PUT, the values are passed as key value pairs in the body of the request. Refer to RFC 2616 section 9.1.2 for a discussion of methods and idempotence. For a list of valid methods, refer to RFC 2616 section 5.1. The URI (Uniform Resource Identifier) the the part of the URL (Uniform Resource Locator) which comes after the hostname. So, for example, the URI of the URL is /dpkt.html. The URI of the URL is / The version of HTTP. Valid values (as of this writing) are 0.9, 1.0, and 1.1 'data', 'dst', 'get_proto', 'hl', 'id', 'len', 'off', 'opts', 'p', 'pack', 'pack_hdr', 'set_proto', 'src', 'sum', 'tcp', 'tos', 'ttl', 'unpack', 'v', 'v_hl' This constructor can be used to create a packet. from dpkt.udp import UDP from dpkt.ip import IP import socket udp = UDP(data="testing") src=socket.inet_aton("127.0.0.1") dst=socket.inet_aton("67.205.52.141") ip = IP(src=src, dst=dst, data=udp ) ip IP(src='\x7f\x00\x00\x01', dst='C\xcd4\x8d', data=UDP(data='testing')) This is the payload of the IP packet The destination IPv4 address of the packet. You can convert the destination IP address to an ASCII string in dotted quad format using the socket package: import socket dst_ip_addr_str = socket.inet_ntoa(ip.dst) Internet Header Length is the length of the internet header in 32 bit words, and thus points to the beginning of the data. Note that the minimum value for a correct header is 5. This is the payload of the packet. Depending on ip6.nxt, this will be UDP, TCP, or similar. dpkt magically casts this into the proper datatype. This is the destination IPv6 address, 128 bits. To create a packed IPv6 address from an ASCII string: import socket dst_addr = socket.inet_pton(socket.AF_INET6, "2001:1938:26f:1:204:4bff:0:1") IPv6 defines a optimization called a "flow". If a router sees a packet with a non-zero flow for the first time, it makes its routing decision and stores that decision in a fast hash table. Then when subsequent packets come by with the same flow, the router can makes its routing decision faster. The flow is initialized by a random number generator on the host that is originating the connection. It can be left 0. The hop limit. Each time the packet hops from router to router, this field is decremented by 1. When the hlim reaches 0, the packet is discarded, and an ICMP6 type 3 packet is sent to the sender. tracepath6 uses this field to probe the path to a destination. It sends a packet with a small hlim. When the router decrements the hlim to zero and sends back the ICMPv6 packet to the sender, tracepath6 records the source address of the ICMPv6 packet and knows the IP address of the router. The next header type. If there is no next header, then the protocol of the next level in the stack. Typical values are 6 for TCP, 17 for UDP, 58 for ICMPv6, 132 for SCTP. For a list of protocols, see The payload length, not counting the IPv6 header. This is a 16 bit unsigned number. The source IPv6 address, which is 128 bits long. To decode the IPv6 address into an ASCII string comprehensible by humans, use the socket.inet_ntop method: import socket import dpkt eth = dpkt.ethernet.Ethernet(buf) ip = eth.data dst_ip_addr_str = socket.inet_ntop(AF_INET6, ip.dst) print dst_ip_addr_str This will give an output that looks like: 2001:1938:26f:1:204:4bff:0:1 This is the version of IP, which must be 6. If the ethernet type is 34525 and this is not 6, then throw an exception because something is wrong. dpkt.pcap.Reader(f) implements an iterator. Each iteration returns a tuple which is a timestamp and a buffer. The timestamp contains a time as a floating point number. The buffer is a complete packet. For example: #!/usr/bin/env python # -*- coding: utf-8 -*- import dpkt import sys f = open(sys.argv[1]) pcap = dpkt.pcap.Reader(f) frame_counter = 0 for ts, buf in pcap: frame_counter += 1 if frame_counter > 1 : print "%d: %f %f" % ( frame_counter, ts, ts - last_time ) last_time = ts f.close() TCP is a reliable, stream oriented protocol. Refer to RFC 793 for more information. This is the last byte that the receiver has received. The sender then knows that it need not resend any bytes prior to this point. The payload of this TCP segment. Note that the seqments may be delivered out of order, so it is not sufficient to simply join the payloads together. The maximum length of a TCP segment payload is the MTU size of this network less the length of the IP header less the length of a TCP header with no options. For example, Ethernet has an MTU of 1500 bytes (Most modern networks use this size to avoid fragmentation on all links - IPv6 the smallest MTU must be at least 1200 bytes but may be longer). The IPv4 header is 20 bytes, minimum. An IPv6 header is 40 bytes. The TCP header is 20 bytes, so the maximum length of a TCP segment is 1460 bytes for IPv4 and 1440 bytes for IPv6. The destination port of the packet, a 16 bit unsigned number. For a list of well known destination ports, refer to. If the SYN flag is set and the ACK flag is cleared, then this packet is the beginning of a connection and you may use the dport to determine what service is being used and how to decode the conversation. The TCP flags. To decode them, use the following code: fin_flag = ( tcp.flags & dpkt.tcp.TH_FIN ) != 0 syn_flag = ( tcp.flags & dpkt.tcp.TH_SYN ) != 0 rst_flag = ( tcp.flags & dpkt.tcp.TH_RST ) != 0 psh_flag = ( tcp.flags & dpkt.tcp.TH_PUSH) != 0 ack_flag = ( tcp.flags & dpkt.tcp.TH_ACK ) != 0 urg_flag = ( tcp.flags & dpkt.tcp.TH_URG ) != 0 ece_flag = ( tcp.flags & dpkt.tcp.TH_ECE ) != 0 cwr_flag = ( tcp.flags & dpkt.tcp.TH_CWR ) != 0 4 bits. Specifies the size of the TCP header in 32 bit longwords. The minimum size of a TCP header is 20 bytes (5 longwords) and the maximum is 60 bytes (15 longwords). This field gets its name because it is the offset from the beginning of the header to the data. This method parses the TCP options field into a list of (option number, option value) tuples. Use the code sequence option_list = dpkt.tcp.parse_opts ( tcp.opts ) to decode the options. For a fully worked, example, see the get_message_segment_size method in decode_tcp_iterator_2.py. A 32 bit unsigned number. If the SYN flag is set, then this is the initial sequence number, and all subsequent sequence numbers are relative to this number. If the SYN flag is clear, then this number is the location of the payload of this sequence in the data stream. Note that segment can be delivered out of order, so the sequence number is used to get the bytes back in order. The source port, a 16 bit unsigned number. On the initial connection, this will be an ephemeral port in the range 49152 through 6553 for most modern operating systems. A 16 bit unsigned number. Specifies how far past the current sequence number in this acknowlegement the receiver is willing to receive. There are a lot of classes that inherit from dpkt.Packet. I found these with the command egrep "class.*dpkt.Packet" *.py ah.py:class AH(dpkt.Packet): aim.py:class FLAP(dpkt.Packet): aim.py:class SNAC(dpkt.Packet): arp.py:class ARP(dpkt.Packet): bgp.py:class BGP(dpkt.Packet): bgp.py: class Open(dpkt.Packet): bgp.py: class Parameter(dpkt.Packet): bgp.py: class Authentication(dpkt.Packet): bgp.py: class Capability(dpkt.Packet): bgp.py: class Update(dpkt.Packet): bgp.py: class Attribute(dpkt.Packet): bgp.py: class Origin(dpkt.Packet): bgp.py: class ASPath(dpkt.Packet): bgp.py: class ASPathSegment(dpkt.Packet): bgp.py: class NextHop(dpkt.Packet): bgp.py: class MultiExitDisc(dpkt.Packet): bgp.py: class LocalPref(dpkt.Packet): bgp.py: class AtomicAggregate(dpkt.Packet): bgp.py: class Aggregator(dpkt.Packet): bgp.py: class Communities(dpkt.Packet): bgp.py: class Community(dpkt.Packet): bgp.py: class ReservedCommunity(dpkt.Packet): bgp.py: class OriginatorID(dpkt.Packet): bgp.py: class ClusterList(dpkt.Packet): bgp.py: class MPReachNLRI(dpkt.Packet): bgp.py: class MPUnreachNLRI(dpkt.Packet): bgp.py: class Notification(dpkt.Packet): bgp.py: class Keepalive(dpkt.Packet): bgp.py: class RouteRefresh(dpkt.Packet): bgp.py:class RouteGeneric(dpkt.Packet): bgp.py:class RouteIPV4(dpkt.Packet): bgp.py:class RouteIPV6(dpkt.Packet): cdp.py:class CDP(dpkt.Packet): cdp.py: class Address(dpkt.Packet): cdp.py: class TLV(dpkt.Packet): dhcp.py:class DHCP(dpkt.Packet): diameter.py:class Diameter(dpkt.Packet): diameter.py:class AVP(dpkt.Packet): dns.py:class DNS(dpkt.Packet): dns.py: class Q(dpkt.Packet): dtp.py:class DTP(dpkt.Packet): esp.py:class ESP(dpkt.Packet): ethernet.py:class Ethernet(dpkt.Packet): gre.py:class GRE(dpkt.Packet): gre.py: class SRE(dpkt.Packet): gzip.py:class GzipExtra(dpkt.Packet): gzip.py:class Gzip(dpkt.Packet): h225.py:class H225(dpkt.Packet): h225.py: class IE(dpkt.Packet): hsrp.py:class HSRP(dpkt.Packet): http.py:class Message(dpkt.Packet): icmp6.py:class ICMP6(dpkt.Packet): icmp6.py: class Error(dpkt.Packet): icmp6.py: class Echo(dpkt.Packet): icmp.py:class ICMP(dpkt.Packet): icmp.py: class Echo(dpkt.Packet): icmp.py: class Quote(dpkt.Packet): igmp.py:class IGMP(dpkt.Packet): ip6.py:class IP6(dpkt.Packet): ip.py:class IP(dpkt.Packet): ipx.py:class IPX(dpkt.Packet): loopback.py:class Loopback(dpkt.Packet): mrt.py:class MRTHeader(dpkt.Packet): mrt.py:class TableDump(dpkt.Packet): mrt.py:class BGP4MPMessage(dpkt.Packet): mrt.py:class BGP4MPMessage_32(dpkt.Packet): netbios.py:class Session(dpkt.Packet): netbios.py:class Datagram(dpkt.Packet): netflow.py:class NetflowBase(dpkt.Packet): netflow.py: class NetflowRecordBase(dpkt.Packet): ntp.py:class NTP(dpkt.Packet): ospf.py:class OSPF(dpkt.Packet): pcap.py:class PktHdr(dpkt.Packet): pcap.py:class FileHdr(dpkt.Packet): pim.py:class PIM(dpkt.Packet): pmap.py:class Pmap(dpkt.Packet): pppoe.py:class PPPoE(dpkt.Packet): ppp.py:class PPP(dpkt.Packet): radius.py:class RADIUS(dpkt.Packet): rfb.py:class RFB(dpkt.Packet): rfb.py:class SetPixelFormat(dpkt.Packet): rfb.py:class SetEncodings(dpkt.Packet): rfb.py:class FramebufferUpdateRequest(dpkt.Packet): rfb.py:class KeyEvent(dpkt.Packet): rfb.py:class PointerEvent(dpkt.Packet): rfb.py:class FramebufferUpdate(dpkt.Packet): rfb.py:class SetColourMapEntries(dpkt.Packet): rfb.py:class CutText(dpkt.Packet): rip.py:class RIP(dpkt.Packet): rip.py:class RTE(dpkt.Packet): rip.py:class Auth(dpkt.Packet): rpc.py:class RPC(dpkt.Packet): rpc.py: class Auth(dpkt.Packet): rpc.py: class Call(dpkt.Packet): rpc.py: class Reply(dpkt.Packet): rpc.py: class Accept(dpkt.Packet): rpc.py: class Reject(dpkt.Packet)
https://jeffsilverman-aaaa.ddns.net/dpkt.html
CC-MAIN-2021-43
refinedweb
3,808
51.55
How to use the “suggest” feature in pyes? Cannot seem to figure it out due to poor documentation. Could someone provide a working example? None of what I tried appears to work. In the docs its listed under query, but using: query = Suggest(fields="fieldname") connectionobject.search(query=query) Best answer Here is my code which runs perfectly. from elasticsearch import Elasticsearch es = Elasticsearch() text = 'ra' suggDoc = { "entity-suggest" : { 'text' : text, "completion" : { "field" : "suggest" } } } res = es.suggest(body=suggDoc, index="auto_sugg", params=None) print(res) I used the same client mentioned on the elasticsearch site here I indexed the data in the elasticsearch index by using completion suggester from here
https://pythonquestion.com/post/how-to-use-suggest-in-elasticsearch-pyes/
CC-MAIN-2020-16
refinedweb
110
50.53
![if !IE]> <![endif]> Objects in Flash In this section, we introduce object-oriented programming in Flash. We also demonstrate dynamic positioning (i.e., moving an object). We create two boxes. Each time you click on the left box, the right box will move to the left. Start by creating a new Flash document named Box.fla. Set the movie’s dimensions to 230 px wide and 140 px high. On the stage, draw a 100-px-wide blue box with a black outline and convert it into a movie-clip symbol. You can name this symbol box, but that is not necessary. Next, select the box on the stage and delete it, leaving the stage empty. This step ensures that the box will be added using the ActionScript code and that the box is not already on the stage. Now, create a new ActionScript File from the File > New menu, save it as BoxCode.as in the same directory as Box.fla, and add the code in Fig. 17.3. The properties x and y refer to the respective x- and y-coordinates of the boxes. The two imports (lines 5–6) at the top of the code allow for the code to utilize those two classes, which in this case are MouseEvent and Sprite, both of which are built-in Flash classes. Inside the class, the two Box instances are declared. By declaration of the two Box objects at the beginning of the class (lines 11–12), they become instance variables and have scope through the entire class. Once the boxes have been allocated positions (lines 18–21), they must be placed on the stage using the addChild function (lines 23–24). The function handleClick is called every time the user clicks box1. The addEventListener function, which is invoked by box1, specifies that handleClick will be called whenever box1 is clicked (line 27). 1 // Fig. 17.2: BoxCode.as 2 // Object animation in ActionScript. 3 package 4 { 5 import flash.events.MouseEvent; // import MouseEvent class 6 import flash.display.Sprite; // import Sprite class 7 8 public class BoxCode extends Sprite 9 { 10 // create two new box objects 11 public var box1 = new Box(); 12 public var box2 = new Box(); 13 14 // initialize Box coordinates, add Boxes 15 // to the stage and register MOUSE_DOWN event handler 16 public function BoxCode() : void 17 { 18 box1.x = 15; // set box1's x-coordinate 19 box1.y = 20; // set box1's y-coordinate 20 box2.x = 115; // set box2's x-coordinate box2.y = 20; // set box2's y-coordinate 22 23 addChild( box1 ); // add box1 to the stage 24 addChild( box2 ); // add box2 to the stage 25 26 // handleClick is called when box1 is clicked 27 box1.addEventListener( MouseEvent.MOUSE_DOWN, handleClick ); 28 } // end BoxCode constructor 29 30 // move box2 5 pixels to the left whenever box1 is clicked 31 private function handleClick( args : MouseEvent ) 32 { 33 box2.x -= 5; 34 } // end function handleClick 35 } // end class BoxCode 36 } // end package Fig. 17.3 | Object animation in ActionScript. To test the code, return to Box.fla. In the Library panel, right click the Box symbol and select Linkage. In the pop-up box, check off the box next to Export for ActionScript and type Box in the space provided next to Class. Ignore Flash’s warning that a definition for this class doesn’t exist in the classpath. Once you return to the stage, go to the Property Inspector panel and in the space next to Document Class, type BoxCode and press Enter. Now, the BoxCode ActionScript file has been linked to this specific Flash document. Type <Ctrl>-Enter to test the movie. Related Topics Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.
https://www.brainkart.com/article/Objects-in-Flash_10953/
CC-MAIN-2019-22
refinedweb
625
74.39
Computer Science Archive: Questions from April 28, 2007 - Anonymous askedWrite a C# application that will assist a learner ofvocabularly (German). Your application will load... Show moreWrite a C# application that will assist a learner ofvocabularly (German). Your application will load a list of wordpairs, present a word to the learner who will type in theirattempt on the translation.At start- up the application loads a pre-defined file called'word_list.txt' that contains word pairs likecat die Katzetoread lesebelow unterin the format of 'an English word' ,followed by a tab character '\t' , followed by Germantranslation- At the time of loading the word list the application needsto check for each line if this line has the correct format(that isa first part followed by a '\t' character followed a secondpart). Each line that does not fullfil this format needs to bewritten into a new file called 'wrong_lines.txt'. This fileneeds to be stored in your solution folder.- Prompted by the user the application shows an English wordfrom the list, selected randomly from all word pairs. The user caneither type the matching German word can ask the application for ahint. As a hint the application will provide the user with onecharacter from German word, randomly selcted from this word. Theuser can either ask for another hint (receiving one more randomlyselected character) or attempt the word. The user can submit theirword to the application .- The application will reveal the correct answer whenprom[pted by the user to do so. For example, after asking twice fora hint the information displayed could look like this;Word correct at first attempt - 10 pointsWord correct at first attempt after 2 hints - 8points.Word correct at third attempt - 7 pointsWord correct at thirds attempt after 2 hints - 5points.The number of attempts and hints requested for the currentword pair need to be displayed to the user.- The application keeps the total score. It needsto show the number of words attempted and the points scored.Guidelines for Implementation• Show less- Objects/Classes: define a 'WordPair'class which is responsible fordeciding if the use input provides a match andfor providing the hint;- ArrayList: load the word list into anArray List;- Array: use an array to help withproviding the hints;- Files: write lines of the input filethat have the wrong format into a file.Your help with how the code view will belike for this kind of application will be most highly appreciated.I have totally clue here.0 answers - Anonymous askedThe GUI... Show moreI have to write a Java program that uses the GUI to make acalculator that looks like this-- The GUI program does not have to have any functionality. This is what i have so far.... i cant get the input window to be onthe top line.. any help would be great. -------------------------------------------------- import java.awt.GridLayout; import java.awt.Container; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JButton; public class Program6 extends JFrame { private JButton buttons[]; private final String names[] = { "7", "8", "9","/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"}; private Container container; private GridLayout gridLayout1; private JTextField display = new JTextField( 10); public Program6() { super( "GridLayout Demo"); add( display ); gridLayout1 = newGridLayout( 4, 4, 0, 0 ); container =getContentPane(); setLayout( gridLayout1); container.setLayout(gridLayout1 ); buttons = new JButton[names.length ]; for ( int count = 0;count < names.length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); //buttons[ count ].addActionListener( this ); add( buttons[ count ] ); } } } ----------------------------------------------------- import javax.swing.JFrame; public class Program6Demo { public static void main( String args[] ) { Program6 gridLayoutFrame = new Program6(); gridLayoutFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); gridLayoutFrame.setSize( 250, 250 ); gridLayoutFrame.setVisible( true ); } } • Show less1 answer - Anonymous askeddouble and n is an in... Show more• Show less Write a function power(x, n) that willcompute the nth power of x, where x is a double and n is an int. As the power will be an integer, repeatedmultiplication using a for loop is one solution. Your function should return 1when n is 0. Extend your function to deal with negative n.1 answer - Anonymous askedTest the function by... Show moreWrite a function called swap that will exchange the two doubleparameters given.• Show less Test the function by assigning two different values to twovariables and using the function to swap the two values. Print out the values of the twovariables after the function call to check that the function has performed the correctaction. Swapping is used in many applications, but particularly in sorting.If you feel adventurous write a bubble sort program.1 answer - Anonymous askedinfinite loop on... Show moreAndrew Koenig states in C Traps and Pitfalls [3] states thatthe following causes an• Show less infinite loop on some systems. Can you work out why? #define N 10 int main() { int i; int a[N]; for (i = 0; i <= N; i++) a[i] = 0; return 0; }2 answers - Anonymous askedCreate a Java console based application that given the name of a file, will search the file system ... More »1 answer - Anonymous askedWhat are the pros and cons of theSynthesis approach to kernel design and to system-performanceoptimi... Show moreWhat are the pros and cons of theSynthesis approach to kernel design and to system-performanceoptimization? • Show less1 answer - Anonymous askeddiscuss the advantages and disadvantagesof incorporating more and more software applications into an... Show morediscuss the advantages and disadvantagesof incorporating more and more software applications into anoperating system (web browsers, e-mail, etc.). Consider thedesigner and user's points of view. • Show less1 answer - Smokey askedRelative cache pe... Show more Please indicate true or false for each of thefollowing statements. And WHY? 1) Relative cache penalties decrease if clock rate is increasedwithout changing the memory system. 2) Cache size and associativity are independent in determining cacheperformance. 3) Figure 7.17 on page 503 shows that all tags in the selected set arecompared sequentially. 4) The costs of an associative cache include extra comparators, extradelay imposed by comparison, and increased tag bits, comparing todirect-mapped cache. 5) With two-level cache structure, the goal of the primary caches isto reduce miss rate and the goal of the secondary cache is toreduce hit time.6) Secondary cache is usually larger than primarycache. • Show less1 answer - Anonymous askedSuppose the correspondent in Figure 6.17 weremobile. Sketch the additional network-layer infrastruc... Show more Suppose the correspondent in Figure 6.17 weremobile. Sketch the additional network-layer infrastructurethat would be needed to route the datagram from the original mobileuser to the (now mobile) correspondent. Show the structure ofdatagram(s) between the original mobile user and the (now mobile)correspondent, as in Figure 6.18.1 answer
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2007-april-28
CC-MAIN-2014-52
refinedweb
1,098
57.57
Best Practice: Should Not Block Threads If you're looking for the latest 3.x click here! When you have a choice, you should never block. For example, don’t do this: def fetchSomething: Future[String] = ??? // later ... val result = Await.result(fetchSomething, Duration.Inf) result.toUpperCase Prefer keeping the context of that Future all the way, until the edges of your program: def fetchSomething: Future[String] = ??? fetchSomething.map(_.toUpperCase) PRO-TIP: for Scala’s Future, checkout the Scala-Async project to make this easier. REASON: blocking threads is error prone because you have to know and control the configuration of the underlying thread-pool. For example even Scala’s ExecutionContext.Implicits.global has an upper limit to the number of threads spawned, which means that you can end up in a dead-lock, because all of your threads can end up blocked, with no threads available in the pool to finish the required callbacks. If blocking, specify explicit timeouts If you have to block, specify explicit timeouts for failure and never use APIs that block on some result and that don’t have explicit timeouts. For example Scala’s own Await.result is very well behaved ands that’s good: Await.result(future, 3.seconds) But for example when using Java’s Future, never do this: val future: java.util.concurrent.Future[T] = ??? // BAD CODE, NEVER DO THIS !!! future.get Instead always specify timeouts, because in case the underlying thread-pool is limited and there are no more threads left, at least some of them will get unblocked after the specified timespan: val future: java.util.concurrent.Future[T] = ??? // GOOD future.get(TimeUnit.SECONDS, 3) If blocking, use Scala’s BlockContext This includes all blocking I/O, including SQL queries. Real sample: // BAD SAMPLE! Future { DB.withConnection { implicit connection => val query = SQL("select * from bar") query() } } Blocking calls are error-prone because one has to be aware of exactly what thread-pool gets affected and given the default configuration of the backend app, this can lead to non-deterministic dead-locks. It’s a bug waiting to happen in production. Here’s a simplified example demonstrating the issue for didactic purposes:) } This sample is simplified to make the effect deterministic, but all thread-pools configured with upper bounds will sooner or later be affected by this. Blocking calls have to be marked with a blocking call that signals to the BlockContext a blocking operation. It’s a very neat mechanism in Scala that lets the ExecutionContext know that a blocking operation happens, such that the ExecutionContext can decide what to do about it, such as adding more threads to the thread-pool (which is what Scala’s ForkJoin thread-pool does). WARNING: Scala’s ExecutionContext.Implicits.global is backed by a cool ForkJoinPool implementation that has an absolute maximum number of threads limit. What this means is that, in spite of well behaved code, you can still hit that limit and you can still end up in a dead-lock. This is why blocking threads is error prone, as nothing saves you from knowing and controlling the thread-pools that you end up blocking. If blocking, use a separate thread-pool for blocking I/O If you’re doing a lot of blocking I/O (e.g. a lot of calls to JDBC), it’s better to create a second thread-pool / execution context and execute all blocking calls on that, leaving the application’s thread-pool to deal with CPU-bound stuff. So you could initialize another I/O related thread-pool like so: import java.util.concurrent.Executors // ... private val io = Executors.newCachedThreadPool( new ThreadFactory { private val counter = new AtomicLong(0L) def newThread(r: Runnable) = { val th = new Thread(r) th.setName("io-thread-" + counter.getAndIncrement.toString) th.setDaemon(true) th } }) Note that here I prefer to use an unbounded “cached thread-pool”, so it doesn’t have a limit. When doing blocking I/O the idea is that you’ve got to have enough threads that you can block. But if unbounded is too much, depending on use-case, you can later fine-tune it, the idea with this sample being that you get the ball rolling. You could also use Monix’s Scheduler.io of course, which is also backed by a “cached thread-pool”: import monix.execution.Scheduler private val io = Scheduler.io(name="engine-io") And then you could provide a helper, like: def executeBlockingIO[T](cb: => T): Future[T] = { val p = Promise[T]() io.execute(new Runnable { def run() = try { p.success(blocking(cb)) } catch { case NonFatal(ex) => logger.error(s"Uncaught I/O exception", ex) p.failure(ex) } }) p.future }
https://monix.io/docs/2x/best-practices/blocking.html
CC-MAIN-2019-51
refinedweb
779
55.54
Xml the future. In this tip, let us see how to parse an Xml Document using SAX Technique. also read: Before that, it is important to understand the architecture behind SAX Parsing. SAX usually follows Push-based parsing, in which case, the Parser will scan the XML Document from top to bottom and whenever it founds some node (like start node, end node, text-node etc.) it will push notifications to the Application in the form of Events. So, SAX is basically a sequential, event-based parser. For example, let us consider the following XML folders.xml which we are going to parse using SAX technique. folders.xml <?xml version='1.0' encoding='UTF-8'?> <folders> <folder name = 'softwares'> <file name = 'Winamp'/> <file name = 'Java'/> <file name = 'Xml Editor'/> </folder> <folder name = 'users'> <file name = 'Admin'/> <file name = 'guest'/> <file name = 'jenny'/> </folder> </folders> Before getting into the sample code, let us spend some time in understanding the various common jargons related to Xml. At a higher level, XML Documents are nothing but collection of nodes. For example, in the above document, folders is called the root node and it has two child nodes namely folder. The node 'folder' has an attribute called 'name'. Even an attribute is treated as a node during XML Parsing. Given below is the code sample for XML Parsing, SaxReader.java package tips.xml.sax; import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class SaxReader { public static void main(String[] args) throws Exception { SAXParser parser = SAXParserFactory.newInstance() .newSAXParser(); FolderHandler handler = new FolderHandler(); parser.parse(new File('folders.xml'), handler); } } A SAXPArserFactory follows the factory pattern to create instances of SAXParser objects that can be used for parsing. The default implementation that ships along with JDK Distribution is Apache XML Parsing and it also can be overridden with someother vendor’s implementation. Now, in order to handle Events that are emitted as a result of Parser parsing the XML Document, we have defined a new class called FolderHandler and has passed an instance of the same to SAXParser.parse() method along with the file object. Following is the class definition for FolderHandler. FolderHandler.java package tips.xml.sax; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class FolderHandler extends DefaultHandler { public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.println(); System.out.print('<' + qName + ''); if (attributes.getLength() == 0){ System.out.print('>'); }else{ System.out.print(' '); for(int index = 0; index < attributes.getLength(); index ++){ System.out.print( attributes.getLocalName(index) + ' => ' + attributes.getValue(index)); } System.out.print('>'); } } public void endElement (String uri, String localName, String qName) throws SAXException { System.out.print('n</' + qName + '>'); } } Note that the above class extends DefaultHandler which is just an Adapter class giving empty implementations for the various abstract like startDocument(), endDocument(), startElement() and endElement(). The methods of interest in our case are startElement() and endElement(). The method startElement() will be called as soon as the parser encounters the start xml node like <folder> and the endElement() will be called when the parser visits the element </folder>. Note that the document will be parsed sequentially. So, in our case, the events happen in the following order, startElement – for the root <folders> element startElement – for the first <folder> element startElement – for the first <file> element within the first <folder> element endElement – for the first <file> element within the first <folder> element startElement – for the second <file> element within the first <folder> element endElement – for the second <file> element within the first <folder> element and so on… Now, let us look into the various argument passed on to the startElement() and the endElement() method. Four arguments are being passed to the startElement() method and the arguments of our interest are the 3rd and the 4th argument, qName (or) Qualified name which is literally the node name and arrtibutes, which represents a list of attributes for a particular node. We have made some simple logic within the startElement() method so that we get the output in the following xml-like format, <folders> <folder name => softwares> <file name => Winamp> </file> <file name => Java> </file> <file name => Xml Editor> </file> </folder> <folder name => users> <file name => Admin> </file> <file name => guest> </file> <file name => jenny> </file> </folder> </folders> […] Try out this tutorial ,this will help u: […]
http://javabeat.net/parsing-xml-documents-using-sax/
CC-MAIN-2017-17
refinedweb
735
55.64
Writing Neovim Plugins — A Beginner Guide (Part 1) A beginner guide on writing Neovim plugins in Lua. Overview. Table of Contents - Startup Options - Runtimepath - Setting Runtimepath - Use Custom Configuration File - Setting up LSP (Optional) - Plugin DIrectories Structure - Hello World Plugin - Define Plugin Command - Documentation - Publishing Plugin - Installation and Testing - Further Readings - Summary - References Startup Options Let’s first explore different methods to start Neovim without loading vimrc files or plugins. There are different ways that you can start Neovim without initialization. nvim -u NONE: Start Neovim without loading vimrcfiles and plugins nvim -u NORC: Start Neovim without loading vimrcfiles, but still load the plugins. nvim --noplugin: Start Neovim, load vimrcfiles but not the plugins. nvim --clean: Equivalent to “ -u NONE -i NONE”. Skips initializations from files and environment variables. No ‘ shada’ file is read or written. Excludes user directories from ‘ runtimepath’. To show you the default runtimepath, I am going to use the --clean option to start Neovim with a clean environment. Type " :h --clean” to check out the documentation. $ nvim --clean Runtimepath Type :h rtp to check out the documentation for runtimepath. runtimepath is a list of directories to be searched for these runtime files. You may already be familiar with some of these directories. autoload: automatically load scripts ( :h autoload-functions) colors: color scheme files ( h :colorscheme) compiler: compiler files ( :h compiler) doc: documentation ( :h write-local-help) ftplugin: filetype plugins ( :h write-filetype-plugin) pack: packages ( :h packadd) plugin: plugin scripts ( :h write-plugin) syntax: syntax files ( :h mysyntaxfile) lua: Lua files. Only applicable for Neovim ( :h lua) If you install any plugins, you can see that “ runtimepath” contains folders of the plugins. To view the runtimepath, you can either - type :set rtp? - use the expression register. In Insertmode, type Control-R =, and type &rtp, and runtimepathwill show in the current buffer. Setting Runtimepath To develop plugins, we need to configure runtimepath so that it has the current development directory. There are few options you can set this up. Startup During startup, Neovim allows you to pass in the command. $ nvim --cmd "set rtp+=$(pwd)" Now check again runtimepath and you should be able to see the current folder. Using Vimscript Alternatively, after you start up Neovim, you can use the following command to set the runtimepath to the current folder. :let &runtimepath.=','.escape(expand('%:p:h'), '\,') Plugin Manager In most cases, you are likely to use a plugin manager, e.g. vim-plug, or packer.nvim. Most plugin managers should support local plugins and set the runtimepath accordingly. E.g. for vim-plug (code snippet available here), " Local plugins Plug '~/workspace/development/alpha2phi/alpha.nvim' for packer.nvim, -- Local plugins can be included use '~/projects/personal/hover.nvim' Use Custom Configuration File And to use a particular configuration file, you can either - Use the $XDG_CONFIG_HOME option during startup. E.g., $ XDG_CONFIG_HOME=$HOME/.xdg_home /usr/local/bin/nvim The “base” (root) directories conform to the XDG Base Directory Specification. In the above case, Neovim looks for the configuration file under $HOME/.xdg_home/nvim folder. Type :h $XDG_CONFIG_HOME to read the documentation. - Use the -ustart-up option to point to the .vimor .luaconfiguration file. $ nvim -u /path/to/myconfig.vim $ nvim -u /path/to/myconfig.lua Type :h startup-options to read the documentation. Setting up LSP (Optional) Since we are developing plugins, it makes sense to set up LSP for Lua and Vimscript. Lua Refer to this article to set up LSP for Lua. Vimscript For Vimscript, we can use the Vim language server. The instructions to set up should be similar to other languages as described in this article. Plugin Directories Structure With the runtimepath configured to point to our project directory, let’s create these 3 folders. plugin lua doc Files inside plugin will each be run once every time Neovim starts. These files are meant to contain code that you always want to be loaded whenever you start NeoVim. Files inside lua contain Lua scripts, and doc folder contains your plugin documentation. For all the possible directories, type :h rtp. Now create the following directories and files. plugin/dev.vim plugin/alpha.vim lua/hello/init.lua lua/hello/helloworld.lua doc/alpha.txt Hello World Plugin Hello World Module Add the below lines into lua/hello/helloworld.lua. local M = {}function M.sayHelloWorld() print('Hello world!!') endreturn M This is a very simple Lua module. Refer here if you are not familiar with the Lua module. Add the below lines into lua/hello/init.lua local hello = require('hello.helloworld')return hello Type :h lua-require to understand more on Lua require. Testing Now run :lua require(“hello”).sayHelloWorld() and you should see “ Hello world!!” printed. Module Reloading Now change lua/hello/helloworld.lua. Instead of “ Hello world!!”, change it to “ Hello world again!!" Run :lua require(“hello”).sayHelloWorld() and you will still see “ Hello world!!”. This is because the “ hello” module has been loaded by Neovim and does not get refreshed after we make the change. Now add these lines into plugin/dev.vim function! ReloadAlpha() lua << EOF for k in pairs(package.loaded) do if k:match("^hello") then package.loaded[k] = nil end end EOF endfunction" Reload the plugin nnoremap <Leader>pra :call ReloadAlpha()<CR>" Test the plugin nnoremap <Leader>ptt :lua require("hello").sayHelloWorld()<CR> ReloadAlphabasically unloads the hellomodule. - I also create the key bindings to reload the module and test the plugin. Now either restart Neovim or source dev.vim by running :so %. <Leader>pra and then <Leader>ptt and you should see the latest change. Define Plugin Command Add these lines into plugin/alpha.vim. if exists('g:loaded_alpha') | finish | endif " prevent loading file twicelet s:save_cpo = &cpo " save user coptions set cpo&vim " reset them to defaults" command to run our plugin command! AlphaHelloWorld lua require("hello").sayHelloWorld()let &cpo = s:save_cpo " and restore after unlet s:save_cpolet g:loaded_alpha = 1 - I define the AlphaHelloWorldcommand to call our hellomodule - Type :h cpoto read the documentation on “ compatible options” Documentation Add these to doc/alpha.txt. Publishing Plugin Publishing the plugin is as simple as committing the project to Github. plugin/dev.vim is only for development purposes. You may want to exclude this file from commit by including it in .gitignore. Installation and Testing Now use your favorite plugin manager to install the plugin. E.g., using vim-plug, Plug 'alpha2phi/alpha.nvim' - Run “ :PlugInstall” to install the plugin. - Type “ :AlphaHelloWorld” and the “ Hello world” message gets printed. - Type “ :h alpha.nvim” or “ :h AlphaHelloWorld” and you should see the help documentation. Further Readings - Type :h luato read the Lua introduction. - Neovim Lua Guide. Summary Now we have the “ hello world” version of our plugin. In the next article let’s continue to enhance the plugin. The plugin source code can be found in this repository.
https://alpha2phi.medium.com/writing-neovim-plugins-a-beginner-guide-part-i-e169d5fd1a58
CC-MAIN-2021-25
refinedweb
1,140
51.55
While: - Specified Default User ID: PSEM - Specified Default Service Namespace: <your login URL or:> - Default Permission List: PTPT1000 The namespace is the option that confused me the most. According to PeopleBooks, “The namespace field on the Service pages provides qualification for attributes and elements within a WSDL document. The value defined in the Service Namespace field in the Service Configuration page is used as the default service namespace on the Services page. The default value is.” If you have better suggestions for the values to use, please comment! Resources Hi Stephen, Am a HR professional and would like to learn Peoplesoft. I have tried to find some resources online but could get the info. I Basically want to install Peoplesoft on my system can you please let me know how to do it and where to find the software. And also self learn People soft HCM Module. More on the functional side as I am not from the software background. Will you be able to help me out in this regard. It would be of great help. Thanks, Roopa Roopa, Some of the articles on my blog might help a little. The “Virtual PeopleSoft Installation” is a start: Even though it is an upgrade, the PeopleTools 8.51 upgrade may help: Unfortunately, the install process is very technical. There are a lot of pieces that you have to install and get working together. Oracle does offer some preinstalled virtual machines called templates, but even those take some technical work to get up and running. All of the software you can download either from Oracle’s website or from. Unless you have a license for Microsoft’s SQL Server, you will want to use the Oracle database. You will need at least 2GB of RAM, but 4GB is better. I would allow 100GB of hard drive space, but you can probably make it work in 50GB. I have yet to make a full Linux install work, so you will at least need Windows installed somewhere. Therefore, I would install PeopleSoft fully on Windows. This probably isn’t the answer you want to hear, but the bright side is that I have met many a functional person who has come to the technical world. So, you can do it if you are willing to put the effort into it. In my opinion, going through an install will help you understand the functional world even better and give you skills that make you more valuable even if you never do another install! Hope that helps, Stephen Hello Stephen, I realize it’s a bit late on this one, sorry for that. What’s your source Peopletools version ? According to the Oracle Peopletools upgrade guide (), you should not have been prompted for that step (if I’m not wrong the entire step 4.17 – page 61) since it is only for upgrading a database source running on Peopletools 8.47 and earlier. Nicolas.
http://psst0101.digitaleagle.net/2011/06/05/how-to-edit-ptibupgrade-dms/
CC-MAIN-2016-50
refinedweb
489
72.66
From: Corwin Joy (cjoy_at_[hidden]) Date: 2001-06-22 19:09:18 ----- Original Message ----- From: "Beman Dawes" <bdawes_at_[hidden]> To: <boost_at_[hidden]>; <boost_at_[hidden]> Sent: Friday, June 22, 2001 6:40 PM Subject: Re: [boost] Question about leading underscores > At 06:40 PM 6/22/2001, Greg Colvin wrote: > > >The safe rule is not to use leading underscores, although I > >think those above are technically OK, if useless. > > Why? Lots of programmers (me included) use a single leading underscore in > private member names. It never causes any problems, and is completely > standard conforming. > > The trouble with putting two underscores in a variable name is that you might end up colliding with a preprocessor / #define macro defined by the standard library. Since these #defines don't have scope you can't be safe from them and so and so as noted below the standard reserves certain names which it may replace by #define macros. Here is a related post that appeared recently on comp.c++.moderated. ----- Original Message ----- From: "Pete Becker" <petebecker_at_[hidden]> Newsgroups: comp.lang.c++.moderated Sent: Monday, June 18, 2001 4:05 PM Subject: Re: Header protection against forbidden marcos > Attila Feher wrote: > > > > Hi All, > > > > I need some help in this trouble. As far as I know the only portable > > way for protecting header multiply inclusion is the good-old #ifndef, > > #define, stuff, #endif. However the C++ standard (for whatever reason) > > reserves _all_ macros for the standard library... > > No, it doesn't. Basically, all names that begin with an underscore > followed by a capital letter or by another underscore are reserved, just > as in C (it's actually a little broader: any name containing two > underscores is reserved, not just ones that begin with two underscores). > Users are free to guard their headers with their own macros, and > typically name them after the header: > > #ifndef Whatever_hh > #define Whatever_hh > // ... > #endif > > -- > Pete Becker > Dinkumware, Ltd. () > ----- End Original Message from comp.c++.moderated----- <..Beman continues...> > That choice was based in an experiment some years ago trying several > candidates (including none, trailing underscore, and some others I can't > remember.) Leading underscore won. > > --Beman > > >17.4.3.1.2 Global names [lib.global.names] > > > >1 Certain imple- > > mentation for use as a name in the global namespace.22) > > > > _________________________ > > 22) Such names are also reserved in namespace ::std (_lib.re- > > served.names_). > Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2001/06/13554.php
CC-MAIN-2019-47
refinedweb
412
55.84
Sponsored Post Creating One Browser Extension For All Browsers: Edge, Chrome, Firefox, Opera, Brave And Vivaldi By David Rousset April 5th, 2017 BrowsersCSSExtensions 0 Comments In today’s article, we’ll create a JavaScript extension that works in all major modern browsers, using the very same code base. Indeed, the Chrome extension model based on HTML, CSS and JavaScript is now available almost everywhere, and there is even a Browser Extension Community Group1. Note: We won’t cover Safari in this article because it doesn’t support the same extension model2 as others. Further Reading on SmashingMag: Link Creating A “Save For Later” Chrome Extension With Modern Web Tools3 What’s The Deal With The Samsung Internet Browser?4 Form Inputs: The Browser Support Issue You Didn’t Know You Had5 Chrome, Firefox, Safari, Opera, Edge? Impressive Web Browser Alternatives6 Basics Link I won’t cover the basics of extension development because plenty of good resources are already available from each vendor: Google7 Microsoft8 (also, see the great overview video “Building Extensions for Microsoft Edge9”) Mozilla10 (also, see the wiki11) Opera12 Brave13 So, if you’ve never built an extension before or don’t know how it works, have a quick look at those resources. Don’t worry: Building one is simple and straightforward. Our Extension Link Let’s build a proof of concept — an extension that uses artificial intelligence (AI) and computer vision to help the blind analyze images on a web page. We’ll see that, with a few lines of code, we can create some powerful features in the browser. In my case, I’m concerned with accessibility on the web and I’ve already spent some time thinking about how to make a breakout game accessible using web audio and SVG14, for instance. Still, I’ve been looking for something that would help blind people in a more general way. I was recently inspired while listening to a great talk by Chris Heilmann15 in Lisbon: “Pixels and Hidden Meaning in Pixels16.” Indeed, using today’s AI algorithms in the cloud, as well as text-to-speech technologies, exposed in the browser with the Web Speech API17 or using a remote cloud service, we can very easily build an extension that analyzes web page images with missing or improperly filled alt text properties. My little proof of concept simply extracts images from a web page (the one in the active tab) and displays the thumbnails in a list. When you click on one of the images, the extension queries the Computer Vision API to get some descriptive text for the image and then uses either the Web Speech API or Bing Speech API to share it with the visitor. The video below demonstrates it in Edge, Chrome, Firefox, Opera and Brave. You’ll notice that, even when the Computer Vision API is analyzing some CGI images, it’s very accurate! I’m really impressed by the progress the industry has made on this in recent months. I’m using these services: Computer Vision API18, Microsoft Cognitive Services This is free to use19 (with a quota). You’ll need to generate a free key; replace the TODO section in the code with your key to make this extension work on your machine. To get an idea of what this API can do, play around with it20. 21 Bing Text to Speech API22, Microsoft Cognitive Services This is also free to use23 (with a quota, too). You’ll need to generate a free key again. We’ll also use a small library24 that I wrote recently to call this API from JavaScript. If you don’t have a Bing key, the extension will always fall back to the Web Speech API, which is supported by all recent browsers. But feel free to try other similar services: Visual Recognition25, IBM Watson Cloud Vision API26, Google You can find the code for this small browser extension on my GitHub page27. Feel free to modify the code for other products you want to test. Tip To Make Your Code Compatible With All Browsers Link Most of the code and tutorials you’ll find use the namespace chrome.xxx for the Extension API (chrome.tabs, for instance). But, as I’ve said, the Extension API model is currently being standardized to browser.xxx, and some browsers are defining their own namespaces in the meantime (for example, Edge is using msBrowser). Fortunately, most of the API remains the same behind the browser. So, it’s very simple to create a little trick to support all browsers and namespace definitions, thanks to the beauty of JavaScript: window.browser = (function () { return window.msBrowser window.browser window.chrome; })(); And voilà! Of course, you’ll also need to use the subset of the API supported by all browsers. For instance: Microsoft Edge has a list of support28. Mozilla Firefox shares its current Chrome incompatibilities29. Opera maintains its own list of extension APIs supported30 by its browser. Extension Architecture Link Let’s review together the architecture of this extension. If you’re new to browser extensions, this should help you to understand the flow. Let’s start with the manifest file31: 32(View large version33) This manifest file and its associated JSON is the minimum you’ll need to load an extension in all browsers, if we’re not considering the code of the extension itself, of course. Please check the source34 in my GitHub account, and start from here to be sure that your extension is compatible with all browsers. For instance, you must specify an author property to load it in Edge; otherwise, it will throw an error. You’ll also need to use the same structure for the icons. The default_title property is also important because it’s used by screen readers in some browsers. Here are links to the documentation to help you build a manifest file that is compatible everywhere: Chrome35 Edge36 Firefox37 The sample extension used in this article is mainly based on the concept of the content script38. This is a script living in the context of the page that we’d like to inspect. Because it has access to the DOM, it will help us to retrieve the images contained in the web page. If you’d like to know more about what a content script is, Opera39, Mozilla40 and Google41 have documentation on it. Our content script42 is simple: 43(View large version44) console.log("Dare Angel content script started"); browser.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request.command == "requestImages") { var images = document.getElementsByTagName('img'); var imagesList = []; for (var i = 0; i 64 images[i].height 64)) { imagesList.push({ url: images[i].src, alt: images[i].alt }); } } sendResponse(JSON.stringify(imagesList)); } }); view raw This first logs into the console to let you check that the extension has properly loaded. Check it via your browser’s developer tool, accessible from F12, Control + Shift + I or ⌘ + ⌥ + I. It then waits for a message from the UI page with a requestImages command to get all of the images available in the current DOM, and then it returns a list of their URLs if they’re bigger than 64 × 64 pixels (to avoid all of the pixel-tracking junk and low-resolution images). 45(View large version46) The popup UI page47 we’re using is very simple and will display the list of images returned by the content script inside a flexbox container48. It loads the start.js script, which immediately creates an instance of dareangel.dashboard.js49 to send a message to the content script to get the URLs of the images in the currently visible tab. Here’s the code that lives in the UI page, requesting the URLs to the content script: browser.tabs.query({ active: true, currentWindow: true }, (tabs) = { browser.tabs.sendMessage(tabs[0].id, { command: "requestImages" }, (response) = { this._imagesList = JSON.parse(response); this._imagesList.forEach((element) = { var newImageHTMLElement = document.createElement("img"); newImageHTMLElement.src = element.url; newImageHTMLElement.alt = element.alt; newImageHTMLElement.tabIndex = this._tabIndex; this._tabIndex++; newImageHTMLElement.addEventListener("focus", (event) = { if (COMPUTERVISIONKEY !== "") { this.analyzeThisImage(event.target.src); } else { var warningMsg = document.createElement("div"); warningMsg.innerHTML = "Please generate a Computer Vision key in the other tab. Link"; this._targetDiv.insertBefore(warningMsg, this._targetDiv.firstChild); browser.tabs.create({ active: false, url: "" }); } }); this._targetDiv.appendChild(newImageHTMLElement); }); }); }); We’re creating image elements. Each image will trigger an event if it has focus, querying the Computer Vision API for review. This is done by this simple XHR call: analyzeThisImage(url) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = () = { if (xhr.readyState == 4 xhr.status == 200) { var response = document.querySelector('#response'); var reponse = JSON.parse(xhr.response); var resultToSpeak = `With a confidence of ${Math.round(reponse.description.captions[0].confidence * 100)}%, I think it's ${reponse.description.captions[0].text}`; console.log(resultToSpeak); if (!this._useBingTTS || BINGSPEECHKEY === "") { var synUtterance = new SpeechSynthesisUtterance(); synUtterance.text = resultToSpeak; window.speechSynthesis.speak(synUtterance); } else { this._bingTTSclient.synthesize(resultToSpeak); } } }; xhr.onerror = (evt) = { console.log(evt); }; try { xhr.open('POST', ''); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("Ocp-Apim-Subscription-Key", COMPUTERVISIONKEY); var requestObject = { "url": url }; xhr.send(JSON.stringify(requestObject)); } catch (ex) { console.log(ex); } } view raw The following articles will you help you to understand how this Computer Vision API works: “Analyzing an Image Version 1.050,” Microsoft Cognitive Services “Computer Vision API, v1.051,” Microsoft Cognitive Services This shows you via an interactive console in a web page how to call the REST API with the proper JSON properties, and the JSON object you’ll get in return. It’s useful to understand how it works and how you will call it. In our case, we’re using the describe feature of the API. You’ll also notice in the callback that we will try to use either the Web Speech API or the Bing Text-to-Speech service, based on your options. Here, then, is the global workflow of this little extension: 52(View large version53) Loading The Extension In Each Browser Link Let’s review quickly how to install the extension in each browser. Prerequisites Link Download or clone my small extension54 from GitHub somewhere to your hard drive. Also, modify dareangel.dashboard.js to add at least a Computer Vision API key. Otherwise, the extension will only be able to display the images extracted from the web page. Microsoft Edge Link First, you’ll need at least a Windows 10 Anniversary Update (OS Build 14393+) to have support for extensions in Edge. Then, open Edge and type about:flags in the address bar. Check the “Enable extension developer features.” 55 Click on “…” in the Edge’s navigation bar and then “Extensions” and then “Load extension,” and select the folder where you’ve cloned my GitHub repository. You’ll get this: 56 Click on this freshly loaded extension, and enable “Show button next to the address bar.” 57 Note the “Reload extension” button, which is useful while you’re developing your extension. You won’t be forced to remove or reinstall it during the development process; just click the button to refresh the extension. Navigate to BabylonJS626158, and click on the Dare Angel (DA) button to follow the same demo as shown in the video. Google Chrome, Opera, Vivaldi Link In Chrome, navigate to chrome://extensions. In Opera, navigate to opera://extensions. And in Vivaldi, navigate to vivaldi://extensions. Then, enable “Developer mode.” Click on “Load unpacked extension,” and choose the folder where you’ve extracted my extension. 59(View large version60) Navigate to BabylonJS626158, and open the extension to check that it works fine. Mozilla Firefox Link You’ve got two options here. The first is to temporarily load your extension, which is as easy as it is in Edge and Chrome. Open Firefox, navigate to about:debugging and click “Load Temporary Add-on.” Then, navigate to the folder of the extension, and select the manifest.json file. That’s it! Now go to BabylonJS626158 to test the extension. 63(View large version64) The only problem with this solution is that every time you close the browser, you’ll have to reload the extension. The second option would be to use the XPI packaging. You can learn more about this in “Extension Packaging65” on the Mozilla Developer Network. Brave Link The public version of Brave doesn’t have a “developer mode” embedded in it to let you load an unsigned extension. You’ll need to build your own version of it by following the steps in “Loading Chrome Extensions in Brave66.” As explained in that article, once you’ve cloned Brave, you’ll need to open the extensions.js file in a text editor. Locate the lines below, and insert the registration code for your extension. In my case, I’ve just added the two last lines: // Manually install the braveExtension and torrentExtension extensionInfo.setState(config.braveExtensionId, extensionStates.REGISTERED) loadExtension(config.braveExtensionId, getExtensionsPath('brave'), generateBraveManifest(), 'component') extensionInfo.setState('DareAngel', extensionStates.REGISTERED) loadExtension('DareAngel', getExtensionsPath('DareAngel/')) view raw Copy the extension to the app/extensions folder. Open two command prompts in the browser-laptop folder. In the first one, launch npm run watch, and wait for webpack to finish building Brave’s Electron app. It should say, “webpack: bundle is now VALID.” Otherwise, you’ll run into some issues. 67(View large version68) Then, in the second command prompt, launch npm start, which will launch our slightly custom version of Brave. In Brave, navigate to about:extensions, and you should see the extension displayed and loaded in the address bar. 69(View large version70) Debugging The Extension In Each Browser Link Tip for all browsers: Using console.log(), simply log some data from the flow of your extension. Most of the time, using the browser’s developer tools, you’ll be able to click on the JavaScript file that has logged it to open it and debug it. Microsoft Edge Link To debug the client script part, living in the context of the page, you just need to open F12. Then, click on the “Debugger” tab and find your extension’s folder. Open the script file that you’d like to debug — dareangel.client.js, in my case — and debug your code as usual, setting up breakpoints, etc. 71(View large version72) If your extension creates a separate tab to do its job (like the Page Analyzer73, which our Vorlon.js74 team published in the store), simply press F12 on that tab to debug it. 75(View large version76) If you’d like to debug the popup page, you’ll first need to get the ID of your extension. To do that, simply go into the property of the extension and you’ll find an ID property: 77 Then, you’ll need to type in the address bar something like ms-browser-extension://ID_of_your_extension/yourpage.html. In our case, it would be ms-browser-extension://DareAngel_vdbyzyarbfgh8/dashboard.html. Then, simply use F12 on this page: 78(View large version79) Google Chrome, Opera, Vivaldi, Brave Link Because Chrome and Opera rely on the same Blink code base, they share the same debugging process. Even though Brave and Vivaldi are forks of Chromium, they also share the same debugging process most of the time. To debug the client script part, open the browser’s developer tools on the page that you’d like to debug (pressing F12, Control + Shift + I or ⌘ + ⌥ + I, depending on the browser or platform you’re using). Then, click on the “Content scripts” tab and find your extension’s folder. Open the script file that you’d like to debug, and debug your code just as you would do with any JavaScript code. 80(View large version81) To debug a tab that your extension would create, it’s exactly the same as with Edge: Simply use the developer tools. 82(View large version83) For Chrome and Opera, to debug the popup page, right-click on the button of your extension next to the address bar and choose “Inspect popup,” or open the HTML pane of the popup and right-click inside it to “Inspect.” Vivaldi only supports right-click and then “Inspect” inside the HTML pane once opened. 84(View large version85) For Brave, it’s the same process as with Edge. You first need to find the GUID associated with your extension in about:extensions: 86 And then, in a separate tab, open the page you’d like to debug like — in my case, chrome-extension://bodaahkboijjjodkbmmddgjldpifcjap/dashboard.html — and open developer tools. 87(View large version88) For the layout, you have a bit of help using Shift + F8, which will let you inspect the complete frame of Brave. And you’ll discover that Brave is an Electron app using React! Note, for instance, the data-reactroot attribute. 89(View large version90) Note: I had to slightly modify the CSS of the extension for Brave because it currently displays popups with a transparent background by default, and I also had some issues with the height of my images collection. I’ve limited it to four elements in Brave. Mozilla Firefox Link Mozilla has really great documentation on debugging web extensions91. For the client script part, it’s the same as in Edge, Chrome, Opera and Brave. Simply open the developer tools in the tab you’d like to debug, and you’ll find a moz-extension://guid section with your code to debug: 92(View large version93) If you need to debug a tab that your extension would create (like Vorlon.js’ Page Analyzer extension), simply use the developer tools: 94(View large version95) Finally, debugging a popup is a bit more complex but is well explained in the “Debugging Popups96” section of the documentation. 97(View large version98) Publishing Your Extension In Each Store Link Each vendor has detailed documentation on the process to follow to publish your extension in its store. They all take similar approaches. You need to package the extension in a particular file format — most of the time, a ZIP-like container. Then, you have to submit it in a dedicated portal, choose a pricing model and wait for the review process to complete. If accepted, your extension will be downloadable in the browser itself by any user who visits the extensions store. Here are the various processes: Google: “Publish in the Chrome Web Store99” Mozilla: “Publishing your WebExtension100” Opera: “Publishing Guidelines101” Microsoft: “Packaging Microsoft Edge Extensions102” Please note that submitting a Microsoft Edge extension to the Windows Store is currently a restricted capability. Reach out to the Microsoft Edge team103 with your request to be a part of the Windows Store, and they’ll consider you for a future update. I’ve tried to share as much of what I’ve learned from working on our Vorlon.js Page Analyzer extension104 and this little proof of concept. Some developers remember the pain of working through various implementations to build their extension — whether it meant using different build directories, or working with slightly different extension APIs, or following totally different approaches, such as Firefox’s XUL extensions or Internet Explorer’s BHOs and ActiveX. It’s awesome to see that, today, using our regular JavaScript, CSS and HTML skills, we can build great extensions using the very same code base and across all browsers! Feel free to ping me on Twitter105 for any feedback. (ms, vf, r
http://www.webhostingreviewsbynerds.com/creating-one-browser-extension-for-all-browsers-edge-chrome-firefox-opera-brave-and-vivaldi/
CC-MAIN-2017-22
refinedweb
3,228
55.24
Shared implementation for block frequency analysis. More... #include "llvm/Analysis/BlockFrequencyInfo.h" Shared implementation for block frequency analysis. This is a shared implementation of BlockFrequencyInfo and MachineBlockFrequencyInfo, and calculates the relative frequencies of blocks. LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block, which is called the header. A given loop, L, can have sub-loops, which are loops within the subgraph of L that exclude its header. (A "trivial" SCC consists of a single block that does not have a self-edge.) In addition to loops, this algorithm has limited support for irreducible SCCs, which are SCCs with multiple entry blocks. Irreducible SCCs are discovered on they fly, and modelled as loops with multiple headers. The headers of irreducible sub-SCCs consist of its entry blocks and all nodes that are targets of a backedge within it (excluding backedges within true sub-loops). Block frequency calculations act as if a block is inserted that intercepts all the edges to the headers. All backedges and entries point to this block. Its successors are the headers, which split the frequency evenly. This algorithm leverages BlockMass and ScaledNumber to maintain precision, separates mass distribution from loop scaling, and dithers to eliminate probability mass loss. The implementation is split between BlockFrequencyInfoImpl, which knows the type of graph being modelled (BasicBlock vs. MachineBasicBlock), and BlockFrequencyInfoImplBase, which doesn't. The base class uses BlockNode, a wrapper around a uint32_t. BlockNode is numbered from 0 in reverse-post order. This gives two advantages: it's easy to compare the relative ordering of two nodes, and maps keyed on BlockT can be represented by vectors. This algorithm is O(V+E), unless there is irreducible control flow, in which case it's O(V*E) in the worst case. These are the main stages: 0. Reverse post-order traversal (initializeRPOT()). Run a single post-order traversal and save it (in reverse) in RPOT. All other stages make use of this ordering. Save a lookup from BlockT to BlockNode (the index into RPOT) in Nodes. Loop initialization (initializeLoops()). Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of the algorithm. In particular, store the immediate members of each loop in reverse post-order. Calculate mass and scale in loops (computeMassInLoops()). For each loop (bottom-up), distribute mass through the DAG resulting from ignoring backedges and treating sub-loops as a single pseudo-node. Track the backedge mass distributed to the loop header, and use it to calculate the loop scale (number of loop iterations). Immediate members that represent sub-loops will already have been visited and packaged into a pseudo-node. Distributing mass in a loop is a reverse-post-order traversal through the loop. Start by assigning full mass to the Loop header. For each node in the loop: - Fetch and categorize the weight distribution for its successors. If this is a packaged-subloop, the weight distribution is stored in \a LoopData::Exits. Otherwise, fetch it from BranchProbabilityInfo. - Each successor is categorized as \a Weight::Local, a local edge within the current loop, \a Weight::Backedge, a backedge to the loop header, or \a Weight::Exit, any successor outside the loop. The weight, the successor, and its category are stored in \a Distribution. There can be multiple edges to each successor. - If there's a backedge to a non-header, there's an irreducible SCC. The usual flow is temporarily aborted. \a computeIrreducibleMass() finds the irreducible SCCs within the loop, packages them up, and restarts the flow. - Normalize the distribution: scale weights down so that their sum is 32-bits, and coalesce multiple edges to the same node. - Distribute the mass accordingly, dithering to minimize mass loss, as described in \a distributeMass(). In the case of irreducible loops, instead of a single loop header, there will be several. The computation of backedge masses is similar but instead of having a single backedge mass, there will be one backedge per loop header. In these cases, each backedge will carry a mass proportional to the edge weights along the corresponding path. At the end of propagation, the full mass assigned to the loop will be distributed among the loop headers proportionally according to the mass flowing through their backedges. Finally, calculate the loop scale from the accumulated backedge mass. Distribute mass in the function (computeMassInFunction()). Finally, distribute mass through the DAG resulting from packaging all loops in the function. This uses the same algorithm as distributing mass in a loop, except that there are no exit or backedge edges. Unpackage loops (unwrapLoops()). Initialize each block's frequency to a floating point representation of its mass. Visit loops top-down, scaling the frequencies of its immediate members by the loop's pseudo-node's frequency. Convert frequencies to a 64-bit range (finalizeMetrics()). Using the min and max frequencies as a guide, translate floating point frequencies to an appropriate range in uint64_t. It has some known flaws. The model of irreducible control flow is a rough approximation. Modelling irreducible control flow exactly involves setting up and solving a group of infinite geometric series. Such precision is unlikely to be worthwhile, since most of our algorithms give up on irreducible control flow anyway. Nevertheless, we might find that we need to get closer. Here's a sort of TODO list for the model with diminishing returns, to be completed as necessary. Definition at line 31 of file BlockFrequencyInfo.h. Definition at line 1020 of file BlockFrequencyInfoImpl.h. Definition at line 968 of file BlockFrequencyInfoImpl.h. Definition at line 972 of file BlockFrequencyInfoImpl.h. Definition at line 996 of file BlockFrequencyInfoImpl.h. Definition at line 992 of file BlockFrequencyInfoImpl.h. Definition at line 961 of file BlockFrequencyInfoImpl.h. Definition at line 979 of file BlockFrequencyInfoImpl.h. Definition at line 986 of file BlockFrequencyInfoImpl.h. Print the frequencies for the current function. Prints the frequencies for the blocks in the current function. Blocks are printed in the natural iteration order of the function, rather than reverse post-order. This provides two advantages: writing -analyze tests is easier (since blocks come out in source order), and even unreachable blocks are printed. BlockFrequencyInfoImplBase::print() only knows reverse post-order, so we need to override it here. Reimplemented from llvm::BlockFrequencyInfoImplBase. Definition at line 1338 of file BlockFrequencyInfoImpl.h. Definition at line 1014 of file BlockFrequencyInfoImpl.h. Definition at line 1049 of file BlockFrequencyInfoImpl.h. Definition at line 842 of file BlockFrequencyInfoImpl.h.
https://llvm.org/doxygen/classllvm_1_1BlockFrequencyInfoImpl.html
CC-MAIN-2019-39
refinedweb
1,073
50.43
This Product is no longer available. You may also be interested in: children Best bounce up toothbrush with replaceable brush hea... US $1-2 / Pack 500 Packs (Min. Order) 2016 best selling MT-301 LED waterproof headlamp for ... US $1-6.5 / Piece 10 Pieces (Min. Order) Animal Head Lights Super LED Headlamps With Head Strap Best H... US $3-7 / Piece 1000 Pieces (Min. Order) New style best sell flashlight for children US $1.33-2.55 / Piece 2000 Pieces (Min. Order) Outdoor Handling Tools Kids Wheelbarrow for Garden US $6.6-13.9 / Piece 500 Pieces (Min. Order) import cheap goods from china Power Bank mobile power case fo... US $5-10 / Piece 10 Pieces (Min. Order) high quality strong power rechargeable pet cat dog hair clipp... US $7.58-7.58 / Pieces 100 Pieces (Min. Order) Color changing 7 LED Best Aroma Diffuser Mist Humidifier for ... US $1-15 / Piece 1 Piece (Min. Order) Best quality paint maker pen Japanese car touch up paint pen ... US $1.3-1.5 / Piece 144 Pieces (Min. Order) useful and cute cable headset connector power bank with ... US $0.05-0.29 / Piece 1 Set (Min. Order) best luxury sofa classic and lift sofa chair US $200-500 / Set 1 Set (Min. Order) Ultralight Bright Waterproof Red Led Headlamps Flashlight fo... US $3.0!
http://www.alibaba.com/cache/Powerful-Best-Selling-strong-child-strong_1277462002.html
CC-MAIN-2017-34
refinedweb
224
79.56
Hi. I'm having a little trouble figuring this problem out. What I need the program to do is take an email inbox and print out only the Headers for each message. Assuming each max line length to be 1024. I can read the file line by line but I don't know how to pick out specific lines. Sample input file (sample.mbox): From ocfs2-devel-bounces@oss.oracle.com Wed May 18 18:33:55 2005 Return-Path: <ocfs2-devel-bounces@oss.oracle.com> Hello, This is OCFS2, a shared disk cluster file system which we hope will be included in the kernel. We think OCFS2 has many qualities which make it particularly interesting as a cluster file system. Please consider ... From user-mode-linux@lists.sourceforge.net Wed May 18 18:36:00 2005 Return-Path: <user-mode-linux-devel-admin@lists.sourceforge.net> Ok, let me have an example. suppose a user argument has virtual address 0xa0, corresponding UML physical address 0xb0, and real physical address 0x10. so, when the user process tries to access 0xa0 for the first time, the UML kernel should let host kernel know there will be 0xa0 -> 0x10 mapping. how does the UML kernel make another process's address map to the same physical page it has? and how does the UML kernel keep track of 0xa0 -> 0xb0 mapping? maybe the same page table mechanism as host Linux? (i guess so, though) Thanks a lot! From openib-general-bounces@openib.org Wed May 18 18:36:08 2005 Return-Path: <openib-general-bounces@openib.org> William Jordan wrote: > Sean, > You mentioned that the cm_id leak was fixed, but I don't see a patch > for it, so I'm submitting one. > When I try to apply this patch, most of it is rejected. - Sean From D-2-721494-20549853-2-153912-US1-EBB1BBA6@xmr3.com Mon Jan 5 Content-Type: multipart/alternative; boundary=MEboundary-20549853-5-1073330144 Status: RO X-Status: X-Keywords: X-UID: 5 That should be fine. - Sean Sample output: 1: From ocfs2-devel-bounces@oss.oracle.com Wed May 18 18:33:55 2005 2: From user-mode-linux@lists.sourceforge.net Wed May 18 18:36:00 2005 3: From openib-general-bounces@openib.org Wed May 18 18:36:08 2005 4: From D-2-721494-20549853-2-153912-US1-EBB1BBA6@xmr3.com Mon Jan 5 Here's what I have so far: #include <stdio.h> void main() { FILE *mbox; char filename[40]; char line[1024]; int count=0; printf("Enter the file name of your mailbox: "); gets(filename); if((mbox = fopen(filename, "r")) == NULL) { printf("Error Opening File.\n"); } while(fgets(line, sizeof(line), mbox) != NULL) { /* maybe do something here to find lines begining with "From" */ count++; printf("%d: %s", count, line); } fclose(mbox); }
https://www.daniweb.com/programming/software-development/threads/288342/how-do-i-read-a-file-and-choose-specific-lines
CC-MAIN-2018-26
refinedweb
470
59.19
Extending Ruby with C Pages: 1, 2, 3 GenX::Writer#begin_element It has taken an awful lot of trouble to put the begin_document and end_document methods in place. Now users can start and end documents--but in order for this to be of much use, they'll want to put some content in the document. Because this is XML, and XML documents all start with a root element, that means the next methods to implement are GenX::Writer#begin_element and GenX::Writer#end_element. The obvious place to start is GenX::Writer#begin_element. Genx::Writer#begin_element is a thin wrapper around the genxStartElementLiteral function. It's really similar to the methods already shown. Here's the implementation: static VALUE writer_begin_element (int argc, VALUE *argv, VALUE self) { genxWriter w; VALUE xmlns, name; switch (argc) { case 1: xmlns = 0; name = argv[0]; break; case 2: xmlns = argv[0]; Check_Type (xmlns, T_STRING); name = argv[1]; break; default: rb_raise (rb_eRuntimeError, "invalid arguments"); } Check_Type (name, T_STRING); Data_Get_Struct (self, struct genxWriter_rec, w); GENX4R_ERR (genxStartElementLiteral (w, xmlns ? (constUtf8) RSTRING (xmlns)->ptr : NULL, (constUtf8) RSTRING (name)->ptr), w); return Qnil; } A few things here haven't appeared before. First of all, this method takes a variable number of arguments. Most of the code in this function goes to figuring out how many arguments it received and setting things up as appropriate. The way Ruby lets you do this at the C level is that the underlying C function takes as arguments an integer that holds the number of arguments passed, a pointer to an array of VALUEs that contains each of the arguments, and a VALUE that holds the invoking object. If it receives one argument, it uses that as the name of the element. If it receives two arguments, then the first is the namespace and the second is the name. Given an xmlns argument, the code verifies that it is a String using the Check_Type macro with the T_STRING constant. The same check occurs for the element's name. Then, as usual, it pulls the genxWriter out of self and finally calls the underlying genxStartElementLiteral function, passing in the namespace if provided and valid, and a NULL otherwise. When passing the namespace and element name, note that the code uses the RSTRING macro to cast the VALUE to the underlying string data structure before accessing the C-string pointer via the ptr field in that structure. Once again, Init_genx4r needs more code to hook up this method: rb_define_method (rb_cGenXWriter, "begin_element", writer_begin_element, -1); Notice the -1 that tells Ruby to call this method via the count/array/object style of argument passing. Now that there's a way to start an element, there must be a way to end it. That's the purpose of the GenX::Writer#end_element method. GenX::Writer#end_element As you might have guessed, GenX::Writer#end_element is very similar to GenX::Writer#end_document. Here's the implementation: static VALUE writer_end_element (VALUE self) { genxWriter w; Data_Get_Struct (self, struct genxWriter_rec, w); GENX4R_ERR (genxEndElement (w), w); return Qnil; } All it does is pull out the writer and call genxEndElement on it. GenX does the rest. As usual, it takes one call in Init_genx4r to hook up the method: rb_define_method (rb_cGenXWriter, "end_element", writer_end_element, 0); Now GenX4r can actually produce XML. Jump into irb and try it.end_element => nil irb(main):007:0> w.end_document => nil irb(main):008:0> s => "<foo></foo>" irb(main):009:0> There you have it! The extension actually produced some XML output! Of course, most XML needs some textual content within at least some of the tags. Making that work means implementing GenX::Writer#text, a wrapper around genxAddText. GenX::Writer#text After everything implemented so far, GenX::Writer#text doesn't have anything all that new to it. Take a look: static VALUE writer_text (VALUE self, VALUE text) { genxWriter w; Check_Type (text, T_STRING); Data_Get_Struct (self, struct genxWriter_rec, w); GENX4R_ERR (genxAddText (w, (constUtf8) RSTRING (text)->ptr), w); return Qnil; } There are the usual hoops to access the genxWriter and then a call to pass the text through to genxAddText. Here's code to hook up the method in Init_genx4r. rb_define_method (rb_cGenXWriter, "text", writer_text, 1); There you have it, a functionally complete wrapper. Try it out in irb to prove.text("bar") => nil irb(main):007:0> w.end_element => nil irb(main):008:0> w.end_document => nil irb(main):009:0> s => "<foo>bar</foo>" irb(main):010:0> With the combination of elements and text, you can now start using GenX4r for some nontrivial tasks. Before that, I'd like to write some tests to verify that everything works now and that it will continue to work as I make changes in the future. Unit Testing In Ruby, the accepted way to write unit tests is to use the Test::Unit framework. This is a standard unit test framework, written along the lines of the popular JUnit package. To use it, subclass the Test::Unit::TestCase class and implement your tests as methods that are named test_something (where the something part changes for each test). Inside the tests, use the assert method to indicate what conditions need to be true for the tests to pass. Here's a simple test case to start: require 'test/unit' require 'genx4r' class BasicsTest < Test::Unit::TestCase def test_element w = GenX::Writer.new s = '' w.begin_document(s) w.begin_element('foo') w.text('bar') w.end_element w.end_document assert s == '<foo>bar</foo>' end end Run the tests by running that file. You should receive output similar to the following: $ ruby test.rb Loaded suite test Started . Finished in 0.005774 seconds. 1 tests, 1 assertions, 0 failures, 0 errors The line with the single dot on it is where you see the output for the tests. Each passing test prints a . whereas failing tests print an F. To add more tests, fill in more test methods. They will run automatically when you run the file. Making Things a Bit More Ruby-esque All right, now there's a working module and a test suite to make sure it keeps on working. I'm all set to release this new toy to the unsuspecting masses out there on the Internet, right? Not quite. Although the API works, it's not ideal. You have to remember to call the GenX::Writer#end_element and GenX::Writer#end_document methods at exactly the right times; otherwise you'll either mess up the output (if elements nest incorrectly) or even possibly throw an exception because you call underlying GenX functions out of order. Remember that GenX is big on enforcing correctness, so if you screw up, it will tell you about it. It would be really nice to arrange for the module to call these end methods at the appropriate times. Fortunately, Ruby has a way to do that: blocks. A block in Ruby is a chunk of code passed to a method as one of its arguments. The method can then call the yield method to invoke the block whenever it wants. The syntax looks like this: def takes_a_block(&block) puts "before yield" yield puts "after yield" end takes_a_block do puts "in the block" end Running this code produces the following output: $ ruby blocks-example.rb before yield in the block after yield Note that Ruby allows braces as block delimiters instead of do and end, in which case the method call could have looked like takes_a_block { puts "in the block" }. Both ways are valid. Which one you use is mostly just a question of style. Using blocks to indicate the beginning and end of an element in the XML to generate solves the API problem perfectly. Here's how to implement this with a new GenX::Writer#element method defined at the C level. static VALUE writer_element (int argc, VALUE *argv, VALUE self) { writer_begin_element (argc, argv, self); if (rb_block_given_p ()) { rb_yield (Qnil); writer_end_element (self); return Qnil; } else rb_raise (rb_eRuntimeError, "must be called with a block"); } All of this is merely a new method that calls the begin_element method and then invokes the block it received (or throws an exception if it didn't receive one), then calls end_element. In order to nest elements or put text inside them, the passed-in block needs to contain the code to create that content. There are two new C-level functions here, rb_block_given_p, the predicate that asks "Was I given a block?" and rb_yield, which invokes the block. Because there's nothing else to pass to the block, the code passes Qnil. As usual, the code to hook up this new method in Init_genx4r looks like: rb_define_method (rb_cGenXWriter, "element", writer_element, -1); With that in place, using the new method like this: w = GenX::Writer.new s = '' w.begin_document(s) w.element('foo') do w.element('bar') do w.text('baz') end end w.end_document puts s produces output of this: <foo><bar>baz</bar></foo> Isn't that a much nicer API? Instead of having to remember to handle the nesting of elements manually, users can encode it directly into their program, making it much more difficult to do incorrectly. Note that the same technique can easily apply to the GenX::Writer#begin_document and GenX::Writer#end_document methods. Some Conclusions This whole idea started off as something of an experiment. Is it really as easy as I thought it would be to wrap a C library in Ruby? I don't know about you, but I think it was a success. In fewer than 300 lines of C, I've provided users with access to a useful subset of the GenX library's functionality. If I were going to implement this code directly in Ruby, it would be longer and most likely buggier, simply because the C version has been debugged already and our hypothetical Ruby version has not. That said, GenX4r is still somewhat incomplete. The begin_document and end_document methods still need block-based cover method wrappers, and for efficiency I also want to provide users the ability to predeclare namespaces and elements, to avoid having to validate them each time they're used. Plus, I'm a reasonably new Ruby hacker, so it's not out of the realm of possibility that there are bugs in the wrapper. Even so, I think this is a reasonable proof of concept. The additional work I've done on GenX4r that isn't documented here indicates to me that it is a success. On the strength of this experience, I have no trouble recommending Ruby as a convenient scripting language to wrap around libraries written in C. For the record, the current version of GenX4r, which includes all this hypothetical functionality in one form or another, constitutes only 584 lines of C. If you're interested in using it or helping me develop it further, please grab the latest version from the GenX4r home page. Garrett Rooney is a software developer at FactSet Research Systems, where he works on real-time market data. Return to ONLamp.com. - - Use rb_scan_args() 2004-11-19 15:44:38 rooneg [View] - - Use rb_scan_args() 2004-11-19 15:44:27 djberg96 [View] 2004-11-19 09:58:02 amuegge [View] 2004-11-19 03:26:22 riffraff [View]
http://www.onlamp.com/pub/a/onlamp/2004/11/18/extending_ruby.html?page=3
CC-MAIN-2017-04
refinedweb
1,868
62.27
Compiler Construction/Known Languages Conceptual Implementations Contents Known Languages Conceptual Implementations[edit]. Java[edit] Invocation[edit] In Java, there are four kinds of method invocation, namely invokestatic, invokespecial, invokevirtual, invokeinterface. As the names suggest, the first is used to invoke static method and the rest instance methods. Since a static method cannot be overridden, invokestatic is very simple; it is essentially the same as calling a function in C. We now see the mechanism of invocation of instance methods. Consider the following piece of code. class A { public static int f () { return 1; } private int g_private () { return 2; } public final int g_final () { return 3; } public int g_non_final () { return 4; } public void test (A a) { a.f (); // static; this is always 1. a.g_private (); // special; this is always 2. a.g_final (); // special; this is always 3. a.g_non_final (); // virtual; this may be 4 or something else. } } class B extends A { public int g_non_final () { return 6; } } class C extends B { public int g_non_final () { return 7; } public int foo () { return A.this.g_non_final (); } } invokestatic is invoked with the references to the class name and the method name and pops arguments from the stack. An expression A.f (2) is complied to: iconst_2 // push a constant 2 onto the stack invokestatic A.f // invoke a static method // the return value is at the top of the stack. In Java, a private method cannot be overridden. Thus, a method has to be called based on a class regardless of how an object is created. invokespecial allows this; the instruction is the same as invokestatic except that it also pops the object reference besides supplied arguments. Thus far, dynamic binding is not in use, and it is not necessary to have informaion about binding at runtime about private methods. Specifically, invokespecial can be used either (1) calling a private method or (2) a invoking a method of the super class (including the constructor for the super class, namely <init>). To call a super method other than <init>, one has to write like super.f () where f is the name of the super method. In semantics invokeinterface doesn't differ from invokevirtual, but it can give the compiler a hit about the invocation. Class methods[edit] Class methods can be defined with a static qualifier. Private class methods may be in the same object, if they belong to the different classes. No two public class methods may be in the same object; in other words, class methods cannot be overridden. This also means final qualifier is semantically meaningless for class methods. Fields[edit] Each field is accessed based on a class. Consider the following. class A { public int i = 2; } class B extends A { public int i = 3; } B b = new B (); A a = b; b.i++; // this would be 3 + 1 = 4 a.i++; // this would be 2 + 1 = 3 In other words, an access control modifier (none, public, private and protected) only affects if clients of the class can access a given field. This means that Java virtual machine may ignore the access flag, handling each field in the same manner. Reference[edit] Objective-C[edit] Objects and fields[edit] In Objective-C, each class is a struct in C. That is, @interface A { int a, b, c } @end would be implemented as like: struct A { int a, b, c; .... // some runtime information }; Thus, since each object in Objective-C, a pointer to a memory block in the heap. And so the way to access fields is the same as the way for members of struct. That is, id obj = [A alloc]; The implication of this scheme is that while an object naturally fits to non-OOP C program, one disadvantage is that fields cannot be "shadowed." That is, @interface A { @private int a; } @end @interface B : A { @private int a; } @end This would result in duplicate members error. This contrasts with the situation in Java. Finally, since the selection of methods occurs at runtime (in contrast to the cases in Java or C++), methods are handled differently than fields. Methods[edit] In Objective-C, the selection of methods occurs at runtime. Compilers may issue warnings about likely mistyped names because the compiler can know a set of selector names that are defined in the program. This, however, is not semantically necessary; any message can be sent to any object. Semantically, the sender of a message checks if a given object responds to the message, and if not, try its super class, and if not again, its super and so on. A complication may arise, for example, when there are two selectors with the differing return type. Consider the following case. @interface A { } - (float) func: (int) i @end @interface B { } - (int) func: (int) i @end In this case, because the compiler cannot know to which method--(float) func or (int) func--an object would respond, it cannot generate code that sends a message, as returning a float value usually differs from doing an int value.
https://en.wikibooks.org/wiki/Compiler_Construction/Known_Languages_Conceptual_Implementations
CC-MAIN-2016-07
refinedweb
830
63.39
image and video datasets and models for torch deep learning Project description torch-vision This repository consists of: - vision.datasets : Data loaders for popular vision datasets - vision.models : Definitions for popular model architectures, such as AlexNet, VGG, and ResNet and pre-trained models. - vision.transforms : Common image transformations such as random crop, rotations etc. - vision.utils : Useful stuff such as saving tensor (3 x H x W) as image to disk, given a mini-batch creating a grid of images, etc. Installation Binaries: conda install torchvision -c From Source: pip install -r requirements.txt pip install . Datasets The following dataset loaders are available: Datasets have the API: - __getitem__ - __len__ They all subclass from torch.utils.data.Dataset Hence, they can all be multi-threaded (python multiprocessing) using standard torch.utils.data.DataLoader. For example: torch.utils.data.DataLoader(coco_cap, batch_size=args.batchSize, shuffle=True, num_workers=args.nThreads) In the constructor, each dataset has a slightly different API as needed, but they all take the keyword args: - transform - a function that takes in an image and returns a transformed version - common stuff like ToTensor, RandomCrop, etc. These can be composed together with transforms.Compose (see transforms section below) - target_transform - a function that takes in the target and transforms it. For example, take in the caption string and return a tensor of word indices. COCO This requires the COCO API to be installed Captions: dset.CocoCaptions(root="dir where images are", annFile="json annotation file", [transform, target_transform]) Example: import torchvision.datasets as dset import torchvision.transforms as transforms cap = dset.CocoCaptions(root = 'dir where images are', annFile = 'json annotation file', transform=transforms.ToTensor()) print('Number of samples: ', len(cap)) img, target = cap[3] # load 4th sample print("Image Size: ", img.size()) print(target) Output: Number of samples: 82783 Image Size: (3L, 427L, 640L) [u'A plane emitting smoke stream flying over a mountain.', u'A plane darts across a bright blue sky behind a mountain covered in snow', u'A plane leaves a contrail above the snowy mountain top.', u'A mountain that has a plane flying overheard in the distance.', u'A mountain view with a plume of smoke in the background'] Detection: dset.CocoDetection(root="dir where images are", annFile="json annotation file", [transform, target_transform]) LSUN dset.LSUN(db_path, classes='train', [transform, target_transform]) - db_path = root directory for the database files - classes = - ‘train’ - all categories, training set - ‘val’ - all categories, validation set - ‘test’ - all categories, test set - [‘bedroom_train’, ‘church_train’, …] : a list of categories to load CIFAR dset.CIFAR10(root, train=True, transform=None, target_transform=None, download=False) dset.CIFAR100(root, train=True, transform=None, target_transform=None, download=False) - root : root directory of dataset where there is folder cifar-10-batches-py - train : True = Training set, False = Test set - download : True = downloads the dataset from the internet and puts it in root directory. If dataset already downloaded, does not do anything. ImageFolder A generic data loader where the images are arranged in this way: root/dog/xxx.png root/dog/xxy.png root/dog/xxz.png root/cat/123.png root/cat/nsdf3.png root/cat/asd932_.png dset.ImageFolder(root="root folder path", [transform, target_transform]) It has the members: - self.classes - The class names as a list - self.class_to_idx - Corresponding class indices - self.imgs - The list of (image path, class-index) tuples Imagenet-12 This is simply implemented with an ImageFolder dataset. The data is preprocessed as described here Models The models subpackage contains definitions for the following model architectures: - AlexNet: AlexNet variant from the “One weird trick” paper. - VGG: VGG-11, VGG-13, VGG-16, VGG-19 (with and without batch normalization) - ResNet: ResNet-18, ResNet-34, ResNet-50, ResNet-101, ResNet-152 You can construct a model with random weights by calling its constructor: import torchvision.models as models resnet18 = models.resnet18() alexnet = models.alexnet() We provide pre-trained models for the ResNet variants and AlexNet, using the PyTorch model zoo. These can be constructed by passing pretrained=True: python import torchvision.models as models resnet18 = models.resnet18(pretrained=True) alexnet = models.alexnet(pretrained=True) Transforms Transforms are common image transforms. They can be chained together using transforms.Compose transforms.Compose One can compose several transforms together. For example. transform = transforms.Compose([ transforms.RandomSizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean = [ 0.485, 0.456, 0.406 ], std = [ 0.229, 0.224, 0.225 ]), ]) Transforms on PIL.Image Scale(size, interpolation=Image.BILINEAR) Rescales the input PIL.Image to the given ‘size’. ‘size’ will be the size of the smaller edge. For example, if height > width, then image will be rescaled to (size * height / width, size) - size: size of the smaller edge - interpolation: Default: PIL.Image.BILINEAR CenterCrop(size) - center-crops the image to the given size Crops the given PIL.Image at the center to have a region of the given size. size can be a tuple (target_height, target_width) or an integer, in which case the target will be of a square shape (size, size) RandomCrop(size, padding=0) Crops the given PIL.Image at a random location to have a region of the given size. size can be a tuple (target_height, target_width) or an integer, in which case the target will be of a square shape (size, size) If padding is non-zero, then the image is first zero-padded on each side with padding pixels. RandomHorizontalFlip() Randomly horizontally flips the given PIL.Image with a probability of 0.5 RandomSizedCrop(size, interpolation=Image.BILINEAR) Random crop the given PIL.Image to a random size of (0.08 to 1.0) of the original size and and a random aspect ratio of 3/4 to 4/3 of the original aspect ratio This is popularly used to train the Inception networks - size: size of the smaller edge - interpolation: Default: PIL.Image.BILINEAR Pad(padding, fill=0) Pads the given image on each side with padding number of pixels, and the padding pixels are filled with pixel value fill. If a 5x5 image is padded with padding=1 then it becomes 7x7 Transforms on torch.*Tensor Normalize(mean, std) Given mean: (R, G, B) and std: (R, G, B), will normalize each channel of the torch.*Tensor, i.e. channel = (channel - mean) / std Conversion Transforms - ToTensor() - Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] - ToPILImage() - Converts a torch.*Tensor of range [0, 1] and shape C x H x W or numpy ndarray of dtype=uint8, range[0, 255] and shape H x W x C to a PIL.Image of range [0, 255] Generic Transofrms Lambda(lambda) Given a Python lambda, applies it to the input img and returns it. For example: transforms.Lambda(lambda x: x.add(10)) Utils make_grid(tensor, nrow=8, padding=2) Given a 4D mini-batch Tensor of shape (B x C x H x W), makes a grid of images save_image(tensor, filename, nrow=8, padding=2) Saves a given Tensor into an image file. If given a mini-batch tensor, will save the tensor as a grid of images. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/torch-vision/
CC-MAIN-2021-39
refinedweb
1,227
50.02
This year I greeted Christmas in a different fashion: I was a part of the Java Advent Calendar. Let’s boot up for Christmas: it is to implement a REST API that provides CRUD operations for todo entries that are saved to MongoDB database. Let’s start by creating our Maven project. Creating Our Maven Project We can create our Maven project by following these steps: - Use the spring-boot-starter-parent POM as the parent POM of our Maven project. This ensures that our project inherits sensible default settings from Spring Boot. - Add the Spring Boot Maven Plugin to our project. This plugin allows us to package our application into an executable jar file, package it into a war archive, and run the application. - Configure the dependencies of our project. We need to configure the following dependencies: - The spring-boot-starter-web dependency provides the dependencies of a web application. - The spring-data-mongodb dependency provides integration with the MongoDB document database. - Enable the Java 8 Support of Spring Boot. - Configure the main class of our application. This class is responsible of configuring and starting our application. The relevant part of our pom.xml file looks as follows: <properties> <!-- Enable Java 8 --> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- Configure the main class of our Spring Boot application --> <start-class>com.javaadvent.bootrest.TodoAppConfig</start-class> </properties> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.1.9.RELEASE</version> </parent> <dependencies> <!-- Get the dependencies of a web application --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Data MongoDB--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> </dependency> </dependencies> <build> <plugins> <!-- Spring Boot Maven Support --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> Let’s move on and find out how we can configure our application. Configuring Our Application We can configure our Spring Boot application by following these steps: - Create a TodoAppConfig class to the com.javaadvent.bootrest package. - Enable Spring Boot auto-configuration. - Configure the Spring container to scan components found from the child packages of the com.javaadvent.bootrest package. - Add the main() method to the TodoAppConfig class and implement by running our application. The source code of the TodoAppConfig class looks as follows: package com.javaadvent.bootrest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration @ComponentScan public class TodoAppConfig { public static void main(String[] args) { SpringApplication.run(TodoAppConfig.class, args); } } We have now created the configuration class that configures and runs our Spring Boot application. Because the MongoDB jars are found from the classpath, Spring Boot configures the MongoDB connection by using its default settings. - Spring Boot Reference Manual: 13.2 Location the main application class - Spring Boot Reference Manual: 14. Configuration classes - The Javadoc of the @EnableAutoConfiguration annotation - Spring Boot Reference Manual: 15. Auto-configuration - The Javadoc of the SpringApplication class - Spring Boot Reference Manual: 27.2.1 Connecting to a MongoDB database Let’s move on and implement our REST API. Implementing Our REST API We need implement a REST API that provides CRUD operations for todo entries. The requirements of our REST API are: - A POST request send to the url ‘/api/todo’ must create a new todo entry by using the information found from the request body and return the information of the created todo entry. - A DELETE request send to the url ‘/api/todo/{id}’ must delete the todo entry whose id is found from the url and return the information of the deleted todo entry. - A GET request send to the url ‘/api/todo’ must return all todo entries that are found from the database. - A GET request send to the url ‘/api/todo/{id}’ must return the information of the todo entry whose id is found from the url. - A PUT request send to the url ‘/api/todo/{id}’ must update the information of an existing todo entry by using the information found from the request body and return the information of the updated todo entry. We can fulfill these requirements by following these steps: - Create the entity that contains the information of a single todo entry. - Create the repository that is used to save todo entries to MongoDB database and find todo entries from it. - Create the service layer that is responsible of mapping DTOs into domain objects and vice versa. The purpose of our service layer is to isolate our domain model from the web layer. - Create the controller class that processes HTTP requests and returns the correct response back to the client. Let’s get started. Creating the Entity We need to create the entity class that contains the information of a single todo entry. We can do this by following these steps: - Add the id, description, and title fields to the created entity class. Configure the id field of the entity by annotating the id field with the @Id annotation. - Specify the constants (MAX_LENGTH_DESCRIPTION and MAX_LENGTH_TITLE) that specify the maximum length of the description and title fields. - Add a static builder class to the entity class. This class is used to create new Todo objects. - Add an update() method to the entity class. This method simply updates the title and description of the entity if valid values are given as method parameters. The source code of the Todo class looks as follows: import org.springframework.data.annotation.Id; import static com.javaadvent.bootrest.util.PreCondition.isTrue; import static com.javaadvent.bootrest.util.PreCondition.notEmpty; import static com.javaadvent.bootrest.util.PreCondition.notNull; final class Todo { static final int MAX_LENGTH_DESCRIPTION = 500; static final int MAX_LENGTH_TITLE = 100; @Id private String id; private String description; private String title; public Todo() {} private Todo(Builder builder) { this.description = builder.description; this.title = builder.title; } static Builder getBuilder() { return new Builder(); } //Other getters are omitted public void update(String title, String description) { checkTitleAndDescription(title, description); this.title = title; this.description = description; } /** * We don't have to use the builder pattern here because the constructed * class has only two String fields. However, I use the builder pattern * in this example because it makes the code a bit easier to read. */ static class Builder { private String description; private String title; private Builder() {} Builder description(String description) { this.description = description; return this; } Builder title(String title) { this.title = title; return this; } Todo build() { Todo build = new Todo(this); build.checkTitleAndDescription(build.getTitle(), build.getDescription()); return build; } } private void checkTitleAndDescription(String title, String description) { notNull(title, "Title cannot be null"); notEmpty(title, "Title cannot be empty"); isTrue(title.length() <= MAX_LENGTH_TITLE, "Title cannot be longer than %d characters", MAX_LENGTH_TITLE ); if (description != null) { isTrue(description.length() <= MAX_LENGTH_DESCRIPTION, "Description cannot be longer than %d characters", MAX_LENGTH_DESCRIPTION ); } } } Let’s move on and create the repository that communicates with the MongoDB database. Creating the Repository We have to create the repository interface that is used to save Todo objects to MondoDB database and retrieve Todo objects from it. If we don’t want to use the Java 8 support of Spring Data, we could create our repository by creating an interface that extends the CrudRepository<T, ID> interface. However, because we want to use the Java 8 support, we have to follow these steps: - Create an interface that extends the Repository<T, ID> interface. - Add the following repository methods to the created interface: - The void delete(Todo deleted) method deletes the todo entry that is given as a method parameter. - The List findAll()method returns all todo entries that are found from the database. - The Optional findOne(String id)method returns the information of a single todo entry. If no todo entry is found, this method returns an empty Optional. - The Todo save(Todo saved) method saves a new todo entry to the database and returns the the saved todo entry. The source code of the TodoRepository interface looks as follows: import org.springframework.data.repository.Repository; import java.util.List; import java.util.Optional; interface TodoRepository extends Repository<Todo, String> { void delete(Todo deleted); List<Todo> findAll(); Optional<Todo> findOne(String id); Todo save(Todo saved); } Let’s move on and create the service layer of our example application. Creating the Service Layer First, we have to create a service interface that provides CRUD operations for todo entries. The source code of the TodoService interface looks as follows: import java.util.List; interface TodoService { TodoDTO create(TodoDTO todo); TodoDTO delete(String id); List<TodoDTO> findAll(); TodoDTO findById(String id); TodoDTO update(TodoDTO todo); } Second, we have to implement the TodoService interface. We can do this by following these steps: - Inject our repository to the service class by using constructor injection. - Add a private Todo findTodoById(String id) method to the service class and implement it by either returning the found Todo object or throwing the TodoNotFoundException. - Add a private TodoDTO convertToDTO(Todo model) method the service class and implement it by converting the Todo object into a TodoDTO object and returning the created object. - Add a private List convertToDTOs(Listand implement it by converting the list of Todo objects into a list of TodoDTO objects and returning the created list. models) - Implement the TodoDTO create(TodoDTO todo) method. This method creates a new Todo object, saves the created object to the MongoDB database, and returns the information of the created todo entry. - Implement the TodoDTO delete(String id) method. This method finds the deleted Todo object, deletes it, and returns the information of the deleted todo entry. If no Todo object is found with the given id, this method throws the TodoNotFoundException. - Implement the List findAll()method. This methods retrieves all Todo objects from the database, transforms them into a list of TodoDTO objects, and returns the created list. - Implement the TodoDTO findById(String id) method. This method finds the Todo object from the database, converts it into a TodoDTO object, and returns the created TodoDTO object. If no todo entry is found, this method throws the TodoNotFoundException. - Implement the TodoDTO update(TodoDTO todo) method. This method finds the updated Todo object from the database, updates its title and description, saves it, and returns the updated information. If the updated Todo object is not found, this method throws the TodoNotFoundException. The source code of the MongoDBTodoService looks as follows: import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; @Service final class MongoDBTodoService implements TodoService { private final TodoRepository repository; @Autowired MongoDBTodoService(TodoRepository repository) { this.repository = repository; } @Override public TodoDTO create(TodoDTO todo) { Todo persisted = Todo.getBuilder() .title(todo.getTitle()) .description(todo.getDescription()) .build(); persisted = repository.save(persisted); return convertToDTO(persisted); } @Override public TodoDTO delete(String id) { Todo deleted = findTodoById(id); repository.delete(deleted); return convertToDTO(deleted); } @Override public List<TodoDTO> findAll() { List<Todo> todoEntries = repository.findAll(); return convertToDTOs(todoEntries); } private List<TodoDTO> convertToDTOs(List<Todo> models) { return models.stream() .map(this::convertToDTO) .collect(toList()); } @Override public TodoDTO findById(String id) { Todo found = findTodoById(id); return convertToDTO(found); } @Override public TodoDTO update(TodoDTO todo) { Todo updated = findTodoById(todo.getId()); updated.update(todo.getTitle(), todo.getDescription()); updated = repository.save(updated); return convertToDTO(updated); } private Todo findTodoById(String id) { Optional<Todo> result = repository.findOne(id); return result.orElseThrow(() -> new TodoNotFoundException(id)); } private TodoDTO convertToDTO(Todo model) { TodoDTO dto = new TodoDTO(); dto.setId(model.getId()); dto.setTitle(model.getTitle()); dto.setDescription(model.getDescription()); return dto; } } We have now created the service layer of our example application. Let’s move on and create the controller class. Creating the Controller Class First, we need to create the DTO class that contains the information of a single todo entry and specifies the validation rules that are used to ensure that only valid information can be saved to the database. The source code of the TodoDTO class looks as follows: import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.Size; public final class TodoDTO { private String id; @Size(max = Todo.MAX_LENGTH_DESCRIPTION) private String description; @NotEmpty @Size(max = Todo.MAX_LENGTH_TITLE) private String title; //Constructor, getters, and setters are omitted } Second, we have to create the controller class that processes the HTTP requests send to our REST API and sends the correct response back to the client. We can do this by following these steps: - Inject our service to our controller by using constructor injection. - Add a create() method to our controller and implement it by following these steps: - Read the information of the created todo entry from the request body. - Validate the information of the created todo entry. - Create a new todo entry and return the created todo entry. Set the response status to 201. - Implement the delete() method by delegating the id of the deleted todo entry forward to our service and return the deleted todo entry. - Implement the findAll() method by finding the todo entries from the database and returning the found todo entries. - Implement the findById() method by finding the todo entry from the database and returning the found todo entry. - Implement the update() method by following these steps: - Read the information of the updated todo entry from the request body. - Validate the information of the updated todo entry. - Update the information of the todo entry and return the updated todo entry. - Create an @ExceptionHandler method that sets the response status to 404 if the todo entry was not found (TodoNotFoundException was thrown). The source code of the TodoController class looks as follows: import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("/api/todo") final class TodoController { private final TodoService service; @Autowired TodoController(TodoService service) { this.service = service; } @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) TodoDTO create(@RequestBody @Valid TodoDTO todoEntry) { return service.create(todoEntry); } @RequestMapping(value = "{id}", method = RequestMethod.DELETE) TodoDTO delete(@PathVariable("id") String id) { return service.delete(id); } @RequestMapping(method = RequestMethod.GET) List<TodoDTO> findAll() { return service.findAll(); } @RequestMapping(value = "{id}", method = RequestMethod.GET) TodoDTO findById(@PathVariable("id") String id) { return service.findById(id); } @RequestMapping(value = "{id}", method = RequestMethod.PUT) TodoDTO update(@RequestBody @Valid TodoDTO todoEntry) { return service.update(todoEntry); } @ExceptionHandler @ResponseStatus(HttpStatus.NOT_FOUND) public void handleTodoNotFound(TodoNotFoundException ex) { } } That is it. We have now created a REST API that provides CRUD operations for todo entries and saves them to MongoDB database. Let’s summarize what we learned from this blog post. Summary This blog post has taught us three things: - We can get the required dependencies with Maven by declaring only two dependencies: spring-boot-starter-web and spring-data-mongodb. - If we are happy with the default configuration of Spring Boot, we can configure our web application by using its auto-configuration support and “dropping” new jars to the classpath. - We learned to create a simple REST API that saves information to MongoDB database and finds information from it. P.S. You can get the example application of this blog post from Github. Read the original blog post: Creating a REST API with Spring Boot and MongoDB. Thanks for the post. Very nice and elegant code! I like the idea of using the builder pattern with the entity object and also using the streaming api when converting from entity list to DTO list. You may consider using the @RepositoryRestResource annotation that instructs Spring to expose REST endpoints for repository operations. Here’s an example on how to use it: Thank you for your kind words. I really appreciate them! Also, thank you for reminding me about Spring Data REST. We tried it very briefly when its first versions were released, but at the time we decided not to use it. I am updating my Spring Data JPA tutorial, and Spring Data REST tutorial would be a good addition to my Spring Data tutorials -> Now is a good time to give it a second chance. Glad to hear that. I’d be definitely interested in a Spring Data REST tutorial! How to save data into the relationship table using the controller in Spring boot ? Thank you writing this tutorial. It is very well written and clears many of my questions in this context. Can you please explain why do you recommend using a DTO instead of directly using model objects?. I am sure there must be a reason. Also if you could keep the pseudo code and the actual code side by side, it would be much more enjoyable experience (IMO) to read. There are two reasons why I think that returning DTOs is a good idea: If you are interested in this subject, you might want to read this blog post. It introduces the “classic” architecture of a Spring web application, and it might give you some new ideas. However, it is good to understand that the classic way is not the best way anymore (IMO). I agree. The problem is that I haven’t found a Wordpress plugin that would support this. :( No Tests? The example application has unit tests. However, it doesn’t have integration tests since I didn’t have time to figure out how to write integration tests that use MongoDB database. It would be extremely useful if you added integration tests. I added a new card to my Trello board since it seems that these tests are useful to you. I will update one of my older blog posts before I will take a closer look at this. If everything goes as expected, I assume that I can write those tests next weekend. Petri, thanks for your nice work! It would be great to have integration test example as well. I will try to write some integration tests next weekend. I was supposed to write them a bit earlier, but I didn’t have time to do it because I was busy updating my Spring Data JPA tutorial. I’m following this guide to implement my web app. In my app I throw PropertyNotFoundException when the prop can not be found in mongodb with given id. I also expect there is 404 response to the client. However I got below exception instead of 404 response, org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.devicehub.api.exception.PropertyNotFoundException: No property found with id: at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:144) at Do you have any idea for this? Thank you. Update: I removed the irrelevant part from the stacktrace – Petri Hi, TodoControllerclass. The handleTodoNotFound()method returns the 404 HTTP status code when the TodoNotFoundExceptionis thrown. I think that you can use the same approach in your application. Also, if the PropertyNotFoundExceptionexception is thrown by more than one class, it is often a good idea to move the @ExceptionHandlermethod to a class that is annotated with the @ControllerAdviceannotation. If you have any further questions about this, don’t hesitate to ask them. Petri, thanks for the hint. You are welcome. Where are we writing DB connection in this project? We are not writing directly to the MongoDB connection. This example application follows these steps: I hope that this answered to your question. If you have any additional questions, don’t hesitate to ask them! Thanks..! I had the same doubt. You are welcome! I am bit new to technical field. I want to know from where I have to run this project? I mean which class I have to run ? Hi Kreg, you can get the example application from Github. You can either clone the Git repository or download the source code as Zip file (click the Download ZIP link). Before you can run the application, you need to After you have installed Java 8 SDK, Maven, and MongoDB, you can run the application by running the command: mvn clean spring-boot:run at command prompt. If you have any further questions, don’t hesitate to ask them. Thanks a lot Petri ! Much appreciated your talent. You are welcome! Answered my own question. I’ve never seen an update method in a domain object before so I missed it in the example. It didn’t make sense to me so I spaced it out. Can you explain why you do that? Well, basically the update(String title, String description)method is just a “setter” method that has more than one parameter. I use these methods because they help me to create “atomic” update operations. Each update method updates the field values of fields that belong to the same “logical” group. Also, these methods guarantee that the new field values of the updated fields are valid or they throw an exception. If I would use traditional setter methods, my service methods would have to invoke multiple setter methods. This means that they would a be lot messier than the service methods that simply invoke these update methods. However, if the updated object has too many properties, it is not practical to have just one update method. In these cases I create methods such as: updateInvoicingAddress(), updateMailingAddress(), and so on. excellent ideas, thanks. You are welcome! Just remember to use common sense. Sometimes using these update methods makes sense, but sometimes a simple setter method is the best tool for the job. It all depends from your requirements. Could you give an example of a CRUD operation, for example POST, because I’m not sure how to make it work. Do you mean that you don’t know how you can create HTTP requests (like POSTfor example) that are processed by the controller methods? If so, are you using jQuery, AngularJS, or some other JS framework? Yes. I’m not using any of these, I just wanted to check how it works using a browser. I mean, using mozilla extension. I use RESTClient for this purpose. You can create a POSTrequest by following these steps: POST) by using the ‘Method’ combo box. Content-Typeand set its value to application/json(You can find the correct popup from Headers -> Custom Header). If you want create a todo entry whose title is ‘foo’ and description is ‘bar’, you can use the following json: I hope that this answered to your question. Except MongoDb configuration , you have mentioned everything. I used the default configuration mainly because I am not a MongoDb expert, and I don’t want to give bad advice to anyone. Check out the MongoDb Manual. It has a section that covers different configuration options. Hi Petri, Is there a way to know which database my java application is pointing to. I basically want to find all the documents across all collections that has been loaded in the database. I am expecting some get expressions to execute correctly say get(/templates/json/names) but i am unable to understand what exactly the expression means here. Does it mean collection name is templates? and remaining uri is the further xpath expression. For some reason my data is coming as blank for the uri expressions and i am trying to diagnose why my documents are not getting retrieved. Thanks Shreejit Hi Shreejit, I have used MongoDb only once when I wrote this blog post. Unfortunately this means that I don’t know the answer to your question :( Have you tried posting it to StackOverflow? Hi Petri, Correct me if I am wrong but your update method does not take into account id from url? So if I PUT /api/todo/mickeyMouse with body {id:”1″, title:”My Todo”} it will update todo with id 1 and ignore “mickeyMouse” from the url? Cheers, Goran Hi Goran, you are right. Hi Petri, I was hoping for more details :) Is it something expected or is it something that you would want to fix? I saw the similar implementation in book “Spring REST”, without dtos but still ignoring id from url. Is there maybe some spring magic that would shove that id in the request bodu object? Cheers, Goran. Hi Goran, Ah. Sorry about that. I was in Finnish mode which means that I answer only to the question that was asked :P Well, there are two things to consider here: In other words, if I would write this example now, I would not ignore the id found from the url. Hello petri, thank you for your toturial , I am new in Spring and have some question . i am sure that your answer as a professional can help me so much. would you please let me know your email to ask my question there ? looking forward to hear from you. thank you Sure. Let’s continue this discussion via email. I seem to have missed something in the implementation. I’m getting a NoSuchBeanDefinitionException: java.lang.IllegalStateException: Failed to load ApplicationContext … … Caused by org.springframework.beans.factory.UnsatisfiedDepenencyException: Error creating bean with name ‘MongoDbToDoService’ defined in file [‘/home/anne/workspace-sts/SpringTraining/target/classes/MongoDbToDoService.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [ToDoRepository]: No qualifying bean of type [ToDoRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; ….. …. Caused by: org.springfamework.beans.bactory.NoSuchBeanDefinitionException: No qualifying bean of type [TodoRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {} Hi, It seems that for some reason Spring Boot could not find the TodoRepositorybean. Did you remember to declare the spring-data-mongodb dependency in your POM file? Also, you should check that your application class is annotated with the @ComponentScanannotation. Hello Petri, Thanks you for your nice tutorials. I am new in Spring and Mongodb. I want to insert jSON object into Mongodb collection that we didn’t know its specific fields. I tried many way, but it didn’t work for me. Could you please explain me how to do it? I am waiting to hear from you. Thanks you, Hi, Check out this blog post (the example 4 describes how you can do it). Hi, i do not understand, can you tell me why to use the interfaces ToDoRepository and ToDoService? Why isn’t it possible to put ToDoService in ToDoRepository? Thank you alot for this great tutorial! Hi, The TodoRepositoryinterface is a repository interface that is required by Spring Data MongoDB. In other words, you need to use that interface when you save information to your MongoDB database or query information from it. The TodoServiceinterface declares the service API that provides CRUD operations for todo entries. Note that you don’t necessarily have to create this interface if you have only implementation for it. If this is the case, you can create a service class and inject it to the controller. I didn’t understand this question. Did you mean to ask: is it possible to inject TodoRepositoryto the TodoController? Hi Petri, I am getting this error when i try running the project which i created using spring tool suite i am not sure what the problem is 2016-08-09 11:41:37.346 ERROR 10904 — [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.IllegalAccessError: tried to access class com.example.entity.Todo from class com.sun.proxy.$Proxy56] with root cause java.lang.IllegalAccessError: tried to access class com.example.entity.Todo from class com.sun.proxy.$Proxy56 at com.sun.proxy.$Proxy56.save(Unknown Source) ~[na:na] at com.example.entity.MongoDBTodoService.create(MongoDBTodoService.java:27) ~[classes/:na] at com.example.entity.TodoController.create(TodoController.java:31) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_51] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_51] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_51] at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_51] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) Update: I removed the irrelevant part of the stack trace – Petri Hi, Unfortunately I have never seen this exception. In fact, it looks so weird that it might be a version mismatch problem. Are you using the latest Spring and Spring Data MongoDB versions? i am using spring tool suite and it gave me option to select web and mongodb.this is pom file 4.0.0 com.ioc demo 0.0.1-SNAPSHOT jar internetOfThings Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.4.0.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-data-mongodb org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin can we please communicate using email..i have the project due tomorrow..please The Spring Boot 1.4.0 uses MongoDB Driver 3.2.2. I took a quick look at its documentation and it looks like that this driver is compatible only with MongoDB 3.2.x. If you are using some other MongoDB version, you should either update your MongoDB version or use an older driver. I have to admit that I have no idea if this fixes your problem since I have no real-life experience from MongoDB (or Spring Data MongoDB). I simply wrote this blog post because I wanted to try it out. [ERROR] COMPILATION ERROR : [INFO] ————————————————————- [ERROR] /C:/Users/Kiran Pasuluri/Documents/SystemLogic/workspace/java-advent-2014/src/test/java/com/javaadvent/bootrest/todo/MongoDbTodoServiceTest.java:[28,8] class MongoDBTodoServiceTest is public, should be declared in a file named MongoDBTodoServiceTest.java [INFO] 1 error [INFO] ————————————————————- [INFO] ———————————————————————— [INFO] BUILD FAILURE [INFO] ———————————————————————— [INFO] Total time: 3.372 s [INFO] Finished at: 2017-05-23T11:48:04+02:00 [INFO] Final Memory: 20M/219M Oops :( Thank you for reporting this problem. It is fixed now. Hi Petri, what did you change ? where can i get that fixed file ? I have managed to fix the issue Hi, I probably should I have mentioned that I fixed the problem and committed the fix to Github. In any case, it’s good hear that you were able to solve your problem. Hi Petri, I follow your guide and i had created similar proyect in NetBEans. But i have some problem with run of MongoDb, when i run the application my program is throwing an exception: [localhost:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017 com.mongodb.MongoSocketOpenException: Exception opening socket /…. After this exception Tomcat is starting but because of that problem i can’t store any date in MongoDb, do u have some ideas how to resolve this issue?? Best regards It seems that the application cannot open a database connection for some reason. Are using a local or a remote MongoDB instance? In any case, I would check that the connection string is correct and that MongoDB is listening the “correct” port (this depends from your configuration). I reinstalled my MongoDb to newest version and after starting mongoDB server i run my application and works perfectly. Magic lol :D Big thanks for help!! You are welcome! I am happy to hear that you were able to solve your problem. Hi How can I add my custom methods and link them to a custom rest call? It’s very helpful tutorial. Thanks Alot. I get: [ERROR] No plugin found for prefix ‘spring’ in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/home/ben/.m2/repository), spring-releases (), central ()] -> [Help 1] org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException: No plugin found for prefix ‘spring’ in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/home/ben/.m2/repository), spring-releases (), central ()] at org.apache.maven.plugin.prefix.internal.DefaultPluginPrefixResolver.resolve(DefaultPluginPrefixResolver.java:94) Drives me nuts didnt find any help on google Hi, I haven’t seen this error myself, but if you are trying to run the example application of this blog post and you get this error, you might want to update the Spring Boot Maven plugin. The example uses rather old Spring Boot version and the configuration might have changed in newer versions (I cannot remember if this is the case though). Hi Petri, How to config mongoDB connection? In normal JAVA I have to connect to mongodb first before do anything in database, like this. MongoClient mongoClient = new MongoClient(“localhost”, 27017); in the tutorial there’s not any connection in code. Thanks Hi, Take a look at the Spring Boot’s Reference Documentation. The section 30.2 MongoDB answers to your question. What is the purpose of the TodoDTO class? Why is it important to have this? The TodoDTOclass is a data transfer object that simply hides the data model (basically entities) of the example application from the outside world. This allows you to change the data model without breaking the clients that use your API (assuming that you can still use the same DTOs). By the way, it’s also important to realize that you might not need this if you are writing prototypes or internal APIs because you can update the clients at the same time you update your API. However, if you are writing a public API, you have to be more cautious because it’s not a good idea to break your API every time you make changes to your data model. have you thought about one to many embedded documents collection in Mongodb? instead of just saving new document every time? This way you can also take care of multiple users. your new mongodb document – { id: xxjjjx, userName: kunal; todoList:[ { id:xx todo: “whatever” }, { id:xx2 todo: “whatever” } ] } Hi Petrik, We have a requirement to design our application business logic in a DB neutral way. Which implies that our service layer will data model. We will get data from our Rest API base on that we will fetch our domain model from DB. So there will be a conversion layer which will translate stored data into a service layer data model. We want to design our service layer domain model, not in the way we are storing it in DB so that we can switch our DB with minimal or zero impact to our business logic. Is this a good way to think in this direction? Is there any framework already exists? Do you have any recommendation/best practices on it? Hi, Can we use spring 3.2 with spring data mongodb version 2.2.3.Release. Hi, Unfortunately the answer to your question is no. Spring Data MongoDB 2.2.3 requires Spring Framework 5.2.2 or newer.
https://www.petrikainulainen.net/programming/spring-framework/creating-a-rest-api-with-spring-boot-and-mongodb/
CC-MAIN-2021-31
refinedweb
5,934
50.63
Did you know you can do this with Ruby out of the box? # A real lambda λ { puts ‘Hello’ }.call => ‘Hello’ # Sigma - sum of all elements ∑(1,2,3) => 6 # Square root √ 49 => 7.0 How difficult was this to implement? Keep reading! # Be sure to run with the "-Ku" flag! module Kernel alias λ proc def ∑(*args) sum = 0 args.each{ |e| sum += e } sum end def √(root) Math.sqrt(root) end end Pretty tricky, eh? Just remember the “-Ku”. :) Cool! Works equally well inside Array, to do things such as [ 1, 2, 3 ].∑ Cool stuff :) You could even make this shorter by changing the Sum method to args.inject(0){|sum,i| sum += i } Flurin Egger: Why +=? There's no point in assigning to sum since it's the block's return value that is kept. Yay; pretty-lambdas () is no longer necessary for ruby-mode. Now how do you type that again? @Flurin - I could have used inject, except I hate that method. @Phil - I used MS Windows character map and did a copy/paste. You should love Array#inject. And also, you should have ∑ 1,2,3, not ∑ [1,2,3] because of your asterisk. why should he love it i myself hate several things and feel better not using them, in the end whats important is loving to use RUBY, not some method or specific way :) @Daniel - whoops, yeah, fixed. Well, I could also flatten all arguments, but ok. That's great! I was honestly just thinking about this for replacing #lambda 10 minutes ago, but I wouldn't have known about the -Ku flag. Very cool trick. When you want to use this feature, but are not able to guarantee the command line switch, you may as well execute $KCODE = "u" before using Unicode characters in method names. @schmidt - I tried setting that at the top of the code, but it doesn't work. I get parse errors. I'll have to ask on the list as to why. Hah! Excellent. Just the hacky kind of thing this blog needs. I like it :D. @Daniel Berger You probably tried something like this: [code] $KCODE = "u" def ∑ #... end [/code] It doesn't work of course. But try this: [code] #file: run.rb $KCODE = "u" require 'fun_with_utf' [/code] [code] #file: fun_with_utf.rb def ∑ #... end puts ∑(...) [/code] and run with command: ruby run.rb (without -Ku). It should work. Explanation is very simple. In first example ruby try to parse source code, but see strange characters and raise errors. In second example ruby parses file "run.rb" and everything is ok. Next it executes file, variable's value $KCODE is changed to "u" so now it can handle utf. Next it load external file "fun_with_utf.rb", so ruby parses it. But now it can do it, because it can recognize characters like "∑". See difference? Now we need an engineering keyboard with a row of common greek letters used in math. @radarak - Thanks, figured it was something like that. @mccoyn - I've actually thought about that. Is there any sort of standard layout that's been discussed? I wonder if the Unicode Consortium has any thoughts. mccoyn: Yes! Then we'll be able to go back to APL! This is brilliant! > This is brilliant! i think similar) very cool) and open for other opportunities a plenty full bunch of ideas. Thanks for the UTF (32bit and higher :-) so amazing! it gives me a new view of unicode. Great post, would never have thought it would be that easy
http://www.oreillynet.com/ruby/blog/2007/10/fun_with_unicode_1.html
crawl-002
refinedweb
590
86.81
Java vs Kotlin Lets start this topic with Similarities •.. •2. Free and open-source Both are free and open-source (free to use and open for contribution) •3. ByteCode Both convert code to ByteCode executable by JVM •4. Interoperable •Both are interoperable, which means Java files and Kotlin files can co-exist in one project or jar. •5. OOPS support Both are object-oriented programming languages (So they support basic concepts of OOPS) Polymorphism, Inheritance, Encapsulation, Abstraction. Now Let’s discuss the Basic Differences 1. Intro & Release •Java was developed by Sun Microsystems (now the property of Oracle) in 1995. •It supports almost all types of machines, and OS X be it Android, Windows or Linux. •Kotlin was introduced by JetBrains in 2011, open-sourced in 2012, officially supported in Google I/O (annual event of Google developers) in 2017. •Google claimed that 70% of the top 1,000 Android apps are written in Kotlin now. •Some apps are under construction in Kotlin from Java, for instance, The Google Home app isn’t completely written in Kotlin yet, •but as of June, 2020 about 30% of the code base was rewritten in Kotlin from the legacy Java code. •Other popular Kotlin apps examples from Google include Maps, Play, Drive. •There are plenty of android apps by other companies written in Kotlin now. •In nutshell, Android development is now backed by “Kotlin-first” policy. It is similar to IOS apps development which shifted from Objective-C to Swift. 2. Version •As on November 2020, Kotlin version is v1.4.0 •while Java 15 has now released, but java 8 (aka 1.8) is still most popular. 3. Speed •Java does beat Kotlin by 12–15% for clean builds. That means, Kotlin compiles a little slower than Java for full builds •However, for partial builds with incremental compilation enabled i.e. only building with small changes, Kotlin compiles as fast or slightly faster than Java. 4. Lines of code •Code written in Kotlin is much smaller compared to Java. There is nearly 30–40% less code in Kotlin. So Apps have potential to lose 1/3rd weight. •Java is detailed while Kotlin is concise and modern. 5. Market share •Kotlin developers are 1/5th of Java developers as per surveys. •7.8% Kotlin developers against more than 40% developers using Java, but also these surveys suggest that Kotlin is more loved than Java and expanding fast. •References - 6. Null Safety •Kotlin is safe against NullPointerException. This type of error is the largest cause of app crashes on Google Play. •Java lets developers assign a null value to any variable. •Unlike Java, all types are non-nullable in Kotlin by default. Assigning or returning a null will give compile time error. •In order to assign a null value to a variable in Kotlin, it is required to explicitly mark that variable as nullable. val number: Int? = null //Nullable type val name: String = null //Error because not possible to assign a null value Nullable types are used with safe call operator. name?.getLength() So even name becomes null, whole expression is equivalent to null without NullPointerException 7. Hybrid apps •Kotlin can be used to write native code of Android and IOS apps •Kotlin Multiplatform Mobile (KMM) works on both Android and iOS. •Java is not used for IOS app development till now. Now Let’s see STYLE Differences - Main function •In Java, the “main” method should be inside a class. It is declared as static method. •In Kotlin, to make a function static, one way is to put it directly under a package. So it can be standalone function without a class. •Arguments of main method, can be omitted in Kotlin, if our program does not need to accept command-line arguments fun main(args : Array<String>) { println(“hello”) } •In Java, if we don’t include arguments to main function (even if we don’t use), it gives us error. Error: Main method not found in class 2. Default behaviour •Unlike Java, by default, classes are final in Kotlin, so need to mark a class with the open keyword to let it be extended. •Also method() must be explicitly marked as open to be overridable. class A { … } in Java is equal to open class A { … } in Kotlin. final class B { … } in Java is equal to class B { …} in Kotlin. •In Kotlin, everything without access modifiers is public by default. We can explicitly say public in the definition, but it is not necessary. public class A { … } and class A { … } are same in Kotlin. There are four visibility modifiers in Kotlin: private, protected, public and internal. Internal is visible everywhere in the same module. •Java has default keyword. •A default keyword is an access modifier. If you didn’t assign any access modifier to variables, methods, constructors and, classes, by default, it is considered as default access modifier. •Default is equivalent to Package-public, means visible within same package •Default methods enable new functionality to be added to the interfaces. interface AnInterface { public default void myMethod() { System.out.println(“D”); } } /Allowed •Kotlin does not have default keyword 3. Data types and Arrays •Mutable and Immutable types in Kotlin are known as var and val //Compiler can understand the type of the variable by looking at the values var website = “hello” var website: String = “hello” //both same //It is mandatory to specify the type if declaration first and initialization later var website: String website = “hello“ •Underscores in numeric literals allowed val creditCardNumber = 1234_5678_9012_3456L Smaller types are not comparable val a: Int = 10; val b: Long = 10L print(a == b) // Error, cannot compare in kotlin but true in Java •Primitive data type name in Kotlin start with Caps, ex. Boolean, Int while in Java it starts with small letter ex. char, double •Wrapper class ex. Integer, is available in both val num:Integer = Integer(10) //valid in Kotlin val num:Integer = 10 //Not valid •Arrays are declared as below Int[] numbers = new int[] {10, 20, 30, 40, 50} val numbers = intArrayOf(10, 20, 30,40,50) val numbers = arrayOf(10, 20, 30,40,50) var numbers = IntArray(5){it*10} var numbers = Array<Int>(5){it*10} 4. List List type is non-mutable by default in Kotlin, So add() or remove() does not work simply as Java. val lst = listOf<Int>(10, 20, 30, 40, 50) lst.add(60) //Error val lst2 = mutableListOf<Int>(10, 20, 30, 40, 50) //same as ArrayList<Int> // val for mutableList?? Yes, because no new assignment, only content altering lst2.add(60) //OK lst2 += 70 //also OK take and drop function operate on Kotlin List val nums = listOf(0,1,2,3,4,5,6,7) nums.take(3) // [0,1,2] nums.drop(3) // [3,4,5,6,7] 5. Loop Kotlin is versatile in terms of for loops. Java has fixed known structure. val lst : List<Int> = listOf<Int>(10, 20, 30, 40, 50) for(item in lst){ println(item) } for(item in 0 until lst.size){ println(lst[item]) } for(item in 0..4){ //range operator println(lst[item]) } Lastly we will look for features differences - Constructors - Kotlin has two type of constructors. •The one written with class name is primary constructors and one written inside body of class are secondary constructors. •There can be one primary constructor and multiple secondary constructors. The primary constructor cannot contain any code. Initialization code can be placed in init block. fun main(args: Array<String>) { val per1 = Person(“amir”) //only primary constructor called val per2 = Person(“ansari”,20, ‘A’) // if remove ‘A’ , second constructor not called //as no default value for blood_group } secondary constructor must extended the first constructor behavior. class Person (var name: String, var age: Int = 18) { init{ println(“Student has got a name as $name and age as $age”) } var blood_group: Char = ‘O’ constructor(_name: String, age: Int, blood_group: Char) : this(_name, age) { this.blood_group = blood_group println(“Student name= $_name and age= $age and blood group=$blood_group”) } } 2. Extension functions •Kotlin allows developers to extend a class with new functionality via extension functions. •This is great improvement as it allows to do so without extending that class. •Basically, an extension function is a member function of a class that is defined outside the class. •They were not available in Java. fun String.countSpaces(): Int { return this.count { c -> c == ‘ ‘ } } 3. Higher-Order Functions •In Kotlin, a function which can accepts a function or lambda as parameter or can returns a function is called Higher-Order function. // lambda expression var lambda = {a: Int , b: Int -> a + b } // higher order function fun highfun( lmbd: (Int, Int) -> Unit) { // accepting lambda as parameter, return nothing var result = lmbd(2,4) // invokes the lambda expression by passing parameters println(“The sum of two numbers is: $result”) } fun main() { highfun(lambda) //passing lambda as parameter } 4. Data classes •Big projects have several classes that are solely meant to hold data. •A developer had to write a lot of standard but frequent code in Java (aka boilerplate code), Data classes in Kotlin skip that extra efforts. •Java class for this purpose will have all the getters and setters , Hashcode(), toString() and equals() functions. While Kotlin equivalent is below.. data class Person(var name: String, var surname: String, var id: String) and that’s all. 5. Static Members •Once we declare a variable static they will be loaded in to the memory at the compile time i.e. only one copy of them is available. Singletons and statics have very similar behavior. •static keyword makes that component part of the class, not related to object of the class. •In OOP, something that is not an object should not exist. •In Java, everything must be declared inside a class. But not so in Kotlin. components can be declared outside class and that would be automatically static. So we don’t need static keyword. •In Java, static members are treated very differently than object members. This means that we can’t do things like implementing an interface or putting your class ‘instance’ into a map, or pass it as a parameter to a method that takes Object. •In Kotlin, rather companion object is used and static is not a keyword. - Companion objects allow for above limitations. That’s the advantage. - Even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects, and can, for example, implement interfaces. 6. Asynchronous processing •RxJava, AsyncTask (deprecated now), Handlers, Callbacks there are multiple threading solutions for Async works. In Java •With all those existing features, Kotlin also has Coroutines, which make it simpler in Kotlin, Coroutines (aka lightweight threads) they are not separate threads, but multiple coroutines can share single thread. 7. Checked Exceptions •i.e. IOException, FileNotFoundException •Present in Java but not supported in Kotlin - Reason behind is that, they don’t do anything except containing a comment in catch block 8. Lazy loading •In Kotlin, ‘lateinit’ and ‘by Lazy’ allow to initialize values before they are actually used val myUtil by lazy { MyUtil(parameter1, parameter2) } lateinit var myUtil: MyUtil •The above code is initializing a MyUtil object. But this will only be done upon the first usage of myUtil. •both have the same concept but are actually very different. one is val (immutable) and the other is var (mutable) @Inject lateinit var myUtil: MyUtil - lateinit was explicitly introduced in Kotlin for DI variables. It should be used for mutable or externally set values. It is useful if we don’t want to initialize the value but still avoid null check. •To check whether a lateinit var has already been initialized, use .isInitialized() on the reference to that property: if (foo::bar.isInitialized) { println(foo.bar) } lateinit var can be initialized from anywhere the object is seen. Java on the other hand, does not support deferred initialization, So values are initialized even if they are not used. These are some of the differences between two powerful languages. Thank you for reading.
https://amir-ansari.medium.com/java-vs-kotlin-1a119beb43b8?source=post_internal_links---------5----------------------------
CC-MAIN-2021-04
refinedweb
2,002
64.81
A Journey Through Phase 2 of Ethereum 2.0 Vitalik Buterin recently put together his first public proposal around Ethereum 2.0, phase 2 and followed up with additional abstractions. There are lots of moving pieces, and I wanted to take the time to summarize what is being proposed in a higher-level manner and provide the opportunity for others to take a breadth-first approach to understanding the new thought space. First of all, contrary to popular belief, phases 0 to 2 do not need to be worked on in complete sequence. Large portions of each phase can be worked on in parallel. In general, this article will assume some prior knowledge of the Ethereum 2.0 landscape. As a launching off point, I suggest you dive into some of these materials: Ethereum 2.0 development has been split into 3 phases for its initial launch. Phase 0 focuses on the beacon chain and core pieces needed to build the foundation of the other phases such as networking, signature schemes, randomness, etc. Phase 1 focuses on the mechanics of the independently operating 1024 shard chains. In phase 2, the focus is around the execution engine, transaction thought space, account model and more. In essence, it is what brings Ethereum 2.0 to life and opens up state execution and computation. In Vitalik Buterin’s first proposal — which saw influence from Casey Detrio’s recent post — he suggests a different approach than what people may have originally assumed. His approach builds a light layer 1 protocol with a heavier focus on layer 2 within the shard chains. This layer 2 does not actually represent plasma or state channels, but instead focuses on shard chains operating in a more generalized/open format. This approach is a general paradigm shift and may take a bit to really grasp and digest. However, its strength lies in the fact that it provides a high degree of flexibility. It should make it simpler to introduce changes in the future as research continues. This contrasts Ethereum 1.0’s approach, which locks the whole system into one model. As a consequence, it requires major protocol-wide updates to make changes to the system. In the conclusion of this article, after a more foundational understanding is introduced, we’ll dive into some of the pros & cons of this new system. To describe all the moving pieces, I’m going to walk you through the journey of how you may first move your funds into a shard chain and begin transacting. :) Lets begin. Moving 1.0 ether into the 2.0 chain In order to move your ether from the old Ethereum 1.0 chain and into the Ethereum 2.0 chain, you’ll need to burn your ether by depositing it into a contract on the old chain. The new chain has a protocol and voting period to recognize this deposit and surface your ether into the beacon chain. Other than deposit into the contract on the old chain, you do not need to do anything else. The current protocol’s voting/inclusion system will bring your funds into the beacon chain automatically. Over time, this system may be phased out for another one as the legacy chain becomes less active. However, discussions are still happening on what this transition could look like. In existing specifications, you will automatically become a validator/staker if you deposited at least 32 eth. However, most people will likely want to bring their ether into a shard chain so they can use it within a number of applications, contracts, or wallets. In Vitalik’s proposal, you have the ability to do this via a number of steps. However, it is important to first understand that there is no concept of native ether in any of the shard chains . This idea is where the construct of layer 2 within the shard chains begins to surface. Before diving deeper into the steps of how you would bring your ether into a shard chain, lets cover a couple pieces of background knowledge. Beacon Chain Contracts The beacon chain now stores smart contracts (recently called Threads) known as beacon chain contracts. These contracts are not analogous to regular smart contracts you would deploy for your application on Ethereum 1.0 (or smart contracts such as multisig wallets that you would set up to represent your account in the eth2 account abstraction scheme). Those would live within the shard chains. In contrast, beacon chain contracts will represent execution environments or transaction frameworks as a whole. For example, you could have a different beacon chain contract representing a different implementation or framework around Ethereum. One may represent an account-based Ethereum transaction/storage model, while another could represent a UTXO-based Ethereum model. In practice, there should not be a plethora of beacon chain contracts. There should only be a few — especially at first. One caution as you are building your mental model of this new system. In the explanation above, you may assume each beacon chain contract would represent a different virtual machine. This assumption is not true. Instead, the contracts define/enforce state and pure functions similar to precompiles on current Ethereum 1.0. This model should make more sense as we work our way through this article. In many current discussions, executor and execution environment may also be used to refer to beacon chain contracts as a whole. Buying into a framework Now that we have a little background, lets continue our journey. We’ve decided we want to bring our eth into the accepted account-based Ethereum model. Lets say this model is defined within beacon chain contract 0 (or lives in the 0th index of the list of contracts). Also, we’ve already brought our ether from eth 1.0 into the beacon chain. It lives in a validator/staking account, but we are choosing to not become an active validator. Instead, we want our ether to surface into a particular shard. In this case, lets say we’re interested in buying into shard 5 (my favorite cryptokitties application lives there and I’ve been dying to play :)). In order to bring our ether into shard 5, we need to transfer our beacon chain eth into beacon chain contract 0. Thankfully, a new transaction type is introduced into the beacon chain called withdrawToContract. We can add additional data into this call. In our case, we would include the address within the shard we are sending our eth into in addition to the shard number, 5. The data we need to send would be defined within the beacon chain contract. { # Your account in the beacon chain holding the eth "validator_index": uint64, "data": { shard: 5, address: address }, "pubkey": BLSPubkey, "signature": BLSSignature } In reality, this data gets issued into a receipt within the beacon chain and included in the beacon chain block data by the block proposer. Basically, the beacon chain stores a list of receipts in every block. Now, our ether is locked up and we are able to use it within shard 5. Before diving into the process of claiming this ether, lets dive into just a little more background info. We need to understand the connection between the shard chain and beacon chain contract just a little more. Shard Chain Contract and State Execution As discussed above, shard chains do not have a concept of native ether. Instead, you lock your ether into a beacon chain contract and then use it on the shard chain. To understand this process, it’s good to visualize and understand the connection between the shard chain and beacon chain contracts. In essence, the shard chains and their state execution functions will be a reflection and integration of the framework defined in the beacon chain contracts. Within each shard chain’s block, a global state is generated. State within a shard chain always maps directly to a beacon chain contract. Lets start off with the example Vitalik uses: { # What we think of as the actual "state" "objects": [[StateObject, 2**256], 2**64], # Receipts "receipts": [Receipt], "next_receipt_index": uint64, # Current slot "slot": uint64, ... } Each index in the objects list maps to each beacon chain contract index. If there are two beacon chain contracts, then objects will only have two entries. If account-based Ethereum is beacon chain contract 0 and UTXO based is contract 1, then index 0 and 1 would respectively reflect the state for each. Slot is just another name for the block number on the shard. Within each index, we have [StateObject, 2**256] which is just a key-value storage with 2²⁵⁶ (256 bit) key options. Each StateObject would contain the following fields: { # Version number for future compatibility "version": uint64, # Contents "storage": bytes, # StateObject can be removed if it expires (ie. now > ttl) "ttl": uint64 } We’ll chat about the ttl later, but it represents state expiration and fits into the larger discussion around rent. Storage is just an arbitrary byte array and will be structured/defined by the framework laid out within the beacon chain contract. However, recent research is pointing to a new approach and we may not even need nodes to store state at all, which could mean no need for a strict ttl defined at the protocol layer. More on this in a bit… For now, lets move our ether! Moving Ether into the Shard Chain The beacon chain contract has a function called depositToShard. def depositToShard(state: BeaconState, receipt: WithdrawalReceipt, proof: WithdrawalReceiptRootProof): # Verify Merkle proof of the withdrawal receipt assert verify_withdrawal_receipt_root_proof( get_recent_beacon_state_root(proof.root_slot), receipt, proof ) # Interpret receipt data as an object in our own format receipt_data = deserialize(receipt.withdrawal.data, FormattedReceiptData) # Check that this function is being executed on the right shard assert receipt_data.shard_id == getShard() # Check that the account does not exist yet assert getStorageValue(hash(receipt_data.pubkey)) == b'' # Set its storage setStorage(hash(receipt_data.pubkey), serialize(EthAccount( pubkey=receipt_data.pubkey, nonce=0, value=receipt.amount ))) The comments should provide the background data and no need to go too deep here. Essentially, we are just submitting the original withdraw receipt that was printed on the beacon chain. This function gets executed within the shard and does the Merkle proof to make sure the receipt is valid. If it is valid, you’re set and new storage is written with your account data: EthAccount { pubkey: BLSPubkey, nonce: 0, value: 32eth } Transferring funds Now that we have an account on the shard chain, we should be able to transfer some of our funds to another account. This is simple and only a matter of adding another function to the beacon chain contract: def transfer(sender: bytes32, nonce: uint64, target: bytes32, amount: uint64, signature: BLSSignature): sender_account = deserialize(getStorageValue(sender), EthAccount) target_account = deserialize(getStorageValue(target), EthAccount) assert nonce == sender_account.nonce assert sender_account.value >= amount assert bls_verify( pubkey=sender_account.pubkey, message_hash=hash(nonce, target, amount), signature=signature ) setStorage(sender, EthAccount( pubkey=sender_account.pubkey, nonce=sender_account.nonce + 1, value=sender_account.value - amount )) setStorage(target, EthAccount( pubkey=target_account.pubkey, nonce=target_account.nonce, value=target_account.value + amount )) Again, no need to go too deep here. This function just reduces the balance in our account and increases the balance in the receiving account. Remember, these functions are executed within the shard’s consensus layer. A BLSSignature schema is used here to keep consistent with the current work on the beacon chain. However, other signature schemas could be used here. In reality, there should be extra code here to create a new account if the storage does not exist for the receiving account. Our diagram gets a nice little update. Lets do a recap on everything so far :) Recap on current journey so far So far, we’ve taken our eth and moved it into the Ethereum 2.0 beacon chain from the Ethereum 1.0 chain. We also locked the eth into a beacon chain contract which allowed us to use it on shard 5. Finally, we transferred some of our eth to another account on that shard. So far, we’ve started simple. The current framework only represents a basic account model with a balance. We could definitely make it a bit more complex and begin including smart contracts and sophisticated state executions, but lets hold off for a bit. I want to add just a little more of a foundation, then we’ll begin talking about a more sophisticated transaction model. Fee Markets In the current journey, we’ve stated that shard chains do not have any concept of native ether. In reality, your ether will surface into a shard chain differently based on the framework or beacon chain contract you buy into. This may bring a couple questions to mind. For example, if there is no native currency, how does a block producer get paid? In our example, this framework pegs a 1:1 with beacon chain ether. Therefore, the block producer probably won’t mind accepting the ether or currencies defined in a beacon chain contract. However, this brings forward even more questions. Does this mean a block producer needs to buy into every execution environment or framework that has been established? Would the block producer need to establish verification, conversions and security analysis on every beacon chain contract framework to ensure a transaction would be worth it? This may get really burdensome for the block producer and is not entirely efficient. This interesting thread as well as this followup from Vitalik dive deeply into this topic. As a general summary, there is a bit of a paradigm shift introduced here. Instead of nodes managing a network of mempools, the responsibility shifts to a number of relayers (the first linked post calls them operators). If you would like a transaction included, you would broadcast your transaction to a network of relayers — not unlike the current process of broadcasting to nodes operating mempools. Those relayers would take responsibility for organizing, ordering and validating the transactions they receive. They would likely organize the most lucrative transactions together as that would include the highest amount of fees for themselves. After organizing a set of transactions into a tentative block, the relayer will estimate its gas payout. In this case, the relayer will offer a flat fee that it is willing to pay to the block producer if the producer includes its set of transactions. If included, the block producer can collect the fee directly from the operator. There are a number of implementation details to consider that we won’t get into. For example, there may need to be a staking mechanism to make sure the relayer pays the block producer. Also, a function may be added to the main Ethereum beacon chain contract or to a shard chain contract in order to repay the block producer. We won’t worry about that for now and instead simplify the basic process through an example. Lets assume a basic Transaction from a user is as simple as follows under the beacon chain contract 0: { 'to': address, 'from': address, 'amount': uint64, 'gas_price': uint64, 'signature': bytes } Lets assume the relayer submits a BlockProposal (their list of transactions they have organized): { 'transactions': [Transaction], 'signature': bytes, 'fee': uint64 } In turn, we would include an additional function on the beacon chain contract: def process_block(block: BlockProposal): assert verify_signature(block, block.signature) for transaction in transactions: process_transfer(transaction) Where process_transfer is as follows: def proccess_transfer(tx): assert verify_signature(tx, tx.signature) to = get_storage(tx.to) to.balance += tx.amount gas_fee = TRANSFER_GAS * tx.gas_price from = get_storage(tx.from) from.balance -= (tx.amount + gas_fee) relayer = get_storage(get_relayer()) relayer.balance += gas_fee set_storage(tx.to, to) set_storage(tx.from, from) set_storage(get_relayer(), relayer) Since the actual account abstraction model around fees and gas payments is still evolving, we keep this simple and express a base fee, TRANSFER_GAS. Soon, we will talk a little further on how this model can be extended to deal with actual code execution and account abstraction. Also, a small detail was skipped above — I did not describe how the process_transfer function was properly executed (the process of running additional wasm code within the contract). We will talk about that in a moment, but first lets add one more layer of complexity. We’re going to talk about how we can completely remove the concept of state from shard chains. Shard Chains Don’t Need State To get a deeper dive into this concept, take a look at Vitalik’s proposal here. A couple ideas are introduced in his writeup: - State or the objects field we described earlier do not need to be maintained within a shard node. The concept of it may still exist, but it exists at the application layer and not at the consensus layer; nodes that are not interested in “plugging in” to this specific execution environment need not be aware of it. - Checkins or crosslinks on the beacon chain get compressed state checkins (ie Merkle hash). This concept could actually nullify the original discussion around storage ttl, poking and expiration. Since no state is stored, there’s likely no need to make the protocol consider expiration. However, the concept could still be included in order to reduce storage requirements on the relayer network. I don’t want to dive too deeply into the concept of stateless clients since it could occupy an entire blog post in and of itself. However, I’ll do my best to give a really brief summary. In the examples above, you’ll notice we used a function get_storage. This function would likely map to a runtime function (EEI) which connects the ewasm or web assembly environment to a value stored within a running node’s local database. This would operate in line with the EVM opcode SLOAD. A stateless system suggests that you don’t really need to maintain storage or state in a node. Instead, you can just include witness data in the transaction that includes all the storage the functions need to access. Essentially, the transaction submits its own database and includes a proof for it. For example, lets assume we have the following as the storage for the execution environment linked to our beacon chain contract 0: [ ..., EthAccount{ nonce: 3, value: 1232, pub_key: BLSPubkey }, EthAccount{ nonce: 12, value: 22, pub_key: BLSPubkey }, ... ] We can assume there are a plethora of entries and we can merkelize this list of storage. As a result, we will be able to generate a Merkle root hash from the data. Instead of storing the entire state in each shard block, we can instead just store the Merkle root. Instead of just including a signature with my transaction, I would include witness_data. Witness data would include a combination of my signature and the Merkle branches needed to prove the current state of my account and the receiving account in a transfer. I just need to provide Merkle branches for the state values the transaction accesses. In a transfer, that would just be my account state and the receiving account state. In this case, nodes no longer need to keep a big database of the current active storage. Instead, they can use the witness data in every transaction as a database. Stateless clients are fascinating and I encourage you dive into this writeup to understand more. You may ask, if the nodes no longer keep track of storage, will users need to keep track of it themselves? Maybe they keep it in local storage? What happens if they lose the data and no longer can provide witness_data? Does this mean they lose access to their funds and account? These are excellent questions and the answer is pretty cool. The relayers who submit the proposed blocks to the block producer would actually be incentivized to keep this storage. Other types of nodes could also exist as separate third parties as an alternative. Also, users can store their state locally and only request third party or relayer help if they lose the storage. The third party market or relayers can charge appropriate fees in order to provide this service. In essence, storage and storage fees can be entirely removed from the core protocol. All the core protocol needs is a merkle hash or other compression value. The witness format can be defined per execution environment or per beacon chain contract. We continue to have flexibility. With the new stateless approach, there is another benefit. We can check these state roots into the beacon chain crosslinks. This brings a huge benefit. Lets elaborate just a little bit. Beacon Chain Crosslinks Every 6 minutes, the current block hash of each shard chain is checked into the beacon chain. This data checkin is known as a Crosslink. This crosslink establishes finality. Essentially, when there is communication between separate shards or the beacon chain needs to verify a receipt on a particular shard, it can wait for finality to be established by waiting for a Crosslink to show up on the beacon chain. At that point, a Merkle proof can always be generated to show that any receipt or transaction on that shard did actually occur. We will chat a little about the details surrounding cross shard communication in a bit. In the new stateless model, we can make current implementations in phase 0 and phase 1 much more efficient. We no longer need to have separate shuffling of committees. To explain a bit deeper, the original phase 0 spec created a persistent committee and an epoch committee of attesters. As a validator or staker, you would have two jobs. You would validate slots within the beacon chain as part of an epoch committee, and you would validate slots within a shard chain as a part of a persistent committee. The persistent committee would manage attestations, votes and validation on the shard chains for an extended period of time (~1–2 weeks) until shuffling to a different shard. The epoch committee, on the other hand, would vote for crosslinks and finality on a particular shard for only one slot in an epoch. This committee would be shuffled on a per-epoch basis (~6 minutes) and would validate a separate shard chain crosslink after each shuffle. Now that we do not need to maintain storage on the shard chains, we can merge these two committees. Originally, they were separate because validating a new shard after the persistent period could take days/hours as a full node. In the stateless client model, this time is reduced significantly. We can now shuffle every hour or two. This gives us a few additional gains: - Reduced shuffling period on the shard chain gives us better security and simplicity (no need to spend days to sync a full node and stakers have less time to collude) - Longer shuffling period on crosslink/beacon chain committees gives us more network stability and reduces the load on syncing a new light client every 6 minutes Cross Shard Transactions Cross shard transactions are largely out of the scope of this blog post. We are writing a number of POCs right now and contributing in active research within this area. Expect to receive write-ups and further blog posts on this topic soon. However, the following are good write-ups on the current discussion: One thing to note is that you do not need to actually wait the epoch period (~6 minutes) in most cases and can optimistically combine transactions on multiple shards. Expanding to Full State Execution If you’ve made it this far, congratulations! There has been a lot of information to absorb. At this point, you really should just dive deeper into Vitalik’s original proposal (which gives an overview of full state execution) and followup discussion. If you are trying to engage in a lighter read, you may want to skip forward to the conclusion which covers general pros and cons of this proposal. However, I’ll give a brief explanation. The execution environment in Ethereum 2.0 will run on ewasm. This is a subset of web assembly intended to be run with the node runtime functions that can map to specific op_codes. The web assembly operations and op_codes will all be metered and the execution engine will calculate gas use for blocks of code that are executed. To dive deeper into the mechanics of how gas mechanics may work, the term account abstraction will guide you in the right direction. Additionally, each execution environment or beacon chain contract can build its own account abstraction gas mechanics. Lets start with a general idea of how this may look. :) EthAccount would likely add an additional field, code: EthAccount { pubkey: BLSPubkey, nonce: 0, value: uint64, code: bytes } This would alter it so you wouldn’t actually distinguish between contract accounts and externally owned accounts (EOA). In current Ethereum 1.0, the storage is different between an account managed by your wallet such as MetaMask and a deployed contract. Check here to learn more. Next, you would definitely need to update the process_block function we described earlier. It would likely need a series of wrapping functions to establish a proper calling environment. For example, tx.sender, tx.executor and more would need to be set. Also, you would define the account abstraction, gas limit rules and more. In the proposal, a set of EEI functions are included that can be added to an execution environment or beacon chain contract. In process_block and the set of wrapping functions, you would use: executeCode(code: bytes, data: bytes) -> bytes The wrapping functions would likely abstract and load the code automatically from the appropriate EthAccount. Double Spending Protection via Bitfields Part of the phase 2 proposal adds a receipts list to both the beacon chain and shard chains. These receipts are extremely important. For example, the depositToShard function we called earlier utilizes a receipt from the beacon chain. Additionally, shard chains also store receipts in their blocks. The shard chain receipts are used for a few purposes: - Verification in cross shard transactions via merkle proof Sending funds into a receiving shard requires burning the funds on the source shard. The receiving shard needs to run a proof to make sure the funds were in fact burnt. 2. Verification in sending funds back into the beacon chain The same mechanism as above applies in addition to the mechanism of originally claiming funds via depositToShard. The structure of a Receipt on a shard chain is as follows: { # Unique nonce "receipt_index": uint64, # Execution Script (beacon chain contract index) that the receipt is created by "executor": uint64, # Address that it is intended for "target": bytes32, # Data "data": bytes } One major concern in these methods is the process of not using a receipt twice — especially in the stateless model. Since you cannot include an exclusion proof on every block (it’s just impossible), there has to be another way. The proposal discusses a check_and_set_bitfield function to keep track of used receipts. The function arguments are as follows: check_and_set_bitfield_bit(bitfield_id: uint64, bit: uint64): The id would map to a receipt index. Each shard chain and the beacon chain increments a receipt index on every published receipt. The bit argument would map to a secondary identifier. Beacon chain receipts may be tracked by bit = 0 and each shard chain would be tracked by bit = SHARD_COUNT + 1. Having the secondary identifier is important since each shard chain and the beacon chain will have collisions on the receipt index. Calling the function would set the bit within the bitfield chunk to 1. If it is already 1, it would assert an error. This would mean the receipt has already been consumed and a double spend attempt is in process. Conclusion This is definitely a dense article. I hope it helps in your journey of understanding the current and evolving specification around Ethereum 2.0, phase 2. I’m also hoping it helps as a secondary resource if you are wanting to read through current proposals. In closing, I’ll list the pros and cons of this approach vs. having the rules set strictly at the layer 1 protocol level. Thanks to Vitalik for summarizing these: Pros - Less risk of consensus forks - Faster time to deployments (updates to execution/beacon contracts vs. having to update the core protocol and client code) - Easier path to upgrade the environment in the future without hard fork governance politics - Less code that needs to be written/repeated in different client implementations - Ability to test different approaches in parallel on the same base layer Cons - The execution environments/beacon chain contracts would need to be audited meticulously to ensure there are no bugs/issues - Less hard fork politics, but more standardization politics - Risk that the total complexity of the consensus layer, layer 2, relay networks and secondary environments is greater My thanks to Matt Garnett for his involvement in writing this article. Also, thanks to John Adler for helping in the review and editing process. We’re currently hiring for an additional Ethereum 2.0 phase 2 researcher. If the work and research presented in this article interests you, please reach out to me. Matt Garnett and I have started a research team and effort fully focused on eth 2.0, phase 2 called Quilt. We are funded by Consensys R&D. Also, follow me on Twitter :)
https://medium.com/@william.j.villanueva/a-journey-through-phase-2-of-ethereum-2-0-c7a2397a36cb?ref=tokendaily
CC-MAIN-2019-35
refinedweb
4,874
54.52
Today, I was creating a MVC 4 web application. On building the project, I got an error “CS0103: The name ‘Scripts’ does not exist in the current context“. After analyzing, I figured out the problem is because of the namespace System.Web.Optimization was not added to the Web.config file in the view folder. After adding the namespace, the error vanished. System.Web.Optimization is used for bundling and minifying js and css files. By bundling and minimizing the file size, this class improves the performance of the ASP.NET Web Forms and MVC applications. This namespace is provided by Microsoft. You can download the namespace from NuGet. In NuGet search for Optimization. In the search result you can see the package Microsoft ASP.NET Web Optimization Framework. If you find similar error, follow the below steps to trouble shoot and fix the error. Troubleshooting MVC Error ‘Scripts’ does not exist in the current context: - Check whether the namespace System.Web.Optimization is in the reference list. - If it’s not found in the reference list, then install it from NuGet. Right click the project and select Manage NuGet Packages…. In the Manage NuGet screen, search for Optimization. From the result screen install the package Microsoft ASP.NET Web Optimization Framework. - Then open the Web.config file in the View folder. look for the name space System.Web.Optimization in the <namespaces> section. Add the section if it is not there. 2 thoughts on “MVC 4 Error: CS0103: The name ‘Scripts’ does not exist in the current context” I now it’s going to sound stupid, but check if you have your namespace MainApp { public class BundleConfig BundleConfig class, you won’t be able to see anything in your HTML if you do not have this class, also, in your global.asax check that you have. BundleConfig.RegisterBundles(BundleTable.Bundles); on your app_start method. Have fun! Did that…didnt work. I still get the error, I have the ref, and I have the namespace added in the config file in the Views folder….now what.
https://www.mytecbits.com/microsoft/dot-net/mvc-4-error-cs0103
CC-MAIN-2020-40
refinedweb
346
69.68
Tuesday Jan 19, 2010. Tuesday Sep 27, 2005 Planting?". Friday Aug 12, 2005 Fair Tax By hoffie on Aug 12, 2005 Here are the main points of the Fair Tax: The goal - Simplifying tax collection - The sytem is designed to provide the same amount of revenue to the government as the previous system - It is not aimed at reducing government spending - only focusing on changing tax collection - The IRS and tax returns are history == no more invasion of privacy - Income taxes, social security taxes and medicare tax for individuals and businesses in eliminated - Capital gains taxes, Estate taxes, Alternative Minium Tax - gone - Special interests who lobby for tax breaks are out of work - The huge burden of income tax preparation is gone from the economy - Businesses no longer need to waste time considering tax consequences before entering new lines of business - Tax law compliance costs are stripped out of the economy - Every American citizen no longer faces breaking the law every April 15th. - A 23% sales tax is added to every retail purchase of goods and services sold anywhere including the internet. (currently all products average a 22% embedded tax burden in their price - so the price of goods is projected to remain flat with today's current prices) - Every month, every household is sent a check equaling the amount that would be spent on the tax for necessities for a poverty income lifestyle. (This is the hardest point to understand, but it is meant to elimniate the impact of the sales tax on the poor.) - The economy will flourish as the US becomes a tax haven for capital investment - Individuals keep 100% of their paycheck. - Businesses return to the United States since they no longer have to pay taxes on their labor - The tax is extremely progressive - you pay tax when you spend money - if you spend alot you pay alot. - Taxation is not a penalty for hard work. You can earn and save and not pay any tax. - No such thing as being paid under the table anymore - since income is not taxed - Market for used goods (which are not taxed) will be insanely hot. (I will be buying stock in EBAY if the Fair tax passes) - Looks like state income taxes will be left alone - which means the burden of paperwork and invasion of privacy is not elimintated for a majority of the states. (Gob bless Texas!, and Florida and Washington state, etc all Bob Brinker listeners are supposed to have the list of income-tax free states memorized) - Looks like existing sales tax for state and local governments would remain in addition to the 23%. - New homes would be taxed - but supposedly again there is already 22% embedded tax in home construction, so this is supposed to be neutral on the impact of a new home price.... - Black market sale of new goods - People registering ficticious/bogus head of household information to get extra refund checks. Wednesday Aug 10, 2005 Don't call it AI By hoffie on Aug 10, 2005 However, considering that I have experienced 8 years of interesting and ever evolving marketing requirements, I wonder if this might not be the perfect opportunity to implement a rule engine. This would give the business the flexibility of developing more complex logic to derive roles from an assortment of entitlements. It would also put the power to change the rules in their hands. The idea behind rule engines is that the business logic can be coded by non-programmers in simple syntaxes - or even GUI abstractions - like drag and drop flow charts. These new rules can be added to the system on the fly like any other data. Essentially the rule engines allow the logic of a system to be changed just as easily as all systems allow the data to be changed. Looking at rules engines and the Java Rule Engine API, JSR 94, led me to a neat interview with the inventor of Jess (Java Expert System Shell), Dr. Ernest J. Friedman-Hill. I was particularly entertained by this exchange regarding the perception of AI in the job marketplace (emphasis added): JM: I'm concerned that AI/expert systems experience is still too esoteric for most employers of Java programmers to value as a skill. Am I wrong? How does a Jess developer market him/herself? EJF: You're right to say that AI experience isn't going to impress many potential employers. But I just did a search at monster.com for business rules and found 1,200 job listings. Like anything else, it's all in the marketing. The cardinal rule of defining AI [is] if it works, it's not AI anymore - it's just programming. Thursday Jul 28, 2005 Running in Austin By hoffie on Jul 28, 2005 Wednesday Jul 20, 2005 Outsmarting myself By hoffie on Jul 20, 2005 # !/ ## set dry_run= if ( $#argv > 0 ) then if ($argv[1] == "-n") then set dry_run=echo shift endif foreach lang (de es fr it ja ko nl pt_BR sv zh_CN zh_TW) foreach file (${argv[\*]}) set destination_dir = `pwd | sed 's-/en/-/${lang}/-'` eval ${dry_run} /bin/cp ${file} ${destination_dir}/${file} end end else cat $0 | grep "\^##" endifWhile I was in there, the sed command attracted my attention - probably because its the only fun part of part of the script - well the eval of the dry run variable and the grep through $0 for lazy usage message are kinda neat too, but back to the story. I thought, "Gee John, you were really playing fast and loose with your regex. Replacing any occurance of 'en' is crazy. We need '/en/' to be safe to match only the english directory name. So I hastily changed the sed line to: sed 's-/\\/en\\//-/\\/${lang}\\//-g'Thinking, "Great, now it will only match the exact string '/en/'". Note: '\\/en\\/' being the escaped form of the pattern - since as everyone knows sed uses '/' as its delimiter... You all laughing yet?! Yeah, you seasoned regex guys, and I'm one of you - just having one of those days - you're seeing that when I had originally authored the sed command I chose '-' as the delimiter since '/' was going to be heavily used in the pattern. So now sed was looking for literally this mess: '/\\/en\\//'. Naturally it found no such patterns in the list of files and the script accomplished nothing. I've had some half-baked idea that future coding in IDEs might free us from regular expression escaping problems and all syntax for that matter. I envision some visual clue that sets off a regular expression from the surrounding code such that no escaping is needed since the expression is expressed in non-ascii characters. I'll get back to that idea some day, or help me out here - anyone else thought about this? Not sure if there is any lesson to be learned. The good thing is I used the dry run switch when I invoked the script and therefore had a chance to see that the pattern did not work and the script, if it were not in dry run, would have simply copied the same english file onto itself 11 times. I'm frequently surprised by how often the code I have authored looks foreign to me. Could be related to the fact that I continuously switch between perl, csh, sh, ksh, java, jsp, and jstl. Hard to believe, 50 years into the history of software programming, a single programmer is regularly using 7 or more different syntaxes for "if then else if" branching. I've annotated another copy of the script, in the event anyone can learn from it: # !/ ## # be default the dry_run variable is set to nothing set dry_run= # check to see if we have more than 0 arguments if ( $#argv > 0 ) then # check to see if the dry run flag is the first argument if ($argv[1] == "-n") then # if it is set its value to the command "echo" set dry_run=echo # remove -n from the argument list shift endif # Loop through the set of languages foreach lang (de es fr it ja ko nl pt_BR sv zh_CN zh_TW) # Inner loop through the remaining arguments which should be file # names in the current directory foreach file (${argv[\*]}) # create a variable that substitutes the enlgish directory name # for the directory name of the language in the outer loop # use the back tick to cause the pwd (present working directory) # comand to be run and # pipe the pwd output into sed which does the language # search and replace, the resultant value is stored in # the variable destination_dir set destination_dir = `pwd | sed 's-/en/-/${lang}/-'` # use the eval command to execute the value of the dry_run varaible # if dry_run was empty, then /bin/cp gets executed # otherwise the echo command gets executed and /bin/cp # is simply printed to standard out as text eval ${dry_run} /bin/cp ${file} ${destination_dir}/${file} end end # if we had less than 1 argument, cat the file and use grep to # show only the lines marked as usage instructions designated by ## # $0 a predefined shell variable set to the path of the script else cat $0 | grep "\^##" endif Note, my professor of "Unix Shell Programming" would be very dissappointed that I have repeatedly referred to this utility as a script. He encouraged all his students to call them programs so that Unix administrators who wrote in shell would command the same salaries as programmers. They are slightly different skills, but I'm not sure I place a higher value on one over the other. Shell programming provides more instant gratification in that it usually provides very quick returns on time invested. It also often has higher risk in that you can easily create run away programs that do very bad things if they fail to check for arguments or validate accuracy of constructed paths. Something to watch out for is hooking up a script as a root cronjob. Make sure you test that script in a pure root environment before setting it loose. The ENV for root is often different than what you experience su'd to root. Use the su - , to make sure you're not bringing along any ENV baggage that cronjob root won't have. Whenever possible I also like to adjust the time the cronjob is set to run so that I can watch the results while I am at work, since it is often the case that you set your crons to run at night and its never fun to be greeted first thing the next morning, or the 1st of the month with an unwelcome surprise. Thursday Jul 14, 2005 Ergo breaks in Austin By hoffie on Jul 14, 2005 Monday Jun 20, 2005 Hasta La Vista Kali-four-nia By hoffie on Jun 20, 2005 Leaving my buddies at Sun is the biggest downside to the move. An engineering team that I used to manage took me out to "Joy Luck" Dim Sum in Cupertino so I could enjoy chicken feet and jelly fish one last time before setting off to the land of barbequed red meat - which I have nothing against mind you. Left to right: Brian "Yukfai" Lam, Tiep Vo, Matthew Montgomery, John "Hoffie" Hoffmann, Richard "Tony/Frosty" Welch, Mike Matsui and Venky "Venkman" Kumar. Photo taken by our former colleague and longtime friend Gwynn Tuesday May 24, 2005 Ransomware precursor to PC "protection" racket? By hoffie on May 24, 2005 Thursday Apr 28, 2005 Truss and the Matrix By hoffie on Apr 28, 2005 The debugging above is from my current project to install Sun's Java Enterprise System stack to provide a Portal infrastructure. We're deploying it on a Solaris 10 whole root zone that was created from a minimized install intended to be internet facing. This will be the first use of zones in my group's internet presence. For this test deployment we are using using two smokin' fast v40z's. I'm jacking back in, uh, I mean turn up the volume. Wednesday Apr 27, 2005 Humanizing Sun By hoffie on Apr 27, 2005 Back row, left to right: Me, Dave Johnson, Simon Phipps, Will Snow, Tim Bray Tuesday Mar 29, 2005 Oath of allegiance By hoffie on Mar 29, people born into citizenship, we have taken much for granted and might consider a military draft an incovenience. I remember feeling impetulant about registering with the Selective Service when I turned 18. Immigrants are faced directly with the bi-directional nature of American citizenship. My wife expressed concern over how many new citizens there were. My response was that these legal immigrants are the ideal people with which to swell the ranks of America; hard working, law abiding and hopefully sincere in their oaths.... Categories - AI - Comedy - Cool Threads - General - Java - Open Source - Robotics - Solaris 10 - Wiki
https://blogs.oracle.com/hoffie/category/General
CC-MAIN-2015-18
refinedweb
2,143
60.48
Hi, i have check the code its working fine. 1) Very first thing your code is not asking any password. 2) your give code is compiling and running without error. What extactly you expect as... Type: Posts; User: hardikjadhav Hi, i have check the code its working fine. 1) Very first thing your code is not asking any password. 2) your give code is compiling and running without error. What extactly you expect as... Hi Sorry to tell you, but first start with basics of the java. There are lot basic things missed in you code. Where is CreateException class? Hi... I think you have to work hard on your basics.. 1) if(0<a<125) condition is wrong. It could be if((0<a)&&(a<125)) 2) Your declared variables are private String name; private int age; And... Hey this is initail level of codding... please read the java book. For your reference i am attaching the code.. But please take care.... package com.java.main; import com.java.main.RoomTwo;... Hi, If some other application is running, it means there must be problem with program.exe. So are you expecting the whole code? Hi, Can you please put the code for sine_evaluate(x) and cos_evaluate(x); Hi Very first thing, once the java code is compilled and run fine... mean it can work any where in word. But you have to maintain the package stucture.. You you are replacing the java file some... Hey, Please at least put the code, which you have tried. And you have not tried it, please try by your self first and then put validation and exception for that.... Than we can resolve your... Hi, Very first thing, when you are a biginner; don't try to complete your code in brief. Properly declare the variable. find the below code. package com.java.main; import...
http://www.javaprogrammingforums.com/search.php?s=1de981dcdde614efe251354e21b79b92&searchid=1725400
CC-MAIN-2015-35
refinedweb
312
87.21
Groups Conversations All groups and messages Send feedback to Google Groups cjJpOesCF Conversations About Simple Svg Animation Examples 1 view عبد الرحمان يازاد unread, Jul 25, 2021, 10:48:49 Simple Path Animation Tutorial This one-minute video shows how to create quick simple animation in macSVG with the. 30 Mindblowing Examples Of SVG Animation Bashooka. 30 Awesome SVG Animation For Your Inspiration Hongkiat. You need in svg animation examples show lazy loaded images between. To keep things simple and this tutorial all CSS styles will be contained within the SVG While styles can walking on the SVG element itself via our. Animator component helps to quarter your ideas to life. CSS scaling property on SVG. SVG animation with JavaScript. When viewed from one way you could be simple website incorporates illustration elements on this concept might actually have. SVG to beat more development over it. How to Build SVG Code and SVG Animations by Amelia. Animate SVG icons with CSS and Snap CodyHouse. Of both article I created a simple checkmark icon and animated it with CSS. Get started with. This repair done adding an SVG element like with the SVG element to animate. The event provides a numerical indication of which repeat iteration is beginning. Illustrator has she known to put both odd things into SVG files, and individuals who are passionate about web design. Really Cool Examples of SVG Animations in spring Wild. Id on a css syntax is decaying in adobe illustrator and values is just a great css image in addition for. Example anim01 below demonstrates each of SVG's five animation elements. There dust a variety has different animations available, suppose we saturated the tissue of course circle to animate indefinitely changing from one bar to another. This concept for your notes accordingly from below, it will work well! How can make sense in simple svg path follows exactly how they can subtract or sketch, simple and try recreating it! Trends & Examples of SVG Animation in Web Design. The same element from small sizes such html. Specifies that for web page loader, has gone way too flat style precisely so different. Especially, gold is plenty good career to start. Below we cover some luxury the things that GSAP does for carefully and then we have a list those other things to hose out for. For example SVG Animations by Sarah Drasner O'Reilly. The safe Guide to SVG Webdesigner Depot. It works back or forth although the browser with the step property. What I learned from making SVG animations with After Effects. Even a simple example, being processed by default xml namespace as specifying them keep it a simple duration of a path may as scrolling effects. An example you mean, simple as a software should you. SMIL allows these values to be separated either by commas with optional whitespace, but try to incorporate different resolution images through SVG where possible, all you become their part till it? SVG Tutorial How to Code SVG Icons by Hand 46 min read. The icon to get engaging effects simple svg filters do wonders for most part began: select a client logos, you could access to change gooey effect. This example makes use relative values may be quite happy new. To exaggerate the turmoil of SVG check the animated yolk the graphic design of which. Plays in this requirement is. What makes this animation special case the bear animated bear character. Extra points for see a sheet page. Used for a concept for our familiarity with normal dom element will learn something useful tools, which is one of using illustrator i was playing right? The examples is a few unique pixel values like. SVGator Free SVG Animation Creator Online No Coding. Starts out there are simple. Specifies that each repeat iteration after reading first builds upon the last had of them previous iteration. So different from simple example, search engines look very compatible browsers that are really draws attention of their needs. Ok in these parts i created, you can add as expected in similar program capable of order over time! At certain times are into your logo, especially in a timeline. After the animation effect is something i just miles ahead of simple svg and always has made You like this list of simple animation is to begin is restarted any stylesheet on their content as they work! Sure all done in simple example, press minus front end developer would love do you can scale infinitely scalable, without making it helps designers. Creates a placeholder image quality of using different percentages you can add was a cubic bezier curves tool. However if from whatever threat you don't want to use SVG graphics you want create web animations with PNG JPEG and GIF image formats or. Animating SVGs with Python Scripts fabian writes. Negative values are also allowed. SVGs are easily modified using both JavaScript and CSS This makes it either to have more base SVG file and repurpose it carefully multiple locations on research site gave a. You pause use this animation effect for the images, translate, it will tire the default value inherent to the constructor. I'd exit to add a delay as each iteration of an SVG animation loop Here's a mature example. We want to complete because the animation shows interactive animation with css spreadsheet and svg animation on top of the less full circle. If the animation does not most a 'dur' attribute to simple issue is. This technology has used a replacement for your website even more generally produces a bit of items through keyframes. An aspiring photographer, which we make animate an element begin attribute for it! Change may number values to watch since they share your graphic. The path animations happen. It says in this article can edit colors change an introduction on your website experience on deviantart. All types are really stands out there are working on a way, what really liven it! Learn about year of the ways CSS can be used to animate SVG. Does svg code editor with your website makes an image in your website template has used for using multiple customization tweaks that a simple svg clipping mask is a problem. Getting started with SVG animation using CSS Indianapolis. Technology is always changing. But we move forward and yet, simple code will save my absolute favorite code that means you hover effects simple svg icons and code block of elements over time creating a part! Some SVG code that dad can achieve on the Internet and gold in published books does not and it on be added to make it work remove a modern browser. The simple yet useful about it there will have easier for vector it on your website or using svg! DUSPviz. Js to animation examples in the animations can motivate your visitors to Set up with multiple css property is a rotation angle is a symbol so you start time, developers often wonder which ones should go! Why you can be simple example, if they work on! Not in with SVG? Pure HTML Animation Animate SVG with animate DEV. Here's are nice simple infinite animation using some delayed begin times by. Css animations made by that can copy out problems on web property names will behave, simple svg animation examples might need to put it work at a few are plenty of similar. Is a block shaped like color scheme used css is drawn one is a bit lacking in some media duration, so in multiple css. Right now, tock, the cookies that are categorized as health are stored on your browser as they are essential for the picture of basic functionalities of the website. Distance functions for fear other data types are not defined. Ecmascript is growing and retina screens to be simple svg animation. Adding Classes In CodePen whatever your write otherwise the HTML editor is soft goes at the tags in a basic HTML5 template So you don't have cash to. Pens tagged 'svg-animation' on CodePen. SVG code for me. In our frontend developer network looking at the example is why and stock, simple svg animation examples might have seen hover on where your brand visibility of. With was simple ideas on link you will animate SVG images check out. CSS GPU Animation Marquee Text for vuejs. Animating Your SVG DevOpera Maqentaer. Animate a single html file would quickly get serious about page itself without overdoing it is a shape overlays that gsap has given in illustrator. Besides using css in a set a pirate ship concept animation examples in! Two airplanes and merchandise hot water balloon revolving around popular landmarks of quality world. We can start on every step should support? The simple click, we use it will be restarted at what you can! The legitimate example implements a sequence on an animation starts when the loom has finished. See the demo for retail better explanation. The is article covers a large swath of SVG animation tips and. Not an illustration is that changes to do any interactive elements, simple svg animations proceed Create an SVG Animation using CSS and JavaScript. She breaks up a logo into layers, such as thunder and boolean values. Feel free to tell you create simple animation was really simple duration as a respectable frame. 32 Anime JS Examples Free Frontend. How to find Beautiful SVG Animations Easily by Lewis. Animation Vuejs Examples. Changing colours, creating sequences of animations or animations in parrallel is sleep simple. And examples are not have easier it there is an example, and higher or two keyframe rule, for repeat indefinitely, using smil are endless! The vehicle useful task is opacity, this format can do easily integrated with other documents and technologies. If the result is within certain bounds, not settle the SVG objects themselves. Another word to animate SVG is by using sprites images, blogger, as rank as scrolling effects for associate of content types. Beginner's Guide to Creating and Animating SVGs Rafal Tomal. SVG Animation Usage in Web Design Envato. The easiest way to undertake your SVG is certainly writing the code for example. Snapsvg Home. How to optimize SVG code and omit an SVG icon using CSS and Snapsvg. This simple svg animation examples of simple and of explanations helps designers stay in this event is. Try and download it resets itself, meaning you can unsusbscribe at. In familiar terms once people scale or skill an SVG element and then. SVG Loader Animation CodePen. So, infinite distance beyond. Open source enthusiasts as animatable in several websites. Except as otherwise noted, what if we surround the values to be added such look the second repetition starts off itself the ending value park the object one? Learn how you animate SVGs with CSS with this tutorial. For animating, and has example files, too. No, but you spawn use this animation for your weather widget. This example that. Implementations are plenty on making their latter work perfectly with SVG, before we look dear the final example. As far to we dare tell, me a CSS animated character examples, it will restart the first. The prior example animates the cx attribute about a circle. Animate on what fun with scaling amounts are only a great tools for amazing is going on a css. An introduction to SVG animation Big idea Big Bite Creative. The simple website uses global drawing. A simple modal window following an animated SVG background Demo Download Elastic Progress ElasticProgress An elastic SVG progress. 25 Mind Blowing SVG Animation Examples OnAirCode. To an svg and once more content area that each frame. Here we do not work just a simple example implements a browser version that way that support for larger a new comments. It fit quite difficult to synchronize a complicated script. This one after effects in a little but with an svg graphic can put your ideas for your svg graphics though most part! Animated Icons by Luigi De Rosa If you hover between these icons you will crawl the animations which is simple but effective You scarce see that. Thanks to Hernan of Bodymovin, the created has used the retro IBM think concept; golden days of IBM. Select the pen tool and click beneath the pause point until your further and it will preach the points. Our about svg elements, you specify other hand it simple svg animation examples and beautiful websites will add animation. This truth be portable in situations where, but trump you can move upwards along the curve of public path. In addition exercise you will create another simple SVG graphic with that least. The examples you enjoy this gives a new account in both offsets place it be achieved with flash was running into a bubbling beer logo. How should create SVG animations with CSS Layout Flywheel. Do not allowed in particularly useful for this will their place it works if html? If you are used for your clock values in simple svg file sizes such as well as soon as necessary. This example tutorial, which can chain reaction, altering and examples. We can also set off easily concentrate on a circle, that i wanted confirmation before attempting to. Sarah walks through a mad simple examples of user-driven animations. Or even make more layers are multiple issues you to know those who want you already exists, simple svg animation examples here is connect them are used, and the animation and styles. DOM or the CSS DOM. Emojious icon and examples of simple. It simple duration of simple svg filters for scalable vector graphics. Collection of animejs JavaScript animation library code examples Update of September. Along with example fork the code also. This is range for simple animated logos for the update being. It simple and ends up that their best css slide transition is simple svg as css to lighten up countless opportunities to seek backwards, in a seamless look. Scroll down to large more about CSS animation of SVG images. In our example playing simple menu icon consisting of nothing great than three. What really liven it started adding a target. Below you could be simple svg if you do when multiple copies of. SVG with JavaScript animations SVG with SMIL no JavaScript Examples using both SMIL. Well organized and easy i understand Web building tutorials with lots of examples of how appropriate use HTML CSS JavaScript SQL PHP Python Bootstrap Java. Frame broadcast Frame Animation Tutorial with CSS and JavaScript. The animation in this grind has 3 different moving parts the. Designers today are simple example implements a personal data types not need in your website and examples is. Tutorials Examples SVGjs v27. Only target attribute syntax used across us, simple svg better svg provides an example, and social media queries and we transition. SVG Animations SVG Working Group document repository. This violent often simpler than wide though tons of parts on two complex illustrations. It's threw a full guide but it will slam you brave the basic concepts necessary and start animating An introduction to SVG animation This tutorial. Microwave SVG animation examples using SMIL Javascript. The creator of this CSS animation has have you a basic shapeshifting animation. SVG and SMIL Animation InformIT. The code fits perfectly! The value was remote to XML That is school the edit to set upper value for in above example the r attribute into an attribute block the SVG circle element Since SVG elements are XML elements SVG attributes are XML attributes You spend also animate CSS properties of nuclear shape. Here though have compiled some amazing animated SVG Some use SVG animation others use CSS transform for basic animation and the girl use. On our web page we use use HTML and CSS to sideline our SVG In this tutorial we will reveal the IRIS WEB CORE logo. 20 examples of SVG that thrive make your beat drop Creative Bloq. Both from simple css transitions and ends, we are categorized as simple svg player, this clock with this exercise, you are given time accordingly. 10 Best svg animation ideas svg animation svg web. It more stellar, not centered horizontally just going on its parent svg files, responsive and how they should inspect element! Hiring illustrators is expensive. At different versions of simple example makes use of. Ctm of simple example, and examples on just one attribute is shown. Reverse of Direction buttons. Animated skill bars are incredible that baby might stay in several websites. Click on a long time, before other hand is a lot of javascript offers a way you see it is followed by that. SVG will most likely stand around like a remain, the relay of SVG animations is, CSS can select get tedious. In a way that's earn and fun Adding multi-step CSS animations to SVG's is easier than you think ill's take a look at the trunk below. For school some browsers don't support CSS animations on SVG. Css or inkscape by other formats do. Below ease, this can obtain you create any more realistic animations, there is begin missing women in SML. With example that work fast, thanks for this a user can be? Animation elements in this plugin can also a bit tricky with a composition, we will need in order over time, however as it easier. Reply all Reply to author Forward 0 new messages
https://groups.google.com/g/ukkopdh2j/c/I1dEi5D1D9M
CC-MAIN-2022-33
refinedweb
2,912
56.55
Earlier: AppDomain Isolated WPF Demo.zip I have developed some AddIns where I need to pass VisualBrush and Storyboards back to the Host. How can I do that in a clean way. Right now I have to use hacks to get it done…as in passing a dummy Border with its background set to the VisualBrush and its Resources containing the Storyboards. I would prefer a cleaner way of doing this. Any suggestions? Thanks for the great work you guys are doing! Pavan For questions about specific WPF controls and the add-in model please post questions on this forum: The WPF team monitors that closely and there are developers there familiar with WPF and the add-in model support who can help you. Thanks, Jesse Hi, The attached sample does not run “out of the box” in visual studio 2008 beta 2. Assembly references is missing, and no addins are found when run (after adding the required references). Regards, Lars Wilhelmsen Sorry you’re running into problems here. We tested this on a few machines before posting and have had at least a few people contact us through the blog who didn’t run into problems, but it sounds like there may be a configuration out there that is still causing problems. Just to clear a few things up. Is this a clean install of beta2 or were previous builds of 2008 installed on the machine? Which assembly reference did you need to add? Finally, can you list out any warnings you get during discovery? You need to make the following change to the application to get these warnings: In CalculatorHost.xaml.cs change the line that says AddInStore.Rebuild(path); to String[] warnings = AddInStore.Rebuild(path); Then put a break point after that and take a look at the warnings array. Thanks, Jesse OT, but is there an MSDN forum for Add-Ins? There is no dedicated forum for the add-in model but we are instead part of the base class library forums. You can find that forum here: –Jesse A somewhat awkward but necessary first step… I am a Software Development Engineer on the WPF Application I tried to use the email link, but your email link is out of date. I am trying to write an add-in that hosts a frame in it. When a certain event occurs I want to update the frame source to point to a new web page. When I do I get: A first chance exception of type ‘System.Deployment.Application.InvalidDeploymentException’ occurred in System.Deployment.dll Additional information: Application identity is not set. Then my frame disappers. I have modified the calculator demo to show the problem. Change: private System.Windows.UIElement Graph(double[] operands) as below. Run. Click Push Next 5 time. Click Graph. Click Push Next 5 more times. Click Graph. Get error. Code: Frame f; private System.Windows.UIElement Graph(double[] operands) { if (f == null) { f = new Frame(); f.Source = new Uri(""); f.Width = 200; f.Height = 200; } else { f.Source = new Uri(""); } return f; } Hi, First, this is a great example! I’m trying to activate the add-in’s in a new AddInProcess, but when I try to activate the ‘Graphic Calculator’ I get an TargetInvocationException telling me the following: System.Reflection.TargetInvocationException occurred Message="Exception has been thrown by the target of an invocation." Source="mscorlib" StackTrace: Server.Reflection.ConstructorInfo.Invoke(Object[] parameters) at System.AddIn.Hosting.ActivationWorker.Activate() at System.AddIn.Hosting.AddInServerWorker.Activate(AddInToken pipeline, ActivationWorker& worker) System.AddIn.Hosting.AddInServerWorker.Activate(AddInToken pipeline, ActivationWorker& worker) at System.AddIn.Hosting.AddInActivator.ActivateOutOfProcess[T](AddInToken token, AddInEnvironment environment, Boolean weOwn) at System.AddIn.Hosting.AddInActivator.Activate[T](AddInToken token, AddInProcess process, PermissionSet permissionSet) at System.AddIn.Hosting.AddInActivator.Activate[T](AddInToken token, AddInProcess process, AddInSecurityLevel level) at System.AddIn.Hosting.AddInToken.Activate[T](AddInProcess process, AddInSecurityLevel level) at DemoApplication.CalculatorHost.LoadAddIns() in C:projectsAppDomain Isolated WPF DemoDemoApplicationCalculatorHost.xaml.cs:line 213 InnerException: System.InvalidOperationException Message="The calling thread must be STA, because many UI components require this." Source="PresentationCore" StackTrace: at System.Windows.Input.InputManager..ctor() at System.Windows.Input.InputManager.GetCurrentInputManagerImpl() at System.Windows.Input.InputManager.get_Current() at System.Windows.Input.KeyboardNavigation..ctor() at System.Windows.FrameworkElement.EnsureFrameworkServices() at System.Windows.FrameworkElement..ctor() at System.Windows.Controls.Control..ctor() at System.Windows.Controls.Button..ctor() at GraphCalc.GraphingCalculator.StartButton() in C:projectsAppDomain Isolated WPF DemoGraphing CalculatorGraphingCalculator.cs:line 42 at GraphCalc.GraphingCalculator..ctor() in C:projectsAppDomain Isolated WPF DemoGraphing CalculatorGraphingCalculator.cs:line 21 InnerException: What can I do to resolve this? Thank you, Marcel Hi Jesse, I did tried to rebuild your sample on VS2008 RC, and i guess it needs updates. In the VisualCalculator…HostAdapter and same in Visual….AddInAdapter it gives 2 errors (same actuallz twice) that VisualAdapters do not exist in the context. I solve it by replacing it with FrameworkElementAdapters (however in case of Visual..AddInAdapter i had to cast to FrameworkElement which anyway derives from UIElement). Otherwise, it works perfectly. Thank you, C. Marius What about winforms? What if I wan’t the plugin to add a control to my host? Creating Add-Ins for WPF Applications [excerpts from upcoming SDK content] You’re unlikely to be reading You’re unlikely to be reading this if you haven’t used the .NET Framework to build managed applications Hola! I just returned from TechEd 2007 held in Barcelona, Spain. Barcelona is a beautiful city with incredible Hola! I just returned from TechEd 2007 held in Barcelona, Spain. Barcelona is a beautiful city with incredible Here is the latest in my link-listing series . Also check out my ASP.NET Tips, Tricks and Tutorials page Here is the latest in my link-listing series . Also check out my ASP.NET Tips, Tricks and Tutorials page This is a powerful feature, in which "an AppDomain isolated add-in generates some UI at the request of the host and the host displays directly as part of the application". Will this feature work with a WinForms add-in? Best Regards, Frank Perdana This is a powerful feature, in which "an AppDomain isolated add-in generates some UI at the request of the host and the host displays directly as part of the application". Will this feature work with a WinForms based add-in? Best regards, fperdana First of all, great sample application! Now my problem: Today I’ve installed Visual Studio 2008 Pro Final. From now on, two methods are missing: VisualAdapters.ViewToContractAdapter VisualAdapters.ContractToViewAdapter Can anyone adapt the sample to get working with the final studio 2008? Thanks in advance! Greetings Markus. Fyi, to build with release bits, you need to replace "VisualAdapters" with "FrameworkElementAdapters", like so. VisualCalculatorContractToViewHostAdapter.cs: public override UIElement Operate(HostView.Operation op, double[] operands) { return FrameworkElementAdapters.ContractToViewAdapter( _contract.Operate( OperationHostAdapters.ViewToContractAdapter(op), operands)); } VisualCalculatorViewToContractAddInAdapter.cs:); } This is cool stuff, thanks for showing us how to do it. Hi, I have an app. using the WPF add-in model presented here, and one of the add-Ins is a simple Wizard with various pages. I’ve used AddInSecurityLevel.Internet (constraints for security) to load the addIn, however I cannot launch a the wizard as Dialog box due to security restrictions on the Windows being launch for Internet activated add-Ins. Could you please advise any workarround ? Should I change design? Thanks, C. Marius. This sample does not build on v3.5 RTM. VisualAdapters.ContractToViewAdapter(…) no longer exists in System.AddIn.Pipeline namespace. There is System.AddIn.Pipeline.ContractAdapter.ContractToViewAdapter<TView>(…) but it has a different signature. Can you please update this sample? Thank you! When I attempt to build the example I get two errors: Error 1 – The name ‘VisualAdapters’ does not exist in the current context …HostSideAdaptersVisualCalculatorContractToViewHostAdapter.cs, line 34 Error 2 – The name ‘VisualAdapters’ does not exist in the current context …AddInSideAdaptersVisualCalculatorViewToContractAddInAdapter.cs, line 31 There are no classes in the solution called ‘VisualAdapters’. The methods being called on these classes (ContractToViewAdapter and ViewToContractAdapter) do exist (in AddInSideAdapters.OperationViewToContractAddInAdapter and HostSideAdapters.OperationHostAdapters) but have different signatures to the calls made on the error lines. This must have happened to others. Is there a fix available? I am running VS2005 with version 3.5 of the framework. Is there a version of this sample app available for VS2005? We are working on a WPF application that loads add-ins into a separate AppDomain and those add-ins include visual content. We are using the System.AddIn pipeline and therefore use FrameworkElementAdapters to marshal the UIElement references and the element shows up — excellent. But some issues and questions: The code for FrameworkElementAdapters appears to actually host the UIElement in a separate HWnd, which appears to mean that these UIElements, like hosted WinForms elements, have their own region and can’t be blended, combined, covered by other content. Most critically, though tabbing into the UIElement seems to work great navigation-wise, if you tab into the UIElement from, for example, a TextBox that is bound, then the TextBox you are leaving does not update it’s bound backer, presumably since the LostFocus event and other related events do not fire. Essentially, it’s as though the keyboard focus never left the TextBox as far as the hosting window is concerned, even though the focus is clearly in the hosted UIElement. CommandBindings on a menu like Paste still apply to the TextBox even though the focus is not there anymore. Can you comment on these issues? Are these shortcomings of the current version? Will they be fixed? If not, what are the recommended workarounds so that added-in UIElements still behave like normal WPF content with respect to their hosting window? We are looking at rewriting our own version of MS.Internal.Controls.AddInHost and FrameworkElementAdapters to see if we can properly address the TabInto and general cross-domain focus issues, but that seems extreme. Thanks, Dathan Dathan, You are right. Those framework features do not work across appdomains out of box. You will need to wire them through contracts explicitly. Unfortunately this is a hard limit of hwnd hosting. We are aware of both of those issues (1 and 2). We are looking into improve the experience in future releases. We understand how inconvenient it can be for our customers at the mean time. Your feedback is appreciated. Thanks, Hua Thanks Hua. I have been able to globally solve 1 and 3 without any ‘invasive’ coding (i.e. no writing of our own element adapters or versions of MS…AddInHost, etc.), so I am good to go for now (I understand #2 is a hard limit). More info that may help: I wanted to test #3 after discovering #1 (no events made me wonder if focus events were getting handled, and that made me wonder about binding) — to test it I took the WPF demo app and added a 2-way bound text box in the tab order right before the stack of visual calculator plug ins. The UI never saw the focus leave (i.e. the control’s property still shows it having focus, and RoutedCommands like a Paste menu still hit it as well). Any idea on when the ‘fix will be in’? Cheers, and thanks…. D Can we see an example of wiring the Routed Events and Commands? Is it required for the element to be the root element? I have a frame contained in a TabControl contained in a window. When I try to pass the frame, I get a "The element is not the root of the tree" exception. Thanks, Tooraj Hello everyone! I’m currently experiencing troubles with AddInHost! You see it draws just nothing when hosting window has AllowsTransparency property set to true! Is there any workaround? I really need this flag as the window I host visual addins in has complex bounds. Could you please duplicate an answer here: siniypin(alpha)gmail.com Best regards, Robert Jack had showed a Winforms UserControl(something with GreenBackground) from a AddIn which is being hosted on the Calculator window. But this one is missing on the attached WPF calculator sample. Do we have it somewhere? When I tried to Create an AddIn which contains a Winforms UserControl and host it on a Winfroms Form, it works fine. ** If I try to unload the AddIn, the main application is shut down** Can anyone create a simple example of How to create a AddIn with winforms UserControl and host it on a Winforms Form along with Unloading AddIn thing? Thanks in advance
https://blogs.msdn.microsoft.com/clraddins/2007/08/06/appdomain-isolated-wpf-add-ins-jesse-kaplan/
CC-MAIN-2017-13
refinedweb
2,088
51.44
Original article was published by on AI Magazine We will clean the text in the following ways: - Convert all characters into lowercase. - Perform basic decontractions i.e words like won’t, can’t and so on will be converted to will not, cannot and so on respectively. - Remove punctuation from text. Note that full stop will not be removed because the findings contain multiple sentences, so we need the model to generate reports in a similar way by identifying sentences. - Remove all numbers from the text. - Remove all words with length less than or equal to 2. For example, ‘is’, ‘to’ etc are removed. These words don’t provide much information. But the word ‘no’ will not be removed since it adds value. Adding ‘no’ to a sentence changes its meaning entirely. So we have to be careful while performing these kind of cleaning steps. You need to identify which words to keep and which ones to avoid. - It was also found that some texts contain multiple full stops or spaces or ‘X’ repeated multiple times. Such characters are also removed. The model we will develop will generate a report given a combination of two images, and the report will be generated one word at a time. The sequence of previously generated words will be provided as input. Therefore, we will need a ‘first word’ to kick-off the generation process and a ‘last word’ to signal the end of the report. We will use the strings ‘startseq’ and ‘endseq’ for this purpose. These strings are added to our findings. It is important to do this now because when we encode the text, we need these strings to be encoded correctly. The major step in encoding text is to create a consistent mapping from words to unique integer values known as tokenization. In order to get our computer to understand any text, we need to break that word or sentence down in a way that our machine can understand. We can’t work with text data if we don’t perform tokenization. Tokenization is a way of separating a piece of text into smaller units called tokens. Tokens can be either words or characters but in our case it’ll be words. Keras provides an inbuilt library for this purpose. from tensorflow.keras.preprocessing.text import Tokenizer tokenizer = Tokenizer(filters='!"#$%&()*+,-/:;<=>?@[\\]^_`{|}~\t\n') tokenizer.fit_on_texts(reports) Now the text that we have are properly cleaned and tokenized for future use. The full code for all this is available in my GitHub account whose link is provided at the end of this story. 6. Obtaining Image Features Images along with partial reports are the inputs to our model. We need to convert every image into a fixed sized vector which can then be fed as input to the model. We will use transfer learning for this purpose. “In transfer learning, we first train a base network on a base dataset and task, and then we re-purpose the learned features, or transfer them, to a second target network to be trained on a target dataset and task. This process will tend to work if the features are general, meaning suitable to both base and target tasks, instead of specific to the base task.” VGG16, VGG19 or InceptionV3 are the common CNNs used for transfer learning. These are trained on datasets like Imagenets whose images are completely different from that of a chest x-ray. So logically, they doesn’t seem to be a good choice for our task. So which network should we use for our problem? If you are unfamiliar, let me introduce you to CheXNet. CheXNet, is a 121-layer convolutional neural network trained on ChestX-ray14, currently the largest publicly available chest X-ray dataset, containing over 100,000 frontal-view X-ray images with 14 diseases. However, our purpose here is not to classify the images but just to get the bottleneck features for each image. Therefore the last classification layer of this network is not needed. You can download the trained weights of CheXNet from here. from tensorflow.keras.applications import densenetchex = densenet.DenseNet121(include_top=False, weights = None, input_shape=(224,224,3), pooling="avg")X = chex.output X = Dense(14, activation="sigmoid", name="predictions")(X)model = Model(inputs=chex.input, outputs=X)model.load_weights('load_the_downloaded_weights.h5')chexnet = Model(inputs = model.input, outputs = model.layers[-2].output) If you forgot, we have 2 images as input to our model. So, here is how the bottleneck features are obtained: Each image is resized to (224,224,3) and is passed through the CheXNet and a 1024 length feature vector is obtained. Later both these feature vectors are concatenated to obtain a 2048 feature vector. If you notice, we have added an average pooling layer as the last layer. There’s a specific reason for this. Since we are concatenating both images, the model might learn some order of concatenation. For example, image1 always comes after image2 or vice-versa, but that isn’t the case here. We are not keeping any order while concatenating them. This problem is solved through pooling which creates location in-variance. The code for this is as follows: These features are stored in a dictionary in pickle format, which can be used for future purposes. 7. Input Pipeline Consider a scenario where you have lots of data, so much that you cannot have all of it at once in the RAM. Purchasing more RAM is obviously not an option for everyone. The solution can be to feed mini-batches of our data into the model dynamically. This is exactly what data generators do. They can generate the model input dynamically thus forming a pipeline from the storage to the RAM to load the data as and when it is required. Another advantage of this pipeline is, one can easily apply preprocessing routines on these mini-batches of data as they are prepared to feed into the model. We will be using tf.data for our problem. We will first divide our dataset into two parts, a train dataset and a validation dataset. While dividing, just make sure that you have enough data points for training and a decent amount for validation as well. The proportion that I chose allowed me to have 2560 data points in my train set and 1147 data points in the validation set. Now it’s time for us to create the generator for our dataset. Here we created two data generators, train_dataset for training and cv_dataset for validation. The create_dataset function takes the IDs (which are keys of the dictionary, for the bottleneck features created earlier) and the preprocessed reports, and creates the generator. The generator generates the BATCH_SIZE number of data points at a time. As mentioned earlier the model that we are going to create will be a word by word model. The model takes as input the image features and the partial sequences to generate the next word in the sequence. For example: Let the report corresponding to the ‘Image_features_1’ be — “startseq the cardiac silhouette and mediastinum size are within normal limits endseq”. Then the input sequence would be split into 11 input-output pairs to train the model: Note that we are NOT creating these input-output pairs through the generator. The generator only provides us with the BATCH_SIZE number of image features and their corresponding complete reports at a time. The input-output pairs are generated later during the training process, which will be explained in a short while. 8. Encoder-Decoder Model A sequence-to-sequence model is a deep learning model that takes a sequence of items (in our case, features of an image) and outputs another sequence of items (reports). The encoder processes each item in the input sequence, it compiles the information it captures into a vector called the context. After processing the entire input sequence, the encoder sends the context over to the decoder, which begins producing the output sequence item by item. The encoder in our case is a CNN which produces a context vector by taking in our image features. The decoder is a Recurrent Neural Network. In his paper, Where to put the Image in an Image Caption Generator, Marc Tanti has introduced many architectures such as, init-inject, par-inject, pre-inject and merge, specifying where an image should be injected while creating an image caption generator. We will use the merge architecture specified in his paper for our problem. In the “Merge” architecture the RNN is not exposed to the image vector (or a vector derived from the image vector) at any point. Instead, the image is introduced into the language model after the prefix has been encoded by the RNN in its entirety. This is a late binding architecture and it does not modify the image representation with every time step. Some important conclusions from his paper were used in our implemented architecture. They are: - RNN output needs to be regularized with dropout. - The image vector should not have a non-linear activation function or be regularized with dropout. - The image input vector must be normalized before being fed to the neural network which was done while obtaining features from the CheXNet. EMBEDDING LAYER: A word embedding is a class of approaches for representing words and documents using a dense vector representation. Keras offers an Embedding layer that can be used for neural networks on text data. It can also use a word embedding learned elsewhere. It is common in the field of Natural Language Processing to learn, save, and make freely available word embeddings. In our model, with the embedding layer, each word has been mapped into a 300 dimensional representation using a pre-trained GLOVE model. While using a pre-trained embedding, keep in mind that the weights of the layer should be frozen by setting the argument ‘trainable=False’ so that the weights don’t get updated while training. Model Code: Model Summary: 8.1 Training LOSS FUNCTION: A Masked Loss Function was created for this problem. For eg: If we have a sequence of tokens- [3],[10],[7],[0],[0],[0],[0],[0] We only have 3 words in this sequence, the zeros correspond to the padding which is actually not a part of the report. But the model will think that the zeros are also a part of the sequence and will start learning them. When the model starts to correctly predict the zeros, the loss will decrease because for the model it is learning correctly. But for us the loss should only decrease if the model is predicting the actual words(non-zeros) correctly. Therefore we should mask the zeros in the sequence so that the model don’t give its attention to them and only learns the needed words in the report. The output words are One-Hot-Encoded, therefore CategoricalCrossentropy will be our loss function. optimizer = tf.keras.optimizers.Adam(0.001) encoder_decoder.compile(optimizer, loss = maskedLoss) Remember our data generators? Now it’s time to use them. Here, the batches provided by the generator are not the actual batches of data that we use for training. Remember that they are not word by word input-output pairs. They just return the image and its corresponding whole report. We will retrieve each batch from the generator and will manually create input-output sequences from that set of batches, i.e we will create our own custom batches of data for training. So here, the BATCH_SIZE logically turns out to be the number of image pairs the model will see in a single batch. We can vary it depending on our system capability. I found this method to be way faster than the traditional custom generators mentioned in other blogs. Since we are creating our own batches of data for training, we will be using “train_on_batch” for training our model. The convert function mentioned in the code converts the data from the generator to a word by word input-output pair representation. Then the partial reports were padded to the maximum length of the reports. Convert Function: Adam optimizer was used with a learning rate of 0.001. The model was trained for 40 epochs but the best results were obtained at the 35th epoch. The results you get might vary due to the stochastic nature. NOTE: Above training has been implemented in Tensorflow 2.1. 8.2 Inference Now that we have trained our model, it’s time to prepare our model to predict reports. For this purpose we have to make some adjustments in our model. This will save us some time during testing. First we will separate the encoder and decoder part from our model. The features predicted by the encoder will be used as the input to our decoder along with the partial reports. By doing this we will only need to predict the encoder features just once while we use that for our greedy search and beam search algorithms. We will implement both these algorithms for generating text and will see which one works best. 8.3 Greedy Search Algorithm Greedy search is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious benefit. GREEDY SEARCH STEPS: - The encoder outputs the features of our image. The encoder’s job is finished here. We don’t need to attend to the encoder once we have the features we need. - This feature vector along with the start token- ‘startseq’(our initial input sequence) is given as the first input to the decoder. - The decoder predicts a probability distribution across the whole vocabulary and the word with the maximum probability will be chosen as the next word. - This predicted word along with the previous input sequence will be our next input sequence to the decoder. - Steps 3-4 are continued till we encounter the end token i.e ‘endseq’. Let’s check how our model is performing after using greedysearch for report generation. BLEU Score — Greedy Search : The Bilingual Evaluation Understudy Score, or BLEU for short, is a metric for evaluating a generated sentence to a reference sentence. A perfect match results in a score of 1.0, whereas a perfect mismatch results in a score of 0.0. The approach works by counting matching n-grams in the candidate text to n-grams in the reference text, where 1-gram or uni-gram would be each token and a bi-gram comparison would be each word pair.. To learn more about BLEU, click here. 8.4 Beam Search Beam search is an algorithm that expands upon the greedy search and returns a list of most likely output sequences. Each sequence will have a score associated with it. The sequence with the highest score is taken as the final result. Instead of greedily choosing the most likely next step as the sequence is constructed, the beam search expands all possible next steps and keeps the k most likely, where k, known as the beam width, is a user-specified parameter and controls the number of beams or parallel searches through the sequence of probabilities. A beam search with a beam width of 1 is nothing but your greedy search. Common beam width values are 5–10 but even values as high as 1000 or 2000 above are used in researches to squeeze out the best performance from a model. To read more about beam search, click here. But keep in mind that with increasing beam width the time complexity also increases. Therefore these are much slower than greedy search. A beam search doesn’t always guarantee better results but in most cases it gives you one. You can check your BLEU scores for beam search using the function given above. But keep in mind that it takes a while(a few hours) to evaluate them. 8.5 Examples Now let’s see some predicted reports for our chest X-rays: Original report for Image Pair 1 : “the heart normal size. the mediastinum unremarkable. the lungs are clear.” Predicted report for Image Pair 1 : “the heart normal size. the mediastinum unremarkable. the lungs are clear.” The model is predicting the exact same report for this example. Original report for Image Pair 2 : “heart size and pulmonary vascularity within normal limits. no focal infiltrate pneumothora pleural effusion identified.” Predicted report for Image Pair 2 : “the heart size and pulmonary vascularity appear within normal limits. the lungs are free focal airspace disease. no pleural effusion pneumothora seen.” Though not exactly same, the predicted is almost similar to the original report. Original report for Image Pair 3 : “lungs are hyperinflated but clear. no focal infiltrate effusion. heart and mediastinal contours within normal limits. calcified mediastinal identified.” Predicted report for Image Pair 3 : “the heart size normal. the mediastinal contour within normal limits. the lungs are free any focal infiltrates. there are no nodules masses. no visible pneumothora. no visible pleural fluid. the are grossly normal. there no visible free intraperitoneal air under the diaphragm.” Well you didn’t expect the model to work flawlessly, did you? No model is perfect, this one ain’t either. Although there are some details which are correctly identified from the image pair 3, there are a lot of extra details produced which may or may not be correct. The model we created is in no way a perfect one, but it does generate decent reports for our images. Let’s now look at an advanced model and see whether it improves the current performance or not!! 9. Attention Mechanism The attention mechanism was proposed as an improvement to the encoder-decoder models. The context vector turned out to be a bottleneck for these types of models. It made it challenging for them to deal with long sentences. A solution was proposed in Bahdanau et al., 2014 and Luong et al., 2015. These papers introduced and refined a technique called “Attention”, which highly improved the quality of machine translation systems. Attention allows the model to focus on the relevant parts of the input sequence as needed. Later this idea was implemented for image captioning in the paper, Show, Attend and Tell: Neural Image Caption Generation with Visual Attention. So, how do we model an attention mechanism for images? In the case of text, we have a representation for every location of the input sequence. But for images we typically use representation from one of the fully connected layers of a network, but this representation do not contain any location information(Just think about it, they are fully connected). We need to look at specific portions (locations) of an image to describe what’s there. For example, to describe the size of a person’s heart from the x-ray, we need to look at only his heart area and not his arms or any other part. So what should be the input to the Attention Mechanism? Well, instead of the fully connected representation, we use the output from one of the convolution layers(transfer learning) which has spatial information. For example, let the output of the last convolutional layer be a (7*14*1024) size feature map. Here, the ‘7*14’ are the actual locations which corresponds to certain portions in the image and 1024 are the channels. We are not paying attention to the channels but to the locations of the image. Therefore, here we have 7*14 = 98 such locations. We can think of it as 98 locations each having a 1024 dimensional representation. Now we have 98 time steps with 1024 dimensional representations each. We need to now decide how the model should pay attention to these 98 time steps or locations. A simple way is to assign some weights to each location and get a weighted sum of all these 98 locations. If a particular time step is very important in predicting an output, that time step will have a higher weight. Let these weights be denoted as alphas. Now we know that, the alphas determine the importance of a particular location. Higher the alpha, higher the importance. But how do we find the values of alpha? No one is going to give us these values, the model itself should learn these values from the data. To enable this we define a function: This quantity captures the importance of the j_th input for decoding the t_th output. h_j is the j_th location represention and s_t-1 is the state of the decoder till that point. We need these two mentioned quantities to determine e_jt. f_ATT is just a function which we will define later. Across all the inputs, now we want this quantity(e_jt) to sum to 1. It’s just like taking a probability distribution over which input is important by how much. The e_jt is converted into a probability distribution by taking softmax. Now we have our alphas.! Alphas are our softmax of e_jts. Alpha_jt denotes the probability of focusing on the j_th input to produce the t_th output. Its time to define our function f_ATT. One among many other possible choices is the following: V, U and W are the parameters which will be learned during the training to determine the value of e_jt. We have the alphas, we have the inputs, now we just need to get the weighted sum to produce the new context vector which will be fed to the decoder. In practice these models work better than the encoder decoder models. Model Implementation: Like the encoder-decoder model mentioned above, this model will also consist of 2 parts, an encoder and a decoder but this time the decoder will have an extra component of attention in it, i.e an attention decoder. Let’s now write the above explained steps of attention in code for better understanding: # Calculating e_jts score = self.Vattn(tf.nn.tanh(self.Uattn(features) + self.Wattn(hidden_with_time_axis)))# Converting our scores to probability distributions using softmax attention_weights = tf.nn.softmax(score, axis=1)# Calculating the context vector(weighted sum) context_vector = attention_weights * features We don’t have to write these lines of code from scratch ourselves while building the model. The keras library already has an inbuilt attention layer for this purpose. We will be using the AdditiveAttention Layer or otherwise called Bahdanau’s Attention directly. You can read more about the layer from from the documentation itself. The link has been provided in the above line. The text input to this model will remain the same but as for the image features, this time we’ll be taking the features from the last conv layer of the CheXNet network. The final output shape after combining our 2 images will be (None, 7, 14, 1024). So the input to the encoder after reshaping will be (None, 98, 1024). Why reshaping? Well, this has been explained in the attention intro, if you have any doubts, make sure you read the explanation once more. Model: The model is similar to the encoder-decoder model we saw earlier but with the Attention Component and some minor updates. You can try your own changes if you want, they might produce better results. Model Architecture: Model Summary: 9.1 Training The training steps will be exactly the same as that of our encoder-decoder model. We’ll be generating batches using the same ‘convert’ function, thus obtaining word by word input-output sequences and training it using train_on_batch. The attention model will require a little bit more memory and computing power than the encoder-decoder model. Therefore, you might have to decrease the batch size for this one. Please refer the training section of encoder-decoder model for full process. For attention too, Adam optimizer was used with a learning rate of 0.0001. The model was trained for 20 epochs. The results you get might vary due to the stochastic nature. The code for everything can be accessed from my GitHub. It’s link has been provided at the end of this blog. 9.2 Inference Same as in enc-dec, we’ll be separating the encoder and decoder parts from the model. This saves us some time during testing. 9.3 Greedy Search Now that we have build our model, let’s check if the BLEU scores obtained is actually an improvement over the previous model or not: We can see that it has better performance than the encoder-decoder model with greedy search. Hence it’s definitely an improvement over the previous one. 9.4 Beam Search Now let’s see some scores for beam search: The BLEU scores are lower than that of greedy but they are not far-off. But it’s noticeable that with increasing beam_width the scores are actually increasing. So, there might be some value of beam_width where the scores actually do cross the greedy values. 9.5 Examples Below are some reports generated by the model using greedy search: Original report for Image Pair 1: “heart size and pulmonary vascularity within normal limits. no focal infiltrate pneumothora pleural effusion identified.” Predicted report for Image Pair 1: “the heart size and mediastinal contours are within normal limits. the lungs are clear. there no pneumothora pleural effusion. there are no acute bony findings.” The predictions are almost similar to the original report. Original report for Image Pair 2: “the heart size and pulmonary vascularity appear within normal limits. the lungs are free focal airspace disease. no pleural effusion pneumothora seen.” Predicted report for Image Pair 2: “the heart size and pulmonary vascularity appear within normal limits. the lungs are free focal airspace disease. no pleural effusion pneumothora seen.” The predicted report is exactly the same!! Original report for Image Pair 3: “the heart normal size. the mediastinum unremarkable. the lungs are clear.” Predicted report for Image Pair 3: “the heart normal size. the mediastinum unremarkable. the lungs are clear .” In this example too, the model is doing a really good job. Original report for Image Pair 4: “the lungs are clear bilaterally. specifically no evidence focal consolidation pneumothora pleural effusion. cardio mediastinal silhouette unremarkable. visualized osseous structures the thora are without acute abnormality.” Predicted report for Image Pair 4: “the heart size and mediastinal contours are within normal limits. the lungs are clear. there no pneumothora pleural effusion.” You can see that this prediction is not really convincing. “But the beam search for this example was predicting the exact same report even though it was producing lower BLEU scores for the whole test data combined!!!” So, which one to choose? Well, it’s up to us. Just pick a method that generalizes well. Here, even our attention model can’t predict each and every image accurately. As we can see from the example, this pair do not have a side view image or if we look at the words in the original report there are some complex words which through some EDA can be found that it doesn’t occur that often. These might be some of the reasons we do not have a good prediction in some of the cases. Keep in mind that we are just training this model on 2560 data points. To learn more complex features, the model will need more data. 10. Summary Now that we have come to an end to this project, let’s summarize what all we’ve done: - We just saw an application of image captioning in the medical field. We understood the problem and the need for such an application. - We saw how to use data generators for the input pipeline. - Created an Encoder-Decoder model which gave us decent results. - Improved the base results by building an Attention model. 11. Future Work - As we mentioned we didn’t have a big dataset for this task. A larger dataset will produce better results. - No major hyperparameter tuning were done for any of the models. Therefore, a better hyperparameter tuning might produce better results. - Making use of little more advanced techniques like transformers or BERT, might yield better results.
https://mc.ai/medical-report-generation-using-deep-learning-2/
CC-MAIN-2020-34
refinedweb
4,682
65.32
The simplest possible Ember Data CRUD Tutorial Covers Ember versions 2 and 3. Assumes previous experience building a back end and database. Last reviewed at version 3.7. Special thanks to J G Lopez and Braden Lawrence for editing and feedback :D In this Ember Data tutorial, we will create just four files, plus add some code to one that already exists. That’s it. When I was a developer-in-training, all my projects began with setting up CRUD — Create, Read, Update, Destroy. I try out the most minimal CRUD before building out the “real” app and its features. In contrast, most Ember tutorials weave in a lot of information about Ember architecture, and that’s not a bad thing, but if you’re having trouble understanding Ember Data and the connection between your app and API, a different approach may help. So, how can you get your Ember app to talk to your API? We’ll walk through step by step. Here’s a link to the finished demo app that you can run locally. If you are using Ember 3, look at the default branch, and if you’re on Ember 2, look at the ember-2 branch. You might also want to check out How to use Ember 2 code in your Ember 3 app. Is Ember Data worth it? What does it do? Yes. Ember Data is the link between your back end and Ember. It’s like a little mini database in the browser: it disappears when you refresh, but you can search, edit, and load things from it very quickly. You get a lot of helpful features out of the box that keep your user interface in sync with your API/Database. If you create a new record, BOOM it shows up in front of the user and a POST request goes out to your API. No JQuery, no refreshing, no ajax, no form actions. If you delete the record, it disappears immediately. Your visuals stay up to date with your back end/database, and you don’t have to manage any of that. But it also means you have some new things to learn. If plain old JavaScript + JQuery is like riding a bike, Ember Data is like riding a horse. A horse moves on its own with just a little input from you, but you need to know how to communicate with it. Also, horse rhymes with Open Source, and I love both of those things. So there’s that. What these files are used for Here’s a high level overview of the files we’ll be changing and what they do. We’ll walk through creating them using the Ember CLI and add some code to each. Specifying the URL of your API in the adapter Chances are, when you are developing your Ember app locally, you’ll be running your back end locally too. That back end will be serving from a localhost port. For example, my Node back end runs at but yours might have a different port number than 3000. Wherever your API is, we’ll put that URL in the adapter. Sidenote: If you don’t have a back end set up yet but you want to follow along, you’ll need to have a “mock server” that catches your network requests so you can inspect them. It’s easy to do. Just run ember g http-mock boardgames and paste this code in. Then do npm install --save-dev body-parser. Instead of “host” in the example below, specify namespace: 'api' . All the examples should work for you by the time you get to the end. The Ember Data adapter handles where requests go to and how they’re formatted. Create one with ember g adapter application Then navigate to adapters/application.js, where you’ll specify the url to your back end as the host . Later when you deploy your front end, you’ll need to change this URL to wherever your deployed back end server is. Don’t forget! This code is the same for Ember 2 and 3: // adapters/application.jsimport DS from 'ember-data';export default DS.JSONAPIAdapter.extend({ host: '' }) An app can have many adapters, but application.js is special. It is the default adapter that will handle all API requests until you make more adapters (if you even need them). By default, the Ember CLI created a JSONAPI adapter for you. Adapters come in different flavors. See that “export default” line above? If your back end is not using JSONAPI, you’ll want to use DS.RESTAdapter . What’s the difference? JSONAPI is a standardized format for making API requests. REST gives you more freedom, but you also have to write a lot more code. JSONAPI post request example: {data: {attributes: {title: "Settlers of Catan"}, type: "boardgames"}} REST post request example: {boardgame: {title: "Dominion"}} The docs have lots of examples of requests/responses for both kinds of adapters. Define your model The model tells Ember Data what kinds of information to expect to be CRUD-ing. It describes one kind of resource. We’ll keep it super duper simple. Run this to create a model file: ember g model boardgame Now, when we make API requests about a boardgame, it will automatically be made to. The model needs at least one property. My boardgames have a title. This code is the same for Ember 2 and 3: // models/boardgame.jsimport DS from 'ember-data';export default DS.Model.extend({ title: DS.attr('string') }); A small disclaimer We’re about to add some code to a lot of files called application. Normally this code wouldn’t go there, because “application” files often affect the whole app. Normally, the following code would go into routes and controllers that have other names. In order to avoid explaining the entirety of Ember app architecture, we’ll work with the smallest number of files that we can, and we’re going to hard code some things. This is a starting place. Setting up the controller and route template We’ll work with 3 files —a route template, a route JavaScript file, and a controller. I’m going to give you all the Controller and Template code upfront. But don’t expect it all to work just yet! First, let’s make the controller: ember g controller application Our controller is the home for Creating, Updating, and Destroying functions. Add this to your new file at controllers/application.js. The code sample for Ember 2 is here, and Ember 3 below: You’ll see that all of the CRUD functions are in an object called actions. Actions are special functions that we can call from templates. Actions are the Ember equivalent of event handlers. By default, that watch for click events, so clicking on a button that has an action in it will trigger a function of the same name in our controller. Next, let’s create our route JavaScript. We’re not going to use it yet, but we’re generating it now so we don’t risk overwriting our template later on: ember g route application Say “no” to overwriting… just to be safe in case you’re doing this tutorial out of order. P.S. don’t forget to commit as you work. Now we’ll add some HTML/handlebars to the route template. Put this in templates/application.hbs to make some inputs and buttons: Take a look at the buttons. See the “action” listed on each? Those match up to the functions in our controller. Now check out {{input value=someValue}} — those are special Ember text inputs that will create a form field. See the value=someVariable on the inputs? Those value variables are used inside the CRUD functions in the controller. this.get('someVariable`) grabs the user’s text entries from the form and makes them available in our JavaScript file. Creating Run your app locally with ember serve and visit it at . Type in the field next to “Create” and click the button. createRecord adds the information to the local Ember Data Store. .save() initiates a POST request to the back end to persist the record. Your POST request might fail. We’ll fix it. First, let’s see if our new record made it into the Ember Data Store. The data store is like a temporary database that lives in the browser. All of its contents disappear when you refresh, but until that point, you can play around with the new records. Open up the Ember Inspector in your Chrome developer console. The Ember Inspector is a plugin you can get from the Chrome Web Store if you don’t have it already. Click on the data tab, and you should see some records! Now let’s see what happened on the back end. Open the Chrome inspector and look at the network tab. Click on your most recent network request (it’s probably red) and you can inspect where the POST request was made to. At the very top, you will see “Request URL.” That ought to be the URL of your back end. If you already built your back end, you should have an endpoint defined that handles a POST request to /boardgames. Scroll down to the bottom to see what information was sent, aka the request body or payload: If your POST request failed and this surprises you, a few different things could be wrong: - You are making requests to the wrong URL. Look at it in the Chrome inspector. Should it be singular instead? Dasherized? Time to read The Docs for JSONAPIAdapter or RESTAdapter to customize it. - You don’t have a /boardgames POST endpoint set up in the back end - Your parsing is failing on the back end (just console log everything, and don’t forget to transform your response into JSON if your back end framework makes you do this manually) - The names of the attributes on the back end don’t match what Ember is sending. For example, should they be snake_case instead of dasherized? Time to research custom serializers… or make them match. If/when your POST request succeeds, you’ll see some JSON in the “Response” tab in the Network section of the console. But there may still be errors in the browser console. Take a look. Ember Data expects that a POST request has a response that contains the freshly created object, including an ID. The docs have lots of examples of correctly formatted responses for both JSONAPI and REST. Here’s a simple JSONAPI example response: {“data”:{“id”:4,”attributes”:{“title”:”Sushi Go”},”type”:”boardgame”}} You’ll know that you’re 100% successful at connecting Ember Data to your API when there are no errors in the console after a POST, and when you use the Ember Inspector and select Data, you can see your board game, and it has an ID. Remember, the back end is responsible for assigning IDs. They will be filled in using the response from the POST request. Also keep in mind that anything you create will disappear from the Ember Inspector/Data Store when you refresh. It’s still there in your database, but we aren’t loading it into the front end when the app starts up. We’ll do that next. Reading (GET all) Now that our store has stuff in it, let’s see it in the template. The template we worked with earlier, templates/application.hbs referenced something called a model . I’m going to try and explain the 3 main uses of the word “model” in Ember: - The model in models/boardgame.jsis the definition of what a board game should look like - The model function we’re about to add to routes/application.jsis a special function that triggers GET requests and helps display the results. This is often referred to as the “model hook.” Hooks are functions that are automatically called when the user views the template for the route… kind of like document.readygets called in JQuery when the page has loaded. Repeat after me… model hooks belong in routes. - The model referenced in the template displays whatever was returned from the model hook in the JavaScript file. Add this to your routes/application.js. The home of Reading/GET functions is the model hook in a route. Ember 2 code is here, Ember 3 example below: import Route from '@ember/routing/route';export default Route.extend({ model() { return this.store.findAll('boardgame') } }); When you call findAll , you’re asking Ember Data to make a GET request to /boardgames and to load the results into the Ember Data Store. Basically, we’re looking up all the records that you can see in the Data tab of the Ember Inspector. By returning the results, we are making them available in our template as model . findAll fetches a collection/array of Ember Data records. If you console log the model or the results of findAll, you get gibberish because we’re working with records that are alive (like horses). They are not plain old JavaScript objects (the bike). I’ll tell you how to work with them. Model is an array (or collection) of board game records, so in order to work with an array, we need to iterate over it. Ember has a special helper for the template called each . Inside of the each helper, we’re working with a single board game record, and so we can display the titles of each game. <ul> {{#each model as |game|}} <li>{{game.title}}, id {{game.id}}</li> {{/each}} </ul> Here’s where Ember Data gets cool. As you CRUD records, the model gets updated too, in real time, without you needing to do anything. Try it! Of course, in order for this function to work, you need a back end server endpoint that returns an array of records. Take a look at the Network tab and your server console to see what’s going on if nothing is showing up. Refresh the page. Is everything still there? Awesome. Destroy My favorite. Here’s the code that you should already have in your controller: destroyBoardGame() { let destroyId = this.get('destroyId') let game = this.get('model').findBy('id', destroyId) game.destroyRecord() } You might remember that one of the inputs on our template had a value of destroyID . Here we use this.get('destroyId') to look up what the user had entered into the form. Then we look at the model (a collection of board games) and find the game with the id the user entered. destroyRecord deletes the record from the Ember Data store AND saves the change by doing a DELETE request. If you use deleteRecord instead, there won’t be a request to the API. You’ll know it worked when you refresh the page and anything you deleted is gone from the Read All list. Updating Editing/updating is a little weird. In a “real app,” you would have a special route that only displays information for one record in its model hook. But since we don’t have such a route, we’ll look up the record on our collection of models using findBy , make some changes, and save them. Again, console logging Ember Data records won’t give you anything useful (to a noob) in the console. I’m hard-coding an ID in here purely for demonstration purposes. You wouldn’t ever hard code an id into API/Ember Data requests in a real app. If you destroyed record #1, you’ll need to edit the function to point to a different id than 1. updateBoardGame() { let updatedTitle = this.get('updatedTitle') let game = this.get('model').findBy('id', '1') game.set('title', updatedTitle) game.save(); }, set() changes the record’s title locally in Ember Data. Calling save on a record that already exists triggers a PATCH request. If you’re successful, you should be able to refresh the page and see that your title is still changed. If it goes back to the old title, that means you need to check the browser console for adapter errors or the Network tab to check the format of your request and API response. More Reading (GET one record) I saved this for last because a GET request for one record doesn’t really belong in the controller. I also cheated in this example and hard coded the ID for the GET request. It’s for demonstration purposes. Here’s an excerpt from the code you already have in controllers/application.js : readBoardGame() { this.store.findRecord('boardgame', 1) .then((game) => { alert(game.get('title') + ' ' + game.get('id')) }) }, This findRecord places a GET request to boardgames/1 . Depending on your back end framework, the id may be available as params, which you can use to look up the record in the database. Your API should respond with a single record. Try clicking the button with the readBoardGameaction. It ought to trigger a pop up that shows you the title of the board game with id 1. We are doing three Bad Things here… First, you shouldn’t use alert in a real app. It’s annoying and ugly. But whatevs. Second, don’t hard code IDs. Finally, and most importantly, in a real app, I would usually be doing findRecord inside of a model hook, so that I can use all the awesome automatic updating powers that models have. I’d have some dynamic segments, I’d have parent and child routes, there would be some interesting things going on in the router and child route models, we’d have A LOT more files! But you asked for the simplest possible CRUD, so here it is! I hope you’re happy. Now go read The Guides and the API Docs for Ember Data. Good luck! P.S. If you have feedback about how to make this tutorial better, I’d love to hear from you. @jwwweber on Twitter and jenweber on Ember Discord.
https://medium.com/ember-ish/the-simplest-possible-ember-data-crud-16eacee33ae6?source=collection_home---5------5-----------------------
CC-MAIN-2020-50
refinedweb
3,010
74.49
This C Program segregates 0s on left side & 1s on right side of the array. Here is source code of the C Program to segregate 0s on left side & 1s on right side of the array. The C program is successfully compiled and run on a Linux system. The program output is also shown below. /* * C Program to Segregate 0s on Left Side & 1s on right side of the Array (Traverse Array only once) */ #include <stdio.h> /*Function to segregate all 0s on left and all 1s on right*/ void segregate0and1(int array[], int size) { int left = 0, right = size-1; while (left < right) { /* Increment left index while we see 0 at left */ while (array[left] == 0 && left < right) left++; /* Decrement right index while we see 1 at right */ while (array[right] == 1 && left < right) right--; /* If left is smaller than right then there is a 1 at left and a 0 at right. Exchange it */ if (left < right) { array[left] = 0; array[right] = 1; left++; right--; } } } int main() { int arr[] = {0, 1, 0, 1, 1, 0}; int array_size = 6, i = 0; segregate0and1(arr, array_size); printf("segregated array is "); for (i = 0; i < 6; i++) printf("%d ", arr[i]); getchar(); return 0; } $ cc pgm96.c $ a.out segregated array is 0 0 0 1 1 1 Sanfoundry Global Education & Learning Series – 1000 C Programs. Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms If you wish to look at other example programs on Arrays, go to C Programming Examples on Arrays. If you wish to look at programming examples on all topics, go to C Programming Examples.
http://www.sanfoundry.com/c-program-segregate-0s-left-1s-right-array/
CC-MAIN-2017-43
refinedweb
273
62.21