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 |
|---|---|---|---|---|---|
- 02 May, 2013 23 commits
- 17 commits
- ...
- Aneesh Kumar K.V authored
We moved the definition of shift_to_mmu_psize and mmu_psize_to_shift out of hugetlbpage.c in patch "powerpc: New hugepage directory format". These functions are not related to hugetlbpage and we want to use them outside hugetlbpage.c We missed a definition for book3e when we moved these functions. Add similar functions to mmu-book3e.h Signed-off-by:
Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> Signed-off-by:
Benjamin Herrenschmidt <benh@kernel.crashing.org>
- Michael Ellerman authored
This context switches the new Event Based Branching (EBB) SPRs. The three new SPRs are: - Event Based Branch Handler Register (EBBHR) - Event Based Branch Return Register (EBBRR) - Branch Event Status and Control Register (BESCR) Signed-off-by:
Michael Ellerman <michael@ellerman.id.au> Signed-off-by:
Matt Evans <matt@ozlabs.org> Signed-off-by:
Michael Neuling <mikey@neuling.org> Signed-off-by:
Benjamin Herrenschmidt <benh@kernel.crashing.org>
- Michael Neuling authored
This turns Event Based Branching (EBB) on in the Hypervisor Facility Status and Control Register (HFSCR) and Facility Status and Control Register (FSCR). Signed-off-by:
Michael Neuling <mikey@neuling.org> Signed-off-by:
Benjamin Herrenschmidt <benh@kernel.crashing.org>
- Michael Ellerman authored
We are getting low on cpu feature bits. So rather than add a separate bit for every new Power8 feature, add a bit for arch 2.07 server catagory and use that instead. Hijack the value we had for BCTAR, but swap the value with CFAR so that all the ARCH defines are together. Note we don't touch CPU_FTR_TM, because it is conditionally enabled if the kernel is built with TM support. Signed-off-by:
Michael Ellerman <michael@ellerman.id.au> Signed-off-by:
Michael Neuling <mikey@neuling.org> Signed-off-by:
Benjamin Herrenschmidt <benh@kernel.crashing.org>
- Anshuman Khandual authored
Make BHRB instructions available in problem and privileged states. Signed-off-by:
Anshuman Khandual <khandual@linux.vnet.ibm.com> Signed-off-by:
Benjamin Herrenschmidt <benh@kernel.crashing.org>
- Bharat Bhushan authored
We do not want to take single step and branch-taken debug exception in kernel exception code. But the address range check was not covering all kernel exception handlers address range. With this patch we defined the interrupt_end label which defines the end on kernel exception code. So now we check interrupt_base to interrupt_end range for not handling debug exception in kernel exception entry. Signed-off-by:
Bharat Bhushan <bharat.bhushan@freescale.com> Signed-off-by:
Benjamin Herrenschmidt <benh@kernel.crashing.org>
- git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip
Pull x86/efi changes from Peter Anvin: "The bulk of these changes are cleaning up the efivars handling and breaking it up into a tree of files. There are a number of fixes as well. The entire changeset is pretty big, but most of it is code movement. Several of these commits are quite new; the history got very messed up due to a mismerge with the urgent changes for rc8 which completely broke IA64, and so Ingo requested that we rebase it to straighten it out." * 'x86-efi-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip: efi: remove "kfree(NULL)" efi: locking fix in efivar_entry_set_safe() efi, pstore: Read data from variable store before memcpy() efi, pstore: Remove entry from list when erasing efi, pstore: Initialise 'entry' before iterating efi: split efisubsystem from efivars efivarfs: Move to fs/efivarfs efivars: Move pstore code into the new EFI directory efivars: efivar_entry API efivars: Keep a private global pointer to efivars efi: move utf16 string functions to efi.h x86, efi: Make efi_memblock_x86_reserve_range more readable efivarfs: convert to use simple_open()
->
Signed-off-by:
Al Viro <viro@zeniv.linux.org.uk>
-
Move non-public declarations and definitions from linux/proc_fs.h to fs/proc/internal.h. Signed-off-by:
David Howells <dhowells@redhat.com> Signed-off-by:
Al Viro <viro@zeniv.linux.org.uk>
Make the PROC_I() and PDE() macros internal to procfs. This means making PDE_DATA() out of line. This could be made more optimal by storing PDE()->data into inode->i_private. Also provide a __PDE_DATA() that is inline and internal to procfs. Signed-off-by:
David Howells <dhowells@redhat.com> Signed-off-by:
Al Viro <viro@zeniv.linux.org.u>
Signed-off-by:
Al Viro <viro@zeniv.linux.org.uk>
Clean up the pseries scanlog driver's use of procfs: (1) Don't need to save the proc_dir_entry pointer as we have the filename to remove with. (2) Save the scan log buffer pointer in a static variable (there is only one of it) and don't save it in the PDE (which doesn't have a destructor). Signed-off-by:
David Howells <dhowells@redhat.com> cc: Benjamin Herrenschmidt <benh@kernel.crashing.org> cc: Paul Mackerras <paulus@samba.org> cc: linuxppc-dev@lists.ozlabs.org Signed-off-by:
Al Viro <viro@zeniv.linux.org.uk>
Clean up some of the problems with the rtas_flash driver: (1) It shouldn't fiddle with the internals of the procfs filesystem (altering pde->count). (2) If pid namespaces are in effect, then you can get multiple inodes connected to a single pde, thereby rendering the pde->count > 2 test useless. (3) The pde->count fudging doesn't work for forked, dup'd or cloned file descriptors, so add static mutexes and use them to wrap access to the driver through read, write and release methods. (4) The driver can only handle one device, so allocate most of the data previously attached to the pde->data as static variables instead (though allocate the validation data buffer with kmalloc). (5) We don't need to save the pde pointers as long as we have the filenames available for removal. (6) Don't try to multiplex what the update file read method does based on the filename. Instead provide separate file ops and split the function. Whilst we're at it, tabulate the procfile information and loop through it when creating or destroying them rather than manually coding each one. [Folded fixes from Vasant Hegde <hegdevasant@linux.vnet.ibm.com>] Signed-off-by:
David Howells <dhowells@redhat.com> cc: Benjamin Herrenschmidt <benh@kernel.crashing.org> cc: Paul Mackerras <paulus@samba.org> cc: Anton Blanchard <anton@samba.org> cc: linuxppc-dev@lists.ozlabs.org Signed-off-by:
Al Viro <viro@zeniv.linux.org.uk> | https://gitlab.flux.utah.edu/xcap/xcap-capability-linux/-/commits/0279b3c0ada1d78882f24acf94ac4595bd657a89 | CC-MAIN-2021-43 | refinedweb | 1,061 | 51.34 |
csh(1) [osf1 man page]
csh(1) General Commands Manual csh(1) NAME
csh - C shell command interpreter SYNOPSIS
csh [-bcefinstvVxX] [argument...] The csh command invokes the C shell and interprets C shell commands. OPTIONS
Forces a break from option processing, causing any further shell arguments to be treated as nonoption arguments. This can be used to pass options to a shell script without confusion or possible subterfuge. The shell cannot run a set-user-ID script without this option. Reads commands from the following single argument, which must be present. Any remaining arguments are placed in argv. Causes the shell to exit if any invoked command terminates abnormally or yields a nonzero exit status. Causes the shell to start faster, because it neither searches for nor executes the file in the invoker's home directory. Causes the shell to be interactive, even if the input does not come from a terminal. Shells are always interactive when invoked from a terminal. Parses commands, but does not execute them. This aids in syntactic checking of shell scripts. Takes command input from the standard input. Reads and executes a single line of input. You can use a (backslash) to escape the newline character at the end of the current line to continue onto another line. Sets the verbose shell vari- able, with the effect that command input is echoed to the standard output after history substitution. Sets the verbose shell variable, even before is executed. Sets the echo shell variable, so that commands are echoed to the standard error after all substitutions and imme- diately before execution. Sets the echo shell variable, even before is executed. After processing of option arguments, if arguments remain but none of the -c, -i, -s, or -t options was given, the first argument is taken as the name of a file of commands to be executed (that is, a shell script). The shell opens this file, and saves its name for possible resubstitution by $0. If the first characters of the shell script are #!shell_pathname or #csh, csh runs the specified shell to process the script. Otherwise, csh runs. Remaining parameters initialize the argv variable. DESCRIPTION
The C shell is an interactive command interpreter and a command programming language that uses a syntax similar to the C programming lan- guage. The shell carries out commands either from a file (called a shell script or procedure) or interactively from a terminal keyboard. When you run csh, it begins by executing commands from the file in your home directory, if it exists. If the shell is invoked with a name that starts with -, as when started by login, the shell runs as a login shell. If csh runs as a login shell, it executes commands from the system-wide login file /etc/csh.login, if that file exists, and then commands from your $home/.cshrc file and your $home/.login file, in that order. (If argument zero ($0) to the shell is a - (dash), then the shell is a login shell.) Your system administrator can create /etc/csh.login to provide a standardized environment for all users, but you can include commands in $home/.cshrc or $home/.login to over- ride settings and assignments made by /etc/csh.login. At log in, the $home shell variable and the $HOME environment variable both refer to your home directory. If you subsequently change $home to some other value, you will encounter problems because the shell will not be able to find files it uses, such as and In the normal case, the shell begins reading commands from the terminal, prompting with % (percent sign) or # (number sign) for the supe- ruser. Processing of arguments and the use of the shell to process files containing command scripts is described later. The shell then repeatedly performs the following actions: A line of command input is read and broken into words. This sequence of words is placed on the command history list and then parsed. Each command in the current line is executed. When a login shell terminates, it executes commands from the file in your home directory. Shell Features Job control and status reporting File name completion History substitution Command aliasing Variable substitution Command substitution File name substitution Input/output redirection and control flow Built-in commands Lexical Structure A simple command is a sequence of words separated by spaces or tabs. The shell splits input lines into words at spaces and tabs with the following exceptions: The characters &, |, ;, <, >, (, ), and # form separate words. If doubled in &&, ||, <<, or >>, these pairs form sin- gle words. Preceding parser metacharacters with a (backslash) prevents the shell from interpreting them as special characters. A new- line preceded by a (backslash) is equivalent to a space. Strings enclosed in " " (double quotes), ` ` (grave accents), or ' ' (single quotes) form parts of a word; metacharacters in these strings, including spaces and tabs, do not form separate words. For more informa- tion, see the section Quoting with Single and Double Quotes. Within pairs of ' or " characters, you can include the newline character by preceding it with a (backslash). When the shell is not reading input from a terminal, it treats any word that begins with a # (number sign) character as a comment and ignores that word and all characters following up to the next newline character. The # character loses its special meaning when it is quoted (preceded) by a (backslash) or when the string is enclosed in quotes using `, ', or ". When the shell is reading input from a terminal without the c option, the # character is not treated specially. However, when read- ing input from a terminal with the c option, the shell treats a # character as the start of a comment and ignores subsequent text up to the next newline unless the # is quoted with a (backslash) or the string is enclosed in quotes using `, ', or ". Shell Commands A simple command is a sequence of words, the first of which (numbered 0) specifies the command to be executed. Any remaining words, with a few exceptions, are passed to that command. If the command specifies an executable file that is a compiled program, the shell immediately runs that program. If the file is marked executable but is not a compiled program, the shell assumes that it is a shell script. In this case, it starts another shell to read the file and execute the commands included in it. (See the section Nonbuilt-In Command Execution for information about using the $shell variable to determine which shell is executed.) A pipeline is a sequence of one or more commands separated by either the | (vertical bar) or |& (vertical bar and ampersand) characters. With |, the standard output of the preceding command is redirected to the standard input of the command that follows. With |&, both the standard error and the standard output are redirected. Note that you cannot pipe to a built-in command and an attempt to do so generates an error message. A list is a sequence of pipelines separated by a ; (semicolon), & (ampersand), && (two ampersands), or || (two vertical bars) and optionally ended by a ; (semicolon) or an & (ampersand). These separators and terminators have the following effects: Causes sequential execution of the preceding pipeline (the shell waits for the pipeline to finish). Causes asynchronous execution of the preced- ing pipeline (the shell does not wait for the pipeline to finish). Causes the list following it to be executed only if the preceding pipe- line returns a 0 (zero) exit value. Causes the list following it to be executed only if the preceding pipeline returns a nonzero exit value. The ; (semicolon) and & (ampersand) separators have equal precedence, as do && and ||. The single-character separators have lower prece- dence than the double-character separators. A newline character without quotes following a pipeline functions the same as a ; (semicolon). A pipeline or sequence can be enclosed in () (parentheses) to form a simple command. Job Control The shell associates a job with each pipeline. It keeps a table of current jobs and assigns them small integer numbers. When you start a job asynchronously by terminating the command with &, the shell displays a line that looks like this: [1] 1234 This line indicates that the job number is 1 and that the job is composed of one process with the process ID of 1234. Use the built-in jobs command to see the table of current jobs. If you are running a job and want to do something else, you can enter the Suspend key sequence (normally <Ctrl-z>) which sends a stop sig- nal to the current job. The shell then normally indicates that the job has been stopped and it prints another prompt. You can then manip- ulate the state of this job, putting it in the background with the bg command, or run some other commands and then eventually bring the job back into the foreground with the foreground command fg. The job suspension takes effect immediately, and is similar to the Interrupt key sequence in that pending output and unread input are discarded. A special key sequence, <Ctrl-y>, does not generate a stop signal until a program attempts to read it. (See the read() system call for more information.) This key sequence can usefully be typed ahead when you have prepared some commands for a job that you want to stop after it has read them. Multiple interactive loop based commands can be started and suspended. These suspended commands can be restarted in any arbitrary order. When a suspended job is restarted, it must be run in the foreground rather than in the background. If an attempt is made to restart it in the background, the shell restarts only the command that was suspended and terminates once the job completes without continuing with the rest of the loop. A job being run in the background stops if it tries to read from the terminal. Background jobs are normally allowed to produce output, but this can be disabled by entering the stty tostop command. If you set this terminal option, background jobs stop when they try to produce output like they do when they try to read input. There are several ways to refer to jobs in the shell. Use the % (percent sign) with the fg and bg built-in commands to control the job. This name can be either the job number or a prefix of the string that started the job, if this name is unique. (% can be used to refer to both background and foreground jobs.) For example, if a make process is running as job number 1, you can refer to it as %1. You can also refer to it as %make, if there is only one job with a name that begins with the string make. You can also use the following characters to specify a job whose name contains string, if there is only one such job: %?string Just naming a job brings it to the foreground, so %1 is a synonym for fg %1, bringing job 1 back into the foreground. Similarly, entering %1 & resumes job 1 in the background. Thus, %ex normally restarts a stopped ex job if there was only one stopped job whose name began with the string ex. The shell maintains a notion of the current and previous jobs. In output produced by the built-in command jobs, the current job is marked with a + (plus sign) and the previous job with a - (dash). The abbreviation %+ refers to the current job and %- refers to the previous job. For close analogy with the syntax of the history mechanism (described later), %% is also a synonym for the current job. Status Reporting The shell tracks the state of each job and reports whenever a job finishes or becomes blocked. The shell prints the status information just before it prints the prompt to avoid disturbing the appearance of the terminal screen. If, however, you set the notify shell vari- able, the shell notifies you immediately of changes of status in background jobs. There is also a notify shell command that marks a single process so that its status changes are immediately reported. By default notify marks the current process. Simply enter notify after start- ing a background job to mark the job. When you try to leave the shell while jobs are stopped, you are warned that you have stopped jobs. You can use the built-in jobs command to see what they are. If you then immediately exit the shell, or use jobs and then exit, the shell does not warn you a second time, and the suspended jobs are terminated. File Name Completion The file name completion feature is enabled by setting the shell variable filec. The csh interactively completes file names and user names from unique prefixes when they are input from the terminal followed by the escape character (the <ESC> key or <Ctrl-[>)). For example, assume the current directory looks like this: DSC.OLD bench chaos cmd dev mail xmpl.c xmpl.out DSC.NEW bin class cmtest lib mbox xmpl.o The input is as follows: % vi ch<ESC> The csh completes the prefix ch to the only matching file name chaos: vi chaos However, given the following command line: vi D<ESC> csh only expands the input as follows: vi DSC. The csh sounds the terminal bell to indicate that the expansion is incomplete, because two file names match the prefix D. If a partial file name is followed by the End-of-File character (shown here as <Ctrl-d>), then instead of completing the name, csh lists all file names matching the prefix. For example, the following input causes all files beginning with D to be listed: vi D<Ctrl-d> DSC.NEW DSC.OLD The input line is then echoed again for you to complete. The same system of <ESC> and <EOF> can also be used to expand partial user names, if the word to be completed (or listed) begins with ~ (tilde). For example, entering the following command line: cd ~ro<ESC> can produce the following expansion: cd ~root The use of the terminal bell to signal errors or multiple matches can be inhibited by setting the variable nobeep. Normally, all files in the particular directory are candidates for name completion. Files with certain suffixes can be excluded from con- sideration by setting the variable fignore to the list of suffixes to be ignored. Thus, if fignore is set by the following command: % set fignore = (.o .out) typing % vi x<ESC> results-d>. All files are listed regardless of their suffixes. History Substitution History substitution places words from previous command input as portions of new commands, making it easy to repeat commands, repeat argu- ments of a previous command in the current command, or fix spelling mistakes in the previous command with little typing. History substitu- tions begin with the ! (exclamation point) character and can begin anywhere on the command line, provided they do not nest (in other words, a history substitution cannot contain another history substitution). You can precede the ! with a (backslash) to prevent the exclamation point's special meaning. In addition, if you place an ! (exclamation point) before a space, tab, newline, = (equal sign), or ( (left parenthesis), the exclamation point is passed to the parser unchanged. (History substitutions also occur when you begin an input line with a ^ (circumflex). This special abbreviation is described later.) The shell echoes any input line containing history substitutions before it executes that command line. Commands input from the terminal that consist of one or more words are saved on the history list. The history substitutions reintroduce sequences of words from these saved commands into the input stream. The history shell variable controls the size of the history list. You must set the history shell variable either in the file or on the command line with the built-in set command. The previous command is always retained, however, regardless of the value of history. Com- mands in the history list are numbered sequentially, starting from 1. The built-in history command produces output of the type: 9 write michael 10 ex write.c 11 cat oldwrite.c 12 diff *write.c The command strings are shown with their event numbers. It is not usually necessary to use event numbers to refer to events, but you can have the current event number displayed as part of your system prompt by placing an ! (exclamation point) in the prompt string assigned to the prompt variable. A full history reference contains an event specification, a word designator, and one or more modifiers in the following general format: event[:]word:modifier[:modifier]... Note that only one word can be modified. A string that contains spaces is not allowed. In the previous sample of history command output, the current event number is 13. Using this example, the following refer to previous events: Refers to event number 10. Refers to event number 11 (the current event minus 2). Refers to a command word beginning with d (in this case, event number 12). Refers to a command word that contains the string mic (in this case, event number 9). These forms, without further modification, simply reintroduce the words of the specified events, each separated by a single space. As a special case, !! refers to the previous command. (The !! command alone on an input line reruns the previous command.) To select words from an event, follow the event specification by a : (colon) and one of the following word designators. The words of an input line are numbered sequentially, starting from 0 (zero), with the first (usually command) word being 0 (zero), the second word (first argument) being 1, and so on. The basic word designators are as follows: First word (command). The nth argument, where n > 0, for exam- ple, !!:3 recalls the third word of the previous command and !:2 recalls to the second word of the current command. !#:n is the same as !:n and recalls the nth word of the current command. First word (word 1). Last word. Word matched by (the immediately preceding) ?string? history search. Range of words from x through y. Words 0-y. The second through the last words, or nothing if only one word in event. Words x- $ Like x*, but omits the last word ($). You can omit the : (colon) separating the event specification from the word designator if the word designator begins with a ^, $, *, -, or %. You can also place a sequence of modifiers, each preceded by a : (colon), after the optional word designator. The following modifiers are defined: Repeats the previous substitution. Removes all but the trailing extension Applies the change globally, prefixing another mod- ifier, for example g&. Removes a trailing path name extension, leaving the head. Prints the new command, but does not execute it. Quotes the substituted words, thus preventing further substitutions. Removes a trailing component, leaving the root name. Substitutes r for l. It is an error for no word to be applicable. Removes all leading path name components, leaving the tail. Like q, but breaks into words at space, tab or newline. Unless the modifier is preceded by a g, the change is applied only to the first modifiable word. The l (left) side of a substitution is not a pattern in the sense of a string recognized by an editor; rather, it is a word, a single unit without spaces. Normally, a / (slash) delimits the word (l) and its replacement (r). However, you can use any character as the delimiter. Thus, in the following example the = character becomes the delimiter, allowing you to include the / in your word: s=/usr/myfile=/usr/your- file= If you include an & (ampersand) in the replacement (r), it is replaced by the text from the left-hand side (l). A null l side is replaced by either the last l string or by the last string used in the contextual scan !?string?. You can omit the trailing delimiter (/) if a new- line character follows immediately. A history reference can be given without an event specification. For example, !$ refers to the last argument of the previous command. If a history reference without an event specification is not the first history reference on the line, it refers to the previous history refer- ence on the line and not to a previous event. For example, in !?foo?^ !$, !?foo?^ gives the first argument of the command matching ?foo?, and the !$ gives the last argument of that same command, not the last argument of the previous command (as it would if it were on a line by itself). A special abbreviation of a history reference occurs when the first nonspace character of an input line is a ^ (circumflex). This is equivalent to !:s^, providing a convenient shorthand for substitutions on the text of the previous line. Thus, ^lb^lib corrects the spell- ing of lib in the previous command. Finally, a history substitution can be enclosed in { } (braces) to insulate it from the characters that follow. Thus, after ls -ld ~paul you might specify !{l}a to do ls -ld ~paula, or !la to rerun a command starting with la. Command Line Editing (cmdedit) If you are using a video display terminal or a workstation terminal emulator, csh allows you to recall and edit commands as if you were using an editor; this capability is in addition to the history mechanism. This version of the C shell provides intra-command line editing that includes features such as a kill buffer, multiline named keyboard macros which can be automatically saved and restored, convenient access to the history list, and user settable key bindings. A summary of the currently available functions is provided below. In most cases, the functionality is apparent from the names of the routines in the list. The shell's editing mode is determined by the value of the shell editmode variable which users should set to emacs or vi in their files. If editmode is not set, then the shell will run in "dumb" mode. It is possible to set the mode after the shell starts up; so if you find your- self in "dumb" mode, you can alter the situation without having to log out and log in again. Setting the editmode variable has two impor- tant side effects:(1) it causes the key bindings to be reevaluated, and(2) it sets the EDITMODE environment variable. The latter has no effect within the shell; so users should not set the environment variable directly in hopes of altering the editing mode. Terminal control capabilities are extracted from the user's termcap file (usually /etc/termcap), using the value of the shell variable term, not the environment variable TERM, as the terminal type. If term is undefined, unknown, or if the associated termcap definition is inadequate, a warning will be displayed and most, or all, of the editing features of the shell will be disabled. It is the user's respon- sibility to make sure that term is set to an appropriate value before the shell editor is initialized. Usually this should be done in the file. If editing is disabled because term is not properly set when the shell starts up, simply setting term to the proper value will nor- mally cause the shell editor to be reenabled. NB: Setting the shell variable term causes the environment variable TERM to be set to the same value. For information on controlling the bell, see the ERRORS section. There is a bind-to-key command in this shell, which allows the functions listed in the table on bindings below, and also user defined key- board macros, to be bound to keys. The form of the command is bind-to-key function key ... where function is one of the function names from the list or else the single character name of a keyboard macro and where key is a quoted string designating a key sequence. Control characters in the key designation should not be entered literally, but should be indicated by the prefix "^", e.g. "^X". Similarly, escape is indicated by "e". A literal backslash is "\". Escape and control-X are the only legitimate "prefix" characters. For vi mode, bindings prefixed with control-X are for insert mode. Otherwise, the bindings are in effect only in command mode. The following mnemonics should be used: ^? delete (rubout) ^c control character line feed (new line) back space horizontal tab v vertical tab f form feed carriage return e escape nn character code in octal Since the shell converts returns to newlines it is probably unwise to alter which would be accomplished using the following command: bind- to-key KillRegion "^U" During editor initialization the shell will read a file named in the user's home directory. If you regularly want certain non-default key bindings to be effective, put the appropriate bind-to-key commands in your ~/.bindings file. NB: Do not place the bind-to-key commands in your ~/.cshrc or ~/.login file; they must be in the ~/.bindings file. Invocation of the history mechanism with "!" either causes the matched command to be inserted on the command line for editing before execu- tion or immediately executes the command. This is controlled by the shell variable edithist, which is automatically set, when the shell variable editmode is set, thereby allowing editing of previous commands invoked by the history mechanism. This feature may be turned off with the command "unset edithist", which may be placed in the user's file. The following table shows the current functions and default key bindings: Emacs Function Name Remark ^B Backspace ESC-b BackwardWord ^A BeginningOfLine ^L ClearScreen DefaultBinding ESC-n DefineNamedMacro name macro ^D DeleteCurrentChar ^H DeletePreviousChar ESC-d DeleteWord after cursor EndOfFile exit shell ^E EndOfLine EraseLine kills whole line ESC-h EraseWord before cursor ExecuteMacro ESC-e ExecuteNamedMacro ESC-x ExecuteNamedMacro ^X-e ExecuteUnNamedMacro ESC-ESC FilenameExpansion ESC-l FilenameList ^F ForwardChar ESC-f ForwardWord GnuTransposeChars like gnu-emacs IncrementalSearchForward IncrementalSearchReverse InsertChar self insert ^V InsertLiteralChar ^W KillRegion to kill buffer ^K KillToEOL to kill buffer ^X^R LoadMacroFile ^N NextHistEntry wraps around ^P PreviousHistEntry wraps around ^R Redisplay redraws line ^U Repetition greater than 0 ^M,^J Return ^X^S SaveMacroFile ^@ SetMark default mark at BOL SearchReverse look for next char SearchForward look for next char ^Q StartFlow (see FLOW CONTROL) ^X-( StartRemembering begin a macro ^S StopFlow (see FLOW CONTROL) ^X-) StopRemembering end a macro ^I Tab inserts 8 spaces ^T TransposeChars before cursor WipeLine kill line without saving ^Y YankKillBuffer no kill ring Vi Function Name Remark A AppendToEOL can't use with bind-to-key ^H BackSpace h BackSpace B BackwardWord b BackwardWord 0 BeginningOfLine ^ BeginningOfLine s ChangeChar can't use with bind-to-key c ChangeFollowingObject can't use with bind-to-key C ChangeToEOL can't use with bind-to-key S ChangeWholeLine can't use with bind-to-key x DeleteCurrentChar d DeleteFollowingObject can't use with bind-to-key X DeletePreviousChar can't use with bind-to-key $ EndOfLine ESC FilenameExpansion ^D FilenameListOrEof l ForwardChar SPACE ForwardChar w ForwardWord W ForwardWord e ForwardWord I InsertAtBOL can't use with bind-to-key D KillToEOL @ ExecuteNamedMacro + NextHistEntry j NextHistEntry ^N NextHistEntry - PreviousHistEntry k PreviousHistEntry ^P PreviousHistEntry ^L Redisplay ^R Redisplay z Redisplay 1-9 Repetition r ReplaceChar can't use with bind-to-key LINEFEED Return RETURN Return / IncrementalSearchForward ? IncrementalSearchReverse f SearchForward F SearchReverse m SetMark a EnterViAppend can't use with bind-to-key i EnterViInsert can't use with bind-to-key p ViYankKillBuffer can't use with bind-to-key P ViYankKillBuffer can't use with bind-to-key Vi insert mode ^H DeletePreviousChar EraseChar DeletePreviousChar ^W EraseWord ESC ExitViInsert can't use with bind-to-key ^D FilenameListOrEof ^Q InsertLiteralChar ^V InsertLiteralChar ^U KillRegion ^N NextHistEntry ^P PreviousHistEntry ^L Redisplay ^R Redisplay LINEFEED Return RETURN Return TAB Tab Users may change the bindings of functions to keys by means of the shell bind-to-key command. These commands may be stored in a file named in the user's home directory and will then be read by the shell when the editor is initialized. Flow control is handled by the terminal driver, not by the shell. The terminal driver normally interprets ^S and ^Q as a signal to respec- tively stop and restart output to the terminal. By default, the shell does not override these "bindings", but the user may override them by rebinding ^S or ^Q to functions other than StopFlow and StartFlow. The functions StopFlow and StartFlow can only be usefully bound to the keys that the terminal driver interprets as performing the corre- sponding flow control functions. In other words, you cannot simply bind these functions to other keys in order to have them perform the flow control operations normally provided by ^S and ^Q. Keyboard macros can be used to simplify repetitive operations and reduce typing lengthy commands. For example, the following lines illus- trate how to create a macro to startup Emacs and have it run the shell inside a buffer: % ^X(emacs -eshell % ^X) Notice that this is a multiline macro, since it contains an embedded newline. The user can give this macro a single character name, e.g. "e", as follows: % ene (escape-n-e). The macro may then be executed by typing "exe". It can also be bound to a key using the bind-to-key command. Macros can be saved in files and can be reloaded automatically when the shell starts up. To create a new unnamed macro, use the StartRemembering function which is bound by default to ^X(. Subsequent keystrokes, until the StopRemembering, ^X ), function is executed, are remembered as an "unnamed" key- board macro. It can contain at most 1024 characters. You are not allowed to begin creating another macro during macro creation, but it is okay to execute other macros, provided loops are not created. The unnamed macro can be executed using the ExecuteUnNamedMacro function, bound to ^Xe. There is only one unnamed macro. Users can have up to 128 named macros. To define such a macro, first create an unnamed macro as above and then give it a name by executing the DefineNamedMacro function, bound to en (escape-n). The function takes a single character argument which will be the name of the macro. Any previous macro with that same name will be destroyed. To execute a named macro simply use the ExecuteNamedMacro function, bound to ex, and give it the name of the macro to be executed. Named macros can also be bound to keys using the built-in C shell command bind-to-key. Named keyboard macros can be saved in files and loaded from files. To save the named macros in a file simply type the file name on the command line (by itself) and then execute the SaveMacroFile function bound to ^X^S. To read a file of previously saved macros type the file name on the command line and execute the LoadMacroFile function bound to ^X^R. Success in each case is indicated by the erasure of the file name. It is okay to store macros in several different macro files. NB: It is not advisable to try to edit saved macros! If the shell variable macrofiles is assigned (in the user's file) the names of one or more files of saved keyboard macros, then those macro files will be automatically loaded when the shell starts up. Similarly, the variable savemacros can be assigned the name of a (single) file in which all named macros will be saved when the user logs out. NB: The names of the incremental search functions have changed since earlier releases of this shell. Four search functions are available to the user, but are not bound (by default) to keys. If you want to use them, use the C shell bind-to- key command to bind them to keys. When the user executes this function he is placed in a read/search loop in which the string to be found is built up character by character. As each new character is added to the search string the cursor is placed at the end of the first match on the command line following the position of the cursor when the function was executed. You can reexecute the search function while in the loop to cause the cursor to move to subsequent matches. Type ESC to exit the loop. This function is similar to IncrementalSearchFor- ward except that the cursor is placed at the beginning of the first match on the command line preceding the position of the cursor when the function was executed. This function grabs the next character you type and searches for that character from the position of the cursor to the end of the command line, leaving the cursor following the first instance of the character if one is found. This function is like SearchForward except that it searches from where the cursor is to the beginning of the command line. If the shell variable breakchars is assigned a string, then the characters in that string are used to determine word boundaries. The default break characters are " ", ",", ^I, /, , (, ), [, ], {, }, ., ;, >, <, !, ^, &, and |. The user defined break characters are used instead of, not in addition to, the default list. The display update functions take no advantage of the capabilities of smart terminals. This will be fixed in the future. The command line cannot exceed 1024 characters if characters are being inserted in the middle of the line; it can be longer if characters are being inserted at the end, but once the 1K boundary is passed the previous characters can no longer be edited or redisplayed. The interactive input routine performs some initialization the first time it is called. As a result some things are not interactively alterable. It is also not possible for the user to turn off echoing of regular characters or to take the terminal out of CBREAK mode by means of the stty command, for example, and have it affect the function of the shell. Error conditions within the editor functions are usually indicated by an audible bell. If you prefer a visual signal and your terminal has a visible bell capability, then you should set the variable visiblebell in your file. If you want an audible bell also, then set both vis- iblebell and audiblebell. If you don't want to be told about your mistakes, you can set the nobell variable. Quoting with Single and Double Quotes Enclose strings in single and double quotes to prevent all or some of the substitutions that remain. Enclosing strings in ' ' (single quotes) prevents any further interpretation except history substitution. Enclosing strings in " " (double quotes) allows further variable and command expansion. In both cases, the text that results becomes (all or part of) a single word. Only in one special case does a string quoted by " " yield parts of more than one word; strings quoted by ' ' never do (see Command Substitution). Alias Substitution The shell maintains a list of aliases that the alias and unalias built-in commands can establish, display, and modify. After the shell scans a command line, it divides the line into distinct commands and checks the first word of each command, left to right, to see if it has an alias. If an alias exists, the text defined as the alias for that command is reread with the history mechanism, as if the alias were the previous input line. The words that result replace the command and argument list. If no reference is made to the history list, the argument list is left unchanged. Thus, if the alias for ls is ls -l, the shell replaces the command ls /usr with ls -l /usr. The argument list is left unchanged because there is no reference to the history list in the command with an alias. Similarly, if the alias for lookup is grep !^ /etc/passwd, then lookup bill maps to grep bill /etc/passwd. Here !^ refers to the history list and the shell replaces it with the first argument in the input line, in this case bill. Note that you can use special pattern-matching characters in an alias. Thus, the line: alias lprint 'pr !* | lpr' makes a command that formats its arguments to the line printer. The ! (exclamation point) is protected from the shell in the alias so that it is not expanded until pr runs. If an alias is found, the word transformation of the input text is performed and the aliasing process begins again on the reformed input line. If the first word of the new text is the same as the old, looping is prevented by flagging it to terminate the alias process. Other loops are detected and cause an error. Variable Substitution The shell maintains a set of variables, each of which has as its value a list of zero or more words. Some of these variables are set by the shell or referred to by it. For instance, the argv variable is an image of the shell variable list, and words that comprise the value of this variable are referred to in special ways. You can display and change the values of variables by using the set and unset commands. Of the variables referred to by the shell, a number are toggles (variables that turn on and off); the shell does not care what their value is, only whether they are set or unset. For instance, the verbose variable is a toggle that causes the words of each command to be echoed. The setting of this variable results from the -v option on the command line. Other operations treat variables numerically. The @ command performs numeric calculations and the result is assigned to a variable. Vari- able values are, however, always represented as (zero or more) strings. For the purposes of numeric operations, the null string is consid- ered to be 0 (zero), and the second and subsequent words of multiword values are ignored. After the input line is parsed and alias substitution is performed, and before each command is executed, variable substitution is per- formed, keyed by $ (dollar sign) characters. You can prevent this expansion by preceding the $ with a (backslash) except within " " (dou- ble quotes), where it always occurs, or by using ' ' (single quotes), where it never occurs. Strings quoted by ` ` (grave accents) are interpreted later (see Command Substitution), so variable substitution does not occur there until later, if at all. A $ is passed unchanged if followed by a space, tab, or newline. Input/output redirection is recognized and expanded before variable expansion occurs. Otherwise, the command name and complete argument list are expanded together. Therefore, it is possible for the first (command) word to this point to generate more than one word, the first of which becomes the command name, and the rest of which become arguments. Unless enclosed in " " or given the :q modifier, the results of variable substitution can themselves eventually be command and file name substituted. Within pairs of double quotes, a variable whose value consists of multiple words expands to a (portion of a) single word, with the words of the variable's value separated by spaces. When you apply the :q modifier to a substitution, the variable expands to mul- tiple words. The individual words are separated by spaces and quoted to prevent later command or file name substitution. The following notation allows you to introduce variable values into the shell input. Except as noted, it is an error to reference a vari- able that is not set. Are replaced by the words assigned to the variable name, each separated by a space. Braces insulate name from fol- lowing characters that would otherwise be part of it. Shell variable names begin with a letter and consist of up to 20 letters and digits, including the underscore character. If name is not a shell variable but is set in the environment, then that value is returned. Be aware that the : (colon) modifiers and the other forms given below are not available in this case. Can be used to select only some of the words from the value of name. The selector is subjected to variable substitution and can consist of a single number or two numbers separated by a - (dash). The first word of a variable's string value is numbered 1. If the first number of a range is omitted, it defaults to 1. If the last member of a range is omitted, it defaults to $#name (the total number of words in the variable). The * (asterisk) selects all words. It is not an error for a range to be empty if the second argument is omitted or in range. Gives the number of words in the variable. This can be used as a [selector] (see previous notation). Substitutes the name of the file from which command input is being read. An error occurs if the name is not known. Equivalent to $argv[number]. Equivalent to $argv[*]. You can apply the modifiers :gh, :gt, :gr, :h, :t, :r, :q and :x to the preceding substitutions. If { } (braces) appear in the command form, the modifiers must appear within the braces. Note that the current implementation allows only one : (colon) modifier on each $ vari- able expansion. The following substitutions cannot be changed with : modifiers. Substitutes the string 1 if name is set, 0 if it is not. Substitutes 1 if the current input file name is known, 0 (zero) if it is not. Substitutes the (decimal) process number of the (parent) shell. Substitutes a line from the standard input, with no further interpretation. Use it to read from the keyboard in a shell script. Command and File name Substitution The shell performs command and file name substitution selectively on the arguments of built-in commands. This means that it does not expand those parts of expressions that are not evaluated. For commands that are not internal (that is, built in) to the shell, the shell substi- tutes the command name separately from the argument list. This occurs very late, after the shell performs input/output redirection, and in a child of the main shell. Command Substitution The shell performs command substitution on a command string enclosed in ` ` (grave accents). The shell normally breaks the output from such a command into separate words at spaces, tabs and newline characters, with null words being discarded; this text then replaces the original command string. Within strings surrounded by " " (double quotes), the shell treats only the newline character as a word separator, thus preserving spaces and tabs. In any case, the single final newline character does not force a new word. Note that it is therefore possible for a command substitution to yield only part of a word, even if the command outputs a complete line. File Name Substitution If a word contains any of the characters *, ?, [, or { or begins with a ~ (tilde), then that word is a candidate for file name substitu- tion, also known as globbing. This word is then regarded as a pattern, and replaced with a sorted list of file names that match the pat- tern. In a list of words specifying file name substitution, it is an error for no pattern to match an existing file name, but it is not required that each pattern match. Only the character-matching symbols (metacharacters) *, ? and [ imply pattern matching; the characters ~ and { are more like abbreviations. In matching file names, the (dot) character at the beginning of a file name or immediately following a / (slash), as well as the / charac- ter, must be matched explicitly. The * (asterisk) character matches any string of characters, including the null string. The ? (question mark) character matches any single character. The sequence [abcd] matches any one of the enclosed characters. Within [ ], a lexical range of characters can be indicated by two characters separated by a - (dash), as in [a-z]. The characters that match this pattern are defined by the current collating sequence. The collating sequence is determined by the value of the LC_COLLATE or LANG environment variable. The ~ (tilde) character at the beginning of a file name is used to refer to home directories. Standing alone, the ~ expands to your home directory as reflected in the value of the home shell variable. When followed by a name that consists of letters, digits, and - (dash) characters, the shell searches for a user with that name and substitutes that user's home directory. Thus, ~ken might expand to /users/ken and ~ken/chmach to /users/ken/chmach. If the ~ (tilde) character is followed by a character other than a letter or / (slash) or does not appear at the beginning of a word, it is left undisturbed. The pattern a{b,c,d}e is a shorthand for abe ace ade. Left-to-right order is preserved, with the results of the matches being sorted sepa- rately at a low level to preserve this order. This construct can be nested. Thus, the shell expands: ~source/s1/{oldls,ls}.c to the file names: /usr/source/s1/oldls.c /usr/source/s1/ls.c The preceding example assumes the home directory for source is /usr/source. (Note that these files may or may not exist.) Similarly, the shell expands: ../{memo,*box} to the paths: ../memo ../box ../mbox (Note that memo was not sorted with the results of matching *box.) As a special case, {, }, and {} are passed undisturbed. Redirecting Input and Output You can redirect the standard input and standard output of a command with the following syntax: Opens file (which is first variable, com- mand and file name expanded) as the standard input. Reads the shell input up to a line that is identical to word. The word is not sub- jected to variable, file name or command substitution; each input line is compared to word before any substitutions are done on this input line. Unless a quoting character (, ", `, or ') appears in word, the shell performs variable and command substitution on the intervening lines, allowing to quote $, , and `. Commands that are substituted have all spaces, tabs, and newline characters preserved, except for the final newline character, which is dropped. The resulting text is placed in an anonymous temporary file and given to the command as standard input. Uses file as standard output. If the file does not exist, it is created; if the file exists, it is truncated, and its pre- vious contents are lost. If the noclobber shell variable is set, then the file must not exist or be a character special file (for example, a terminal or /dev/null) or an error results. This helps prevent the accidental destruction of files. In this case, use the ! (exclamation point) forms to suppress this check. The forms involving & (ampersand) route the diagnostic output into the specified file as well as the standard output. file is expanded in the same way as < input file names. Uses file as standard output like > but places output at the end of the file. If the noclobber shell variable is set, it is an error for the file not to exist unless one of the ! forms is given. Otherwise, it is similar to >. A command receives the environment in which the shell was invoked, as changed by the input/output parameters and the presence of the com- mand in a pipeline. Thus, unlike some previous shells, commands run from a shell script have no access to the text of the commands by default; rather they receive the original standard input of the shell. Use the << mechanism to present inline data. This lets shell scripts function as components of pipelines and lets the shell read its input in blocks. To redirect diagnostic output through a pipe with the standard output, use the form |& (vertical bar, ampersand) rather than | (vertical bar) alone. Control Flow The shell contains a number of, and the if-then-else form of the if statement, require that the major keywords appear in a sin- gle simple command on an input line. If the shell input is not seekable, the shell buffers input whenever a loop is being read and performs seeks in the internal buffer to do the rereading implied by the loop. (To the extent that this allows, backward gotos succeed on non-seekable inputs.) Built-In Commands Built-in commands are executed within the shell. If a built-in command occurs as any component of a pipeline except the last, it is exe- cuted in a subshell. The csh searches for a csh built-in command first. If a built-in does not exist, the csh searches through the direc- tories specified by the environment variable path for a system-level command to execute. If no arguments are specified, displays all aliases. If name is specified, displays the alias for name. If a word_list is also specified, alias assigns the specified word_list as the alias of name. Command and file name substitution are performed on word_list. Puts the current (if %job is not specified) or specified jobs into the background, continuing them if they were stopped. Causes execution to resume after the end of the nearest enclosing foreach or while. The remaining commands on the current line are executed. Multilevel breaks are therefore possible by writing them all on one line. Causes a break from a switch; resumes after the endsw. Defines a label in a switch statement. (See switch.) Changes the shell's working directory to directory. If no argument is given, it changes to your home directory. If directory is not found as a subdirectory of the current directory (and does not begin with /, or cdpath shell variable is checked to see if it has a subdirectory directory. Finally, if all else fails, but directory is a shell variable whose value begins with /, this is tried to see if it is a directory. Continues execution of the nearest enclosing while or foreach. The rest of the commands on the current line are executed. Labels the default case in a switch statement. The default should come after all case labels. Displays the directory stack; the top of the stack is at the left, the first directory in the stack being the current directory. Writes the specified words to the shell's standard output, separated by spaces, and terminated with a newline character, unless the -n option is specified. See the description of foreach, if, switch, and while below. Reads arguments as input to the shell and executes the resulting commands. This is usually used to execute commands generated as the result of command or variable substitu- tion, since parsing occurs before these substitutions. Executes the specified command in place of the current shell. Exits the shell with either the value of the status shell variable, if no expression is specified, or with the value of the specified expres- sion. Brings the current (if %job is not specified) or specified job into the foreground, continuing them if they were stopped. Sets the variable name to each member of word_list successively and executes the sequence of commands between the foreach command and the matching end. (foreach and end commands must appear alone on separate lines.) Use the built-in continue command to continue the loop and the built-in break command to terminate it prematurely. When this com- mand is read from the terminal, the loop is read once, prompting with ? before any statement in the loop is executed. If you make a mistake in entering a loop at the terminal, it can be corrected before you run the loop. Commands within loops prompted for by ? are not placed in the history list. Functions like echo, but does not recognize (backslash) escapes and delimits words by null characters in the output. Useful if you want to use the shell to perform file name substitution to expand a list of words. Performs file name and command expansion on the specified word to yield a string of the form label:. The shell rewinds its input as much as possible and searches for a line of the form label:, possibly preceded by spaces or tabs. Execution continues after the line speci- fied by word. Displays the history event list; by default, the oldest events are displayed first. If you specify a number, only the number most recent events are displayed. The -r option reverses the display order to the most recent first, rather than the oldest first. The -h option displays the history list without leading numbers. Use this to produce files suitable for sourcing using the source command. Executes the single command (including its arguments) if the specified expression evaluates TRUE. Variable substi- tution on command happens early, at the same time it does for the rest of the if command. The command argument must be a simple command (rather than a pipeline, command list, alias, or parenthesized command list). Note that input/output redirection occurs even if expression is FALSE and command is not executed. If expression is TRUE, executes the commands following the first then up to the first else; otherwise, if expression2 is TRUE, executes the commands following the second then up to the second else. Any number of else-if pairs are possible; only one endif is needed. The else part is optional. (The words else and endif must appear at the beginning of input lines. The if command must appear alone on its input line or after an else.) This command is no longer sup- ported. See the loader(5) reference page for information on using shared libraries. Lists the active jobs; with the -l option, lists process IDs in addition to job numbers, status, and the command. Sends either the TERM (terminate) signal or the specified signal to the jobs or processes that you specify. Signals are either given by number or by name (as given in /usr/include/sys/sig- nal.h, stripped of the prefix SIG). The signal names are listed by kill -l. There is no default job; specifying kill with no job or PID does not send a signal to the current job. If the signal being sent is SIGTERM (terminate) or SIGHUP (hangup), then the job or process is sent a SIGCONT (continue) signal as well. Limits the usage by the current process and each process it creates not to (individually) exceed maximum_use on the specified resource. If no maximum_use is given, then the current limit is displayed; if no resource is given, then all limitations are given. If the -h option is given, addresspace (the maximum address space in bytes for a process), coredumpsize (the size of the largest core dump that is created), cputime (the maximum number of CPU seconds to be used by each process), datasize (the maxi- mum growth of the data region allowed beyond the end of the program text), descriptors (the maximum number of open files for each process), filesize (the largest single file that can be created), memoryuse (the maximum size to which a process's resident set size can grow), and stacksize (the maximum size of the automatically extended stack region). The maximum_use can be specified as a floating-point or integer number followed by a scale factor: k or kbytes (1024 bytes), m or megabytes, or b or blocks. For both resource names and scale factors, unambiguous prefixes of the names suffice. The scale factor optionally can be separated from the numeric value by a space; 1024k is exactly equivalent to 1024 k. The filesize can be lowered by an instance of csh, but can only be raised by an instance whose effective user ID is root. For more information, refer to the docu- mentation for the ulimit system call. Terminates a login shell and replaces it with an instance of /usr/bin/login. This is one way to log out (included for compatibility with sh). Terminates a login shell. Especially useful if ignoreeof is set. num- bers. Only a user who is root can change the primary group of the shell to one in which the user does not have membership. Any active user-generated shell is terminated when the newgrp command is used. Without arguments, nice sets the priority of commands run in this shell to 4. The +number arguments sets the priority to the specified number. The command argument causes command to run at priority 4 (without the +number argument) or at priority number (if +number is specified). The greater the number, the less CPU the process gets. The superuser can raise the priority by using nice with a negative number. The command is always executed in a sub- shell, and the restrictions placed on commands in simple if statements apply. The first form causes hangups to be ignored for the remainder of the shell script. The second form causes the specified command to be run with hangups ignored. To run a pipeline or list of commands with this form, put the pipeline or list in a shell script, give the script execute permission, and use the shell script as the command. All processes run in the background with & are effectively protected from being sent a hangup signal when you log out, but are still subject to explicitly sent hangups unless nohup is used. Causes the shell to notify you asynchronously when the status of the current (if %job is not specified) or specified jobs changes. Normally, notification is presented immediately before the shell prompt. This is automatic if the notify shell variable is set. Controls the action of the shell on interrupts. The first form restores the default action of the shell on interrupts, which is to terminate shell scripts or to return to the ter- minal command input level. The second form causes all interrupts to be ignored. The third form causes the shell to execute a goto label when it receives an interrupt or when a child process terminates due to an interruption. In any case, if the shell is running in the background and interrupts are being ignored, all forms of onintr have no meaning and interrupts continue to be ignored by the shell and all invoked commands. Pops the directory stack (removes the top entry), changing directories to the new top directory. With a +number argument, popd discards the number entry in the stack. The elements of the directory stack are numbered from the top, starting at 0 (zero). Changes to the directory that comes to the top of the stack. With no arguments, pushd exchanges the top two elements of the directory stack. With a name argument, pushd changes to the new directory (that is, cd) and pushes the old current working directory (given in the cwd shell variable) onto the directory stack. With a numeric argument, pushd rotates the number argument of the directory stack around to be the top element and changes directory to it. The members of the directory stack are numbered from the top, starting at 0 (zero). Causes the internal hash table of the contents of the directories in the path shell variable to be recomputed. This is needed if new commands are added to directories in path while you are logged in. This should be necessary only if commands are added to one of your own directories, or if someone changes the contents of one of the system directories. Executes the specified command, which is subject to the same restrictions as in the simple if statement, count times. Note that input/output redirections occur exactly once, even if count is 0 (zero). This command is no longer supported. See the loader(5) reference page for information on using shared libraries. The first form of the command displays the value of all shell variables. Variables that have values other than a single word are displayed_list. In all cases, the value is command and file name expanded. These arguments can be repeated to set multiple values in a single set command. Note however, that variable expansion happens for all arguments before any setting occurs. Sets the value of the environment vari- able name to be value, a single string. The most commonly used environment variables USER, TERM, HOME, and PATH are automatically imported to and exported from the csh variables user, term, home, and path, so there is no need to use setenv for these common envi- ronment variables. If you modify the LC_COLLATE or LANG environment variables, the current international character support environment and collating sequence are changed as specified for subsequent commands executed from the shell. Shifts to the left the members of argv (discard- ing argv[1]) or the specified variable. An error occurs if argv is not set or has fewer than two strings assigned to it. Causes the shell to read commands from name. You can nest source commands. However, if they are nested too deeply, the shell can run out of file descriptors. An error in a source at any level terminates all nested source commands. Normally, input during source commands is not placed on the history list. The -h option causes the commands to be placed in the history list without being executed. Stops the current (if %job is not specified) or specified job that is executing in the background. Causes the shell to suspend execution by sending itself a stop signal. This command gives an error message if attempted from a login shell. Since csh normally ignores the stop signal, this is the only way of suspending the shell. Successively matches each case label (string1) against string, which is first command and file name expanded. Use the pattern-matching characters *, ?, and [...] in the case labels, which are variable expanded. If none of the labels match before a default label is found, then execution begins after the default label. Each case label and the default label must appear at the beginning of a line. The breaksw command causes execution to continue after the endsw command. Otherwise, control can fall through case labels and the default labels, as in C. If no label matches and there is no default, execution continues after the endsw command. With no argument, displays a summary of time used by this shell and its children. If arguments are given, the specified command is timed and a time summary (as described under the time shell variable) is displayed. If necessary, an extra shell is created to display the time when the command completes. Displays the file creation mask (first form) or sets it to the specified value (second form). The mask is given as an octal value. Common values for the mask are 002, giving all access to the owner and group, and assigning read and execute access to others, or 022, giving all access to the owner, and assigning read and execute access to users in the group and others. Discards all aliases with names that match pattern. Thus, all aliases are removed by unalias *. The absence of aliases that match pattern does not cause an error. Disables the use of the internal hash table to speed location of executed programs. Removes the limitation on resource. If no resource is specified, then all resource limitations are removed. If -h is given, the corresponding hard limits are removed. Only the superuser can do this. Removes all variables with names that match pattern. Use unset * to remove all variables. The absence of variables that match pattern is not an error. Removes all vari- ables with names that match pattern from the environment. See also the setenv command (discussed earlier in this list). Waits for all background jobs to terminate. If the shell is interactive, an interrupt can disrupt the wait, at which time the shell displays the names and job numbers of all jobs known to be outstanding. Takes a list of names and looks for the files which would be exe- cuted had these names been given as commands. This built-in command works like /usr/bin/which if the -U option is given; without the option, the built-in command provides more useful information by identifying shell built-ins and aliases. See which(1) for more information. While expression evaluates as nonzero, executes the commands between the while and the matching end. You can use the break command to terminate the loop prematurely and the continue command to continue the loop. (The while and end must appear alone on their input lines.) If the input is a terminal, prompting occurs the first time through the loop, as for the foreach statement. Brings the specified job into the foreground. Continues the specified job in the background. The first form displays the values of all the shell variables. The second form sets the specified name to the value of expression. If the expression contains <, >, &, or |, at least this part of the expression must be placed within ( ) (parentheses). The third form assigns the value of expression to the indexth argument of name. Both name and its indexth component must already exist. C operators, such as *= and +=, are available. White space separating the name from the assignment operator is optional. Spaces are, however, mandatory in separating components of expression, which would otherwise be single words. Special postfix ++ and - - operators increment and decrement name, respectively, for example @ i++. Expressions The built-in commands @, exit, if, and while accept expressions that include operators similar to those of C, but with a precedence from right to left instead of from left to right. The following operators are available: ( ) ~ ! * / % + - << >> <= >= < > == != =~ !~ & ^ | && || In the preceding list, operators of equal precedence appear on the same line, below those lines containing operators (if any) that have greater precedence, and above those lines containing operators having lesser precedence. The ==, !=, =~, and !~ operators compare their arguments as strings; all others operate on numbers. The =~ and !~ operators are similar to != and ==, except that the rightmost side is a pattern against which the left-hand operand is matched. This reduces the need for use of the switch statement in shell scripts when all that is really needed is pattern matching. Null or missing arguments are considered 0 (zero). The result of all expressions are strings, which represent decimal numbers. It is impor- tant to note that no two components of an expression can appear in the same word. Except when next to components of expressions that are syntactically significant to the parser (&, |, <, >, -, (, and ) ) expression components should be surrounded with spaces. Also available in expressions as primitive operands are command executions enclosed in { and } and file inquiries of the form -l name where l is one of the following: Read access Write access Execute access Existence Ownership Zero size Plain file Directory Symbolic link The specified file is command and file name expanded and then tested to see if it has the specified relationship to the real user. If the file does not exist or is inaccessible, then all inquiries return FALSE, that is, 0 (zero). Command executions succeed, returning TRUE(1), if the command exits with status 0 (zero); otherwise, they fail, returning FALSE(0). If more detailed status information is required, execute the command outside of an expression and examine the status shell variable. Predefined and Environment Variables The following variables have special meaning to the shell. Of these, argv, cwd, home, path, prompt, shell, and status are always set by the shell. Except for cwd and status, this setting occurs only at initialization; the remaining variables maintain their settings unless you explicitly reset them. The csh command copies the USER environment variable into the variable user, TERM into term, and HOME into home, and copies these back into the environment whenever the normal shell variables are reset. The PATH environment variable is handled similarly; it is not necessary to worry about their settings other than in the file. Each csh subprocess imports the definition of path from the environment, and exports it again if you then change it. Is set to the arguments to the shell. It is from this variable that positional parameters are substituted, for example, $1 is replaced by $argv[1], and so on. If autologout is set to a value greater than 0 (zero), the shell terminates if a com- mand is not entered within the prescribed number of minutes after issuing the shell prompt. Auto-logout is enabled by default if the shell runs as a login shell and if the standard input stream is not a pseudo tty and the DISPLAY environment variable is not set. Auto-logout can be disabled by adding the following line to your or file: set autologout = 0 Gives a list of alternate directories to be searched to find subdirectories in chdir commands. Is set to the full path name of the current directory. Causes each command and its arguments to be echoed to standard output just before it is executed. It is set when the -x command line option is specified. For nonbuilt-in commands, all expansions occur before echoing. Built-in commands are echoed before command and file name substitution, since these substitutions are then done selectively. Enables file name completion. Changes the characters used in history substitution when given a string value. The first character of its value is used as the history substitution character, replacing the default character ! (exclamation point). The second charac- ter of its value replaces the character ^ (circumflex) in quick substitutions. Controls the existence and size of the history buf- fer. All commands (executable or not) are saved in the history buffer. Values of history that are too large can run the shell out of memory. The last executed command is always saved on the history list even if history is left unset. Contains the absolute path name to the home directory of the user, initialized from the environment. The file name expansion of ~ (tilde) refers to this vari- able. Causes the shell to ignore End-of-File characters from input devices that are terminals. This prevents shells from acciden- tally being killed when they read an End-of-File character.. Specifies the collating sequence to use when sorting names and when character ranges occur in patterns. The default value is the collating sequence for American English. Specifies the character classification information to use on your system. The default value is American English. Specifies the language that the system expects for user input of yes and no strings. The default value is American English. Specifies the monetary format for your system. The default value is the monetary format for American English. Specifies the numeric format for your system. The default value is the numeric format for American English. Specifies the date and time format for your system. The default value is the date and time format for American English. Specifies the files where the shell checks for mail. This is done after each command completion that results in a prompt, if a spec- ified interval has elapsed. The shell displays the message You have new mail if the file has been modified since the last check. If the first word of the value of mail is numeric, it specifies a different mail checking interval (in seconds) than the default (10 minutes). If you specify multiple mail files, the shell displays the message New mail in file when there is mail in file. Specifies a list of directories to search to find message catalogs. If set, places restrictions on output redirection to ensure that files are not accidentally destroyed, and that >> redirections refer to existing files. (See also Redirecting Input and Output.) If set, inhibits file name expansion. This is most useful in shell scripts that do not deal with file names, or after a list of file names is obtained and further expansions are not desirable. If set, does not return an error for a file name expansion that does not match any existing files; rather, the primitive pattern is returned. It is still an error for the primitive pattern to be malformed, for example, echo [ still gives an error. If set, causes the shell to notify you asynchronously of background job completion. The default is to present job status changes immediately before printing a prompt. Each word of the path variable specifies a directory in which commands are to be sought for execution. A null word specifies the current directory. If no path variable is set, then only full path names are executed. The usual search path is the current directory and /usr/bin, but this can vary from system to system. A shell that is given neither the -c nor the -t option normally hashes the contents of the directories in the path variable after reading and each time the path variable is reset. If new commands are added to these directories while the shell is active, it is necessary to execute the rehash command in order to access the new commands. The string that is printed before each command is read from an interactive terminal input. If a ! (exclamation point) appears in the string, it is replaced by the current event number, unless it is preceded by a (backslash). The default prompt is %, # for the superuser. When given a numeric value, con- trols the number of entries of the history list that are saved in ~/.history when you log out. All commands (executable or not) that are in the history list are saved. During startup, the shell sources ~/.history into the history list, enabling history to be saved across logins. Very large values of savehist slow down the shell during startup. The file in which the shell resides. This is used in forking shells to interpret files that have execute bits set, but that are not executable by the system. (See Nonbuilt-In Command Execution.) This is initialized to the (system-dependent) location of the shell. The status returned by the last command. If it terminated abnormally, then 0200 is added to the status. Built-in commands that fail return exit status 1; all other built-in com- mands set status 0 (zero). Controls automatic timing of commands, and the line displayed by a built-in time command. The value can consist of zero, one, or two words. The first word is the threshold for automatic timing, measured in CPU seconds; for any command that takes at least that many CPU seconds, the shell displays a line showing the timing information when that command finishes. The second word is a string, enclosed in ' ' (single quotes) or " " (double quotes), specifying the timing line to be displayed; it controls both the automatic display and the output of the time command. The string can contain any combination of text as well as the following specifiers, which must be uppercase characters and preceded by a % (percent sign) as shown. Sequences such as are not treated as special characters in the string. Kilobytes of data space. Elapsed time, measured in seconds. Number of page faults. Number of blocks read during I/O operations. Kilobytes of stack space. Total kilobytes of memory. Number of blocks writ- ten during I/O operations. CPU time (both system and user) as a percentage of elapsed time. System time: CPU seconds used by sys- tem calls. User time: CPU seconds used by the process outside of system calls. Number of times the process was swapped. Kilobytes of text space. If the first word is zero or if the time variable is set with no value, every command is timed. The default string displayed, when the second word is not supplied, is as follows: %Uu %Ss %E %P% %X+%Dk %I+%Oio %Fpf+%Ww Causes the words of each command to be displayed on the standard output after history substi- tution. Set by the -v command line option. Nonbuilt-In Command Execution When a command to be executed is found not to be a built-in command, the shell attempts to execute the command with the execv() system call. Each word in the path shell variable names a directory from which the shell attempts to execute the command (if the command does not begin with a / (slash)). If it is given neither a -c nor a -t option, the shell hashes the names in these directories into an internal table so that it only tries an execv in a directory if there is a possibility that the command resides there. This greatly speeds command location when a large number of directories are present in the search path. If this mechanism was turned off (with unhash), or if the shell was given a -c or -t argument (and in any case, for each directory component of path that does not begin with a /), the shell concatenates the directory name with the given command name to form a path name of a file, which it then attempts to execute. Commands in parentheses are always executed in a subshell. Thus, (cd ; pwd) ; pwd displays the home directory and then the current direc- tory, without changing the current directory location; whereas, cd ; pwd changes the current directory location to the home directory, and prints the home directory. Commands in parentheses are most often used to prevent chdir from affecting the current shell. If the file has execute permissions but is not an executable binary to the system, then it is assumed to be a file containing shell com- mands and a new shell is created to read it. If there is an alias for shell, then the words of the alias are prefixed to the argument list to form the shell command. The first word of the alias should be the full path name of the shell (for example, $shell). Note that this is a special, late-occurring case of alias sub- stitution and only allows words to be prefixed to the argument list without modification. Signal Handling The shell normally ignores SIGQUIT signals. Jobs running in the background (either by & or the bg or %...& commands) are immune to signals generated from the keyboard (SIGINT, SIGQUIT, and SIGHUP). Other signals have the values the shell inherited from its parent. You can con- trol the shell's handling of interrupts and terminate signals in shell scripts with onintr. Login shells catch the SIGTERM (terminate) sig- nal; otherwise, this signal is passed on to children from the state in the shell's parent. In no case are interrupts allowed when a login shell is reading the file. Limitations The following are csh limitations: Words can be no longer than 1024 bytes. Argument lists are limited to 38912 bytes. However, the argu- ment list space is shared with the space for environment variables; having a large list of environment variables can severely limit the allowable argument list length. The number of arguments to a command that involves file name expansion is limited to 1/6th the number of characters allowed in an argument list. Command substitutions can substitute no more characters than are allowed in an argument list. To detect looping, the shell restricts the number of alias substitutions on a single line to 20. Words can also be separated by double spa- ces. Character Classes You can use the following notation to match file names within a range indication: [:charclass:] This format instructs the system to match any single character belonging to charclass; the defined classes correspond to ctype() subrou-. RESTRICTIONS
Due to problems with the getrusage system call, csh incorrectly returns a value of 0 for each of the following fields when the built-in time(3) function or the time shell variable is used: %D Kilobytes of data space %F Number of page faults %K Kilobytes of stack space %W Number of times the process was swapped %X Kilobytes of text space RETURN VALUES
For information about return values, see the following sections: sallyShell Commands, Expressions, Predefined and Environment Variables, and OPTIONS. FILES
C shell startup file; read at beginning of execution by each C shell. Read by login shell (after Read by login shell at logout. The path to the default shell. Temporary file for <<. Contains user information. SEE ALSO
Commands: alias(1), bg(1), cd(1), echo(1), fg(1), hash(1), jobs(1), kill(1), ksh(1), newgrp(1), nice(1), nohup(1), sh(1), Bourne shell sh(1b), POSIX shell sh(1p), time(1), ulimit(1), umask(1), unalias(1), wait(1) Functions: access(2), chdir(2), exec(2), fork(2), getrlimit(2), pipe(2), umask(2), wait(2) Files: locale(4), null(7) Miscellaneous: loader(5) Command and Shell User's Guide csh(1) | https://www.unix.com/man-page/osf1/1/csh/ | CC-MAIN-2021-43 | refinedweb | 13,409 | 62.68 |
Took the Virtual Campus Creating Python Scripts for Raster Analysis, and the exercise shows me how to enter raster processing steps in the ArcGIS Pro python window, then at the end of the exercise, how to save the window contents to a python file so I could run it in a IDE or tool. I opened the file in IDLE, edited it, tried to run it, but the line "slopeRaster2 = sa.Slope(baseRaster,'DEGREE')" kept blowing up on me. I got it to work by changing the Slope line to arcpy.sa.Slope instead. It seemed to me that in IDLE, Slope might have been going to Slope_3d by default which has two required arguments, inraster and outraster, while sa.Slope only has one required argument. "DEGREE" wasn't working in Slope_3D which thought it was supposed to be the outraster.
The script exported from the exercise:
# coding: utf-8
import arcpy
from arcpy import *
baseRaster = Raster('DEM_elkhorn.tif')
baseRaster.maximum
# 2856.9016113281
baseRaster.minimum
# 2174.0673828125
baseRaster.noDataValue
# -3.4028230607370965e+38
slopeRaster = Slope('DEM_elkhorn.tif', 'DEGREE')
# Traceback (most recent call last):
# File "<string>", line 1, in <module>
# NameError: name 'Slope' is not defined
from arcpy.sa import *
slopeRaster = Slope('DEM_elkhorn.tif', 'DEGREE')
gThan40 = slopeRaster > 40
cliff = baseRaster - baseRaster.mean
cliffPresent = arcpy.sa.GreaterThan(cliff,160)
FalconHabitat = gThan40 & cliffPresent
FalconHabitat.save("C:\\EsriTraining\\PythonScriptsRaster\\Data\\HabitatOutput.tif")
After editing a bit to clean up:
import arcpy
from arcpy import *
from arcpy.sa import *
import arcpy.sa
baseRaster = Raster("C:\\EsriTraining\\PythonScriptsRaster\\Data\\DEM_elkhorn.tif")
#slopeRaster = Slope('C:\\EsriTraining\\PythonScriptsRaster\\Data\\DEM_elkhorn.tif', 'DEGREE')
slopeRaster2 = sa.Slope(baseRaster,'DEGREE')
gThan402 = slopeRaster > 40
cliff2 = baseRaster - baseRaster.mean
cliffPresent2 = arcpy.sa.GreaterThan(cliff,160)
FalconHabitat2 = gThan40 & cliffPresent
#FalconHabitat2.save("C:\\EsriTraining\\PythonScriptsRaster\\Data\\HabitatOutput2.tif")
I would have thought that the lines 1-4 trying every which way to import sa would have been sufficient, but line 6 kept blowing up, and going to line 7 using sa.Slope still wasn't good enough.
But this worked:
# coding: utf-8
#HabitatScriptEd3.py
#Created on 8/03/2018 by PH
#From exercise in ESRI Virtual Campus Course Creating Python Scripts for Raster Analysis
import arcpy
from arcpy import *
from arcpy.sa import *
arcpy.CheckOutExtension("spatial")
baseRaster = Raster("C:\\EsriTraining\\PythonScriptsRaster\\Data\\DEM_elkhorn.tif")
#slopeRaster = Slope('C:\\EsriTraining\\PythonScriptsRaster\\Data\\DEM_elkhorn.tif', 'DEGREE')
slopeRaster = Slope(baseRaster, 'DEGREE')
#slopeRaster2 = arcpy.sa.Slope(baseRaster,'DEGREE')
gThan402 = slopeRaster > 40
cliff2 = baseRaster - baseRaster.mean
cliffPresent2 = arcpy.sa.GreaterThan(cliff2,160)
FalconHabitat2 = gThan402 & cliffPresent2
#FalconHabitat2.save("C:\\EsriTraining\\PythonScriptsRaster\\Data\\HabitatOutput2.tif")
So apparently, the three imports aren't enough to make sa available in a script running outside the Python window. I also need to check out the spatial extension.
Along the way, I learned there is a different Python version installed for ArcMap 10.6.1 (Python 2.7.14) and for ArcPro 2.2 (Python 3.6.5). You can find the two different versions of IDLE and run the one that is appropriate by searching way down in Program files for idle.pyw. But an easy way to launch the correct version of IDLE is to examine the folder containing the script in File Explorer, right click, and there is a choice provided on which version to use.
But it turns out with the full name to the Slope method, the script will run in python 2.7.14, the version from ArcMap 10.6.1.
I have SA licensed in Pro with a local license server, concurrent licensing. But how does python in IDLE know this?
I was real hopeful that was the answer since that's exactly my situation. But I got the same error as before. It seems that sa must be getting loaded because print (baseRaster.maximum) returns an answer. The error message seems indicate that python thinks Slope is a variable name that python doesn't know about. But it is not that Slope shouldn't be capitalized. | https://community.esri.com/thread/219120-why-doesnt-sa-slope-get-called-as-expected-in-python-script | CC-MAIN-2018-34 | refinedweb | 657 | 52.36 |
18582/how-can-i-get-laplacian-pyramid-using-opencv
I'm trying to get a layer of the Laplacian pyramid using the opencv functions: pyrUp and pyrDown.
In the documentation and in more detail in this book, I found that the i-th Laplacian layer should be obtained by the following expression:
Li = Gi - pyrDown(Gi+1)
where Gi is the i-th layer of the Gaussian pyramid.
What I've tried is:)
But I get different sizes of the images involved in the substraction. I don't understand it because pyrUp is suppposed to invert the process of the Gaussian pyramid, i.e. pyrDown (with a lose of information of course but that should not affect the size, right?).
UPDATE
I refactored my code to:
def get_laplacian_pyramid_layer(img, n):
'''Returns the n-th layer of the laplacian pyramid'''
currImg, i = img, 0
while i < n: # and currImg.size > max_level (83)
down, up = new_empty_img(img.shape), new_empty_img(img.shape)
down = cv2.pyrDown(img)
up = cv2.pyrUp(down, dstsize=currImg.shape)
lap = currImg - up
currImg = down
i += 1
return lap
As you can see, I force the destination image to be of the same size of the source with the parameter dstsize of the pyrUp function.
However, this code also gives me an error when when executing the pyrUp function. The message of the error is:
OpenCV Error: Assertion failed (std::abs(dsize.width - ssize.width*2) == dsize.width % 2 && std::abs(dsize.height - ssize.height*2) == dsize.height % 2) in pyrUp_,
OpenCV Error: Assertion failed (std::abs(dsize.width - ssize.width*2) == dsize.width % 2 && std::abs(dsize.height - ssize.height*2) == dsize.height % 2) in pyrUp_,
In debug mode I checked the expression of the assertion with:
up.shape[1]-down.shape[1]*2 == up.shape[1] %2 and up.shape[0]-down.shape[0]*2 == up.shape[0] %2
and it is satisfied.
So, I don't have a clue of what is happening.
As far as I can see you use pyrDown on your input image img in every iteration
down = cv2.pyrDown(img)
I suggest youTheeThe problem is that you're iterating ...READ MORE
Actually in later versions of pandas this ...READ MORE
Hi there, instead of sklearn you could ...READ MORE
Solution
My 50 cents for getting a pip freeze-like ...READ MORE
Building on Alexander-Reynolds answer above, here is ..
Here am talking about my example you ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/18582/how-can-i-get-laplacian-pyramid-using-opencv?show=18585 | CC-MAIN-2020-34 | refinedweb | 412 | 67.25 |
![: am3359
Tool/software: Starterware
Hi TI,
AM335x starter kit, starterware, CCS Version: 7.2.0.00013
I am working on starterware with AM335x starter kit. Below is the test program on clock() function.
#include <stdio.h>#include <time.h>int main(int argc, char *argv[]){ int i; clock_t t_start, t_stop, t_overhead; t_start = clock (); for (i = 0; i < 10000000; ++i) // dummy for loop ; t_stop = clock (); t_overhead = t_stop - t_start; printf("took: %ld CPU time\n", (long) t_overhead); return 0;}
console output: [CortxA8] took: 0 CPU time
search on e2e, and found similar thread, such as below from 4 years ago,
e2e.ti.com/.../303963
It mentioned "In your CCS Debug view--->Target menu, go to Clock and select Enable." However, CCS7 seems changed a lot, and I cannot find the right location to enable this Clock. (if I missed, please help to provide a screenshot for my instruction)
I also tried to replace the "dummy for loop" by my already working project codes, in case CCS7 optimizing out the "dummy for loop". Though it didn't help either.
Please advise, Thanks in advance.
M yang:. | http://e2e.ti.com/support/embedded/starterware/f/790/p/623551/2309607 | CC-MAIN-2018-30 | refinedweb | 183 | 69.52 |
Opened 8 years ago
Closed 6 years ago
#15308 closed defect (fixed)
init.sage file is not read when starting the notebook
Description
See. This problem seems to have been introduced in #14523.
Change History (14)
comment:1 Changed 7 years ago by
- Milestone changed from sage-6.1 to sage-6.2
comment:2 Changed 7 years ago by
- Milestone changed from sage-6.2 to sage-6.3
comment:3 Changed 7 years ago by
comment:4 Changed 7 years ago by
Afaik attach doesn't work on the notebook.
Your problem seems to be that
init.sage is evaluated before Sage is started. A workaround might be to use a
.py file starting with
from sage.all import *
comment:5 Changed 7 years ago by
- Milestone changed from sage-6.3 to sage-6.4
comment:6 Changed 7 years ago by
- Component changed from misc to notebook
- Report Upstream changed from N/A to Reported upstream. Developers acknowledge bug.
Upstream at though I'm not sure if it's identical to the init.sage issue.
comment:7 Changed 7 years ago by
I appear to have a fix upstream; comments welcome there. Somehow the change in #14523 in the definition of
attach from
import preparser for filename in files: preparser.load(filename, globals(), attach=True)
to
try: ipy = get_ipython() except NameError: ipy = None global attached for filename in files: if ipy: code = load_wrap(filename, attach=True) ipy.run_cell(code) else: load(filename, globals(), attach=True)
did this. Probably that should really be fixed in Sage, but I don't want to mess around with two fixes.
Can anyone think of why either adding that global (which one would think wouldn't clobber
all globals, such as
Integer?) or having the command-line code would be a problem? Really, neither one should in principle cause a problem. But it does.
comment:8 Changed 7 years ago by
Indeed, a little more testing shows that
globals() is definitely not the usual Sage globals at that point - it is just the globals for that module, including the things that were imported like
os and the builtins. E.g.
'{\'load\': <function load at 0x1054cc488>, \'load_attach_path\': <function load_attach_path at 0x110d99e60>, \'reload_attached_files_if_modified\': <function reload_attached_files_if_modified at 0x110d9f2a8>, ... \'__doc__\': \'\\nKeep track of attached files\\n\\nTESTS::\\n\\n sage: attach(\\\'\\\')\\n Traceback (most recent call last):\\n ...\\n ... \'load_wrap\': <function load_wrap at 0x1054cc500>, \'load_attach_mode\': <function load_attach_mode at 0x110d99de8>, \'__builtins__\': {\'bytearray\': <type \'bytearray\'>, \'IndexError\': <type \'exceptions.IndexError\'>, ...}, ... \'os\': <module \'os\' from \'/Users/.../sage/local/lib/python/os.pyc\'>, \'modified_file_iterator\': <function modified_file_iterator at 0x110d9f230>}'
Zoinks!
comment:9 Changed 7 years ago by
From the Python doc:
Remember that at module level, globals and locals are the same dictionary.
But on the other hand nothing really changed. Except maybe that it was in a Cython file, and now is in a Python file?
comment:10 Changed 7 years ago by
- Report Upstream changed from Reported upstream. Developers acknowledge bug. to Completely fixed; Fix reported upstream
Fix upstream at
comment:11 Changed 7 years ago by
- Cc ppurka novoselt added
This is 100% ready to go, just need a reviewer upstream!
comment:12 Changed 6 years ago by
- Milestone changed from sage-6.4 to sage-duplicate/invalid/wontfix
- Reviewers set to Karl-Dieter Crisman
- Status changed from new to needs_review
This was fixed and is now in a merged package.
comment:13 Changed 6 years ago by
- Status changed from needs_review to positive_review
comment:14 Changed 6 years ago by
- Resolution set to fixed
- Status changed from positive_review to closed
An example of output caused by this bug is:
Traceback (most recent call last): #The OrthogonalCurvilinearOutput?.sage file will output the coefficients and differential operators defined
NameError?: name 'var' is not defined | https://trac.sagemath.org/ticket/15308 | CC-MAIN-2021-31 | refinedweb | 625 | 66.74 |
Note: The current release is NetBeans IDE 6.5. If you are
using NetBeans IDE 6.5, see NetBeans IDE 6.5 Java Quick Start Tutorial.
Welcome, build,.
To follow class for you.
You can add the "Hello World!" message to the
skeleton code by replacing the line:
// TODO code application logic here
System.out.println("Hello World!");
Save the change by choosing File > Save.
The file should look something like the following:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworldapp;
/**
*
* @author Sonya Bannister
*/
public class HelloWorldApp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
To compile your source file, choose Build > Build Main Project (F11) from the IDE's main menu.
You can view the output of the build process by choosing Window > Output > Output. (F6).
The next figure shows what you should now see.
Congratulations! Your program works!
You now know how to accomplish some of the most common programming tasks in the IDE.
For a broader introduction to useful IDE features that are generally applicable to Java | http://www.netbeans.org/kb/60/java/quickstart.html | crawl-002 | refinedweb | 187 | 68.77 |
Spark Integration
GraphLab Create has the ability to convert Apache Spark's Resilient Distributed Datasets (RDD) to an SFrame and back.
Setup the Environment
To use GraphLab Create within PySpark, you need to set the
$SPARK_HOME and
$PYTHONPATH environment variables on the driver. A common usage:
export PYTHONPATH=$SPARK_HOME/python/:$SPARK_HOME/python/lib/py4j-0.8.2.1-src.zip:$PYTHONPATH export SPARK_HOME =
Run from the PySpark Python Shell
cd $SPARK_HOME bin/pyspark
Run from a standard Python Shell
Make sure you have exported the
PYTHONPATH and
SPARK_HOME environment variables. Then run (for example):
ipython
Then you need to start spark:
from pyspark import SparkContext from pyspark.sql import SQLContext # Launch spark by creating a spark context sc = SparkContext() # Create a SparkSQL context to manage dataframe schema information. sql = SQLContext(sc)
Make an SFrame from an RDD
from graphlab import SFrame rdd = sc.parallelize([(x,str(x), "hello") for x in range(0,5)]) sframe = SFrame.from_rdd(rdd, sc) print sframe
+---------------+ | X1 | +---------------+ | [0, 0, hello] | | [1, 1, hello] | | [2, 2, hello] | | [3, 3, hello] | | [4, 4, hello] | +---------------+ [5 rows x 1 columns]
Make an SFrame from a Dataframe (preferred)
from graphlab import SFrame rdd = sc.parallelize([(x,str(x), "hello") for x in range(0,5)]) df = sql.createDataFrame(rdd) sframe = SFrame.from_rdd(df, sc) print sframe
+----+----+-------+ | _1 | _2 | _3 | +----+----+-------+ | 0 | 0 | hello | | 1 | 1 | hello | | 2 | 2 | hello | | 3 | 3 | hello | | 4 | 4 | hello | +----+----+-------+ [5 rows x 3 columns]
Make an RDD from an SFrame
from graphlab import SFrame sf = gl.SFrame({'x': [1,2,3], 'y': ['fish', 'chips', 'salad']}) rdd = sf.to_rdd(sc) rdd.collect()
[(0, '0', 'hello'), (1, '1', 'hello'), (2, '2', 'hello'), (3, '3', 'hello'), (4, '4', 'hello')]
Make a DataFrame from an SFrame (preferred)
from graphlab import SFrame sf = gl.SFrame({'x': [1,2,3], 'y': ['fish', 'chips', 'salad']}) df = sf.to_spark_dataframe(sc,sql) df.show()
+---+-----+ | x| y| +---+-----+ | 1| fish| | 2|chips| | 3|salad| +---+-----+
Requirements and Caveats
The currently release requires Python 2.7, Spark 1.3 or later, and the
hadoopbinary must be within the
PATHof the driver when running on a cluster or interacting with
Hadoop(e.g., you should be able to run
hadoop classpath).
We also currently only support Mac and Linux platforms but will have Windows support soon.
- The GraphLab integration with Spark supports Spark execution modes
local,
yarn-client, and standalone
spark://<hostname:port>. ("yarn-cluster" is not available through PySpark)
Recommended Settings for Spark Installation on a Cluster
We recommend downloading
Pre-built for Hadoop 2.4 and later version of Apache Spark.
Notes
- RDD conversion works with GraphLab Create right out of the box. No additional Spark setup is required. When you install GraphLab Create, it comes with a JAR that enables this feature. To find the location of the JAR file, execute this command:
graphlab.get_spark_integration_jar_path()
GraphLab Create can only convert to types it supports. This means that if you have an RDD with Python types other than int, long, str, list, dict, array.array, or datetime.datetime (image is not supported for conversion currently), your conversion may fail (when using Spark locally, you may get lucky and successfully convert an unsupported type, but it will probably fail on a YARN cluster).
SFrames fit most naturally with DataFrame. Both have strict column types and a they have a similar approach to storing data. This is why we also have a graphlab.SFrame.to_spark_dataframe method. The graphlab.SFrame.from_rdd method works with both DataFrame and any other rdd, so there is no
from_dataframemethod. | https://turi.com/learn/userguide/data_formats_and_sources/spark_integration.html | CC-MAIN-2017-09 | refinedweb | 586 | 64.91 |
This add-in permits you to define strings into a ResourceDictionary of your project and use them in code just like you could do with RESX files. In this way, during localization process, you don't have to merge satellite DLLs.
ResourceDictionary
The core of the utility is StringsResourceGeneratorTask, a custom task that runs the BeforeBuild step of MSBuild. You can use the task without the StringsResourceGenerator add-in, installing the DLL in the GAC and editing your project file manually. At the bottom of the project file, as children of the Project node, you have to add:
<UsingTask
TaskName="StringsResourceGeneratorTask"
AssemblyName="StringsResourceGeneratorTask,
Version=1.0.0.0,
Culture=neutral,
PublicKeyToken=157d1456ea169140" />
<Target
Name="BeforeBuild">
<StringsResourceGeneratorTask
Namespace="YourNamespace"
AssemblyName="YourAssembly"
ClassName="YourClassName"
StringsResourceFileName="YourRelativeFileNamePath" />
</Target>
For information on the UsingTask and Target tags, see the "References" section. The StringsResourceGeneratorTask tag defines the custom tag, and its attributes, the properties. The Namespace attribute specifies the namespace of the class that will be created. The AssemblyName attribute defines the assembly of your project. ClassName is the name of the class that will be generated. StringsResourceFileName is the relative path of the files XAML and CS (for example, if the files are called LocalizableStrings.xaml and LocalizableStrings.xaml.cs under "Folder1", the value of StringsResourceFileName will be "Folder1/LocalizableStrings", extension is not necessary).
UsingTask
Target
StringsResourceGeneratorTask
Namespace
AssemblyName
ClassName
StringsResourceFileName
Reload the project. A dialog will appear:
Choose "Load project normally".
The task can generate code for C# only, but it's easy to expand it for other languages. You have to inherit from the TypeCodeController class and override the StringsCodeTemplate property and the GeneratePropertyCode function. The CSController class, used to generate the C# code, is an example.
TypeCodeController
StringsCodeTemplate
GeneratePropertyCode
CSController
In the project, you have to insert a .xaml file and a .cs file. The .cs file must be in the same path as the XAML file and have the same name, with the extension .xaml.cs.
The simpler way to obtain it is to insert a WPF UserControl. In the XAML, replace all with an empty ResourceDictionary with a reference to the MsCorlib library and a prefix "system" for the namespace. The prefix system is very important because it will be used by the custom task:
system
<ResourceDictionary
xmlns="
xmlns:x="
xmlns:
</ResourceDictionary>
In the C# file, remove all. If you want to add a string, go to the XAML file and add:
system:String x:
And, compile the project (see "Known Bugs"). Now, if you want to show a MessageBox, you can write:
MessageBox
MessageBox.Show(YuourClassName.MyString);
In Documentation.zip, there is a doc file "How to use StringsResourceGeneratorTask" that explains the settings of the task in a detailed way.
Here is the scheme for the task:
This add-in adds an item in the Tools main menu with the name "StringsResourceGenerator...". You must select an item or a folder in the project in which you want to add the XAML and cs files for managing the strings from code. Then, you click the add-in item. A dialog appears:
StringsResourceFileName represents the files name for the ResourceDictionary and code. For example, if you choose LocalizableStrings, two files will be added in the project: LocalizableStrings.xaml and LocalizableStrings.xaml.cs.
LocalizableStrings
Namespace is the namespace in which the class will be added. AssemblyName is the name of the assembly generated by the compile process. ClassName represents the name of the class that will be generated. Once you have generated the files, you can modify (or delete) the file name or class name, but manually, you have to edit the project file and change the attributes related to StringsResourceGeneratorTask. The add-in uses a template for adding the files to the project. The template, during installation, will go under Visual Studio 2008 C# item templates. There isn't a template for VB.
Visual Studio 2008 is the environment fully supported. If you use Visual Studio 2005, you can use the custom task only and set it manually (see "The Custom Task for MSBuild").
Support for VB projects.
After adding the XAML and cs files with the Add-in menu item, the first compilation doesn't work. After the second one, all works correctly. If your project doesn't have WindowsBase and PresentationFramework as references, you have to add them manually. If you select the project root, the add-in doesn't work! You have to select an item or a folder. If you modify or delete resource files previously created, the project file isn't updated automatically.
WindowsBase
PresentationFramework
For the Custom Task:
For the Add-in. | https://www.codeproject.com/Articles/26440/StringsResourceGenerator-Custom-Task-Add-in-for-ma?msg=2724005 | CC-MAIN-2017-09 | refinedweb | 768 | 57.06 |
The Java Specialists' Newsletter
Issue 1262006-05-14
Category:
Language
Java version: JDK 1.3+
GitHub
Subscribe Free
RSS Feed
Welcome to the 126th edition of The Java(tm) Specialists' Newsletter, which I wrote whilst
sitting in a train driving through the Black Forest in Germany,
en route to visiting my brother. According to Encarta, the
Black Forest has 22,950 km of long-distance paths, making it a
great place for cycling, hiking and cross-country skiing. This
week I am in Karlsruhe, so please let me know if you would like
to meet one evening for a beer and chat.
NEW:
Please see our new "Extreme Java" course, combining
concurrency, a little bit of performance and Java 8.
Extreme Java - Concurrency & Performance for Java 8.
The topic for this newsletter was inspired by Rodolphe Huard
from Montpellier in France. Rodolphe sent me an email reminding
me of the problem of an incorrectly coded equals()
method in proxies. Special care needs to be taken to ensure
its correctness.
Since my train is bumping me through the Black Forest, let's
define a Forest interface and a ForestImpl class:
public interface Forest {
String getColour();
}
public class ForestImpl implements Forest {
private final String colour;
public ForestImpl(String colour) {
this.colour = colour;
}
public String getColour() {
return colour;
}
}
We are going to create a dynamic proxy of the Forest that will
wrap the ForestImpl. For our example, we are not going to add
any additional functionality or control to the proxy object.
To create a dynamic proxy, we need an InvocationHandler that
takes care of method calls and delegates them to the wrapped
object.
import java.lang.reflect.*;
public class DelegationHandler implements InvocationHandler {
private final Object wrapped;
public DelegationHandler(Object wrapped) {
this.wrapped = wrapped;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("Called: " + method);
return method.invoke(wrapped, args);
}
}
In our test code, we create two proxy instances that are
wrapping the same object. We would expect the objects to be
different, but the equals() to be the same. But this is not
what happens:
import java.lang.reflect.Proxy;
public class ProxyEquality {
public static void main(String[] args) {
DelegationHandler dh = new DelegationHandler(
new ForestImpl("Black"));
Forest i0 = make(dh);
Forest i1 = make(dh);
System.out.println(i0 == i1); // should be false
System.out.println(i0.equals(i1)); // should be true
}
private static Forest make(DelegationHandler dh) {
return (Forest) Proxy.newProxyInstance(
Forest.class.getClassLoader(),
new Class[] {Forest.class}, dh);
}
}
The output however is different to what we would expect. The
equals() method does get called, but it returns "false".
false
Called: public boolean Object.equals(Object)
false
If we want to compare on object identity inside our equals()
method (i.e. with "=="), then we might try this:
public class ForestImpl implements Forest {
private final String colour;
public ForestImpl(String colour) {
this.colour = colour;
}
public String getColour() {
return colour;
}
public boolean equals(Object obj) {
return this == obj;
}
}
However, this does not work, because we are comparing the
wrapped object to a proxy object, which is obviously false. You
can verify this by changing the equals() method to this:
public boolean equals(Object obj) {
System.out.println(System.identityHashCode(obj));
System.out.println(System.identityHashCode(this));
return this == obj;
}
This means that we will have to write a proper equals method,
one that takes object identity into account using some fields.
(Don't forget to pair the equals() and hashCode() methods).
This should work, right?
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ForestImpl)) return false;
return colour.equals(((ForestImpl) o).colour);
}
When we run it, the equals() method still returns "false"!
It actually fails on the instanceof
test. The object we are
comparing ourselves to is the proxy object, not the wrapped
object. We therefore need to change the test to look at the
common interface:
instanceof
One disadvantage is that we have to now expose our object's
identifying state so that we can compare it. In Java, we can
access private fields of other objects of the same type, as is
typically done in the classical equals method. However, if we
are comparing on the interface level, we need to expose the
internal identifying state in the interface:
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Forest)) return false;
Forest forest = (Forest) o;
return colour.equals(forest.getColour());
}
There is a workaround that would help you to avoid exposing the
identity state of the object to the public. This might be
important to you, but would obviously complicate matters a bit.
We start by defining an interface for comparing objects:
public interface ProxyEquals {
boolean equalsCallBack(Object o, boolean calledOnWrappedObject);
}
We let the Forest interface extend the ProxyEquals interface and
implement it in the ForestImpl class:
public boolean equals(Object o) {
return equalsCallBack(o, false);
}
public boolean equalsCallBack(Object o, boolean calledOnWrappedObject) {
if (!(o instanceof Forest)) return false;
Forest forest = (Forest) o;
if (calledOnWrappedObject) {
if (!(forest instanceof ForestImpl)) return false;
return colour.equals(((ForestImpl)o).colour);
} else {
return forest.equalsCallBack(this, true);
}
}
This more complicated mechanism now returns "true" when we run
the ProxyEquality test class, without us needing to expose the
inner state of our objects.
This morning was the first time that I sat in a Porsche. My
buddy Marcus, whom I am staying with in Karlsruhe, took me to
the train station and demonstrated the cornering to me. "I want
one" best describes my sentiments. This was the first vehicle
I sat in that cornered better than my Alfa 156. Problem in
South Africa is that such vehicles get slapped with a
prohibitive import duty so that they will cost approximately
double to what they do in Germany. So it will remain just a
dream :)
Kind regards
Heinz
Language Articles
Related Java Course | http://www.javaspecialists.eu/archive/Issue126.html | CC-MAIN-2016-40 | refinedweb | 969 | 55.03 |
isdigit()
Test a character to see if it's a decimal digit
Synopsis:
#include <ctype.h> int isdigit(digit() function tests for a decimal digit (characters 0 through 9).
Returns:
Nonzero if c is a decimal digit; otherwise, zero.
Examples:
#include <stdio.h> #include <stdlib.h> #include <ctype.h> char the_chars[] = { 'A', '5', '$' }; #define SIZE sizeof( the_chars ) / sizeof( char ) int main( void ) { int i; for( i = 0; i < SIZE; i++ ) { if( isdigit( the_chars[i] ) ) { printf( "Char %c is a digit character\n", the_chars[i] ); } else { printf( "Char %c is not a digit character\n", the_chars[i] ); } } return EXIT_SUCCESS; }
produces the output:
Char A is not a digit character Char 5 is a digit character Char $ is not a digit character
Classification:
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/i/isdigit.html | CC-MAIN-2016-44 | refinedweb | 142 | 57.06 |
README.md
youtube-dl - download videos from youtube.com or other video platforms
- INSTALLATION
- DESCRIPTION
- OPTIONS
- CONFIGURATION
- OUTPUT TEMPLATE
- FORMAT SELECTION
- VIDEO SELECTION
- DEVELOPER INSTRUCTIONS
- EMBEDDING YOUTUBE-DL
- BUGS
INSTALLATION
To install it right away for all UNIX users (Linux, macOS,
Windows users can download.
youtube-dl [OPTIONS] URL [URL...]
OPTIONS
-h, --help Print this help text and exit --version Print program version and exit -U, --update Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed) -i, --ignore-errors Continue on download errors, for example to skip unavailable videos in a playlist --abort-on-error Abort downloading of further videos (in the playlist or the command line) if an error occurs --dump-user-agent Display the current browser identification --list-extractors List all supported extractors --extractor-descriptions Output descriptions of all supported extractors --force-generic-extractor Force extraction to use the generic extractor --default-search PREFIX Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". Use the value "auto" to let youtube-dl guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching. --ignore-config Do not read configuration files. When given in the global configuration file /etc/youtube-dl.conf: Do not read the user configuration in ~/.config/youtube- dl/config (%APPDATA%/youtube-dl/config.txt on Windows) -
Video Selection:
--playlist-start NUMBER Playlist video to start at (default is 1) --playlist-end NUMBER Playlist video to end at (default is last) --playlist-items ITEM_SPEC Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13. --match-title REGEX Download only matching titles (regex or caseless sub-string) --reject-title REGEX Skip download for matching titles (regex or caseless sub-string) --max-downloads NUMBER Abort after downloading NUMBER files --min-filesize SIZE Do not download any videos smaller than SIZE (e.g. 50k or 44.6m) --max-filesize SIZE Do not download any videos larger than SIZE (e.g. 50k or 44.6m) --date DATE Download only videos uploaded in this date --datebefore DATE Download only videos uploaded on or before this date (i.e. inclusive) --dateafter DATE Download only videos uploaded on or after this date (i.e. inclusive) --min-views COUNT Do not download any videos with less than COUNT views --max-views COUNT Do not download any videos with more than COUNT views --match-filter FILTER Generic video filter. and & to require multiple matches. Values which are not known are excluded unless you put a question mark (?) after the operator. For example, to only match videos that have been liked more than 100 times and disliked less than 50 times (or the dislike functionality is not available at the given service), but who also have a description, use --match-filter "like_count > 100 & dislike_count <? 50 & description" . --no-playlist Download only the video, if the URL refers to a video and a playlist. --yes-playlist Download the playlist, if the URL refers to a video and a playlist. --age-limit YEARS Download only videos suitable for the given age --download-archive FILE Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it. --include-ads Download advertisements as well (experimental)
Download Options:
-r, - -w, --no-overwrites Do not overwrite files -c, --continue Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible. --no-continue Do not resume partially downloaded files (restart from beginning) --no-part Do not use .part files - write directly into output file --no-mtime Do not use the Last-modified header to set the file modification time --write-description Write video description to a .description file --write-info-json Write video metadata to a .info.json file --write-annotations Write video annotations to a .annotations.xml file --load-info-json FILE JSON file containing the video information (created with the "--write-info-json" option) --cookies FILE File to read cookies from and dump cookie jar in --cache-dir DIR Location in the filesystem where youtube-dl can store some downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl . At the moment, only YouTube player files (for videos with obfuscated signatures) are cached, but that may change. --no-cache-dir Disable filesystem caching --rm-cache-dir Delete all filesystem cache files
Thumbnail images:
--write-thumbnail Write thumbnail image to disk --write-all-thumbnails Write all thumbnail image formats to disk --list-thumbnails Simulate and list all available thumbnail formats
Verbosity / Simulation Options:
-q, --quiet Activate quiet mode --no-warnings Ignore warnings -s, --simulate Do not download the video and do not write anything to disk --skip-download Do not download the video -g, --get-url Simulate, quiet but print URL -e, --get-title Simulate, quiet but print title --get-id Simulate, quiet but print id --get-thumbnail Simulate, quiet but print thumbnail URL --get-description Simulate, quiet but print video description --get-duration Simulate, quiet but print video length --get-filename Simulate, quiet but print output filename --get-format Simulate, quiet but print output format -j, --dump-json Simulate, quiet but print JSON information. See the "OUTPUT TEMPLATE" for a description of available keys. -J, --dump-single-json Simulate, quiet but print JSON information for each command-line argument. If the URL refers to a playlist, dump the whole playlist information in a single line. --print-json Be quiet and print the video information as JSON (video is still being downloaded). --newline Output progress bar as new lines --no-progress Do not print progress bar --console-title Display progress in console titlebar -v, --verbose Print various debugging information --dump-pages Print downloaded pages encoded using base64 to debug problems (very verbose) --write-pages Write downloaded intermediary pages to files in the current directory to debug problems --print-traffic Display sent and read HTTP traffic -C, --call-home Contact the youtube-dl server for debugging --no-call-home Do NOT contact the youtube-dl server for debugging
Workarounds:
--encoding ENCODING Force the specified encoding (experimental) --no-check-certificate Suppress HTTPS certificate validation --prefer-insecure Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube) --user-agent UA Specify a custom user agent --referer URL Specify a custom referer, use if the video access is restricted to one domain --add-header FIELD:VALUE Specify a custom HTTP header and its value, separated by a colon ':'. You can use this option multiple times --bidi-workaround Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH --sleep-interval SECONDS Number of seconds to sleep before each download --youtube-skip-dash-manifest Do not download the DASH manifests and related data on YouTube videos --merge-output-format FORMAT If a merge is required (e.g. bestvideo+bestaudio), output to given container format. One of mkv, mp4, ogg, webm, flv. Ignored if no merge is required
Subtitle Options:
--write-sub Write subtitle file --write-auto-sub Write automatically generated subtitle file (YouTube only) --all-subs Download all the available subtitles of the video --list-subs List all available subtitles for the video --sub-format FORMAT Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best" --sub-lang LANGS Languages of the subtitles to download (optional) separated by commas, use --list- subs for available language tags, youku) --audio-quality QUALITY Specify ffmpeg/avconv audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default 5) --recode-video FORMAT Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi) --postprocessor-args ARGS Give these arguments to the postprocessor -k, --keep-video Keep the video file on disk after the post- processing; the video is erased by default --no-post-overwrites Do not overwrite post-processed files; the post-processed files are overwritten by default --embed-subs Embed subtitles in the video (only for>.+)" --xattrs Write metadata to the video file's xattrs (using dublin core and xdg standards) --fixup POLICY Automatically correct known faults of the file. One of never (do nothing), warn (only emit a warning), detect_or_warn (the default; fix file if we can, warn otherwise) --prefer-avconv Prefer avconv over ffmpeg for running the postprocessors -.
Authentication with
.netrc file
You may also want to configure automatic credentials storage for extractors that support authentication (by providing login and password with
--username and
--password) in order not to pass credentials as command line arguments on every youtube-dl execution and prevent tracking plain text passwords in the shell command history. You can achieve this using a
Each aforementioned sequence when referenced in an output template will be replaced by the actual value corresponding to the sequence name. Note that some of the sequences are not guaranteed to be present since they depend on the metadata obtained by a particular extractor. Such sequences will be replaced with
NA. -.
The current default template is
%(title)s-%(id)s.%(ext)s.
In some cases, you don't want special characters such as 中, spaces, or &, such as when transferring the downloaded filename to a Windows system or the filename through an 8bit-unsafe channel. In these cases, add the
--restrict-filenames flag to get a shorter title:.
$ youtube-dl --get-filename -o '%(title)s.%(ext)s' BaW_jenozKc youtube-dl test video ''_ä↭
language: Language code.
Formats for which the value is not known are excluded unless you put a question mark (
?) after the operator. You can combine format filters, so
-f "[height <=? 720][tbr>500]" selects up to 720p videos (or videos where the height is not known) with a bitrate of at least 500 KBit.
Format selectors can also be grouped using parentheses, for example if you want to download the best mp4 and webm formats with a height lower than 480 you can use
-f '(mp4,webm)[height<480]'.
Since the end of April 2015 and version 2015.04.26, youtube-dl uses
-f bestvideo+bestaudio/best as the default format selection (see #5447, #5456). If ffmpeg or avconv are installed this results in downloading
bestvideo and
bestaudio separately and muxing them together into a single file giving the best overall quality available. Otherwise it falls back to
best and results in downloading the best available quality served as a single file.
best is also needed for videos that don't come from YouTube because they don't provide the audio and video in two different files. If you want to only download some DASH formats (for example if you are not interested in getting videos with a resolution higher than 1080p), you can add
-f bestvideo[height<=?1080]+bestaudio/best to your configuration file. Note that if you use youtube-dl to stream tol 2015.04.26), i.e. you want to download)?
Examples:
# Download only the videos uploaded in the last 6 months $ youtube-dl --dateafter now-6months # Download only the videos uploaded on January 1, 1970 $ youtube-dl --date 19700101 $ # Download only the videos uploaded in the 200x decade $ youtube-dl --dateafter 20000101 --datebefore 20091231
How do I update youtube-dl?
If you've followed our manual installation instructions, you can simply run
youtube-dl -U (or, on Linux,
sudo youtube-dl -U).
If you have used pip, a simple
sudo pip install -U youtube-dl is sufficient to update.
Afterwards, simply follow our manual installation instructions:
sudo wget -O /usr/local/bin/youtube-dl sudo chmod a.
I'm getting an error
Unable to extract OpenGraph title on YouTube playlists
YouTube changed their playlist format in March 2014 and later on, so you'll need at least youtube-dl 2014.07.25 to download all YouTube videos.
If you have installed youtube-dl with a package manager, pip, setup.py.
Do I always have to pass
-citw?.
Can you please put the
-b option back?
Most people asking this question are not aware that youtube-dl now defaults to downloading the highest available quality as reported by YouTube, which will be 1080p or 720p in some cases, so you no longer need the
-b option. For some specific videos, maybe YouTube does not report them to be available in a specific high quality format you're interested in. In that case, simply request it with the
-f option and youtube-dl will try to download it.
I get HTTP error 402 when trying to download a video. What's this?
Apparently YouTube requires you to pass a CAPTCHA test if you download too much. We're considering to provide a way to let you solve the CAPTCHA, but at the moment, your best course of action is pointing a web.
It may be beneficial to use IPv6; in some cases, the restrictions are only applied to IPv4. Some services (sometimes only for a subset of videos) do not restrict the video URL by IP address, cookie, or user-agent, but these are the exception rather than the rule.
Please bear in mind that some URL protocols are not supported by browsers out of the box, including RTMP. If you are using
-g, your own downloader must support these as well.
If you want to play the video on a machine that is not running youtube-dl, you can relay the video content from the machine that runs youtube-dl. You can use
-o -
[1] 2839 or
youtube-dl.zip first on some systems) or clone the git repository, as laid out above. If you modify the code, you can run it by executing the
__main__.py file. To recompile the executable, run
make youtube-dl.
The exe throws an error due to missing
MSVCR100.dll
To run the exe you need to install first the Microsoft Visual C++ 2010 Redistributable Package (x86).,
C:\bin, or
C:\Users\<User name>\bin), put all the executables directly in there, and then set your PATH environment variable to include that directory.
From then on, after restarting your shell, you will be able to access both youtube-dl and ffmpeg (and youtube-dl will be able to find ffmpeg) by simply typing
youtube-dl or
ffmpeg, no matter what directory you're in.
How do I put downloads into a specific folder?
Use the
-o to specify an output template, for example
-o "/home/user/videos/%(title)s-%(id)s.%(ext)s". If you want this for all of your downloads, put the option into your configuration file..
In order to extract cookies from browser use any conforming browser extension for exporting cookies. For example, Get does not include support for services that specialize in infringing copyright. As a rule of thumb, if you cannot easily find a video that the service is quite obviously allowed to distribute (i.e. that has been uploaded by the creator, the creator's distributor, or is published under a free license), the service is probably unfit for inclusion to youtube-dl.
A note on the service that they don't host the infringing content, but just link to those who do, is evidence that the service should not be included into youtube-dl. The same goes for any DMCA note when the whole front page of the service is filled with videos they are not allowed to distribute. A "fair use" note is equally unconvincing if the service shows copyright-protected videos in full without authorization.
Support requests for services that do purchase the rights to distribute their content are perfectly fine though. If in doubt, you can simply include a source that mentions the legitimate purchase of content.
How can I speed up work on my issue?
(Also known as: Help, my important issue not being solved!) The youtube-dl core developer team is quite small. While we do our best to solve as many issues as possible, sometimes that can take quite a while. To speed up your issue, here's what you can do:
First of all, please do report the issue at our issue tracker. That allows us to coordinate all efforts by users and developers, and serves as a unified point. Unfortunately, the youtube-dl project has grown too large to use personal email as an effective communication channel.
Please read the bug reporting instructions below. A lot of bugs lack all the necessary information. If you can, offer proxy, VPN, or shell access to the youtube-dl developers. If you are able to, test the issue from multiple computers in multiple countries to exclude local censorship or misconfiguration issues.
If nobody is interested in solving your issue, you are welcome to take matters into your own hands and submit a pull request (or coerce/pay somebody else to do so).
Feel free to bump the issue from time to time by writing a small comment ("Issue is still present in youtube-dl version ...from France, but fixed from Belgium"), but please not more than once a month. Please do not declare your issue as
important or
urgent. contains a generic extractor which matches all URLs. You may be tempted to disable, exclude, or remove the generic extractor, but the generic extractor not only allows users to extract videos from lots of websites that embed a video from another service, but may also be used to extract video from a service that it's hosting itself. Therefore, we neither recommend nor support disabling, excluding, or removing the generic extractor.
If you want to find out whether a given URL is supported, simply call youtube-dl with it. If you get no videos back, chances are the URL is either not referring to a video or unsupported. You can find out which by examining the output (if you run youtube-dl on the console) or catching an
UnsupportedError
python -m youtube_dl
To run the test, simply invoke your favorite test runner, or execute a test file directly; any of the following work:
python -m unittest discover python test/test_download.py nosetests
See item 6 of new extractor tutorial for how to run extractor specific test cases.
If you want to create a build of youtube-dl yourself, you'll need
- python
- make (only GNU make is supported)
- pandoc
- zip
- nosetests:
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class YourExtractorIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?yourextractor\.com/watch/(?P<id>[0-9]+)' _TEST = { 'url': '', 'md5': 'TODO: md5 sum of the first 10241 bytes of the video file (use --test)', 'info_dict': { 'id': '42', 'ext': 'mp4', 'title': 'Video title goes here', 'thumbnail': r're:^https?://.*\.jpg$', # TODO more properties, either as: # * A value # * MD5 checksum; start the string with md5: # * A regular expression; start the string with re: # * Any Python type (for example int or float) } } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) # TODO more code goes here, for example ... title = self._html_search_regex(r'<h1>(.+?)</h1>', webpage, 'title') return { 'id': video_id, 'title': title, 'description': self._og_search_description(webpage), 'uploader': self._search_regex(r'<div[^>]+id="uploader"[^>]*>([^<]+)<', webpage, 'uploader', fatal=False), # TODO more properties (see youtube_dl/extractor/common.py) }
Add an import in
youtube_dl/extractor/extractors.py.
Run
python test/test_download.py TestDownload.test_YourExtractor. This should fail at first, but you can continually re-run it until you're done. If you decide to add more than one test, then rename
_TESTto
_TESTSand make it into a list of dictionaries. The tests will then be named
TestDownload.test_YourExtractor,
TestDownload.test_YourExtractor_1,
TestDownload.test_YourExtractor_2, etc. Note that tests with
only_matchingkey in test's dict are not counted in.
Have a look at
youtube_dl/extractor/common.pyfor+.
When the tests pass, add the new files and commit them and push the result, like this:
$ git add youtube_dl/extractor/extractors.py $ git add youtube_dl/extractor/yourextractor.py $ git commit -m '[yourextractor] Add new extractor' $ git push origin yourextractor
Finally, create a pull request. We'll then review and merge it..
Example.
Provide fallbacks
When extracting metadata try to do so from multiple sources. For example if
title is present in several places, try extracting from at least some of them. This makes it more future-proof in case some of the sources become unavailable.
Example.
Regular expressions
Don't capture groups you don't use
Capturing group must be an indication that it's used somewhere in the code. Any group that is not used must be non capturing.
Example
Don't capture id attribute name here since you can't use it for anything anyway.
Correct:
r'(?:id|ID)=(?P<id>\d+)'
Incorrect:
r'(id|ID)=(?P<id>\d+)'
Make regular expressions relaxed and flexible
When using regular expressions try to write them fuzzy, relaxed and flexible, skipping insignificant parts that are more likely to change, allowing both single and double quotes for quoted values and so on.
Example')
Long lines policy'
Inline values
Extracting variables is acceptable for reducing code duplication and improving readability of complex expressions. However, you should avoid extracting variables used only once and moving them to opposite parts of the extractor file, which makes reading the linear flow difficult.
Example
Correct:
title = self._html_search_regex(r'<title>([^<]+)</title>', webpage, 'title')
Incorrect:
TITLE_RE = r'<title>([^<]+)</title>' # ...some lines of code... title = self._html_search_regex(TITLE_RE, webpage, 'title')
Collapse fallbacks
Multiple fallback values can quickly become unwieldy. Collapse multiple fallback values into a single expression via a list of patterns.
Example.
Trailing parentheses
Always move trailing parentheses after the last argument.
Example
Correct:
lambda x: x['ResultSet']['Result'][0]['VideoUrlSet']['VideoUrl'], list)
Incorrect:
lambda x: x['ResultSet']['Result'][0]['VideoUrlSet']['VideoUrl'], list, )
Use convenience conversion and parsing functions.
More examples
Safely extract optional description from parsed JSON
description = try_get(response, lambda x: x['result']['video'][0]['summary'], compat_str)
Safely extract more optional metadata
video = try_get(response, lambda x: x['result']['video'][0], dict) or {} description = video.get('summary') duration = float_or_none(video.get('durationMs'), scale=1000) view_count = int_or_none(video.get('views'))
EMBEDDING YOUTUBE-DL:
from __future__ import unicode_literals import youtube_dl ydl_opts = {} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([''])
Most likely, you'll want to use various options. For a list of options available, have a look at
youtube_dl/YoutubeDL.py. For a start, if you want to intercept youtube-dl's output, set a
logger object.
Here's a more complete example of a program that outputs only errors (and a short message after the download is finished), and downloads/converts the video to an mp3 file:
from __future__ import unicode_literals import youtube_dl youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([''])
BUGS
-v, i.e. add
version 2015.12.06 [debug] Git HEAD: 135392e [debug] Python version 2.6.6 - Windows-2003Server-5.2.3790-SP2 [debug] exe versions: ffmpeg N-75573-g1d0487f, ffprobe N-75573-g1d0487f, rtmpdump 2.4 [debug] Proxy map: {} ...
Do not post screenshots of verbose logs; only plain text is acceptable.
The output (including the first lines) contains important debugging information. Issues without the full output are often not reproducible and therefore do not get solved in short order, if ever.
Please re-read your issue once again to avoid a couple of common mistakes (you can and should use this as a checklist):
Is the description of the issue itself sufficient?
We often get issue reports that we cannot really decipher. While in most cases we eventually get the required information after asking back multiple times, this poses an unnecessary drain on our resources. Many contributors, including myself, are also not native speakers, so we may misread some parts.
So please elaborate on what feature you are requesting, or what bug you want to be fixed. Make sure that it's obvious
- What the problem is
- How it could be fixed
-itter myself, I often get frustrated by these issues, since the only possible way for me to move forward on them is to ask for clarification over and over.
For bug reports, this means that your report should contain the complete output of youtube-dl.
Site support requests must contain an example URL. An example URL is a URL you might want to download, like. There should be an obvious video present. Except under very special circumstances, the main page of a video service (e.g.) is not an example URL.
Are you using the latest version?
Before reporting any issue, type
youtube-dl -U. Issues of this repository.?
People want to solve problems, and often think they do us a favor by breaking down their larger problems (e.g. wanting to skip already downloaded files) to a specific request (e.g. requesting us to look whether the file exists before downloading the info page). However, what often happens is that they break down the problem into two steps: One simple, and one impossible (or extremely complicated one).
We are then presented with a very complicated request when the original problem could be solved far easier, e.g. by recording the downloaded video IDs in a separate file. To avoid this, you must include the greater context where it is non-obvious. In particular, every feature request that does not consist of adding support for a new site should contain a use case scenario that explains in what situation the missing feature would be useful.
Does the issue involve one problem, and one problem only?
Some of our users seem to think there is a limit of issues they can or should open. There is no limit of issues they can or should open. While it may seem appealing to be able to dump all your issues into one ticket, that means that someone who solves one of your issues cannot mark the issue as closed. Typically, reporting a bunch of issues leads to the ticket lingering since nobody wants to attack that behemoth, until someone mercifully splits the issue into multiple ones.
In particular, every site support request issue should only pertain to services at one site (generally under a common domain, but always using the same backend technology). Do not request support for vimeo user videos, White house podcasts, and Google Plus pages in the same issue. Also, make sure that you don't post bug reports alongside feature requests. As a rule of thumb, a feature request does not include outputs of. | https://code.ur.gs/lupine/youtube-dl | CC-MAIN-2021-31 | refinedweb | 4,435 | 53.41 |
This is the second part of a series of articles looking at problems arising when waiting on multiple events in Python Asyncio. The first article explored how to manage the lifecycle of tasks when using
asyncio.wait. This article discusses how
asyncio.wait handles exceptions and what the programmer needs to do to ensure that results are gathered and tasks terminated in a coordinated manner.
Waiting on a single coroutine
When awaiting a single coroutine exception handling is managed in exactly the same way as non-asyncio code using a try…except…finally, block. As an example, an exception is raised in the
foo coroutine which propagates up to the
main block where it is captured and the error is printed.
import asyncio async def foo(): raise ValueError("Foo value error") return("Foo finished") async def main(): try: result = await foo() print(result) except ValueError as e: print(f"ValueError: {e}") asyncio.run(main())
However, if the result in main is waiting on several coroutines to complete what should happen if one of those coroutines throws an exception? Should it be immediately propagated to the main coroutine? What about unfinished tasks? Should they be terminated or allowed to continue? To prevent any unwanted side-effects the programmer needs to have a plan of action to handle exceptions when they arise.
It’s the scheduler that calls the coroutine
In the previous example when we run the main and await the foo coroutines they don’t start running immediately. Instead, they are added to a list of coroutines to run at some point in time in the future. This is a major difference compared with regular Python functions and what allows multiple tasks to seemingly run in parallel.
So, when
asyncio.run(main()) is called the coroutine
main() is placed on the event loop and, as it is the only coroutine on the event loop, it is called by the scheduler and starts executing. When the main coroutine meets the
await foo() statement the foo coroutine is added to the event list and execution of the main function is suspended with control yielded back to the scheduler. The scheduler then looks to see if there are any other tasks to execute and seeing
foo calls the coroutine until it terminates. Termination of foo sets a flag in main that the call to
foo has completed; so on the next trip round the event loop, the scheduler sees that
main is able to continue execution and so calls it, with execution continuing from the point where
main yielded.
asyncio run starts the event loop and creates a task for the scheduler to execute.
We can also consider the case when
main is waiting on two tasks to complete. In this case, two tasks are created (
a,
b). These are added to the event loop, but will not execute until the main loop yields control back to the scheduler and the scheduler is then free to call the newly created tasks.
The scheduler executes the first task (main) until it hands execution back to the scheduler (await). The task may create additional tasks which are added to the event loop.
We can now consider the case where the
main coroutine has yielded control to the scheduler and the scheduler has called task
a. For some reason, task
a rases an exception. This exception does not propagate up to
main, as
main is a peer of
a on the event loop and does, instead, propagate up to the scheduler.
The scheduler captures the exception and passes a task object back to
main noting that an exception has been raised. Depending upon the parameters in asyncio.wait the scheduler will then determine whether
main is callable on the next trip around the event loop, or whether all tasks have to complete before
main is called.
When a co-routine raises an exception it propagates up to the scheduler. The scheduler captures the exception, marks the task as done, removes it from the event loop and notes the exception in the task object.
At this point you will note:
- No exception has been raised in
mainat this point. It can only be handled once the scheduler calls the
maincoroutine — which occurs when the
return_whencondition is met.
- The coroutine
ahas terminated and will be removed from the event loop. All the resources it used will be released.
- The status of coroutine
bis not determined. It might or might not have started execution; and, might or might not have completed. If the
return_whencondition for
mainis
FIRST_EXCEPTIONthen main may continue execution and complete before
bis executed and terminates.
When waiting on multiple tasks a plan is needed:
- What behaviour is required when an exception is raised in a task (coroutine)? Do you want to wait for all other tasks to complete before the calling coroutine continues execution or return immediately?
- If you wait for all tasks to return how will you determine which tasks returned results and which had exceptions? How many tasks can simultaneously return exceptions? This could be zero up to the number of tasks that you are waiting on.
- If you return when the first exception is raised how do you ensure that all other tasks have completed execution and any resources they use are safely released? Tasks may be in an unknown state and may create unwanted side-effects if they are left to run indefinitely or resources they rely on are destroyed. For instance, if the calling coroutine closes network connections before the called coroutine is executed then the called coroutine may wait indefinitely for a network connection that doesn’t exist.
Capturing exceptions raised in tasks
To demonstrate exception handling with asyncio.wait the following example has two coroutines:
foo which immediately raises a
ValueError and
bar which sleeps for one second and then returns. The
main function encapsulates these coroutines in tasks before waiting for both tasks to complete. When the tasks complete then completed tasks are returned in the
done list and tasks which have not completed are returned in}") for task in pending: task.cancel() except Exception as e: print(f"Exception caught: {e}") asyncio.run(main())
When
foo_task and
bar_task complete the done list contains both tasks. However, at this point the exception raised in
foo is not re-thrown into
main. If the code is run then the following output is produced.
Done: Waiting task Done: Exception task------------ At program termination ------------- Task exception was never retrieved future: <Task finished name='Exception task' coro=<foo() done,exception=ValueError('Foo value error')> > ValueError: Foo value error
We can clearly see that both tasks completed, and we are able to retrieve the name of the tasks and print them. However, accessing the name of the task did not cause the exception in foo_task to be re-thrown. What is perhaps more concerning is that the foo_task remains on the event loop until the program terminates. If the exception is not handled then tasks can remain on the event loop indefinitely.
Retrieving exceptions for each task
Tasks returned from asyncio.wait have the following methods which are relevant to handling exceptions:
get_name(): This is optional, however, giving tasks meaningful names makes creating descriptive exceptions and debugging significantly easier.
exception(): Returns the exception object raised by the coroutine,
Noneif no exception as raised.
result(): Returns the result of the coroutine, re-throws the exception if the coroutine raised an exception.
Using these methods we can rewrite the main function to print the name of the task; test whether the coroutine threw an exception and print the exception details; and, retrieve the result of the coroutine, using a try…except block to capture any re-thrown}") exception = task.exception() if isinstance(exception, Exception): print(f"{name} threw {exception}") try: result = task.result() print(f"{name} returned {result}") except ValueError as e: print(f"ValueError: {e}") for task in pending: task.cancel() except Exception as e: print("Outer Exception") asyncio.run(main())
Running the above code produces the following output. We can clearly see that foo threw a ValueError exception, which was then re-thrown and caught when
.result() was called. Note, the ordering of the returned tasks is the order in which they completed; and, using this comprehensive approach to handling exceptions and pending tasks ensures that all tasks are managed and removed from the event loop prior to termination of the calling coroutine (in this case
main).
DONE: Exception_task Exception_task threw Foo value error ValueError: Foo value error DONE: Waiting_task Waiting_task returned Bar finished------------ At program termination -------------
There are a couple of considerations when planning how to handle exceptions and cancel pending tasks:
- Plan how you will handle pending tasks and exceptions. It is difficult to debug asyncio code when there is no code to explicitly handle these conditions.
- There is a high probability that tasks that throw exceptions will return earlier than those that return a value result. This means they will appear earlier, if not first, in the iterable list. Therefore, the first task for which
result()method is called may throw an exception, in which case you may want to process all other results and cancel pending tasks before re-throwing this error.
- The ordering of activities following
asyncio.waitmay be important in your implementation. Work out the most appropriate order for cancelling pending tasks, getting results, testing for and handling exceptions.
- If more than one task throws an exception you may need to work out how to aggregate them into a single error message that can be re-thrown once all other tasks have been processed.
Exceptions in asyncio.gather
Python provides
asyncio.gather as a higher-level alternative to
asyncio.wait when waiting for all tasks to complete. It manages the wrapping of coroutines in tasks and ensuring the tasks are removed from the event loop when the function returns. Using the previous foo bar example we can replace
asyncio.wait with:
results = await asyncio.gather(foo(), bar(), return_exceptions=True) print(results)[ValueError('Foo value error'), 'Bar finished']
The key parameter here is
return_exceptions. When this parameter is set to
True, the function returns a list of both values and exceptions; allowing all tasks to complete before returning. As all tasks have been completed they are removed from the event loop.
If
return_exceptions is set to
False (the default value) then
asyncio.gather returns immediately, throwing the exception into the calling coroutine. Any task which has not been terminated will remain on the event loop.
The following code explains the behaviour more clearly.
import asyncio async def foo(): raise ValueError("Foo value error.") return("Foo finished.") async def bar(): try: await asyncio.sleep(1) return("Bar finished.") except asyncio.CancelledError: print("Bar Cancelled.") async def main(): try: results = await asyncio.gather( foo(), bar(), return_exceptions=False ) print(results) except ValueError as e: print("Value Error raised.") asyncio.run(main())
When this code executes
foo immediately throws a
ValueError exception. This propagates immediately to main where it is caught and an error message printed. As the gather function exits the await statement, as a result of the exception, any pending tasks are cancelled (
task.cancel()). This causes a
CancelledError to be raised in
bar.
Value Error raised. Bar Cancelled.
Always Plan for Cancelled Tasks
The previous example draws attention to potential cancellation of tasks mid-execution. When planning how the code executes it is quite possible that coroutines are cancelled when an execution is thrown elsewhere in the code. In the case of gather, this may cause a
CancelledError to be thrown into a peer coroutine.
If the coroutine in which a
CancelledError is raised is communicating with another system, accessing a database or changing resources it may leave the system in an unstable state. Catching the
CancelledError provides an opportunity to unwind transactions minimising the risk of data corruption, inefficiency, or system failure.
Python asyncio is a powerful tool for improving system efficiency using asynchronous execution of code. However, it is very easy to implement code that does not explicitly handle the lifecycle of tasks and exceptions. Planning in advance how tasks are created and cancelled, and how exceptions should be handled, will significantly reduce the amount of time trying to diagnose bugs that may arise. | https://plainenglish.io/blog/how-to-manage-exceptions-when-waiting-on-multiple-asyncio | CC-MAIN-2022-40 | refinedweb | 2,037 | 54.22 |
Not Logged In
KezMenu 0.3.1
A simple and basical Pygame library for fast develop of menu interfaces
KezMenu
A simple and basical Pygame based module for a fast development of menu interfaces.
Introduction
This module is based on the original work of PyMike, from the Pygame community (see the EzMeNu project for more info). As I found some issues using the Mike's version library, I release this one that fix some issue.
- What you can do with this?
- You can easilly draw a menu interface, and selecting an option using the mouse of arrow keys.
Examples and usage
Here a fully example of use of this library. Even if we use the Python doctest format, this isn't a politically correct automated test because we'll wait for user input and no real tests are done onto results (no... this is not true, but none of the major feature are really tested here).
Maybe someday I'll add better python tests!
However... The code in this page is a working example. If you know nothing about doctests, only know that you can run this code simply downloading the source, going to the kezmenu directory and type:
python tests.py
If you have the library installed on your system you can run the example program from the python interpreter:
import kezmenu kezmenu.runTests()
Init all the Pygame stuff
First of all we need to enable the Pygame environment:
>>> import pygame >>> from pygame.locals import * >>> import pygame.font >>> pygame.font.init() >>> screen = pygame.display.set_mode((640,480), 0, 32)
KezMEnu works drawing the menu onto a pygame.Surface instance; the better (simpler) choice is always draw the menu onto the screen (another Surface instance obtained using methods of the pygame.display Pygame's module like pygame.display.set_mode), because is not possible in Pygame to know the offset of a blitten surface from the screen topleft corner.
This is not important if you are not planning to use the mouse on the menus, but rely only up and down keys. To disable the mouse, just put to False the 'mouse_enabled' attribute of a KezMEnu instance.
In the first example below we will use a surface inside the screen for drawing the menu. So we create this surface first:
>>> surface = pygame.Surface( (400,400), flags=SRCALPHA, depth=32 ) >>> surface.fill( (50,50,50,255) ) <rect(0, 0, 400, 400)>
Now we can blit the surface on the screen. We will repeat this procedure some times so it's better create out first dummy function (those functions aren't really useful outside this test environment):
>>> def blitSurface(): ... screen.blit(surface, (50,50) ) ... pygame.display.update()
So we can call it for the first time:
>>> blitSurface()
This is a graphical test, so we need to delay the automatic actions and make possible that the user can look at results and then go over. We wait for user input before going over.
To do this we create a second silly function that we'll call often later:
>>> click_count = 0 >>> def waitForUserAction(msg='???'): ... global click_count ... click_count+=1 ... pygame.display.set_caption("Example %s - %s" % (click_count, msg)) ... while True: ... for event in pygame.event.get(): ... if event.type==KEYDOWN: ... return
Ok, lets call it for the first time:
>>> waitForUserAction("An empty, dark surface")
We only displayed on the screen a surface filled with a dark color.
The KezMenu
Now it's time to create our KezMenu instance:
>>> from kezmenu import KezMenu >>> menu = KezMenu()
To draw out menu we create before another second dummy function for test needs:
>>> def drawMenu(): ... surface.fill( (50,50,50,255) ) ... menu.draw(screen) ... blitSurface() ... pygame.display.flip()
This is a valid way to create our menu, but we only obtain an empty menu (so invisible to user).
>>> drawMenu() >>> waitForUserAction("You see no difference")
You see no changes from the example 1, isn't it? If we create our menu in this way we need to fill it runtime with our options. You can do this by modifying runtime the 'options' attribute.
We need to know what the menu action must execute, before defining the option:
>>> option_selected = None >>> def option1(): ... global option_selected ... option_selected = 1 >>> menu.options = ( {'label': 'First option!', 'callable': option1}, )
As you can see the options member must be a tuple of dictionary. Those dict must contains (at least) the 'label' and 'callable' parameter; other paramter can be specified for advanced use (see EFFECTS.txt).
The 'label' is the string to be draw for the menu option, and the 'callable' is the function, object, method, ... to be called on selection.
>>> drawMenu() >>> waitForUserAction("Our first option!")
As far as we blitted the menu inside a surface that isn't in the (0,0) screen position, we need (if we wanna use also mouse control later) to specify the 'screen_topleft_offset' attribute:
>>> menu.screen_topleft_offset = (50,50)
In this way we say to the menu that all coordinates must keep count of an offset from the topleft corner of the screen.
Pass a screen object directly to the menu.draw method is more common, so in all other examples we will drop the use of the surface object.
>>> surface = None
Ways to link action to menu selection
Manually change the 'options' attribute is simple (and can be useful) but the most common way is to create the options directly on menu creation. To do make tests more complete, we need to add some other callable!
>>> def option2(): ... global option_selected ... option_selected = 1 >>> def option3(): ... global option_selected ... option_selected = 1>>> import sys >>> def optionX(p): ... global option_selected ... option_selected = p
Now create a new menu instance:
>>> menu = KezMenu( ... ["First option!", option1], ... ["sEcond", option2], ... ["Again!", option3], ... ["Lambda", lambda: optionX(71)], ... ["Quit", sys.exit], ... )
You can fast create menu entries giving a list of couples that are our 'label' and 'callable' attributes. The __init__ method does the magic and save those values in the right way.
>>> type(menu.options[0]) == dict True >>> menu.options[1]['callable'] <function option2 at ...> >>> [x['label'] for x in menu.options] ['First option!', 'sEcond', 'Again!', 'Lambda', 'Quit']
Like said above we will not use anymore the surface object, so we can simplify a little our dummy function:
>>> def drawMenu(): ... screen.fill( (50,50,50,255) ) ... menu.draw(screen) ... pygame.display.flip()
And now we refresh our window:
>>> drawMenu() >>> waitForUserAction("All our options")
It's very important to see how the actions are linked to the menu items. We must create couples of labels and callable objects without calling it! Like above you must pass the callable to the KezMenu a function, you must not call the callable yourself.
We can also use as callable argument a method of an object, a Python standard callable (like the sys.exit above)
What if you wanna also need to pass parameter(s) to the callable? The use of the lambda function above will show you how to do this!
Customize the menu GUI: colors, font, ...
The menu showed in the last example is a little ugly. Too near the the screen border and color used for non selected elements are ugly. You can modify those properties also for an already created menu:
>>> menu.position (0, 0) >>> menu.position = (30,50) >>> menu.position (30, 50) >>> drawMenu() >>> waitForUserAction("Not soo near to border now...")
Now the menu is in a better position on the screen.
Lets go over and modify some font properties, but first let me talk about the menu dimension. Data about the menu dimension is always available using the 'width' and 'height' attributes:
>>> menu.width 126 >>> menu.height 115
Those values are related to the labels displayed in the menu voices and also influenced by the font used (and it's dimension):
>>> new_font = pygame.font.Font(None, 38) >>> menu.font = new_font >>> drawMenu() >>> waitForUserAction("Bigger font")
This bigger font has different size, so the whole menu size raise:
>>> menu.width 154 >>> menu.height 135
Now colors:
>>> menu.color = (255,255,255,100) >>> menu.focus_color = (255,255,0) >>> drawMenu() >>> waitForUserAction("...and better colors")
As you can see we can easily manipulate the font color, and the font of the selected item.
Do something useful with our KezMenu
You surely noticed that our previous examples are rightnow static screenshots without any action possible over they.
To make some real examples with our menu we need to use the KezMEnu.update method, and pass it the pygame.Event instances that Pygame had captured. The waitForUserAction dummy function is no more needed because a menu is commonly a way to wait for user decision itself.
>>> click_count+=1 >>> pygame.display.set_caption("Example %s - %s" % (click_count, "Use the KezMenu freely")) >>> while True: ... events = pygame.event.get() ... menu.update(events) ... drawMenu() ... if option_selected: ... break >>> option_selected is not None True
The option_selected variable now contains the return value of the callable, relative to the option choosen.
NB: if you select the 'Quit' option running this test you will get a fake test failure. This isn't a KezMenu bug, but it's normal in Python tests: the sys.exit call raise a SystemExit exception that in tests are handled in a different way.
Ok, the example is at the end!
But KezMenu has also some effects! You can find examples about menu effects in the EFFECTS.txt file!
Goodbye!
>>> pygame.quit()
Play with the KezMenu's effects
Introduction
From version 0.3.0 the inner KezMenu structure is changed a lot. One of the first news is that every line has it's own pygame.font.Font to use.
This will give us a lot of freedom for menu's entries display effects.
>>> import pygame >>> from pygame.locals import * >>> import pygame.font >>> pygame.font.init() >>> screen = pygame.display.set_mode((640,480), 0, 32) >>> screen.fill( (50,50,50,255) ) <rect(0, 0, 640, 480)>>>> click_count = 0 >>> def waitForUserAction(msg='???'): ... global click_count ... click_count+=1 ... pygame.display.set_caption("Example %s - %s" % (click_count, msg)) ... while True: ... for event in pygame.event.get(): ... if event.type==KEYDOWN: ... return>>> def updateCaption(msg='???'): ... global click_count ... click_count+=1 ... pygame.display.set_caption("Example %s - %s" % (click_count, msg))>>> from kezmenu import KezMenu >>> def drawMenu(): ... screen.fill( (50,50,50,255) ) ... menu.draw(screen) ... pygame.display.flip()>>> option_selected = 0 >>> def optSelected(): ... global option_selected ... option_selected=1>>> menu = KezMenu( ... ["First option!", optSelected], ... ["sEcond", optSelected], ... ["Again!", optSelected], ... ["Lambda", optSelected], ... ["Quit", optSelected], ... ) >>> menu.font = pygame.font.Font(None, 20) >>> menu.color = (255,255,255) >>> menu.position = (10,10)
Lets show a moment the actual menu height:
>>> menu.height 70
Here again a standard menu.
>>> drawMenu() >>> waitForUserAction("The same boring menu")
Now we want a bigger font for 'sEcond' entry:
>>> menu.options[1]['font'] = pygame.font.Font(None, 26) >>> drawMenu() >>> waitForUserAction("Bigger entry 2")
Lets who now that manually play with the options menu can lead to some errors in the menu itself, because KezMenu instance is not warn of changed parameters:
>>> menu.height 70
So even if we display a new well drawn menu, the saved size is not changed. This is bad. We can fix this simply calling an internal KezMenu method, that commonly KezMenu objects call for us:
>>> menu._fixSize() >>> menu.height 74
This introduction was only a taste of what there's inside KezMenu effect's ways to do things.
The KezMenu available effects
Here a list and example of usage of all available effects. Effects are enabled using the 'enableEffect' method, and must be used for existing effects, or a KeyError is raised:
>>> menu.enableEffect('not-existing-effect-just-for-raise-error') Traceback (most recent call last): ... KeyError: "KezMenu don't know an effect of type not-existing-effect-just-for-raise-error"
In all the following example we need a timer, and so can use the pygame.time.Clock:
>>> clock = pygame.time.Clock()
To enable an effect, we must use the 'enableEffect' method, passing to it the name of the effect and optionally some keyword arguments.
Important thing: effects can be (sometimes) combined!
raise-line-padding-on-focus
This effect raise the padding above and below the focused element while time is passing. Padding on the last element will only raise the top padding. Padding on the first element will only raise the bottom padding.
- padding
- Default: 10px. The number of pixel that will be added above and below the selected menu entry.
- enlarge_time
Default: 500 millisec. Time needed (in seconds) to reach the max padding.
>>> updateCaption('raise-line-padding-on-focus') >>> option_selected = 0 >>> menu.enableEffect('raise-line-padding-on-focus') >>> while True: ... time_passed = clock.tick() / 1000. ... events = pygame.event.get() ... menu.update(events, time_passed) ... drawMenu() ... if option_selected: ... break
We can call this effect with new custom values:
>>> updateCaption('raise-line-padding-on-focus (custom)') >>> option_selected = 0 >>> menu.enableEffect('raise-line-padding-on-focus', padding=30, enlarge_time=1.) >>> while True: ... time_passed = clock.tick() / 1000. ... events = pygame.event.get() ... menu.update(events, time_passed) ... drawMenu() ... if option_selected: ... break >>> menu.disableEffect('raise-line-padding-on-focus')
raise-col-padding-on-focus
This effect raise the padding on the left of the focused element while time is passing.
- padding
- Default: 10px. The number of pixel that will be added on the left of the selected menu entry.
- enlarge_time
Default: 500 millisec. Time needed (in seconds) to reach the max padding.
>>> updateCaption('raise-col-padding-on-focus') >>> option_selected = 0 >>> menu.enableEffect('raise-col-padding-on-focus') >>> while True: ... time_passed = clock.tick() / 1000. ... events = pygame.event.get() ... menu.update(events, time_passed) ... drawMenu() ... if option_selected: ... break
We can call this effect with new custom values:
>>> updateCaption('raise-col-padding-on-focus (custom)') >>> option_selected = 0 >>> menu.enableEffect('raise-col-padding-on-focus', padding=20, enlarge_time=3.) >>> while True: ... time_passed = clock.tick() / 1000. ... events = pygame.event.get() ... menu.update(events, time_passed) ... drawMenu() ... if option_selected: ... break >>> menu.disableEffect('raise-col-padding-on-focus')
enlarge-font-on-focus
This effect will raise the font size of the selected element on the menu of a given multiply factor. The Font class of Pygame has a limitation (not a bug): is not possible to obtain the font data (family, size) after the font creation. So for use this effect is needed to pass to the init method all font data, and a new font will be created (the standard menu 'font' property will be overrided).
- font
- Required. A font name of path, same as you are passing it to Pygame Font constructor, so can also be None.
- size
- Required. The size of the font, same as you are passing it to Pygame Font constructor.
- enlarge_factor
- Default: 2.(200%). The multiply factor of the font size at the maximum extension, as a real value.
- enlarge_time
Default: 500 millisec. Time needed (in seconds) to reach the max font size.
>>> updateCaption('enlarge-font-on-focus') >>> option_selected = 0 >>> menu.enableEffect('enlarge-font-on-focus', font=None, size=18) >>> while True: ... time_passed = clock.tick() / 1000. ... events = pygame.event.get() ... menu.update(events, time_passed) ... drawMenu() ... if option_selected: ... break
Lets now customized all the data:
>>> updateCaption('enlarge-font-on-focus (focus)') >>> option_selected = 0 >>> menu.enableEffect('enlarge-font-on-focus', font=None, size=18, enlarge_factor=5., enlarge_time=2.) >>> while True: ... time_passed = clock.tick() / 1000. ... events = pygame.event.get() ... menu.update(events, time_passed) ... drawMenu() ... if option_selected: ... break >>> menu.disableEffect('enlarge-font-on-focus')
Combining KezMenu effects
The primary scope of KezMenu effects is to be enough flexible to be activated in same time. As the effects available will raise in future, sometimes can be that effects will fall in conflict each other, but in general I'll try to integrate them.
Activate more that one effects in the same time is very simple: just activate it!
>>> updateCaption('Combined effects example') >>> option_selected = 0 >>> menu.enableEffect('raise-line-padding-on-focus', padding=30, enlarge_time=1.) >>> menu.enableEffect('raise-col-padding-on-focus', padding=20, enlarge_time=1.) >>> menu.enableEffect('enlarge-font-on-focus', font=None, size=16, enlarge_factor=3.) >>> while True: ... time_passed = clock.tick() / 1000. ... events = pygame.event.get() ... menu.update(events, time_passed) ... drawMenu() ... if option_selected: ... break >>> menu.disableEffect('raise-line-padding-on-focus') >>> menu.disableEffect('raise-col-padding-on-focus') >>> menu.disableEffect('enlarge-font-on-focus')
Wanna write a new effect?
If anyone is interested in develop a new effect, I will be happy to integrate it in KezMenu!
Changelog
0.3.1
- Nothing new, but fixed a problem that break menus if the module is used in a py2exe environment
0.3.0
0.2.1
- Released as egg.
- Added some txt file.
0.2.0 - Unreleased
- Fixed many issues related to font handle.
- Added the support to mouse usage.
0.1.0
For version 0.1.0 I mean the original EzMeNu version 1.0.
Credits
- PyMike from the Pygame community for his original work.
TODO
- Submenus?
- More effects
- Fixes neede for work better with transparency
Subversion and other
The SVN repository is hosted at the Keul's Python Libraries
- Author: Keul
- Keywords: python pygame menu kezmenu: KezMenu-0.3.1.xml | http://pypi.python.org/pypi/KezMenu/0.3.1/ | crawl-003 | refinedweb | 2,784 | 58.48 |
Recently I thought I'd take a jab at functional languages just to try out a different paradigm of thinking, and I decided to pick up
Elixir since it's so syntatically similar to
Ruby. While I was learning, I found something.
TLDR:
- Elixir has no loops
- Recursion makes an additional call to call stack (which is why your stack overflows if you forget your base case)
- Tail Call Optimizations is a compiler feature that optimizes recursions (if the last thing it does is call itself)!
There is no concept of loop in Elixir.
Yes, none of your
for loops or
.each. It's a bit of a strange concept at first, but let's see what's the alternative.
If you can't use an iterative approach to iterate a loop, how do you traverse a list? Recursion.
Brief recap: Recursion is when a function calls itself, like this
A Ruby Example:
def traverse(tail) head = tail.shift # shift takes out the first element puts "Element: #{head}" return if tail.empty? traverse(tail) end
An Elixir Example:
defmodule Recursion do def traverse([]), do: IO.puts "Done" def traverse([head | tail]) do IO.puts "Element: #{head}" traverse(tail) end end
Pretty interesting to traverse recursively instead of the iteratively aye?
LARGE NUMBERS!
Next, let's see what happens when it comes to a large number!
Ruby:
large_array = Array.new(500_000).fill { |i| i + 1 } traverse(large_array) # Element: 1 # Element: ... # Element: ... # Element: 10918 #=> stack level too deep (SystemStackError)
It crashes with a
SystemStackError! Wow, does that mean
recursion is bad? does that mean
recursion is bad? does the mean
recursion is bad? does that mean
recursion is ... Okay, before we go crazy, let's take a look at how Elixir deals with it.
Elixir:
start = 1 increment = 1 length = 500000 list = Stream.iterate(start, &(&1 + increment)) |> Enum.take(length) Recursion.traverse(list) # Element: 1 # Element: ... # Element: ... # Element: 500000 # Done #=> :ok
You can see that Elixir effortlessly handles all five hundred thousands recursion. But why does it work in
Elixir but not
Ruby?
Because of
Tail Call Optimization!
What is Tail Call Optimization?
Tail Call Optimization (TCO) is a compiler feature in which the compiler automatically optimizes the stack, if the last thing that a function does is call itself.
But what is the stack? and what do you mean by 'optimizes the stack'?
Stack is a data structure that employs the LIFO mindset (Last-In-First-Out), think of it as a fixed array but you can only insert from one end and take out from the same end. What we're specifically talking about here is the call stack.
To understand this better, we need to first understand how call stacks work.
When you call a function, it gets added to the call stack, and when it finish executing, it gets popped off the stack, like so:
And when you have a recursive function call, it's basically adding itself to the call stack every single time. If you forget your base case/have too big of a call stack, it throws a stack overflow error! (what we saw earlier), like this.
All TCO means is that, when the compiler sees the last call of the function is calling itself, instead of adding the function call to the call stack, it does a
goto instead, and basically restarts the same function call, requiring O(1) instead of O(n) space (we will prove this later).
Now this is what it looks like when it's TCO-ed:
Do we have that in Ruby?
We do indeed! However TCO is not enabled by default, so you have to pass in the compile option during runtime, and you can do it like so:
RubyVM::InstructionSequence.compile_option = { tailcall_optimization: true, trace_instruction: false } require './tail_recursion.rb' large_array = Array.new(500_000).fill { |i| i + 1 } traverse(large_array) # Element: 1 # Element: ... # Element: ... #=> Element: 500000
Not very useful if you have to enable it with a flag, but it's there if you need it!
Proof?
Got your back! In RubyLand, We can inspect the current call stack with a call to
Kernel#caller. Lets
.count!
Change our code like so:
def traverse(tail) head = list.shift puts "Element: #{head}, Stack Count: #{caller.count}" #=> new line return if tail.empty? traverse(tail) end # Normal ruby traverse(large_array) # Element: 1, Stack Count: 1 # Element: ..., Stack Count: ... # Element: ..., Stack Count: ... # Element: 10918, Stack Count: 10918 # => stack level too deep (SystemStackError) # TCO-enabled traverse(large_array) # Element: 1, Stack Count: 1 # Element: ..., Stack Count: 1 # Element: ..., Stack Count: 1 # Element: 500000, Stack Count: 1
Conclusion
Alright so that's it for today! Thought it's pretty cool that I'm trying to learn Elixir but end up learning something about compiler instead!
Attribution
Russian doll cover image source
Discussion
Didn't know there's a flag.
Why isn't it enabled by default?
Seems like a no-brainer optimization to do when the conditions allow it.
Also, it works in all explicit/implicit return positions, right? Not just at the end of the function?
What about mutual recursion with both functions calling each other in tail position?
There are implicit trade-off, such as losing the stack trace which could make things harder to debug.
I think you have to keep in mind though, software is about tradeoffs - just because the condition allow it does not mean the tradeoff is worth it.
One of the most popular use case is recursion, but we don't really do recursions in Ruby, so is it really worth the tradeoff then?
It's also Python's reasoning (Guido). You can read more about his blog posts here explaining his rationale, it's a pretty good read.
1) neopythonic.blogspot.com/2009/04/t...
2) neopythonic.blogspot.com/2009/04/f...
You can also read about the progress on Ruby's official issue tracker - bugs.ruby-lang.org/issues/6602
Yes it doesn't have to literally be on the last line, but just the last executed statement.
Not sure what you mean about mutual calling, I don't think that's really possible (I could be wrong) - Yes, you can mutual call each other at tail call position, but that does not instantly make it possible for tail call optimization; TCO is when a compiler recognizes it's calling itself (as stated in the gifs). TCO also eliminates the stackframe (can read in the issue tracker). I don't think compilers can recognize a mutual calling tail call and optimize that
ES6 spec mandated TCO for mutually recursive functions as well that both call each other in tail call position.
Only Apple browsers have it implemented at the moment, Chrome implemented it but later removed it.
One notable part of the spec was that
would not get optimized, because there is an implicit
return undefinedafter the last line.
I understand how that limitation came about, but I don't really see why they couldn't add a single "void" to the stack and then merrily recurse as if it's this:
since the return value of the inner a is never used.
The tradeoffs for Ruby specifically sound like something that is more relevant in development than production, almost like something that should be a flag... Oh. That's what they did. Okay.
(I'd still suggest it be the default, until someone needs to pass
--debug, but I get the idea)
Very interesting explanation. I've been using Elixir for a while now, and even though I knew that the BEAM provides tail call optimization, I did not know how it worked behind scenes, it is a
goto!
Glad you liked it man! Yeah it's always interesting to see how things work behind the scene!
Just want to mention that tail call optimization is not always the best solution. Sometimes, it consumes more memory and runs slower than body recursion.
Interesting, can you elaborate on that?
P.S: And welcome to dev.to :D
After Erlang/OTP R12B, a body-recursive function generally uses the same amount of memory as a tail-recursive function and generally hard to predict whether the tail-recursive or the body-recursive version will be faster.
With around 10, 000 elements, a body-reclusive function is about 10% faster. But with larger lists (like 10, 000, 000 elements), a body-reclusive function is about 97% lower and it is about as faster as the standard library map.
references:
Myth: Tail-Recursive Functions are Much Faster Than Recursive Functions
erlang.org/doc/efficiency_guide/my...
TAIL CALL OPTIMIZATION IN ELIXIR & ERLANG – NOT AS EFFICIENT AND IMPORTANT AS YOU PROBABLY THINK
pragtob.wordpress.com/2016/06/16/t...
Wow that is interesting indeed, thanks for sharing!
Why is the Elixir example considered a use of TCO? It uses a Stream for lazy evaluation but is it using TCO under the hood?
That was just a quick way for me to generate large numbers
Ah okay I get it now, thanks!
May I mark it with the triple unicorn? ) Thanks a lot!
That means a lot man, thanks! :D
Just share it to three other friend who'll unicorn it hahaha | https://practicaldev-herokuapp-com.global.ssl.fastly.net/edisonywh/recursion-tail-call-optimization-and-recursion-2enh | CC-MAIN-2020-50 | refinedweb | 1,529 | 65.12 |
form_driver(3x) form_driver(3x)
form_driver, form_driver_w - command-processing loop of the form system
#include <form.h> int form_driver(FORM *form, int c); int form_driver_w(FORM *form, int c, wchar_t wch);
Once a form has been posted (displayed), you should funnel input events to it through form_driver. This routine has three major input cases: o The input is a form navigation request. Navigation request codes are constants defined in <form.h>, which are distinct from the key- and character codes returned by wgetch(3x). o The input is a printable character. Printable characters (which must be positive, less than 256) are checked according to the pro- gram's locale settings. o The input is the KEY_MOUSE special key associated with an mouse event.
This extension simplifies the use of the forms library using wide char- acters. The input is either a key code (a request) or a wide character returned by get_wch(3x). The type must be passed as well, to enable the library to determine whether the parameter is a wide character or a request.
The form driver requests are as follows: Name Description ---------------------------------------------------------------------: o a call to set_current_field attempts to move to a different field. o a call to set_current_page attempts to move to a different page of the form. o a request attempts to move to a different field. o a request attempts to move to a different page of the form. In each case, the move fails if the field is invalid. If the modified field is valid, the form driver copies the modified data from the window associated with the field to the field buffer.: o the form cursor is positioned to that field. o com- mand should be executed. o If a translation into a request was done, form_driver returns the result of this request. If you clicked outside the user window or the mouse event could not be translated into a form request an E_REQUEST_DENIED is returned.
If the second argument is neither printable nor one of the above pre- defined form requests, the driver assumes it is an application-specific command and returns E_UNKNOWN_COMMAND. Application-defined commands should be defined relative to MAX_COMMAND, the maximum value of these pre-defined requests.
form_NOT_CONNECTED No fields are connected to the form. E_REQUEST_DENIED The form driver could not process the request. E_SYSTEM_ERROR System error occurred (see errno(3)). <curses.h>.
These routines emulate the System V forms library. They were not sup- ported on Version 7 or BSD versions.
Juergen Pfeifer. Manual pages and adaptation for new curses by Eric S. Raymond. form_driver(3x) | http://ncurses.scripts.mit.edu/?p=ncurses.git;a=blob_plain;f=doc/html/man/form_driver.3x.html;hb=89730563d0a660d4ddd83d28660dc23c6d3f0bed | CC-MAIN-2020-50 | refinedweb | 428 | 57.06 |
Let's start with a very high-level description of how computer programming works. When you're writing a computer program, you're describing to the computer what you want, and then asking the computer to figure that thing out for you. Your description of what you want is called an expression. The process that the computer uses to turn your expression into whatever that expression means is called evaluation.
Think of a science fiction movie where a character asks the computer, out loud, "What's the square root of nine billion?" or "How many people older than 50 live in Paris, France?" Those are examples of expressions. The process that the computer uses to transform those expressions into a response is evaluation.
When the process of evaluation is complete, you're left with a single "value". Think of it schematically like so:
Expression (you write this) -> Evaluation (the computer does this) -> Value (the resulting output)
What makes computer programs powerful is that they make it possible to write very precise and sophisticated expressions. And importantly, you can embed the results of evaluating one expression inside of another expression, or save the results of evaluating an expression for later in your program.
Unfortunately, computers can't understand and intuit your desires simply from a verbal description. That's why we need computer programming languages: to give us a way to write expressions in a way that the computer can understand. Because programming languages are designed to be precise, they can also be persnickety (and frustrating). And every programming language is different. It's tricky, but worth it.
Let's start with simple arithmetic expressions. The way that you write arithmetic expressions in Python is very similar to the way that you write arithmetic expressions in, say, grade school arithmetic, or algebra. In the example below,
3 + 5 is the expression, and
print 3 + 5
8
Arithmetic expressions in Python can be much more sophisticated than this, of course. We won't go over all of the details right now, but one thing you should know immediately is that Python arithmetic operations are evaluated using the typical order of operations, which you can override with parentheses:
print 4 + 5 * 6 print (4 + 5) * 6
34 54
You can write arithmetic expressions with or without spaces between the numbers and the operators (but usually it's considered better style to include spaces):
print 10+20+30
60
Expressions in Python can also be very simple. In fact, a number on its own is its own expression, which Python evaluates to that number itself:
print 19
19
If you write an expression that Python doesn't understand, then you'll get an error. Here's what that looks like:
print + 20 19
File "<ipython-input-132-b7afa4290b0f>", line 1 print + 20 19 ^ SyntaxError: invalid syntax
You can also ask Python whether two expressions evaluate to the same value, or if one expression evaluates to a value greater than another expression, using a similar familiar syntax. When evaluating such expressions, Python will return one of two special values: either
True or
False.
The
== operator compares the expression on its left side to the expression on its right side. It evaluates to
True if the values are equal, and
False if they're not equal.
print 3 * 5 == 9 + 6
True
print 20 == 7 * 3
False
The
< operator compares the expression on its left side to the expression on its right side, evaluating to
True if the left-side expression is less than the right-side expression,
False otherwise. The
> does the same thing, except checking to see if the left-side expression is greater than the right-side expression:
print 17 < 18
True
print 17 > 18
False
You can save the result of evaluating an expression for later using the
= operator. On the left-hand side of the
=, write a word that you'd like to use to refer to the value of the expression, and on the right-hand side, write the expression itself. After you've assigned a value like this, whenever you include that word in your Python code, Python will evaluate the word and replace it with the value you assigned to it earlier. Like so:
x = (4 + 5) * 6 print x
54
You can create as many variables as you want!
another_variable = (x + 2) * 4 print another_variable
224
Variable names can contain letters, numbers and underscores, but must begin with a letter or underscore. There are other, more technical constraints on variable names; you can review them here.
If you attempt to use a the name of a variable that you haven't defined in the notebook, Python will raise an error:
print voldemort
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-139-4b4667502dbf> in <module>() ----> 1 print voldemort NameError: name 'voldemort' is not defined
Another important thing to know is that when Python evaluates an expression, it assigns the result to a "type." A type is a description of what kind of thing a value is, and Python uses that information to determine later what you can do with that value, and what kinds of expressions that value can be used in. You can ask Python what type it thinks a particular expression evaluates to, or what type a particular value is, using the
type() function:
print type(100 + 1)
<type 'int'>
The word
int stands for "integer." Python has many, many other types, and lots of (sometimes arcane) rules for how those types interact with each other when used in the same expression. For example, you can create a floating point type by writing a number with a decimal point in it:
print type(3.14)
<type 'float'>
Interestingly, the result of adding a floating-point number and an integer number together is always a floating point number:
print type(3.14 + 17)
<type 'float'>
... and the result of dividing one integer by another integer is always an integer:
print type(4 / 3)
<type 'int'>
Throwing an expression into the
type() function is a good way to know whether or not the value you're working with is the value you were expecting to work with. We'll use it for debugging some example code later.
[5, 10, 15, 20, 25, 30]
[5, 10, 15, 20, 25, 30]
That is: a left square bracket, followed by a series of comma-separated expressions, followed by a right square bracket. Items in a list don't have to be values; they can be more complex expressions as well. Python will evaluate those expressions and put them in the list.
[5, 2*5, 3*5, 4*5, 5*5, 6*5]
[5, 10, 15, 20, 25, 30]
Lists can have an arbitrary number of values. Here's a list with only one value in it:
[5]
[5]
And here's a list with no values in it:
[]
[]
Here's what happens when we ask Python what type of value a list is:
print type([1, 2, 3])
<type 'list'>
It's a value of type
list.
Once we have a list, we might want to get values out of the list. You can write a Python expression that evaluates to a particular value in a list using square brackets to the right of your list, with a number representing which value you want, numbered from the beginning (the left-hand side) of the list. Here's an example:
print [5, 10, 15, 20][2]
15
If we were to say this expression out loud, it might read, "I have a list of four things: 5, 10, 15, 20. Give me back the second item in the list." Python evaluates that expression to
15, the second item in the list.
You're right---good catch. But for reasons too complicated to go into here, Python (along with many other programming languages!) starts list indexes at 0, instead of 1. So what looks like the third element of the list to human eyes is actually the second element to Python. The first element of the list is accessed using index 0, like so:
print [5, 10, 15, 20][0]
5
The way I like to conceptualize this is to think of list indexes not as specifying the number of the item you want, but instead specifying how "far away" from the beginning of the list to look for that value.
If you attempt to use a value for the index of a list that is beyond the end of the list (i.e., the value you use is higher than the last index in the list), Python gives you an error:
print [1, 2, 3][47]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-151-6875f95c5cd6> in <module>() ----> 1 print [1, 2, 3][47] IndexError: list index out of range
Note that while the type of a list is
list, the type of an expression using index brackets to get an item out of the list is the type of whatever was in the list to begin with. To illustrate:
print type([1, 2, 3])
<type 'list'>
print type([1, 2, 3][0])
<type 'int'>
print [5, 10, 15, 20][6 / 2]
20
x = 3 print [5, 10, 15, 20][x]
20
shoe_sizes = [6.5, 9, 11, 10.5, 7] print shoe_sizes[1]
9
Because lists are so central to Python programming, Python includes a number of built-in functions that allow us to write expressions that evaluate to interesting facts about lists. For example, try putting a list between the parentheses of the
len() function. It will evaluate to the number of items in the list:
print len([10, 20, 30, 40])
4
print len([20])
1
print len([])
0
The
max() function will evaluate to the highest value in the list:
print max([9, 8, 42, 3, -17, 2])
42
... and the
min() function will evaluate to the lowest value in the list:
print min([9, 8, 42, 3, -17, 2])
-17
The
sum() function evaluates to the sum of all values in the list.
print sum([2, 4, 6, 8, 80])
100
Finally, the
sorted() function evaluates to a copy of the list, sorted from smallest value to largest value:
print sorted([9, 8, 42, 3, -17, 2])
[-17, 2, 3, 8, 9, 42]
print range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You can start the range at an integer other than zero by giving two parameters to the
range() function (separated by commas):
print range(10, 20)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
print range(-15, 15)
[-15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
fib = [1, 1, 2, 3, 5] print fib[-1]
5
The expression evaluates to the last item in the list. This is essentially the same thing as the following code:
print fib[len(fib) - 1]
5
... except easier to write. In fact, you can use any negative integer in the index brackets, and Python will count that many items from the end of the list, and evaluate the expression to that item.
print fib[-3]
2
If the value in the brackets would "go past" the beginning of the list, Python will raise an error:
print fib[-14]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-170-a9b12c62649a> in <module>() ----> 1 print fib[-14] IndexError: list index out of range
The index bracket syntax explained above allows you to write an expression that evaluates to a particular item in a list, based on its position in the list. Python also has a powerful way for you to write expressions that return a section of a list, starting from a particular index and ending with another index. In Python parlance we'll call this section a slice.
Writing an expression to get a slice of a list looks a lot like writing an expression to get a single value. The difference is that instead of putting one number between square brackets, we put two numbers, separated by a colon. The first number tells Python where to begin the slice, and the second number tells Python where to end it.
print [4, 5, 6, 10, 12, 15][1:4]
[5, 6, 10]
Note that the value after the colon specifies at which index the slice should end, but the slice does not include the value at that index. (You can tell how long the slice will be by subtracting the value before the colon from the value after it.)
Also note that---as always!---any expression that evaluates to an integer can be used for either value in the brackets. For example:
x = 3 print [4, 5, 6, 10, 12, 15][x:x+2]
[10, 12]
Finally, note that the type of a slice is
list:
print type([4, 5, 6, 10, 12, 15])
<type 'list'>
print type([4, 5, 6, 10, 12, 15][1:4])
<type 'list'>
print [4, 5, 6, 10, 12, 15][0:3]
[4, 5, 6]
You can leave out the
0 and write this instead:
print [4, 5, 6, 10, 12, 15][:3]
[4, 5, 6]
Likewise, if you wanted a slice that starts at index 4 and goes to the end of the list, you might write:
print [4, 5, 6, 10, 12, 15][4:]
[12, 15]
print [4, 5, 6, 10, 12, 15][-4:-2]
[6, 10]
To get the last three elements of the list:
print [4, 5, 6, 10, 12, 15][:-3]
[4, 5, 6]
So far we've seen lists that contain integers and floating-point numbers. But we're not limited to just those types! Importantly, lists can themselves contain... other lists. Lists within lists is one of the ways Python represents a matrix of values, like a spreadsheet. Here's what it looks like when you have lists inside of a list:
[[1, 2, 3, 4], [5, 10, 15, 20], [100, 200, 300, 400]]
[[1, 2, 3, 4], [5, 10, 15, 20], [100, 200, 300, 400]]
Whew, that's a lot of brackets! This is a list that has three items, each of which is itself a list containing four items. One way to visualize this list is to think of it as a table or spreadsheet that looks like this:
Using the
len() function on this list returns the number of items in the outer list, or the number of "rows" in the "table":
print len([[1, 2, 3, 4], [5, 10, 15, 20], [100, 200, 300, 400]])
3
You can write an expression that evaluates to a single "row" of a list-of-lists by using the square bracket indexing syntax:
print [[1, 2, 3, 4], [5, 10, 15, 20], [100, 200, 300, 400]][1]
[5, 10, 15, 20]
It's important to remember that a single element of a list-of-lists is itself a list:
print type([[1, 2, 3, 4], [5, 10, 15, 20], [100, 200, 300, 400]][1])
<type 'list'>
What if you want to write an expression that evaluates to a single item in that row? Well, then you need to use the square brackets index syntax... twice. The first square bracket index gets the row, and the second square bracket index gets the item from that row:
print [[1, 2, 3, 4], [5, 10, 15, 20], [100, 200, 300, 400]][1][3]
20
Still more brackets! Maybe it'll be clearer if we assign our list-of-lists to a variable first:
data = [[1, 2, 3, 4], [5, 10, 15, 20], [100, 200, 300, 400]] print data[1] print data[1][3]
[5, 10, 15, 20] 20
A very common task in both data analysis and computer programming is applying some operation to every item in a list (e.g., scaling the numbers in a list by a fixed factor), or to create a copy of a list with only those items that match a particular criterion (e.g., eliminating values that fall below a certain threshold). Python has a succinct syntax, called a list comprehension, which allows you to easily write expressions that transform and filter lists.
A list comprehension has a few parts:
Trueor
False; and
These parts are arranged like so:
[predicate expression
fortemporary variable name
insource list
ifmembership expression
]
The words
for,
in, and
if are a part of the syntax of the expression. They don't mean anything in particular (and in fact, they do completely different things in other parts of the Python language). You just have to spell them right and put them in the right place in order for the list comprehension to work.
Here's an example, returning the squares of integers zero up to ten:
print [x * x for x in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In the example above,
x*x is the predicate expression;
x is the temporary variable name; and
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] is the source list. There's no membership expression in this example, so we omit it (and the word
if).
There's nothing special about the variable
x; it's just a name that we chose. We could easily choose any other temporary variable name, as long as we use it in the predicate expression as well. Below, I use the name of one of my cats as the temporary variable name, and the expression evaluates the same way it did with
x:
print [shumai * shumai for shumai in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Notice that the type of the value that a list comprehension evaluates to is itself type
list:
print type([x * x for x in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
<type 'list'>
The expression we supply for the source list component of a list comprehension doesn't have to be a list that you've written out by hand. It can also be a variable:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print [x * x for x in numbers]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
... or it can be the result of some other expression that evaluates to a list:
print [x * x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
We've used the expression
x * x as the predicate expression in the examples above, but you can use any expression you want. For example, to scale the values of a list by 0.5:
print [x * 0.5 for x in range(10)]
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
In fact, the expression in the list comprehension can just be the temporary variable itself, in which case the list comprehension will simply evaluate to a copy of the original list:
print [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You don't technically even need to use the temporary variable in the predicate expression:
print [42 for x in range(10)]
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
Bonus exercise: Write a list comprehension for the list
range(5)that evaluates to a list where every value has been multiplied by two (i.e., the expression would evaluate to
[0, 2, 4, 6, 8]).
As indicated above, you can include an expression at the end of the list comprehension to determine whether or not the item in the source list will be evaluated and included in the resulting list. One way, for example, of including only those values from the source list that are greater than or equal to five:
print [x*x for x in range(10) if x >= 5]
[25, 36, 49, 64, 81]
We've learned how lists work, and we've learned some basic techniques for getting data from lists and turning lists into other lists. But so far it's been pretty abstract—we've been working with lists of numbers we've been typing in by hand, instead of with, you know, actual data fetched from some source. The reason for this is that getting data from real-world sources is... well, it's hard, and learning how to do that constitutes much of the content of this course.
Data files from real world sources usually come in a series of bytes—basically, a long sequence of numbers that correlate to how data is stored on disk or transmitted over the network. Our job as data mungers is to figure out how to "parse" this data ("parse" is used here loosely, in its colloquial meaning), transforming it from its "raw" form into actual Python data structures, like integers and lists.
One way of representing raw data in Python is with a data type called a string. A string is essentially a sequence of characters of arbitrary length. You can write one in iPython using single quotes (
') or double quotes (
") surrounding whatever characters you want. (The rules are a little more complicated than that, but we're focusing on the simple stuff for now.) Here's an example of a string:
print "this is a string. I can put a bunch of characters in here."
this is a string. I can put a bunch of characters in here.
Using
len() function will return the length of a string, just as it returns the length of a list:
x = "hi i'm a string" print x print len(x)
hi i'm a string 15
Strings have their own data type, type
str:
print type("mother said there'd be days like these")
<type 'str'>
print "15" - "4"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-195-a8252f2e06d4> in <module>() ----> 1 print "15" - "4" TypeError: unsupported operand type(s) for -: 'str' and 'str'
Attempting to add an integer or floating-point number to a string that has a number inside of it will raise a similar error:
print 16 + "8.9"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-196-cf6d61fa7c30> in <module>() ----> 1 print 16 + "8.9" TypeError: unsupported operand type(s) for +: 'int' and 'str'
"TypeError: unsupported operand type(s)" translates from Python talk to "you gave me two values, and asked me to perform an operation on those values, but I don't know how to do that when the values belong to these types." In this case, Python has no idea how to "add" a number and a string of characters. Fortunately, there are built-in functions whose purpose is to convert from one type to another; notably, you can put a string inside the parentheses of the
int() and
float() functions, and it will evaluate to (what Python interprets as) the integer and floating-point values (respectively) of the string:
print type("17") print int("17") print type(int("17"))
<type 'str'> 17 <type 'int'>
print type("3.14159") print float("3.14159") print type(float("3.14159"))
<type 'str'> 3.14159 <type 'float'>
If you give a string to one of these functions that Python can't interpret as an integer or floating-point number, Python will raise an error:
print int("shumai")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-199-725f52c691bd> in <module>() ----> 1 print int("shumai") ValueError: invalid literal for int() with base 10: 'shumai'
We'll be talking a LOT about what you can do with strings in this class. But for the purposes of this session, I just want to talk about one additional thing: the
split() method. The
split() method is a funny thing you can do with a string to transform it into a list. If you have an expression that evaluates to a string, you can put
.split() right after it, and Python will evaluate the whole expression to mean "take this string, and 'split' it on white space, giving me a list of strings with the remaining parts." For example:
print "this is a test".split()
['this', 'is', 'a', 'test']
Notably, while the
type of a string is
str, the type of the result of
split() is
list:
print type("this is a test".split())
<type 'list'>
If the string in question has some delimiter in it other than whitespace that we want to use to separate the fields in the resulting list, we can put a string with that delimiter inside the parentheses of the
split() method. Maybe you can tell where I'm going with this at this point!
For example, I happen to have here a string that represents the total points scored by LeBron James in each of his NBA games in the 2013-2014 regular season.
You can either cut-and-paste this string from the notes, or see a file on github with these values here.
Now if I just cut-and-pasted this string into a variable and tried to call list functions on it, I wouldn't get very helpful responses:
raw_str = " print max(raw_str)
9
This is wrong—we know that LeBron James scored more than nine points in his highest scoring game. The
max() function clearly does strange things when we give it a string instead of a list. The reason for this is that all Python knows about a string is that it's a series of characters. It's easy for a human to look at this string and think, "Hey, that's a list of numbers!" But Python doesn't know that. We have to explicitly "translate" that string into the kind of data we want Python to treat it as.
Bonus advanced exercise: Take a guess as to why, specifically, Python evaluates
max(raw_str)to
9. Hint: what's the result of
type(max(raw_str))?
What we want to do, then, is find some way to convert this string that represents integer values into an actual Python list of integer values. We'll start by splitting this string into a list, using the
split() method, passing
"," as a parameter so it splits on commas instead of on whitespace:
str_list = raw_str.split(",") print']
Looks good so far. What does
max() have to say about it?
print min(str_list)
13
This works. But what if we wanted to find the total number of points scored by LBJ? We should be able to do something like this:
print sum(str_list)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-205-cb32670f7064> in <module>() ----> 1 print sum(str_list) TypeError: unsupported operand type(s) for +: 'int' and 'str'
... but we get an error. Why this error? The reason lies in what kind of data is in our list. We can check the data type of an element of the list with the
type() function:
print type(str_list[0])
<type 'str'>
A-ha! The type is
str. So the error message we got before (
unsupported operand type(s) for +: 'int' and 'str') is Python's way of telling us, "You gave me a list of strings and then asked me to add them all together. I'm not sure what I can do for you."
So there's one step left in our process of "converting" our "raw" string, consisting of comma-separated numbers, into a list of numbers. What we have is a list of strings; what we want is a list of numbers. Fortunately, we know how to write an expression to transform one list into another list, applying an expression to each member of the list along the way—it's called a list comprehension. Equally fortunately, we know how to write an expression that converts a string representing an integer into an actual integer (
int()). Here's how to write that expression:
print [int(x) for x in]
Let's double-check that the values in this list are, in fact, integers, by spot-checking the first item in the list:
print type([int(x) for x in str_list][0])
<type 'int'>
Hey, voila! Now we'll assign that list to a variable, for the sake of convenience, and then check to see if
sum() works how we expect it to.
int_list = [int(x) for x in str_list] print sum(int_list)
2089
Wow! 2089 points in one season! Good work, King James.
A common task in this class will be to (1) take data from some source, (2) figure out what format that data is in, then (3) parse the data into Python data structures so we can (4) perform operations on it and synthesize useful information. The example in the section above—taking a string containing a comma-separated list of numbers, splitting it apart, converting it to integers, and then finding its sum—is a simple example of that task.
Step (3) above usually turns out to be the most difficult step in the process. Fortunately, Python makes available many "libraries" that know how to take apart data in particular formats and convert them to Python data structures that we can use in our notebooks. (A library is a piece of pre-existing code that you can incorporate into your program. Some libraries come pre-installed with Python; some are pre-installed on your EC2 machine as a part of the AMI for this class; others still you may need to install by hand. We'll talk about that step when the time comes!)
One such library is called
csv—it's a library for parsing comma-separated value files (CSVs). CSV is a common "exchange" format, often used when exporting data from a spreadsheet program. Here's an example of some CSV-formatted data, representing statistics for LeBron James' first five games of the 2013-2014 NBA season (source):
Rk,G,Date,Age,Tm,,Opp,,GS,MP,FG,FGA,FG%,3P,3PA,3P%,FT,FTA,FT%,ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PTS,GmSc,+/- 1,1,2013-10-29,28-303,MIA,,CHI,W (+12),1,38:01,5,11,.455,0,1,.000,7,9,.778,0,6,6,8,1,0,2,0,17,16.9,+8 2,2,2013-10-30,28-304,MIA,@,PHI,L (-4),1,36:38,9,17,.529,4,7,.571,3,4,.750,0,4,4,13,0,0,4,3,25,21.4,-8 3,3,2013-11-01,28-306,MIA,@,BRK,L (-1),1,42:14,11,19,.579,1,2,.500,3,5,.600,1,6,7,6,2,1,5,2,26,19.9,-3 4,4,2013-11-03,28-308,MIA,,WAS,W (+10),1,34:41,9,14,.643,3,5,.600,4,5,.800,0,3,3,5,1,0,6,2,25,17.0,+16 5,5,2013-11-05,28-310,MIA,@,TOR,W (+9),1,36:01,13,20,.650,1,3,.333,8,8,1.000,2,6,8,8,0,1,1,2,35,33.9,+3
The gist of the CSV format is that it consists of a number of records, one per line, each of consists of an equal number of fields. Fields are separated with a comma. Often, the first line of data in a CSV file gives some clue as to how to interpret the information in the corresponding fields in the following rows. We can surmise that, e.g., the data in the fields corresponding to
PTS represent the number of points scored in that game, that
FGA is the number of field goals attempted, etc.
Knowing what we know already, we can sort of imagine what the code to parse a file in this format might look like. We'd need to put that whole chunk of data into a big string, then split that string (somehow?) into individual lines; that would give us a list of strings. We could then write an expression to split those strings into lists of individual fields. In the end, we'd end up with a list of lists.
csvlibrary¶
Fortunately, we don't have to do that work for ourselves (if we don't want to). There's an existing library for Python called
csv that will do the work of taking a string and turning it into a list of lists for us.
I'm going to show you how to use this library, so you can get started doing simple data tasks with CSV files you find on the web. In the examples below, there is going to be some code that you won't be prepared for just yet—but I'm going to try to be careful to show you which parts of the code you can change yourself, and which parts you need to leave alone.
The full version of the LeBron James CSV file is here. Instead of cutting and pasting this entire file into a string, the code I write below will fetch the data straight from github. (I'll show you how this works and how to do it for arbitrary web addresses next session!)
Here's some code for loading an entire CSV into a list of lists:
import csv import urllib url = "" stats = list(csv.reader(urllib.urlopen(url)))
The
import csv line at the top of the cell simply tells Python that we want to use the
csv library for the rest of the notebook. The part of the code that does all the work is this one:
url = "YOUR_URL_HERE" stats = list(csv.reader(urllib.urlopen(url)))
You can change the value of the
url variable to whatever URL you want, as long as what's on the other side is a CSV file. The second line (
stats = csv.reader(urllib.urlopen(url))) loads the CSV at that URL and parses it into a list, assigning that list to a variable called
stats. Let's examine the
stats variable:
print type(stats)
<type 'list'>
It's a list! What's in the list?
print type(stats[0])
<type 'list'>
The first element of this list is... also a list! Looks like we've got a list of lists here. Let's see what's actually inside the list:
print stats[0]
['Rk', 'G', 'Date', 'Age', 'Tm', '', 'Opp', '', 'GS', 'MP', 'FG', 'FGA', 'FG%', '3P', '3PA', '3P%', 'FT', 'FTA', 'FT%', 'ORB', 'DRB', 'TRB', 'AST', 'STL', 'BLK', 'TOV', 'PF', 'PTS', 'GmSc', '+/-']
Looks like the first element of the
stats list is a list of column headings. What's in the second element?
print stats[1]
['1', '1', '2013-10-29', '28-303', 'MIA', '', 'CHI', 'W (+12)', '1', '38:01', '5', '11', '.455', '0', '1', '.000', '7', '9', '.778', '0', '6', '6', '8', '1', '0', '2', '0', '17', '16.9', '+8']
Ah, okay, now we're finally getting some actual data. How many records do we have? We'll use the
len() function to check, taking care to not include the first record in our count (since that's the column heading row, and doesn't itself represent a game):
print len(stats[1:])
77
77 games total. (NBA fans: yes, there are 82 games in a season, but I purposefully excluded games in which James was marked as "Inactive.")
We can access a particular item in a particular record by using the list indexing brackets twice. According to the column headings, the number of points scored in a game is in the... let's count it together, actually (remember to start counting at zero!):
['Rk', 'G', 'Date', 'Age', 'Tm', '', 'Opp', '', 'GS', 'MP', 'FG', 'FGA', 'FG%', '3P', '3PA', '3P%', 'FT', 'FTA', 'FT%', 'ORB', 'DRB', 'TRB', 'AST', 'STL', 'BLK', 'TOV', 'PF', 'PTS', 'GmSc', '+/-']
...27! So we can get the number of points LBJ scored in his first game of the season like so:
print stats[1][27]
17
print [int(record[27]) for record in stats[1:]]
]
Hey, that looks familiar! It's the same list of numbers we came up with earlier. Let's break down that list comprehension a bit.
stats[1:]. (Why
stats[1:]and not just
stats? Because we want to omit the column header row.)
record. As mentioned above, this can be anything! I chose
recordto remind us of the fact that each element in the source list is itself a record in a table.
int(record[27]), which translates into English as "get the 27th element of the list called
recordand convert it to an integer value."
Bonus exercise: Write an expression to get the sum of these values.
Here's another example. Let's get a list of how many points LBJ scored in games where he had exactly ten assists. ("Assists" are in the column labelled
AST, or column number 22.)
print [int(record[27]) for record in stats[1:] if int(record[22]) == 10]
[25, 26, 21]
Bonus exercise: Write an expression to get the number of blocks (the column labelled
BLK) that LeBron James had in games 10 up to 20.
We've put down the foundation today for you to become fluent in Python's very powerful and super-convenient syntax for lists. We've also done a bit of data parsing and analysis! Pretty good for day one.
Further resources: | http://nbviewer.jupyter.org/github/ledeprogram/courses/blob/master/databases/01%20Lists.ipynb | CC-MAIN-2018-30 | refinedweb | 6,228 | 73.1 |
brace-tags 1.0.4
The simplest static site generator
==========
> The simplest static site generator
Tags is a command line static site generator focused on simplicity. There are
only two tags: `include` and `is`. It's meant for building multi-page static
sites with common navigation and footer code.
Here's an example site using Tags:
index.html:
<html>
<body>
{% include nav.html %}
Welcome to Brace Tags!
</body>
</html>
about.html:
<html>
<body>
{% include nav.html %}
Tags is very simple!
</body>
</html>
nav.html:
<ul>
<li>
<a href="/" {%="" is="" index.home</a>
</li>
<li>
<a href="/about.html" {%="" is="" about.about</a>
</li>
</ul>
That's basically all there is to Brace Tags. There's almost zero convention or
syntax to learn. It doesn't currently support markdown, or provide fancy
optimizations. It's just here to help you avoid duplicating HTML boilerplate on
several web pages.
## Installing Brace Tags
Brace Tags is written in Python. Most computers today come with Python. You can
install it with `easy_install` by opening up your terminal and typing in:
sudo easy_install brace-tags
(The sudo part will ask you to log-in. It's required because Brace Tags needs to
install the `tags` command line script.)
Alternatively, if you're familiar with Python, you can use pip to install it:
pip install brace-tags
Brace has one external dependency, `watchdog` which is only required if you want
to use Brace to monitor a folder for changes, and recompile your site on the
fly. Before using the `--watch` option you'll need to install `watchdog`.
easy_install watchdog
## Using Brace Tags
Tags has two commands, the `build` command and the `serve` command. Build is
used to generate a site from a source folder.
tags build
By default, Brace Tags compiles all the .html files in your site. Tags places
the generated site in the `_site` folder, and ignores those files during future
builds. (In fact, it ignores all folders that start with an underscore.)
If you want to be specific about what files to compile, or where your site gets
generated, you can specify that with the `--files` and `--out` options:
tags build --files docs/*.html --out www/docs
As mentioned above, you can track the changes in your site folder and re-build
automatically with the `--watch` option. However this requires that you first
install `watchdog`.
easy_install watchdog
tags build --watch
The `serve` command will start a local webserver that you can use for testing.
tags serve
For more options and explanation, check out the help:
tags --help
## Extending Brace Tags
Brace Tags was built to be easily extended. You can add your own tags to
implement custom functionality.
A custom tag should look like this:
{% mytag argument1 argument2 %}
Optionally, a tag can have a body, like this:
{% mytag %}
Tag Body
{% endmytag %}
When Tags generates a file, each time it encounters a tag in the input, it
checks for a corresponding tag function. If the function exists, it is called
and returns a string that's substituted in the output.
In the `/tags/tags.py` file you'll find a function for each template tag. Add
your custom tag functions here. They should look something like this:
@lang.add_tag
def print3x(style, body=u'', context={}):
''' A tag that appends 3 copies of its body '''
result = body + body + body
if style == "bold":
result = u'<b>' + result + u'</b>'
return result
The above function defines a print3x tag that would be called like this:
{% print3x bold %}
<h1> ROBOTS, MAKE MY HTML! </h1>
{% endprint3x %}
When adding a new tag function, here are some things you should know:
- The `add_tag` decorator adds the tag function to the template language.
- The tag's name is taken from the function's name. For example, the function
above creates a `print3x` tag. Optionally you can use the `add_tag_with_name`
decorator to supply a tag name.
- The positional arguments of the function define the tag's required arguments.
In this case the tag requires one argument, `style`.
- If you specify a `body` keyword argument, then the tag will require a body.
The body is the content between the opening tag and an end tag.
- All tag functions must accept a `context` keyword argument. This is a
dictionary containing contextual data passed in by the generator. By default,
context includes a `filename` key whose value is the file currently being
generated.
You can also define tags that accept a variable argument list like so:
@lang.add_tag
def whatever(*args, **kwargs):
return str(len(args))
When called, the `*args` parameter will contain the variable argument list, and
the `body` and `context` keyword args will be in the `**kwargs` dictionary.
- Author: Cole Krumbholz, Lauri Hynynen
- License: LICENSE
- Package Index Owner: colevscode
- DOAP record: brace-tags-1.0.4.xml | https://pypi.python.org/pypi/brace-tags/1.0.4 | CC-MAIN-2017-22 | refinedweb | 793 | 66.44 |
Learning Chinese is difficult and memorizing a new word comes at price (requires independently memorizing the characters, pinyin and tone!). Recently I tried watching (with excessive pausing) the TV series 微微一笑, and with each new word I had encountered I asked myself "Is this word worth memorizing?".
It's not straightforward to answer. Examining the word's characters is meaningless - a character with many strokes is usually not more difficult to recognize than a simple character. At least for me the cost of memorizing each word is the same.
But when looking at all the words together we can estimate the word's frequency which measures how likely I am to encounter this word again (and how much less of a waste of time learning it would be!). For example in 微微一笑, words about Computer Science appear relatively frequently, so it pays off to memorize those. So my first instinct was to take all the subtitle files of the show, calculate n-gram histograms and only learn most frequent words. But after a bit of googling I realized two things:
Frequency depends on the body of text used (aka corpus). Cai & Brysbaert 2010 used a massive TV series and movie subtitle dataset as a corpus and they are even nice enough to share the data online. Their methodology appear sound enough for me to ignore the fact that it uses a broad database. Even so, looking at the data I get a sense that it represents modern TV much better than HSK ranking.
Now I can make a list of Chinese words to memorize:
So the rest of notebook does just that.
%matplotlib inline from pylab import *
import requests, StringIO, zipfile def download_zip(url): return zipfile.ZipFile( StringIO.StringIO( requests.get(url, stream=True).content))
freq_zip = download_zip('')
import pandas with freq_zip.open('SUBTLEX-CH-WF.xlsx') as freq_xlsx: freq_df = pandas.read_excel(freq_xlsx, header=2, index_col=0) freq_df = freq_df.sort('WCount', ascending=False) freq_df['rank'] = range(1, len(freq_df)+1) # Rank is useful pandas.options.display.max_rows = 10 freq_df
99121 rows × 7 columns
So how frequent is that word I didn't know?
freq_df[freq_df.index == u'眨眼']
Not frequent at all, I can safely ignore it.
Now with almost 100,000 words I have to somehow determine the most cost-effective amount of words to learn. Let's check the distribution of words:
semilogx(freq_df.WCount/float(freq_df.WCount.sum()));
What an extreme distribution. Let's see the CDF
semilogx(freq_df.WCount.cumsum()/float(freq_df.WCount.cumsum()[-1]));
So by memorizing the 1000 most frequent words I should on average know 4 out of every 5 words, which is often enough for understanding a sentence from context. So we are left with
freq_top_df = freq_df[freq_df['rank']<=1000] freq_top_df
1000 rows × 7 columns
Luckily there's a Creative Commons Chinese-English dictionary available (). It's supposed to be community based and updated regularly. Its format is a bit strange but I wrote this parser
import re def parse_ce_dict(): ce_zip = download_zip('') for line_ascii in ce_zip.open("cedict_ts.u8",'r'): if line_ascii.startswith('#'): continue line = line_ascii.decode('utf-8') (hanzi, pinyin, definitions) = re.findall('[^ ]+ ([^ ]+) \[(.+)\] /(.*)/', line)[0] yield (hanzi, pinyin, definitions) ce_df = pandas.DataFrame(data=[x for x in parse_ce_dict()], columns=('hanzi', 'pinyin', 'definitions')) ce_df
114835 rows × 3 columns
Now we can check the meaning of that word
ce_df[ce_df.hanzi == u'眨眼']
Sadly with Chinese a Hanzi character doesn't uniquely identifies a meaning. That is, some characters have several Pinyin meanings. Take 了 For example:
ce_df[ce_df['hanzi'] == u'了']
So 了 can be pronounced in and mean 4 different things. And this is not a special case, let's group the dictionary by Hanzi (aggregating Pinyin and definition)
ce_hanzi_groups = ce_df.groupby('hanzi')
and look at the distribution
%matplotlib inline from pylab import * hist([len(x[1]) for x in ce_hanzi_groups], log=True); xlabel('Different pronounciations');
Since we're dealing with character frequency, I want to create a dictionary that uniquely describes characters. Let's create one by joining piyin and definitions of the same Hanzi combination together
ce_hanzi_df = pandas.DataFrame( columns = ce_df.columns, data=((hanzi, ';'.join(ce_df['pinyin'][indices]), ';'.join(ce_df['definitions'][indices])) for hanzi, indices in ce_hanzi_groups.groups.iteritems())) ce_hanzi_df.index = ce_hanzi_df['hanzi'] ce_hanzi_df
111545 rows × 3 columns
known_df = pandas.DataFrame.from_csv(r"Hanping Chinese Pro Starred Export (1).txt", parse_dates=False, sep='\t', header=-1, encoding='utf-8') known_df = known_df.iloc[:-1] # Skip last line known_df.columns = ('pinyin', 'definition') known_df.index = pandas.Index([x.strip() for x in known_df.index]) known_df['hanzi'] = known_df.index known_df
822 rows × 3 columns
freq_top_def_df = freq_top_df.join(ce_hanzi_df, rsuffix='_ce')[['pinyin', 'rank', 'definitions']] freq_top_def_df.to_csv('frequent_1000.csv', encoding='utf-8') freq_top_def_new_df = freq_top_def_df.loc[freq_top_def_df.index.difference(known_df.index)].sort('rank') freq_top_def_new_df.to_csv('my_frequent.csv', encoding='utf-8') pandas.options.display.max_rows = 20 freq_top_def_new_df
502 rows × 3 columns | http://chengoldberg.com/notes/Chinese%20Words%20to%20Memorize/ | CC-MAIN-2019-09 | refinedweb | 803 | 50.43 |
Feature #8956
Allow hash members delimited by \n inside of {}
Description
Currently, hashes require members to be delimited by commas (
,), even inside curly braces. E.g.,
some_hash = { :foo => 'bar', :bar => 'foo', :baz => { :qux => 'quux', :corge => 'grault' } }
In my opinion, these commas add nothing of value to this particular example since, visually, the members are already delimited by a newline (
\n). Additionally, missing a comma between members results in
syntax error, unexpected tSYMBEG, expecting '}'.
I propose we make these commas optional, such that the following syntax would be possible:
some_hash = { :foo => 'bar' :bar => 'foo' :baz => { :qux => 'quux' :corge => 'grault' } }
This change would not affect existing hashes. Developers would be able to mix and match the old and new syntaxes as such:
some_hash = { :foo => 'bar' :bar => 'foo' :baz => { :foo => 'bar' + 'baz' :bar => 'foo', :qux => 'quux' :corge => 'grault' } }
This change would also reduce the occurrence of syntax errors in cases where the developer temporarily replaces a value in the hash, e.g.,
some_hash = { :this => 'that', :foo => 'not bar'#'bar', :those => 'the other' }
Finally, this change would only affect hashes inside curly braces (for hopefully obvious reasons).
I have attached a diff of my suggested changes along with a script to test a variety of use cases. I also have an open pull request on GitHub: URL:
Please let me know if there's anything I've missed or that needs clarification.
History
#1
[ruby-core:57408]
Updated by Adam Dunson over 2 years ago
I feel the need to mention that at this time, my changes do not include Ruby 1.9 style symbol hashes. These still require commas, e.g.,
some_hash = { foo: 'bar', bar: 'foo', baz: { qux: 'quux', corge: 'grault' } }
#2
[ruby-core:57417]
Updated by Nobuyoshi Nakada over 2 years ago
Additional patch for labeled
assocs.
diff --git a/parse.y b/parse.y index b0a7cc4..63b4334 100644 --- a/parse.y +++ b/parse.y @@ -5013,4 +5013,7 @@ trailer : /* none */ assoc_seperator : '\n' + { + command_start = FALSE; + } | ',' ;
#3
[ruby-core:57419]
Updated by Alexey Muranov over 2 years ago
Same about arrays, i guess? :)
#4
[ruby-core:57421]
Updated by Tsuyoshi Sawada over 2 years ago
If this proposal is going to be considered, then I think it should not be just for hashes, but also for arrays, and for arguments passed to a method.
[ :foo :bar ] foo( "arg1" "arg2" )
Also note that, since
"\n" should be replacable by
";", the proposal would mean the following is allowed:
{:foo => 1; :bar => 2}
#5
[ruby-core:57447]
Updated by Adam Dunson over 2 years ago
Thanks for the patch, nobu. That was easier than I thought it would be; I was looking in the wrong place entirely.
sawa (Tsuyoshi Sawada) wrote:
[...] I think it should not be just for hashes, but also for arrays, and for arguments passed to a method.
I agree. Hashes were the easiest to tackle, but I have also been working on a solution for arrays and arguments. I'm definitely open to suggestions if anyone figures it out before I do.
sawa (Tsuyoshi Sawada) wrote:
Also note that, since
"\n"should be replacable by
";", the proposal would mean the following is allowed:
{:foo => 1; :bar => 2}
Is this a desired effect? My current patch does not account for this, but it shouldn't be difficult to add support for it.
#6
[ruby-core:57499]
Updated by Adam Dunson over 2 years ago
- File add-array-support.patch
added
I've attached a patch for array support (only between square brackets). I've also renamed the
assoc_seperator rule to be
nl_or_comma to make it a little more generic.
This allows for syntax similar to hashes (here's a rather complex example):
some_array = [ :foo :bar [ 'baz' :qux ] { :quux => 'grault' 'garply' => [ 'waldo' => :fred ] :plugh => 'xyzzy' } ]
#7
[ruby-core:57560]
Updated by Adam Dunson over 2 years ago
- File add-method-arg-support.patch
added
Adding a patch for method argument support. For example, this allows the following syntaxes:
Hash[ :foo, 'bar' :baz, 'qux' ]
which becomes
{ :foo => "bar", :baz => "qux" }, as well as
puts("this is line one" "this is line two" "this is line three")
#8
[ruby-core:57561]
Updated by Adam Dunson over 2 years ago
- File add-method-arg-support-FIXED.patch
added
Sorry, the previous patch was incorrect (add-method-arg-support.patch). Please use the attached version instead.
#9
[ruby-core:57563]
Updated by Adam Dunson over 2 years ago
I should also mention that this patch does not apply to method definitions, so these still require commas (at least, for now):
def some_method(foo, bar, baz) # do stuff end
#10
[ruby-core:57567]
Updated by Tsuyoshi Sawada over 2 years ago
Another case where similar syntax might be relevant is
| | inside a block. Whether you want to do this:
{| foo bar baz | ....}
should go together with whether arguments in method definition can be written as:
def foo( foo bar = some_complicated_expression_as_default_value baz = maybe_another_complicated_default_value )... end
The latter is useful if you want to put some complicated expression as default value. Usefulness of the former would depend on whether default value would be allowed for block variables.
#11
[ruby-core:57569]
Updated by Tsuyoshi Sawada over 2 years ago
I also thought that maybe you can go one step further and allow any sequence of white characters as delimiters when the parentheses/braces/brackets/pipes are not omitted:
foo(:foo :bar :baz) {foo: "bar baz: "qux"} [:foo :bar :baz] foo{|foo bar baz| ...}
#12
[ruby-core:57777]
Updated by Adam Dunson over 2 years ago
Hi sawa,
Another case where similar syntax might be relevant is
| |inside a block. ... should go together with ... arguments in method definition
I agree. Arguments in method definitions have been on my to-do list — I haven't had much time lately to look at this, but good call on allowing newlines inside vertical bars in a block.
I also thought that maybe you can go one step further and allow any sequence of white characters as delimiters when the parentheses/braces/brackets/pipes are not omitted
I like the idea, but this one might be too ambitious. The problem that I see is that it introduces ambiguity when passing a method as an argument, e.g.,
def foo(a, b = 0, c = 0) puts a + b + c end def bar(a = 0) a + 1 end foo(bar 1 2)
In this instance, it is difficult to tell whether
foo is being called with three arguments (
bar,
1, and
2) or with two arguments (
bar(1) and
2).
#13
[ruby-core:57784]
Updated by Tsuyoshi Sawada over 2 years ago
adamdunson,
As I wrote already, omission of comma is to be allowed only when the
()[]{}| is not omitted.
foo(bar 1 2)
would be unambiguously
foo taking three arguments
bar,
1, and
2.
#14
[ruby-core:57791]
Updated by Adam Dunson over 2 years ago
sawa,
Could you elaborate? I still find that expression to be ambiguous. Here's another example that works with ruby 2.0.0-p247:
def foo(a, b = 0, c = 0) a + b + c end def bar(a = 1, b = 0) a + b end puts foo(bar 1, 2) # outputs 3 puts foo(bar, 1, 2) # outputs 4
If spaces and commas were made to be interchangeable inside parentheses, then the above two calls to
foo would be equivalent (which they are not).
#15
[ruby-core:57827]
Updated by Adam Dunson over 2 years ago
- File no-comma-tests.patch
added
Adding another patch with tests for no-comma hashes, arrays, and method arguments.
#16
[ruby-core:58024]
Updated by Tim Rosenblatt over 2 years ago
bump? This looks helpful.
#17
[ruby-core:58470]
Updated by Tim Rosenblatt about 2 years ago
- File comic-pet-desktop-very-happy-cat.jpg added
Bump again. Can we get a thumbs up or down on this?
As a gift, here is a picture of a very happy cat.
URL:
#18
[ruby-core:62164]
Updated by Nobuyoshi Nakada almost 2 years ago
It seems this issue has diverged so far from the original.
I reject it for now.
#19
[ruby-core:66372]
Updated by Alexey Muranov about 1 year ago
Also available in: Atom PDF | https://bugs.ruby-lang.org/issues/8956 | CC-MAIN-2016-07 | refinedweb | 1,359 | 59.84 |
Stripping Reddit From HackerNews With BOSS Mashuppython (59), boss (11)
In a previous article, I wrote some search recipes using Python and Yahoo's BOSS Mashup Framework, now lets start looking at actually doing a mashup. We'll walk through a fairly simple example that represents something of a dream of mine:
YC's Hacker News with all the reposts from Reddit Programming stripped out. In other words, calculate the intersectionf between HackerNews and Reddit Programming, and remove that intersection from HackerNews, and return the remaining content in HackerNews.
Note that you'll need to have the BOSS Mashup Framework installed and a Yahoo BOSS App Id before you get started. I walked through that process here.
Getting Started
First lets look at grabbing HackerNew's RSS feed.
>>> from yos.yql import db,udfs >>> hn = db.create(Comments</a>', 'hn$title': 'Play this game for 20 minutes - learn about concurrency', 'hn$comments': '' }, { 'hn$link': '', 'hn$description': '<a href="">Comments</a>', 'hn$title': "Today is one of the 2 days each year when the sun lines up with Manhattan's grid", 'hn$comments': '' }, "Additional results truncated for brevity..." ]
The
db.create function is used for retrieving the contents of an RSS feed (and
also search results from Yahoo's exposed search APIs), and encapsulating them in
an easy to manipulate object.
db.select is performing a map across all the results, and in this case it is
applying the
udfs.unnest_value function to each row and returning the
results. (The
udfs.unnest_value function tries to collapse nested dictionaries
into a single dictionary with all values at the base level.) As a quick example
of using
db.select lets write a function that strips out the
hn$description
key from the dictionaries.
>>> from yos.yql import db,udfs >>> def strip_key(row, key): ... if row.has_key(key): ... del row[key] ... return row ... >>> def strip_desc(row): ... return strip_key(row, "hn$description") ... >>> hn = db.create(name="hn",url="") >>> _hn = db.select(udf=udfs.unnest_value,table=hn) >>> __hn = db.select(udf=strip_des,table=_hn) >>> __hn.rows [ { 'hn$link': '', 'hn$title': 'Play this game for 20 minutes - learn about concurrency', 'hn$comments': '' }, "Additional results stripped for brevity." ]
Okay, and now lets grab the RSS feed for Reddit Programming.
>>> rp = db.create([link]</a> <a href="">[comments]</a>', 'rp$title': 'Human DNA in C code', 'rp$date': '2008-07-12T11:43:35.936253+00:00', 'rp$guid': '' }, "Additional results stripped for brevity." ]
Now we want to strip all the Reddit Programming results from the Hacker News results.
Our first step is to find a way to correlate results with each other. Often times the
titles are very similar, but using urls would be ideal. HackerNews makes the url
easily available, but Reddit is hiding the url within the
description data, so
we're going to have to parse it out.
Fortunately we can do that pretty easily with a regular expression.
>>> from yos.yql import db,udfs >>> import re >>> REDDIT_LINK_REGEX = re.compile(r'<a href="(?P<url>.*?)">\[link\]</a>') >>> def update_link(row): ... m = REDDIT_LINK_REGEX.search(row['rp$description']) ... if not m: return row ... row['rp$link'] = m.group('url') ... return row ... >>> rp = db.create([link]</a> <a href="">[comments]</a>', 'rp$title': "Donal Knuth's Complexity of Songs", 'rp$date': '2008-07-13T01:44:18.961669+00:00', 'rp$guid': '' }, "Additional rows truncated for brevity.", ]
Okay, we have collected the ingredients and just need to cook the stew.
Finding the Intersection
Lets take a look at a sample entry from our transformed HackerNews and Reddit Programming feeds. First lets look one from HackerNews:
{ 'hn$link': '', 'hn$description': '<a href="">Comments</a>', 'hn$title': 'Play this game for 20 minutes - learn about concurrency', 'hn$comments':'' }
And now one from Reddit Programming (after we have run the
update_link function on it):
{ 'rp$link': '', 'rp$description': '<a href="">[link]</a> <a href="">[comments]</a>', 'rp$title': "Donal Knuth's Complexity of Songs", 'rp$date': '2008-07-13T01:44:18.961669+00:00', 'rp$guid': '' }
Now we use the
link key to find the intersection between the two RSS feeds.
Notice that in the
overlap function we use
'link' as the key,
as opposed to using
'rp$link' and
'hn$link' for the keys.
The
db.join function is smart enough to strip off namespaces
before it passes the arguments in.
>>> def overlap(r1,r2): ... return r1['link'].strip() == r2['link'].strip() ... >>> len(_hn) 25 >>> len(rp) 25 >>> joint = db.join(overlap, [_hn, _rp]) >>> len(joint) 3 >>> joint.rows[0] { 'hn$description': '<a href="">Comments</a>', 'hn$title': "Donald Knuth's Complexity of Songs", 'rp$date': '2008-07-13T01:44:18.961669+00:00', 'hn$comments': '', 'hn$link': '', 'rp$description': '<a href="">[link]</a> <a href="">[comments]</a>', 'rp$title': "Donal Knuth's Complexity of Songs", 'rp$guid': '', 'rp$link': '' }
But, the goal isn't really to find the intersection, its to find the content in HackerNews that is not contained in Reddit Programming. Fortunately, we can write a quick Python function to strip the intersection out.
>>> joint = db.join(overlap, [_hn, _rp]) >>> def in_reddit(row): ... for dup in joint.rows: ... if row['hn$link'] == dup['hn$link']: ... return True ... return False ... >>> hn_uniques = [ x for x in _hn.rows if in_reddit(x) == False ] >>> len(hn_uniques) 22
And we've finally accomplished our noble goal: creating a feed of HackerNews with the intersection of entries with Reddit Programming stripped out. Putting all the code together it looks like this:
import re from yos.yql import db,udfs
REDDIT_LINK_REGEX = re.compile(r'<a href="(?P<url>.*?)">[link]</a>') def update_link(row): "Replace key 'rp$link' with url parsed from 'rp$description'." m = REDDIT_LINK_REGEX.search(row['rp$description']) if not m: return row row['rp$link'] = m.group('url') return row
def overlap(r1,r2): "Returns true if dicts r1 and r2 have same value for key 'link'." return r1['link'].strip() == r2['link'].strip()
# Get HackerNews RSS feed. hn = db.create(name="hn",url="") _hn = db.select(udf=udfs.unnest_value,table=hn)
# Get Reddit Programming RSS feed. rp = db.create(name="rp",url="") _rp = db.select(udf=udfs.unnest_value,table=rp) _rp = db.select(udf=update_link,table=rp)
# Calculate the intersection between both feeds. joint = db.join(overlap, [_hn, _rp])
def in_reddit(row): for dup in joint.rows: if row['hn$link'] == dup['hn$link']: return True return False
# Strip intersection from HackerNews RSS feed. hn_uniques = [ x for x in _hn.rows if in_reddit(x) == False ]
I'll be the first to admit that this is a fairly contrived example. That said, it does show how the BOSS Mashup Framework has provided some useful tools to play around with. There is certainly more depth to the framework that isn't touched here, and this task is a bit of an abnormality in the sense that it is more difficult than most things you'd be trying to accomplish using the framework.
The Mashup Framework has a lot of support for merging things together in interesting ways--ya know, mashing things up--but not much for removing duplicate results, which isn't surprising since that is almost the exact opposite of what it is intended to do. In that sense, it's something of a testament to the framework that its still fairly easy to accomplish. Of course, it would have been fairly easy to accomplish this example without using the BOSS Mashup Framework at all...
In my next (and likely, for a while, last) tutorial on using the BOSS Mashup Framework I'll put it to use at a task that it's actually good at.
Let me know if there are any mistakes or if you have any questions. | https://lethain.com/stripping-reddit-from-hackernews-with-boss-mashup/ | CC-MAIN-2021-39 | refinedweb | 1,276 | 56.55 |
My last post C++20: The Big Four started with an overview of concepts, ranges, coroutines, and modules. Of course, C++20 has more to offer. Today, let's continue my overview of the core language.
When you look at the image, you see the features I want to cover.
The three-way comparison operator <=> is often just called spaceship operator. The spaceship operator determines for two values A and B whether A < B, A = B, or A > B.
The compiler can auto-generate the three-way comparison operator. You have only to ask for it politely with default. In this case you get all six comparison operators such as ==, !=, <, <=, >, and >=.
#include <compare>
struct MyInt {
int value;
MyInt(int value): value{value} { }
auto operator<=>(const MyInt&) const = default;
};
The default operator <=> performs lexicographical comparison starting the base classes left to right and using the non-static members in declaration order. Here is a quite sophisticated example from the Microsoft blog: Simplify Your Code with Rocket Science: C++ 20's Spaceship Operator.);
}
I assume, the most complicated stuff in this code-snippet is not the spaceship operator but the initialisation of Base using aggregate initialisation. Aggregate initialisation essential means that you can directly initialise the members of class types (class, struct, or union) if all members are public. You can use in this case, a braced-initialisation-list such as in the example. Okay, this was a simplification. Read the details here: aggregate initial.
Before C++20, you can not use a string as a non-type template parameter. With C++20, you can use it. The idea is to use the standard defined basic_fixed_string, which has a constexpr constructor. The constexpr constructor enables it to instantiate the fixed string at compile-time.
template<std::basic_fixed_string T>
class Foo {
static constexpr char const* Name = T;
public:
void hello() const;
};
int main() {
Foo<"Hello!"> foo;
foo.hello();
}
Virtual functions can not be invoked in constant expressions because the dynamic type is not known. This restriction will fall with C++20.
Let me first write about aggregate initialisation. Here is a straightforward example.
// aggregateInitialisation.cpp
#include <iostream>
struct Point2D{
int x;
int y;
};
class Point3D{
public:
int x;
int y;
int z;
};
int main(){
std::cout << std::endl;
Point2D point2D {1, 2};
Point3D point3D {1, 2, 3};
std::cout << "point2D: " << point2D.x << " " << point2D.y << std::endl;
std::cout << "point3D: " << point3D.x << " " << point3D.y << " " << point3D.z << std::endl;
std::cout << std::endl;
}
I assume an explanation of the program is not necessary. Here is the output of the program:
Explicit is better than implicit. Let's see what that means. The initialisation in the program aggregateInitialisation.cpp is quite error-prone because you can swap the constructor arguments, and you will never notice. Here designated initializers from C99 kick in.
// designatedInitializer.cpp
#include <iostream>
struct Point2D{
int x;
int y;
};
class Point3D{
public:
int x;
int y;
int z;
};
int main(){
std::cout << std::endl;
Point2D point2D {.x = 1, .y = 2};
// Point2D point2d {.y = 2, .x = 1}; // (1) error
Point3D point3D {.x = 1, .y = 2, .z = 2};
// Point3D point3D {.x = 1, .z = 2} // (2) {1, 0, 2}
std::cout << "point2D: " << point2D.x << " " << point2D.y << std::endl;
std::cout << "point3D: " << point3D.x << " " << point3D.y << " " << point3D.z << std::endl;
std::cout << std::endl;
}
The arguments for the instances of Point2d and Point3D are explicitly named. The output of the program is identical to the output of the program aggregateInitialisation.cpp. The commented outlines (1) and (2) are quite interesting. Line (1) would give an error because the order of the designator does not match their declaration order. The designator for y is missing inline (3). In this case, y would be initialised to 0, such as using braces-initialisation-list {1, 0, 3}.
Lambas will have many improvements in C++20.
If you want to have move details, go to Bartek's post about lambda improvements in C++17 and C++20 or wait for my detailed posts. Anyway, here are two interesting changes we will get.
Allow [=, this] as lambda capture and deprecate implicit capture of this via [=]
struct Lambda {
auto foo() {
return [=] { std::cout << s << std::endl; };
}
std::string s;
};
struct LambdaCpp20 {
auto foo() {
return [=, this] { std::cout << s << std::endl; };
}
std::string s;
};
The implicit [=] capture by copy inside the struct Lambda causes in C++20 a deprecation warning. You don't get with C++20 a deprecation warning when you capture this explicitly by copy [=, this].
Template lambdas
Your first impression like mine may be: Why do we need template lambdas? When you write a generic lambda with C++14 [](auto x){ return x; }, the compiler automatically generates a class with a templatised call operator:
template <typename T>
T operator(T x) const {
return x;
}
Sometimes, you want to define a lambda that works only for a specific type such as a std::vector. Now, template lambdas come to our rescue. Instead of a type parameter, you can also use a concept:
auto foo = []<typename T>(std::vector<T> const& vec) {
// do vector specific stuff
};
With C++20, we get new attributes [[likely]] and [[unlikely]]. Both attributes allow it to give the optimiser a hint, whether the path of execution is more or less likely.
for(size_t i=0; i < v.size(); ++i){
if (v[i] < 0) [[likely]] sum -= sqrt(-v[i]);
else sum += sqrt(v[i]);
}
The new specifier consteval creates an immediate function. For an immediate function, every call to the function must produce a compile-time constant expression. An immediate function is implicit a constexpr function.
consteval int sqr(int n) {
return n*n;
}
constexpr int r = sqr(100); // OK
int x = 100;
int r2 = sqr(x); // Error
The final assignment gives an error because x is not a constant expression and, therefore, sqr(x) can not be performed at compile-time
constinit ensures that the variable with static storage duration is initialized at compile-time. Static storage duration means that the object is allocated when the program begins and deallocated when the program ends. Objects declared at namespace scope (global objects), objects declared as static or extern have static storage duration.
C++11 has two macros for __LINE__ and __FILE__ to get the information when the macros are used. With C++20, the class source_location gives you the file name, the line number, column number, and function name about the source code. The short example from cppreference.com shows the first usage:
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location = std::source_location::current())
{
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << " "
<< message << '\n';
}
int main()
{
log("Hello world!"); // info:main.cpp:15 Hello world!
}
This post was the first overview of the smaller features in the core language. The next post continues my story with the library features in C+.
concerning likely and unlikely:the code example should be aligned with the proposal:
Hunting
Today 4182
Yesterday 6041
Week 36038
Month 149928
All 10307690
Currently are 162 guests and no members online
Kubik-Rubik Joomla! Extensions
Read more...
the code example should be aligned with the proposal:
the attribute "unlikely" should be placed after the statement.
#include
#include
double func(const std::vector& v) {
double sum = 0.;
for(size_t i = 0; i < v.size(); ++i) {
if (v < 0.) [[unlikely]]
{
sum -= sqrt(-v);
}
else
{
sum += sqrt(+v);
}
}
return sum;
}
not all compilers support the std::basic_fixed_string type already. It should be useful to provide the reader with the basic idea behind the type.
namespace std {
template
struct basic_fixed_string {
constexpr basic_fixed_string(const CharT(&foo)[N + 1U]) {
std::copy_n(foo, N + 1U, m_data);
}
CharT m_data[N + 1U]{};
};
template
basic_fixed_string(const CharT(&str)[N])->basic_fixed_string;
template
using fixed_string = basic_fixed_string;
}
and afterwards the example can look as
//foo takes non-type template parameter
template
class Foo {
static constexpr char const* Name = Str.m_data;
public:
void hello() const {
std::cout
Thanks. I fixed it. | https://www.modernescpp.com/index.php/c-20-the-core-language | CC-MAIN-2022-40 | refinedweb | 1,316 | 56.66 |
The objective of this post is to explain how to use external pin interrupts on MicroPython running on the ESP32. The tests were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.
Introduction
The objective of this post is to explain how to use external pin interrupts on MicroPython running on the ESP32. Please note that some of the code we are going to use here was explained in more detail on this previous post about timer interrupts.
The tests were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board. The MicroPython IDE used was uPyCraft.
The code
First of all, we will import the machine module, which we will use to configure the external interrupts.
import machine
Next we will declare a global variable that will be used by the interrupt handling function to communicate to the main program that an interrupt has occurred. This variable will be a counter, in order for us to not loose interrupts. You can check at this previous post why using a counter instead of a flag for communication between the interrupt and the main code.
Note that we should not perform long operations inside interrupt service routines (such as printing content to the serial console), and thus we will design it to execute as fast as possible. So, as mentioned the interrupt service routine will just inform the main code (by incrementing the counter) that the interrupt occurred, and it will be the main code that will actually handle it.
interruptCounter = 0
We will also use another variable to keep track of how many interrupts have occurred since the program started executing. We will increment it and print its value each time an interrupt occurs.
totalInterruptsCounter = 0
Next we will define the callback function to be executed when the interrupt occurs. This function has an input parameter in which an object of class Pin will be passed when the interrupt happens. Nonetheless, we will not use it in this tutorial.
The actual implementation of the function will consist on incrementing the previously defined interruptCounter variable. Note that this variable needs to be declared as global before we are able to modify it inside the function.
def callback(pin): global interruptCounter interruptCounter = interruptCounter+1
Next we need to create an object of class Pin, which is used to control GPIO pins in MicroPython [1]. You can check all the available parameters for the constructor here. For our program, we will need to pass as input the number of the pin we want to use, the mode of the pin and if it has a pull resistor associated.
For this example, I’m using pin 25, but you can use other. Please note that for some ESP32 boards, the ESP32 GPIO numbers may not match the ones labeled on the board.
We will also set the pin mode to input, with the IN constant of the Pin class.
Finally, we will set the pin to use its pull up resistor, which will guarantee that it will be in a known state (VCC) when no electrical signal is applied. This is done by passing the PULL_UP constant of the Pin class.
p25 = machine.Pin(25, machine.Pin.IN, machine.Pin.PULL_UP)
Next we will specify how the interrupt will be triggered and what is the callback function to execute, by calling the irq function of our Pin object.
For this example, we will specify that the interrupt should be triggered when a falling edge is detected in the input signal connected to the pin. To do it, we need to pass the IRQ_FALLING constant of the Pin class as the trigger argument of the irq function. You can check here all the trigger types available.
We will also specify the handling function by passing our previously defined interrupt function as the handler parameter.
p25.irq(trigger=machine.Pin.IRQ_FALLING, handler=callback)
Since all the configurations are now finished, we will enter in a polling loop to check for our interruptCounter variable. Naturally, we are polling only because our program is very simple and we are not doing anything else. Nonetheless, in a real application, we would most likely be performing some computation or the board would be in sleep mode to save energy, instead of being constantly checking the value of the variable.
When we detect that its value is greater than 0, we will treat the interrupt. First, we will decrement the counter value, to signal that it is going to be handled.
Note that since this variable is shared with the interrupt service routine code, we will previously disable the interrupts, only then decrement the counter, and then re-enable the interrupts, to avoid racing conditions.
The disabling and re-enabling of interrupts is done with the disable_irq and enable_irq functions of the machine module. You can check in more detail how to use them in the previous post.
Finally, we will increment the total number of interrupts counter and print its value. In this case, since this variable is not shared with the interrupt service routine, we don’t need to disable interrupts to change its value.
The final source code for the MicroPython script can be seen below, and already includes the interrupt checking loop.
import machine interruptCounter = 0 totalInterruptsCounter = 0 def callback(pin): global interruptCounter interruptCounter = interruptCounter+1 p25 = machine.Pin(25, machine.Pin.IN, machine.Pin.PULL_UP) p25.irq(trigger=machine.Pin.IRQ_FALLING, handler=callback) and run it. Upon running, the easiest way to trigger an interrupt without the need for external hardware is to connect and disconnect the pin where the interrupt was attached to the board’s GND pin.
Please be careful when executing this procedure to avoid connecting the GND pin to the wrong GPIO and damage the board.
You can check below at figure 1 the result from the interrupts.
Figure 1 – ESP32 MicroPython external pin interrupts.
Related posts
- ESP32 MicroPython: Timer interrupts
- ESP32 Arduino: Timer interrupts
- ESP32 Arduino: External interrupts
References
[1] | https://techtutorialsx.com/2017/10/08/esp32-micropython-external-interrupts/ | CC-MAIN-2017-43 | refinedweb | 1,010 | 60.24 |
Hi,
This message was posted using Page2Forum from SetLicense Method - Aspose.Words for .NET
Hi,
Ah! I’ve discovered that it throws an InvalidOperationException with a message along the lines of:
Hi
Thanks for your inquiry. Yes, you are right, Aspose.Words throws an exception when you attempt to set an invalid license.
Also, for testing purposes, you might find the following method useful:
/// Returns true if the Aspsoe.Words license is set.
///
private static bool IsLicenseSet()
{
// We will insert this text at the beggining of the document.
// If the license set this text will be in the first paragraph,
// if not an evaluation watermark will be in the first paragraph.
const string text = "This is text used to check if the license is set";
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write(text);
// Save and optn the document. If Aspose.Words works in evaluation mote it will add a watermark.
using (MemoryStream docStream = new MemoryStream())
{
doc.Save(docStream, SaveFormat.Doc);
docStream.Position = 0;
doc = new Document(docStream);
}
// Check text of the first paragraph.
return (doc.FirstSection.Body.FirstParagraph.ToTxt().Trim() == text);
}
Best regards, | https://forum.aspose.com/t/what-happens-if-the-license-is-invalid/65045 | CC-MAIN-2022-21 | refinedweb | 187 | 51.55 |
Easy API Response with Jb18 May 2021
A well-structured web application codebase is extensible and maintainable. MVC framework is a software design pattern allowing us to achieve that goal. The framework decouples the component for interface, internal business logic, and data persistence layer so that we can easily modify each of them without affecting other building blocks.
We can say the same thing for the REST API application as well. While that type of application does not have a clear view presented to users, separating the logic to construct the API response from the internal business logic is still critical to develop the extensible and scalable web application.
This time, I found jb is helpful for that purpose. It is a simple Ruby library, and we can quickly get it integrated with your Rails application. The library proved to be neat and handy in my own Rails application. If you want to get the sorted architecture for the Rails REST API application, jb should be your help.
How to use jb
The fun will start by putting the template file in the view directory with the extension
*.jb.
jp_users = if @users.jp.present? @users.jp.map do |r| { 'region' => 'jp', 'first_name' => r.first_name, 'last_name' => r.last_name }.compact end else [] end us_users = if @users.us.present? @users.us.uniq(:id).map do |r| { 'region' => 'us', 'first_name' => r.first_name, 'last_name' => r.last_name, 'middle_name' => r.middle_name.present? ? 'N/A' : r.middle_name }.compact end else [] end { 'users' => jp_users + us_users }
In the corresponding controller, all we need to do is retrieving users.
def users @users = Users.all if exceed_max_screening_result(@users) render json: { 'message': 'Too many users' }, status: :bad_request else render formats: :json, status: :ok end end
It renders the following response.
{ "users": [ { "region": "jp", "first_name": "Kai", "last_name": "Sasaki" }, { "region": "us", "first_name": "Joe", "last_name": "Biden", "middle_name": "Robinette" } ] }
In the template file, we can use ActiveModels or modules available in the Rails application and the helper method used typically for rendering the view. As you have seen, We can encapsulate all complexities involving the response construction in the template file. That is a great advantage using jb as an API response builder. | https://www.lewuathe.com/easy-api-response-with-jb.html | CC-MAIN-2021-49 | refinedweb | 356 | 56.66 |
Mergers and Acquisitions: Private Equity (PE) Firms
In some situations, you may consider acquiring a company from a private equity (PE) firm, a pool of money that buys companies with the intention of reselling them later for a sizable profit. PE firms can be very motivated Sellers.
But be warned: They’re also extremely crafty deal-makers. After all, buying and selling companies is their industry. They’re experts. Here are some considerations to keep in mind as you look at dealing with a PE firm.
Understand why PE firms sell
Because PE firms are in the game to make money (and who isn’t?), a PE firm will eventually be looking to exit its investment (which may now include some add-on acquisitions).
PE firms also hear the constant ticking of the internal rate of return (IRR), one of the key metrics they like to flaunt when raising capital. In a nutshell, the longer a PE firm holds an investment, the greater the chance the IRR will be lower than the PE firm prefers.
Evaluate a PE firm’s portfolio company
Here are a few specific suggestions to look at for a PE firm’s portfolio companies.
Does the company fit with your goals? This question is pretty basic, of course, but as Buyer, take care when evaluating the fit of a portfolio company with your company. Despite the great case the PE firm may make for the portfolio company, a company that doesn’t fit your goals isn’t that great a deal.
How will the company’s earnings affect your earnings? If the acquired company’s earnings increase your earnings, they’re accretive; if they decrease your company’s earnings, they’re dilutive. Decide whether a potential earnings hit matters to your company. Consider also whether the acquired company will eventually be able to generate higher earnings for the entire firm if earnings take an initial hit.
Is the company actually an integrated set of other companies? PE firms often cobble together multiple companies into one integrated firm. This setup is perfectly fine, and PE firms often do a wonderful job of integrating, but you need to be wary of just how well organized formerly disparate companies have been integrated.
How long has an integrated company been operating (since the last acquisition)? If the acquired company is actually a group of formerly independent companies, don’t make an acquisition too quickly. Waiting awhile (at least a year) to make sure these formerly independent companies are operating as a cohesive unit is a good idea. | http://www.dummies.com/how-to/content/mergers-and-acquisitions-private-equity-pe-firms.navId-815544.html | CC-MAIN-2015-22 | refinedweb | 427 | 53.31 |
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo
You can subscribe to this list here.
Showing
2
results of 2
Notepad++ is a very nice editor. I am using it for almost all of my text
file processing, and for any program file viewing that will not require a
build. ( If I need to make changes for building a program, I still use the
IDE. )
Questions:
1. Is there any way to configure Notepad++ to include Filename, current
date, current time, page numbers, ... information in printed output?
2. It would be nice if the user define dialog allowed me to export and
import user definitions. I would like to share my language definition with
another developer for example.
3. is it possible to use regular expressions in the user define dialog?
For example, I am editing a script language that has both an "ON" verb, and
an "ON" option. When used as a verb, it is always "^ *ON" (at beginning of
line with optional leading spaces) and should be displayed in the color for
commands. When used as an option (ex. set option on) then it should be
described as "^ *[^ ]* +on" and displayed with a different color.
4. the folder keywords do not seem to be working for my user defined
language. I have a script language that contains WHILE ... ENDWHILE
blocks. I have defined WHILE as the beginning of a folder, and ENDWHILE as
end of folder, but these do not seem to be recognized.
Michael Giroux
When I want to "Save As", no file name comes up in the Save Box. Is
there a way to make the File name appear there so it doesn't have to be
re-typed everytime? I save emails first to C: drive, edit them with
Notepad++, then re-save them to C: drive, then Save As on A: drive. At
this last step, the file name box is blank and I have to re-type in the
file name. Is there a way around this that I just can't do right?
Thanks, Ken | http://sourceforge.net/p/notepad-plus/mailman/notepad-plus-plus/?viewmonth=200502&viewday=4 | CC-MAIN-2015-18 | refinedweb | 355 | 80.72 |
Created on 2007-12-18 15:41 by cjwatson, last changed 2019-09-09 14:40 by gregory.p.smith. This issue is now closed.
On Unix, Python sets SIGPIPE to SIG_IGN on startup, because it prefers
to check every write and raise an IOError exception rather than taking
SIGPIPE. This is all well and good for Python itself. However,
non-Python Unix subprocesses generally expect to have SIGPIPE set to the
default action, since that's what will happen if they're started from a
normal shell. If this is not the case, then rather than taking SIGPIPE
when a write fails due to the reading end of a pipe having been closed,
write will return EPIPE and it's up to the process to check that. Many
programs are lazy and fail to check for write errors, but in the
specific case of pipe closure they are fine when invoked from a normal
shell because they rely on taking the signal. Even correctly written
programs that diligently check for write errors will typically produce
different (and confusing) output when SIGPIPE is ignored. For instance,
an example only very slightly adapted from one in the subprocess
documentation:
$ dd if=/dev/zero of=bigfile bs=1024 seek=10000 count=1
1+0 records in
1+0 records out
1024 bytes (1.0 kB) copied, 0.000176709 seconds, 5.8 MB/s
$ cat bigfile | head -n0
$ cat t.py
from subprocess import Popen, PIPE
p1 = Popen(["cat", "bigfile"], stdout=PIPE)
p2 = Popen(["head", "-n0"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
$ python t.py
cat: write error: Broken pipe
In some cases this problem can be much more significant. For instance,
it is very common for shell scripts to rely on SIGPIPE's default action
in order to behave correctly. A year or two ago I ran into this in OS
installer code I was writing in Python, which called some underlying
utility code in shell and C to deal with disk partitioning. In the event
that the Python code failed to handle an exception, the shell script
being run in a subprocess would spiral out of control rather than
cleanly exiting at the first sign of trouble. This actually caused
massive data loss on several testers' systems and required a quick
release to fix
( and). Now
obviously this was ultimately my fault for failing to catch the
exceptional condition in testing, but this misdesign in Python and the
lack of any documentation of this gotcha really didn't help at the time.
For the record, the fix was to call this in a preexec_fn:
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
This is an area of Unix that's very easy to get wrong. I've written my
own subprocess handling library in C for another project, and I still
found it non-trivial to track this down when it bit me. Since it
essentially arises due to an implementation detail of the Python
language, I think it should also be Python's responsibility to fix it up
when subprocesses are involved.
There are many ways to invoke subprocesses in Python, but the new,
all-singing, all-dancing one is of course the subprocess module. I think
it would be sufficient for that to do the right thing, or at least have
an option to do so, and it's certainly the easiest place to add the
option. I'm attaching a suggested patch which adds a restore_sigpipe
option and documents it in what seem to be all the relevant places.
Note that nearly all the examples end up with restore_sigpipe enabled.
In some future release of Python, I think this should be the default.
I'm not entirely familiar with migration plan processes in Python; how
should this be done?
Raising priority.
What incompatibilities could occur if SIGPIPE is restored by default?
To be quite honest I can't think of any incompatibilities that wouldn't
have the basic result of improving matters. I put the migration stuff in
my bug report in case somebody else could, because I don't want the bug
fix to stall on that.
My preference would be for Python to move to behaviour equivalent to
restore_sigpipe=True in the next release, but I would rather that it
gained restore_sigpipe with the wrong default than that it didn't gain
it at all.
Martin, what do you think?
The patch as it stands (subprocess-sigpipe.patch) definitely can't go
into 2.5.x: it introduces a new feature.
It's not clear to me whether Colin intended to target it for 2.5.x, as
it is against the trunk. For the trunk, the patch is fine.
Regargeting for 2.6. Colin, if that wasn't your intention, please speak up.
2.6 is fine if that's what the release process dictates; I don't want it
to be lost, that's all.
Is there anything more I can do to move this along? Thanks.
Find someone to review the patch and post their evaluation here. It
doesn't have to be a committer, though that would be even better.
Hmm. Looks like the patch is missing a unit test for the new feature.
I think restore_sigpipe=True would be a reasonable default.
As RDM says, adding an unit test would be better, but it may be difficult to do so (we probably can't spawn Python itself since it will change the default SIGPIPE handler at startup).
Looking at the patch, you don't need to import `signal` again: it's already imported at the top level.
Yes, we set SIG_IGN in Python/pythonrun.c initsigs() on SIGPIPE, SIGXFZ & SIGXFSZ.
We should restore these to SIG_DFL prior to exec by default. I'm in the middle of working on subprocess improvements that touch this code, I'll include this.
A restore_signals parameter was added in py3k r78946.
I'm leaving this issue open as it needs backporting to 2.7.
Fixed an oversight on the switch None ==> -1 which prevents compilation on some buildbot. See r78961.
GHC Haskell compiler is currently opting for a different solution: installing an default empty handler which is cleared by exec automatically and signal handler is restored back to SIG_DFL:
closing because it is too late to backport this to 2.7. It is available as a backport in.
As for the idea of not using SIG_IGN and installing a default no-op handler, that is another approach.
signal.getsignal would need to be able to return it so that software wanting to temporarily handle its own sigpipes could restore that behavior afterwards. | https://bugs.python.org/issue1652 | CC-MAIN-2020-05 | refinedweb | 1,108 | 71.85 |
second session that is available on demand, with a summary below from the presenter, Canadian MVP Colin Bowern.
One of the joys of having an MSDN subscription is being able to keep current with the tooling. With the recent release of Visual Studio 2013 there are a lot of smaller reasons to keep current, and that story keeps getting more compelling with each Update released. In the video below, recorded live at ObjectSharp’s “At the Movies”, I highlighted some of the smaller aspects of the new release that make it compelling to upgrade.
Backwards Compatibility
If you use Visual Studio 2012 today you should be able to jump right into Visual Studio 2013 while the rest of the team upgrades. With backwards compatibility in solution and project format you can get all the goodness in the tools update while the rest of the team catches up. There are still some cases where things were not carried over, but if you are one of the two people still using FrontPage Web Sites it is time to check out ASP.NET Web Pages.
Settings Sync
Whether you get a new workstation or need to rebuild yours one of the time consuming tasks is getting everything setup just the way you want. Now you can optionally sign in with your Microsoft Account to Visual Studio and have key settings synchronize with the cloud including:
- Development environment settings (the dialog you see on first launch)
- Theme settings
- Fonts and colors
- Keyboard shortcuts
- Startup options
- Text Editor options
- User-defined command aliases
Browser Link
As a web developer we tinker a lot in the browser with markup and styles. The nature of the user agent rendering differences requires the real-time editing to build pixel perfect layouts. The web tooling team knows this all too well and using the power of SignalR created a bi-directional pipeline between the browser and source code called Browser Link. During the session I highlighted:
- Matching elements in the browser and source code using an Inspect tool
- Changing element content in the browser and having it reflect in the source using the Design mode
- Changing CSS (and LESS!) in the browser developer tools and having it Auto-sync with the source code
There was not enough time to show off the ability to identify unused CSS classes, but if you are designing bandwidth sensitive apps then this is a great insight to your stylesheets.
Edit and Continue
With a shift towards 64-bit computing well underway the desire to edit-and-continue during debug sessions regardless of bitness. This change required an underlying CLR change which is one reasons, among others, for .NET Framework 4.5.1. With that in place we can move forward with editing on the fly as we debug. It would be great to see lambda support added now that we have this, so be sure to add your support to see this investment continue.
Return Value Inspection
When trying to inline functions there are times where you want to see the individual return values during debugging:
static void Main()
{
var result = Multiply(Five(), Six());
}
private static int Multiply(int num1, int num2)
{
return (num1 * num2);
}
private static int Five()
{
return 5;
}
private static int Six()
{
return 6;
}
Next time just pop open the Debug > Window > Autos window and look for the return value there:
Performance and Diagnostics Hub - JavaScript included too!
We have come full circle where performance matters again. The tooling to profile our applications has been built into the IDE for a while now, but it has not always been the easiest to use. With so much emphasis on performance in the mobile and web space the way in which we start profiling apps has had a rethink. The Performance and Diagnostics Hub builds on the investments in Visual Studio 2012 and the subsequent updates to make it easy to understand how your app is performing. As someone who spends a lot of the time in the web one aspect that delighted me was being able to see the ability to trace memory, responsiveness, and CPU usage across the server and browser in the same view.
The release cadence for Visual Studio is speeding up - get the most out of your tools by grabbing the latest today and watch out for exciting updates shipping soon! | https://blogs.msdn.microsoft.com/cdndevs/2014/05/30/something-for-everyone-in-visual-studio-2013/ | CC-MAIN-2019-13 | refinedweb | 724 | 52.23 |
How Wikipedia Works/Chapter 10
Contents
- 1 Chapter 10: The Life Cycle of an Article
- 2 Birth of an Article
- 3 Deletion
- 4 Maintenance Tagging
- 5 Editing Improvements
- 6 Potential Merge
- 7 Discussion and Content Tags
- 8 Categories
- 9 Bots Arrive
- 10 Incoming Wikilinks
- 11 Artie Is Moved
- 12 In Good Times
- 13 In Bad Times
- 14 Bad Times, and a True Story
- 15 Search Engines Find the Article
- 16 New Relatives
- 17 Getting the Picture
- 18 Good Article
- 19 Summary
- 20 Conclusion to Part II
Chapter 10: The Life Cycle of an Article[edit]
So far, we've broadly examined Wikipedia from the perspective of readers and editors. Of course, a Wikipedia reader can come and go as he or she pleases, and even the most ardent Wikipedia editor abandons his or her computer from time to time. But a Wikipedia article is always on the website, day in and day out.
So, how do things look from that article's perspective?
Let's follow Artie the Article, created by Eddie the Editor. Perhaps Artie's title is Gingerbread cottage architecture, the title used previously in Chapter 6, Good Writing and Research.
Birth of an Article[edit]
Eddie types Gingerbread cottage architecture into the search field. He discovers the article doesn't yet exist, follows the Start the Page link from the search page, and composes a few sentences. He clicks the Save Page button: Artie is born.
The moment Eddie saves his new article, it goes "live" and can be linked to and discovered through the search function. But, just as importantly, its title is immediately displayed at the top of a list called Special:Newpages. This page lists the 5,000 most-recently created articles. Gingerbread cottage architecture will slide down the list for two or three days as other editors—and possibly Wikipedia administrators on patrol—review these new articles.
After this preliminary review, many outcomes are possible.
Deletion[edit]
Wikipedia articles are created in a hostile environment, and stub articles—those short compositions of just a few sentences—are in particular peril. They are no more than tadpoles in the Wikipedia pond. New articles that do not seem appropriate for the site are often flagged for deletion as they are reviewed by other editors; this is the fate of hundreds of articles a day, many of them well meaning.
Eddie should therefore keep an eye on his article. If the content is very poor—if it contains graffiti or is un-encyclopedic, or if the topic does not seem adequately referenced for notability—a red-bar template might be added to the beginning of the text, nominating the article for deletion. (There are three types of deletion nominations, each using a different template; see Chapter 7, Cleanup, Projects, and Processes.)
Eddie should not remove a deletion template himself, but he can contest the deletion nomination. For example, he can contest a speedy deletion nomination by adding the Template:Hangon template to the article just below the deletion template and then immediately arguing his case on the article's talk page.
If a deletion tag is added to an article and is not contested, Artie's future is bleak, so Eddie needs to find out about any deletion nominations as soon as they happen. Eddie can keep track of changes to his article in a few ways:
- Eddie can add the article to his watchlist by checking Watch this page (this is done by default for pages you create). Eddie's watchlist will reveal nominations for deletion and other edits to the article.
- Eddie can check his user talk page. Any time an article is nominated for deletion, its creator should be informed via the creator's talk page (in this case, a message should be left on User talk:Eddie). This is not fail-proof, however, as not all editors may follow this custom.
- Eddie can keep a braglist in his user space—a list of links to articles he has created. If he puts the braglist on its own page (for example, [[User:Eddie/Articles I created]]), then he can click the Related Changes link from that page for a convenient list of recent edits. This solution is even better than monitoring a watchlist for keeping an eye on just the articles you have created.
If other Wikipedia editors judge the article's content as being good enough, Artie will avoid immediate deletion. Now comes the work of improving the article.
Maintenance Tagging[edit]
As they come across articles that need attention, editors tag those articles for maintenance. Many of these yellow-bar templates might be added at the beginning of the article. For instance, if the article needs formatting work or rewriting for clarity, the {{cleanup}} tag might be added; if there are no good references, it is likely that the {{unreferenced}} tag will be placed on the article. Other yellow-bar templates may be more technical, for example, {{film-fiction}}: This film-related article may fail to make a clear distinction between fact and fiction. Particular criticisms of the writing standard may appear as orange-bar templates. For example, Template:Wikify may be added if the article could use more wikilinks. Eddie shouldn't take these templates personally—he's getting feedback on his work and now knows how the article needs to improve. It is a good idea for Eddie to do what he can to fix the article in response to any such messages.
If Artie is still a stub (in other words, just a beginning treatment, lacking something essential), editors may tag him with a {{stub}} template. But since stubs are actively sorted by category (Chapter 8, Make and Mend Wikipedia's Web), this general stub template will probably be replaced by a more specific one. For example, {{fairy-tale stub}} denotes all stubs about fairy tales, and this tag would be an appropriate one to add to Gingerbread cottage architecture. One side effect of this template being added is that Gingerbread cottage architecture will be placed in a category with similar articles that still need work, such as List of mermaid supermodels and Great Pumpkin appearances in 2008.
Editing Improvements[edit]
As soon as an article is created, other editors may set to work improving and adding to the content. Basic formatting work is often done quickly. If an article is about something in the news or an ongoing event, an editor may add a blue-bar template indicating that the article is time critical. Time-critical articles are also likely to be edited a great deal.
If the article is not about a high-profile topic (the vast majority of topics are low-profile), it might not get edited for a while. Editing might also occur in fits and starts; another editor interested in substantively working on the article may not come along for months or even years. WikiProjects generally maintain a list of new articles in their subject area, so Eddie's article may be added to one of those lists and thrive from expert attention. (Gingerbread cottage architecture might be well received at WikiProject Fairytales, for example.)
Potential Merge[edit]
Artie is not out of the woods yet. He might still be merged into an existing article, for instance, Building in folklore. One editor might feel strongly that material about a common topic has been included in many Wikipedia articles and would be better presented in a single article. Sometimes a duplicate article might not be discovered for months if it is not properly categorized and linked to other articles—did someone else create Architecture of gingerbread cottages, with similar content?
The procedural side of merging was covered in Chapter 8, Make and Mend Wikipedia's Web. If an editor proposes a merge, he or she will flag the article with a purple-bar template.
If Artie is merged, then the content created by Eddie will be included in a larger article that subsumes the gingerbread cottage architecture material. Artie will not be gone but will have become a humble redirect page. Eddie should dispute any hasty merge or redirect proposals by simply discussing them on the relevant article talk pages.
Discussion and Content Tags[edit]
A reader or editor, quite possibly someone visiting Wikipedia who is not a regular, may query what the article says. Is it true? Is it the whole truth? Is it slanted? Can a reference be provided for a specific assertion? These points will likely be added to Talk:Gingerbread cottage architecture; though in some cases, remarks might be added to User talk:Eddie—let us hope politely.
This kind of input is a further chance to improve Artie's clarity and accuracy. Comments may also take the form of orange-bar templates. For example, the template {{NPOV}} indicates that someone thinks the article fails to be neutral (does not conform to the Neutral Point of View policy). Whoever added that template should also add comments indicating his or her reason. Templates raising content issues, if not totally self-explanatory, should always be backed up by talk page comments that address the problem or slant in specific terms. Without such a detailed note, Eddie might be mystified as to what needs fixing.
If Eddie is still watching the article, he should respond to all reasonable queries rather than become annoyed. Certainly simply removing a tag requesting some sort of clarification does an article no favors, unless the tag is entirely undeserved. Having a tag on an article for a while does little actual harm, and it is normal for content to be rewritten on Wikipedia, even if the issue raised only relates to cosmetic improvements in writing style.
Categories[edit]
Readers can easily find an article about a broad topic (like the United States) but have more difficultly finding an article about a smaller or more specific topic—especially if they don't know the article's exact title. These less prominent articles are often found by editors searching a category.
The chance of an editor finding an article—and correspondingly editing it—improves if the correct category tags have been added. Eddie might do this himself. If you're starting a new article (or undertaking an edit of one), pay attention to the categories that similar articles have been placed in.
It doesn't matter if early categories aren't perfect. Even an approximate category can put an article into a position where an expert can apply the appropriate subcategories.
Bots Arrive[edit]
Editors who happen to be programmers can write software for making certain types of procedural edits automatically. These programs are nicknamed bots, and Artie may be visited by a slew of them over his life. Some will make spelling corrections or small formatting changes in compliance with Manual of Style guidelines, while others analyze the content of a new page—by keywords, for example—and log it to various lists kept as project pages. (The logs can be detected in the backlinks.) Any edits made by bots will be clearly visible in the article's history, just like edits made by human editors; a bot is just another type of account. (A bot's username almost always indicates that it's a bot, not a human, for example, Sinebot, the bot that goes around signing comments on talk pages when editors fail to do so.)
If Artie hasn't been categorized, Artie's first bot edit might be the addition of an {{uncategorized}} tag. Note See a bot misbehaving? You can normally contact the bot's programmer via the bot's user talk page. So Eddie has some recourse if a bot messes up his article with some automated edit; Eddie should revert the edit but also notify the bot's owner.
Incoming Wikilinks[edit]
In our full review of article creation in Chapter 6, Good Writing and Research, you learned that wikilinks pointing to the new article should be added to related articles (which can themselves be found through the search function). In fact, these links should ideally be added before the new article even exists.
If Eddie is experienced at creating articles, he will consider incoming wikilinks from the outset. How many pages are displayed, as soon as Artie is created, when clicking the What Links Here link on the sidebar? Eddie should check. Being born an orphan would not be so much fun for Artie. If Eddie doesn't add links to his article, someone else might add the Template:Orphan yellow-bar template to it, placing Artie in.
If there aren't any links to the article, there could be several explanations. For example, the chosen title for Artie the Article, Gingerbread cottage architecture, might be unconventional or spelled incorrectly. It is also possible that the concept or article title is in fact mentioned in other articles but simply has not been wikilinked. After creating the article, Eddie can still create links to Artie. Creating wikilinks will also (and subtly) draw attention to his article because the wikified pages are likely on the watchlists of editors already working in related areas. Eddie should create redirects to Artie from other possible titles, too.
An Example of Keyword Analysis
The article Carter B. Magruder, about an American general, was picked up shortly after its creation in September 2007 by a bot run by Alex Bakharev. The bot added the article to 22 logs, such as User:AlexNewArtBot/OhioLog, User:AlexNewArtBot/VirginiaLog, User:AlexNewArtBot/WWIILog, and User:AlexNewArtBot/ColdWarLog. These are simply short-term lists of new articles, kept in the User namespace and created by analyzing the article text. These logs are now routinely passed onto relevant WikiProjects, similar to the style of a Google Alert. The entry in User:AlexNewArtBot/OhioLog, a list of new articles related to Ohio, was not caused by the occurrence of Ohio in the text but by the occurrence of Cincinnati, in the phrase Society of the Cincinnati (which refers to a historical association, not the city in Ohio).
Thus bots clearly have limitations: They can suggest that articles are related to a topic area when they aren't, and they can occasionally make other mistakes a human would not make. Of course, anyone can undo edits that are not helpful and remove an article from a category or log if necessary.
Artie Is Moved[edit]
A Wikipedia move is actually a rename—something Artie might experience early in life. Particular conventions sometimes govern titles, and articles are often renamed by people familiar with those conventions. (For example, a lowercase title might be capitalized or vice versa.)
A page move, carried out by someone well meaning, might draw more attention to Artie, which might, in turn, draw more incoming links. (Artie will, of course, retain all his old wikilinks even after being renamed.) A move may also create double redirects (see Chapter 8, Make and Mend Wikipedia's Web), a technical problem that should be fixed by the article mover.
In Good Times[edit]
If all goes well, other editors will develop Artie further. Suppose Fred and Greta like what Eddie has written but think the article could be developed. Fred may standardize the formatting and add wikilinks, external links, and references, improving the article's appearance and its credibility. Greta may divide the article into sections, sorting the different aspects of the topic into some more consistent, logical order. Creating a conventional lead section that tells readers quickly whatthe content covers always helps an article. Greta will have a better idea about this once she is done with the restructuring. Perhaps, in a whimsical mood, she will even take her camera into the woods and shoot some photos of gingerbread cottage architecture.
Fred's efforts at wikifying will probably leave redlinks in Eddie's article—in other words, suggestions for more articles to write to develop Wikipedia. If these redlinks provoke Harold and Isabel, two more interested editors, to create useful new articles, Artie has really arrived in Wikipedia, and Eddie has contributed to developing the overall coverage of the topic.
In Bad Times[edit]
As editors insert additional information, the article might actually get worse, stylistically! When new facts are not integrated properly, they can upend the article's structure and muddy its writing style. (Sometimes this happens when the editors adding those facts aren't familiar with the topic or aren't fluent at editing Wikipedia.) If this continues, Artie could be destined for mere mediocrity. A strong-minded editor could step in and restore an earlier, cleaner version, do a thorough re-write, or take a red pencil to incremental changes that were not, in fact, beneficial.
When adding to articles, keep the article's overall structure in mind. Although adding a new fact onto the end of a convenient paragraph is easy, integrating that fact squarely into the article is much more helpful.
On a more positive note: Articles, on average, tend to improve over time.
Bad Times, and a True Story[edit]
Beginning on the day Artie is created, an edit war could erupt over his content, a passing vandal could deface the article, or a user could accidentally delete a chunk of vital content. These risks become more acute as more people read the article. In extreme cases, an article may be protected (or semiprotected), which halts the damage but also may prevent improvement. A gray-bar template indicates an article is protected, but full protection should only be temporary.
Another, more serious danger is that Artie may be nominated for Articles for Deletion. If the content really is worthy of an encyclopedia article, this will be a nerve-wracking time for Eddie. Even if Artie should by rights survive, the result can go the wrong way, especially if the writing is poor. That would be the end of Artie, unless a salvage mission during Deletion Review succeeds. (Deleted articles should not be re-created for six months.)
One deletion debate over a new article, which happened on September 17, 2007, has become Wikipedia legend.
During the heat of the debate, the discussion about whether a business was notable enough to have a Wikipedia page seemed typical. (Employees or others associated with a business often start these types of articles, raising questions of notability and conflict of interest.) Indeed, the article's first few hours were filled with the types of wiki perils we've discussed in this chapter. We've reprinted partof the article's edit history here; you can read what happened in reverse chronological order, just as the history would display on the site. At 11:51, less than three hours after creation, the article had been nominated for deletion, and subsequent edits were attempts to improve the article in order to influence the deletion vote.
The punchline, though, is at the bottom of the article history, in the first edit: Despite the typical arc of its debate, this was not a business trying to promote itself.
Article History:
- 12:13, September 17, 2007 Wikidemo (Talk | contribs) (2,206 bytes) (?Description - add material) (undo)
- 12:00, September 17, 2007 David Eppstein (Talk | contribs) (1,745 bytes) (?External Links - another blog entry, from Jimbo's old version) (undo)
- 11:54, September 17, 2007 Carcharoth (Talk | contribs) (1,610 bytes) (add three more) (undo)
- 11:51, September 17, 2007 ^demon (Talk | contribs) (1,529 bytes) (Nominated for deletion; see Wikipedia:Articles for deletion/Mzoli's Meats.) (undo)
- 11:50, September 17, 2007 Cobaltbluetony (Talk | contribs) (1,312 bytes) (dunno how the tag got back on...) (undo)
- 11:49, September 17, 2007 Cobaltbluetony (Talk | contribs) m (moved Mzoli's to Mzoli's Meats: full name of establishment) (undo)
- 11:48, September 17, 2007 EVula (Talk | contribs) (1,327 bytes) (contesting prod; I think if we give this article a bit more than a couple of hours of existence, we might have something worthwhile) (undo)
- 11:46, September 17, 2007 Carcharoth (Talk | contribs) (1,695 bytes) (hmm, we don't have a category on butchers, I'm not surprised) (undo)
- 11:46, September 17, 2007 Carcharoth (Talk | contribs) (1,717 bytes) (add categories) (undo)
- 11:44, September 17, 2007 ^demon (Talk | contribs) (1,645 bytes) (Proposing deletion) (undo)
- 11:40, September 17, 2007 Cobaltbluetony (Talk | contribs) (1,277 bytes) (notability needed according to wiki standards) (undo)
- 11:36, September 17, 2007 Melsaran (Talk | contribs) (1,262 bytes) ("famous" is a value judgement, and it is not really relevant anyway + doesn't add anything to the article. the fact that some sources call it famous doesn't mean that we should.) (undo)
- 11:34, September 17, 2007 Wikidemo (Talk | contribs) m (1,269 bytes) (restoring "famous" - source says it is; other coverage suports claim.) (undo)
- 11:30, September 17, 2007 Grcampbell (Talk | contribs) (1,262 bytes) (how is it famous??) (undo)
- 11:18, September 17, 2007 EVula (Talk | contribs) (1,269 bytes) (removing G11 tag; just because we have an article on a company doesn't mean that it is spam) (undo)
- 11:08, September 17, 2007 Cobaltbluetony (Talk | contribs) (1,281 bytes) (spam) (undo)
- 11:05, September 17, 2007 Wikidemo (Talk | contribs) m (1,269 bytes) (Undid revision 158530993 by Deb (talk) rm advertising tag - this is not written as an ad; it simply reports sourced info) (undo)
- 11:03, September 17, 2007 Deb (Talk | contribs) m (1,280 bytes) (tag) (undo)
- 11:01, September 17, 2007 Wikidemo (Talk | contribs) (1,269 bytes) (write new article; have not seen deleted version but this is new, sourced content that claims importance/notability of subject) (undo)
- 09:55, September 17, 2007 ^demon (Talk | contribs) deleted "Mzoli's" ? (CSD A7 (Corp): Article about a company that doesn't assert significance)
- 09:37, September 17, 2007 Jimbo Wales (Talk | contribs) (275 bytes) (just collecting some links as a base for writing more) (undo)
- 09:33, September 17, 2007 Jimbo Wales (Talk | contribs) (206 bytes) (just a stub for now, will be adding pictures and more in coming days... I need help finding reliable sources though)
That final line, at 9:33, reveals the original creator of the article: one Jimmy "Jimbo" Wales, founding father of the Wikipedia site. Jimbo's original stub of a few lines was speedily deleted after around 20 minutes on the site!
During the first few hours that Wales' article about a celebrated South African restaurant existed, it was put through all three deletion processes mentioned in Chapter 7, Cleanup, Projects, and Processes. First, the article was speedily deleted and then re-created by another author. Then it was tagged as advertising and then untagged. It was tagged as spam and nominated for a second speedy deletion. This nomination was contested; the nominator then nominated it again for proposed deletion (PROD).
This proposed deletion was again contested, so the deletion nominator called for the final deletion process at Articles for Deletion (AfD). AfD debates are intended to last five days, so this debate went on at Wikipedia:Articles for deletion/Mzoli's Meats (note that the content only exists in the page history, as this page was wiped blank and protected, an example of a courtesy blanking). The debate was closed on September 19, 2007, and the article was kept. Mzoli's Meats eventually grew into a substantial piece, with a photo and a dozen references.
This article went through the entire deletion process and survived. Its story was even featured in the LA Times. [24] Other articles are not so lucky; most pieces suspected of being covert promotion—or simply of being about non-notable topics—will face some deletion attempts, and many of these attempts will succeed. The majority of deletion debates are not as controversial as this example, however; this debate garnered extra attention both because the article was begun by Wales and because it became something of a celebrity cause within the community, discussed on the Village Pump (see Chapter 12, Community and Communication) and in one of the ongoing mailing-list discussions about how deletions are conducted.
[24] See David Samo, "Wikipedia Wars Erupt," Los Angeles Times, September 30, 2007,
Search Engines Find the Article[edit]
As soon as an article such as Artie is created, it will be indexed and findable using Wikipedia's built-in search. General-purpose search engines will be able to find Artie within a few weeks or sometimes even sooner—within a day or two for Google. Once registered by search engines, Artie will have much greater prominence on the Web. People searching the Web generally, not specifically looking for a Wikipedia article, will begin to read the article as it shows up in their search results. This can have a good or bad effect on the article's quality. Experts in the topic may contribute to it, but random outsiders could also commit vandalism. For Artie's sake, we hope that he is now on some attentive editors' watchlists.
New Relatives[edit]
Over time, Artie's content will propagate outward in two ways: It will be copied verbatim, and it could be translated into other languages.
Within about a month, non-Wikipedia websites will grab Artie's content and reprint it in full. These mirrors are perfectly legal as long as they respect the GFDL license. As these copies spread across the Web, Artie's content on Wikipedia can stay more relevant by being continuously updated.
Artie's content might also be translated to provide content for Wikipedias in other languages. These new wiki articles may attract further edits, and their content may begin to diverge from the original article.
One caveat: If Artie contains mistakes, so will Artie's mirrors and translations—and even if the mistake is fixed in Artie, it will remain on the mirror sites (at least until the mirror sites refresh their content from the latest version of Wikipedia) and in translations (until someone corrects it manually).
Getting the Picture[edit]
A picture is a worth a thousand words.
Eddie might be tempted to find a relevant image somewhere on the Internet, upload it to Wikipedia, and add it to his article, but unless the image is public domain or GFDL-licensed (and most are not), this addition will lead to nothing but trouble. Non-free images are aggressively deleted from Wikipedia; they live only as long as cut flowers—a few days at most.
Instead, Eddie might take a photograph himself (or create a graphic). Or he might search for relevant images in other Wikipedia articles or on Wikimedia Commons.
Good Article[edit]
Assuming Eddie's article avoids the hazards discussed so far, Artie may be developed by skilled editors who know how to improve pages step by step. And apart from regular editing, these editors might send Artie through a number of structured improvement processes, for example, a formal peer review. If Artie is officially recognized as a good article, more possibilities open up, including induction into that rarified stratum called featured articles. The main page beckons!
Article Quality
Only about 0.1 percent of articles qualify as featured, so this parable is a little on the optimistic side, and a fairy godmother would come in handy. Some dedicated editors aim to produce featured articles from scratch, but most articles obtain this standard of quality gradually.
Other editors produce large numbers of shorter pieces. These approaches are complementary, from the point of view of the encyclopedia, and suit different editor temperaments. What really matters is that articles are in the end written collectively and thoroughly. Wikipedia has no one correct way to write an article.
Summary[edit]
The whole system for producing Wikipedia's content might seem cockeyed or random. It is certainly fallible. Content emerges from a complex but well-meaning development process, where two steps might be taken forward and then one step taken backward. But Wikipedia offers many layers of review and improvement, even if there is no single set of procedures, and ultimately Wikipedia draws readers because its content is, on balance, very useful. Indeed, Wikipedia's footprint on the World Wide Web is growing steadily.
Conclusion to Part II[edit]
Wikipedia needs all types of articles. What should you write about? Many possibilities for new articles exist, but the majority of Wikipedia's two million existing articles still need work as well. If you want to help out with articles, you can always apply basic wikification and formatting (Chapter 5, Basic Editing), work on rewriting for clarity and referencing facts (Chapter 6, Good Writing and Research), do cleanup tasks (Chapter 7, Cleanup, Projects, and Processes), sort out hypertext and category issues (Chapter 8, Make and Mend Wikipedia's Web), and perhaps even contribute images or expert syntax (Chapter 9, Images, Templates, and Special Characters).
But our central advice on writing for Wikipedia is that four things matter most to an article:
- Being fairly well written and reliably sourced from the very first revision helps stave off possible deletion and provides the foundation of a good article.
- Complying with the basic content policies of Neutrality, Verifiability, and No Original Research.
- Fitting well with existing Wikipedia material so that incoming wikilinks exist or can be created.
- Being about a topic that is also of interest to others, perhaps fitting within the scope of a WikiProject, so that others will find and develop it.
Good editors can often find parts of Wikipedia that are currently undeveloped, where new articles might be created. Just as often, many articles exist, but they are in poor shape and require a big structuring and linking effort. When you feel ready to tackle this type of work, you have mastered this part of the book. You can then consider yourself an advanced editor. | https://en.wikibooks.org/wiki/How_Wikipedia_Works/Chapter_10 | CC-MAIN-2019-26 | refinedweb | 4,957 | 50.16 |
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
On Fri, Jun 9, 2017 at 6:41 AM, Szabolcs Nagy <szabolcs.nagy@arm.com> wrote: > On 09/06/17 14:06, H.J. Lu wrote: >> On Fri, Jun 9, 2017 at 5:57 AM, Szabolcs Nagy <szabolcs.nagy@arm.com> wrote: >>> On 09/06/17 12:45, H.J. Lu wrote: >>>> On Fri, Jun 9, 2017 at 4:44 AM, Szabolcs Nagy <szabolcs.nagy@arm.com> wrote: >>>>> On 09/06/17 12:40, H.J. Lu wrote: >>>>>> On Fri, Jun 9, 2017 at 4:32 AM, Florian Weimer <fweimer@redhat.com> wrote: >>>>>>> On 06/09/2017 01:28 PM, H.J. Lu wrote: >>>>>>>> Yes, 99% of codes just need to recompile. If context functions >>>>>>>> are used or jmpbuf is used independently of setjmp/longjmp, >>>>>>>> enabling is needed. >>>>>>> >>>>>>> Would you please clarify if the size of the type jmp_buf changes in the >>>>>>> new compilation mode? >>>>>>> >>>>>> >>>>>> jmp_buf size will be increased unconditionally in glibc whose <setjmp.h> >>>>>> has >>>>>> >>> >>> note that there is a large unused space in jmp_buf >>> on linux because of the hurd sigset (__saved_mask member), >>> if that space can be used in target specific ways then >>> the abi complications may be possible to avoid. >> >> On x86, we have >> >> # if __WORDSIZE == 64 >> typedef long int __jmp_buf[8]; >> # elif defined __x86_64__ >> __extension__ typedef long long int __jmp_buf[8]; >> # else >> typedef int __jmp_buf[6]; >> # endif >> >> We need to grow it for shadow stack. >> > > that's just the first part of the jmp_buf struct, > what matters is the size of jmp_buf which is > > struct __jmp_buf_tag > { > /* NOTE: The machine-dependent definitions of `__sigsetjmp' > assume that a `jmp_buf' begins with a `__jmp_buf' and that > `__mask_was_saved' follows it. Do not move these members > or add others before it. */ > __jmp_buf __jmpbuf; /* Calling environment. */ > int __mask_was_saved; /* Saved the signal mask? */ > __sigset_t __saved_mask; /* Saved signal mask. */ > }; > > typedef struct __jmp_buf_tag jmp_buf[1]; > > and only the first few bytes of __saved_mask is used on linux, > there is lot of free space there, it's just not setup for > target specific tinkering currently. > > We can use the unused space for SSP. -- H.J. | http://sourceware.org/ml/libc-alpha/2017-06/msg00399.html | CC-MAIN-2020-05 | refinedweb | 358 | 74.49 |
SVG is a language for describing two-dimensional graphics in XML [ ,XML11 ]. SVG allows for three types of graphic objects: vector graphic shapes (e.g., paths consisting of straight lines and curves), multimedia (such as raster images and video) and text. Graphical objects can be grouped, styled, transformed and composited into previously rendered
Web Architecture
SVG
Mobile 1.1 specificationDOM,. discussion of Version Control .
There is no DTD for SVG 1.2, and therefore no need to specify
the DOCTYPE for an SVG 1.2 document (unless it is desired to use
the internal
DTD subset
, for purposes of entity definitions for example).
Instead, identification is by the SVG namespace, plus the
version and
baseProfile
attributes. In SVG Tiny 1.2, validation is
provided by the SVG Tiny 1
1.2
file:" Recommendation [ XML11 ] and "Extensible Markup Language (XML) 1.0 (Third
Edition)" Recommendations [ XML10 ]
SVG Tiny 1.2 is compatible with both the
"Namespaces in XML 1.0"
[ XML-NS10 ] and the "Namespaces in XML 1.1"
Recommendations [
XML-NS ]
SVG Tiny 1.2 utilizes
"XML Linking Language (XLink)" [ XLINK ] for IRI referencing and requires
support for base IRI specifications defined in "XML Base" [ XML-BASE ].
SVG Tiny 1.2 uses the
xml:id
attribute [ XMLID ].
SVG Tiny 1.2 content can be generated
by
XSLT (see "XSL Transformations (XSLT) Version 1.0" [
XSLT ]). " [
DOM3 ], including namespace
support and event handling.
SVG Tiny 1.2 incorporates some features from
"Synchronized
Multimedia Integration Language
(SMIL) 2.0 Specification" [ SMIL2.0 ], including the
'switch' element
,:
Unicode [ UNICODE ], Resource
Identifiers [ CHARMOD-RI ]
and the Character
Model [ CHARMOD
]. Also, see Internationalization
Support . .)
SVG is compatible with W3C work on Web Accessibility [ WAI ].
Also,
see Accessibility Support ...
<svg xmlns='' text content elements , for the purposes of the bounding box calculation, each glyph must be treated as a separate graphics element. The calculations must assume that all glyphs occupy the full glyph cell. For example, for horizontal text, the calculations must assume that each glyph extends vertically to the full ascent and descent values for the font. An exception to this is the 'textArea' , which uses that element's geometry for the bounding box calculation..
. .
, ,
,
container element
. depends on the value of the 'timelineBegin'
attribute. The document begin for:
loadevent is
The document end of an SVG
document fragment is the
point
definition of
document time
..
element
types that can cause graphics to be
drawn onto the target canvas. Specifically: 'path' , 'text' , 'textArea' , 'rect' , 'circle' , 'ellipse' , 'line' , 'polyline' , 'polygon' , 'image' , 'use' , 'animation' and 'video' .
A graphics element
which
uses a reference to a different document or
element as the source of its graphical content. Specifically: 'use' , 'image' , 'animation' and 'video' .
,
Timing
,
Paused Elements and Active Duration , and
Event Sensitivity .
An
Internationalized Resource Identifier
(IRI).
Defined in RFC
3987 . Serves
as a reference to a resource or (with a
fragment identifier) to a secondary resource. See References .
.
.
,
that references a fragment within the same resource. See References .
, , , , , , , , . .
IRI
] that represents a
reference to a
different document or an element within a different document.
,
paint
.
.
A paint represents a way of putting color values onto the canvas. A paint might consist of both color values and associated alpha values which control the blending of colors against already existing color values on the canvas. SVG supports two types of built-in paint: color and gradients .
XML attribute on an SVG element which specifies a value for a given property for that element. See Styling .
A parameter that helps
specify how a document should be rendered. A complete list of
SVG's properties can be found in Property Index
. Properties are assigned to elements in
the SVG language by presentation attributes . See Styling .
The set of
elements being rendered, aurally or visually using the painters
model,
on an SVG
document fragment . The following elements in the
fragment:
, . shape
.
A graphics
element that comprises a defined combination of straight
lines and curves.
Specifically any instance
of the element types: 'path' , 'rect' , 'circle' , 'ellipse' , 'line' , 'polyline'
, 'polygon' . ,
stroke
.
operation of painting the outline of a shape or the outline of character glyphs in a text string.
The canvas onto which the SVG content is
rendered. See the discussion of the SVG canvas in the
chapter on Coordinate
Systems, Transformations and Units . . .
An element within the SVG namespace defined by the SVG language specification.
The viewport within
the SVG
canvas which defines the rectangular region into which
SVG content is rendered. See the discussion of the SVG viewport in the
chapter on Coordinate
Systems, Transformations and Units . Syncbase
SMIL
.
that
can define
a text string that is to be rendered onto the canvas.
SVG Tiny 1.2's text content
elements are the following: 'text' , 'tspan' and 'textArea' .
A
text content element that serves as a
standalone element for a unit of text, and which may optionally
contain certain child text
content elements (e.g. 'tspan' ). SVG Tiny
1.2's
text content block elements are the
following: 'text'
, and 'textArea' .
that
support the SVG Timing
Attributes
. They are: animate , animateColor , animateMotion
, animateTransform
, set , video , audio
and animation .
A modification of the current transformation matrix (CTM) by providing a supplemental transformation in the form of a set of simple transformations specifications (such as scaling, rotation or translation) and/or one or more transformation matrices . See Coordinate system transformations .10] . .
synonym for user coordinate system .
A coordinate value or length expressed in user units represents a coordinate value or length in the current user coordinate system . Thus, 10 user units represents a length of 10 units in the current user coordinate system.
A rectangular region
within the current canvas onto which graphics
elements are to be rendered. See the discussion of the
SVG viewport in the
chapter on Coordinate Systems, Transformations and Units
. hav . .
. | http://www.w3.org/TR/2008/WD-SVGMobile12-20080915/diff/intro.html | CC-MAIN-2016-22 | refinedweb | 961 | 50.73 |
Technical blog on Microsoft ASP.NET and ASP.NET AJAX.
From the suggestion box Marc Brooks asks:
"More about the needed fixes for ObjectDataSource (e.g. allowing it to acquire the object instead of creating exnilo)."
In fact, the ObjectDataSource already supports this functionality through its ObjectCreating and ObjectDisposing events. In the attached ZIP file (download it from the bottom of this post) I have a sample web site that demonstrates a factory for business objects. Some details of the factory:
Business object factory API:
namespace Eilon.Samples { public static class BusinessObjectFactory { public static BusinessObject GetBusinessObject(); public static void ReturnBusinessObject(object o); }}
The sample object in the demo has some calls to Thread.Sleep in it to help demonstrate expensive operations. Each business object instance takes two seconds to initialize, and each call to its Select method takes another two seconds. By making several rapid requests the demo shows that the object pool's maximum size of three objects is quickly exhausted. As mentioned earlier, we need to wire up the business object factory to the ObjectDataSource using some events:
protected void ProductsDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e) { e.ObjectInstance = BusinessObjectFactory.GetBusinessObject(); }
protected void ProductsDataSource_ObjectDisposing(object sender, ObjectDataSourceDisposingEventArgs e) { BusinessObjectFactory.ReturnBusinessObject(e.ObjectInstance); }...<asp:ObjectDataSource</asp:ObjectDataSource>
Running the demo:
Feel free to reuse this code for the business object factory, but be aware that it suffers from serious starvation issues due to its busy-wait loop. Using a more dynamic system for maintaining the pool such as a dynamic size might be more appropriate for some systems. This code is just meant to demonstrate a lesser known feature of the ObjectDataSource.
- Eilon
Ah, the factory design pattern. Very important to know :)
Very interesting, but completely unrelated to what I was asking for... I'm more concerned about the bogus coupling of the update parameters when using DataObjectType... the "old object" not being fetch, but being created and having ONLY the values exposed on the FormView/GridView/DetailsView set... while leaving the rest of the attributes in the "just constructed" state (instead of, in a delete/update situation, being what was loaded from the object store).
Well let's call that "oops" :)
The reason for what you're describing is an unfortunate consequence of the design we have for data sources and data bound controls. Since ASP.NET pages are generally stateless with respect to the server, all live objects go away after the page is unloaded. The data source relies entirely on the data bound control to give it the old/new values that it needs.
On the other hand, once nice consequence of the design is that the requirements on the business objects are quite few. We require no support for any type of persistence or serialization. The only requirements are a pattern for the object model regarding the signatures of the constructor(s) and availability of property getters and setters on the data object.
I am interested to hear any ideas you have on how your ideal data source might work, though. Where should the data objects be persisted? Any other aspects that need to be handled here?
The key to the issue, for me, comes down to the fact that when using DataObjectType, ObjectDataSource will always create a new instance of the specified class and start setting properties in whatever order the consumer bothered to pass them. If it, instead, called a virtual method on itself (that I could override), then I could take the key-values passed in, and build the object in whatever manner I wish (get from web service/cache/ORM/database, etc.) Then let ODS do its value settings. I even filed several requests against ODS during the beta and RC1 (and in the final) on LadyBug, but they kept getting closed for no good reason (basicially because they are "red-bits" for the VS2005 SP1, but shouldn't have been for the still-needed .Net 2.0 SP1).
Of course I could fix this myself if ODS didn't do everything in its power to prevent me from using my own derived ObjectDataSourceView class... but that path is walled off too...
It's really about replacing the method ObjectDataSource.BuildDataObject with a virtual call, and making the existing version get called by the new virtual method (and making both BuildDataObject and BuildObjectValue protected instead of private so they can be used). | http://weblogs.asp.net/leftslipper/archive/2007/01/25/from-the-suggestion-box.aspx | crawl-002 | refinedweb | 729 | 53 |
Tyaedalis Wrote:thanks. i have a question. is there a link between cocoa and c?
#include <stdio.h>
Tyaedalis Wrote:am having trouble with the
Code:
#include <stdio.h>
i dont know what the stdio.h means
i kow it means standard something, but what does it do?
does the program need it?
also, how do i set up Xcode for C compiling?
Tyaedalis Wrote:pythons seems boring. what can you do with it and how do you compile (or interperet) it?
Tyaedalis Wrote:type that in the terminal?
and i write the code in textedit?
print "Hello, World!"
#include <stdio.h>
int main()
{
char name[20], age[9];
printf("\nWhat is your name? ");
scanf("%s", name);
printf("How old are you? ");
scanf("%s", age);
printf("Your name is %s, and you are %s years old.\n", name,age);
return 0;
}
fflush(stdin); | http://idevgames.com/forums/printthread.php?tid=5045 | CC-MAIN-2016-36 | refinedweb | 143 | 88.94 |
----------------------------------------------------------- This is an automatically generated e-mail. To reply, visit: -----------------------------------------------------------
Advertising
Ship it! 3rdparty/libprocess/3rdparty/stout/include/stout/uuid.hpp (lines 78 - 79) <> Can you add a comment here? (Pretty much what you said in the description). - Joseph Wu On Oct. 10, 2015, 4:46 p.m., Alex Clemmer wrote: > > ----------------------------------------------------------- > This is an automatically generated e-mail. To reply, visit: > > ----------------------------------------------------------- > > (Updated Oct. 10, 2015, 4:46 p.m.) > > > Review request for mesos, Artem Harutyunyan, Joris Van Remoortere, and Joseph > Wu. > > > Repository: mesos > > > Description > ------- > > The `Windows.h` head includes a header that defines the UUID struct for > the DCE RPC API. This is dumped into the global namespace, just like our > UUID implementation found in `stout/uuid.hpp`. > > Since this causes a compilation error on Windows, we simply move our > UUID into `stout::`. We further add a `using stout::UUID;` in the file > so that we don't have to change every callsite in the Mesos codebase > that uses it. > > > Diffs > ----- > > 3rdparty/libprocess/3rdparty/stout/include/stout/uuid.hpp > bc167f1fa9e64f89138f131e726e7733c66da29c > > Diff: > > > Testing > ------- > > > Thanks, > > Alex Clemmer > > | https://www.mail-archive.com/reviews@mesos.apache.org/msg11961.html | CC-MAIN-2016-44 | refinedweb | 175 | 61.93 |
To be honest, this isn't my first attempt to post and get help, but the other site decided to close my post because it wasn't a good enough question and because I decided to bump it. Be awesome if you could help me out, been trying to figure this out.
When I go to assemble and run the code, the program loops back up to the user prompt over and over again. I can only edit the Search section of the code. Basically the program should take the user input and tell where in the list the number that the is, if the number is in the list. When I ran it line by line, it went past the part it was stuck at, but it just printed the entire list. You will be considered awesome and get an internet high five from me.
Here is the MIPS Code:
.data list: .word 5 .word 7 .word 4 .word 6 .word 3 .word 8 .word 2 .word 9 .word 0 .word 30 .word 31 .word 39 .word 32 .word 38 .word 33 .word 37 .word 34 .word 36 .word 35 .word 20 .word 21 .word 29 .word 22 .word 28 .word 23 .word 27 .word 24 .word 26 .word 25 .word 10 .word 11 .word 19 .word 12 .word 18 .word 13 .word 17 .word 14 .word 16 .word 15 .word 1 # last array element .word -1 # not part of array prompt1: .asciiz "\nPlease enter an array element: " prompt2: .asciiz "\nPlease enter a search target: " space: .asciiz " " nfound: .asciiz "\nThe target was not found." found: .asciiz "\nThe target was found at array location " .text .globl main main: add $t0, $zero, $zero # [main] add $t1, $zero, $zero # addi $t2, $zero, 39 # addi $t3, $zero, 39 # add $t4, $zero, $zero # add $t5, $zero, $zero # add $t6, $zero, $zero # # add $t7, $zero, $zero # la $t8, list read: addi $v0, $zero, 4 # [read] la $a0, prompt1 # syscall addi $v0, $zero, 5 # syscall sll $t7, $t0, 2 # add $t9, $t8, $t7 sw $v0, 0($t9) addi $t0, $t0, 1 # ble $t0, $t2, read # # add the code that is missing from right here add $t0, $zero, $zero # search: add $t1, $zero, $zero search2: lw $t4, 0($t9) lw $t5, 1($t9) sgt $t7, $t4, $t5 sw $t4, 0($t9) sw $t5, 1($t9) add $t1, $t1, 1 blt $t1, $t3, search2 sub $t3, $t3, 1 add $t0, $t0, 1 blt $t0, $t2, search print: addi $v0, $zero, 1 # [print] sll $t7, $t0, 2 # add $t9, $t8, $t7 lw $a0, 0($t9) syscall addi $v0, $zero, 4 # la $a0, space # syscall addi $t0, $t0, 1 # ble $t0, $t2, print # end: addi $v0, $zero, 10 # [end] syscall
Here is the Java Code:
import java.io.*; public class CIS2233StarterCode2Java { public static void main (String [] args) throws IOException { BufferedReader kbd = new BufferedReader (new InputStreamReader (System.in)); int [] list = {5,7,4,6,3,8,2,9,0,20,21,29,22,28,23,27,24,26,25,30,31,39,32,38,33,37,34,36,35,10,11,19,12,18,13,17,14,16,15,1}; String prompt1 = "\nPlease enter an array element: "; String prompt2 = "\nPlease enter a search target: "; String space = " "; String nfound = "\nThe target was not found."; String found = "\nThe target was fount at array location "; int t0 = 0; int t1 = 0; int t2 = 39; int t3 = 39; int t4; int t5; int t6; int a0; int v0; // address calculation register t7 // base address of array register t8 // address calculation register t9 do { System.out.print (prompt1); v0 = Integer.parseInt(kbd.readLine()); list [t0] = v0; t0 ++; } while (t0 <= t2); t0 = 0; do { t1 = 0; do { t4 = list [t1]; t5 = list [t1 + 1]; if (t4 > t5) { list [t1 + 1] = t4; list [t1] = t5; } t1 ++; } while (t1 < t3); t3 --; t0 ++; } while (t0 < t2); t0 = 0; do { a0 = list [t0]; System.out.print (a0); System.out.print (space); t0 ++; } while (t0 <= t2); } } | http://forum.codecall.net/topic/80515-converting-java-to-mips-user-prompt-displayed-over-and-over-again/ | CC-MAIN-2018-51 | refinedweb | 654 | 69.35 |
- Name
- Synopsis
- Usage
- Description
- Options
- Class Interface
- Instance Interface
- Instance Methods
- Instance Accessors
- To Do
- Support
- Author
Name
Pod::Site - Build browsable HTML documentation for your app
Synopsis
use Pod::Site; Pod::Site->go;
Usage
podsite --name App \ --doc-root /path/to/output/html \ --base-uri /browser/base/uri \ /path/to/perl/libs \ /path/to/perl/bins
Description
This program.
Configuration
Sites generated by Pod::Site are static HTML sites with all interactivity powered by CSS and jQuery. It does its best to create links to documents within the site, and for Pod outside the site it links to CPAN search.
You can specify links directly to a specific document on your site by simply adding a module name to the URL after a question mark. An example:
There is one server configuration that you'll want to make to allow links without the question-mark:
Getting this to work is simple: Just have your Web server send 404s to the index page. If your base URI is /docs/api, for example, in Apache's httpd.conf you can just do this:
<Location /docs/api> ErrorDocument 404 /docs/current/api/index.html </Location>
Options
-d --doc-root DIRECTORY Browser document root -u --base-uri URI Browser base URI -n --name NAME Site name -t --versioned-title Include main module version number in title -l --label LABEL Label to append to site title -m --main-module MODULE Primary module for the documentation -s --sample-module MODULE Module to use for sample links -i --index-file FILENAME File name for index file -c --css-path PATH Path to CSS file -j --js-path PATH Path to CSS file --replace-css Replace existing CSS file --replace-js Replace existing JavaScript file -V --verbose Incremental verbose mode. -h --help Print a usage statement and exit. -M --man Print the complete documentation and exit. -v --version Print the version number and exit.
Class Interface
Class Method
go
Pod::Site->go;
Called from
podsite, this class method parses command-line options in
@ARGV, passes them to the constructor, and builds the site.
Constructor
new
my $ps = Pod::Site->new(\%params);
Constructs and returns a Pod::Site object. The supported parameters are:
module_roots
An array reference of directories to search for Pod files, or for the paths of Pod files themselves. These files and directories will be searched for the Pod documentation to build the browser.
doc_root
Path to a directory to use as the site document root. This directory will be created if it does not already exist.
base_uri
Base URI for the Pod site. For example, if your documentation will be served from /docs/2.0/api, then that would be the base URI for the site.
May be an array reference of base URIs. This is useful if your Pod site will be served from more than one URL. This is common for versioned documentation, where you might have docs in /docs/2.0/api and a symlink to that directory from /docs/current/api. This parameter is important to get links from one page to another within the site to work properly.
name
The name of the site. Defaults to the name of the main module.
versioned_title
If true, the version of the main module will be included in the site title.
label
Optional label to append to the site title. Something like "API Browser" is recommended.
main_module
The main module defining the site. For example, if you were building a documentation site for the Moose, Class::MOP, and
MooseXnamespaces, the main module would be "Moose". Defaults to the first module found when all module names are sorted in alphabetical order.
sample_module
Module to use in the example documentation links in the table of contents. This is the main page displayed on the site
index_file
Name of the site index file. Defaults to index.html, but you might need it to be, e.g., default.html if you were deploying to a Windows server.
css_path
Path to CSS files. Defaults to the base URI.
js_path
Path to JavaScript files. Defaults to the base URI.
replace_css
-
replace_js
If you're building a new site over an old site, by default Pod::Site will not replace the CSS and JavaScript files, seeing as you might have changed them. If you want it to replace them, pass a true value for this parameter.
If you're building a new site over an old site, by default Pod::Site will not replace the CSS and JavaScript files, seeing as you might have changed them. If you want it to replace them (and in general you ought to), pass a true value for these parameters.
verbose
Pass a value greater than 0 for verbose output. The higher the number, the more verbose (up to 3).
Instance Interface
Instance Methods
build
$ps->build;
Builds the Pod::Site. This is likely the only instance method you'll ever need. In summary, it:
Searches through the module roots for Pod files (modules and scripts) using Pod::Simple::Search
Creates HTML files for all the files found using Pod::Simple::HTMLBatch and a custom subclass of Pod::Simple::XHTML
Iterates over the list of files to create the index with the navigation tree and the table of contents page (toc.html).
sort_files
$ps->sort_files;
Iterates through the Pod files found by Pod::Simple::Search and sorts them into two categories: modules and scripts. All appear in the navigation tree, but scripts are listed under "bin" and are not otherwise in tree form.
start_nav
$ps->start_nav($filehandle);
Starts the HTML for the navigation document, writing the output to $filehandle.
start_toc
$ps->start_toc($filehandle);
Starts the HTML for the table of contents document, writing the output to $filehandle.
output
$ps->output($filehandle, $tree);
Writes the content of the module tree to the navigation document via $filehandle. The $tree argument contains the tree. This method is called recursively as it descends through the tree to create the navigation tree.
output_bin
$ps->output_bin($filehandle);
Outputs the list of script files to the table of contents document via $filehandle.
finish_nav
$ps->finish_nav($filehandle);
Finishes the HTML for the navigation document, writing the output to $filehandle.
finish_toc
$ps->finish_toc($filehandle);
Finishes the HTML for the table of contents document, writing the output to $filehandle.
batch_html
$ps->batch_html;
Does the work of invoking Pod::Simple::HTMLBatch to look for Pod files and write out the corresponding HTML files for each.
copy_etc
$ps->copy_etc;
Copies the additional files, podsite.js and podsite.css to the document root. These files are necessary to the functioning of the site.
get_desc
$ps->get_desc( $module, $file);
Parses the Pod in $file to find the description of $module. This is the text after the hyphen in the `=head1 Name` section of the Pod, often called the "abstract" by toolchain modules like Module::Build.
Instance Accessors
main_module
my $mod = $ps->main_module;
Returns the name of the main module as specified by the
main_module parameter to
new() or, if none was specified, as first module in the list of found modules, sorted case-insensitively.
sample_module
my $mod = $ps->sample_module;
The name of the module to use for the sample links in the table of contents. Defaults to
main_module.
name
my $name = $ps->name;
Returns the name of the site. Defaults to
main_module.
label
my $label = $ps->label;
Returns the optional label to append to the site title. None by default.
title
my $title = $ps->title;
Returns the title of the site. This will be constructed from
name and
label and, if
versioned_title is true, the title of the main module.
nav_header
my $header = $ps->nav_header;
Returns the header used at the top of the navigation. This will be constructed from
name and, if
versioned_title is true, the title of the main module.
versioned_title
my $versioned_title = $ps->versioned_title;
Returns true if the version is to be included in the site title, and false if it is not, as specified via the
versioned_title parameter to
new().
version
my $version = $ps->version;
Returns the version number of the main module.
module_roots
my $roots = $ps->module_roots;
Returns an array reference of the directories and files passed to the
module_roots parameter to
new().
doc_root
my $doc_root = $ps->doc_root;
Returns the path to the document root specified via the
doc_root parameter to
new().
base_uri
my $base_uri = $ps->base_uri;
Returns the value of the base URI as specified via the
base_uri parameter to
new().
index_file
my $index_file = $ps->index_file;
Returns the value of index files as specified via the
index_file parameter to
new(). Defaults to index.html.
css_path
my $css_path = $ps->css_path;
Returns the URI path for CSS files as specified via the
css.
js_path
my $js_path = $ps->js_path;
Returns the URI path for JavaScript files as specified via the
js.
replace_css
my $replace_css = $ps->replace_css;
Returns true if Pod::Site should replace an existing podsite.css file when regenerating a site, as specified via the
replace_css parameter to
new().
replace_js
my $replace_js = $ps->replace_js;
Returns true if Pod::Site should replace an existing podsite.js file when regenerating a site, as specified via the
replace_js parameter to
new().
mod_files
my $mod_files = $ps->mod_files;
Returns a tree structure containing all the module files with Pod found by Pod::Simple::Search. The structure has file base names as keys and full file names as values. For nested structures, the keys are the last part of a module name and the values are an array of more file names and module branches. For example, a partial tree of module files for Moose might be structured like this:
$mod_files = { 'Moose.pm' => 'lib/Moose.pm', 'Moose' => { 'Meta' => { 'Class.pm' => 'lib/Moose/Meta/Class.pm', 'Instance.pm' => 'lib/Moose/Meta/Instance.pm', 'Method.pm' => 'lib/Moose/Meta/Method.pm', 'Role.pm' => 'lib/Moose/Meta/Role.pm', }, }, }
bin_files
my $bin_files = $ps->bin_files;
Returns a tree structure containing all the scripts with Pod found by Pod::Simple::Search. The structure has file names as keys and full file names as values.
verbose
my $verbose = $ps->verbose;
Returns the value passed for the
verbose parameter to
new(). Defaults to 0.
To Do
Add support for resizing the nav pane.
Allow right and middle clicks on nav window links to copy links or open them in a new Window (Issue #1).
This module is stored in an open GitHub repository. Feel free to fork and contribute!
Found a bug? Please file a report!
Support
This module is stored in an open GitHub repository,. Feel free to fork and contribute!
Please file bug reports at.
Author
David E. Wheeler <david@justatheory.com>
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | https://metacpan.org/pod/Pod::Site | CC-MAIN-2015-11 | refinedweb | 1,778 | 56.76 |
Yes! FLTK in Dart, just like this:
import 'package:fltk/fltk.dart' as fl; int main() { fl.scheme('gleam'); var window = new fl.Window(350, 180, 'FLTK'); var box = new fl.Box(20, 40, 310, 100, 'Hello, World!'); window.end(); window.show(); return fl.run(); }
image
dartgl
cairodart
This library is mostly experimental and a way to spend some time. Currently only a subset of features are supported (the exiting ones like loading images, displaying OpenGL graphics, and asynchronous event streams). The majority of widgets is not yet ported to Dart. However a sophisticated code generation program is already in place and adding simple widgets is pretty easy. If this library is useful for you and you need more widgets, feel free to open an issue!
Most bindings are automatically generated from YAML descriptions of the FLTK functions and classes. Class bindings do not create the target class directly, instead they create a wrapper class that takes care of draw and callback events.
Maybe we should use static linking for the FLTK libraries so this extension can be used without locally compiling FLTK.
Add this to your package's pubspec.yaml file:
dependencies: fltk: "^0.0.5"
You can install packages from the command line:
with pub:
$ pub get
Alternatively, your editor might support
pub get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:fltk/fltk.dart';
We analyzed this package on Jun 15, 2018, and provided a score, details, and suggestions below. Analysis was completed with status tool failures using:
Detected platforms: unsure
Error(s) prevent platform classification:
Fix dependencies in
pubspec.yaml.
Fix dependencies in
pubspec.yaml.
Running
pub upgradefailed with the following output:
Exceeded timeout of 0:02:00.000000
Fix platform conflicts.
Error(s) prevent platform classification:
Fix dependencies in
pubspec.yaml.
Running
dartdoc failed.
Make sure
dartdocruns without any issues.
Maintain
CHANGELOG.md.
Changelog entries help clients to follow the progress in your code.
Package is getting outdated.
The package was released 93
fltk.dart.
Use
analysis_options.yaml.
Rename old
.analysis_optionsfile to
analysis_options.yaml. | https://pub.dartlang.org/packages/fltk | CC-MAIN-2018-26 | refinedweb | 350 | 61.02 |
The only PCI-express card I could find) and plugging that into the new computer. That gave me a working video instead of a monitor that kept falling asleep.
Next came Slackware. When I booted the Slackware 14.2 installer, it did not give me a network connection. The Slackware Live Edition (based on slackware-current) worked properly on the other hand. But the graphics card I plugged into the computer did not work too well with the nouveau driver – whenever I started Chromium, it was inevitable that the computer would lock up after some time. Initially I blamed this on the computer hardware and feared that I bought a dead duck, but once I stopped running Chromium in the graphical desktop of Slackware Live, the system would remain operational. Since it is not going to be used as a desktop system and I will access it only remotely, that buggy nouveau driver is not a big issue and I could still install the binary Nvidia blob if needed.
So, the question became: I want to run a stable Slackware release on my new build server, but how am I going to install it? I was facing two major issues:
- The installer of Slackware 14.2 does not support NVMe boot devices (the new type of SSD hard drives with a M.2 PCI-express interface)
- The Slackware 14.2 installer lacks network capability on this new hardware, so I would have to perform a local install
I could spend a USB stick, putting the Slackware 14.2 DVD ISO on it, but then I still would have to patch the installer and I would not have a network connection after reboot. Considering the fact that slackware-current’s kernel works much better and NVMe support was added to the -current installer recently, I decided on a different approach.
I used a slackware-current based liveslak to setup the computer with Slackware 14.2 and then added a 4.9 kernel using the configfile for this kernel as found in slackware-current.
Steps taken:
- Obtain a recent ISO of the Slackware Live Edition which is based on slackware-current (for instance, the 2.7 GB bleeding edge version or else the 700 MB XFCE based edition)
- Write the ISO to a USB stick and boot liveslak. Now you have a proper graphical environment where you can query Google/DuckDuckGo and download anything you need.
- We can not use the “setup2hd” of liveslak because that will install slackware-current and I want 14.2. So, download the smallest installer we can get: slackware64-current-mini-install.iso which contains just the kernel and the installer (no packages) and is slightly more than 100 MB in size:
# wget
- Download my “extract_initramfs.sh” script which makes it easier to extract the initrd.gz file containing the installer:
# wget
- Partition the SSD drive. The M.2 interface results in a character device /dev/nvme0 and a namespace block device /dev/nvme0n1. The first partition on this device will be called /dev/nvme0n1p1. The installer in Slackware 14.2 can not handle this new namespacing format. The one in -current can.
This is a UEFI computer, and I want Slackware to use this. That requires a FAT partition which will be used as the EFI system partition. Slackware will mount this partition at /boot/efi. I created a 100 MB partition of type EF00 (EFI system) and formatted this with:
# mkdosfs -F32 -s 2 -n “EFI” /dev/nvme0n1p1
The remainder of the disk is partitioned with swap (yes even with 64 GB of RAM it is still a good idea to add some swap space), and additional partitions are created for /, /boot, /var, /tmp and /home .
- Extract the installer from this mini ISO into a new directory “/root/initrd64-current“:
# mount -o loop slackware64-current-mini-install.iso /mnt/tmp
# sh extract_initramfs.sh /mnt/tmp/isolinux/initrd.img /root/initrd64-current
- Get the installer running in the terminal while we are still in a liveslak graphical Desktop Environment:
# mount -o bind /dev /root/initrd64-current/dev
# mount -o bind /proc /root/initrd64-current/proc
# mount -o bind /sys /root/initrd64-current/sys
# chroot /root/initrd64-current
- Inside this chroot-ed installer environment, run the ‘setup‘ command and proceed as usual with the installation of Slackware64 14.2 from a network server. The liveslak has already taken care of the network connectivity. I have NFS and HTTP servers at home, providing package trees but I pick NFS because that is much faster. I pointed the installer to a Slackware64-14.2 package source and did a full install (first time ever that I installed the Emacs package, go figure).
- At the end of the installation, do note yet exit! Instead, run “chroot /mnt” to enter the freshly installed system. Configure slackpkg with a suitable mirror, then run:
# slackpkg upgrade-all
This will install all the latest patches including the latest kernel.
- Finally, blacklist the kernel-generic and kernel-modules so that slackpkg will never replace our kernel accidentally.
- Create an initrd (the /usr/share/mkinitrd/mkinitrd_command_generator.sh script will help you finding the correct parameters) and copy the generic kernel and this initrd to the EFI partition. This is the elilo.conf file I ended up with:
# cat /boot/efi/EFI/Slackware/elilo.conf chooser=simple delay=50 timeout=50 default=slackware142 image=vmlinuz label=huge142 read-only append="root=/dev/nvme0n1p7 vga=normal ro" image=vmlinuz-generic-4.4.75 label=slackware142 initrd=initrd_4.4.75.gz read-only append="root=/dev/nvme0n1p7 vga=normal ro"
- Now that the Slackware 14.2 installation is complete we have to ensure that we add a working kernel to it. I want to use the kernel as found in slackware-current because I know the 4.9.x series is good (liveslak proved that) and because slackware-current contains a kernel config that I can just re-use. Download the kernel source, and the kernel packaging scripts so that we can compile a kernel and its modules manually but still can wrap the results in package format and install those. Warning – when you try this at home, the actual kernel version may have moved beyond the “4.9.44” which I use in the example below. Just substitute the actual version instead:
# CWD=$(pwd)
# lftp -c “open; mirror k”
# cd k/
# tar -C /usr/src -xf linux-4.9.44.tar.xz
# cp config-x86_64/config-generic-4.9.44.x64 /usr/src/linux-4.9.44/.config
Now we can compile that kernel (yes I compile kernels as root):
# cd /usr/src/linux-4.9.44
# make oldconfig
# make -j 15 all
# make install
Now that the kernel is installed as /boot/bzimage and the modules as /lib/modules/4.9.44 we use the Slackware packaging scripts to create two packages:
# cd $CWD/k/packaging-x86_64/kernel-generic
# ./kernel-generic.SlackBuild
# cd $CWD/k/packaging-x86_64/kernel-modules
# ./kernel-modules.SlackBuild
The two packages in /tmp can then be installed using “installpkg”. Do not use “upgradepkg” with your kernels – you will want to keep at least one previous kernel. The kernel-modules package will essentialy overwrite what’s in /lib/modules/4.9.44 but now with a package, we can control it through the package manager if needed. The kernel-generic package will have installed the new kernel as /boot/vmlinuz-generic-4.9.44. Copy that kernel to the EFI partition, and create a new initrd in the same location to match the kernel:
# cp /boot/vmlinuz-generic-4.9.44 /boot/efi/EFI/Slackware/
# $(/usr/share/mkinitrd/mkinitrd_command_generator.sh -k 4.9.44 -r -a “-o /boot/efi/EFI/Slackware/initrd_4.9.44.gz”)
Add a section for the new kernel to elilo.conf. You can just copy the existing section for “label=slackware142” and change the version numbers. Make sure that the “default” keyword has this new label as its value. We want the new kernel to boot by default.
- Exit the installed system’s chroot:
# exit
- Then exit the installer’s chroot:
# exit
- We are almost done. Unfortunately the eliloconfig of Slackware 14.2 did not add a Slackware entry to the computer’s EFI boot menu. So now that we are back in liveslak we need to fix this omission using the eliloconfig of slackware-current which is part of our liveslak:
# eliloconfig /setup2hd /dev/nvme0n1p7
This assumes the installed system is mounted under /setup2hd and the root partition is /dev/nvme0n1p7 . Change the parameters to match your situation. This time you will see that the Slackware entry is being created.
- Reboot the system.
- Have fun!
If I have omitted anything or steps are unclear, let me know. Now that I have Slackware on it, I can start thinking of how to add a virtualization solution. Either use my old scripts that wrap qemu and are very convenient and versatile, or go for qemu with libvirt and manage my virtual machines with virt-manager. The possibilities are endless. But first I need to get on with virtualizing my current server’s OS… its LAN services must stay operational but then in a VM on the new hardware.
There was some issue with the Ryzen cpu and Linux. Not sure if you’re one of the ones affected, but:
So the segfaults you have might not be video card related.
The segfaults happen during parallel compilation tasks where the CPU is stressed. I compiled the linux kernel twice in a row – on 15 of its 16 cores, and that took 7.5 minutes both times, without any issue or error.
The issue seems to affect older batches of Ryzen, perhaps I have one that’s new enough.
Just yesterday, Sunday, my time, I drove to the nearest large computer store and bought a Asus Prime B350-Plus motherboard, a Ryzen 5 1400 CPU and 16 gigs of RAM.
Put my “old” Nvidia GT-730 video card in it and attached my existing SSD which had both winXp and Slackware64-current on it.
Booted right up into Slackware. No fuss, no muss. It won’t boot winXp, but I expected that.
In honor of the new hardware, this morning I did a fresh install of Slackware64-current, added your multilib files and several others and it has been off to the races.
I re-partitioned the SSD, putting a 100 meg EFI partition on it, four gigs for a swap file (not sure that is really needed anymore) about a 50 gig boot/system directory and the rest
is /home.
So far, so good.
The actuall “fresh” install took less than twenty minutes. The rest of the time was installing and tweaking this and that.
As I said, so far, so good.
No surprises.
I’m looking for information on editing the elilo.conf file. I would like to see a graphic come up on the screen a la lilo.conf. That can wait.
🙂
For many years, when I installed slackware on a new computer, I had already slackware(64)-current installed and working on some other computer. I installed then on the new computer from a DVD built from the slackware(64)-current tree. I realize that probably in many cases it had been impossible to install from the official slackware DVDs.
But generally newcomers will know only the official distribution. Is not it a problem ?
Hi Helios.
No, I do not think that is a problem. Newcomers to Slackware should work with the stable release and not try to mess with -current. If they own hardware which does not work with Slackware, then there’s the LQ forum for questions and answers. Also, I created liveslak so that you can easily test new hardware for compatibility with Slackware 14.2 and -current. Just boot the Live ISO and see what works (or not).
9 out of 10 cases I just restore on the new computer a backup of the install on the old one.
There are some minor things to be taken care of — /etc/udev/rules.d/70-persistent-net.rules, /etc/fstab and /etc/hosts come to mind — but that is all.
14.2 almost works with NVMe. The installer simply doesn’t search for a EFI partition on an NVMe disk. This can be fixed by a minor modification of the script /usr/lib/setup/SeTEFI in initrd.img inside usbboot.img. Details (obvious) are in this post:
In this way I already installed 14.2 on 3 computers with NVMe SSDs.
Congrats Eric on the new hardware and also Thank you for this detailed writeup. I plan to print it out for my next hardware upgrade of both laptop and desktop. Cheers
The only problem I’ve had with the new Ryzen chip, so far, is
VirtualBox. The most recent version, doesn’t see the USB ports…. Well, I should say VB as host sees them, but the “guest” does not. Doesn’t matter switch way I set the preferences.
Perhaps, Oracle has a new version in the wings.
Pingback: Links 23/8/2017: Chrome OS For Work, GNOME 3.25.91 | Techrights
Well, the problem with VirtualBox and USB ports is not the fault of the CPU or VirtualBox.
Turns out, “….all USB devices connected to the USB 2.0 and USB 3.0 ports are controlled by the xHCI controller.”
And, according to Intel, “…the Intel xHCI USB driver is not supported on Windows XP or Windows Vista,” and Xp is what is running as a VirtualBox guest.
Had I known that I would have shopped for a different motherboard….. OTOH, I wouldn’t be surprised if USB support is the same on all recent motherboards.
Hi Eric,
Congrats on the new server! (I’m so jealous!)
As for virtualization, I hope you go the libvirt route, as it is the most versatile.
I use a mix of my own scripts (that use libvirt) and virt-manager.
Using virt-manager for managing VMs on a remote host (via ssh connection) is so convenient!
You can always mod your scripts to wrap libvirt instead of qemu directly 🙂
Anyway, I’ll stay tuned to your adventures with the new server as they are guaranteed to produce interesting stuff for the Slackware community.
I’m specially looking forward to your jenkins project and how you’ll integrate it with virtualization to build Slackware packages on a “clean” environment.
Best wishes,
Slax-Dude
Hi!
What benefits brings separate partitions for /tmp and /var?
As I understand it, some like to mount / as Read Only, but /tmp and /var hold temporary files, state data, and other data that changes during system up time so they need to be Read/Write.
My prefernce is to only have /home as a separate partition and leave / as rw. Probably a bit less secure but handy for my home systems.
I think if I were to do multiple partitions that I would use btrfs and use logical mounts. That way the file system can allocate the space to a given mount point as needed. This seems to eliminate the concern of whether /tmp or /var were made big enough or too big.
Hi Eric,
What did you end up using for managing your vm’s? virt-manager or qemu scripts?
Slackware live 1.9 I can´t compile VLC, the error say xlocal.h is missing, besaides is not possible to compile live555.
David, I fail to see how your remark is relevant to the article you are posting it in.
Just to prevent you posting this twice, here is my answer: join the online Slackware forum where these slackware-current related compilation issues are discussed every day, and the solutions posted as well.
Bottomline: your question is irrelevant to the article above, and in addition your issue has nothing to do with Slackware Live.
Hi, I am trying to follow your article to install slackware 14.2 onto a new M.2 nvme disk. However, I am getting lost at the beginning. When I extract the mini ISO (slackware64-current-mini-install.iso) into a new directory /root/initrd64-current is that on the current hard disk or on the new nvme disk ? And if I have mounted the newly formatted nvme disk on /mnt/tmp then is the chroot to /root/initrd64-current to do the new installation on the new disk (therefore /mnt/tmp/root/initrd64-current) or on the current hard disk (therefore /root/initrd64-current) ?
Thanks.
David.
David Fenlon, I thought that was pretty clear.
When you start, you do not have an installation on that NVMe disk yet. You do all these steps in the Live environment, i.e. in a RAM based filesystem. There’s a distinct difference before and after you do the chroot.
The /root directory is that of the live environment (before the chroot). And the only thing you mount on /mnt/tmp is the mini ISO – also before the chroot.
Once you have chroot-ed you are inside the directory structure of the installer and the /mnt there is something different than the /mnt of the live OS (i.e. before the chroot).
Examine these steps again. Analyze what they do, and where they do it: in the RAM-based filesystem Live OS, inside the chroot of the extracted installer, or on the fresh NVMe harddisk.
Hello again, Thanks for the quick reply. And yes, I agree, it is very clear. And idiot proof except for an idiot like me who misses out a crucial step. I missed out the step of booting the liveslak usb (quite an important step eh !). I have now got to the part of building the new kernel (4.14.23). The make went O.K. but the make install fails with the message “Fatal: Cannot open: /etc/lilo.conf”. The full output of the make install command is :
root@darkstar:/usr/src/linux-4.14.23# make install
sh ./arch/x86/boot/install.sh 4.14.23 arch/x86/boot/bzImage \
System.map “/boot”
Fatal: Cannot open: /etc/lilo.conf
arch/x86/boot/Makefile:192: recipe for target ‘install’ failed
make[1]: *** [install] Error 1
arch/x86/Makefile:308: recipe for target ‘install’ failed
make: *** [install] Error 2
root@darkstar:/usr/src/linux-4.14.23#
I don’t know what obvious mistake I have made this time because I copied and pasted the commands from your instruction page on the web (obviously changing the kernel version numbers) and I only used -j 6 in the make command.
Any help would be greatly appreciated.
Thank You.
David.
I think is important to remark that eliloconfig need params with no trail “/”.
eliloconfig /setup2hd /dev/nvme0n1p7 # works
eliloconfig /my/dir/ /dev/sda1 # doesn’t works
Alienbob writes it rightly, but I spent mins to understand. | https://alien.slackbook.org/blog/build-box-step-1-install-slackware/?replytocom=32500 | CC-MAIN-2021-17 | refinedweb | 3,147 | 65.93 |
Let's make a PHP file that will contain our function to generate keys.
<?php //function.php /** *generate_key * *generates a random key * *@return (string) random string of 64 characters * */ function generate_key() { $length = 32; $characters = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z')); shuffle($characters); return hash_hmac('sha256', substr(implode('', $characters), 0, $length), time()); } ?>
The function above uses array_merge to combine the arrays of character sets a - z, A - Z and 0 - 9 into one array. Shuffle is then used to rearrange the $characters array in a random order. The last line is where it may seem a bit confusing. Implode retrieves the array elements and makes a string out of them with the first parameter being the glue or basically the character that's going between each character in the string. So now we have a string of 62 characters in length. We now take the first 32 characters of that string and perform a SHA256 hash on it with a key being the current timestamp.
Now we'll make our the page for our login form.
<html> <head> <title>Login</title> </head> <body> <form action="login.php" method="post" enctype="application/x-www-form-urlencoded"> Username <input type="text" name="username" /><br /> Password <input type="password" name="password" /><br /> <input type="submit" value="Login" /> </form> </body> </html>
This is a simple straight forward login form with a username and password field.
This is going to be our authentication page.
<?php //login.php session_start(); require_once("functions.php"); if(isset($_POST['username'], $_POST['password'])) //verify we've got what we need to work with { /*********database_credentials.php**************/ $mysqli = new MySQLi('localhost', 'root', '', 'test'); //change to suit your database if($mysqli->errno) //connection wasn't made //handle the error here header("location: index.html"); //we'll just redirect for now /************************************************/ //We don't have to work about SQL injections here $stmt = $mysqli->prepare("SELECT COUNT(username) AS total FROM credentials WHERE username = ? AND password = ?"); //if the passwords in your table are hashed then you should apply the hashing and/or salts before passing it //they should in fact be hashed preferably with a hashing algorithm of the SHA family $stmt->bind_param('ss', $_POST['username'], $_POST['password']); $stmt->execute(); $stmt->bind_result($total); //place the result (total) into this variable $stmt->fetch(); //fill the result variable(s) binded //close all connections $stmt->close(); $mysqli->close(); //if total is equal to 1 then that means we have a match if((int)$total == 1) { session_regenerate_id(true); //delete old session variables /*********Explained below************/ $_SESSION['user'] = $_POST['username']; $key = generate_key(); $hash = hash_hmac('sha512', $_POST['password'], $key); $_SESSION['key'] = $key; $_SESSION['auth'] = hash_hmac('sha512', $key, hash_hmac('sha512', $_SESSION['user'] . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']), $hash)); /************************************/ if(!setcookie('hash', $hash, 0, '/')) //login isn't possible if user's browser doesn't accept cookies { session_regenerate_id(true); header("location: your_login_page.php"); //original_page would be your login page exit(); } header("location: protected_page.php"); } else { //anything else we don't care about header("location: your_login_page.php"); } } ?>
Our $hash variable will be used to store the hash of the user's password with the randomly generated key in a cookie. It is important it is stored in a cookie because basically we want to calculate the hash of 2 strings/keys to get one final hash and the server and client must have one key each. If one of those keys is incorrect by even a single character the user will not have access to protected pages.
Next we store our key within a session variable for later use. Now for the most important part of authentication, $_SESSION['auth']. This hash is comprised of 4 things, $key, username, client's IP and $hash. The client's IP address is concatenated unto the username thus deriving something like this
codeprada69.68.11.127This will be hashed with SHA512 while using $hash as the key. The hash produced from this will be used as the key to apply another SHA512 hash unto $key.
If a client is using a proxy then more times than not HTTP_X_FORWARDED_FOR will contain the client's IP instead of REMOTE_ADDR. This doesn't apply to anonymous proxies that doesn't set the value of HTTP_X_FORWARDED_FOR. The IP address is used so that if the user either changes computers but tries to re-use the same cookies (replay attack) or does anything that changes their IP the login session would not be valid.
Let's now make our checklogin.php
<?php //checklogin.php session_start(); //don't want to read a cookie or session variable that doesn't exist if(isset($_COOKIE['hash'], $_SESSION['key'], $_SESSION['user']) ) { if(strcmp($_SESSION['auth'], //remember this? hash_hmac('sha512', $_SESSION['key'], //see below for explanation hash_hmac('sha512', $_SESSION['user'] . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']), $_COOKIE['hash']) ) ) ) { header("location: index.html"); } } else { header("location: index.html"); } ?>
We must now rebuild the keys collected from the cookies and session and verify that the final hashed string matches $_SESSION['auth']. The key is read from $_SESSION['key'] and a SHA512 hash is applied to it with a key of the string produced from a SHA512 hash of the username concatenated with the client's IP address with a key of the hash retrieved from the cookie. This should produce the exact same string as $_SESSION['auth'] if no data was tampered with or changed.
To restrict access to a page this must be placed at the top of that page.
require_once("checklogin.php");
Here's our protected page
<?php //protected_page.php require_once("checklogin.php"); ?> <html> <head> <title>Sample Page</title> </head> <body> <h1>Welcome to the protected sample page.</h1> <h2><a href="logout.php">Logout Here</a></h2> </body> </html>
The final piece will be our logout page of course.
<?php //logout.php session_start(); session_destroy(); unset($_SESSION); setcookie("hash", "", time() - 3600); header("location: index.html"); ?> | http://www.dreamincode.net/forums/topic/234806-user-authentication-via-two-keys-ip-address/ | CC-MAIN-2016-07 | refinedweb | 970 | 53.81 |
#include <sys/usb/usba.h> int usb_pipe_get_state(usb_pipe_handle_t pipe_handle, usb_pipe_state_t *pipe_state, usb_flags_t usb_flags);
Solaris DDI specific (Solaris DDI)
Handle of the pipe to retrieve the state.
Pointer to where pipe state is returned.
No flags are recognized. Reserved for future expansion.
The usb_pipe_get_state() function retrieves the state of the pipe referred to by pipe_handle into the location pointed to by pipe_state.
Possible pipe states are:
Pipe is closed.
Pipe is active and can send/receive data. Polling is active for isochronous and interrupt pipes.
Polling is stopped for isochronous and interrupt-IN pipes.
An error occurred. Client must call usb_pipe_reset(). Note that this status is not seen by a client driver if USB_ATTRS_AUTOCLEARING is set in the request attributes.
Pipe is being closed. Requests are being drained from the pipe and other cleanup is in progress.
Pipe state returned in second argument.
Pipe_state argument is NULL.
Pipe_handle argument is NULL.
May be called from user, kernel or interrupt context.
usb_pipe_handle_t pipe; usb_pipe_state_t state; /* Recover if the pipe is in an error state. */ if ((usb_pipe_get_state(pipe, &state, 0) == USB_SUCCESS) && (state == USB_PIPE_STATE_ERROR)) { cmn_err (CE_WARN, "%s%d: USB Pipe error.", ddi_driver_name(dip), ddi_get_instance(dip)); do_recovery(); }
See attributes(5) for descriptions of the following attributes:
attributes(5), usb_clr_feature(9F), usb_get_cfg(9F). usb_get_status(9F), usb_pipe_close(9F), usb_pipe_ctrl_xfer(9F), usb_pipe_open(9F). usb_pipe_reset(9F) | https://docs.oracle.com/cd/E36784_01/html/E36886/usb-pipe-get-state-9f.html | CC-MAIN-2021-21 | refinedweb | 217 | 62.34 |
Java program to Delete a file :
In this example, we will learn how to delete a file in Java. In the below program, the full path of the file is stored in ‘fileName’ variable. First we create one ‘File’ object using ‘File(fileName)’ constructor. Then we will delete that file using ‘delete()’ function. It will return ‘true’ if the file is deleted successfully. ‘false’ otherwise.
Let’s take a look into the program :
Example Program :
import java.io.File; public class Main { /** * Utility functions for System.out.println() and System.out.print() */ private static void println(String str) { System.out.println(str); } private static final String fileName = "new.txt"; //file name with path public static void main(String args[]) { File file = new File(fileName); if(file.delete()){ println("File is deleted successfully."); }else{ println("Not able to delete the file"); } } }
To run this program , change ‘new.txt’ with the full path of your file you want to delete.
Similar tutorials :
- How to override toString method to print contents of a object in Java
- Java program to print a Rhombus pattern
- Java program to print all files and folders in a directory in sorted order
- Java program to replace string in a file
- Java program to print the boundary elements of a matrix
- Java example to filter files in a directory using FilenameFilter | https://www.codevscolor.com/java-program-delete-file-using-file | CC-MAIN-2020-40 | refinedweb | 222 | 66.23 |
I am facing a very frustrating issue:
After running
exp publish all Assets and the Vector Icons from
@expo/vector-icons are not displayed anymore. This happens for both JS urls, development and production.
It is a detached expo app and I try to run it on Android.
I tried to re-build the Android project again several times, every time it stops working after I run
exp publish.
I also tried this solution of @llamaluvr but
import { Asset } from 'expo'; Asset; did not help and
expo-pre29.gradle does not find
"./android/detach-scripts/run-exp.sh".
I have noticed that when I run
exp publish there are no changes detected, even if I delete the published project beforehand.
[17:37:04] Uploading assets [17:37:04] No assets changed, skipped. [17:37:04] Processing asset bundle patterns: [17:37:04] - /home/dfels/projects/my_app/**/*
Is there a solution for this? | https://forums.expo.io/t/assets-and-vector-icons-not-displayed-anymore-after-exp-publish/13300/2 | CC-MAIN-2018-39 | refinedweb | 152 | 65.12 |
Building an Infinite Timer using Python
This article was published as a part of the Data Science Blogathon
Overview
- What is this “Infinite timer in Python”?
- What are its uses?
- How to make it?
What is this “Infinite Timer using python”?
Infinite timer using Python is a program written in Python using its libraries. It serves as a reminder by notifying you of tasks or notifying users at a regular interval like a so-called infinite timer.
What are the uses of Infinite Timer?
Suppose someone is very forgetful about his/her breaks or tasks. Then this program can be used to remind him of the work at a regular time interval.
How to make an Infinite Timer in Python?
Now the real part comes in. Here we are going to use some python libraries to make it.
- plyer module – for notifying purpose
- speechRecognition – For voice commands
- pyttsx3 (python text-to-speech) module – to interact with the user
- Time module – for the reminder
- Regex or re module
Now we will install the plyer and speechRecognition and pyttsx3 module. The syntax for this –
pip install plyer speechRecognition pyttsx3
NOTE: TIME AND RE MODULE COMES BUILT-IN WITH PYTHON, SO NO NEED TO INSTALL IT!
So the theme is that we are going to make a program in which we will give the commands using our voice like talking to Siri or Alexa and it will set our reminder and will notify the user.
First of all import notification from plyer module
from plyer import notification
Then import remaining libraries-
import time import pyttsx3 import re
We will import speech_recognition as sr(So we can call it easily)
import speech_recognition as sr
Now we will activate the Recognizer function from the speech_recognition module
listener = sr.Recognizer()
Now activate init() function from pyttsx3 to initialize the pyttsx3 engine and then set the properties for it as given here:
engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) engine.setProperty("rate", 125)
Now we are going to create a function that will use pyttsx3 to speak out something. So we can say something to user like “Hello How can I help you” and a number of times.
def talk(text): engine.say(text) engine.runAndWait()
In the above function, we have used the say() function which will mainly speak out the content, and then runAndWait() function will stop the engine.
Now we are making another function receive_command. Here using speech_recognition we are going to intake the words from the user.
def receive_command(): try: with sr.Microphone() as source: print('listening...') voice = listener.listen(source) command = listener.recognize_google(voice) command = command.lower() except: talk(“Error in decoding command”) return command
In the above function, what we have done is, firstly we have put there a try-except statement which will help when the recognizer may not be able to catch up with the commands. Then we have used the Microphone function from the “sr” library as source to listen to the commands. Then to ensure that we are successfully listening to the user we will print listening. Using function listen of “sr” program we will get the source then using recognize_google() function the command will be decoded and got back to the program in command variable. Now we will use a python in-built function lower() to make the command in lower case of the alphabet to match if any word if we want. Then using except syntax we have excepted the function that is if there is any problem in try then except will perform and talk() function will be called and it will say “Error in decoding command” and then the function will return the command variable
Now we are going to make another function that is a reminder and it will be our main function of this program. Its motive will be to interact with the user and use the above functions to comfort the user.
def reminder(): talk("hello what's the command") talk("reminder please") command = receive_command() command2 = re.findall("[0-5][0-9]",command) talk("Do you want to repeat it at regular interval. Yes or NO") command3 = receive_command() talk("OK") repeat = True if "no" in command3: repeat = "A" while repeat: notification.notify( title = "Timer", message = "Message for reminder", app_icon = "path to your .ico file", app_name = "Tiimer" ) time.sleep(60*int(command2[0])) #In minutes
In this last function reminder(), we have welcomed the user then asked the user for the reminder, then listened to it using the receive_command() function. Now we will use the re module to find the timer given in the command. So we are using findall() function of re and here ”([0-5][0-9]” is the syntax to find the exact minutes after which the program needs to remind. Then asked the user if he/she wants to repeat it at regular intervals or only 1 time. And using receive_command function, listened to the user and returned the command in command3 variable, again ensuring user “OK” that the program listened to him/her successfully then using a logic that if the user says “yes” then repeat will be True or it defaults true and then using “if statement” if a user says “no”, repeat will be “A” and it will overwrite repeat. Now, there is only one character in repeat variable, so in while loop “A” will be of 1 character then it will run only for 1 time and if the user had said “yes” then repeat will be True and it will run always until the user had not killed the program. Now in the loop, we have used notify function of notification which we had imported before from the plyer library. Then it requires several things like title, message, app_icon, etc.
Title – It takes string. And it is the title of the notification
- Message – string and message of the notification
- app_name – string and name of the app launching this notification
- app_icon – string and path of .ico file that is the path of icon to be displayed along with the message
- timeout – integer and time to display the message for, defaults to 10
- ticker – string and text to display on the status bar as the notification arrives
- toast – Boolean and simple Android message instead of full notification
In the above arguments, most of them are optional like if you only want it simple then just put title and message.
Again going to the last function we have given here title, message, app_name, app_icon. And then in the last statement, we used the time library, and then and as per the order of user we will multiply it by 60 to convert it into minutes.
TIP: YOU CAN CHANGE THE TIMER TO HOURS OR ONLY SECONDS AS YOUR CONVENIENCE AND YOU CAN SET THE TITLE AND MESSAGE ONLY ONE TIME AND USE IT EVERY TIME WITHOUT CHANGING. YOU CAN USE receive_command() TO CHANGE THE TITLE OR MESSAGE.
REMEMBER: Speech_recognition will take some time to decode the command or even sometimes it will through error. So try again and it will not work when the user is offline.
if __name__ == '__main__': reminder()
At last, we have called the ”__main__” function so that we can run it anywhere on the system and then called reminder() function
Conclusion
You change the minutes or seconds or even you change the contents of the message or title. You can customize the program as your wish.
If you are likely to be reminded at a regular interval and you don’t want to run this program manually then you can automatically run this on startup. The steps for running automatically is given for windows-
Voila! Now you have your own so-called infinite timer.
If you face any problem with the program then feel free to ask in the comment section.
Images:
Photo by Ron Lach from Pexels
I am Atulya Khatri a python geek. I love to learn different programming languages and different libraries and create stuff. Do share this with all your friends who you think need this.
Leave a Reply Your email address will not be published. Required fields are marked * | https://www.analyticsvidhya.com/blog/2021/11/building-an-infinite-timer-using-python/ | CC-MAIN-2022-40 | refinedweb | 1,359 | 60.45 |
Ctrl+P
A beautiful way to get information about coding for alt:V without stumbling around in the dark. This will give you information about what you are typing by hovering over different elements in your code. However, it will not cover all elements. Just in most cases you can get general information while working with the alt:V API.
This tool provides human readable examples for the alt:V API while also ensuring that you don't spend too much time weeding through documentation files to figure out how something works.
This is an unofficial community extension for alt:V and the documentation that you find inside of it can be modified and updated.
Made for Usage with altv.mp
npm init
myServer
myServer/
├─── altv-server.exe OR altv-server
├─── libnode.dll
├─── server.cfg
├─── package.json # From running 'npm init'
├─── modules/
│ └─── js-module
└─── resources*/
└─── myResource/
├─── server/
├─── client/
└─── resource.cfg
* = Any Folder Name
⚠️ Open up a workspace folder where altv-server is located.
altv-server
⚠️ This will not work without altv-server present.
⚠️ If it does not work the first time you will need to re-open VSCode.
Verifies if altv-server is present in the current workspace. The rest of the plugin will not load until a proper server infrastructure is setup. Please refer to the Setup & Installation guide above.
Sets up your workspace to install missing dependencies needed for alt:V.
Requires package.json to be present.
package.json
.js
.mjs
Adds references to the tops of files if using .js or .mjs. Which automatically figures out if you're on client-side or server-side. This is necessary for types to work properly for using non-typescript infrastructure.
Automatically fixes a module bug that users often overlook. This ensures that you are working in an ES6 environment regardless of whether or not you are using Javascript or Typescript.
Hover over a type to get more information about the type. This uses the official alt:V Types but this also provides human readable examples by clicking on the >> Open Documentation.
>> Open Documentation
Simply click: Open alt:V Docs to bring up built-in documentation for alt:V Types with examples. This will provide basic examples of how to use certain namespaces, functions, and properties.
Open alt:V Docs
You can also use the command palette CTRL + Shift + P and type alt:V Documentation to browse docs.
CTRL + Shift + P
alt:V Documentation
.md
docs
Front Matter
Basically each folder is a prefix for some documentation.
⚠️ Only useful for making contributions.
If you are running this from the cloned github repository.
npm install
Run Extension
npm: watch
You can also hit F5 in VSCode to debug the extension.
1.1.7
- Updated Welcome Page
- Added RAGE:MP Migration Page
- Updated Various Player Documentation
- Added Meta Documentation
- Added Documentation for client-side player
- Added Syntax for client-side player and server-side player.
- Added How to Install the Chat Resource
- Added How to Write Commands for Chat Resource
1.1.6
- Added Snippet for Help Text
- Added Snippet for Markers
- Added Snippet for Notifications
- Added Snippet for Prototyping
- Added Snippet for Text Labels
- Added Snippet for Voice
- Added New Snippets to Snippet Directory
- Added Section 10 to Bootcamp
- Added Section 11 to Bootcamp
- Misc. Changes to `player` Section
1.1.5
- Added Bootcamp Tutorial
- Bootcamp includes 9 pages on getting started with alt:V
1.1.4
- Refactored Functionality
- Added Better Getting Started Page
- Added Backlinks to Getting Started Page
- Added Better Browsing Experience
1.1.2
- Added First Time Loading Page
- Added Getting Started Guide
- Added New Tables
1.1.1
- Remove Hover Markdown
- Documentation is now accessible through open 'x' document on hover.
- Added 'local' replacement for player.
- Local now shows documentation for client-side player.
- Updated README to be more feature complete.
- Added Server Events
- Added New Concepts
- Added Tables
1.1.0
- Add Front Matter to .md Files
- Add Better Title / Prefix Handling for Files
- Format All .md Files
- Thanks Alexa/Zack!
1.0.9
- Better Search Box for Documentation Browsing
- Better Markdown Preview for Documentation Browsing
1.0.8
- New Built In Documentation Browser
1.0.7
- Fix Types for Smaller Files
1.0.6
- More Types!
1.0.5
- Must have 'altv-server' in workspace to start.
1.0.4
- Better Word Lookup Extension
- Auto Install Missing Dependencies
- Auto Check if `altv-server` workspace
- Auto Install References for .js / .mjs
- Organized Folders
1.0.3
- Added server alt definitions
1.0.2
- Added Client / Server Check
- Added Vehicle
1.0.1
- Added Basic Player Parameters
1.0.0
- Release Template | https://marketplace.visualstudio.com/items?itemName=stuyk.altv-vscode-docs | CC-MAIN-2021-21 | refinedweb | 766 | 59.6 |
As we all know, Amazon Web Services (AWS) is a very popular name and a wonderful platform for Java application development to run Java workloads which offer for deploying and managing both off the shelf as well as custom applications. The new customers are unclear as to which method will allow them to quickly get their application running up when planning to deploy a java web application to AWS for the first time. AWS is an evolving and comprehensive cloud computing platform provided by Amazon for a mix of infrastructure as a service (IaaS), platform as a service (PaaS) and packaged software as a service (SaaS).
Amazon.com launched AWS in 2006 from its internal infrastructure to handle all online retail operations. It was one of the first company to introduce pay as you go cloud computing model that scales to provide users with storage as needed. AWS offers services from dozens of data centers spread across availability zones in regions across the world.
An availability zone is a location that typically contains multiple physical data centers, whereas a region is a collection of AZs in geographic proximity connected by low-latency network links. Virtual machines are spun up by AWS customer to replicate data in different AZs to achieve a highly reliable infrastructure that is resistant to failures of individual servers or an entire data center. In this article, we will provide you with a quick overview so that you get an idea about deploying your Java enterprise application on the AWS cloud.
In order to begin, you are required to sign up for an AWS account which can be done via aws.amazon.com. Click on the button like "Create an AWS account" or "Sign in to the Console" which will take you to the account creation or sign in the screen that looks like depicted below.
If you are a regular customer who does shopping from Amazon, then you don't need to sign up again; you can continue with AWS from the same shopping account. But, if you are creating a brand new account then you definitely have to fill out some account information as given below.
[Related Article: Brief Introduction To Amazon Web Services (AWS)]
After filling out all of your personal and business information you also need to give payment information. Amazon does not charge a single penny for the first 12 months for using AWS. All of the payment procedure begins once the free trial months get completed. The payment information contains to enter your credit or debit card data and after entering it, you will have to verify your identity by receiving a call or typing a PIN on the assigned phone number/email.
Related Blog: [Best Java EE Frameworks]
After everything is filled up, you need to select the support plan that gives you an opportunity to have access to set everything up. Unless you are a large corporation you don't need to choose anything other than their basic support plan which is totally free and gives you access to their online documentation.
And there you go! After successfully creating the account, you can log in to the console and type your account information that you created previously to log in to your AWS dashboard. Then comes the next step to create a Tomcat server using Amazon Web Services called Elastic Beanstalk product for Java development services.
Next, we are going to create a virtual server in the cloud for an instance that will be running a Tomcat server which is known as a t2.micro instance, its part of Amazon's free tier offering. To create this server, you need to login to your AWS dashboard and navigate to Elastic Beanstalk by clicking on services option.
After clicking, you are going to Get Started by entering a few simple details to get your environment up and running.
Once you hit the 'Create Application' button, AWS will proceed to create your environment for you.
This usually takes about a few minutes and then presents with a familiar screen.
Before working in Elastic Beanstalk, you need to take care of few points.
After your app is launched, take a note of your screen to go ahead and click on your app's URL to see in action.
We also need to launch our own code onto this Linux server with Tomcat installed on it. To create your new Java development company cloud environment, you need to look at some other important configuration.
Change your t2.micro instance by clicking on 'Instance type' label.
Once the environment is accustomed to seeing, you will see its updates on the screen.
All of that INFO status will be changed to OK health status once your new t2.micro instance is ready to go.
want to take your cloud knowledge next level click here to learn What is Cloud Computing
You got a running instance in elastic beanstalk but it does not contain your application's code yet. To insert your code you have two options to unfold:
If you have created your application code using SpringBoot then you can skip this step. But for those, you haven't, here's all that you can do. Firstly, you have to create a deployable WAR file from your project by invoking a Maven install on your code-base. Just be sure to get your maven pom.xml as a WAR and not JAR. You can simply take your WAR file and upload it to Elastic Beanstalk.
The basic logic is to replace your existing class which contains your main method with the SpringBoot version which looks like this:
@SpringBootApplication public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
Related Blog: AWS vs Azure
Your code is prepared for getting ready to deploy to AWS. Make sure you have set up Maven to deploy your project as a WAR file which can be seen inside of your pom.xml file under that looks something like this:
< ?xml < modelVersion >4.0.0< /modelVersion > < groupId >com.proffesso< /groupId > < artifactId >proffesso-core< /artifactId > < version >1.5.1.12< /version > < !-- Here's where you set it up as a WAR file-- > < packaging>war< /packaging > < name >CourseCreation< /name > < description >CourseCreation project for Spring Boot< /description > < /project >
The next step is to maven package your code together into a deployable WAR file by selecting your application's root project folder and running it as Maven install.
Then, you need to upload and deploy your source code file.
By hitting that deploy button your WAR file gets uploaded to Elastic Beanstalk and deployed in front of you. Once it is reported to OK health status, you should be able to visit your unique URL for your website.
By following the steps sincerely, you have successfully launched your application into the cloud but what if you still need to hook it up to a database. The newly launched cloud application does not work properly using a reference to localhost:8080 fro your database connection string. To overcome this, you need to launch a database in the cloud using Amazon RDS.
If you have already created an RDS instance before, you just need to click the 'Launch a DB instance' button. We will be creating a MySQL instance which tends to be cheap as MySQL is free. You can also choose whichever option suits your needs.
Next, we will need to choose what kind of instance to run for the database and specify your DB details for free tier support.
After all these steps, you are all set to launch your first Amazon RDS instance. But still, there requires other configuration we need to do. Go ahead and click on 'View Your DB Instance' to watch your database get created before your eyes as it usually takes 10 minutes to get through the entire process.
Once the status of your DB instance is set to available, you will ready to start configuring things. You can connect your DB from outside of your Virtual Private Cloud. Identify which security group was created for your DB instance to expand the details section.
You can also head over to EC2 page by clicking on Services.
You can click the Edit button to edit the inbound rules and edit the existing rule or add a new one like so. Also, you can choose a new rule and open it up to allows all inbound traffic as given in the below screenshots.
Thus, your new DB instance is ready to rock.
You can log into DB instance using MySQL Workbench or Toad for MySQL by following the given procedure.
Next, you need to connect your application code to this database via your properties file which you used to connect to your database previously. This can be found in your application.properties file if you are using a Spring Boot application.
Frequently Asked AWS Interview Questions
To get rid of the non-friendly UEL that Elastic Beanstalk assigns to your application, you can use another AWS product called 'Route 53'. Once you begin with it, you can create 'Hosted Zones' which allow forwarding our incoming HTTP traffic to our Elastic Beanstalk application from any domain we owe.
The only pre-requisite is that you will need to own a domain name that will get forwarded to Elastic Beanstalk application. To point towards the AWS app when someone navigates to your domain name, create a new 'Record Set' and also point to a subdomain to the same place as well. And Voila! you are all set to go.
In a few simple clicks and steps, you can deploy a simple yet production-ready Spring Boot application with a MySQL database on AWS using Elastic Beanstalk. The launch and configuration of the environment as a part of Elastic Beanstalk to launch resources using other AWS services as these resources still remain under your control. These resources can be accessed through other AWS service consoles like EC2 and RDS.
With the help of deploying your Java enterprise application to the Amazon's AWS cloud computing helps to trade capital expense for the variable expense, benefits from massive economies of scale, delimits the storage capacity, increases the speed and agility and also ease out from maintaining data centers as well as gets global in minutes of time. So, what are you waiting for? Start now
Are Kolkata , AWS Online Training in London, AWS Online Training in Mumbai, AWS Online Training in NewYork, AWS Online Training in Noida, AWS Online Training in Pune, AWS Online Training in Toronto
These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in AWS and help you to achieve your dream job
About Author | https://mindmajix.com/java-enterprise-application-in-aws-cloud | CC-MAIN-2021-31 | refinedweb | 1,818 | 59.74 |
In order to interop with .NET libraries, we need first load in the assemblies we want to play with. The family of AddReference methods in the clr module serves the purpose.
clr.AddReference accepts System.Reflection.Assembly objects and/or assembly names. The typical usage looks like:
If a string is passed in, Assembly.Load(string) is used to load the assembly. If failed, it re-tries with Assembly.LoadWithPartialName(string).
clr.AddReferenceByName basically is the wrapper of Assembly.Load, which means the assembly full name is expected. Similarly, clr.AddReferenceByPartialName is the wrapper around the obsolete Assembly.LoadWithPartialName: "System.Drawing" and "System.Drawing, Version=2.0.0.0" are examples of valid arguments.
A typical usage of clr.AddReferenceToFile looks like:
It expects file name(s) without the directory path as the argument. To locate my1.dll, it searches each directory in sys.path until the specified file is found (it also tries to append ".dll" or ".exe"). Behind the scene, the loading is via Assembly.LoadFile. Normally sys.path includes the current working directory; so if my1.dll and my2.dll exist in the current directory, clr.AddReferenceToFile("my1.dll", "my2") should succeed. If you know the exact full path of a clr assembly, you may use clr.AddReferenceToFileAndPath to load. As a by-product, the path of the assembly file will be appended to sys.path. Note Assembly.LoadFrom is never used underneath by these 5 methods due to the loading context concern.
We can use clr.References to list which assemblies have been loaded. The output shows that mscorlib.dll and System.dll are implicitly loaded/added (without the need of calling clr.AddReference).
By treating the namespace like the python module, IronPython extends the import statement semantics to bring in the clr namespace. In current implementation the "classical" python module is still preferred by import: given the statement "import MyLib", if the file "MyLib.py" is present under any directory of sys.path, that file will be imported; if not, for each loaded assembly, import tries to find the namespace "MyLib". Although not common in well-designed .NET frameworks, a type could have empty namespace; so "import MyLib" also tries to find type "MyLib" in the loaded assemblies.
The namespace of "MyLib" could exist more than 1 loaded assemblies. The following snippet shows that, "import System" adds a CLS module to sys.modules and this CLS module contains members from 2 assemblies: mscorlib.dll and System.dll (since both assemblies has types and down-level namespaces like System.*). | http://blogs.msdn.com/b/haibo_luo/archive/2007/09/25/5130072.aspx | CC-MAIN-2014-41 | refinedweb | 423 | 54.08 |
Important: Please read the Qt Code of Conduct -
Qt 4.7.4 qmetatype errors in Linux
- danil_mark last edited by
Hello, dear Qt developers! I got a problem and I can't understand why it appears. I downloaded Qt 4.7.4 sources, build it in Linux (Mint16 if it matters).
I used Qt in VS before, so I generate .pro files using Qt add-in and copied whole project to Linux. Fixed some path issues etc, and now when I try to compile my project there one of the errors I get is the
- /opt/Qt4.7.4/include/QtCore/qmetatype.h:271: error: definition of 'static int QMetaTypeId<QMap<int, double>>::qt_metatype_id()' is not in namespace enclosing 'QMetaTypeId<QMap<int, double>>' [-fpermissive]
!(error output)!
When I run my project in Windows there are no such error!
Whats worng? How to fix that problem if its possible?
bq. When I run my project in Windows there are no such error!
Nothing to do with running your application. You are not getting past compilation.
bq. Whats worng? How to fix that problem if its possible?
We cannot see your code so we cannot know exactly what you are doing to trigger this. At a guess you are declaring a QMetaTypeId specialisation in a namespace by incorrectly using Q_DECLARE_METATYPE. GCC is not compiling the resulting source where MSVC has been more lax.
You should read the docs about Q_DECLARE_METATYPE and namespaces:
Is there a reason you are using an old version of Qt? | https://forum.qt.io/topic/38154/qt-4-7-4-qmetatype-errors-in-linux | CC-MAIN-2022-05 | refinedweb | 252 | 75.91 |
PHP News You May Have Missed – August, September 2014).
Let’s see what’s new.
HHVM announces LTS.
Geocoder at 2.6
Geocoder, the library that helps you build geo-aware applications, got to version 2.6. This sounds minor, bit given the additions we got, it really isn’t. Got any geo-aware PHP apps you’d like to share with us? Let us know – we’d love to publish and promote your work, as long as it follows best practices and people can learn from it!
Zend Framework 2 for Beginners
Our very own Matthew Setter published his own Zend Framework book, titled Zend Framework 2 Foundations. In it, he explores the intricate depths of the behemoth framework, covering everything a beginning Zender needs to get familiar with the framework enough to proceed on his own. Matthew put his heart and soul into this manuscript, so make sure you give it a shot if you’re the least bit interested in Zend Framework 2.
Versionscan 1.0
The Versionscan tool by Chris Cornutt reached its 1.0 milestone. We covered the tool a bit here, but in essence, you use it to scan your PHP’s version for known unfixed bugs and issues, thereby gauging your installation’s default security and maturity. If you’ve ever been unsure of whether you should invest the time to update the version on your production server to the newest one, use this tool to help yourself out.
Recki-CT and JitFu
Anthony Ferrara released his 20% project recently, calling it ReckiCT. Explaining it and/or arguing whether or not it makes sense to use it seeing as it seems to be slower than native implementation right now is beyond the scope of this post, so just check out the quick tip if you’d like to learn how to install it and give it a go.
If you’re completely unaware of what it is, it’s a compiler written in PHP, which produces optimized PHP code the speed of which rivals recent implementations – one difference being that you don’t move away from PHP syntax, unlike in most other solutions like Zephir. You can, allegedly, use Recki to optimize parts of your app without changing the entire underlying runtime (unlike with HHVM).
Laravel 5 News
Laracon is over, and the new version (now 5.0 instead of 4.3) brings us some interesting goodies. First and foremost, the directory structure has changed – the app folder now only contains three folders: Console, HTTP, and Providers. Under Console, you’ll have all the CLI aspects of your application. HTTP will contain everything that happens when you access your website in the browser, and you’ll use Providers to register filters, services and such. The models now go into the root of the app directory, and all the classes are namespaced with PSR-4. You can rename the main root namespace of the application from App to X (where X is anything you want) by running
php artisan app:name X. This will traverse all the files and rename the app name where needed. Furthermore, namespaces can be custom configured in
config/namespaces.php.
You can also have arguments auto-injected into controller methods from the IoC container, which is very useful when validating stuff – it cuts down on the amount of code drastically. New generators were added, so you can have a bunch of files written for you automatically. There’s also multiple filesystem support via FlySystem, Contracts, Route Caching for ultra fast route registration and Socialite for dead easy social network authentication, but Jeffrey Way covers all these very very well, for free.
Phalcon 2.0 beta 2
Whilst on the topic of new versions of popular frameworks, the ever more amazing Phalcon has released beta 2 and is looking for user feedback. Install it, test it, dive in and see what you can do with it – it has now been almost completely rewritten in Zephir (the API is still the same), so you can lend a hand at further conversions and tests as well. Read their official blog post for more info!
PhpStorm 8.0 adds Z-Ray and PHP 5.6 support!
The upcoming version of PHPStorm will not only have full support for PHP 5.6, but Jebrains, the makers of PHPStorm, have also struck a deal with Zend Technologies to include Z-Ray in the next release. If you’re unclear on Z-Ray, it’s a part of Zend Server which we’ve covered before to some extent, and which you can find out more about at this link.
In the words of.
Let us know if you try it out, we’d love to publish some detailed insights and offset your Zend Server bill ;)
That’s it for this time around, if you feel like I’ve missed anything, let me know! | https://www.sitepoint.com/php-news-may-missed-august-september-2014/ | CC-MAIN-2019-13 | refinedweb | 817 | 68.81 |
WaitGroup is a concurrency control method often used in development. Its source code is in Src / sync / WaitGroup In the go file, 1 Structure and 4 methods are defined:
- WaitGroup {}: structure.
- state(): the internal method is called in Add() and Wait().
- Add(): adds the number of tasks.
- Done(): completing a task is actually Add(-1).
- Wait(): block waiting for all tasks to complete.
The following source code is based on go version 1.17.5 and has been deleted.
$ go version go version go1.17.5 darwin/amd64
Before learning, you can understand some concepts:
- Refer to the related contents of structure alignment Previous notes.
- There are two semaphore functions:
runtime_Semacquire means to add a semaphore and suspend the current goroutine. Used in Wait().
runtime_Semrelease means to reduce a semaphore and wake up one of the waiting goroutine s on sema. Used in Add().
- unsafe.Pointer is used to convert various pointers to each other;
uintptr is a built-in type of golang. It can store pointer integers. Its underlying type is int, which can be combined with unsafe Point to point conversion.
1, Structure
1.1 composition of state1 array
type WaitGroup struct { // Indicates that 'WaitGroup' cannot be copied and can only be passed by pointer to ensure global uniqueness. noCopy noCopy // state1 = state(*unit64) + sema(*unit32) // state = counter + waiter state1 [3]uint32 }
state1 is a uint32 array, which contains the total number of counter s, the waiting number of waiter s and semaphores of semaphores, where:
- counter: the count value of the sub goroutine set through Add().
- Waiters: the number of waiter s caught blocking through Wait().
- sema: semaphore.
1.2 location of state and sema
In fact, counter and water are used together as a 64 bit integer, so the state1 array can be regarded as composed of * unit64 state and * unit32 sema, that is:
state1 = state + sema, among state = counter + waiter.
4-byte alignment in 32-bit system and 8-byte alignment in 64 bit system. The following internal method state() is used to judge.
The state() method takes out the state stored in the state1 array. The return value statep is the state of the counter, that is, the whole of counter and water, and semap is the semaphore.
func (wg *WaitGroup) state() (statep *uint64, semap *uint32) { // Determine whether 64 bit alignment if uintptr(unsafe.Pointer(&wg.state1))%8 == 0 { return (*uint64)(unsafe.Pointer(&wg.state1)), &wg.state1[2] } else { return (*uint64)(unsafe.Pointer(&wg.state1[1])), &wg.state1[0] } }
In state(), after converting the address allocated by the runtime into uintptr, and then%8, judge whether the result is equal to 0. If it is 0, it indicates that the allocated address is 64 bit aligned.
- If it is 64 bit aligned, the first two bits of the array are state and the last bit is sema;
- If it is not 64 bit aligned, the first bit is sema (32-bit) and the last two bits are state.
When we initialize a waitGroup object, its counter value, water value and sema value are all 0.
1.3 why is the state1 array so designed
Why design counter and water as a whole? This is because atomic is used for state 64 operations, such as:
- Add()
state := atomic.AddUint64(statep, uint64(delta)<<32)
- Wait()
state := atomic.LoadUint64(statep) if atomic.CompareAndSwapUint64(statep, state, state+1) {}
To ensure the 64 bit atomicity of state, it is necessary to ensure that the data is read into memory at one time, and to ensure this one-time, it is necessary to ensure that state is 64 bit aligned.
2, Add() function
Using 64 bit atomic addition, add delta to the counter (delta may be negative). When the counter becomes zero, wake up the waiting goroutine through the semaphore. Here, Add() is analyzed in several steps:
- step 1: get the pointers corresponding to counter, water, and sema, and add delta to counter.
// Get pointers to statep and semap, that is, counter, water and sema statep, semap := wg.state() // Move the delta left by 32 bits and add it to the state, that is, add the waiting couter using atoms and add Delta state := atomic.AddUint64(statep, uint64(delta)<<32) v := int32(state >> 32) // The lower 32 bits are couter, that is, increased. Note that this is converted to int32 type w := uint32(state) // The upper 32 bits are waiter
- step 2: counter is not allowed to be negative. Otherwise, panic is reported.
if v < 0 { panic("sync: negative WaitGroup counter") }
counter is the number of active goroutine s, which must be greater than 0. If it is negative, there are two cases:
The first is Add(), where delta is directly negative. After atomic addition, counter is less than 0, which is generally not written in this way;
The second is to execute Done(), that is, when Add(-1) is executed, the previous goroutine is reduced to 0. Before the execution is completed, it is suspended, and another Done() comes, and the logic goes wrong.
- step 3: Wait has been executed. Add is not allowed at this time.
if w != 0 && delta > 0 && v == int32(delta) { panic("sync: WaitGroup misuse: Add called concurrently with Wait") }
Water is the number of goroutine s waiting. There are only two operations: adding 1 and setting zero, so it must be greater than or equal to 0. When adding (n) for the first time, counter=n, water = 0, w= 0 indicates that Wait has been executed;
Delta > 0 indicates that this is an addition operation. If v == int32(delta), that is, v + delta == delta, deduces v=0, it may be the first time to Add() or execute Add(-1) to reduce V to 0, that is, Wait first and then Add.
- step 4: if counter > 0 or water = 0, return directly.
if v > 0 || w == 0 { return }
After accumulation, counter > = 0.
If the counter is positive, it means there is no need to release the semaphore and exit directly;
If the waiter is 0, it means that there is no waiting person, and there is no need to release the semaphore. Exit directly.
- step 5: check whether WaitGroup is abused, that is, Add cannot be called concurrently with Wait.
if *statep != state { panic("sync: WaitGroup misuse: Add called concurrently with Wait") }
After execution, counter = 0 & & water > 0 indicates that the previous Done has been completed, the counter is cleared, and it is time to release the signal to wake up all goroutine s in the wait. If the state status changes at this time, it indicates that someone has modified it and added it, reporting panic.
This step of judgment is equivalent to a lock to ensure that WaitGroup is not abused.
- step 6: release all queued waiter s.
*statep = 0 for ; w != 0; w-- { runtime_Semrelease(semap, false, 0) }
If it is executed here, it must be a negative delta operation. counter=0 and water > 0 indicate that the task has been completed, there is no active goroutine, and the semaphore needs to be released. Set all States to 0 and release all blocked waiter s.
3, Wait() function
The main goroutine executing the Wait() function will add 1 to the wait value and block. Wait until the value is 0 before continuing to execute subsequent code.
func (wg *WaitGroup) Wait() { // Get pointers to statep and semap, that is, counter, water and sema statep, semap := wg.state() for {// Note that this is in an endless loop state := atomic.LoadUint64(statep)// Atomic operation v := int32(state >> 32) // couter w := uint32(state) // waiter // If the counter is 0, it means that all goroutine s exit without waiting if v == 0 { return } // Add waiter for CAS operation if atomic.CompareAndSwapUint64(statep, state, state+1) { // Once semaphore sema is greater than 0, the current goroutine is suspended runtime_Semacquire(semap) // The Add() function will set the counter and water to 0 before triggering the semaphore, so * statep must be 0 at this time. If * statep is not 0, it means that the WaitGroup has been reused before the waiter completes the Wait() and performs the Add() or Wait() operation. if *statep != 0 { panic("sync: WaitGroup is reused before previous Wait has returned") } return } } }
4, Competitive analysis
In Add() and Wait(), there is data competition for the operation of state data:
To solve the data competition, you can lock the state1 array before the operation and release the lock after the operation. This certainly has no security problem, but it is inefficient.
Data competition is solved in the source code without using locks. It is solved in several cases:
- Add and add concurrent
If multiple Add numbers are added at the same time, only Add numbers, whether positive or negative. As long as the counter is greater than 0, return directly. Because it is atomic addition, there is always a sequence to ensure that it will not be lost.
if v > 0 || w == 0 { return }
If the counter is equal to 0 after adding a negative number, the signal will be released at this time. Other adds cannot be allowed to change this data at the same time.
if w != 0 && delta > 0 && v == int32(delta) { panic("sync: WaitGroup misuse: Add called concurrently with Wait") }
- Add and Wait concurrent
If the counter is equal to 0 after Add plus a negative number, the signal is released at this time, and Wait is not allowed to modify the data. If Wait reads state first and then changes state, panic will appear.
if *statep != state { panic("sync: WaitGroup misuse: Add called concurrently with Wait") }
5, Case analysis
func main() { var wg sync.WaitGroup...............① wg.Add(2)...........................② go func() { fmt.Println(1) wg.Done().......................③ }() go func() { fmt.Println(2) wg.Done().......................④ }() wg.Wait()...........................⑤ fmt.Println("all work done!") }
After 1 and 2 are executed, 3, 4 and 5 are executed randomly.
Assuming that it is executed in the order of [1, 2, 3, 4, 5], the values of counter and water change as follows:
① counter=0, water = 0 / / the default value of initialization is 0
② counter=2, water = 0 / / the atomic addition operation adds 2 to the counter
③ counter=1, water = 0 / / complete a Done, subtract 1 from the counter, and the counter changes from 2 to 1
④ counter=0, water = 0 / / another Done is completed. Subtract 1 from the counter and the counter becomes 0. If V > 0 or w=0 is satisfied, return directly without sending a signal
⑤ counter=0, water = 0 / / because v=0, return directly without CAS operation
Assuming that it is executed in the order of [1, 2, 5, 3 and 4], the values of counter and water change as follows:
① counter=0, water = 0 / / the default value of initialization is 0
② counter=2, water = 0 / / the atomic addition operation adds 2 to the counter
⑤ counter=2, water = 1 / / CAS adds 1 to the water, so the water changes from 0 to 2
③ counter=1, water = 1, complete a Done, subtract 1 from the counter, and the counter changes from 2 to 1
④ counter=0, water = 1, complete another Done, subtract 1 from the counter, the counter becomes 0, send a signal to inform the water that it is no longer blocked, and main continues to execute | https://programmer.ink/think/go-waitgroup-source-code-analysis.html | CC-MAIN-2022-05 | refinedweb | 1,884 | 60.55 |
Hello! I'm trying to learn parsing and parser combinations in Haskell, using, as usual, Wadler's Monads in Functional Programming as my text book. Everything works fine except for a small but annoying problem related to "read". I'm sure it must be something easy, some kind of stupid faq. Still I'm not able to find a way out. I created a simple parser and made it an instance of monad and MonadPlus. I then created "iterateP" to combine recursive parsers, and "filterP" to apply some filters. Then I created a function "number", to parse numbers. This function returns a string and works fine. But I wanted to have integers back from parsing. So I created a filter, "digitS", and a new parser for numbers, "number1", that applies recursively digitS and should be returning an Int using "read". The")] Obviously if I use Parsec I can parse that number perfectly. So I tried with another approach: "number2" recursively applies a filter, "digitI", that returns an Int. asNumber is a function that takes a list of single digit integers and returns the corresponding integer. *Main> runP number2 "12345678901 and the rest" [(Just 1234567890," and the rest")] *Main> runP number2 "12345678901 and the rest" [(Just (-539222987)," and the rest")] The very same result. Can you please help me understand why I seem not to be able to get the number I'd like to get? As I said, I think I'm missing something that must be pretty obvious, but still I cannot see it! Thanks for your kind attention. Andrea ps: sorry for such a long message. Moreover, here's the code: module Main where import Control.Monad import Data.Char newtype M a = S {unpack :: String -> [(a,String)]} instance Monad M where return a = S $ \s -> [(a,s)] m >>= f = S $ \s -> [(b,z) | (a,y) <- unpack m s, (b,z) <- unpack (f a) y] instance MonadPlus M where mzero = S $ \x -> [] mplus a b = a `bchoice` b bchoice (S m) (S m1) = S $ \s -> case m s of [] -> m1 s other -> other iterateP m = do { a <- m ; b <- iterateP m ; return (a:b) } `mplus` return [] filterP p = S (\xs -> case xs of [] -> [] (x:xs') -> if p x then [(x,xs')] else []) number = do { a <- filterP isDigit ; b <- number ; return (a:b) } `mplus` return [] digitS = do a <- filterP isDigit return a number1 :: M Int number1 = do a <- iterateP digitS return (read a) -- a different approach maybeAdd a b = do x <- a y <- b return (x + y) asNumber :: [Int] -> Maybe Int asNumber [] = Nothing asNumber (x:[]) = Just x asNumber (x:xs) = Just (x * 10 ^ length xs) `maybeAdd` asNumber xs digitI = do a <- filterP isDigit return $ ord a - ord '0' number2 :: M (Maybe Int) number2 = do a <- iterateP digitI return $ asNumber a runP (S f) = f | http://www.haskell.org/pipermail/haskell-cafe/2006-September/018180.html | CC-MAIN-2014-23 | refinedweb | 465 | 66.88 |
Originally posted by Lasse Koskela: To me, a beginning Scala programmer, that stuff is plain unreadable. Function values are great but can be taken too far.
Originally posted by Lasse Koskela:that stuff is plain unreadable.
Originally posted by Garrett Rowe: I must admit, your comment surprised me though. I don't see a lot of difference in readability between defining a method and defining value that is a function.
def f(n: Int): Int = {
n + 1
}
val f: Int => Int = {
n => n + 1
} There's a bit more line noise with the extra =>'s, but there's no difference in the way they are invoked.
One of the things I'm not too sure I like about Scala is that although there are a lot of different ways to do things, there are'nt a lot of *norms*. A Scala programmer doesn't have a lot to go on if they want to write API's that other Scala coders can use comfortably.
Originally posted by Garrett Rowe: Since readability directly maps to maintainability, I'd say that that is a valid concern.[/CODE]
[..]instead the authors made a few extremely useful tools like the iteration methods (each, collect, findAll) and MarkupBuilder and showed the average programmer how much easier it is to code using those tools. | http://www.coderanch.com/t/71/Scala/Stateless-methods-functions | CC-MAIN-2014-15 | refinedweb | 218 | 67.38 |
Bummer! This is just a preview. You need to be signed in with a Treehouse account to view the entire video.
Creating Classes8:57 with Craig Dennis
We will create and use our newly created class.
Explanations
- I am following the contributing guidelines for Android guidelines. The "m" for member prefix, is just a coding style.
- You might not have seen a PEZ Dispenser before. I hope you can experience it someday if you haven't. It's a lot of fun.
- 0:00
Objects in software, allow us to express and
- 0:02
model things that we have and use in real life.
- 0:05
Programmers have discovered that all real world objects share
- 0:08
two important characteristics.
- 0:10
They have state, and behavior.
- 0:13
By creating an object in code that maintains state and exposes behaviour it
- 0:17
allows you to hide how things actually work from the user of your object.
- 0:21
A great example of this is a radio.
- 0:23
It has some state.
- 0:24
Is it on or off?
- 0:26
What station is it on?
- 0:27
And it has some behaviour that it exposes.
- 0:29
You can turn the power on, we can change the station.
- 0:32
How does it actually work?
- 0:33
I have no idea.
- 0:34
It's implementation details are hidden from me.
- 0:37
But its behavior is exposed, and
- 0:38
I can manipulate the state that it wants me to change.
- 0:42
Before we go any deeper, I wanna apologize for what I'm about to do to your brain.
- 0:47
Chances are,
- 0:47
after I introduce this concept to you, you will not be able to stop thinking about
- 0:51
how you would implement everything you see in real life as an object in code.
- 0:56
Like an ear worm, when someone sings.
- 0:58
We built this city.
- 1:00
You're gonna be building an object representation of
- 1:03
every single thing that you see.
- 1:06
Sorry about that.
- 1:07
Okay, so let's explore a real life object together.
- 1:10
How about this Yoda Pez Dispenser right here.
- 1:14
Let's see.
- 1:15
It definitely has some state.
- 1:16
Is it empty?
- 1:17
Nope.
- 1:18
How many Pez are inside?
- 1:20
There's also some behavior, namely its main job.
- 1:23
Dispense.
- 1:25
When we do this, it changes the state of the Pez Dispenser.
- 1:28
There were ten and now there are nine.
- 1:31
And it can also be loaded, which will change its state.
- 1:35
You know, come to think of it, all Pez Dispensers kinda work the same.
- 1:39
They just have different character heads.
- 1:41
If we imagine the factory where these are made, I bet that there's some sort of
- 1:45
master blueprint of Pez Dispensers that is used to create each one of them.
- 1:50
And then it customizes the character head for each one that comes through.
- 1:54
This blueprint used to create objects in Java is called a class.
- 1:59
Could we build something like this blueprint in code and
- 2:01
then create objects from it?
- 2:02
We definitely can.
- 2:03
And it's pretty straightforward.
- 2:05
Let's do just that.
- 2:07
Okay.
- 2:08
So what we'll do is we create a new class and
- 2:10
then we'll use it in a console application.
- 2:12
I've gone ahead and I've built the console application boiler plate for us again.
- 2:16
It's in a file called Example.java.
- 2:18
Let's open that up. [BLANK_AUDIO]
- 2:23
In the last application we built, we used a Java.io console object to take input and
- 2:28
write out to the string.
- 2:30
Well this was new to some students that had explored Java in the past.
- 2:33
And they asked, what's the difference between this and,
- 2:35
what I used in the past which was system.out.
- 2:39
Well console is actually just a convenient wrap around system.out and system.in.
- 2:44
Since we're not going to be taking input,
- 2:45
let's take a look at this common pattern for writing out to the console.
- 2:48
[BLANK_AUDIO]
- 2:51
So System, with a capital S is a class that
- 2:55
exposes a static public field named out.
- 2:59
Out is a print stream,
- 3:00
which exposes some methods that we've seen before in the console object.
- 3:04
So don't worry about that mouthful I just said.
- 3:06
Just know that we can write out to the screen using this.
- 3:09
System.out.printlin.
- 3:12
We are making a new Pez Dispenser.
- 3:18
[BLANK_AUDIO]
- 3:21
Now in the past,
- 3:22
what we were doing when we were using printf, we were using a backslash n.
- 3:26
What print line does or println here.
- 3:29
What that does is it prints a line and automatically puts a slash in at the end.
- 3:34
Okay.
- 3:35
So let's make a new file called PezDispenser.java.
- 3:38
So to make a new file you just right-click over here and choose New File.
- 3:42
And we'll call it PezDispenser.java.
- 3:47
All right. So let's create this class.
- 3:50
When defining a class we wanna talk about the access level.
- 3:53
Who can access this class?
- 3:54
So the way that we do that is with what is called an access level modifier.
- 3:58
So, we're gonna talk about one that's very common, and it's public, and
- 4:02
that means everybody can access this.
- 4:04
We'll dive deeper in to the different access levels.
- 4:06
But for now, let's just use public.
- 4:09
So public and the keyword is class that we're gonna use.
- 4:11
We're building a class, so
- 4:12
we say this is a public class, and the public class's name is PezDispenser.
- 4:19
Note how PezDispenser is using camel case.
- 4:22
But the first character is upper case.
- 4:24
This is very common for defining classes in almost every programming language.
- 4:29
So, then, like you'd assume, we open up our
- 4:32
code block with an open parentheses and then we close our parentheses.
- 4:36
Now, believe it our not, this is actually enough to create the class.
- 4:40
But we should probably add a little more info so
- 4:41
that we can show off that it's working.
- 4:43
Let's add some state.
- 4:44
How about the name of the character who's head's on the dispenser.
- 4:47
So, in order to do that, we'll add a field or a member variable.
- 4:54
And again, just temporarily, let's use the access modifier public.
- 5:00
This'll make sure that everybody who creates this object can see this
- 5:03
member variable.
- 5:05
Okay, so, public and after this it works just like a variable declaration.
- 5:10
So it's a string.
- 5:11
And then we're gonna give it its name.
- 5:13
It's a character name.
- 5:16
And then we're going to say, Yoda.
- 5:19
Now, a common naming prefix that you use for member variables is m.
- 5:24
That way when you look at something you know that it's a member variable.
- 5:29
So we're gonna change that to mCharacterName just like that.
- 5:32
Okay so I'm gonna save this file.
- 5:34
And then let's go use it over here in the example file.
- 5:37
Now because the PezDispenser.java is in the same folder as our example Java file,
- 5:42
and we haven't yet placed this into a package.
- 5:45
Our example program can simply just access the class by using its name.
- 5:49
We'll talk more about packages and importing later, but for
- 5:51
now let's just use our new class.
- 5:52
[BLANK_AUDIO]
- 5:57
Just like every other variable, this is gonna have a type.
- 5:59
And the type is PezDispenser.
- 6:03
And it gets a name and we're gonna go name it dispenser.
- 6:05
And we're gonna make a brand new one of these,
- 6:08
so the keyword that we use is actually new.
- 6:11
We're gonna make a brand new PezDispenser.
- 6:13
And we put these parenthesis here and
- 6:17
we'll get to those later what that means, and end the line.
- 6:20
Remember before when we were using the printf method.
- 6:23
Well the System.out also has a printf method, so let's do that again.
- 6:27
We'll do System.out.printf.
- 6:30
Let's say, The dispenser character is and we'll do a %s and
- 6:35
that's where we'll replace things.
- 6:38
And then, again, we're gonna do the \n for the new line, and we'll do a comma.
- 6:44
I'm gonna drop onto the next line, cause this is getting long.
- 6:47
And we'll say, dispenser.
- 6:48
.
- 6:50
We can access the fields that we expose publicly, mCharacterName.
- 6:54
And again, this is just temporary,
- 6:57
probably would never want to actually expose an m variable.
- 7:00
We'll talk about that soon.
- 7:02
Okay, so let's save this.
- 7:04
And let's go ahead and run this.
- 7:05
So I'm gonna say clear.
- 7:08
And because we're gonna run this a lot,
- 7:09
I'm gonna this command line trick that we do.
- 7:11
I'm gonna say clear the screen and then compile Example.java.
- 7:18
And then, let's run it.
- 7:20
And so, we compile it with Java c and we run it with Java.
- 7:26
And I don't need to put the extension afterwards.
- 7:29
Okay, here we go.
- 7:30
[BLANK_AUDIO]
- 7:32
Great.
- 7:33
So it says, we are making a new Pez Dispenser, and
- 7:36
again, I did the new line because of the print line.
- 7:38
And then the dispenser character is and we did dispenser.mCharacterName and
- 7:42
I replace it there, Yoda.
- 7:45
Excellent.
- 7:46
Did you notice how we didn't have to compile our PezDispenser class,
- 7:49
it automatically happened.
- 7:51
This is looking good.
- 7:52
Now we have a blueprint or
- 7:54
class that we can use to finish modelling out our example.
- 7:58
There are a few bugs in what we're doing right now,
- 7:59
but it's a great starting block.
- 8:00
And we learned about fields and how we access them on newly created objects.
- 8:05
Now in order to hide those implementation details, we're gonna need to pick up
- 8:08
a few new tricks, which we'll get to in the next video.
- 8:12
Now, before you ask,
- 8:13
when will we ever need to create a Pez Dispenser in code in real life?
- 8:17
Well let me answer you with this.
- 8:19
You'd be surprised.
- 8:20
As a developer, your skills are needed by all sorts of industries and markets.
- 8:24
Everyone wants a website.
- 8:26
[LAUGH] In fact, when researching Pez for this course, I found out that there's
- 8:30
actually a new site that's allowing you to 3D print your head onto a Pez Dispenser.
- 8:35
Guess what they have on their website?
- 8:37
A way for you to upload your head and
- 8:38
simulate a Pez Dispenser, just to see what it might look like.
- 8:42
Someone had to write that.
- 8:45
One time while I was doing some consulting work,
- 8:46
I had to write code that simulated a go-kart.
- 8:51
Gives me an idea.
- 8:52
Let's do a quick exercise to check our syntax on creating classes and
- 8:56
then we'll go fix those bugs up. | https://teamtreehouse.com/library/java-objects/meet-objects/creating-classes | CC-MAIN-2016-40 | refinedweb | 2,138 | 84.47 |
sherlynjustus72
Profile
Carb Cycling - Do You Know The Many Names Of The Carb Cycling Diet?
The outcome of all with this particular is that your body will now be trained shed that excessive fat and you can do finally plan the return (or arrival) of your six pack abs. Go jump for joy, then come for you to read outside of.
(image:)
The case is different between a bodybuilder or athlete along with the children fighting epilepsy. Messy has been used into the Pro Shred Keto Pills diet consider about these two years and ending a ketosis diet likely would have extreme effects particularly you should definitely performed precisely. Just like when you started out with the diet, the weaning period also needs associated with support and guidance from the parents. You need to make little one understand that we have going staying changes once again but this time, your child will not get to be able to the ketosis diet. Ask your doctor about 1 of it.
The lifestyles that much of us have can become overwhelming every single. And is certainly very in order to understand let us overcome us from to be able to time and cause us to become derailed on our goals temporarily.
So, Got to as well as beat this thing on my own. The dizzy spells, the panic attacks, the hypoglycemic episodes, the weakness, the fatigue, the shakes, the a pounding heart.and, well, I did!
This doesn't mean go off your lose weight. Instead, increase your calories (no more than 500 calories per day), mainly from carbohydrates provide your system a 'break' from calorie restriction. Pro Shred Keto Review diet facts After the 7-10 day period cut your calories back and pounds loss commence back this. This strategy works well if you've got been dieting for most of the time.
The body is with regards to achieving homeostasis, so what you may need attempt is shake things up and get our systems un-homeostatic (not sure if it is a word). Ideas 4 ways that you can disrupt homeostasis and blast through pounds loss plateau. You aren't expected to do virtually all them instead just find one at at time.
Fat can be a longer term energy source for our bodies that delivers some important nourishment such as omega-3 an indispensable fatty acid for reducing inflammation. The straightforward chia seed provides 1.72 grams of fat per ounce . of. That has more fat per ounce than salmon at 1.68 grams and eggs at 7.82 grams. For people eating a ketogenic, in other words fat burning diet, providing a particularly good supply of bioavailable fat.
Making the switch from carbohydrates being a fuel source to fat as an energy source will not be fun at extremely! You will be tired, cranky and have zero vigour! However, your blood sugar is stabilizing. Again, consult with someone knowledgeable about this diet prior to starting.
The human body can stockpile about 400 grams of glycogen. In larger persons this quantity can go up. In addition to this, for every gram of glycogen accumulated in man's body, 3 grams water are also, kept. Prone to figure it out, this would total up to about 1600 grams (3.5 pounds) of glycogen and water.
Forum Role: Participant
Topics Started: 0
Replies Created: 0 | https://www.ocpsoft.org/support/users/sherlynjustus72/ | CC-MAIN-2021-04 | refinedweb | 563 | 72.87 |
The improve the deployment of the executable jar, we will be running it in a docker container. This does NOT require the jar to be executed as a cron job nor as a Windows scheduled task.
Follow these steps to run your Java process in a Docker container.
Create your executable jar to be ran.
An executable jar can be created any number of ways. This example is a maven project that uses the maven-shade-plugin for packing the executable jar. The pom file below demonstrates how to build an executable jar file with the maven-shade-plugin.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns=" xmlns: <mainClass>ExecuteTimer</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
Note that this is just one way of building an executable jar, but not the only or recommended way.
Create a scheduled task in Java
You can schedule tasks in Java any number of ways. This example will use the TimerTask class.
import java.util.Date; import java.util.TimerTask; public class TimerExample extends TimerTask { private String name; public TimerExample(String n) { this.name = n; } @Override public void run() { System.out.println(Thread.currentThread().getName() + " " + name + " the task has executed successfully " + new Date()); } }
Now execute this run method from within your main method.
import java.util.Timer; public class ExecuteTimer { public static void main(String[] args) { TimerExample te1 = new TimerExample("Task1"); Timer t = new Timer(); t.scheduleAtFixedRate(te1, 0, 1000); } }
Note that in the maven-shade-plugin example above, the ExecuteTimer class is defined as the class having the main method to run.
Create a docker compose file using a Java image
There are a variety of java docker images available. This example will use an amazon corretto image for Java 11.
version: '3.8' services: task-test: image: amazoncorretto:11-alpine3.15 container_name: task-test restart: always volumes: - .:/usr/local/scripts/task-test/ command: java -jar /usr/local/scripts/task-test/target/task-test-1.0-SNAPSHOT.jar
task-test is the name of the service being started.
image is the image to pull from the docker repository at
container_name is the custom name you are giving the container. We recommend setting a container name so that you can reference it by a known name if needed.
restart: always means to restart the container any time it does unless it was explicitly killed. If the server is restarted, this docker container will also restart which is almost always the desired behavior of a scheduled task.
volumes in this example is mounting the project directory to a location on the server. The project directory contains the executable jar which will be ran using the next option.
command is the command to execute the Java process in Docker.
Conclusion – Java process in Docker
In conclusion, after running
docker-compose up the java process will now run as scheduled. To kill the process, just kill the docker container with
docker kill task-test.
Let us know in the comments if you have any questions or would like us to provide more examples on how to run a Java process in a docker container.
Read more of our posts on Java, Docker, and security centric programming. | https://www.misterpki.com/java-process-in-docker/ | CC-MAIN-2022-21 | refinedweb | 534 | 56.66 |
Basics of Arrays for C Programming
An array in the C programming language is series of variables of the same type: a dozen int variables, two or three double variables, or a string of char variables. The array doesn’t contain all the same values. No, it’s more like a series of cubbyholes into which you stick different values.
An array is declared like any other variable. It’s given a type and a name and then also a set of square brackets. The following statement declares the highscore array:
int highscore[];
This declaration is incomplete; the compiler doesn’t yet know how many items, or elements, are in the array. So if the highscore array were to hold three elements, it would be declared like this:
int highscore[3];
This array contains three elements, each of them its own int value. The elements are accessed like this:
highscore[0] = 750; highscore[1] = 699; highscore[2] = 675;
An array element is referenced by its index number in square brackets. The first item is index 0, which is something you have to remember. In C, you start counting at 0, which has its advantages, so don’t think it’s stupid.
In the preceding example, the first array element, highscore[0], is assigned the value 750; the second element, 699; and the third, 675.
After initialization, an array variable is used like any other variable in your code:
var = highscore[0];
This statement stores the value of array element highscore[0] to variable var. If highscore[0] is equal to 750, var is equal to 750 after the statement executes.
HIGH SCORES, THE AWFUL VERSION
#include <stdio.h> int main() { int highscore1,highscore2,highscore3; printf("Your highest score: "); scanf("%d",&highscore1); printf("Your second highest score: "); scanf("%d",&highscore2); printf("Your third highest score: "); scanf("%d",&highscore3); puts("Here are your high scores"); printf("#1 %dn",highscore1); printf("#2 %dn",highscore2); printf("#3 %dn",highscore3); return(0); }
Exercise 1: Rewrite the source code from High Scores, the Awful Version, adding a fourth high score and using an array — but keep in mind that your array holds four values, not three.
Many solutions exist for Exercise 1. The brute-force solution has you stuffing each array variable individually, line after line, similar to the source code in High Scores, the Awful Version. A better, more insightful solution is offered in High Scores, a Better Version.
HIGH SCORES, A BETTER VERSION
#include <stdio.h> int main() { int highscore[4]; int x; for(x=0;x<4;x++) { printf("Your #%d score: ",x+1); scanf("%d",&highscore[x]); } puts("Here are your high scores"); for(x=0;x<4;x++) printf("#%d %dn",x+1,highscore[x]); return(0); }
Most of the code from High Scores, a Better Version should be familiar to you, albeit the new array notation. The x+1 arguments in the printf() statements (Lines 10 and 16) allow you to use the x variable in the loop but display its value starting with 1 instead of 0. Although C likes to start numbering at 0, humans still prefer starting at 1.
Exercise 2: Type the source code from High Scores, a Better Version into your editor and build a new project. Run it.
Though the program’s output is pretty much the same as the output in Exercise 1, the method is far more efficient, as proven by working Exercise 3:
Exercise 3: Modify the source code from High Scores, a Better Version so that the top ten scores are input and displayed.
Imagine how you’d have to code the answer to Exercise 3 if you chose not to use arrays!
The first element of an array is 0.
When declaring an array, use the full number of elements, such as 10 for ten elements. Even though the elements are indexed from 0 through 9, you still must specify 10 when declaring the array’s size. | https://www.dummies.com/programming/c/basics-of-arrays-for-c-programming/ | CC-MAIN-2019-39 | refinedweb | 658 | 66.78 |
User talk:Romartus
Romartus from Uncyclopedia. --Romartus (talk) 09:57, 28 December 2012 (UTC)
Greetings, Romartus, and thank you for joining the wiki of macabre funeral directors! I hope you enjoy your time here.
Radioactive afikomen Please ignore all my awful pre-2014 comments. 09:59, 28 December 2012 (UTC)
- Salve..as they say in Rome, and I guess, The Vatican. --Romartus (talk) 10:09, 28 December 2012 (UTC)
- It's been years since I've talked to an Uncyclopedian. How are things over at the unwiki? Are Zombiebaron and Skullthumper still around?
Radioactive afikomen Please ignore all my awful pre-2014 comments. 10:19, 28 December 2012 (UTC)
- ZB is there, now a bureaucrat. Skullthumper is elsewhere, sometimes drops in. I have been active on Uncyclopedia for the last four years. I did create an account at RW years ago but had forgotten the n&p. It was only when I saw that RW had no separate article about Uncyclopedia that I decided to create an account here. Then I noticed some of your other articles weren't so clear either (Fundamentalism)...so may contribute real information here in future. --Romartus (talk) 10:24, 28 December 2012 (UTC)
- ZB's a bureaucrat? Good for them. I was on Uncyc for most of 2007 (geez, I remember when Electrified Mocha Chinchilla was a newbie), but faded away as I focused on this site.
- I eagerly await your future contributions.
Radioactive afikomen Please ignore all my awful pre-2014 comments. 10:32, 28 December 2012 (UTC)
Your signature[edit]
...was in the wrong namespace. I've moved it. You may need to modify your settings. --ZooGuard (talk) 12:22, 28 December 2012 . — Palaeonictis Fossil beds 15:28, 31 January 2019 (UTC)
- Thanks, that's a nice surprise. I wasn't expecting that. This is to encourage me to lurk+contribute around a bit more at Rationalwiki. I was thinking about it as this website chimes with my overall world view anyway. :) --Romartus (talk) 15:35, 31 January 2019 (UTC)
- I`m surprised it wasn't added earlier TBH. — Palaeonictis Fossil beds 15:41, 31 January 2019 (UTC)
Test[edit]
--
RomArtus*Imperator ITRA (Orate) ® 14:23, 20 February 2021 (UTC) | https://rationalwiki.org/wiki/User_talk:Romartus | CC-MAIN-2021-21 | refinedweb | 368 | 69.58 |
Tutorial 10: Email Yourself your IP Address
You have your Raspberry Pi web server online and now it is secured. Now how do you find it?
Most websites you visit have a static IP address - that is: an IP address that does not change. So when you type in "google.com" you are actually visiting "64.233.169.138", the address of google.com. Static IP addresses are not offered by default by ISPs; instead they assign you a changing or dynamic IP address so you can navigate online. This dynamic IP address of yours may last a week, a day, or even just an hour. This makes it difficult to visit the server you're trying to host on your Pi!
In this tutorial I show you how to write a Python script that automatically checks your IP address and then sends the IP address to a gmail email account. Why? Well, regardless of where you are you will be able to access your email. If you have the current dynamic home IP address you will be able to access your server! A simple work around that won't cost you anything.
This tutorial is a little older (published in 2015!). The main principles are still relevant, so I haven't needed to update this lesson.
DIFFICULTY
LINUX UNDERSTANDING
COMPUTER FAMILIARITY
PYTHON PROGRAMMING
from urllib.request import urlopen import re import smtplib import sm # Setup our login credentials from_address = '' to_address = '' subject = 'Pi IP' username = '' password = '' # Setup where we will get our IP address url = '' print ("Our chosen IP address service is ", url) # Open up the url, then read the contents, and take away our IP address request = urlopen(url).read().decode('utf-8') # We extract the IP address only ourIP = re.findall("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", request) ourIP = str(ourIP) print ("Our IP address is: ", ourIP) def send_email(ourIP): # Body of the email body_text = ourIP + ' is our PlayPi IP address' msg = '\r\n'.join(['To: %s' % to_address, 'From: %s' % from_address, 'Subject: %s' % subject, '', body_text]) # Actually send the email! server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() # Our security for transmission of credentials server.login(username,password) server.sendmail(from_address, to_address, msg) server.quit() print ("Our email has been sent!") # Open up previous IP address (last_ip.txt) and extract contents with open('/home/pi/ipemail/last_ip.txt', 'rt') as last_ip: last_ip = last_ip.read() # Read the text file # Check to see if our IP address has really changed if last_ip == ourIP: print("Our IP address has not changed.") else: print ("We have a new IP address.") with open('/home/pi/ipemail/last_ip.txt', 'wt') as last_ip: last_ip.write(ourIP) print ("We have written the new IP address to the text file.") send_email(ourIP) | http://thezanshow.com/electronics-tutorials/raspberry-pi/tutorial-10 | CC-MAIN-2019-39 | refinedweb | 461 | 66.33 |
Currently, SVG defines several the use of the href attribute on several different elements to use the XLink namespace, for both "incoming" (references) and "outgoing" (hyperlinks) links.
The SVG WG is considering allowing the href attribute to be used without the xlink: prefix, and possibly to allow incoming references to use the src attribute, for syntactic similarity to HTML, for SVG 2.0 (this does not affect SVG 1.1).
If this is going to be done, the time to do it is now, while SVG is not yet ubiquitous.
Resolution
The current plan for handling this in SVG 2.0 is to allow the href attribute to be used without the xlink: prefix anywhere the xlink:href attribute is allowed. The href attribute (which we believe will be used more going forward) will take precedence over the xlink:href attribute if both are present and there is a conflict. This applies both to attribute values and to the DOM property getter/setter, for parsing and for DOM operations.
- The href attribute takes precedence over the xlink:href attribute
- If there is only an href attribute, the resulting property will have the value of the href attribute
- If there is only an xlink:href attribute, the resulting property will have the value of the xlink:href attribute
- If there is both an xlink:href attribute and an href attribute, there is a single resulting href property, with the value of the href attribute
- When serialized, all attribute are retained as set in the original document
Serialization
For serialization, user agents should use href without the XLink namespace declaration or prefix.
Authoring Tools
Authoring tools should should output href without the XLink namespace declaration or prefix.
All user agents must support both 'xlink:href and href as input.
We are interested in hearing feedback for this idea.
Some background and factors for consideration are listed below.
Next Steps
The src attribute has different options, which are not yet resolved:
- The use of the src attribute is not defined (that is, it does nothing)
- The use of the src attribute changes the behavior of the element
Issues
xlink:href
The use of XLink-namespaced attributes in SVG is often challenging to content creators new to the language and to XML namespaces. In particular:
- the XLink declaration may be accidentally omitted, especially in copy-paste cases, making the XLink prefix (normally "xlink:") unbound, causing an error.
- the XLink declaration may have a typo (the correct declaration looks like this: xmlns:xlink=""), causing an error.
- setting the xlink:href attribute via script often trips people up; here are some typical mistakes (in this case, setting the <image> attribute, but the same applies for getting and setting the attributes on <use>, <a>, etc.):
- el.setAttribute( "href", "foo.png" );
- el.setAttribute( "xlink:href", "foo.png" );
- el.setAttributeNS( "xlink:href", "foo.png" );
- el.setAttributeNS( "xlink", "href", "foo.png" );
- el.setAttributeNS( xlink, "href", "foo.png" ); (where there is no JS variable called "xlink")
- el.setAttributeNS( "", "href", "foo.png" ); (Correct)
- var xlinkns = ""; el.setAttributeNS( xlinkns, "href", "foo.png" ); (Correct)
HTML vs SVG image elements
The SVG <image> element has several differences with the HTML <img> element, which can trip up authors coming from HTML to SVG:
- <img> references images using the src attribute, while SVG <image> uses the href attribute (in the XLink namespace, currently)
- The SVG <image> element must be closed, either with a slash at the end of the element, or with a closing tag, while HTML <img> should not be closed
- The SVG <image> element may contain child content, while HTML <img> cannot
- The HTML <img> element defaults to the native dimensions of the referenced raster image, while SVG <image> defaults to a width and height of 0, and must be explicitly set to specific dimensions.
Factors for consideration
href and xlink:href on same element, and error handling
If SVG allows the href attribute without the XLink namespace prefix, authors may wish to supply the same attribute in the XLink namespace, for backwards compatibility with older browsers, plugins, and authoring tools. This leads to the question of what a user agent should do if both attributes are present, especially if their values are not the same:
- which attribute should take precedence, href or xlink:href?
- what should be the namespace of the .href property on the element's DOM interface?
- what should happen when one or the other is set by script or animated?
- should the value be "mirrored" among both of them?
- should there be a difference between using the .href property and setAttribute/NS?
src on <image>
The SVG WG has discussed whether to allow the SVG <image> element to allow the use of src in addition to href, for syntactic similarity with the HTML <img> element.
However, this would raise several new problems:
- how does src work with respect to href or xlink:href
- which attribute value takes precedence?
- what is the name of the DOM attribute?
- if the DOM attribute is set for one, is is changed for all?
- will this confuse authors who expect <svg:image> and <html:img> to work the same?
After discussion, the SVG WG believes that, especially in light of the differences between the SVG and HTML elements, it is better at this point to be self-consistent within SVG in the use of href as the single attribute for both inbound and outbound links, making it easier to learn and more intuitive to use.
Note: HTML is not universally consistent in distinguishing between inbound (or "content replacement") and outbound links in its use of attribute names, so there is not a single precedent:
- <a> uses href (outbound)
- <link> uses href (inbound and outbound)
- <img> uses src (inbound)
- <iframe> uses src (inbound)
- <script> uses src (inbound?)
- <embed> uses src (inbound)
- <object> uses data (inbound)
- <applet> uses code (inbound)
Discussions
Henri Sivonen: | https://www.w3.org/Graphics/SVG/WG/wiki/index.php?title=Href&mobileaction=toggle_view_mobile | CC-MAIN-2015-27 | refinedweb | 975 | 57.91 |
30 September 2010 18:20 [Source: ICIS news]
TORONTO (ICIS)--?xml:namespace>
Toronto-based CIBC bank said it expected
However, despite the softer growth outlook, the government should stick with its plans for fiscal tightening, at least for the time being, said CIBC chief economist Avery Shenfeld.
“Only if the Bank of Canada [the country's central bank] were forced to take rates back to zero would it be appropriate to postpone a much-needed, if gradual, path back to fiscal rectitude," he said.
“At this point,
Canada had started raising interest rates, presumably to prevent growth from being so brisk that inflation broke out, and as such it made no sense “to be stepping on the monetary policy brake” while at the same time providing fiscal stimulus, he said.
CIBC’s forecast came as federal statistics agency Statistics Canada said that the country’s GDP fell 0.1% in July from June - the first decline in 11 months.
Manufacturing, retail and wholesale, and construction and forestry all posted decreases.
Craig Alexander, chief economist for Toronto-based TD Bank, said the latest data suggested a sharper-than-expected deceleration in GDP growth in the third quarter.
But like CIBC, Alexander said even though growth would be slower, new fiscal stimulus packages were not needed. | http://www.icis.com/Articles/2010/09/30/9397817/canadas-economic-growth-to-slow-sharply-next-year.html | CC-MAIN-2014-35 | refinedweb | 214 | 57.2 |
Difference between revisions of "MoDisco/MDT Migration"
Latest revision as of 11:28, 7 July 2010
Contents
- 1 Overview
- 2 Possible solutions
- 2.1 duplicate
- 2.2 delegate
- 3 Coding rules to respect to avoid such problems in the future
Overview
MoDisco moved from Modeling/GMT to Modeling/MDT (see this bug). As part of this migration, we should have renamed all Java packages from
org.eclipse.gmt.modisco.* to
org.eclipse.modisco.*.
Unfortunately, this means breaking every existing API, which is in contradiction with the API policy that was established for MoDisco. Among other things, this policy states that API cannot be broken without notifying adopters at least one year before that.
This means for MoDisco that we cannot just rename the Java packages, because we still have to support the API that existed in the
org.eclipse.gmt.modisco.* namespace.
To reconcile these two contradicting requirements, we explored several solutions, which are presented below.
Possible solutions
duplicate. The problem with this solution is for adopters that rely on plug-ins with the old namespace, but that want to start developing plug-ins for the latest version of MoDisco. This would be an all-or-nothing solution: either migrate everything to the latest version of MoDisco, or develop new projects with the old version.
Another solution would be to create a "backward compatibility SDK" (with GMT packages) that delegates to the MDT version of MoDisco. The idea looks straightforward: every call to a GMT API are forwarded to the corresponding MDT API.
This could be automated through a refactoring that would create proxies (in the GMT namespace) for each MoDisco API, that delegate to the corresponding methods with the same name, but in the
org.eclipse.modisco namespace.
This would look like this:
A proxy knows its delegate, but a delegate doesn't know its proxy. But we need this information to be able to find the proxy that was associated with an element that is returned from a method. So, we have to keep this information somewhere. For example in a HashMap:
So far, so good. But in practice, we discovered that this is not always so simple, and there are many roadblocks that prevent this solution from working 100%. Moreover, even getting it to work only for common cases that can work is far from trivial, and requires a fair amount of work.
Difficulties
- For methods that return a collection (list, map, queue, set, etc.), the user can then proceed to call methods on this collection to modify it. And we would expect the underlying collection to be modified accordingly. So, we can't just get away with copying the collection when making a proxy for it. We have to provide a collection proxy that delegates every operation to its delegate collection. And this, for each and every collection that is used in MoDisco (lists, sets, maps, etc.)
- Similarly, for collections that are passed as parameters to methods that modify it, we must also create a proxy collection, in the other direction this time.
- A sub-class can call protected methods on its super-class. But since these methods are protected, they can't normally be called from the proxy (this can be solved by the use of reflection)
- If the super-class of a MoDisco class is not itself a MoDisco class, then we won't have a proxy for it. This means that method calls won't execute on the right object. So, we have to create a proxy method for every method, including those inherited from super-classes. This is bad for memory use, and we risk PermGen space exceptions.
Can not be handled
Public fields
We can't have proxies for public fields, so they wouldn't be handled at all.
Number of
Implicit knowledge - Generics
Of the return type is
List<EObject> for example, they we will create a proxy for
List. But the user can cast this to
BasicEList<EObject>, knowing that the collection will always be this type. This is bad practice, but it happens anyway, and we wouldn't be able to handle this kind of uses.
Number of occurrences of the case in MoDisco source code: <to be counted>
Implicit knowledge - not well typed elements
If a method returns something like
Object, we don't know (statically) whether we should create a proxy for it. For example, when using the
IAdaptable interface, the method
Object getAdapter(Class adapter) always returns an Object, but since by contract this Object is supposed to be of the type that is passed as a parameter, the user will cast it right away. And that would fail because we haven't made a proxy for this. (In fact, this is even worse, since
getAdapter would be passed a
Class in the GMT namespace, which it wouldn't know about).
Number of occurrences of the case in MoDisco source code: <to be counted>
Arrays
We can't create a proxy for an array, so we have to return a copy of it with the other type. So, if a method returns an array and the user modifies this array, these modifications won't be propagated to the right array.
Number of occurrences of the case in MoDisco source code: 85
Equality test
As seen above, MoDisco objects with the
org.eclipse.modisco namespace can leak through (under the cover of an
Object for example). If the user uses the
== comparison operator, s/he will get the wrong result when comparing a proxy with an original MoDisco element.
Number of occurrences of the case in MoDisco source code: 12215
non-MoDisco code that returns MoDisco objects
For example, a user who wants to work with the ModelBrowser can use an Eclipse API that will return an instance of
EcoreBrowser from the
org.eclipse.modisco namespace, and there is nothing we can do to substitute it with a proxy:
IEditorPart editor = IDE.openEditor(page, file, EcoreBrowser.EDITOR_ID); EcoreBrowser browser = (EcoreBrowser) editor; // this will fail!!!
Number of occurrences of the problem cannot be determined because this problem is located in non-MoDisco code. | http://wiki.eclipse.org/index.php?title=MoDisco/MDT_Migration&diff=210631&oldid=207339 | CC-MAIN-2015-40 | refinedweb | 1,016 | 60.35 |
Struts2 - Hello World
I have been trying for some days to get the "standard" example (varying flavours) to work. The error that keeps on appearing is "There is no Action mapped for namespace / and action name HelloStruts. - [unknown location]".
I have tried many combinations, the only thing that seems sure is that no notice is taken of the struts.xml file, in the WEB-INF dir and in the WEB-INF/lib dir. I have made changes to this to inject errors that have not been noticed.
If there is someone interested out there I can provide more detailed information but the bet I am making is that someone has the quick and easy answer. Of course I may be wrong but this thing should work easily in a compliant web server?
This is beginning to drive me crazy.......... So any help will be appreciated.
JohnR | http://www.java-index.com/java-technologies-archive/519/application-servers-5194545.shtm | crawl-001 | refinedweb | 146 | 72.36 |
IRC log of tagmem on 2011-06-07
Timestamps are in UTC.
01:26:47 [JeniT]
JeniT has joined #tagmem
02:19:31 [noah]
noah has joined #tagmem
03:21:51 [timbl]
timbl has joined #tagmem
07:00:45 [Bernard]
Bernard has joined #tagmem
13:02:30 [RRSAgent]
RRSAgent has joined #tagmem
13:02:30 [RRSAgent]
logging to
13:02:36 [Yves]
Scribe: Yves
13:02:38 [Zakim]
Zakim has joined #tagmem
13:02:57 [ht]
ht has joined #tagmem
13:03:31 [masinter]
masinter has joined #tagmem
13:04:36 [Ashok]
Ashok has joined #tagmem
13:04:39 [timbl]
timbl has joined #tagmem
13:05:29 [Yves]
Topic: Fragment ID Semantics
13:06:04 [Yves]
13:06:47 [noah]
q+
13:06:51 [noah]
q-
13:07:39 [Yves]
Jeni describes the goal of the session
13:08:59 [Yves]
rfc3986 describe fragments and how they relates to meia types, AWWW talks also about fragment and conneg
13:09:38 [Yves]
3023bis draft describe that fragments MUST be interpreted per XPointer spec
13:10:17 [Yves]
- hashbangs and conflict with HTML/XHTML media type definitions
13:11:40 [Yves]
Larry: HTML5 definition contains new definition for fragments
13:12:31 [masinter]
s\for fragments\for text/html type\
13:12:46 [Yves]
Jeni: media fragment define fragment syntax, but SVG can't use it because of rfc3023bis rules
13:13:09 [masinter]
suggest looking at some other media type definitions with fragment identifiers for completeness and additional constraints
13:13:23 [Yves]
In SemWeb fragments can describe unconstrained things
13:13:57 [Yves]
which is an issue for the application/rdf+xml media type
13:15:25 [masinter]
think there were proposals for letting fragment identifiers to depend on the scheme as well as the media type, especially for streaming protocols
13:15:44 [Yves]
RDFa core is a way to add RDF in XML documents, leading to situations where fragments won't necessarily identify parts of the document
13:16:43 [Yves]
jar: we should need coordination with 3023bis for the RDFa core case.
13:17:51 [Yves]
jar: when you have RDFa that identify endpoints that may be fragments of the XML document
13:18:15 [noah]
(logging earlier discussion)
13:18:39 [Yves]
Jeni: new media type for other RDF serialization are silent on fragments
13:18:50 [noah]
NM: Does anyone have a formal action to follow up on "agreement" with 3023bis editors regarding changes for fragid and generic processing?
13:19:20 [noah]
HT: I informally track 3023bis progress (Henry later clarified in private communication that there is no formal action for his tracking)
13:19:34 [noah]
JAR: Let's do this at the end of this session.
13:19:46 [noah]
NM: OK, as long as we don't forget to get a formal action.
13:21:06 [Yves]
Jeni: first point is about SVG. Per media type definition, it has to use XPointer for its fragment identifier, however mediafragments describe ways of identifying part of an image => clash
13:22:11 [Yves]
Noah: we have two level of genericity there, the +xml and in media fragment it is about the image/ part
13:23:01 [Yves]
for application/svg+xml it is covered by 3023bis only
13:23:24 [masinter]
i think the media fragment draft is inconsistent with other specifications
13:23:42 [Yves]
13:24:08 [jar]
13:24:35 [Yves]
links to image/svg+xml
13:26:07 [ht]
13:26:18 [Yves]
ht: from 3023bis image/svg+xml is covered by the +xml
13:26:59 [Yves]
dka: as an user, you will use the kind of fragment you need to idenfify part of XML or part of the image
13:27:44 [Yves]
ht: it is entirely fine to have tow layer and be able to address each layer that are only disambiguated by use.
13:29:01 [masinter]
s/tow/two/
13:29:17 [Ashok]
s/tow layer/two layers/
13:29:46 [masinter]
s/two layer /two layers /
13:29:47 [Yves]
ht: good practise is "if you use XML representation, it make sense to use a +xml media type and reference bits of XML has XML" and have a syntax to do a non overlapping identification based on the media type
13:30:01 [jar]
ht: Two modes of interpretation, over nonoverlapping fragid syntaxes
13:30:11 [Yves]
noah: there is an issue that people want to say 1/ it's an image, 2/ it's XML 3, it's SVG
13:31:21 [Yves]
ht: issue with application/rdf+xml is that there is syntax overlapping between the RDF and the XML cases
13:32:01 [masinter]
things are inconsistent (a) what are the possibilities and (b) what specs would have to change
13:32:07 [Yves]
timbl: SVG also have their viewport syntax
13:32:18 [Yves]
Jeni: it is expressed as valid Xpointer syntax
13:32:51 [masinter]
discussion about how SVG uses an xpointer extension
13:33:01 [noah]
YL: What if I'm an Xinclude processor processing an image/svg+xml
13:33:44 [masinter]
could someone explain the xinclude/fragid connection?
13:33:45 [jar]
RDF/XML gives a meaning to id="foo" ...
13:35:00 [ht]
13:36:53 [Yves]
ht: the 3023bis spec says "you should a +xml media type and the consequences are those..." for XML content
13:38:38 [masinter]
thinking about the +json convention as another case
13:39:32 [masinter]
((yves asking about whether generic processers come across SVG fragment which isn't valid XPointer))
13:39:48 [Yves]
timbl: is there a way, if you have an id to make it explicitely clear that it's a Xpointer ID and not 'foo'
13:39:57 [Yves]
ht: yes, but nobody does that
13:40:27 [Yves]
timbl: so can you enforce non-overlapping by forbidding the use of bare names for XML content when you mean xpointer id?
13:41:14 [Yves]
ht: there are lots of pointers, so doing so would be very difficult
13:42:12 [masinter]
are there any other cases of inconsistencies between the generic URI/MIME etc. approaches and the specific case
13:42:25 [Yves]
ht: people want sometimes to point to XML parts, sometime to media-specific fragments (like SVG viewport)
13:42:45 [noah]
Time check: 30 mins, hard stop. We need some time for wrapup and actions.
13:42:47 [masinter]
text/* vs. text/html and charset, EOL, line length limits
13:43:17 [jar]
conneg between python and common lisp?
13:44:32 [Yves]
jeni: we are in agreement that there is an issue with the wording of 3023bis that makes it stricter than needed the fragment processing, and it should talk about non overlapping syntax instead
13:44:57 [Yves]
larry: issue is that there are documents who are saying confilcting things and they all need to be fixed
13:45:12 [Yves]
another issue is text/* and defaut charset
13:46:21 [Yves]
jeni: what can we learn from other conflicts?
13:46:59 [jar]
RDF id="foo" is part of the reification feature, and the RDF WG charter says "Deprecate some RDF features (e.g., reification...)"
13:47:01 [Yves]
larry: "stuff happens", we can either document inconsitencies, try to fix the media type definitions...
13:47:36 [Yves]
noah: one think we can do is alert for future media type definition
13:47:39 [jar]
well... maybe ... id= is used in 2 ways ... long story
13:48:07 [Yves]
for the RDF case we can document the breakage
13:48:31 [Yves]
timbl: there is real damage that needs to be fixed, when you have a mixture of RDFa and anchors
13:48:35 [masinter]
i want to make a case for not trying to fix fragment identifiers
13:48:44 [Yves]
s/RDFa/XML and RDFa/
13:49:12 [masinter]
because fragment identifiers have such difficulty anyway, e.g., with non-ascii characters and IRI of fragments
13:49:39 [Yves]
timbl: it wold be tempting for an browser implementation or an RDF implementation to pre-suppose things about fragments based on their understanding of it
13:49:44 [Yves]
s/it/them/
13:49:50 [masinter]
encourage people not to use URIs with fragments to identify components, and instead use some other syntax, e.g., (content + xpointer) or (content + time syntax)
13:50:47 [Yves]
jar: three cases, fragments that may have different meaning, fragments that belong to disjoint syntax spaces
13:51:00 [Yves]
s/three/two/
13:51:22 [OKolkman]
OKolkman has joined #tagmem
13:51:28 [Yves]
there is a use case to have fragments that can be understood in two different ways _on purpose_
13:52:10 [Yves]
jeni: when he has an URI in #foo, what is meant?
13:52:15 [Yves]
jar: it depends on the processor
13:52:40 [Yves]
larry: would it be ok to warn people about using fragment identifier ?
13:53:04 [jar]
warn people *against* using fragids
13:53:09 [jar]
all sorts of problems
13:53:35 [noah]
NM: +1 to LM, with a big caveat. 10 years ago, he would have been exactly right. The RDF train, and many others, have long since left the station.
13:54:07 [Yves]
larry: issue with fragment microformats, i18n issues etc...
13:54:17 [jar]
pain from having to shove multiple semantics into narrow pipe of #
13:54:17 [Yves]
jeni: we have to live with fragments
13:55:10 [Yves]
timbl: is the proposal to have another attribute in html or xml to have a kind of fragment? How can you bookmark that?
13:55:38 [jar]
why would a bookmark have to be only a raw URI?
13:55:47 [jar]
s/why would/masinter: why would/
13:55:48 [Yves]
timbl: awww says that you should identify things using URIs
13:56:13 [Yves]
ashok: one solution would be to say "don't use generic media types definitions"
13:56:48 [Yves]
noah: our first resolution was to remove the genericity part, but the feedback from the XML community is that the genericity part was the important thing
13:56:54 [masinter]
you SHOULD identify resources with URIs, not clear it says you SHOULD identify fragments with URIs too
13:57:21 [jar]
(my 3 cases above: 1. fragids can have different kinds of meaning in disjoint syntactic spaces, 2. fragids can have different meanings for different ids, 3. single fragid can have multiple meanings depending on processor)
13:57:32 [jar]
Manu is for #3
13:57:45 [Yves]
13:57:50 [jar]
HT: SVG would be fine with #2
13:57:54 [Yves]
svgview fragments
13:58:00 [Yves]
generic XML
13:58:28 [Yves]
ht: SVGView is not overlapping and is application specific syntax
13:58:28 [masinter]
new URI scheme media-fragment: which uses some other character than #
13:59:24 [Yves]
media fragment mandates the use of '=' which is not an allowed character in #1, so we can tell by inspection the kind of processing that should occur
14:00:00 [Yves]
larry: SVG can have script, so fragments identifying script state
14:00:09 [jar]
masinter: Don't forget the scripting case. Maybe an SVG hosted script can take fragid as a parameter
14:00:28 [masinter]
((someone with camera take picture of board?))
14:01:02 [Yves]
timbl: RDFa can be embedded in SVG as well
14:01:32 [jar]
timbl: Anchors, RDFa, and scripts all use the ncname syntactic space
14:02:46 [jar]
timbl: How about if script parameters are always distinguished so they're in a disjoint syntactic space
14:03:47 [masinter]
compound document is a separate issue
14:04:09 [jar]
yves: We're getting into compound document issue - multiple kinds of content in one document - and that's a different issue
14:05:03 [jar]
timbl: The compound document situation is the core problem
14:05:15 [masinter]
what about IRI issues of fragments, ID with %xx in it cannot be referenced?
14:05:54 [Bernard]
Bernard has joined #tagmem
14:06:24 [Yves]
ht: the RDFa case and script case is generic, while SVG case is about what the media type definition says
14:07:36 [Yves]
noah: we spent time to talk about compound documents, here it seems that we are diving on identification of those documents
14:08:04 [Yves]
jeni: what are the next steps then?
14:09:06 [noah]
ACTION-509?
14:09:06 [trackbot]
ACTION-509 -- Jonathan Rees to communicate with RDFa WG regarding documenting the fragid / media type issue -- due 2011-06-15 -- OPEN
14:09:06 [trackbot]
14:09:12 [noah]
ACTION-543?
14:09:12 [trackbot]
ACTION-543 -- Jeni Tennison to propose addition to MIME/Web draft to discuss sem-web use of fragids not grounded in media type -- due 2011-06-15 -- OPEN
14:09:12 [trackbot]
14:09:26 [Yves]
timbl: should media fragment use Xpointer syntax?
14:09:34 [Yves]
to reduce the syntax spaces
14:10:55 [masinter]
i think this belongs in a URI/IRI spec update
14:11:17 [Yves]
ht: wrt 3023bis, it is entirely possible that we would need something new in the future, so there are nothing we agreed on that we should require from the editors
14:11:34 [noah]
. ACTION Henry to track fragid issues in 3023bis, report to TAG and/or communicate with 3023bis editors as appropriate
14:11:42 [masinter]
i have some new information
14:11:51 [noah]
ACTION Henry to track fragid issues in 3023bis, report to TAG and/or communicate with 3023bis editors as appropriate
14:11:51 [trackbot]
Created ACTION-564 - Track fragid issues in 3023bis, report to TAG and/or communicate with 3023bis editors as appropriate [on Henry Thompson - due 2011-06-14].
14:12:24 [noah]
IAB folks: we will break at the quarter hour and start dialing in
14:12:27 [Yves]
Jeni: wrt 543 my text is about describing the issues, not about solving it
14:12:34 [noah]
3 mins
14:13:48 [noah]
ACTION-543?
14:13:48 [trackbot]
ACTION-543 -- Jeni Tennison to propose addition to MIME/Web draft to discuss sem-web use of fragids not grounded in media type -- due 2011-06-15 -- OPEN
14:13:48 [trackbot]
14:18:32 [jar]
Group decision to table discussion at point where Larry started talking about how MIME & Web doc is progressing.
14:19:02 [jar]
Will resume later in this meeting.
14:20:57 [Zakim]
Zakim has joined #tagmem
14:21:36 [Zakim]
TAG_f2f(IABTAG)10:00AM has now started
14:21:43 [Zakim]
+ +1.617.715.aaaa
14:21:49 [ht]
IAB guests, 422824 is the code you need to enter the call
14:22:26 [noah]
We are dialed, but on break. Will be ready for start at the half hour
14:23:17 [masinter`]
masinter` has joined #tagmem
14:23:36 [masinter]
masinter has joined #tagmem
14:25:11 [masinter]
zakim, who's here
14:25:11 [Zakim]
masinter, you need to end that query with '?'
14:25:14 [masinter]
zakim, who's here?
14:25:14 [Zakim]
On the phone I see TAG
14:25:15 [Zakim]
TAG has JeniT, ht, DKA, Yves, Ashok, TimBL, Larry, JAR, NoahM
14:25:17 [Zakim]
On IRC I see masinter, Zakim, OKolkman, timbl, Ashok, ht, RRSAgent, DKA, JeniT, noah, jar, Norm, plinss_, Yves, trackbot
14:27:13 [Zakim]
+ +31.20.750.aabb
14:27:44 [ht]
zakim, aabb is Okolkman
14:27:44 [Zakim]
+Okolkman; got it
14:27:49 [OKolkman]
Exactly
14:28:07 [masinter]
please speak so we can hear your volume, we're not hearing anything now
14:28:15 [OKolkman]
Do I need to speak?
14:28:27 [noah]
It would be helpful if you spoke.
14:29:04 [Zakim]
+[Microsoft]
14:29:19 [Zakim]
+ +1.415.738.aacc
14:29:33 [ht]
zakim, Microsoft is Bernard
14:29:33 [Zakim]
+Bernard; got it
14:30:14 [Bernard]
Bernard has joined #tagmem
14:30:27 [OKolkman]
It is Olaf, not Olafur...
14:30:29 [Zakim]
+ +1.214.755.aadd
14:30:43 [ht]
zakim, 415 is DStreet
14:30:43 [Zakim]
sorry, ht, I do not recognize a party named '415'
14:31:12 [ht]
zakim, aadd is SDawkins
14:31:12 [Zakim]
+SDawkins; got it
14:31:18 [dowstreet]
dowstreet has joined #tagmem
14:31:33 [Zakim]
+ +1.858.750.aaee
14:31:36 [Zakim]
+ +1.510.386.aaff
14:31:44 [ht]
zakim, DStreet is dowstreet
14:31:44 [Zakim]
+dowstreet; got it
14:32:06 [timbl]
timbl has joined #tagmem
14:32:13 [ht]
zakim, aaff is CMorgan
14:32:13 [Zakim]
+CMorgan; got it
14:32:23 [ht]
zakim, aaee is JPeterson
14:32:23 [Zakim]
+JPeterson; got it
14:32:25 [cindymorgan]
cindymorgan has joined #tagmem
14:32:31 [noah]
Entry from TAG agenda for this call:
14:32:34 [ht]
zakim, CMorgan is cindymorgan
14:32:34 [Zakim]
+cindymorgan; got it
14:32:57 [noah]
TAG agenda points to this working agenda for the call:
14:33:54 [Zakim]
+ +1.202.637.aagg
14:34:49 [alissa]
alissa has joined #tagmem
14:35:12 [ht]
zakim, aagg is alissa
14:35:12 [Zakim]
+alissa; got it
14:35:52 [Yves]
(round of introduction)
14:36:47 [noah]
We should be logging IAB attendee names, I think
14:37:13 [Yves]
14:37:32 [noah]
Olaf Kolkman
14:37:38 [noah]
Jon Peterson
14:37:54 [noah]
Alissa Cooper
14:38:07 [noah]
Spencer Dawkins
14:38:22 [Bernard]
Bernard Aboba
14:38:39 [plh]
plh has joined #tagmem
14:38:43 [timbl]
Zakin, who is on the call?
14:38:44 [ht]
Dow Street
14:38:50 [timbl]
Zakim, who is on the call?
14:38:50 [Zakim]
On the phone I see TAG, Okolkman, Bernard, dowstreet, SDawkins, JPeterson, cindymorgan, alissa
14:38:52 [Zakim]
TAG has JeniT, ht, DKA, Yves, Ashok, TimBL, Larry, JAR, NoahM
14:38:54 [Zakim]
+ +1.703.435.aahh
14:39:06 [noah]
Russ Housley
14:39:19 [timbl]
Zakim, TAG now holds PLH
14:39:19 [Zakim]
+PLH; got it
14:39:22 [ht]
zakim, aahh is RHousley
14:39:22 [Zakim]
+RHousley; got it
14:39:39 [noah]
Philippe le Hegaret
14:40:17 [ht]
Cindy Morgan
14:40:38 [housley]
housley has joined #tagmem
14:40:46 [noah]
Hannes' flight was delayed.
14:40:58 [ht]
Regrets from Hannes Tschofenig
14:41:21 [ht]
zakim, RHousley is housley
14:41:21 [Zakim]
+housley; got it
14:42:05 [Yves]
14:42:07 [noah]
Agenda:
14:42:55 [noah]
14:43:02 [noah]
TAG's public home page:
14:43:03 [Yves]
ht: I am asking the two chairs an elevator pitch to decribe what each group is doing
14:43:15 [noah]
Charter:
14:43:18 [Bernard]
14:43:22 [Bernard]
IAB Charter
14:43:32 [noah]
The mission of the TAG is stewardship of the Web architecture. There are three aspects to this mission:
14:43:41 [noah]
to document and build consensus around principles of Web architecture and to interpret and clarify these principles when necessary;
14:43:41 [noah]
to resolve issues involving general Web architecture brought to the TAG;
14:43:41 [noah]
to help coordinate cross-technology architecture developments inside and outside W3C.
14:45:00 [noah]
Architecture of the World Wide Web:
14:45:02 [Bernard]
From Section 2 of RFC 2850:
14:45:03 [Bernard]
The IAB is chartered both as a committee of the IETF and as an
14:45:03 [Bernard]
advisory body of the Internet Society. Its responsibilities include:
14:45:03 [Bernard]
(a) IESG Appointment
14:45:03 [Bernard]
(b) Architectural Oversight
14:45:03 [Bernard]
(c) Standards Process Oversight and Appeal
14:45:04 [Bernard]
(d) RFC Series and IANA
14:45:06 [Bernard]
14:45:08 [Bernard]
(e) ISOC Liaison
14:45:10 [Bernard]
14:45:12 [Bernard]
(f) External Liaison
14:45:54 [noah]
14:46:14 [masinter]
14:46:55 [noah]
Public TAG mailing list:
14:48:32 [Yves]
Bernard: IAB also has administrative duties, including IESG appointement, see section 2 above
14:49:34 [Yves]
series of document published on different aspects of the Internet
14:49:57 [masinter]
zakim, who's here
14:49:57 [Zakim]
masinter, you need to end that query with '?'
14:49:57 [Bernard]
Bernard has joined #tagmem
14:49:59 [Zakim]
-Bernard
14:50:00 [masinter]
zakim, who's here?
14:50:01 [Zakim]
On the phone I see TAG, Okolkman, dowstreet, SDawkins, JPeterson, cindymorgan, alissa, housley
14:50:04 [Zakim]
TAG has PLH
14:50:06 [Zakim]
On IRC I see Bernard, housley, plh, alissa, cindymorgan, timbl, dowstreet, masinter, Zakim, OKolkman, Ashok, ht, RRSAgent, DKA, JeniT, noah, jar, Norm, plinss_, Yves, trackbot
14:50:31 [Bernard]
Yes
14:50:53 [Zakim]
+[Microsoft]
14:51:02 [ht]
zakim, [ is Bernard
14:51:02 [Zakim]
+Bernard; got it
14:52:16 [ht]
q+ to explain how the quere works
14:52:22 [ht]
ack ht
14:52:22 [Zakim]
ht, you wanted to explain how the quere works
14:52:28 [noah]
To get on the q, say something like "q+ to flame about TCP architecture"
14:52:50 [noah]
To find out who's on the queue, say "q?" (no quotes on any of that)
14:52:59 [noah]
To take yourself off the queue: "q-"
14:53:06 [timbl]
s/quere/queue/
14:53:06 [noah]
q?
14:53:59 [Yves]
first topic: Versioning: IAB document on extensibility vs. TAG notes on versioning
14:54:13 [noah]
Link?
14:54:41 [masinter]
14:54:41 [masinter]
14:54:41 [masinter]
14:55:03 [masinter]
sent to TAG
but not on our agenda
14:55:18 [Yves]
Bernard: it is an attempt to documentsways of extending protocols
14:56:04 [Yves]
Noah: versionning and extensibility came up while reviewing specification that provided or not hooks for extensibility
14:56:16 [Bernard]
Review comments can be submitted by sending email to iab@iab.org, or by using TRAC (
).
14:57:10 [Yves]
key points are: decentralized extensibility, identification using URIs leading to namespaces, CURIes, etc...
14:57:16 [masinter]
s/documentsways/document ways/
14:58:03 [Yves]
we got also TAG finding about good architecture for document formats, using XML as a tool to demonstrate that, but it was not finished
14:58:20 [Yves]
there are still new things proposed in that space
14:58:52 [jpeterson]
jpeterson has joined #tagmem
14:58:54 [Yves]
ht: for example, TAG discussed extensibility in HTML5 and provided feedback
14:59:10 [noah]
HT: Extensibility in HTML5 is somewhat circumscribed.
14:59:45 [noah]
Also, pertinent to this discussion, HTML5 relies on various forms of registries, including some IANA registries, some proposed Wikis, etc.
15:00:42 [Yves]
larry: there is some similarity in TAG vs W3C and IAB vs IETF, would it be ok to link those efforts between IAB and TAG, like how do you plan to have an influence on IETF
15:01:42 [Bernard]
audio back up
15:02:04 [Yves]
next topic is security.
15:02:06 [noah]
zakim, who is here?
15:02:06 [Zakim]
On the phone I see TAG, Okolkman, dowstreet, SDawkins, JPeterson, cindymorgan, alissa, housley, Bernard
15:02:08 [Zakim]
TAG has PLH
15:02:09 [Zakim]
On IRC I see jpeterson, Bernard, housley, plh, alissa, cindymorgan, timbl, dowstreet, masinter, Zakim, OKolkman, Ashok, ht, RRSAgent, DKA, JeniT, noah, jar, Norm, plinss_, Yves,
15:02:12 [Zakim]
... trackbot
15:03:14 [masinter]
zakim, tag holds JeniT, ht, DKA, Yves, Ashok, TimBL, Larry, JAR, NoahM, PLH
15:03:14 [Zakim]
PLH was already listed in TAG, masinter
15:03:15 [Zakim]
+JeniT, ht, DKA, Yves, Ashok, TimBL, Larry, JAR, NoahM; got it
15:03:27 [Yves]
jar: there are efforts in W3C around security but TAG doesn't have the right expertise to answer security queries. One example is CORS (Cross Origin Resource Sharing), UMP... attemps to turn a browser into a security platform to access resources
15:03:29 [plh]
-->
Cross-Origin Resource Sharing
15:04:08 [Bernard]
It has also come up in IETF RTCWEB
15:04:20 [Yves]
the TAG looked at that, tried to review it, but it has been a challenge for us. Still we are trying to keep an eye on security issues as it has an impact on ther parts of the Web
15:04:21 [masinter]
15:04:41 [plh]
I would note that W3C has been trying to create a Web Applications Security Working Group for the past 6 months or so
15:05:12 [Yves]
we has a session with Adam Barth on cookies. John Kemp (who left the TAG since then) made good initial work in that area
15:05:23 [plh]
s/has/had/
15:06:42 [noah]
q?
15:06:52 [noah]
q+ to mention TAG interest in protocol security
15:07:21 [Yves]
JonPeterson: we would be happy to hear about documents within W3C that talks about security, would it be good to have a way to refer to documents needing review?
15:07:35 [Yves]
jar: we have a process for that usually Last Call triggers such reviews
15:07:56 [Yves]
ht: it is usually better to use the traditionnal IETF/W3C liaison for that
15:08:56 [Yves]
JonPeterson: the IAB has a broad oversee of the IETF, currently things about identity is of great interest for IAB members
15:08:59 [ht]
We will come back to Identity later on
15:08:59 [noah]
q?
15:09:26 [Yves]
the IAB is tyring to look at broader topics that are not addressed by working groups
15:09:44 [Yves]
s/tyring/trying/
15:10:25 [ht]
q?
15:10:36 [ht]
q+ Spencer
15:10:38 [ht]
ack next
15:10:40 [Zakim]
noah, you wanted to mention TAG interest in protocol security
15:10:51 [Yves]
the IAB once worked on security architecture of the internet, this led to security considerations in groups.
15:11:50 [Yves]
noah: in domains like security, it is difficult to assess things without having deep knowledge of protocols or formats involved
15:11:53 [ht]
ack next
15:12:08 [Bernard]
IAB has also held workshops on things like "unwanted traffic", published surveys on DDoS, etc.
15:13:10 [Bernard]
15:13:32 [Bernard]
Report from a Security-related Workshop (on unwanted traffic).
15:14:19 [Bernard]
Internet Denial of Service Considerations:
15:14:47 [Yves]
ht: the TAG started recently to work at privacy. Both security and privacy issue impact organizaition in multiple ways, and extracting the architecture part of those issues can be tricky
15:15:50 [Yves]
DKA: involve in a serie of workshop on privacy, like device API privacy workshop, as well as the IAB-W3C workshop, the do-not-track workshop.
15:16:43 [Yves]
working on a draft TAG finding relative to data minimization when building an API (Web API)
15:19:00 [Yves]
AlissaC: same situation as the TAG, still in early stages. How do we take guidance to specification writers on privacy topics, trying to do something like what Bernard described for security awareness in groups
15:19:33 [ht]
q?
15:20:08 [Bernard]
15:20:50 [Yves]
Ashok: there is a report on the DNT workshop by Thomas Roessler. We are thinking about starting a Working Group on DNT
15:22:07 [noah]
q?
15:22:28 [masinter]
I wondered about whether tracking based on DNS lookups, for example, were in scope, or tracking on SIP telephony
15:23:53 [masinter]
i would worry less about drawing boundaries and more about collaborating on the overlap
15:24:13 [Yves]
JonPeterson: we want to avoid a W3C way of doing privacy and an IETF way of doing privacy, so we need to ensure we have the right liaisons
15:24:51 [Yves]
Noah: the TAG doesn't have a directionnal role, we are more alerting on issues
15:24:56 [Bernard]
+q Bernard
15:25:05 [ht]
q+ to repeat that the primary boundary-drawing responsibility lies with the existing liaison
15:25:27 [ht]
ack Bernard
15:26:07 [Yves]
Bernard: how we analyze privacy issue? There are technical issues, but also legal issues and business issues
15:26:53 [Yves]
privacy is much more complex than security for IETF. ie: what it the threat model here?
15:26:54 [jpeterson]
agreed larry
15:26:59 [ht]
ack ht
15:26:59 [Zakim]
ht, you wanted to repeat that the primary boundary-drawing responsibility lies with the existing liaison
15:28:11 [masinter]
will raise venue-shopping during 'next steps' discussion
15:28:19 [Yves]
ht: issue about the conflation between privacy and security. Privacy is in fact far more complicated than protecting your data, so knowing what privacy encompass is important.
15:28:20 [DKA_]
DKA_ has joined #tagmem
15:28:29 [Ashok]
Ashok has joined #tagmem
15:28:53 [timbl]
timbl has joined #tagmem
15:29:32 [Yves]
boundaries definition is the role of the IETF/W3C liaisons, the TAG doesn't have liaison oversight, unlike the IAB
15:29:38 [timbl]
q+
15:29:52 [Yves]
Larry: would like to hear about what the IAB did wrt liaisons to other organizations
15:30:15 [Bernard]
IAB appoints liaisons, shepards liaisons. It is a high level role.
15:30:16 [Yves]
JonP: we have mnot acting as a sheperd for the W3C liaison, he brings regular feedback to us
15:30:54 [Yves]
questions are about what is needed to augment collaborations between the two organizations.
15:30:58 [Bernard]
IAB does not duplicate the liaison role.
15:31:18 [ht]
ack next
15:31:28 [Yves]
ht: we forgot to include mnot in this call and it was our mistake.
15:33:04 [Yves]
timbl: there have been issues when html5 evolved as it impacted several groups not only in W3C but also in other organizations.
15:34:26 [Yves]
ht: can you elaborate on 'real time communication' ?
15:34:43 [Ashok]
Report on Do Not Track Workshop:
15:35:53 [Yves]
JonP: IETF worked on lots of specification and efforts, now things are moving to the browser, we need to ensure that W3C and IETF side of the efforts, despite the differences between organizational models, need to collaborate more closely.
15:37:04 [Bernard]
RTCWEB is a merger of two major technologies: HTML 5 and realtime communications. So it is an inherently complex undertaking.
15:38:14 [Bernard]
It will both affect the evolution of realtime, as well as the web security model.
15:38:28 [Bernard]
+q bernard
15:39:57 [alissa]
q+
15:39:58 [Yves]
JonP: do you have an opinion as the TAG on where the HTML5 effor is goins ?
15:40:04 [Yves]
s/goins/going/
15:41:15 [Yves]
ht: we are looking at various aspects fo HTML5 and presented our position as feedback to the HTML-WG, some comments were accepted, some other not. But that's the role of the TAG.
15:42:03 [Bernard]
RTCWEB will also have privacy impacts. The question is: do we understand how to analyze these issues?
15:43:31 [ht]
s/effor/effort/
15:44:12 [Bernard]
We do not yet have recommendations on how to analyze Privacy Considerations.... security impact is likely to go way beyond protocol-based Security Considerations
15:45:20 [noah]
I'm curious how much we know about the likely technical shape of this "real time Web". E.g. what would be the key use cases, protocols and formats
15:45:33 [ht]
q+ to ack that the TAG has not looked at RTCWEB as such
15:45:40 [ht]
ack bernard
15:46:03 [ht]
ack next
15:47:19 [Bernard]
RTCWEB + Geolocation = Emergency Services (see
)
15:47:20 [Yves]
Alissa: another impact of RTCWeb is on emergency services, in combination with geolocation. IETF did lots of work in that area, it is not something that could be ignored. Liaison with W3C on that topic is important.
15:47:53 [ht]
ack ht
15:47:53 [Zakim]
ht, you wanted to ack that the TAG has not looked at RTCWEB as such
15:48:23 [noah]
q+ to ask about RTC requirements, specs, etc.
15:48:44 [OKolkman]
I need to drop. Apologies for that
15:48:55 [Yves]
ht: the TAG has not considered RTCWeb yet, looks like an interesting topic for us
15:48:58 [OKolkman]
See you all later Thanks for hosting this call!
15:49:04 [Zakim]
-Okolkman
15:49:07 [ht]
ack noah
15:49:07 [Zakim]
noah, you wanted to ask about RTC requirements, specs, etc.
15:49:13 [OKolkman]
OKolkman has left #tagmem
15:49:51 [timbl]
15:49:55 [Yves]
Noah: wondering what is behind 'RTCWeb', would be interesting to hear form the IAB about requirements and directions of it
15:51:16 [Yves]
ht: IAB and TAG hasn't work together in the past. It is probably an error, and it would be a good thing to have a more 'technical' liaison between the TAG and the IAB
15:52:25 [noah]
Thanks Tim. Very interesting. That stuff's all useful, and I'm likely in favor, but it's not the first thing I would have expected from the shorthand "RTC"
15:52:39 [Bernard]
See also FCC Location NOI:
15:52:45 [Yves]
JonP: we need to look at what our processes are, etc...
15:53:03 [timbl]
15:53:42 [noah]
q?
15:53:51 [Bernard]
FCC NG911 NOI:
15:53:55 [noah]
q+ to emphasize real work, for now, over documents on logistics
15:54:01 [Yves]
Larry: we have the issues of 'venue shopping' figuring out which organisation to send work to. Documenting the overlap between organisation woule be good. Also our existing liaison could be responsible for identifying topic we could work on together
15:54:02 [ht]
ack noah
15:54:02 [Zakim]
noah, you wanted to emphasize real work, for now, over documents on logistics
15:54:08 [Yves]
Plh: we should discuss this, yes
15:55:02 [ht]
q+ to remember Prague (IETF 80) and look towards the future
15:55:15 [Yves]
Noah: people doing venue shopping will continue to do so, so such document will not change things, however finding a way to do technical work together is interesting, and documenting that experience after some times would be interesting
15:55:18 [timbl]
q+
15:55:33 [ht]
ack ht
15:55:33 [Zakim]
ht, you wanted to remember Prague (IETF 80) and look towards the future
15:55:50 [noah]
I'm actually going a bit further, saying: let's make sure we take opportunities to actually DO technical work as they arise, and see how it goes.
15:55:55 [Bernard]
Example of documenting existing practice in liaison:
15:56:31 [Yves]
ht: the RTCWeb is a good topic to try to do things together
15:57:39 [masinter]
update?
15:57:48 [noah]
q?
15:57:57 [masinter]
as architectural issue, how does it apply to RTCWeb
15:58:02 [ht]
ack next
15:58:08 [Bernard]
Yes, IAB has discussed potential update to RFC 3205.
15:58:12 [jpeterson]
on the iab side of that question ht look at
15:58:20 [ht]
Jon, yes
15:58:21 [jpeterson]
the post-standardization argument is given there
15:59:18 [noah]
Curious what IAB knows about it's physical meeting schedule next 9-12 months.
15:59:19 [ht]
For W3C readers, per that doc't "post-standarization" means standardization, if at all, outside IETF
15:59:24 [noah]
s/it's/its/
15:59:36 [masinter]
should TAG review that document? Would that be helpful? What impact would IAB like to have on W3C?
15:59:43 [ht]
IAB meets at IETF plenaries
15:59:54 [ht]
Which are fixed for next 12 mo already
15:59:59 [noah]
at...
16:00:22 [noah]
e.g. is there one winter/spring?
16:00:47 [jpeterson]
ht it doesn't really mean standardizing outside the ietf, it means application protocol development that doesn't require a published specification in any venue because it relies on pushing code
16:01:00 [jpeterson]
winter is in taipei
16:01:13 [plh]
-->
W3C/OMA MOU liaison
16:01:24 [masinter]
16:02:00 [noah]
Thanks. To bad. Very unlikely we could get TAG to Teipei, I'd guess, but we could think about it.
16:02:11 [masinter]
November 13-18 Taipei, March 25-30 2012 Paris
16:02:19 [noah]
s/To bad/Too bad/
16:02:32 [Bernard]
Next plenary will cover Privacy at IETF 81.
16:02:44 [timbl]
Is there an iCalendar file I can subscribe to for the IETF meetings?
16:03:02 [masinter]
tim,
16:03:07 [timbl]
tx
16:03:09 [Yves]
Bernard: what is the followup?
16:03:28 [Yves]
Noah: trying to think about that.
16:03:40 [Yves]
Larry: it would be good to have the existing liaisons doing recommendations
16:03:53 [Yves]
Plh: will do
16:03:57 [Zakim]
-housley
16:04:22 [Bernard]
IAB will be at IETF meetings (see
for current schedule). F2F retreat once a year (date and location not set for 2012).
16:05:06 [Bernard]
We can talk offline and see if we can align.
16:05:18 [timbl]
Thank you everyone.
16:05:21 [DKA_]
q+ to suggest more calls like this might be a good idea as well.
16:05:25 [noah]
ACTION: Noah to talk to Bernard about possible IAB/TAG co-location
16:05:25 [trackbot]
Created ACTION-565 - Talk to Bernard about possible IAB/TAG co-location [on Noah Mendelsohn - due 2011-06-14].
16:05:41 [noah]
ack next
16:05:43 [Zakim]
DKA_, you wanted to suggest more calls like this might be a good idea as well.
16:05:59 [Zakim]
-Bernard
16:06:50 [plh]
fyi, the next W3C/IETF liaison call is this Monday
16:06:56 [Zakim]
-alissa
16:06:58 [Zakim]
-cindymorgan
16:07:00 [Zakim]
-dowstreet
16:07:02 [Zakim]
-TAG
16:07:04 [Zakim]
-JPeterson
16:07:15 [Zakim]
-SDawkins
16:07:16 [Zakim]
TAG_f2f(IABTAG)10:00AM has ended
16:07:18 [Zakim]
Attendees were +1.617.715.aaaa, JeniT, ht, DKA, Yves, Ashok, TimBL, Larry, JAR, NoahM, +31.20.750.aabb, Okolkman, +1.415.738.aacc, Bernard, +1.214.755.aadd, SDawkins,
16:07:21 [Zakim]
... +1.858.750.aaee, +1.510.386.aaff, dowstreet, JPeterson, cindymorgan, +1.202.637.aagg, alissa, +1.703.435.aahh, PLH, housley, [Microsoft]
16:07:34 [Yves]
Ashok: we should have more focussed scopes
16:08:25 [Ashok]
For example, on Security or Privacy
16:08:53 [DKA_]
ACTION: Dan to contact Alissa Cooper, organize a future joint discussion on privacy with IAB.
16:08:53 [trackbot]
Created ACTION-566 - Contact Alissa Cooper, organize a future joint discussion on privacy with IAB. [on Daniel Appelquist - due 2011-06-14].
16:09:24 [Yves]
Noah: would be good to have RTCWeb knowledge, have a telcon on that topic
16:09:34 [masinter]
what are architectural issues around RTCWEB that raise it to IAB and should also be brought to TAG
16:57:34 [timbl]
timbl has joined #tagmem
16:59:55 [jar]
jar has joined #tagmem
17:00:12 [ht]
ht has joined #tagmem
17:05:47 [JeniT]
JeniT has joined #tagmem
17:15:53 [timbl_]
timbl_ has joined #tagmem
17:18:24 [timbl_]
timbl_ has joined #tagmem
17:25:38 [masinter]
masinter has joined #tagmem
17:30:02 [DKA]
DKA has joined #tagmem
17:30:20 [DKA]
Scribe: Dan
17:30:22 [DKA]
ScribeNick: DKA
17:31:21 [DKA]
Topic: Restarting session on Fragment IDs
17:31:37 [DKA]
Noah: 10 minutes. Jenni can you lead the wrapup?
17:31:41 [noah]
noah has joined #tagmem
17:31:52 [JeniT]
s/Jenni/Jeni/
17:32:49 [DKA]
Jeni: larry you were talking about the mime and the web draft?
17:33:52 [DKA]
Larry: The issues raised there seem to fall into 2 categories - interactions between w3c and IANA (extending to other registries)...
17:34:49 [DKA]
... 2nd set: things wrong with the mime registry. To that end, Alexi M. has offered to help co-edit the document.
17:35:20 [DKA]
... so that's what's happening. He suggested we meet together at IETF in Quebec. I will be there.
17:35:33 [DKA]
Noah: Do we care if this becomes an IETF draft or a TAG finding?
17:35:34 [Yves]
s/Alexi M./Alexey Melnikov/
17:35:54 [DKA]
Larry: If there's something we can fix through IETF then we wouldn't need a TAG document to endorse these changes.
17:36:09 [DKA]
... looking for some feedback.
17:36:37 [DKA]
Jeni: My feeling is that the level of discussion went into earlier is bigger than the frag identifiers section of that document...
17:37:01 [DKA]
... I think it needs to be expanded quite a lot. Should that be in your document or a separate document?
17:37:26 [DKA]
Larry: I like having a second document better that talks about fragment identifiers.
17:37:52 [DKA]
Jeni: In that case I will take an action to do a draft document that outlines the problems with frag IDs and starts to outline the solutions.
17:38:08 [DKA]
Larry: You could say how things need to change and consider doing an internet draft.
17:39:01 [DKA]
Noah: Are there other actions or clean-up?
17:39:10 [DKA]
[consensus to move on]
17:40:09 [JeniT]
ACTION: Jeni to draft a document describing problems around fragids and ways things should be changed due 2011-06-28
17:40:09 [trackbot]
Created ACTION-567 - Draft a document describing problems around fragids and ways things should be changed due 2011-06-28 [on Jeni Tennison - due 2011-06-14].
17:40:14 [DKA]
Topic: URI Definition Discovery; Metadata Architecture
17:40:25 [DKA]
ISSUE-57?
17:40:25 [trackbot]
ISSUE-57 -- Mechanisms for obtaining information about the meaning of a given URI -- open
17:40:25 [trackbot]
17:40:31 [DKA]
ISSUE-63?
17:40:31 [trackbot]
ISSUE-63 -- Metadata Architecture for the Web -- open
17:40:31 [trackbot]
17:40:36 [DKA]
ISSUE-14?
17:40:36 [trackbot]
ISSUE-14 -- What is the range of the HTTP dereference function? -- closed
17:40:36 [trackbot]
17:42:18 [DKA]
JAR: on Issue-57. History - Tim raised ISSUE-14 in 2002. TAG resolved it in 2005. This percolated through the community. In 2007 we opened ISSUE-57.
17:42:28 [DKA]
... the complaint is that 303s are too slow.
17:42:49 [DKA]
... there are two round-trips required.
17:43:21 [DKA]
... also the complaint that it's hard to deploy - especially for those who use hosted solutions that make it more difficult to send 303 responses.
17:43:51 [DKA]
... I came to this issue in 2007 with a different complaint - I don't know what an "Information Resource" is.
17:44:15 [DKA]
... Harry Halpin has helped - sent an email in 2011 laying out problems with the 303 situation.
17:44:46 [DKA]
... so - how do you use URIs for things other than information resources?
17:45:32 [DKA]
... each URI refers to the information resource that you get at that URI.
17:46:00 [Ashok]
Ashok has joined #tagmem
17:46:13 [DKA]
... at the last f2f where we discussed it, we agreed I would create a document and then call for public review on www-tag.
17:46:41 [DKA]
17:47:38 [DKA]
... we would then decide how to pursue this. We could start a new community group, do a tag finding, charter a new working group, start a document in an existing working group, etc.. [or something else]
17:47:53 [DKA]
... I would like an answer - are we prepared for a consensus process on this issue?
17:48:28 [DKA]
... How I see this issue more generally - this is about the relation of RDF to Web Architecture.
17:48:52 [DKA]
... RDF is supposed to use the URI namespace in a way that is compatible with Web Architecture.
17:50:46 [DKA]
....
17:52:18 [DKA]
... [adopters could simply choose to go another way.]
17:53:00 [DKA]
... There is also the claim that the specs are weak on how this all works.
17:53:44 [DKA]
... e.g. RFC-2616 bis
17:54:55 [DKA]
Tim: From the perspective of someone implementing a web server, it is strong, but not from a semantic web perspective.
17:55:33 [DKA]
JAR: So - what might happen as this goes to a consensus process?
17:55:55 [Yves]
7 drafts
17:56:37 [Yves]
for the revised 303 definition I talked about
17:57:02 [DKA]
... Does Webarch have defenders in the linked data community? Tabulator; users of xhv:license, anyone who cares about metadata or provenance...
17:57:38 [DKA]
... most people in the RDF world probably take it for granted.
17:58:20 [DKA]
... having more choice may also be confusing.
17:58:46 [DKA]
Jeni: It's already the case that people trying to do linked data have problems figuring out what to do - to add another story onto that, we make the story worse.
17:58:56 [DKA]
... so [it hinders linked data adoption].
17:59:22 [DKA]
Ashok: If you are able to endorse one story? That would make things better.
17:59:37 [DKA]
Jeni: That also has big implications.
18:01:12 [DKA]
JAR: If there were a REC, what might it say? Strengthen httpRange-14, help out with issue-57; or retract httpRange-14
18:01:53 [DKA]
... that option means that some RDF related working group gets to decide what URIs mean to it -
18:02:13 [DKA]
... this would mean an "opt in" to Web architecture.
18:03:33 [DKA]
... another possibility - if we fail to reach consensus then fall back to a TAG finding, or do nothing. But there is a need for clarity.
18:03:51 [DKA]
... "Undefended linguistic space will be invaded."
18:05:22 [Ashok]
Jar: I've told you my take on this ... do you want to give me advice
18:05:51 [Ashok]
... the effect may be that a community secedes from Web Arch
18:05:52 [jar]
q?
18:06:28 [Ashok]
lMM: I didn't understand the stuff in sections 3 and 4
18:06:38 [Ashok]
s/IMM/LMM/
18:07:02 [DKA]
Larry: can we bring more light to bear on the choices?
18:07:14 [DKA]
JAR: Probably that's why I'm asking for review.
18:07:28 [DKA]
[docuemnt review]
18:07:50 [masinter]
I want to understand the idea in HTTPRange-14 that a resource is either an information resource or not, and whether that can change over time... and the substantive time-dependency makes me not like range-14
18:08:15 [DKA]
18:11:13 [DKA]
Ashok: Can you tell me how this is different from the other use case on Metadata?
18:11:32 [DKA]
Ashok: The Mark Nottingham use case?
18:11:58 [DKA]
JAR: This is where you're trying to extend the dictionary.
18:12:38 [DKA]
18:17:02 [masinter]
the dictionary has a definition of the word. The word doesn't have the definition in the dictionary. There are multiple dictionaries, which have different definitions.
18:17:04 [DKA]
Tim: Word and URI are in the same [category] - a collective noun.
18:17:34 [DKA]
Noah: [thinks URIs are different category than words]
18:17:39 [DKA]
[ moving on ]
18:18:59 [noah]
Would "establishing the referent of a URI" be closer to correct than "defining a URI"?
18:19:55 [noah]
I think words and URIs are different in that the word dog existed and was used to refer to a class of animal long before there was writing, and thus before the 3 letter string "d-o-g" was used to represent the word.
18:20:06 [noah]
Per RFC 3986, the URI is the string.
18:24:34 [ndw]
ndw has joined #tagmem
18:28:33 [DKA]
Tim: [referencing to 3.5] - the idea of the # is that it binds the URI of the document to a local identifier in any language. Doing this for RDF is really just one small case.
18:29:00 [DKA]
... this was in the Web design before html - a fundamental operation in the theory of Web architecture.
18:31:29 [masinter]
i'm concerned about temporal variability (the "thunderstorm") comment
18:31:37 [jar]
timbl: 3.5 maybe relay point about abstractness of # operator
18:33:43 .
18:34:41 [masinter]
i think you need to argue against it without editorializing about it. calling something "upside-down" or "confusion" isn't an argument.
18:36:17 [masinter]
my concern about hash and 303 is that the make meaning depend on deployment of services infrastructure, which cost power and money to maintain
18:36:35 [masinter]
and that to mean something you shouldn't have to have a foundation
18:36:41 [DKA]
Tim: What is Harry's position?
18:37:04 [DKA]
JAR: His position is the anti-HTTPRange-14 position.
18:37:46 [DKA]
Larry: My concern. I want to say something today and mean something 100 years from now without having to endow a foundation to maintain that URI. I would have to guarantee that 100 years from now that there's something there to return 303s.
18:38:38 [DKA]
Tim: You're confusing 2 things. Supposing you want to use URNs. In the URN it's perfectly reasonable to give the URN for the american citizenship act 2012 with a #citizen - to mean citizen as defined in that document.
18:38:50 [DKA]
... this is very common.
18:39:44 [DKA]
Tim: I think the URN issue and the hash issue are orthogonal.
18:42:21 [masinter]
i'd like to see in section 5 the issue of requirement for long-term availability of URI data or services (303 or hash)
18:42:24 [timbl]
In legal circles, it is very common to define a term with respect to a document such as a law, a la: "resident" in the terms of the Residence Act of 1876.
18:42:32 ?
18:42:37 [masinter]
also about the "thunderstorm" example, where the meaning changes if there's a thunderstorm
18:42:38 [timbl]
... That is what the "#" is doing here
18:43:25 [timbl]
JeniT, that is a teason I felt HTTPRage-14 was important
18:43:45 [JeniT]
s/teason/reason/
18:44:51 [jar]
timbl doesn't like postfix #
18:45:38 [jar]
... because "" isn't an ncname
18:46:31 [jar]
... include a warning against using empty fragid
18:49:38 [DKA]
JAR: Rumor: Some tools - site builders - are [munging] the RDFa by cutting off the frag identifiers.
18:52:00 [DKA]]?"
18:52:09 [DKA]
JAR: Jango and Sinatra were the frameworks named.
18:52:25 [JeniT]
s/Jango/Django/
18:55:13 [DKA]
[some discussion on purl.org reliability issues]
18:55:45 [DKA]
[referncing 3.6.1]
18:56:02 [DKA]
Jeni: Governments would not feel happy using purl.org URIs.
18:56:12 [DKA]
Dan: We also had the same issue with Vodafone.
18:58:40 [DKA]
[ref 3.6.3 - 303s difficult to bookmark - some discussion on lack of ability to copy the previous URI out of the address bar in browsers]
18:59:23 [DKA]
JAR: 303 is "fixed" by HTTPbis - 200 is not fixed by HTTPbis.
19:00:21 [DKA]
19:02:15 [noah]
Interesting.RFC 2616 does not use the word "representation" in definition of 200 status code for GET. Rather it says: "the response;"
19:02:36 [noah]
So, the question is whether the "corresponding to" relation can hold for other than an information resource.
19:02:48 [noah]
I infer that Tim believes: "no, it can't"
19:03:50 [DKA]
Jeni: [on 4.2] if you have a URI that represents schools and a fragment identifier for a particular school, you could return a 404 to say that school does not exist or you could redirect to another document which says it doesn't exist.
19:04:11 [DKA]
... point being you may want to use some of the http status codes to say something about the non-information-resource.
19:04:27 [DKA]
HT: I think 404 always means no representation found.
19:04:49 [DKA]
Noah: [cites chapter and verse of 404 and 410]
19:08:05 [DKA]
[section 4.3]
19:08:21 [DKA]
[discussion on mget]
19:08:48 [DKA]
HT: You might want to reference XRI and a whole bunch of other stuff...
19:08:59 [DKA]
JAR: XRI is using well-known.
19:09:59 [DKA]
Tim: Now things are getting interesting.
19:10:27 [DKA]
... supposing for example - what things could we tweak about the request and the response...
19:11:24 [ht]
ht has joined #tagmem
19:11:39 [jar]
tweak the content-type
19:11:56 [DKA]
Tim: I think that people are using an upload space then they can use hashes.
19:12:31 [masinter]
i don't think it should cost energy to mean something
19:13:04 [jar]
processing instruction ?
19:13:27 [Norm]
Norm has joined #tagmem
19:14:23 [DKA]
Noah: THis strikes me as another thing like client side state - we could spend more time on this at the risk of dropping other things?
19:18:15 [DKA]
[break]
19:18:22 [DKA]
RRSagent, draft minutes
19:18:22 [RRSAgent]
I have made the request to generate
DKA
19:18:39 [DKA]
rrsagent make logs public
19:18:53 [DKA]
rrsagent, make logs public
19:23:33 [plh]
plh has left #tagmem
20:09:20 [ndw]
ndw has joined #tagmem
20:41:58 [ht]
ht has joined #tagmem
21:01:14 [JeniT]
JeniT has joined #tagmem
21:28:08 [ht]
ht has joined #tagmem
21:35:27 [DKA]
DKA has joined #tagmem
21:35:33 [DKA]
[resume]
21:36:08 [DKA]
[change of venue - Condord]
21:40:54 [DKA]
present+ Jeni, Tim, Ashok, Larry, Henry, Noah, Dan, JAR, Yves
21:41:25 [DKA]
Tim: "Is a representation of a document" got turned into "representation"
21:41:46 [DKA]
... argument went - HTTPRange-14 was badly phrases.
21:43:06 [DKA]
... then people said the domain of http 200 is information resource - that means you can only use http uris to refer to informaiton resource. Then you would say you can only put information resource on your web server...
21:43:18 [DKA]
Larry: I'm still confused.
21:43:32 [DKA]
JAR: THe other document (Web Metadata) is the one that [clarifies].
21:44:00 [DKA]
... people put a document on the web, it's title is X so they write RDF that this document's title is X.
21:44:52 [DKA]
Larry: I think it's a problem with the way that it's described and not with the practice.
21:45:33 [DKA]
JAR: People are successfully using this metadata patern.
21:45:53 [DKA]
Larry: I'm concerned in the way you're descibing the patern - [dependency on running web server]
21:46:16 [DKA]
... if you do a get on the string, web server must be running when you do that GET.
21:47:03 [DKA]
Tim: There's a fundamental switch - http is a namespace - you use it for naming things. One property is - you own domain names so you can allocate names to things. These names have a second property that on a good day you can find out stuff about them.
21:47:18 [DKA]
Larry: I understand that but I'm concerned about how it's described.
21:47:52 [DKA]
JAR: I described it precisely. Based on what http-bis says and what people already do...
21:50:32 [DKA]
... 2 documents - the information resource document - a distillation of a [long] process. Stands on its own, independent of issue-57. It says you could go either way on this.
21:50:42 [noah]
noah has joined #tagmem
21:50:43 [DKA]
Ashok: I think you got to tell the world what you would like to happen.
21:51:22 [DKA]
JAR: I don't know what I'd like to happen. I think in this case we can solve this one problem [a threat to linked data].
21:51:50 [DKA]
... half a billion documents deployed using this pattern described in this document and billions and billions more. We want to get it right.
21:52:32 [DKA]
Larry: asking about sometimes CC license is embedded...
21:52:43 [DKA]
HT: Sometimes that's not allowed eg for image formats.
21:53:07 [DKA]
JAR: That's right - that's why we need this.
21:53:58 [DKA]
HT: How can we turn this into a decision process? We need to get to a bottom line.
21:55:06 [DKA]
... we need a story of how to get there from here.
21:55:29 [DKA]
... of the possible ways forward, what are the ones we can get to from here in a way that's believable?
21:55:46 [DKA]
... e.g. "solutions that require changes to the server are impossible because we can't get them done."
21:56:06 [DKA]
... if in fact that's only relevant in the corner cases and we could tell the new story from day 1 because the 99% case you don't have to worry about.
21:56:51 [DKA]
... suppose this straw man: suppose we endorse the "pun"?
21:57:14 [DKA]
Tim: There's a third way - Sandro's [work]...
21:57:56 [DKA]
HT: ... but - the problem with the pun is that there are URIs out there that you want to use in both ways - both to refer to the document and what it refers to....
21:59:29 [DKA]
Tim: In fact, we need to ground this. What exactly should implementers do?
22:00:34 [DKA]
... could we create a new way to do this? Create 209?
22:00:55 [DKA]
JAR: The one I tend to favor right now is the Pun solution.
22:01:21 [DKA]
[this is 4.4]
22:02:03 [DKA]
Tim: There's a vast number of cases of web pages about web pages - that this can't handle.
22:02:17 [DKA]
JAR: I've come to believe that these cases are fewer than you think they are.
22:02:29 [DKA]
JAR: Well - it's all of FlickR (for instance).
22:03:07 [DKA]
... now -we could go to FlickR and ask them to change. But I don't want to do that until we have a spec.
22:04:24 [DKA]
Larry: if you believe that linking to an image by embedding is a copyright infringement then...
22:04:54 [DKA]
JAR: Yes but [poem in the comment] case. - [in this case you would draw the conclusion that the CC license applies to the poem which is not the case].
22:05:34 [Zakim]
Zakim has left #tagmem
22:06:14 [DKA]
Larry: in the case where the book is by john but bill wrote the preference...
22:06:45 [DKA]
... in defence of punning. You're asserting that this metadata that you're applying belongs to the thing and the document about the thing...
22:06:58 [DKA]
JAR: In the case of license, this is a long conversation.
22:09:17 [DKA]
Tim: When you said - if it works for most of what's out there now that's really important. Yes - it should work for semantic web stuff, but it should [also] work for The Web.
22:09:40 [DKA]
... URIs identify Web pages.
22:09:59 [DKA]
HT: Linked data people are not interested in data about documents.
22:10:06 [DKA]
Jeni: Some aren't.
22:10:32 [DKA]
JAR: We can ask Harry what he thinks.
22:11:58 [JeniT]
JeniT has joined #tagmem
22:12:19 [DKA]
HT: I was going to take the use case - consider the library of congress catalog entry for Moby Dick.
22:13:03 [DKA]
... and suppose consensus emerges that we have one URI to talk about Moby Dick. You then say that the author is Herman Melville using dc:author, etc...
22:13:18 [DKA]
and other namespaces...
22:13:45 [DKA]
... but they're not good because now I need to say that the author of the card catalog entry is so-and-so....
22:13:55 [DKA]
... then you're not going to be able to use creator.
22:15:42 [DKA] principle subject of the resource referenced.
22:16:05 [DKA]
JAR: That is the Pun solution.
22:18:10 [DKA]
Noah: The complication here is that there are some properties you only want to have one name of but you define parallel properties - one for the author of the page, and one to the principle subject.
22:18:20 [DKA]
DKA: But then you need to have a list of all properties somewhere?
22:18:40 [DKA]
Jeni: No.
22:21:22 [DKA]
Tim: This X is a page about this. dc:author is the author of the page. ogp:author is the author of the principle subject.
22:21:22 [DKA]
... you can say there are relationships between these properties.
22:21:22 [DKA]
JAR: You can say this is the license of this, and you can also say this is the license of what this is about...
22:21:25 [DKA]
Tim: The number of levels of indirection is in the eyes of the beholder.
22:21:28 [DKA]
JAR: THis is a pattern for complying with HTTPrange-14.
22:21:33 [DKA]
... but FlickR would need to be changed.
22:21:58 [DKA]
Jeni: you would need a new property in the case of FlickR.
22:23:57 [DKA]...
22:24:14 [DKA]
... it can't depend on doesn't resolve. What I just said was wrong.
22:26:22 [DKA]
JAR: what's the decision procedure?
22:26:57 [DKA]
HT: We have to have another go at this ourselves
22:27:07 [DKA]
LM: We have a provenance group
22:27:17 [DKA]
JAR: The provenance group is asking us for help
22:28:10 [DKA]
LM: Do the provenance requirements help us to make a decision?
22:28:45 [DKA]
JAR: They invited me to their meeting
22:29:03 [DKA]
Yves: July 6-7th at the Stata centre
22:31:49 [DKA]
[discussion on meta-meta-data]
23:17:18 [DKA]
DKA has joined #tagmem
23:18:26 [DKA]
rrsagent, draft minutes
23:18:26 [RRSAgent]
I have made the request to generate
DKA | http://www.w3.org/2011/06/07-tagmem-irc | CC-MAIN-2016-30 | refinedweb | 10,580 | 65.15 |
Any chance of one? VirtualWire sounds like what I need for my project, but the mystery to me is how to use it.
I’ve tried to de-cypher the code, but I can’t see how to add inputs, or how to affect the output content. Or maybe I’m on the wrong track entirely.
I searched the forum & got only 2 hits which may be handy later.
Any tips welcome.
Any chance of one? VirtualWire sounds like what I need for my project, but the mystery to me is how to use it.
I think the examples are the only resource. :-/
I played with it for the first time last night and it is really easy to use.
The library includes transmitter and receiver examples. I just compiled the two pieces and loaded each on a separate Arduino and it just worked. I’m using the 434Mhz transmitter and receiver that I got from SparkFun.
The only issue I ran into was that the examples would not compile without adding the statement
#include <WProgram.h>
above the #include statement for VirtualWire.h.
It might be good to mention a little more about what you’re hoping to achieve.
VirtualWire would probably be one of the best documented libraries out there but maybe the total amount of detail is a little daunting to start with.
–Phil.
Thanks for the replies, guys.
@ follower: You’re right. :-[ Short story: I want to use switches/ buttons etc on the inputs of the transmitter arduino to control things (mainly motors) with outputs from the receiver arduino. I get that I might need an interface after the second arduino.
Quote:< one of the best documented libraries>: hmm, I’m sure I must have missed a lot of it. Any links? Apart from the site I downloaded VirtualWire from. I better check there again.
@dogsop: Are you using the libraries unmodified by your own code?( See my previous post for what I’m trying to do)
Even though I’m still struggling with code, I’m probably just having a serious brain fart. Eventually something will hit me the right way and the penny will drop. Hit me, guys!
In the VirtualWire download directory there is the VirtualWire documentation in PDF format.
If I understand you correctly you want to be able to push a button connected to the transmitter Arduino and then have the receiver Arduino operate a motor or whatever?
If so, then you will want to look at how to get the transmitter example to accept an input and send some data over the wireless link as a result. And then look at how to get the receiver example to perform an action when it gets the data.
–Phil.
@follower: We’re making some headway- Thanks for your input so far. Taking your reply a paragraph at a time:
- I have that PDF. It’s the one I’ve been trying to figure out.
- Correct, except I need to use multiple buttons & multiple motors.
- In section 4 of the PDF I see
vw_set_tx_pin
extern void vw_set_tx_pin(uint8_t pin);
which I understand is for setting the input pin, but I can’t seem to find an example of it anywhere else that gives me a clue how to use it. Where does the pin number go?
I also need to know if I can use that instruction, say 10 times in the one sketch to set 10 input pins.
I keep referring to the Arduino Primer (may not be its correct name) I downloaded months ago, which got me through simpler sketches, but Mike’s PDF almost looks like a different language!
Hi rodmac,
I’ve used the VirtualWire library to replace a broken transmitter/receiver in a RC car which has two motors, one to control forwards/backwards, and the other to control the steering (left/right).
You should only call vw_set_tx_pin(uint8_t pin) if you want to use a different pin for transmitting, the library uses pin 12 by default. This means that ‘pin’ (normally 12) will output data from the arduino to the Sparkfun transmitter.
You should use vw_send(uint8_t* buf, uint8_t len) to actually send the data to the transmitter.
Here’s part of the code I use in the remote:
#define pinLED 13 void setup() { vw_setup(2000); // Bits per sec } void loop() { sendCommand('L', 12); //Go left and set motor speed to 12 delay(100); sendCommand('F',132); //Go forward and set motor speed to 132 delay(100); sendCommand('S', 0); //Stop! delay(400); } void sendCommand(char command[], byte value) { char buffer[5]; //create buffer to hold data to be transmitted //create buffer to hold value converted to a string e.g '123' - max value //is 255 ('cos val is of type byte). char num[4]; memset(buffer, '\0', sizeof(buffer)); memset(num, '\0', sizeof(num)); //My command var is a single letter e.g. 'S' stop, 'R' right etc buffer[0] = command[0]; itoa(value, num, 10); //convert value to a string //concatenate num to the buffer, result would be 'S0', 'F132', 'L12' strcat(buffer, num); digitalWrite(pinLED, true); // Flash a light to show transmitting vw_send((uint8_t *)buffer, strlen(buffer)); //Send the data vw_wait_tx(); // Wait until the whole message is gone }
Then in the arduino actually in the car (which uses the Sparkfun receiver)
void setup(){ Serial.begin(9600); vw_setup(2000); // Bits per sec vw_rx_start(); // Start the receiver PLL running //Receiver is connected to 11 (default pin in VirtualWire library) delay(5); } void loop() { uint8_t buf[VW_MAX_MESSAGE_LEN]; uint8_t buflen = VW_MAX_MESSAGE_LEN; //see if we have received a message from our TX if (vw_get_message(buf, &buflen)) // Non-blocking { //invalid message length must be S/B/F/L/R + number (max 3 digits) if (buflen < 3 || buflen > 5) return; char val[buflen]; //Same as buf, last char will be used for null terminator memset(val, '\0', sizeof(val)); //Copy value from string i.e. 213 from R213 into separate string strncpy(val, (char *)buf + 1, buflen - 1); //convert string containing value to integer e.g. "213" to 213. int VAL = atoi ( val ); switch (buf[0]) { case 'B': Serial.print("spin motor backwards at speed:\t") Serial.println(VAL); break; case 'F': Serial.print("spin motor forwards at speed:\t") Serial.println(VAL); break; case 'L': Serial.print("Steer car left at speed:\t") Serial.println(VAL); break; case 'R': Serial.print("Steer car right at speed:\t") Serial.println(VAL); break; case 'S': Serial.println("STOP THE CAR") break; default: //do nothing break; } } }
HTH
Hi Veronica.
Thanks a million! Finally I see where I’ve been going wrong! I thought
vw_set_tx_pin(uint8_t pin); was setting up an input. Now I see that it sets the output pin.
Can I assume that the input pins are set using standard digital input call, e.g. pinMode(inPin, INPUT) ? I don’t see that in the part of the code you posted.
But just a quick look at your code has answered a lot of questions I haven’t even asked yet. I’m going to study it closely as soon as I get the chance.
I hope anyone else who is puzzled by virtualWire finds this topic.
Thanks again!
Hi rodmac,
Yeah, sorry about not posting the full code, I’m using a Wii nunchuck as input for the remote and thought that code would just complicate the example too much. To answer your question, yes, you can use pinMode(inPin, INPUT) and then digitalRead(inPin) , you’re just reading the state of buttons, right ?
HTH
Veronica
Hi Veronica,
No apology necessary! Your post is already changing my view of how libraries, e.g. VirtualWire, fit into the Arduino scheme. My lack of experience with them had me totally confused. It’s much clearer now.
Thanks again.
Rod. | https://forum.arduino.cc/t/virtualwire-tutorial/3310 | CC-MAIN-2021-49 | refinedweb | 1,296 | 72.87 |
Opened 9 years ago
Closed 6 years ago
#3046 closed defect (invalid)
Genshi prerequisite
Description
Hi,
Thanks for writing this plugin, I'll be using it a lot. I did have a little bit of trouble installing it. It wasn't clear at all to me that this plugin requires Genshi, so I wanted to suggest mentioning that on the TracMathPlugin wiki.
Andrew
Attachments (0)
Change History (4)
comment:1 Changed 9 years ago by
comment:2 Changed 9 years ago by
I've successfully installed this plugin on a 0.10.3 installation by commenting the genshi import (
from genshi.builder import tag in tracmath.py) and all is working like a charm :-)
comment:3 Changed 6 years ago by
comment:4 Changed 6 years ago by
Going forward I only plan to support 0.11 or higher. 0.10 is pretty much ancient by now...
Note: See TracTickets for help on using tickets.
The plugin is marked as only support 0.11, which already requires Genshi. | https://trac-hacks.org/ticket/3046 | CC-MAIN-2017-13 | refinedweb | 168 | 66.94 |
Introduction
The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.
Problem Statement
Given a sorted doubly linked-list of distinct nodes (No two nodes have the same data) and a value X. Count triplets in the list that sum to a given value X.
Problem Statement Understanding
Let’s try to understand the problem statement with the help of some examples.
According to the problem statement, we are given a sorted doubly linked list and a value X. We have to count all the triplets from this doubly linked list which have a sum equal to X.
If the doubly linked list is: head → 2 ←→ 3 ←→ 5 ←→ 7 ←→ 10 ←→ 13 and X = 15.
- From the linked list, we can see that there are only two possible triplets (2, 3, 10) and (3, 5, 7), which have the sum equal to 15. Rest all the possible triplets have sum not equal to X.
- So our count of triplets will be 2.
If the doubly linked list is: head → 1 ←→ 2 ←→ 3 ←→ 4 ←→ 5 and X = 9.
- In this case, out of all the possible triplets, the triplets with the sum equal to 9 will be (1, 3, 5), (2, 3, 4).
- So our count of triplets will be 2.
Some more examples
Sample Input 1 : head → 1 ←→ 2 ←→ 3 ←→ 4, X = 5
Sample Output 1: 0
There do not exist any triplet with sum equal to 5.
Sample Input 2: head → 1 ←→ 3 ←→ 5 ←→ 7 ←→ 9 ←→ 11, X = 15
Sample Output 2: 3
The triplets are (1, 3, 11), (3, 5, 7), (1, 5, 9).
Now I think from the above examples, the problem statement is clear. So let's see how we will approach it. Any Ideas?
- If not, it's okay. We will see in the next section thoroughly how we can approach this problem.
Let’s move to the approach section.
Approach 1
Our naive approach will be to traverse the linked list using three nested loops, and while traversing, for every triplet, we will check whether the triplet sums up to X or not:
- If it does sum up to X, then count this triplet combination.
- Else continue with the loops.
Time complexity: O(N3), Since we are using three nested loops to count triplet combinations.
Space complexity: O(1), As no extra space is used.
Next, we will see how we can reduce this complexity. Any ideas?
- If not, it's okay. We will see in the next section how we can reduce the time complexity.
Let’s move to a comparatively better approach than approach 1.
Approach 2
The idea is to create a hashmap with (key, value) pair to store the node’s data as the key and a pointer to that node as the value.
- Now, generate each possible pair of nodes from the linked list. For each pair of nodes, calculate the pair_sum(sum of data in the two nodes) and check whether (X-pair_sum) exists in the hash table or not.
- If it exists, then also verify that the two nodes in the pair are not the same as the node associated with (X-pair_sum) in the hash table and finally increment the count.
- Finally, we will be returning (count / 3) as our output as each of our triplet having sum equal to x has been counted 3 times during the above process.
Algorithm 2
- Initialize the count to zero.
- Now traverse through the linked list and store the node’s data as a key and a pointer to that node as the value in a map.
- Further, iterate over the linked list using two nested loops in which the first loop iterates from head to NULL using ptr1, and the second nested loop iterates from the next node of pointer of first loop (ptr1->next) to NULL.
- Now in the variable pair_sum, stores the sum of data of two pointers, i.e., ptr1->data + ptr2->data.
- Now check if the map contains (X - pair_sum) and also check if the two nodes in the pair are not the same as the node associated with a value (X-pair_sum) in the map.
- Now, if the condition satisfies, increment the count.
- Finally, we have to return (count / 3) as our output because each triplet has been counted 3 times during the above process.
Time Complexity: O(N2), Since we have traversed through the linked list twice for every Element.
Space Complexity: O(N), No extra space used.
Now we can see that this approach is far better than the previous approach, but we are also using extra space here. So next, we will try to see if we can somehow reduce the space complexity. Any Ideas?
- If not, it's okay. We will see in the next approach how we can do this in less space complexity.
Let's move to next approach.
Approach 3
This approach is an efficient one. Here the idea is to traverse the linked list from left to right, and for each node, count number of pairs in the list that sum up to the value (X - Current Node’s Data).
Let's see the algorithm.
Algorithm 3
Create a count named variable and initialize it to 0. This count variable will keep track of the total number of possible triplets in the linked list having sum X.
Start traversing the linked list from the head node using a pointer variable curr.
During traversal for each node, initialize two pointers begin and end to next of current node (curr->next) and end node of linked list respectively.
Count the number of pairs in list from begin to end having sum equal to (X - curr→data). Add the count of pairs to the variable count. Please visit the following article to see how we can find the pairs in a doubly linked list having a certain sum Check out this article.
Finally, after the traversal is over, the count variable will have the count of all possible triplets having sum equal to X.
Dry Run
Code Implementation
#include
using namespace std; /* Node structure of the doubly linked-list*/ struct Node { int data; struct Node* next, *prev; }; /* Using this function we will count the number of pairs having sum equal to given the given value */ int countValpairs(struct Node* begin, struct Node* end, int value) { int count = 0; while (begin != NULL && end != NULL && begin != end && end->next != begin) { if ((begin->data + end->data) == value) { count++; begin = begin->next; end = end->prev; } else if ((begin->data + end->data) > value){ end = end->prev; } else{ begin = begin->next; } } return count; } /* Using this function we will count the number of triplets in a list having sum equal to X */ int countXtriplets(struct Node* head, int X) { if (head == NULL){ return 0; } struct Node* current, *first, *last; int count = 0; last = head; while (last->next != NULL){ last = last->next; } for (current = head; current != NULL; current = current->next) { first = current->next; count += countValpairs(first, last, X - current->data); } return count; } /* Using this function we will add a new node at the beginning of doubly linked list */ void insertAtHead(struct Node** head, int data) { struct Node* temp = new Node(); temp->data = data; temp->next = temp->prev = NULL; if ((*head) == NULL){ (*head) = temp; }else{ temp->next = *head; (*head)->prev = temp; (*head) = temp; } } int main() { struct Node* head = NULL; insertAtHead(&head, 5); insertAtHead(&head, 4); insertAtHead(&head, 3); insertAtHead(&head, 2); insertAtHead(&head, 1); int X = 9; cout << "Count of triplets having sum equal to "<
Output
Count of triplets having sum equal to 9 is 2
Time Complexity: O(N2), Since we have traversed through the linked list twice for every element.
[forminator_quiz id="4903"]
So, In this blog, we have learned How to count triplets in a sorted doubly linked list whose sum is equal to a given value x. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List. | https://www.prepbytes.com/blog/linked-list/count-triplets-in-a-sorted-doubly-linked-list-whose-sum-is-equal-to-a-given-value-x/ | CC-MAIN-2022-21 | refinedweb | 1,355 | 76.56 |
"Hyper Terra" is a projection-mapped sculpture with an integrated projector, computer, and power supply. The sculpture is a mountain with simulated solar and lunar lighting that can be set up with any lat/long on Earth and a point in time. The graphics software has controls for time advancement towards the past or future, the long/lat on Earth, solar/lunar positioning, light color, and more. The result is both a sculpture and a dynamic visual timepiece.
Artist and Author: Gabriel Labov Dunne (www)
Title: "Hyper Terra"
Instructable Link:
Flickr Gallery:
Description: An abstract landscape is illuminated by light and shadow generated by sun and moon positions from any time and place on Earth. Graphics are projection-mapped onto the landscape by an embedded projector and computer, powered by an integrated power supply.
Medium: MDF, Birch Plywood, Aluminum, LCD Projector, Embedded Computer, Power Supply, Custom graphics software written in C++
Tooling: CNC, Water Jet, Laser Cutter, Wood Shop, Metal Shop
Design Software Used: McNeel Rhino/Grasshopper, Autodesk Inventor/HSM, Autodesk Maya
Step 1: Concept
To execute this concept, I began sketching ideas for dioramas and miniature scenes. I also had to include an embedded computer and projector to somewhere to augment the time and place of a scene. I started out with boxy-like diorama constructions and varied all the way to craggily peaks and towers.
In my research I was also interested in traditional Chinese model landscapes call 山水 盆景, or “Penjing”, which represent small landscape models and/or living sculptures. Sometimes these sculptures include practical effects such as real water, plants, smoke, and lighting. One thing I especially appreciated about these small landscapes is that you could view it from all angles. I felt this was extremely important, so I ditched any ideas that involved putting the project in a box.
Goals
- The projection should work decently when there is bright ambient light.
- The object should be viewable from all angles.
- The projection computer should have a fast start-up time, allowing the sculpture to be turn on and off quickly seamlessly.
- Software settings should be easily set an controlled from a tablet or phone, or other seamless interface.
Software Ideas
- Color gradient of the sky.
- Cloud layer and atmosphere, such as fog
- Color temperature (Kelvin) throughout the day.
- Colors and texture themes that could represent seasonal foliage, rain, and snow.
- A body of water so I can play with the aesthetics of specular reflections of the sun and the moon.
- Calendar events and cycles.Movement of the Earth the sun, the moon, and the stars, based on actual astrological positions, using and ephemeris table or pull from the internet.
- Night-time motifs. It would be cool to include tiny roads with car headlights, traversing through the mountains, or other urban lighting effects.
Because the software is ephemeral, and the sculpture is physical, it's easy to have many visual ideas before committing to them as I can upgrade the software at any time.
Step 2: Landscape Design
For my landscape, I created an object with Rhino/Grashopper. Vertices define the shape, and then I used the Delunay node in Grasshopper to generate the mesh.
I designed the form keeping in mind the amount of labor it would be to hand map each vertex later, which is basically projection mapping ground-zero. If other helpful mapping techniques aren't available (see OpenCV, Structured Light), one can always place vertices by hand. I created a shape with less than 100 points, so even if each vert took a minute (unlikely), at most it would take less than 2 hours. I planned to have the projector locked to the form, so I only have to do this mapping once.
I used this same landscape model my entire residency, it was interesting to see it evolve. I never had the chance or inspiration to design a new object, as this one just worked. They software works with any object, and the base is modular, so I can make new designs in the future and they can fit right in to the system.
Step 3: 3D Printing Test Models
I 3D printed some mini models with a trusty MakerBot Duo for projection tests.
A really interesting thing happened with some old ABS plastic filament that had been sun-bleached and discolored, resulting in some landscape striations that resembled real stoned and sediment layers.
Step 4: Raspberry Pi Projection-Mapping Setup
I zip-tied a raspberry pi to a pico projector, and mounted the whole rig on a tripod. I created a simple mesh-mapping projection software with OpenFrameworks, and then projected upon the 3D printed objects.
A cool thing about the equipment setup is that I could power the RPi from the USB port on the projector, leaving me with only one power plug.
I also really liked how the semi-transparent PLA played with the light. It sometimes felt like the objects were illuminated from within.
This step about using the Raspberry Pi as a mini-mapping became its own Instructable: Mini Projection Mapped Sculpture.
Software Screencap:
Mapping Result:
In this software, I simply had a virtual lights revolving around an object in sinusoidal patterns. There was no positioning based on the sun or the moon at this point.
As far as the projection quality, while I love the form factor of the little DLP pico projectors, I much prefer using LCD technology because it gives a much better image when documenting on video. I'm still searching for a bright, LCD-based pico projector with a small form factor. Due to crossover conversations I had with some otherawesomeAiR's at Pier 9, I see the potential mangling a consumer LCD projector to reduce the form factor, or potentially fabricate my own, all the way down to the lenses.
For an extreme example of how crazy DLP banding can get, to the point where it can be utterly psychedelic, check this out:
Step 5: Create Toolpaths for CNC MIlling
I had grown to like this little landscape and wanted it to be a little bit larger than the 3D printed tests, so I prepared the sculpture for milling.
I used Autodesk Inventor HSM to generate my tool paths for the 5-Axis DMS router at Pier9. As a material, MDF is great for testing, and ultimately I used it for my final piece as well.
Step 6: Stock Prep and Layup
I cut everything to the material bounds with the table saw, and then created Layer-cakes of MDF panels and wood glue to both sides so just a little bit seeps out the sides, clamp, and set to dry.
Step 7: Roughing Passes
The roughing passes took about 20 to 30 minutes.
Ridiculous amounts of dust.
The mountain is revealed.
Step 8: Clean Up Between Passes
It took a few tries to get my feeds and speeds right with the MDF layups. I was looking for the right combination of speed and chip size. Huge thanks to Dan, Pier 9 CNC Master Chief.
Sometimes, opening the doors of the DMS reveals a ridiculous pile of chips, resembling a fuzzed-out MD5 dust mountain. This is before we had the fancy dust-collection integrated into the DMS.
Cleaning up the chips and dust was felt like uncovering an archeological relic.
Since these photos were taken, I have definitely improved my CNC technique and I now pause the pass to clean up so I can see the tool head operating. These photos were among the first I took when learning the ins and outs of the DMS.
Step 9: Finishing Passes
Finishing passes were done with a 1/2" round bit and averaged 30 to 40 minutes.
Step 10: Milling Strategies
Step 11: Separately-Milled Mountain Peaks
I had to work out a few tooling strategies in order to get the sharpest edges possible with the milling process. Some methods involved milling the mountain peaks separately so I could use shorter, finer bits in the finishing passes.
After milling, I had to clean them from the stock before attaching them to the mountain base with wood glue.
I first used the band saw to separate them from the rest of the stock, and then with a combination of temporary band-saw jigs and the belt-sander, were made to fit seamlessly.
Step 12: Sanding, Prepping for Finish
Going through all the grits of sandpaper to get the finish silky smooth, and used a tack cloth to remove fine dust.
Step 13: Finishing
I used a matte aerosol primer and sealer and went layer by layer in the paint booth.
Sand, prime, sand, prime, sand, prime. Going for that "Impossibly smooth" feel.
It was a challenge to hand-sand the sculpture and retain those crisp, sharp edges. In the end, they got a little rounded.
Due to the softness of MDF, occasionally there would be toolpath artifacts that i wouldn't realize until the finish stage. I used Golden Semi-Gloss Modeling Paste (and my Clipper Card, the perfect applicator) to fill in the cracks inbetween sanding.
When the finish began to resemble the polygons in the graphics software, I knew I was getting somewhere.
Step 14: Landscape Series
Because I used the same mesh throughout all the fabrication, I could compare differences in machining processes.
Step 15: Software Ephemeris With Python and the PyEphem Lib
I needed a Fundamental Ephemeris for this piece to track the Sun and the Moon so I don't need to be connected to the internet. A fellow AiR, Robb Godshaw, recommended I check out PyEphem, a Python library that is based on XEphem, an astronomical software ephemeris.
With ephemScript.py, we can query the Sun and Moon positions which return altitude and azimuth which are then called and converted to spherical coordinates from C++ to place the lights in the scene.
def getSunAzimuth(time) def getSunAltitude(time) def getMoonAzimuth(time) def getMoonAltitude(time)
Step 16: Graphics Software in C++
The graphics software at minimum needs the following features:
- Mesh (OBJ) Importing
- Dynamic Lighting Model with Shadows
- Manual Per-Vertex positions
- Camera (Eye) positioning
- Object positioning
- Ability to Save/Load Camera position, obj position, and obj vertex settings
- Include Python library to utilize PyEphem for sun/moon tracking.
- Hook light positions into Sun and Moon positions queried from the ephem script.
- Include OSC Library for the ability to interface with a control surface.
These are the bare features needed for this project to work. Every other cool software goal I had in my concept can be added later. I coded a solution that supports all these features on my linux fork of Cinder that compiles on the TK1.
The entire source code is hosted on my GitHub:
For the light renderer, I ended up utilizing a deferred rendering library that supports multiple lights, screen space ambient occlusion, and shadows.
Step 17: Embedded Computer
For my embedded computer I used the Nvidia Jetson TK1. This tiny 5"x5" computer supports full OpenGL 4.4, OpenCV, comes with Ubuntu Desktop pre-installed, and has an external power supply. I wrote a TK1 Setup Guide as I set up the computer, which includes the methods for auto-booting the software and setting the hardware clock.
For my TK1 case, I laser-cut Phillip Burgess's clean and simple SneezeGuard design on Thingaverse.
It is connected via HDMI to Epson PowerLite 1761W 3LCD projector (unpictured here, but seen in later steps).
Step 18: Connecting Graphics to a Controller
I used Liine Lemur running on my iPod touch to control the graphics software wirelessly w/OSC. TouchOSC is another app that works for this purpose.
Step 19: Base Design
Back into Rhino to design the base. I came up with a design that allowed the piece to be viewed from all angles by using four metal structural bars to hold a "crown" which contains the projector and the computer.
For this design process I should have used a parametric modeling program like Inventor or SolidWorks. What started as a "simple" design became more complex than I anticipated, and by then I felt I was already so far deep into my design in Rhino that I just went with it. Had I used a parametric program for this step, I could have adjusted material thicknesses and scale without having to manually modify the object, which is something that happened a lot.
I've included the final object as a Rhino5 .3dm format for you to explore.
Step 20: Frame Prototyping: Plinth
I went through a few iterations to create a structure for the projector and computer. I started with a basic cubic plinth and right-angled steel to get scale and projector-throw correct. This allowed me projector throw right with my model of projector.
I used the Projector Central Projection Calculator for the model of projector to give me the throw distance and image size.
Conceptually I originally had a bunch of wild ideas to make some craggily peaks and strange formations, but projection-alignment was the priority at this point.
Step 21: Cutting Vertical Panels
My design was that only 4 of the base panels had mitre angles, and the other 4 were right-angle cuts. So, I laser-etched a template to cut on the table saw.
Why didn't I just cut the panels on the laser cutter? Had I done that, I would have had a charred edge which I would have to sand so I could get a good glue connection, which has the potential to get entire shape out of alignment. It's really tricky to make a glue joint on a burnt edge.
Also, in roughly the same amount of time, I can create some table saw jigs and do it with good enough precision.
Step 22: Attaching Vertical Panels to Base
I brad-nailed a lip for each panel and clamped them so they rested precisely on the base while the glue set.
Step 23: Adding Adjustable Feed
Adding threaded inserts in the base to allow me to use adjustable leveling-feet.
Step 24: Waterjetting Mitre Panels
With Pier9's WaterJet, I was able to CNC cut the remaining 4 mitred panels from plywood with the A-Jet 5-Axis waterjet head. I could have made a table saw jig for this as well, but the prospect of cutting mitres on the water jet was too tempting to pass up, and they turned out so clean! I mean, when you have access to a water jet...
Cutting material on the water jet invariably gets it wet, but my parts were fine after washing the garnet off and letting them dry. Pre-finishing the wood with polyurethane or wax is a good technique to keep the garnet from staining the wood, which it definitely does. I didn't care too much about this as I planned to finish it with paint.
I imported my shapes to Omax Intellicam/Make/Layout following fellow AiR qDot's great Instructable on making 5-axis cuts on the waterjet.
Step 25: Attaching Mitred Panels
I created a series of wedges that I brad nailed/glued onto the mitred panels, and then slipped them into the vertical uprights that were already attached to the base. Gravity and clamps held the panels in securely while the glue set overnight.
Step 26: Fabricating the Structural Bars
Back to the WaterJet to cut the support bars out of 1/4" thick aluminum stock, and filing off the tabs. I also drilled and tapped threads into two of the bars, which will be used later for connecting power.
Step 27: Creating Structural Bar Inserts
I then bradding/gluing in block supports made from 3/4" ply on the table saw so the bars could slide in and be held into place by gravity.
Step 28: Adding Mitred Trim
I measured the angles in CAD and then made some trim on the mitre saw out of 3/4" ply so it was flush to the base, and the bars.
Getting the fit right by "feel":
Step 29: Bars and Trim
When the trim finished drying I was able to test the fit of the bars.
Step 30: Crown Design
The design for the crown is made from plywood, and rests on top of the aluminum bars, and is held into place with gravity and wooden guides. It holds the projector, the power inverter, and the computer. The light from the projector reflects downwards by bouncing off a first-surface mirror, through a hole in an acrylic mask.
I designed base panels of the crown in Rhino, and I designed the mirror assembly on the fly.
Step 31: Fabricating Crown Panels
Based on my previous success with cutting the base panels on the WaterJet, I used the same technique for the crown panels.
Warning to headphones users: Loud and abrasive audio.
Step 32: Assembling the Crown
Because the panels were not 90 degrees, I had to do a special dado-slot for the base of the grown. I built a table saw jig and made an angled dado in each panel to fit the base.
Then I made a glue-up jig and brad-nailed and clamped the entire assembly together while the glue set. In order to test fit, I clamped it too the upright bars so I could get a feel for the shape.
Step 33: Mirror Assembly
I designed a mirror assembly so I could have the projector sitting flat with the image shining downwards.
I created a mirror assembly with a first surface mirror that allows me to adjust the position of the mirror when aligning the projection.
I dado'd slots into some plywood. I could have used a router table for this, but I personally feel much safer, and therefore more precise doing dado's on the table saw (it has a Saw Stop), rather than the router table.
I used long bolts and wing nuts to attach the assembly to the crown, which gives the ability to adjust the reflection angle.
Step 34: Projector Mask
In order to create a mask, I plugged the projector into a ceiling outlet and set it inside the crown assembly, and got the mirror calibrated. When I turned it on, and set up the mirror assembly, I taped a piece of paper underneath to trace out the mask with pencil.
Once I had the trace, I created the shape in Adobe Illustrator and laser-cut the mask out of 1/8" white acrylic.
I used a series of neodymium magnets so there would be no visible fasteners, and as a bonus I can remove the mask easily if I ever need to access the projector from the underside.
Also during this step, I created supports for the sculpture in the base. After a little trimming of the edges, I made it fit flush in the square recess.
Step 35: Powering the Electronics
The entire thing needs to be powered from one plug, and all the electronics were on top of the sculpture in the crown. These things need powered:
- 350w LCD Projector: Epson PowerLite 1761w
- ~5w Computer: NVidia TK1
- ~5w Wireless Router: TP-Link TL-WR720N, OpenWRT Wiki
The inspiration for routing power through the metal bars was from a suggestion by a fellow AiR, Paolo Salvagione. He suggested I explore converting the signal to 12v DC and run them up the metal support rails. I had to tap threads the threads in the top and bottom of two of the bars so I could use molex connectors to wire them to the power supply in the base, and connect them to an inverter in the crown.
For the power chain I used:
- Generic 12v DC 60a 720w Power Supply (found on eBay)
- 750w A/C Inverter w/2 outlets (found on Amazon)
- 12-gauge insulated cable
- Molex connectors
At first I was actually wary of pursuing this method because I couldn't help but to think that someone would get shocked when touching both the bars at the same time. It wasn't until I physically tested it and touched both bars at the same time that I confirmed for my brain that you won't get shocked, and the entire thing works flawlessly. The human body is an insulator and can't complete the circuit better than the metal bars can. Also, if you were to somehow short the circuit, the fuse on the power supply or the inverter would blow before shocking you.
Step 36: Installing the Electronics
I built an interior shelf for the power supply, and crammed all the other stuff into the crown before trimming up the wires.
I connected the leads of the A/C Inverter to the two bars that I marked positive and negative, which are diagonal opposite from each other.
Then, down in the base, I attached leads from the pos/neg bars to the pos/neg leads on the power supply.
Step 37: Priming
I refinished and primed everything white with the exception of the metal parts.
Step 38: Projection Mapping Graphics Alignment
After getting everything installed and powered up for the first time (really exciting!). It's time to align the projection graphics.
As I was getting the software working, I had a keyboard and mouse plugged in and haphazardly hanging from a powered USB hub. I use a mouse to tweak the vertices as I haven't yet figured out an good way to precisely drag vertices around with a touch screen interface. Fortunately this is a one-time step because the projector and the object are locked down.
Manual Vertex-Mapping Time Lapse
I had to do a few changes to the code as I was getting it set up. It was so cool to see the linux terminal cascading the compiler output over the mountains surface, followed by crisp, high-framerate OpenGL graphics.
A walkthrough of the setup at the Pier's Studio9.
Having an LCD projector really makes for a huge quality difference when filming, even when shooting with my iPod camera. No banding.
Step 39: Finishing the Bars and Final Assembly
I sanded and polished the aluminum bars and softened their edges.
I figured out that I could also use the bars as a lever to remove the sculpture and get access to the base like this:
Step 40: Projection Graphics Controls and Settings
As I mentioned in previous steps, I used the Lemur app by Liine for my iPod touch for the graphics controller. I've attached my control scheme.
There are a lot of fun graphic modes to play with. Here's a demo of some of the settings.
Step 41: Complete!
I've hit all the base milestones I originally set out to do, and it definitely feels "done". But, is it ever really done.... ?
Some things I'm still working on:
- Apply some sort of finish to the primed white surface, as any time I handle it I'm getting it dirty.
- Create a cap for the crown to cover the unsightly electronics. I'll probably add an acyclic cap with vents.
- Some software tweaks, of course (endless!)
Special thanks to all the other AiR's and everyone at Pier9 for being so incredibly supportive and inspiring during the making of this project. I had the freedom to let my design to evolve as I worked on it, and it was so great to get such valuable input and feedback along the way to support my own process of learning by making.
If you have any feedback or questions, I'll try to respond in the comments.
(Video coming soon!)
Thanks for looking!
10 Discussions
2 years ago
amazing, me and my friend are going to make it at our school
3 years ago on Introduction
awesome
3 years ago on Introduction
Amaizing project.
3 years ago on Step 3
Whoa. Interesting bit about the sun-bleached ABS -- it's quite beautiful!
3 years ago on Introduction
truly amazing process.
3 years ago on Introduction
congrats Gabe! Looks so great man! Love the design & process!
3 years ago
so difficultT_T
3 years ago on Introduction
wow!
3 years ago
this is so beautiful
3 years ago on Introduction
Very, very cool project! I really enjoyed reading your process in making this. | https://www.instructables.com/id/Hyper-Terra/ | CC-MAIN-2018-51 | refinedweb | 4,060 | 68.2 |
info_outline
Solutions will be available when this assignment is resolved, or after a few failing attempts.
Time is over! You can keep submitting you assignments, but they won't compute for the score of this quiz.
Pretty Results Decorator
Implement a
@pretty_result decorator that changes the result of any function, returning the result plus a pretty message. Example, the function
sum(1, 2) should return
3. If applied
@pretty_result it should return
"The result of the function 'sum' is: 3".
Test Cases
test subtract function - Run Test
def test_subtract_function(): @pretty_result def subtract(x, y): return x - y assert subtract(13, 8) == "The result of the function 'subtract' is: 5" | https://learn.rmotr.com/python/advanced-python-programming/advanced-python-features/pretty-results-decorator | CC-MAIN-2018-22 | refinedweb | 109 | 56.25 |
In this episode we'll be looking at dynamic backends. Dynamic backends in Varnish allow backends to be defined on the fly, instead of being predefined. Basically imagine if instead of connecting varnish to one specific origin server, you enable it to connect to different ones as required, say multiple servers.
Traditionally backends in Varnish are defined in the VCL file using a static backend definition. Host and port information is also static, and any DNS name that is used will be resolved at compile time:
backend default { .host = "server1.example.com"; .port = "80"; }
The same applies when using multiple backends, to perform load balancing. The association between the backend and the director object in charge of load balancing is also done statically.
This approach has some limitations. Because DNS is resolved at compile time, any runtime changes in terms of DNS are not noted by Varnish. If your IP address changes while Varnish is running, it will not know. Also, a hostname can only have a single IP address. If your hostname uses multiple IP addresses for DNS-based load balancing, that is out of the question. And lastly, it is not possible to define ad-hoc backends using runtime information.
And that's exactly why dynamic backends come into play, through Varnish Enterprise’s goto VMOD you can define them, and they offer some clear benefits.
First of all, you can use DNS records with multiple IP addresses and perform DNS-based load balancing. If DNS records tend to change every now and then, that is also supported. So if you have a dynamic inventory, potentially in the cloud, VMOD goto is the perfect module for you.
And finally, you can define backends at runtime and use all kinds of input to locate the backend. Here's a code example that shows you how to get started with DNS-based load balancing:
import goto; { backend default none;
sub vcl_init {
new apipool = goto.dns_director ("backend.example.com"); }
sub vcl_recv {
set req.backend_init = apipool.backend();
}
You import the goto VMOD, you still have to define the static backend, but in this case, it's an empty one. And then you initialize the director object through goto.dns_director. Instead of defining it statically, whatever IP address is linked to backend.example.com is used, and can be refreshed.
If multiple IP addresses are used, the director object will cycle through them, every time you call APIpool.backend.
Here's another code example where we define an ad-hoc backend:
import goto;
backend default none;
sub vcl_backend_fetch {
set bereq.backend = goto.dns_backend (bereq.http.host);
}
We can do that using goto.DNS_backend and whatever hostname is entered will be resolved. It could use runtime variables, or could even use a string. Whatever hostname is returned will be resolved to its IP address. If multiple IP addresses are used, we will cycle through them. | https://info.varnish-software.com/blog/two-minutes-tech-tuesdays-dynamic-backend | CC-MAIN-2022-27 | refinedweb | 481 | 56.66 |
GNU Octave Version 1
Summary of important user-visible changes
News for version 6 5 4.4 4.2 4 3.8 3.6 3.4 3.2 3 2 1 (Release History)
- Summary of important user-visible changes
- Version 1.1.1
- Version 1.1.0
- Version 1.0
- Version 0.83
- Version 0.82
- Version 0.81
- Version 0.80
- Version 0.79
- Version 0.78
- Version 0.77
- Version 0.76
- Version 0.75
- Version 0.74
- Version 0.73
- Version 0.72
- Version 0.71
- Version 0.70
- Version 0.69
- Version 0.68
- Version 0.67
- Version 0.66
- Version 0.63
- Version 0.61
- Version 0.57
- Version 0.56
- Version 0.55
- Version 0.52
- Version 0.51
- Version 0.50
Version 1.1.1
* New built-in variables, default_return_value and define_all_return_values. If define_all_return_values is set to "false", Octave does not do anything special for return values that are left undefined, and you will get an error message if you try to use them. For example, if the function function [x, y] = f () y = 1; endfunction is called as octave:13> [a, b] = f () Octave will print an error message for the attempt to assign an undefined value to `a'. This is incompatible with Matlab, which will define the return variable `x' to be the empty matrix. To get the Matlab-like behavior, you can set the variable define_all_return_values to "true" (the default is "false") and default_return_value to `[]' (the default). Then, any return values that remain undefined when the function returns will be initialized to `[]'. If the function is called without explicitly asking for an output, it will succeed. This behavior is compatible and unchanged from previous versions of Octave. * New built-in variable suppress_verbose_help_message. If set to "true", Octave will not add additional help information to the end of the output from the help command and usage messages for built-in commands. The default value is "false". * New built-in variable PS4 is used as the prefix of echoed input (enabled with the --echo-input (-x) option). * The function size() now accepts an optional second argument. * Output from `save - ...' now goes through the pager. * The break statement may also be used to exit a function, for compatibility with Matlab. * The directory tree for installing Octave is now closer to conforming with the current GNU standards. * More bug fixes.
Version 1.1.0
* Octave now requires g++ 2.6.3 or later. This change is necessary to make template instantiations cleaner, and to avoid having to have special cases in the code for earlier versions of gcc. * A new data structure type has been added. The implementation uses an associative array with indices limited to strings, but the syntax is more like C-style structures. here are some examples of using it. Elements of structures can be of any type, including structures: octave:1> x.a = 1; octave:2> x.b = [1, 2; 3, 4]; octave:3> x.c = "string"; octave:4> x x = <structure: a b c> octave:5> x.a x.a = 1 octave:6> x.b x.b = 1 2 3 4 octave:7> x.c x.c = string octave:8> x.b.d = 3 x.b.d = 3 octave:9> x.b x.b = <structure: d> octave:10> x.b.d x.b.d = 3 Functions can return structures: octave:1> a = rand (3) + rand (3) * I; octave:2> function y = f (x) > y.re = real (x); > y.im = imag (x); > endfunction octave:3> f (a) ans = <structure: im re> octave:4> ans.im ans.im = 0.093411 0.229690 0.627585 0.415128 0.221706 0.850341 0.894990 0.343265 0.384018 octave:5> ans.re ans.re = 0.56234 0.14797 0.26416 0.72120 0.62691 0.20910 0.89211 0.25175 0.21081 Return lists can include structure elements: octave:1> [x.u, x.s, x.v] = svd ([1, 2; 3, 4]) x.u = -0.40455 -0.91451 -0.91451 0.40455 x.s = 5.46499 0.00000 0.00000 0.36597 x.v = -0.57605 0.81742 -0.81742 -0.57605 octave:8> x x = <structure: s u v> This feature should be considered experimental, but it seems to work ok. Suggestions for ways to improve it are welcome. * Octave now supports a limited form of exception handling modelled after the unwind-protect form of Lisp: built-in variable do_fortran_indexing even if an error occurs while performing the indexing operation. save_do_fortran_indexing = do_fortran_indexing; unwind_protect do_fortran_indexing = "true"; elt = a (idx) unwind_protect_cleanup do_fortran_indexing = save_do_fortran_indexing; end_unwind_protect Without unwind_protect, the value of do_fortran_indexing would not be restored if an error occurs while performing the indexing operation because evaluation would stop at the point of the error and the statement to restore the value would not be executed. * Recursive directory searching has been implemented using Karl Berry's kpathsea library. Directories below path elements that end in // are searched recursively for .m files. * Octave now waits for additional input when a pair of parentheses is `open' instead of giving an error. This allows one to write statements like this if (big_long_variable_name == other_long_variable_name || not_so_short_variable_name > 4 && y > x) some (code, here); without having to clutter up the if statement with continuation characters. * Continuation lines are now allowed in string constants and are handled correctly inside matrix constants. * Both `...{whitespace}\n' and `\{whitespace}\n' can be used to introduce continuation lines, where {whitespace} may include spaces, tabs and comemnts. * The script directory has been split up by topic. * Dynamic linking mostly works with dld. The following limitations are known problems: -- Clearing dynamically linked functions doesn't work. -- Dynamic linking only works with dld, which has not been ported to very many systems yet. -- Configuring with --enable-lite-kernel seems to mostly work to make nonessential built-in functions dynamically loaded, but there also seem to be some problems. For example, fsolve seems to always return info == 3. This is difficult to debug since gdb won't seem to allow breakpoints to be set inside dynamically loaded functions. -- Octave uses a lot of memory if the dynamically linked functions are compiled with -g. This appears to be a limitation with dld, and can be avoided by not using -g to compile functions that will be linked dynamically. * fft2 and ifft2 are now built-in functions. * The `&&' and `||' logical operators are now evaluated in a short-circuit fashion and work differently than the element by element operators `&' and `|'. See the Octave manual for more details. * Expressions like 1./m are now parsed as 1 ./ m, not 1. / m. * The replot command now takes the same arguments as gplot or gsplot (except ranges, which cannot be respecified with replot (yet)) so you can add additional lines to existing plots. * The hold command has been implemented. * New function `clearplot' clears the plot window. The name `clg' is aliased to `clearplot' for compatibility with Matlab. * The commands `gplot clear' and `gsplot clear' are equivalent to `clearplot'. (Previously, `gplot clear' would evaluate `clear' as an ordinary expression and clear all the visible variables.) * The Matlab-style plotting commands have been improved. They now accept line-style arguments, multiple x-y pairs, and other plot option flags. For example, plot (x, y, "@12", x, y2, x, y3, "4", x, y4, "+") results in a plot with y plotted with points of type 2 ("+") and color 1 (red). y2 plotted with lines. y3 plotted with lines of color 4. y4 plotted with points which are "+"s. the help message for `plot' and `plot_opt' provide full descriptions of the options. * NaN is now dropped from plot data, and Inf is converted to a very large value before calling gnuplot. * Improved load and save commands: -- The save and load commands can now read and write a new binary file format. Conversion to and from IEEE big and little endian formats is handled automatically. Conversion for other formats has not yet been implemented. -- The load command can now read Matlab .mat files, though it is not yet able to read sparse matrices or handle conversion for all data formats. -- The save command can write Matlab .mat files. -- The load command automatically determines the save format (binary, ascii, or Matlab binary). -- The default format for the save command is taken from the built-in variable `default_save_format'. -- The save and load commands now both accept a list of globbing patterns so you can easily load a list of variables from a file. -- The load command now accepts the option -list, for listing the variable names without actually loading the data. With -verbose, it prints a long listing. -- The load command now accepts the option -float-binary, for saving floating point data in binary files in single precision. * who and whos now accept a list of globbing patterns so you can limit the lists of variables and functions to those that match a given set of patterns. * New functions for manipulating polynomials compan -- companion matrix corresponding to polynomial coefficients conv -- convolve two vectors deconv -- deconvolve two vectors roots -- find the roots of a polynomial poly -- characteristic polynomial of a matrix polyderiv -- differentiate a polynomial polyinteg -- integrate a polynomial polyreduce -- reduce a polynomial to minimum number of terms polyval -- evaluate a polynomial at a point polyvalm -- evaluate a polynomial in the matrix sense residue -- partial fraction expansion corresponding to the ratio of two polynomials * New functions for manipulating sets create_set -- create a set of unique values complement -- find the complement of two sets intersection -- find the intersection of two sets union -- find the union of two sets * New elementary functions: acot acoth acsc acsch asec asech cot coth csc csch log2 sec sech * New special functions: beta -- beta function betai -- incomplete beta function gammai -- incomplete gamma function * New image processing functions: colormap -- set and return current colormap gray -- set a gray colormap gray2ind -- image format conversion image -- display an image imagesc -- scale and display an image imshow -- display images ind2gray -- image format conversion ind2rgb -- image format conversion loadimage -- load an image from a file ntsc2rgb -- image format conversion ocean -- set a color colormap rgb2ind -- image format conversion rgb2ntsc -- image format conversion saveimage -- save an image to a file * New time and date funcitons: tic -- set wall-clock timer toc -- get elapsed wall-clock time, since timer last set etime -- another way to get elapsed wall-clock time cputime -- get CPU time used since Octave started is_leap_year -- is the given year a leap year? * Other new functions: bug_report -- submit a bug report to the bug-octave mailing list toascii -- convert a string to a matrix of ASCII character codes octave_tmp_file -- generate a unique temporary file name undo_string_escapes -- replace special characters in a string by their backslash forms is_struct -- determine whether something is a structure data type feof -- check EOF condition for a specified file ferror -- check error state for a specified file fread -- read binary data from a file fwrite -- write binary data to a file file_in_path -- check to see if named file exists in given path kbhit -- get a single character from the terminal axis -- change plot ranges hist -- plot histograms diary -- save commands and output to a file type -- show the definition of a function which -- print the type of an identifier or the location of a function file isieee -- Returns 1 if host uses IEEE floating point realmax -- Returns largest floating point number realmin -- Returns smallest floating point number gcd -- greatest common divisor lcm -- least common multiple null -- orthonormal basis of the null space of a matrix orth -- orthonormal basis of the range space of a matrix fft2 -- two-dimensional fast fourier transform ifft2 -- two-dimensional inverse fast fourier transform filter -- digital filter fftfilt -- filter using fft fftconv -- convolve to vectors using fft sinc -- returns sin(pi*x)/(pi*x) freqz -- compute the frequency response of a filter * The meaning of nargin (== args.length ()) in built-in functions has been changed to match the meaning of nargin in user-defined functions. * Variable return lists. Octave now has a real mechanism for handling functions that return an unspecified number of values, so it is no longer necessary to place an upper bound on the number of outputs that a function can produce. Here is an example of a function that uses the new syntax to produce n values: function [...] = foo (n) for i = 1:n vr_val (i * x); endfor endfunction * New keyword, all_va_args, that allows the entire list of va_args to be passed to another function. For example, given the functions function f (...) while (nargin--) disp (va_arg ()) endwhile endfunction function g (...) f ("begin", all_va_args, "end") endfunction the statement g (1, 2, 3) prints begin 1 2 3 end all_va_args may be used more than once, but can only be used within functions that take a variable number of arguments. * If given a second argument, svd now returns an economy-sized decomposition, eliminating the unecessary rows or columns of U or V. * The max and min functions correctly handle complex matrices in which some columns contain real values only. * The find function now handles 2 and 3 output arguments. * The qr function now allows computation of QR with pivoting. * hilb() is much faster for large matrices. * computer() is now a built-in function. * pinv() is now a built-in function. * The output from the history command now goes through the pager. * If a function is called without assigning the result, nargout is now correctly set to 0. * It is now possible to write functions that only set some return values. For example, calling the function function [x, y, z] = f () x = 1; z = 2; endfunction as [a, b, c] = f () produces: a = 1 b = [](0x0) c = 2 * The shell_cmd function has been renamed to system (the name shell_cmd remains for compatibility). It now returns [output, status]. * New built-in variable `OCTAVE_VERSION'. Also a new function, version, for compatibility with Matlab. * New built-in variable `automatic_replot'. If it is "true", Octave will automatically send a replot command to gnuplot each time the plot changes. Since this is fairly inefficient, the default value is "false". * New built-in variable `whitespace_in_literal_matrix' allows some control over how Octave decides to convert spaces to commas in matrix expressions like `[m (1)]'.. * Line numbers in error messages for functions defined in files and for script files now correspond to the file line number, not the number of lines after the function keyword appeared. * Octave now extracts help from script files. The comments must come before any other statements in the file. * In function files, the first block of comments in the file will now be interpreted as the help text if it doesn't look like the Octave copyright notice. Otherwise, Octave extracts the first set of comments after the function keyword. * The function clock is more accurate on systems that have the gettimeofday() function. * The standard output stream is now automatically flushed before reading from stdin with any of the *scanf() functions. * Expanded reference card. * The Octave distribution now includes a frequently asked questions file, with answers. Better answers and more questions (with answers!) are welcome. * New option --verbose. If Octave is invoked with --verbose and not --silent, a message is printed if an octaverc file is read while Octave is starting. * An improved configure script generated by Autoconf 2.0. * Lots of bug fixes.
Version 1.0
- C-style I/O functions now handle files referenced by name or by number more consistently.
Version 0.83
Clearing the screen doesn’t reprint the prompt unnecessarily.
The operations
<complex scalar> OP <real matrix>for
OP == +, -, *, or ./no longer crash Octave.
More portability and configuration fixes.
Version 0.82
* Octave now comes with a reference card. * The manual has been improved, but more work remains to be done. * The atanh function now works for complex arguments. * The asin, acos, acosh, and atanh functions now work properly when given real-valued arguments that produce complex results. * SEEK_SET, SEEK_CUR, and SEEK_END are now constants. * The `using' qualifier now works with gplot and gsplot when the data to plot is coming directly from a file. * The strcmp function now works correctly for empty strings. * Eliminated bogus parse error for M-files that don't end with `end' or `endfunction'. * For empty matrices with one nonzero dimension, the +, -, .*, and ./ operators now correctly preserve the dimension. * Octave no longer crashes if you type ^D at the beginning of a line in the middle of defining a loop or if statement. * On AIX systems, Back off on indexing DiagArray via Proxy class to avoid gcc (or possibly AIX assembler?) bug. * Various other bug and portability fixes.
Version 0.81
* Octave no longer dumps core if you try to define a function in your .octaverc file. * Fixed bug in Array class that resulted in bogus off-diagonal elements when computing eigenvalue and singular value decompositions. * Fixed bug that prevented lsode from working on the SPARCstation, at least with some versions of Sun's f77. This bug was introduced in 0.80, when I changed LSODE to allow the user to abort the integration from within the RHS function. * Fixed bug that prevented global attribute of variables from being saved with save(), and another that prevented load() from working at all.
Version 0.80
* I have started working on a manual for the C++ classes. At this point, it is little more than a list of function names. If you would like to volunteer to help work on this, please contact bug-octave@bevo.che.wisc.edu. * The patterns accepted by the save and clear commands now work like file name globbing patterns instead of regular expressions. I apologize for any inconvenience this change may cause, but file name globbing seems like a more reasonable style of pattern matching for this purpose. * It is now possible to specify tolerances and other optional inputs for dassl, fsolve, lsode, npsol, qpsol, and quad. For each of these functions, there is a corresponding function X_options, which takes a keyword and value arguments. If invoked without any arguments, the X_options functions print a list of possible keywords and current values. For example, npsol_options () prints a list of possible options with values, and npsol_options ("major print level", 10) sets the major print level to 10. The keyword match is not case sensitive, and the keywords may be abbreviated to the shortest unique match. For example, npsol_options ("ma p", 10) is equivalent to the statement shown above. * The new built-in variable save_precision can be used to set the number of digits preserved by the ASCII save command. * Assignment of [] now works in most cases to allow you to delete rows or columns of matrices and vectors. For example, given a 4x5 matrix A, the assignment A (3, :) = [] deletes the third row of A, and the assignment A (:, 1:2:5) = [] deletes the first, third, and fifth columns. * Variable argument lists. Octave now has a real mechanism for handling functions that take an unspecified number of arguments, so it is no longer necessary to place an upper bound on the number of optional arguments that a function can accept. Here is an example of a function that uses the new syntax to print a header followed by an unspecified number of values: function foo (heading, ...) disp (heading); va_start (); while (--nargin) disp (va_arg ()); endwhile endfunction Note that the argument list must contain at least one named argument (this restriction may eventually be removed), and the ellipsis must appear as the last element of the argument list. Calling va_start() positions an internal pointer to the first unnamed argument and allows you to cycle through the arguments more than once. It is not necessary to call va_start() if you do not plan to cycle through the arguments more than once. * Recursive functions should work now. * The environment variable OCTAVE_PATH is now handled in the same way as TeX handles TEXINPUTS. If the path starts with `:', the standard path is prepended to the value obtained from the environment. If it ends with `:' the standard path is appended to the value obtained from the environment. * New functions, from Kurt Hornik (hornik@neuro.tuwien.ac.at) and the Department of Probability Theory and Statistics TU Wien, Austria: corrcoef -- corrcoef (X, Y) is the correlation between the i-th variable in X and the j-th variable in Y corrcoef (X) is corrcoef (X, X) cov -- cov (X, Y) is the covariance between the i-th variable in X and the j-th variable in Y cov (X) is cov (X, X) gls -- generalized least squares estimation kurtosis -- kurtosis(x) = N^(-1) std(x)^(-4) SUM_i (x(i)-mean(x))^4 - 3 If x is a matrix, return the row vector containing the kurtosis of each column mahalanobis -- returns Mahalanobis' D-square distance between the multivariate samples X and Y, which must have the same number of components (columns), but may have a different number of observations (rows) ols -- ordinary least squares estimation pinv -- returns the pseudoinverse of X; singular values less than tol are ignored skewness -- skewness (x) = N^(-1) std(x)^(-3) SUM_i (x(i)-mean(x))^3 if x is a matrix, return the row vector containing the skewness of each column * Errors in user-supplied functions called from dassl, fsolve, lsode, npsol, and quad are handled more gracefully. * Programming errors in the use of the C++ classes within Octave should no longer cause Octave to abort. Instead, Octave's error handler function is called and execution continues as best as is possible. This should result in eventually returning control to the top-level Octave prompt. (It would be nice to have a real exception handling mechanism...) * A number of memory leaks have been eliminated. Thanks to Fong Kin Fui <fui@ee.nus.sg> for reporting them. * The C++ matrix classes are now derived from a generic template-based array class. * The readline function operate-and-get-next (from bash) is now available and bound to C-O by default. * Octave now uses the version of readline currently distributed with bash-1.13. On some systems, interactive invocations of Octave will now blink the cursor to show matching parens. * By default, include files are now installed in $prefix/include/octave instead of $prefix/include. * Octave now uses a config.h file instead of putting all defines on the compiler command line.
Version 0.79
* New control systems functions: dgram -- Returns the discrete controllability and observability gramian. dlqr -- Discrete linear quadratic regulator design. dlqe -- Discrete linear quadratic estimator (Kalman Filter) design. c2d -- Convert continuous system description to discrete time description assuming zero-order hold and given sample time. * The max (min) functions can now return the index of the max (min) value as a second return value.
Version 0.78
* Octave's handling of global variables has been completely rewritten. To access global variables inside a function, you must now declare them to be global within the function body. Likewise, if you do not declare a variable as global at the command line, you will not have access to it within a function, even if it is declared global there. For example, given the function function f () global x = 1; y = 2; endfunction the global variable `x' is not visible at the top level until the command octave:13> global x has been evaluated, and the variable `y' remains local to the function f() even if it is declared global at the top level. Clearing a global variable at the top level will remove its global scope and leave it undefined. For example, octave:1> function f () # Define a function that accesses > global x; # the global variable `x'. > x > endfunction octave:2> global x = 1 # Give the variable `x' a value. octave:3> f () # Evaluating the function accesses the x = 1 # global `x'. octave:4> clear x # Remove `x' from global scope, clear value. octave:5> x = 2 # Define new local `x' at the top level x = 2 octave:6> f # The global `x' is no longer defined. error: `x' undefined near line 1 column 25 error: evaluating expression near line 1, column 25 error: called from `f' octave:7> x # But the local one is. x = 2 * The new function, `is_global (string)' returns 1 if the variable named by string is globally visible. Otherwise, returns 0. * The implementation of `who' has changed. It now accepts the following options: -b -builtins -- display info for built-in variables and functions -f -functions -- display info for currently compiled functions -v -variables -- display info for user variables -l -long -- display long info The long output looks like this: octave:5> who -l *** currently compiled functions: prot type rows cols name ==== ==== ==== ==== ==== wd user function - - f *** local user variables: prot type rows cols name ==== ==== ==== ==== ==== wd real scalar 1 1 y *** globally visible user variables: prot type rows cols name ==== ==== ==== ==== ==== wd complex matrix 13 13 x where the first character of the `protection' field is `w' if the symbol can be redefined, and `-' if it has read-only access. The second character may be `d' if the symbol can be deleted, or `-' if the symbol cannot be cleared. * The new built-in variable ignore_function_time_stamp can be used to prevent Octave from calling stat() each time it looks up functions defined in M-files. If set to "system", Octave will not automatically recompile M-files in subdirectories of $OCTAVE_HOME/lib/VERSION if they have changed since they were last compiled, but will recompile other M-files in the LOADPATH if they change. If set to "all", Octave will not recompile any M-files unless their definitions are removed with clear. For any other value of ignore_function_time_stamp, Octave will always check to see if functions defined in M-files need to recompiled. The default value of ignore_function_time_stamp is "system". * The new built-in variable EDITOR can be used to specify the editor for the edit_history command. It is set to the value of the environment variable EDITOR, or `vi' if EDITOR is not set, or is empty. * There is a new built-in variable, INFO_FILE, which is used as the location of the info file. Its initial value is $OCTAVE_HOME/info/octave.info, so `help -i' should now work provided that OCTAVE_HOME is set correctly, even if Octave is installed in a directory different from that specified at compile time. * There is a new command line option, --info-file FILE, that may be used to set Octave's idea of the location of the info file. It will override any value of OCTAVE_INFO_FILE found in the environment, but not any INFO_FILE="filename" commands found in the system or user startup files. * Octave's Info reader will now recognize gzipped files that have names ending in `.gz'. * The save command now accepts regular expressions as arguments. Note that these patterns are regular expressions, and do not work like filename globbing. For example, given the variables `a', `aa', and `a1', the command `save a*' saves `a' and `aa' but not `a1'. To match all variables beginning with `a', you must use an expression like `a.*' (match all sequences beginning with `a' followed by zero or more characters). * Line and column information is included in more error messages.
Version 0.77
* Improved help. The command `help -i topic' now uses the GNU Info browser to display help for the given topic directly from the Texinfo documenation. * New function: chol -- Cholesky factorization.
Version 0.76
* Better run-time error messages. Many now include line and column information indicating where the error occurred. Octave will also print a traceback for errors occurring inside functions. If you find error messages that could use improvement, or errors that Octave fails to catch, please send a bug report to bug-octave@bevo.che.wisc.edu. * If gplot (or gsplot) is given a string to plot, and the string does not name a file, Octave will pass the string along to gnuplot directly. This allows commands like gplot "sin (x)" w l, data w p to work (assuming that data is a variable containing a matrix of values). * Long options (--help, --version, etc.) are supported.
Version 0.75
* The documentation is much more complete, but still could use a lot of work. * The history function now prints line numbers by default. The command `history -q' will omit them. * The clear function now accepts regular expressions. * If gplot (or gsplot) is given a string to plot, and the string names a file, Octave attempts to plot the contents of the file. * New functions: history: run_history -- run commands from the history list. edit_history -- edit commands from the history list with your favorite editor. linear algebra: balance -- Balancing for algebraic and generalized eigenvalue problems. givens -- Givens rotation. is_square -- Check to see if a matrix is square. qzhess -- QZ decomposition of the matrix pencil (a - lambda b). qzval -- Generalized eigenvalues for real matrices. syl -- Sylvester equation solver. control systems: is_symmetric -- Check to see if a matrix is symmetric. abcddim -- Check dimensions of linear dynamic system [A,B,C,D]. is_controllable -- Check to see if [A,B,C,D] is controllable. is_observable -- Check to see if [A,B,C,D] is observable. are -- Solve algebraic Ricatti equation. dare -- Solve discrete-time algebraic Ricatti equation. lqe -- Kalman filter design for continuous linear system. lqr -- Linear Quadratic Regulator design. lyap -- Solve Lyapunov equation. dlyap -- Solve discrete Lyapunov equation. tzero -- Compute the transmission zeros of [A,B,C,D].
Version 0.74
* Formal parameters to functions are now always considered to be local variables, so things like global x = 0 global y = 0 function y = f (x) x = 1; y = x; end f (x) result in the function returning 1, with the global values of x and y unchanged. * Multiple assignment expressions are now allowed to take indices, so things like octave:13> [a([1,2],[3,4]), b([5,6],[7,8])] = lu ([1,2;3,4]) will work correctly.
Version 0.73
* Saving and loading global variables works correctly now. * The save command no longer saves built-in variables. * Global variables are more reliable. * Matrices may now have one or both dimensions zero, so that operations on empty matrices are now handled more consistently. By default, dimensions of the empty matrix are now printed along with the empty matrix symbol, `[]'. For example: octave:13> zeros (3, 0) ans = [](3x0) The new variable `print_empty_dimensions' controls this behavior. See also Carl de Boor, An Empty Exercise, SIGNUM, Volume 25, pages 2--6, 1990, or C. N. Nett and W. M. Haddad, A System-Theoretic Appropriate Realization of the Empty Matrix Concept, IEEE Transactions on Automatic Control, Volume 38, Number 5, May 1993. * The right and left division operators `/' and `\' will now find a minimum norm solution if the system is not square, or if the coefficient matrix is singular. * New functions: hess -- Hessenberg decomposition schur -- Ordered Schur factorization perror -- print error messages corresponding to error codes returned from the functions fsolve, npsol, and qpsol (with others to possibly be added later). * Octave now prints a warning if it finds anything other than whitespace or comments after the final `end` or `endfunction` statement. * The bodies of functions, and the for, while, and if commands are now allowed to be empty. * Support for Gill and Murray's QPSOL has been added. Like NPSOL, QPSOL is not freely redistributable either, so you must obtain your own copy to be able to use this feature. More information about where to find QPSOL and NPSOL are in the file README.NLP.
Version 0.72
* For numeric output, columns are now lined up on the decimal point. (This requires libg++-2.3.1 or later to work correctly). * If octave is running interactively and the output intended for the screen is longer than one page and a pager is available, it is sent to the pager through a pipe. You may specify the program to use as the pager by setting the variable PAGER. PAGER may also specify a command pipeline. * Spaces are not always significant inside square brackets now, so commands like [ linspace (1, 2) ] will work. However, some possible sources of confusion remain because Octave tries (possibly too hard) to determine exactly what operation is intended from the context surrounding an operator. For example: -- In the command [ 1 - 1 ] the `-' is treated as a binary operator and the result is the scalar 0, but in the command [ 1 -1 ] the `-' is treated as a unary operator and the result is the vector [ 1 -1 ]. -- In the command a = 1; [ 1 a' ] the single quote character `'' is treated as a transpose operator and the result is the vector [ 1 1 ], but in the command a = 1; [ 1 a ' ] an error message indicating an unterminated string constant is printed. * Assignments are just expressions now, so they are valid anywhere other expressions are. This means that things like if (a = n < m) ... endif are valid. This is parsed as: compare `n < m', assign the result to the variable `a', and use it as the test expression in the if statement. To help avoid errors where `=' has been used but `==' was intended, Octave issues a warning suggesting parenthesis around assignments used as truth values. You can suppress this warning by adding parenthesis, or by setting the value of the new built-in variable `warn_assign_as_truth_value' to 'false' (the default value is 'true'). This is also true for multiple assignments, so expressions like [a, b, c] = [u, s, v] = expression are now possible. If the expression is a function, nargout is set to the number of arguments for the right-most assignment. The other assignments need not contain the same number of elements. Extra left hand side variables in an assignment become undefined. * The default line style for plots is now `lines' instead of `points'. To change it, use the `set data style STYLE' command. * New file handling and I/O functions: fopen -- open a file for reading or writing fclose -- close a file fflush -- flush output to a file fgets -- read characters from a file frewind -- set file position to the beginning of a file fseek -- set file position ftell -- tell file position freport -- print a report for all open files fscanf -- read from a file sscanf -- read from a string scanf -- read from the standard input * New built-in variables for file and I/O functions: stdin -- file number corresponding to the standard input stream. stdout -- file number corresponding to the standard output stream. stderr -- file number corresponding to the standard error stream. The following may be used as the final (optional) argument for fseek: SEEK_SET -- set position relative to the beginning of the file. SEEK_CUR -- set position relative to the current position. SEEK_END -- set position relative to the end of the file. * New function: setstr -- convert vectors or scalars to strings (doesn't work for matrices yet). * If possible, computer now prints the system type instead of always printing `Hi Dave, I'm a HAL-9000'. * Octave now properly saves and restores its internal state correctly in more places. Interrupting Octave while it is executing a script file no longer causes it to exit. * Octave now does tilde expansion on each element of the LOADPATH. * A number of memory leaks have been plugged. * Dependencies for C++ source files are now generated automatically by g++. * There is a new command line option, -p PATH, that may be used to set Octave's loadpath from the command line. It will override any value of OCTAVE_PATH found in the environment, but not any LOADPATH="path" commands found in the system or user startup files. * It is now possible to override Octave's default idea of the location of the system-wide startup file (usually stored in $(prefix)/lib/octave/octaverc) using the environment variable OCTAVE_HOME. If OCTAVE_HOME has a value, Octave will look for octaverc and its M-files in the directory $OCTAVE_HOME/lib/octave. This allows people who are using binary distributions (as is common with systems like Linux) to install the real octave binary in any directory (using a name like octave.bin) and then install a simple script like this #!/bin/sh OCTAVE_HOME=/foo/bar/baz export OCTAVE_HOME exec octave.bin to be invoked as octave.
Version 0.71
* Much improved plotting facility. With this release, Octave does not require a specially modified version of gnuplot, so gnuplot sources are no longer distributed with Octave. For a more detailed description of the new plotting features, see the file PLOTTING. * New plotting commands: plot -- 2D plots semilogx -- 2D semilog plot with logscale on the x axis semilogy -- 2D semilog plot with logscale on the y axis loglog -- 2D log-log plot mesh -- 3D mesh plot meshdom -- create matrices for 3D plotting from two vectors contour -- contour plots of 3D data bar -- create bar graphs stairs -- create stairstep plots polar -- 2D plots from theta-R data grid -- turn plot grid lines on or off xlabel, ylabel -- place labels on the x and y axes of 2D plots sombrero -- demonstrate 3D plotting gplot -- 2D plot command with gnuplot-like syntax gsplot -- 3D plot command with gnuplot-like syntax set -- set plot options with gnuplot syntax show -- show plot options with gnuplot syntax closeplot -- close stream to gnuplot process purge_tmp_files -- delete temporary files created by plot command * Other new commands: ls, dir -- print a directory listing shell_cmd -- execute shell commands keyboard -- get input from keyboard, useful for debugging menu -- display a menu of options and ask for input fft -- fast fourier transform ifft -- inverse fast fourier transform * Strings may be enclosed in either single or double quote characters. Double quote characters are not special within single quote strings, and single quotes are not special within double quote strings. * Command name completion now works for M-file names too. * Better help and usage messages for many functions. * Help is now available for functions defined in M-files. The first block of comments is taken as the text of the help message. * Numerous changes in preparation to support dynamic loading of object files with dld. * Bug fixes to make solving DAEs with dassl actually work. * The command `save file' now saves all variables in the named file. * If do_fortran_indexing is 'true', indexing a scalar with [1,1,1,...] (n times) replicates its value n times. The orientation of the resulting vector depends on the value of prefer_column_vectors. * Things like [[1,2][3,4]] no longer cause core dumps, and invalid input like [1,2;3,4,[5,6]] now produces a diagnositic message. * The cd, save, and load commands now do tilde expansion. * It's now possible to clear global variables and functions by name. * Use of clear inside functions is now a parse error.
Version 0.70
* Better parse error diagnostics. For interactive input, you get messages like octave:1> a = 3 + * 4; parse error: a = 3 + * 4; ^ and for script files, the message includes the file name and input line number: octave:1> foo parse error near line 4 of file foo.m: a = 3 + * 4; ^ * New built-in variable PS2 which is used as the secondary prompt. The default value is '> '. * New file, octave-mode.el, for editing Octave code with GNU Emacs. This is a modified version of Matthew R. Wette's matlab-mode.el. * Better support for missing math functions. * User preferences are now cached in a global struct so we don't have to do a symbol table lookup each time we need to know what they are. This should mean slightly improved performance for evaluating expressions.
Version 0.69
* Multiple assignments are now possible, so statements like a = b = c = 3; a = b = c = [1,2;3,4]; or c = (a = (b = 2) * 3 + 4) * 5 are legal, as are things that have even more bizarre effects, like a(4:6,4:6) = b(2:3,2:3) = [1,2;3,4]; (try it). * Improved parsing of strings (but they still don't work as matrix elements). * An M-file may now either define a function or be a list of commands to execute. * Better detection and conditional compilation of IEEE functions isinf, finite, and isnan. * Replacements for acosh, asinh, atanh, and gamma from the BSD math library for those systems that don't have them.
Version 0.68
* New functions: eval -- evaluate a string as a sequence of Octave commands. input -- print a prompt and get user input.
Version 0.67
* New functions: find -- return the indices of nonzero elements. * Zero-one style indexing now works. For example, a = [1,2,3,4]; b = a([1,0,0,1]) sets b to the first and fourth elememnts of a. Zero-one style indexing also works for indexing the left hand side of an assignment. For example, a = rand (1,2;3,4); a([0,1],:) = [-1,-2] sets the second row of a to [-1 -2] The behavior for the ambiguous case a = [1,2,3,4]; b = a([1,1,1,1]); is controlled by the new global variable `prefer_zero_one_indexing'. If this variable is equal to 'true', b will be set to [1 2 3 4]. If it is false, b will be set to [1 1 1 1]. The default value is 'false'. * Using the new global variable `propagate_empty_matrices', it is possible to have unary andy binary operations on empty matrices return an empty matrix. The default value of this variable is 'warn', so that empty matrices are propagated but you get a warning. Some functions, like eig and svd have also been changed to handle this. * Empty matrices can be used in conditionals, but they always evaluate to `false'. With propagate_empty_matrices = 'true', both of the following expressions print 0: if [], 1, else 0, end if ~[], 1, else 0, end * Octave no longer converts input like `3.2 i' or `3 I' to complex constants directly because that causes problems inside square brackets, where spaces are important. This abbreviated notation *does* work if there isn't a space between the number and the i, I, j, or J.
Version 0.66
* Logical unary not operator (~ or !) now works for complex. * Left division works. * Right and left element by element division should work correctly now. * Numbers like .3e+2 are no longer errors. * Indexing a matrix with a complex value doesn't cause a core dump. * The min and max functions should work correctly for two arguments. * Improved (I hope!) configuration checks. * Octave is now installed as octave-M.N, where M and N are version numbers, and octave is a link to that file. This makes it possible to have more than one version of the interpreter installed.
Version 0.63
* The reshape function works again. * Octave now converts input like `3.2i' or `3 I' or `2.3e5 j' to be complex constants directly, rather than requiring an expression like `3.3 * i' to be evaluated.
Version 0.61
* Octave has been successfully compiled using gcc 2.3.3 and libg++ 2.3. on a 486 system running Linux. * The win_texas_lotto function is now called texas_lotto (it's a script file, and win_texas_lotto.m is too long for some Linux and System V systems).
Version 0.57
* The C-like formatted print functions printf, fprintf, and sprintf finally work.
Version 0.56
* By default, octave prints a short disclaimer when it starts. (You can suppress it by invoking octave with -q). * You can keep octave from reading your ~/.octaverc and .octaverc files by invoking it with -f. * When returning two values, eig now returns [v, d] instead of [lambda, v], where d is a diagonal matrix made from lambda. * The win_texas_lotto function now produces a sorted list. * New functions: expm -- matrix exponential. logm -- matrix logarithm.
Version 0.55
* The following (C-style) backslash escape sequences work in quoted strings (useful(?) with printf()): \a bell \r carriage return \b backspace \t horizontal tab \f formfeed \v vertical tab \n newline \\ backslash * Use of `...' at the end of a line will allow a statement to continue over more than one line. * The names `inf' and `nan' are now aliases for `Inf' and `NaN', respectively. * New functions: casesen -- print a warning if the luser tries to turn off case sensitivity. median -- find median value. norm -- compute the norm of a matrix. sort -- sort columns. * New variable, `silent_functions'. If silent_functions == 'true', the results of expressions are not printed even if they are not followed by a semicolon. The disp() and printf() functions still result in output. The default value for this variable is 'false'. * New variable `return_last_value_computed'. If it is 'true', functions defined in script files return the last value computed if a return value has not been explicitly declared. The default value for this variable is 'false'.
Version 0.52
* Name completion works for function and variable names currently in the symbol tables. Coming soon: completion for names of functions defined in script files but not yet compiled. * The initial value of do_fortran_indexing is now false, and the initial value of prefer_column_vectors is now true. Swap the values of these variables if you want behavior that is more like Matlab. * All script files check the number of input arguments before doing much real work. * The identifiers `i' and `j' are now also names for sqrt(-1). These symbols may be used for other purposes, but their original definition will reappear if they are cleared. * The symbol tables are now implemented with hash tables for faster searching. * A small amount of help is now available for most built-in operators, keywords and functions. Coming soon: help for script files. * Without any arguments, the help command now lists all known built-in operators, keywords and functions. * Generic parse errors are now signalled by `Eh, what's up doc?', which is closer to what Bugs actually says. * The who command now only prints variable names by default. Use the -fcn (or -fcns, or -functions) switch to print the names of built-in or currently compiled functions.
Version 0.51
Major overhaul of array indexing.
The colloc function actually works now.
Version 0.50
* The lsode and dassl functions now return the states only, instead of the time and the states, so you must keep track of the corresponding times (this is easy though, because you have to specify a vector of desired output times anyway). * Solution of NLPs with NPSOL now works on the SPARC. * New keywords `endif', `endfor', `endfunction', `endif', and `endwhile', which allow for better diagnostics. The `end' keyword is still recognized. All script files have been changed to use these new keywords in place of `end'. * It is now possible to uninstall Octave by doing a `make uninstall' in the top level directory. * The Makefiles are much closer to conforming with GNU coding standards. * New functions: win_texas_lotto -- produce six unique random numbers between 1 and 50. quad -- numerical integration. lu -- LU factorization qr -- QR factorization dassl -- Solution of DAEs using DASSL. * New files: THANKS -- A list of people and organazations who have supported the development of Octave. NEWS -- This file, listing recent changes. * Help is now available at the gnuplot prompt. | https://www.gnu.org/software/octave/NEWS-1.html | CC-MAIN-2021-04 | refinedweb | 7,818 | 64.71 |
Permissions are a set of rules (or constraints) that allow a user or a group of users to view, add, alter, or delete items in Django. Django has a permissions system built-in. It enables you to provide permissions to individual users or groups of users.
Using django.contrib.auth, Django provides several default permissions.
When you include django.contrib.auth in your INSTALLED APPS option, it will create four default permissions for each Django model defined in one of your installed applications: add, change, delete, and view.
This article seeks to provide a concise and easy-to-understand overview of Django roles, permissions, and groups. To do so, I’ll go through everything you need to know and understand about permissions, groups, and roles, and then I’ll look at some code samples.
Permissions in Django
Key things to understand to better use Permissions:
- Users
- Permissions
- Groups
- Users Roles
To comprehend when these permissions are appropriate, we must first grasp the difference between authentication and authorization.
Authentication involves verifying that the user’s credentials, such as email and password, are correct. Authorization, on the other hand, specifies what the user is allowed to do within the application.
What is the meaning of user roles?
Suppose you’re establishing a Django project with many user types, for example, a School project with multiple roles such as a teacher, accountant, librarian, and so on. In that case, you’ll need a separate job for each individual to categorize.
What are the benefits of using user roles?
To use roles in your models, you must extend AbstractUser most straightforwardly.
from django.contrib.auth.models import AbstractUser
class User(AbstractUser): TEACHER = 1 ACCOUNTANT = 2 LIBRARIAN =3 ROLE_CHOICES = ( (TEACHER, 'Teacher'), (ACCOUNTANT, 'Accountant'), (LIBRARIAN, 'Librarian'), ) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, null=True) # You can create Role model separately and add ManyToMany if user has more than one role
To check the user role, run the following set of commands.
user = User.objects.first() user.role = User.TEACHER user.save() user.role == User.ACCOUNTANT False user.role == User.LIBRARIAN True
Assuming you have an app with an app_label or app name School and a Vote model, you can use the code below to see which users have the necessary permissions.
python manage.py shell user = User.objects.first() add: user.has_perm('school.add_vote') change: user.has_perm('school .change_vote') delete: user.has_perm('school .delete_vote') view: user.has_perm('school .view_vote')
Alternatively, you can use the decorator to confirm if the current user has permission to execute the function or not.
from django.contrib.auth.decorators import permission_required @permission_required('school.add_vote') def your_func(request): """or you can raise permission denied exception"""
The other approach is to use the class, PermissionRequiredMixin just in case you use a class-based view.
from django.contrib.auth.mixins import PermissionRequiredMixin from django.views.generic import ListView class VoteListView(PermissionRequiredMixin, ListView): permission_required = 'school.add_vote' # Or multiple of permissions<br>permission_required = ('school .add_vote', 'school .change_vote')
The syntax for checking if the given user has the necessary permissions in the template is as follows.
{% if perms.app_label.can_do_something %} {% if perms.school.add_vote %}
Alternatively, you can use the if condition within your function to check if the user has the necessary permissions.
user.has_perm('vote.change_vote')
And, from the abstract Permission model PermissionsMixin, this User(AbstractUser) model has a ManyToMany field named user permissions. Below are the methods for assigning and removing permission from or to the user.
user.user_permissions.set([permission_list]) user.user_permissions.add(permission, permission, …) user.user_permissions.remove(permission, permission, …) user.user_permissions.clear()
The syntax for fetching all the permissions for users is as follows.
user.user_permissions.all()
Permissions on a model-by-model basis
If you’re not happy with the default permissions in Django, you can create your custom permissions.
On the Vote model, for example, I added two extra special permissions.
from django.db import models class Vote(models.Model): user = models.ForeignKey(User) class Meta: permissions = ( ("view_student_reports", "can view student reports"), ("find_student_vote", "can find a student's vote"), )
Remember to run makemigrations and migrate the changes to the model.
How to create custom permissions programmatically
from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType content_type = ContentType.objects.get_for_model(Vote) permission = Permission.objects.create( codename='can_see_vote_count', name='Can See Vote Count', content_type=content_type, )
Let’s look at the following example to understand permission caching.
#be sure every permission must be unique(set, duplicate not allowed) user.has_perm('school.find_owner') # False,because no perm available # create permission content_type = ContentType.objects.get_for_model(Vote) permission = Permission.objects.get( codename='find_owner', content_type=content_type, ) # assign new permission to user user.user_permissions.add(permission) # Checking the cached permission set user.has_perm('school .find_owner') # False, because of cache problem. # get new instance of User # Be aware that user.refresh_from_db() won't clear the cache. user = get_object_or_404(User, pk=user_id) # Permission cache is repopulated from the database user.has_perm('myapp.find_owner') # True
Note that superuser has all permissions (has_perm will return True), but you can change them to meet your project’s needs.
# source code verification # Active superusers have all permissions. if self.is_active and self.is_superuser: return True
An object, an instance, a record, or a row in a database table Permission
Django guardian library is designed to grant object or instance level permission. So, when you build a model, Django generates four permissions, and they are not available to the user until they are assigned.
We need to restrict users from modifying other users’ records because they have the permissions. For example, if the admin gives change_vote permission to one user, that user should not change all the votes that belong to other users. As a result, we need to restrict the user from modifying other user records for this purpose.
Groups in Django
As the name implies, groups can contain a list of permissions or is simply a collection of items.
A group is also a collection of users. A single user can belong to many groups, while a single group can have multiple users. Groups can also label users.
django.contrib.auth.models
Group models are a generic means of categorizing users so that permissions or other labels can be applied. A user can be a member of as many groups as they choose.
A user who is a member of a group inherits the group’s permissions. If the group site editors have permission to edit the home page, for example, any user in that group will have the ability.
Rather than maintaining permissions for each user, which is not scalable, it is preferable to have Groups such as Teacher, Accountant, and Librarian. Then assign users to these groups or multiple groups. Subsequently, check these user permissions using the syntax mentioned above (has_perm).
If a user is a group member, that groups’ permissions will be passed down to that user.
To limit permissions, you can form groups such as Teacher1, Teacher2, Accountant1, Accountant2, etc.
How to Create Groups
from django.contrib.auth.models import Group teacher_group, created = Group.objects.get_or_create(name='Teacher')
The next step involves assigning the given set of permissions to a specified group.
teacher_group.permissions.set([permission_list]) teacher_group.permissions.add(permission, permission, …) teacher_group.permissions.remove(permission, permission, …) teacher_group.permissions.clear()
Assigning a single user to groups
teacher_group.user_set.add(user)
OR
user.groups.add(teacher_group)
How to find a given user in the group
def is_teacher(user): return user.groups.filter(name='Teacher').exists() from django.contrib.auth.decorators import user_passes_test @user_passes_test(is_teacher) def my_view(request): pass # Check user in the group in the template # you can use a custom template tag to check users in a group or groups
Groups vs. Roles
Most of the time, roles and groups are referred to interchangeably, but their functions are distinct, and most users have numerous roles and groups. Therefore, when creating a position, it’s better to use the same group name each time.
My idea is to use roles to display different HTML pages to users based on their category and use groups for permissions.
Models
The permissions field in the model’s “class Meta” section is used to define permissions. You can declare as many permissions as you need in a tuple, with each permission described as a nested tuple with the permission name and permission display value. For instance, we might create permission that allows a user to mark a book as returned, as shown:
class BookInstance(models.Model): … class Meta: … permissions = (("can_mark_returned", "Set book as returned"),)
The permission might then be assigned to a “Librarian” group in the Admin site.
As seen above, open catalog/models.py and add the permission. To update the database, you’ll need to re-run your migrations as follows.
python3 manage.py makemigrations python3 manage.py migrate
Templates
The current user’s permissions are saved in the perms template variable. You can use the exact variable name within the linked Django “app” to check whether the current user has specific permission — for example, perms.catalog.can mark returned will be True if the user has this permission, and False otherwise. We usually use the template percent if percent tag to check for permission.
{% if perms.catalog.can_mark_returned %} {% endif %}
Views
The permission required decorator can be used to test permissions in a function view, and the PermissionRequiredMixin can be used to test permissions in a class-based view. The pattern is the same as that for login authentication. However, you may need to add several permissions in some cases.
Decorator for the function view:
from django.contrib.auth.decorators import permission_required @permission_required('catalog.can_mark_returned') @permission_required('catalog.can_edit') def my_view(request): …
Example of A permission-required mixin for class kind of!
Note that the behavior described above has a slight default difference. For a logged-in user with permission violation, the following is the default behavior:
@permission required takes you to the login page (HTTP Status 302). On the other hand, PermissionRequiredMixin returns a 403 Forbidden error whose HTTP Status is Forbidden.
The PermissionRequiredMixin behavior is what you want: If a user is logged in but does not have the appropriate permissions, return 403. Use @login_required and @permission_required with raise_exception=True for a function view, as shown:
from django.contrib.auth.decorators import login_required, permission_required @login_required @permission_required('catalog.can_mark_returned', raise_exception=True) def my_view(request): …
Example how to Authenticate and Apply Permissions
I’ll teach you how to let people log in with their accounts on your site, as well as how to limit what they can do and see based on whether or not they’re authenticated and have the necessary permissions.
Django provides an authentication and authorization system that allows you to validate user credentials and define what actions each user is permitted to execute. Built-in models for Users and Groups have permissions or flags that designate whether a user may execute a task, forms, and views for logging in users. It also determines view tools for restricting contingency in the framework.
This article will also cover how to activate user authentication on a school website, create custom login and logout pages, add permissions to your models, and manage page access.
I’ll utilize authentication/permissions to show both users’ and librarians’ listings of books that have been borrowed.
The authentication mechanism is quite versatile, and you can create your URLs, forms, views, and templates by just contacting the given API to log in to the user. However, this tutorial will use Django’s authentication views and forms for our login and logout pages.
I’ll still need to make some templates, but it should be pretty straightforward.
I’ll show you how to create permissions and verify login status and permissions in both views and templates.
Note: When we used the django-admin startproject command to create the app, all necessary configurations were done for us. When we first used python manage.py migrate, user database tables and model permissions were automatically created.
The setup is in the project file (school/school/settings.py) under the INSTALLED APPS and MIDDLEWARE sections,. .…
User and group creation
First, create your first user (a superuser), which can be created with the command:
python manage.py createsuperuser
I’ll need to build a test user to represent a regular site user because our superuser is already authenticated and has all capabilities. Next, I’ll create our local library groups and website logins through the admin site because it’s one of the quickest ways to do so.
Users can also be created programmatically, as seen in the example below. For instance, if you’re creating an interface that allows users to create their logins (you shouldn’t offer them access to the admin site), you’ll need to do this on their behalf.
When beginning a project, it is highly advised that you create a custom user model. Then, if the necessity arises, you’ll be able to customize it in the future quickly.
I’ll start by creating a group, then a user. Even though we don’t have any permissions for our library members yet, adding them to the group rather than separately to each member will make it easier if we need to later.
Start the development server and go to the admin site ( in your local web browser. Use the credentials for your superuser account to log in to the site.
All of your models are listed on the top level of the Admin site, categorized by “Django application.” Click the Users or Groups buttons in the Authentication and Authorization section to access their existing records.
Group Creation
Let’s start by making a new group for our library users.
To create a new Group, click the Add button (next to Group) and give it the name “Librarian”.
We don’t need any permissions for the group, so just press SAVE, and you will be taken to a list of groups.
Since we do not require any permissions for the group, go ahead and press SAVE. The last step will now show the entire list of groups.
User Creation
Next is the user creation step. But, first, return to the admin site’s home page.
To enter the Add User dialogue box, click the Add button next to Users.
For your test user, enter an appropriate Username and Password/Password Confirmation.
To create the user, press SAVE.
The admin site will create a new user and lead you to a Modify user screen where you may change your username and fill out the optional sections for the User model. The first name, last name, email address, and the user’s status and rights are all included in these fields (only the Active flag should be set).
You can also specify the user’s groups and rights further down and see relevant dates about the person, such as their join date and last log in.
Select the Librarian group from the Available groups’ list in the Groups section, then press the right-arrow between the boxes to move it to the Chosen groups box.
We don’t need to do anything else here, so select SAVE once more to return to the user list.
You now have a “librarian” account that you may use for testing. You can do this once the pages to allow them to log in have been implemented.
Configuring the authentication views
Django comes with practically everything you’ll need to build authentication pages that handle login, logout, and password management. It includes a URL mapper, views, and forms, but not templates, which we must develop ourselves.
I’ll show you how to integrate the default system into the School website and create templates in this section. Then, I’ll include them in the project’s main URLs.
URLs for projects
To the bottom of the project urls.py file (school/school/urls.py), add the following:
# Add Django site authentication URLs (for login, logout, password management) urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ]
Go to (notice the trailing forward slash!) and type in your username and password. Django will display an error message stating that it was unable to locate this URL, as well as a list of all the URLs it attempted. You can view the URLs that will function, for example:
accounts/ login/ [name='login'] accounts/ logout/ [name='logout'] accounts/ password_change/ [name='password_change'] accounts/ password_change/done/ [name='password_change_done'] accounts/ password_reset/ [name='password_reset'] accounts/ password_reset/done/ [name='password_reset_done'] accounts/ reset/// [name='password_reset_confirm'] accounts/ reset/done/ [name='password_reset_complete']
Note: Using the above approach adds the following URLs, which can reverse the URL mappings, with names in square brackets. You don’t need to do anything further because the above URL mapping will automatically map the URLs listed below.
Now go to and try to log in. It will fail again, but this time with an error stating that the required template (registration/login.html) is missing from the template search path. In the yellow part at the top, you’ll see the following lines:
- TemplateDoesNotExist is an exception type.
- registration/login.html is an exceptional value.
The next step is to add the login.html file to the registration directory on the search path.
Directory of Templates
The newly added URLs (and indirectly, views) seek to find their related templates in the /registration/ directory somewhere in the templates search path.
I’ll place our HTML pages in the templates/registration/ directory for this site. This directory should be the same as the catalog and school folders in your project root directory. So first, make these folders right away.
In addition, we must include the templates directory in the template search path to see the template loader. (/school/school/settings.py)
Open the project settings. After that, import the os module and add the following line near the top of the file.
import os # needed by code below
Update the ‘DIRS’ line in the TEMPLATES section as follows:
... TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, …
Login template
Make a new HTML file called /school/templates/registration/login.html and fill it with the following information:
{% extends our base template and replaces the content block. The rest of the code is standard form handling code. For the time being, all you need to know is that this will bring up a form where you may enter your username and password. Subsequently, if you input invalid values, you will be prompted to enter proper ones when the page refreshes.
Once you’ve saved your template, go back to the login page ( and you should see something like this:
You’ll be forwarded to another page if you log in with the correct credentials (by default, The issue is that Django assumes that when you log in, you want to go to your profile page, which may or may not be the case. You’ll get another error because you haven’t defined this page yet!
Add the text below at the bottom of the project settings (/school/school/settings.py). By default, you should now be taken to the site homepage when you log in.
Redirect to home URL after login (Default redirects to /accounts/profile/) LOGIN_REDIRECT_URL = '/'
Template for logging out
If you go to the logout URL ( you’ll notice something strange: your user will be logged out, but you’ll be taken to the Admin logout page instead. That’s not what you want, even if the login link on that page gets you to the Admin login screen. Unfortunately, the admin login is only accessible to people with is_staff permission.
/school/templates/registration/logged_out.html should be created and opened. Fill in the blanks with the following text:
{% extends "base_generic.html" %} {% block content %} <p>Logged out!</p> <a href="{% url 'login'%}">Click here to login again.</a> {% endblock %}
It is a pretty basic template. It just shows you a notification alerting you that you have been logged out, along with a link to return to the login screen. If you go back to the logout URL, you should see the following page:
Template for password reset
The default password reset system sends a reset link to the user through email. You’ll need to build forms to collect the user’s email address, send the email, allow them to change their password, and keep track of when everything is finished.
As a starting point, the following templates can be used.
It is the form used to obtain the user’s email address for sending the password reset email. Create /school/templates/registration/password_reset_form.html, and give it the following contents:
{% extends "base_generic.html" %} {% block content %} {% csrf_token %} {% if form.email.errors %} {{ form.email.errors }} {% endif %} {{ form.email }} {% endblock %}
Testing new authentication pages
The login pages should now automatically function after adding the URL configuration and producing all of these templates!
You can try logging in and out of your superuser account using these URLs to test the new authentication pages:
-
-
You can test the password reset feature by clicking the link on the login page. Remember that Django will only send reset emails to addresses (users) that it already has on file!
Validation with authenticated users
This section looks at how we can restrict what content users see based on whether or not they are logged in.
Using templates for testing
The user template variable can be used in templates to acquire information about the currently logged-in user (this is added to the template context by default when you set up the project as we did in our skeleton).
To check whether the user can see specific content, you’ll usually start using the user.is_authenticated template variable. Next, we’ll edit our sidebar to show a “Login” link if the user is logged out and a “Logout” link if they are logged in.
Copy the following text into the sidebar block, directly before the endblock template tag, in the base template (/school/catalog/templates/base_generic.html).
<ul class="sidebar-nav"> ... {% if user.is_authenticated %} <li>User: {{ user.get_username }}</li> <li><a href="{% url 'logout'%}?next={{request.path}}">Logout</a></li> {% else %} <li><a href="{% url 'login'%}?next={{request.path}}">Login</a></li> {% endif %} </ul>
We utilize if-else-endif template tags to conditionally display content depending on whether {{user.is_authenticated }} is true, as you can see. We know we have a valid user if the user is authorized, so we call {{user.is_authenticated }} to display their name.
We generate the login and logout link URLs using the URL template tag and the names of the corresponding URL configurations. Take note of how we’ve added ?next={{request.path}} to the end of the URLs. It adds a URL parameter at the end of the linked URL containing the current page’s address (URL).
Testing in views
Applying the login required decorator to your view function, as shown below, is the easiest way to restrict access to your functions if you’re using function-based views. Your view code will normally run if the user is logged in. If the user is not logged in, the current absolute path will be passed as the next URL parameter to the login URL defined in the project settings (settings.LOGIN_URL).
If the user successfully logs in, they will be returned to this page, but they will be authenticated this time.
... from django.contrib.auth.decorators import login_required @login_required def my_view(request): ...
Deriving from LoginRequiredMixin is also the simplest way to restrict access to logged-in users in your class-based views. This mixin must be declared before the main view class in the superclass list.
… from django.contrib.auth.mixins import LoginRequiredMixin class MyView(LoginRequiredMixin, View): … class MyView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' …
The login required decorator has the same redirect behavior like this one. You can also specify a URL parameter name instead of “next” to insert the current absolute path (redirect field name) and an alternative location to redirect the user to if they are not authenticated (login_url).
Conclusion
In this article, I have introduced permissions and groups and compared roles with groups, covering all essentials. Please keep in mind that roles (such as a teacher) and groups (such as teacher group 1 and teacher group 2, where the teacher1 group only has limited ability to view first-reports for students but cannot modify the students’ score) are two separate things.
With a simple example, I covered the principles and how they work.
I sincerely hope that this article has helped you better understand permissions and groups. Please feel free to ask any questions you may have, and thank you.
Thank you very much, this page describe how we can leverage Django’s default authentication and authorisation solution. Can you suggest how the solution looks like if you want to use 3rd Party tools like Auth0 to handle authentication and authorisation instead of using Django’s default solution. | https://www.codeunderscored.com/django-roles-permissions-and-groups/ | CC-MAIN-2022-21 | refinedweb | 4,150 | 56.05 |
When working with many developers we may want to restrict the access for some objects
to some of them (either change, or delete for instance)
XI allows us to do it very easily and this is a simple example on how to start using so called “Data Dependent Authorizations”.
In the initial situation we have access to all objects and when we click Change button
we can change any object we want (unless the software component version is not checked “Objects are modifiable”)
but we’d like to change this and forbid our user to access Message mappings in one software component version.
1. From the Integration builder: Repository let’s go to Tools -> User Roles -> New
2. Let’s name our role: SampleRestriction
3. Now we’ll Exclude access to our Software component version + for all of it’s namespaces and exclude access to all Message Mappings from that component.
This picture was changed a little bit so it’s easier to see all objects on it.
Obviously we can choose many other Objects if we want
4. Then hit save & activate our role.
5. Now we have to go to the: to assing the new role to our user
but before that make sure you got
com.sap.aii.util.server.auth.activation property set to true in your ExchangeProfile
– IntegrationBuilder
— IntegrationBuilder.Repository
6. Click Roles -> search for role XiRep_Samplerestriction
7. Assign users to…
8. Then we can add a user to the new role.
9. Now we can see that our user has been added.
We can log on to the XI Repository and when we click the Change button for the Message mapping we’ll see:
**********************************************************************************
More information about repository authorizations can be found on:
1. User Roles – help.sap.com
2. Latest XI configuration guide under:
Users with Data-Dependent Authorizations
**********************************************************************************
Cheers. Keep blogging… :-))
Thx:)
but the truth is that I (as a developer)
don’t want to have restricted access 🙂
BTW
I keep reading you contributions too and I really like he one with the message flow 🙂
you too keep on (web)blogging 🙂
Regards,
michal
Yea i assent wth ya..tht we shouldnt have restricted access…;)
cheers …keep bloggin
Sudhir
till the first delete of Our SWC:)))
Regards:)
michal
The chaos can even be if there are many teams on one place:)
but we have to create “managed chaos” 🙂
Regards,
michal
for the solution that I show in this weblog? 🙂
I believe it has even more functions with new SPs…
Regards,
michal
I tryed your blog.but, when i click the change button in the repository objtct its not performing perticular role.
i was configured ExchangeProfile parametes and created new user and its roles.
Would you tell where i done mistake. according to your blog.
i did this, but somehow for reason i don’t know yet when i add the com.sap.aii.util.server.auth.activation in ExchangeProfile –> IntegrationBuilder �¨ IntegrationBuilder.Repository it is also added in IntegrationBuilder.Directory
I’ve repeated it 5 times already but it is really getting added in the IntegrationBuilder.Directory, which then applies the restriction also to Directory objects
Our system is XI 3.0 SP19
would you know why this happens?
I have tried it but I can continue modifing objects.
1. I have created a user in XI (Trans. SU01) with role SAP_XI_DEVELOPER.
2. I have create the Exchange profile parameter with true, and restart J2EE
3. I have created a role in IR:
Exclude/SWCV/*/Exclude/Message Mapping/Full Edit
4. I have assigned the role to the user
and the user can modify all objects in the SWCV.
Could you help me? | https://blogs.sap.com/2005/05/25/xi-how-to-add-authorizations-to-repository-objects/ | CC-MAIN-2018-30 | refinedweb | 609 | 64.2 |
Eclipse Community Forums - RDF feed Eclipse Community Forums MOXy: <xml-attribute> and JSON <![CDATA[I have an OXM mapping file that is used to marshall my objects to JSON (and to XML). The mappings I have supplied as xml-attribute work when creating XML, but do not appear when marshalling to JSON. Is this expected behavior? Is there another approach I should be using?]]> David Vree 2012-02-02T22:28:47-00:00 Re: MOXy: <xml-attribute> and JSON <![CDATA[It turns out that only the "read-only" attributes are not be written out with JSON. Again, is this expected behavior?]]> David Vree 2012-02-03T14:27:07-00:00 Re: MOXy: <xml-attribute> and JSON <![CDATA[It turns out that only the "read-only" attributes are not be written out with JSON. Again, is this expected behavior? This is expected behaviour. If you specify a mapping as "read-only" then it will not be marshalled to XML or JSON. <xml-attribute Below is complete example demonstrating an object mapping with MOXy's external mapping document with an attribute property marshalled to both XML and JSON: feb3.Root The following will be used as the domain model: package feb3; public class Root { private String foo; public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } } feb3/oxm.xml We will use MOXy's external mapping document to map the foo property as an XML attribute. <?xml version="1.0"?> <xml-bindings <java-types> <java-type <xml-root-element <java-attributes> <xml-attribute </java-attributes> </java-type> </java-types> </xml-bindings> feb3.Demo The following code demonstrates how to bootstrap from MOXy's external mapping document, and how to marshal to both XML (default) and JSON. package feb3;, "feb3/oxm.xml"); JAXBContext jc = JAXBContext.newInstance(new Class[] {Root.class}, properties); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Root root = new Root(); root.setFoo("Hello World"); // Marshal to XML marshaller.marshal(root, System.out); // Marshal to JSON marshaller.setProperty("eclipselink.media-type", "application/json"); marshaller.marshal(root, System.out); } } Output Here is the XML and JSON output from running the demo code: <?xml version="1.0" encoding="UTF-8"?> <rss foo="Hello World"/> {"rss" : {"foo" : "Hello World"}}]]> Blaise Doughan 2012-02-03T15:08:06-00:00 Re: MOXy: <xml-attribute> and JSON <![CDATA[I have posted a reply to this question in your other thread:]]> Blaise Doughan 2012-02-03T15:11:20-00:00 Re: MOXy: <xml-attribute> and JSON <![CDATA[Blaise Doughan wrote on Fri, 03 February 2012 10:08 > It turns out that only the "read-only" attributes are not be written out with JSON. Again, is this expected behavior? > > This is expected behaviour. If you specify a mapping as "read-only" then it will not be marshalled to XML or JSON. Thanks for the quick reply. Stupid me, I had the meaning of read-only and write-only backwards. I was look at it from the perspective of the Java class property, but it looks like I need to think of it from the perspective of the JAXBContext!]]> David Vree 2012-02-03T19:22:39-00:00 | http://www.eclipse.org/forums/feed.php?mode=m&th=284022&basic=1 | CC-MAIN-2017-17 | refinedweb | 533 | 60.11 |
Home >>Java Programs >Java Program for linear search
In this example, we'll see a Java program to search the array elements using the linear search.
Linear search is used to look for a key element from multiple elements. It is less used because it's slower than binary search and hashing.Algorithm:
import java.util.Scanner; class Main { public static void main(String args[]) { int c, n, search, array[]; Scanner in = new Scanner(System.in); System.out.println("Enter number of elements"); n = in.nextInt(); array = new int[n]; System.out.println("Enter those " + n + " elements");) /* Element to search isn't present */ System.out.println(search + " isn't present in array."); } } | https://www.phptpoint.com/java-program-for-linear-search/ | CC-MAIN-2021-39 | refinedweb | 112 | 52.76 |
NoSsr API
API documentation for the React NoSsr component. Learn about the available props and the CSS API.
Import
You can learn about the difference by reading this guide on minimizing bundle size.
import NoSsr from '@mui/core/NoSsr'; // or import { NoSsr } from '@mui/core';
NoSsr purposely removes components from the subject of Server Side Rendering (SSR).
This component can be useful in a variety of situations:
- Escape hatch for broken dependencies not supporting SSR.
- Improve the time-to-first paint on the client by only rendering above the fold.
- Reduce the rendering time on the server.
- Under too heavy server load, you can turn on service degradation.
Props
The component cannot hold a ref. | https://mui.com/api/no-ssr/ | CC-MAIN-2021-43 | refinedweb | 115 | 67.55 |
Opened 8 years ago
Closed 6 years ago
#14654 closed enhancement (fixed)
implement flow polytopes
Description
Flow polytopes (or cones) of a directed graph is a polytope formed by assigning a nonnegative flow to each of edges of the graph such that the flow is conserved on internal vertices, and there is a unit of flow entering the sources and leaving the sinks.
The faces and volume of these polytopes are of interest. Examples of these polytopes are the Chan-Robbins-Yuen polytope and the Pitman-Stanley polytope.
Implement a class for these polytopes to compute the faces and the volume (maybe using #13249 or implementing known triangulations of them).
Change History (39)
comment:1 Changed 8 years ago by
- Milestone changed from sage-5.11 to sage-5.12
comment:2 Changed 7 years ago by
- Milestone changed from sage-6.1 to sage-6.2
comment:3 Changed 7 years ago by
- Milestone changed from sage-6.2 to sage-wishlist
- Type changed from PLEASE CHANGE to enhancement
comment:4 Changed 7 years ago by
- Branch set to u/chapoton/14654
- Commit set to 33472ec876b496cd45955fa7578e20faeca1b1fc
comment:5 Changed 6 years ago by
- Cc ncohen added
- Component changed from combinatorics to graph theory
- Owner changed from sage-combinat to graphcomponentowner
- Summary changed from implement class for flow polytopes to implement flow polytopes
comment:6 follow-up: ↓ 9 Changed 6 years ago by
Might I suggest to put this either into a digraph class or into
src/sage/geometry/polyhedron/library.py&?
comment:7 Changed 6 years ago by
Yepyep.
This should probably be a digraph method. It should also appear in
polytopes.<tab> I guess.
Nathann
comment:8 Changed 6 years ago by
(You can also write the code in geometry/polyhedron and create a fake digraph function that calls it, btw)
Also, the docstring mentions sources/sinks but the code never heard of it.
Nathann
comment:9 in reply to: ↑ 6 Changed 6 years ago by
Might I suggest to put this either into a digraph class or into
src/sage/geometry/polyhedron/library.py?
On the other hand, beware of another
src/sage/graphs/generic_graph.py which just contains too much stuff.
Note that you can
import methods into classes just the same way as you can
import other stuff.
comment:10 Changed 6 years ago by
- Commit changed from 33472ec876b496cd45955fa7578e20faeca1b1fc to 1b57c82f1eae104a3f6675f2f08c26e529f33f68
Branch pushed to git repo; I updated commit sha1. New commits:
comment:11 Changed 6 years ago by
Why import
line_graph?
comment:12 Changed 6 years ago by
(please don't create a file for a 10 lines function)
comment:13 Changed 6 years ago by
- Commit changed from 1b57c82f1eae104a3f6675f2f08c26e529f33f68 to 1cbe9656be3255a956e3fcc19ab67cb5273ab928
Branch pushed to git repo; I updated commit sha1. New commits:
comment:14 follow-up: ↓ 15 Changed 6 years ago by
(BTW, digraph.py for some reason imports deprecation without needing it.)
comment:15 in reply to: ↑ 14 Changed 6 years ago by
(BTW, digraph.py for some reason imports deprecation without needing it.)
Oh. Well, let's remove it then. Here or somewhere else.
Nathann
comment:16 Changed 6 years ago by
- Commit changed from 1cbe9656be3255a956e3fcc19ab67cb5273ab928 to a1fa21827894719e987b1ac3e41527e92df43f68
Branch pushed to git repo; I updated commit sha1. New commits:
comment:17 Changed 6 years ago by
- Status changed from new to needs_review
I do not know how to add this as a method of
polytopes
comment:18 follow-up: ↓ 19 Changed 6 years ago by
It seems that what appears in
polytopes.<tab> are the functions defined in
sage.geometry.polyhedron.library.Polytopes.
Also, since you changed the status to
needs_review: the documentation of
DiGraph.flow_polytope mentions a source and a sink with a non-null flow, while the function only takes one argument, i.e. the graph.... Is that normal ?
O_o
Nathann
comment:19 in reply to: ↑ 18 ; follow-up: ↓ 20 Changed 6 years ago by
It seems that what appears in
polytopes.<tab>are the functions defined in
sage.geometry.polyhedron.library.Polytopes.
Yes, but is there a way to just import the function as a method
polytopes.flow_polytope ?
Also, since you changed the status to
needs_review: the documentation of
DiGraph.flow_polytopementions a source and a sink with a non-null flow, while the function only takes one argument, i.e. the graph.... Is that normal ?
O_o
Well, for quiver guys like me, a source is a vertex with only outgoing edges, and a sink with only incoming edges..
comment:20 in reply to: ↑ 19 Changed 6 years ago by
Yo !
Yes, but is there a way to just import the function as a method
polytopes.flow_polytope?
There is, but it may be a bit awkard for in one version the function takes a graph as an argument, and in the other
polytopes.flow_polytope(G) it needs to be provided explicitly... But maybe that is not a problem.
About importing the method:
sage: class A: ....: def hey(self): ....: print self sage: A.hey(1) ... TypeError: unbound method hey() must be called with A instance as first argument (got Integer instance instead) sage: A.hey.__func__(1) 1
But I am afraid that it does not preserve the docstring...
On the other hand it is possible to take a 'normal' function and make a copy of it inside of a class. You have many functions like that at the end of
graphs/graph.py
Well, for quiver guys like me, a source is a vertex with only outgoing edges, and a sink with only incoming edge..
Oh I see
O_o
Well, for graph guys like me we expect the sources to be explicitly given, like in
GenericGraph.flow.
HMmmm... Well, if you are positive that this is the standard that people who call this method would expect, could you make it a bit clearer for the graph guys ? Something like:
... and there is a unit of flow entering the sources (i.e. vertices of indegree 0) and leaving the sinks (i.e. vertices of outdegree 0)
The point is that I would understand if you talk about "the sinks/sources of a graph", but in the context of flow problem we expect the sources/sinks to be specific vertices. Could you also add a sentence about the necessity to have as many sinks as sources ?
Thaaaaaaanks and sorry for that ! Different people, different standards
^^;
Nathann
comment:21 Changed 6 years ago by
- Commit changed from a1fa21827894719e987b1ac3e41527e92df43f68 to f0309ebc481de9b3cffda40807197c9390615ff8
Branch pushed to git repo; I updated commit sha1. New commits:
comment:22 Changed 6 years ago by
comment:23 Changed 6 years ago by
Helloooooo !
Sorry for having delayed this patch for so long. I am about to leave for a couple of months and I had a lot of things to attend to
T_T
I found a way to make this
polytopes.<tab> thing work. Wasn't that hard after all. I also merged the branch with the latest release.
It seems all good to go, still I have one question: from the way your code is written, a digraph obtained from "any digraph + an isolated vertex" has an empty flow polyhedron. I don't think that it is the expected behaviour, but might it be what you want for your applications ?
Nathann
(the additional commits are to be found at public/14654)
comment:24 Changed 6 years ago by
- Commit changed from f0309ebc481de9b3cffda40807197c9390615ff8 to d74ca66ad183162f85ea4479810ba5909cbeec19
Branch pushed to git repo; I updated commit sha1. New commits:
comment:25 Changed 6 years ago by
Thanks a lot, Nathann, for all the time you spend on my tickets.
I have made a modification that takes care of isolated points by considering them as both sources and sinks, and so letting a flow of 1 silently going through them.
comment:26 Changed 6 years ago by
Hmm. I don't like the idea that the sources and the sinks are inferred. I'd prefer to have the user provide them (and letting the code infer them only if so required), as I can see myself applying such a method for various sink-source configurations on a single graph, and it looks strange to build a new graph every time.
(I was planning to make these changes myself soon enough, once I'm done with Gelfand-Tsetlin and Berenstein-Zelevinsky polytopes, but I caught something last week and now all I'm swamped with work.)
comment:27 Changed 6 years ago by
.......soooooooooooo ???
Nathann
comment:28 Changed 6 years ago by
Darij ? Do you have any plans to implement the change you mentionned ? You left your comment 7 weeks ago and this ticket is "on hold" since...
Nathann
comment:29 Changed 6 years ago by
OOPS, please don't regard my comments as blockers! I indeed wanted to do changes, but then I noticed that the polytopes class doesn't work the way I want it to and all these changes have to wait for my other patch, which has to wait for my end-of-term work... so this might take some time. Meanwhile, feel free to review and merge this patch -- whatever I want to change I will change later with my BZ polytopes patch.
comment:30 Changed 6 years ago by
- Reviewers set to Nathann Cohen
- Status changed from needs_review to positive_review
Okay, then let it get in. And you are welcome to make those source/sinks explicit, it also feels more natural to me
;-)
Cheers,
Nathann
comment:31 Changed 6 years ago by
- Branch changed from u/chapoton/14654 to u/tscrim/flow_polytopes-14654
- Commit changed from d74ca66ad183162f85ea4479810ba5909cbeec19 to 703016840815038fe79b466d67bb297a8fd43042
- Milestone changed from sage-wishlist to sage-6.5
I allowed myself to make the trivial change for speed:
len(ins) == 0 to
not ins.
New commits:
comment:32 Changed 6 years ago by
- Status changed from positive_review to needs_work
File "src/sage/combinat/cluster_algebra_quiver/quiver.py", line 162, in sage.combinat.cluster_algebra_quiver.quiver.ClusterQuiver Failed example: Q = ClusterQuiver([[1,1]]) Expected: Traceback (most recent call last): ... ValueError: The input DiGraph contains a loop Got: <BLANKLINE> Traceback (most recent call last): File "/mnt/disk/home/release/Sage/local/lib/python2.7/site-packages/sage/doctest/forker.py", line 488, in _run self.compile_and_execute(example, compiler, test.globs) File "/mnt/disk/home/release/Sage/local/lib/python2.7/site-packages/sage/doctest/forker.py", line 850, in compile_and_execute exec(compiled, globs) File "<doctest sage.combinat.cluster_algebra_quiver.quiver.ClusterQuiver[37]>", line 1, in <module> Q = ClusterQuiver([[Integer(1),Integer(1)]]) File "sage/misc/lazy_import.pyx", line 383, in sage.misc.lazy_import.LazyImport.__call__ (build/cythonized/sage/misc/lazy_import.c:3398) return self._get_object()(*args, **kwds) File "/mnt/disk/home/release/Sage/local/lib/python2.7/site-packages/sage/combinat/cluster_algebra_quiver/quiver.py", line 342, in __init__ dg = DiGraph( data ) File "/mnt/disk/home/release/Sage/local/lib/python2.7/site-packages/sage/graphs/digraph.py", line 716, in __init__ deprecation(15706, "You created a graph with loops from a list. "+ NameError: global name 'deprecation' is not defined ********************************************************************** 1 item had failures: 2 of 41 in sage.combinat.cluster_algebra_quiver.quiver.ClusterQuiver [227 tests, 2 failures, 2.01 s] ---------------------------------------------------------------------- sage -t --warn-long 38.5 src/sage/combinat/cluster_algebra_quiver/quiver.py # 2 doctests failed
comment:33 Changed 6 years ago by
- Branch changed from u/tscrim/flow_polytopes-14654 to u/darij/flow_polytopes-14654
- Commit changed from 703016840815038fe79b466d67bb297a8fd43042 to 187d1d8a216d763ae4c3af3ce5c4f449d5720c74
- Status changed from needs_work to needs_review
New commits:
comment:34 Changed 6 years ago by
Sorry guys, just added some more complexity. I do not particularly trust
self.edges() to be consistent, let alone reasonable, about the order in which it outputs edges. And sources and sinks are now specifiable by the user.
comment:35 Changed 6 years ago by
- Branch changed from u/darij/flow_polytopes-14654 to u/chapoton/14654
- Commit changed from 187d1d8a216d763ae4c3af3ce5c4f449d5720c74 to 37ef5cbd6aaa4bc4938f55b420c7db15933322d4
Ok, I have just added the word "optional" in a few places. I would have prefered more simplicity, but nevertheless this seems to be good to go. If somebody else agrees, please set it to positive review.
New commits:
comment:36 Changed 6 years ago by
I definitely agree with your "optional"s -- they can never hurt. Does this mean I should set the ticket to positive_review?
comment:37 Changed 6 years ago by
- Reviewers changed from Nathann Cohen to Nathann Cohen, Darij Grinberg, Travis Scrimshaw
- Status changed from needs_review to positive_review
In short, yes (although I've just done it :P).
comment:38 Changed 6 years ago by
- Milestone changed from sage-6.5 to sage-6.6
comment:39 Changed 6 years ago by
- Branch changed from u/chapoton/14654 to 37ef5cbd6aaa4bc4938f55b420c7db15933322d4
- Resolution set to fixed
- Status changed from positive_review to closed
New commits: | https://trac.sagemath.org/ticket/14654?cversion=0&cnum_hist=6 | CC-MAIN-2021-10 | refinedweb | 2,109 | 64 |
If; } }
And the output for the first 15 values:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
I guess this proves that I probably am compulsive problem solver. In my defence I was pointing someone else at the idea behind FizzBuzz and I couldn't resist to put down a few lines of code that produced the desired output ...
Um, the actual game involves substituting "fizz", "buzz" and "fizzbuzz" for the numbers in the proper places, not adding them.
Here:
int main()
{
bool flag;
for (int i = 1; i < 101; ++i)
{
flag = true;
if (i % 3 == 0)
{
cout << "Fizz";
flag = False;
}
if (i % 5 == 0)
{
cout << "Buzz";
flag=False;
}
if (flag == True)
{
cout << i << " ";
}
cout << endl;
}
}
That fixes your code. It uses a flag to note if fizz or buzz was written and, if not, writes the integer.
An alternative is to test for mod 3 or mod 5 all at once (i.e. i%3==0||i%5==0 or even (i%3)*(i%5)==0). I think flipping a bit is more elegent than performing redundant math, but that is just my opinion.
I tried to be smart and show the index numbers to confirm that it shows the text at correct positions. But after double checking the original task I admit the index numbers should be replaced. Example updated. Thanks for pointing it out. Have fun :)
My solution:
#include
using namespace std;
int main(){
int x = 0;
for(x= 1; x<50; ++x){
if (x % 3 == 0){
cout <<"fizz";
}
if (x % 5 == 0){
cout <<"buzz";
}
if(x % 3 != 0 && x % 5 != 0){
cout <<x;
}
cout <<endl;
}
} | http://mybyteofcode.blogspot.com/2010/02/my-fizzbuzz-solution-in-c.html | CC-MAIN-2017-47 | refinedweb | 276 | 86.44 |
Introduction
Many well-established software projects have used flat text configuration and resource files for several years without major issues. As projects grow and become more complex, the need increases for greater rigor and adaptability. With XML, and the application of XML using concrete standards, you can potentially benefit from: cross-project and cross-platform compatibility, robustness, and extensibility in areas such as Unicode.
By converting flat text files to the relevant open source standard, you can also increase flexibility and reliability. The lexicon in voice recognition work provides a good example that's used in this article. Whether or not your open source projects move to XML for resource files, you can employ XML standards in your work without loss of functions.
In this article, learn to easily move between flat and Pronunciation Lexicon Specification (PLS) formats. Examples show how to store customized lexicons in the PLS format and extract data into the required flat file.
Example: The lexicon
Lexicons are lists of words that you use in speech recognition tools. They contain information on how the word must be printed or rendered graphically and how it sounds using phonemes. The lexicon in regular use with the Hidden Markov Model Toolkit (HTK) is widely used in voice control projects (see Resources). Listing 1 is an extract from a VoxForge HTK lexicon.
Listing 1. Extract from a VoxForge HTK lexicon
AGENCY [AGENCY] ey jh ih n s iy AGENDA [AGENDA] ax jh eh n d ax AGENT [AGENT] ey jh ih n t AGENTS [AGENTS] ey jh ih n t s AGER [AGER] ey g er AGES [AGES] ey jh ih z
The file in Listing 1 consists of three tab-separated fields:
- The label that describes the word generally
- The square brackets that surround the word as you want it printed or shown on the screen (the grapheme)
- A sequence of single-space-separated phonemes from the Arpabet (see Resources) set that describe how the word sounds
In the example above, the pronunciations are from the English language, which is easily encompassed by American Standard Code for Information Interchange (ASCII) characters.
The CMU Sphinx project (see Resources) stores the lexicon (or dictionary in CMU Sphinx context) in a similar manner. Listing 2 shows an extract.
Listing 2. Extract from a CMU Sphinx lexicon
agency EY JH AH N S IY agenda AH JH EH N D AH agendas AH JH EH N D AH Z agent EY JH AH N T agents EY JH AH N T S ager EY JH ER
In Listing 2 has only two fields: the word/grapheme and its phoneme rendering. The two example lexicons have some subtle differences:
- The words and phonemes are in different cases.
- The phonemes have some slight differences.
- Punctuation (comma, exclamation point, and so on) is treated slightly differently.
You can see the entire dictionary in the cmu07a.dic file in the current download of PocketSphinx (see Resources).
Because the lexicon describes specific pronunciations of words, you might need to edit the file to suit specific people or dialects. Over time, you build up knowledge capital in your own customized lexicon. It's easy to edit the flat file with a text editor, but it's also easy to introduce errors, such as: using a separator other than the standard for the file, inserting non-ASCII characters, putting the fields in the wrong order, sorting the records incorrectly, missing square brackets where required, and so on.
There's another subtle disadvantage of flat files. As you build your customized file, you remain incompatible with other speech projects. A lexicon in a standard XML format such as PLS, if recognized by both projects, is immediately compatible in both.
Pronunciation Lexicon Specification
The PLSA has a straightforward, basic format, as in Listing 3.
Listing 3. Basic PLS format
<?xml version="1.0" encoding="UTF-8"?> <lexicon version="1.0" xmlns="" xmlns: <lexeme ...> <grapheme>...</grapheme> <phoneme ...>...</phoneme> </lexeme> </lexicon>
The XML describes the root element
lexicon that can
contain multiple
lexeme child elements. Each
lexeme can contain multiple
grapheme
elements and multiple
phoneme elements. The
specification lets you override the
alphabet attribute
but does not allow you to override the
xml:lang
language attribute. To store lexemes for different languages, you strictly need
separate PLS lexicon files. The default alphabet in this lexicon is
ipa, which refers to the International Phonetic Alphabet (IPA) system
of representing sounds (see Resources). The IPA
representations of phonemes are multibyte Unicode characters. Both HTK and Sphinx
use plain ASCII codes. This important consideration is addressed later in this article.
The advantage of using the PLS specification is that it adds more rigorous
structure and lets you store more information, such as part of speech and
specific alphabets. Part-of-speech detail is important in English because some
words that can be spelled identically (homographs) are pronounced differently
depending on their grammatical role. For example, perfect as an adjective
sounds different from the same word as a verb because the stress is in a
different place. The extra information stored in attributes allows you to extract specific records from the entire file, depending on need. Using this method, you can search for a specific alphabet among multiple
phoneme elements.
Consider the PLS lexicon as a database of lexicon information from which you can extract detail relevant to the voice tool that you use. Listing 4 is an example in PLS format.
Listing 4. One word in PLS format
<?xml version="1.0" encoding="UTF-8"?> <lexicon version="1.0" xmlns="" xmlns: <lexeme role="noun"> <grapheme>agency</grapheme> <phoneme alphabet="x-htk-voxforge">ey jh ih n s iy</phoneme> <phoneme alphabet="x-cmusphinx">EY JH AH N S IY</phoneme> </lexeme> </lexicon>
The example in Listing 4 stores only one word that has two
possible phonemic representations. You can filter out one of the
phoneme strings by using the
alphabet attribute. The
lexeme element shows the
role attribute of
noun. While this is informative, it is redundant in this case because the word is only used as a noun, with no complicating pronunciation scenarios.
By placing the
phoneme representations from two
different sources side by side, you can already discern subtle differences. This information could be helpful in resolving speech recognition problems.
Neither CMU Sphinx nor HTK can use a PLS lexicon directly, but the simon (see Resources) front end to the HTK toolkit can. If you're using straight HTK or Sphinx, you need to be sure you can get easily from plain text to PLS and back again without loss of information.
The following sections show how to use Python to get from a flat file to PLS and back to a flat file. It is assumed that you have customized information in a flat lexicon file.
Conversion to PLS
The code in Listing 5 uses Python, but you can accomplish the same thing many other ways. (For an example, see the developerWorks tutorial on Extensible Stylesheet Language Transformations (XSLT) in Resources.) Some people want to use libraries that check the robustness of the XML at each minor step for more immediate feedback on where the problem is, especially if source files are large and liable to contain errors and inconsistencies. The example below leaves the checking to the last step, which implies a certain level of confidence that the flat files are in good shape.
Listing 5. Conversion to PLS
from elementtree.ElementTree import parse import string as str import sys import cgi # # call with # python flat2pls.py vox # or # python flat2pls.py spx # if len(sys.argv) == 2: src = sys.argv[1] else: exit("wrong args") #') # now the lexemes if src == "vox": f = open("vf.lex","r") for line in f: line = str.strip(line) word = str.split(line,"\t") #gr = str.strip(word[1],"[]") gr = cgi.escape(word[0]) out.write('\n\ <lexeme>\n\ <grapheme>'+gr+'</grapheme>\n\ <phoneme alphabet="x-htk-voxforge">'+word[2]+'</phoneme>\n\ </lexeme>') else: # src is sphinx f = open("cmu.dic","r") for line in f: line = str.strip(line) word = str.split(line,"\t") gr = cgi.escape(word[0]) out.write('\n\ <lexeme>\n\ <grapheme>'+gr+'</grapheme>\n\ <phoneme alphabet="x-cmusphinx">'+word[1]+'</phoneme>\n\ </lexeme>') # ended lexemes out.write('\n</lexicon>\n') out.close() # now check the output is ok tree = parse(outfile) lexicon = tree.getroot() mylexcount = 0 for lexeme in lexicon: mylexcount += 1 print 'Found %(number)d lexemes' % {"number":mylexcount}
Listing 5 begins by importing modules from the XML
parsing library
elementtree (see Resources) and some supporting libraries. Importing
ElementTree on different distributions can involve a slightly different syntax,
depending on how you install the module. The example code is from openSUSE with
the module installed from source, but Ubuntu might require
from xml.etree.ElementTree import parse. The module
str allows some string manipulations,
sys
gives you access to files, and
cgi provides an
all-important escaping routine essential in handling data for XML. The code
expects to get a command-line interface (CLI) argument telling it whether to
translate from CMU Sphinx format or HTK/VoxForge. The example code then opens the file
for output and writes the XML prologue suitable for PLS. Because you're not storing
any Unicode characters at this stage, it's sufficient to open the file for plain ASCII access only.
At this point, the code in Listing 5:
- Processes the source file line by line, splitting the fields into separate strings and writing the
lexeme,
grapheme, and
phonemecomponents
- Identifies the
phonemewith attribute
alphabet="x-htk-voxforge"if the incoming data is from the VoxForge lexicon and with
alphabet="x-cmusphinx"if the data is from Sphinx
- Retains the case of the phonemes
When the first field is imported it may contain characters, such as ampersand (&), that cause problems in the XML unless escaped with
cgi.escape().
Finally, the code:
- Writes the closing tags
- Closes the PLS file and then reloads it as an XML file
- Reads through the file counting
lexemeelements
- Reports the count of lexemes
If the count is reported, then the XML appears to be robust and well-formed.
Listing 6 is an extract of the result from VoxForge HTK lexicon.
Listing 6. Extract of result from VoxForge HTK lexicon
... <lexeme> <grapheme>AGENDA</grapheme> <phoneme alphabet="x-htk-voxforge">ax jh eh n d ax</phoneme> </lexeme> <lexeme> <grapheme>AGENT</grapheme> <phoneme alphabet="x-htk-voxforge">ey jh ih n t</phoneme> </lexeme> ...
Conversion from PLS
It's important to know that you can easily get back from PLS format to a flat file. The code in Listing 7 assumes that you have your lexicon stored in a PLS-formatted file and that your speech recognition project can only use a flat file in either HTK or CMU Sphinx format.
Listing 7. Conversion from PLS
from elementtree.ElementTree import parse import string as str import sys # # call with # python pls2flat.py x-htk-voxforge > mylexicon # or # python pls2flat.py x-cmusphinx > mylexicon.dic # if len(sys.argv) > 1: alpha = sys.argv[1] # if alpha == "x-htk-voxforge": tree = parse("mylexvox.pls") else: tree = parse("mylexspx.pls") lexicon = tree.getroot() for lexeme in lexicon: for child in lexeme: #print child.tag if child.tag[-8:] == 'grapheme': if alpha == 'x-htk-voxforge': gr = str.upper(child.text) print gr,"\t","["+gr+"]","\t", else: gr = child.text print gr,"\t", if child.tag[-7:] == 'phoneme': if child.get('alphabet') == alpha: print child.text
This short script uses the
elementtree library to parse
the PLS XML file. It establishes the root element and then iterates over the
child lexemes, looking for the
grapheme and
phoneme, and writes the values to a text file in the relevant format.
The script asks for the last eight characters in the tag for
grapheme since there will be a namespace prefix returned with the tag. It recreates the three-field format for HTK and two fields for CMU Sphinx.
Merging and dealing with Unicode
The script in Listing 8 uses two PLS files
to create one common PLS file that contains information for both of the original
files. It also translates the VoxForge
phoneme string
to Unicode and stores the Unicode version in a separate
phoneme element identified with the
alphabet="ipa" attribute.
Listing 8. Merging and Unicode
#! /usr/bin/python -u # -*- coding: utf-8 -*- # # challenge is to merge two pls files # given two pls files, merge them into one # import elementtree.ElementTree as ET from elementtree.ElementTree import parse import string as str import codecs import cgi # treevox = ET.parse("mylexvox.pls") treespx = ET.parse("mylexspx.pls") # lexvox = treevox.getroot() lexspx = treespx.getroot() # phons = { 'aa':u'ɑ','ae':u'æ','ah':u'ʌ','ao':u'ɔ','ar':u'ɛr','aw':u'aʊ', 'ax':u'ə','ay':u'aɪ','b':u'b','ch':u'tʃ','d':u'd','dh':u'ð','eh':u'ɛ', 'el':u'ɔl','en':u'ɑn','er':u'ər','ey':u'eɪ','f':u'f', 'g':u'ɡ','hh':u'h','ih':u'ɪ','ir':u'ɪr','iy':u'i','jh':u'dʒ','k':u'k','l':u'l', 'm':u'm','n':u'n','ng':u'ŋ','ow':u'oʊ','oy':u'ɔɪ','p':u'p','r':u'r','s':u's', 'sh':u'ʃ','t':u't','th':u'θ','uh':u'ʊ','ur':u'ʊr','uw':u'u','v':u'v', 'w':u'w','y':u'j','z':u'z','zh':u'ʒ','sil':'' } # def to_utf(s): myp = str.split(s) myipa = [] for p in myp: myipa.append(phons[p]) return str.join(myipa,'') #') # # scan the two pls, create dictionary voxdict = {} for lexeme in lexvox: gr = str.lower(lexeme[0].text) ph = lexeme[1].text voxdict[gr] = {ph,} # for lexeme in lexspx: gr = lexeme[0].text ph = lexeme[1].text if gr in voxdict: voxdict[gr].add(ph) else: voxdict[gr] = {ph,} # for gr in sorted(voxdict.iterkeys()): out.write('\n\ <lexeme>\n\ <grapheme>'+cgi.escape(gr)+'</grapheme>') #print "%s: %s" % (key, voxdict[key]) for ph in sorted(voxdict[gr]): alph = 'x-htk-voxforge' if ph.islower() else 'x-cmusphinx' out.write('\n\ <phoneme alphabet="'+alph+'">'+ph+'</phoneme>') if ph.islower(): phipa = to_utf(ph) out.write(u'\n\ <phoneme alphabet="ipa">'+phipa+'</phoneme>') out.write('\n\ </lexeme>') # done, close files out.write('\n</lexicon>') out.close() # now check the output is ok tree = parse(outfile) lexicon = tree.getroot() mylexcount = 0 for lexeme in lexicon: mylexcount += 1 print 'Found %(number)d lexemes' % {"number":mylexcount}
You begin with a hashbang (#!) expression followed by a special indicator
to the Python interpreter, on the second line, that this code contains Unicode
characters. The script then imports a number of modules, including
elementtree,
codecs, and
cgi, that are useful when dealing with Unicode. You tell the interpreter where the two PLS files are and point to their root elements.
The
phons variable stores a special dictionary that
contains a mapping from the CMU Arpabet codes to an equivalent Unicode
combination. This dictionary translates existing
phoneme strings to a Unicode version. Feel free to modify the mapping
for your own purposes—for example, you might feel that the equivalent of
'aa' in Unicode is
u'ɑ:',
which lengthens the a sound.
A single defined function,
to_utf(), that
translates an ASCII Arpabet string to Unicode. The final part of the foundation
is to open a file for storage of the output, making sure that this file knows it
must be prepared to accept Unicode, and to write the PLS prologue into it.
Now you're ready to process the files by creating two special internal Python
dictionaries, one from each of the PLS files, by scanning them with the
elementtree library. It is assumed that the
grapheme will be the first child and the
phoneme the second child of the lexeme. The script adds all of the records from the first file to a new merge dictionary. When scanning the second file, if a key already exists in the new merge dictionary you add to its set of phonemes. If not, you create a new key item in the merged dictionary. At the end of the loop, the new merged dictionary contains keys from both the original files and an associated set of one or two
phoneme strings.
Write the new PLS file from the merge you just created. As you scan through the
dictionary, you add the
alphabet attribute to
distinguish one
phoneme from another. Having written
out the existing phonemes, you create a new
phoneme
string that is the Unicode equivalent of the CMU Arpabet string, which you can get from the HTK or the Sphinx version (or both) according to your needs.
Finally, close out the root element, close the file, and parse it again as you did before to check that it is well formed.
The result should look something like Listing 9.
Listing 9. Merge results
... <lexeme> <grapheme>agenda</grapheme> <phoneme alphabet="x-cmusphinx">AH JH EH N D AH</phoneme> <phoneme alphabet="x-htk-voxforge">ax jh eh n d ax</phoneme> <phoneme alphabet="ipa">ədʒɛndə</phoneme> </lexeme> <lexeme> <grapheme>agendas</grapheme> <phoneme alphabet="x-cmusphinx">AH JH EH N D AH Z</phoneme> </lexeme> <lexeme> <grapheme>agent</grapheme> <phoneme alphabet="x-cmusphinx">EY JH AH N T</phoneme> <phoneme alphabet="x-htk-voxforge">ey jh ih n t</phoneme> <phoneme alphabet="ipa">eɪdʒɪnt</phoneme> </lexeme> <lexeme> <grapheme>agent's</grapheme> <phoneme alphabet="x-cmusphinx">EY JH AH N T S</phoneme> </lexeme> ...
With the merged PLS dictionary, you can apply Extensible Stylesheet Language (XSL) or any other procedures to generate the results you need, whether flat file or a new specific PLS file. In theory, you can store other
phoneme strings in this file as well, even from other languages. However, that is a nonstandard use of the PLS specification.
Kai Schott has done a lot of work with PLS and has several already prepared files for download in different languages, particularly German (see Resources).
Unresolved issues
Though you can get a lot of information from the flat files, the following issues remain unresolved.
- Selecting from multiple graphemes
- On occasion, you need to deal with multiple spellings for a word in the same language. The role and the phoneme are identical for both orthographies, so you have multiple graphemes in the same lexeme. However, there is nothing in the PLS that allows you to add an attribute to the
graphemeelement as there is with the
alphabetattribute of the
phonemeelement.
- Acronyms
- Lexicons frequently contain acronyms. The PLS deals with these in a child element of
lexemecalled an
<alias>.To build a PLS automatically from a flat file, you need a way to distinguish the acronyms from the real words in the lexicon. The flat files don't necessarily have that information.
- Role/part of speech
- As with acronyms, part-of-speech information is not available from the flat files to build
roleattributes into the PLS.
Conclusion
In this article, you learned to move quite easily between flat and PLS formats. Storing lexicons in PLS format has potential advantages. Open source projects may or may not move to XML for resource files. That is a decision for project managers to make—they alone can assess resources and apply them in the best way generally accepted in their communities.
In the meantime, you can employ XML standards in your own work without loss of functions. For lexicons and dictionaries used in voice recognition work, you can increase cross-project adaptability, robustness, and utility by storing customized lexicons in the PLS format. You can easily extract data as needed into the required flat file.
Resources
Learn
- W3C Pronunciation Lexicon Specification (PLS): Get more information on lexemes, graphemes, and phonemes.
- International Phonetic Alphabet: Read more on Wikipedia about this alphabetic system of phonetic notation, including the Arpabet and Unicode equivalents.
- HTK: Learn about the Hidden Markov Model Toolkit (HTK) portable toolkit for building and manipulating hidden Markov models.
- CMU Sphinx: Explore the open source toolkit for speech recognition from Carnegie Mellon University.
- ElementTree: Read more about the ElementTree XML library for Python.
- simon: Learn more about this speech recognition platform.
- Testing simon, Kai Schott's blog: Find several already prepared PLS files for various languages.
- Analyze with XSLT, Part 1: Analyze non-XML data with XSLT (Chuck White, developerWorks, December 2003): Provides information about using XSLT to work with XML.
- More articles by this author (Colin Beckingham, developerWorks, March 2009-current): Read articles about XML, voice recognition, XQuery, PHP,
- VoxForge: Create acoustic models and find out more about putting together a speech recognition model.
- CMU Sphinx: Get the speech recognition toolkit.
- Python: Get more information about this programming language, including download links.
-. | http://www.ibm.com/developerworks/library/x-flatfilespython/ | CC-MAIN-2015-06 | refinedweb | 3,443 | 55.34 |
I know how item_array[2] becomes 0 but i don't know why. since array[] is not a reference to item_array[2] how does the function biggest, which returns a reference to array[bigges], assign 0 to item_array[2]???
could someone please explain this to me, thank you.
Code:#include <iostream> int& biggest(int array[], int n_elements){ int index; int biggest; biggest = 0; for(index = 1; index < n_elements; ++index){ if(array[biggest] < array[index]) biggest = index; } return(array[biggest]); } int main(){ using namespace std; int item_array[5] = {1, 2, 5000, 3, 4}; cout << "The biggest element is " << biggest(item_array, 5) << endl; biggest(item_array, 5) = 0; cout << item_array[2] << endl; return 0; } | http://cboard.cprogramming.com/cplusplus-programming/35462-return-reference.html | CC-MAIN-2015-11 | refinedweb | 111 | 56.08 |
Answered by:
The contract name 'WCFTest1.CalculatorService' could not be found in the list of contracts implemented by the service 'CalculatorService'.
- Hi,
I'm evidently doing something critically wrong, but I've been banging my head against this for hours, and can't get to the bottom of it. Just trying to get some of the MSDN samples to work so that I can learn from them.
What I have been finding is that I can get a service to work if I just define a class for it, but as soon as I use an interface, and let the class implement the interface, I get the error message as shown above.
Environment: Win Xp Pro, VS 2008, .NET framework 3.5sp1.
Example method and code: Start a new web project, add new item: Silverlight-enabled WCF service, paste in example code as per
Error shows up whilst the class implements the interface. As soon as the interface is removed from the class (and the class tagged with [ServiceContract], and a method given [OperationContract]), the error disappears. Same seems to hold for every sample I can find.
I have tried tagging the class as full trust with no effect. I have also tried repairing my installation of .NET 3.5sp1, again with no effect. I suspect it may be something to do with namespaces, but can't get my head around what or why.
I conclude that it's something fundamental I am doing wrong, but I just can't see what it is. Can anyone help me see my foolishness?
Question
Answers
- from the error it looks like the config file is still referring to the class rather than the interface in the endpoint's contract name
Richard Blewett, thinktecture -
All replies
- from the error it looks like the config file is still referring to the class rather than the interface in the endpoint's contract name
Richard Blewett, thinktecture -
- Thanks, the config file was still pointing to the class rather than the interface, which I hadn't realised was wrong. With hindsight, fairly obvious, as the interface provides the contract, and the class doesn't.
I now have a different set of errors to deal with, but at least have a bit more understanding of what I'm doing.
Thanks for saving me hours more of banging my head against the wall, I'd reached the stage of not being able to see what I was looking at. | https://social.msdn.microsoft.com/Forums/vstudio/en-US/f2729d17-79f5-4a9c-ac2c-bb6abbe39841/the-contract-name-wcftest1calculatorservice-could-not-be-found-in-the-list-of-contracts?forum=wcf | CC-MAIN-2016-22 | refinedweb | 410 | 68.4 |
In this post, we will learn about Eigenface — an application of Principal Component Analysis (PCA) for human faces. We will also share C++ and Python code written using OpenCV to explain the concept.
The video below shows a demo of EigenFaces. The code for the application shown in the video is shared in this post.
What is PCA?
In our previous post, we learned about a dimensionality reduction technique called PCA. If you have not read the post, please do so. It is a pre-requisite for understanding this post.
To quickly recap, we learned that the first principal component is the direction of maximum variance in the data. The second principal component is the direction of maximum variance in the space perpendicular (orthogonal) to the first principal component and so on and so forth. The first and second principal components the red dots (2D data) are shown using blue and green lines.
We also learned that the first principal component is the eigenvector of the covariance matrix corresponding to the maximum eigenvalue. The second principal component is the eigenvector corresponding to the second largest eigenvalue. If what was said in this paragraph is not clear to you, it is a good idea to brush up your understanding of PCA by reading the previous post
What are EigenFaces ?
Eigenfaces are images that can be added to a mean (average) face to create new facial images. We can write this mathematically as,
where,
is a new face.
is the mean or the average face,
is an EigenFace,
are scalar multipliers we can choose to create new faces. They can be positive or negative.
Eigenfaces are calculated by estimating the principal components of the dataset of facial images. They are used for applications like Face Recognition and Facial Landmark Detection.
An Image as a Vector
In the previous post, all examples shown were 2D or 3D data points. We learned that if we had a collection of these points, we can find the principal components. But how do we represent an image as a point in a higher dimensional space? Let’s look at an example.
A 100 x 100 color image is nothing but an array of 100 x 100 x 3 ( one for each R, G, B color channel ) numbers. Usually, we like to think of 100 x 100 x 3 array as a 3D array, but you can think of it as a long 1D array consisting of 30,000 elements.
You can think of this array of 30k elements as a point in a 30k-dimensional space just as you can imagine an array of 3 numbers (x, y, z) as a point in a 3D space!
How do you visualize a 30k dimensional space? You can’t. Most of the time you can build your argument as if there were only three dimensions, and usually ( but not always ), they hold true for higher dimensional spaces as well.
How to calculate EigenFaces?
To calculate EigenFaces, we need to use the following steps.
- Obtain a facial image dataset : We need a collection of facial images containing different kinds of faces. In this post, we used about 200 images from CelebA.
- Align and resize images : Next we need to align and resize images so the center of the eyes are aligned in all images. This can be done by first finding facial landmarks. In this post, we used aligned images supplied in CelebA. At this point, all the images in the dataset should be the same size.
- Create a data matrix: Create a data matrix containing all images as a row vector. If all the images in the dataset are of size 100 x 100 and there are 1000 images, we will have a data matrix of size 30k x 1000.
- Calculate Mean Vector [Optional]: Before performing PCA on the data, we need to subtract the mean vector. In our case, the mean vector will be a 30k x 1 row vector calculated by averaging all the rows of the data matrix. The reason calculating this mean vector is not necessary for using OpenCV’s PCA class is because OpenCV conveniently calculates the mean for us if the vector is not supplied. This may not be the case in other linear algebra packages.
- Calculate Principal Components: The principal components of this data matrix are calculated by finding the Eigenvectors of the covariance matrix. Fortunately, the PCA class in OpenCV handles this calculation for us. We just need to supply the datamatrix, and out comes a matrix containing the Eigenvectors
- Reshape Eigenvectors to obtain EigenFaces: The Eigenvectors so obtained will have a length of 30k if our dataset contained images of size 100 x 100 x 3. We can reshape these Eigenvectors into 100 x 100 x 3 images to obtain EigenFaces.
Principal Component Analysis (PCA) using OpenCV
The PCA class in OpenCV allows us to compute the principal components of a data matrix. Read the documentation for different usages. Here we are discussing the most common way to use the PCA class.
C++
// Example usage PCA pca(data, Mat(), PCA::DATA_ORDER_ROW, 10); Mat mean = pca.mean; Mat eigenVectors = pca.eigenvectors;
Python
// Example usage mean, eigenVectors = cv2.PCACompute(data, mean=None, maxComponents=10)
where,
EigenFace : C++ and Python Code
In this section, we will examine the relevant parts of the code. The credit for the code goes to Subham Rajgaria . He wrote this code as part of his internship at our company Big Vision LLC.
To easily follow along this tutorial, please download code by clicking on the button below. It’s FREE!
Let’s go over the main function in both C++ and Python. Look for the explanation and expansion of the functions used after this code block.
C++
#define NUM_EIGEN_FACES 10 #define MAX_SLIDER_VALUE 255 int main(int argc, char **argv) { // Directory containing images string dirName = "images/"; // Read images in the directory vector<Mat> images; readImages(dirName, images); // Size of images. All images should be the same size. Size sz = images[0].size(); // Create data matrix for PCA. Mat data = createDataMatrix(images); // Calculate PCA of the data matrix cout << "Calculating PCA ..."; PCA pca(data, Mat(), PCA::DATA_AS_ROW, NUM_EIGEN_FACES); cout << " DONE"<< endl; // Extract mean vector and reshape it to obtain average face averageFace = pca.mean.reshape(3,sz.height); // Find eigen vectors. Mat eigenVectors = pca.eigenvectors; // Reshape Eigenvectors to obtain EigenFaces for(int i = 0; i < NUM_EIGEN_FACES; i++) { Mat eigenFace = eigenVectors.row(i).reshape(3,sz.height); eigenFaces.push_back(eigenFace); } // Show mean face image at 2x the original size Mat output; resize(averageFace, output, Size(), 2, 2); namedWindow("Result", CV_WINDOW_AUTOSIZE); imshow("Result", output); // Create trackbars namedWindow("Trackbars", CV_WINDOW_AUTOSIZE); for(int i = 0; i < NUM_EIGEN_FACES; i++) { sliderValues[i] = MAX_SLIDER_VALUE/2; createTrackbar( "Weight" + to_string(i), "Trackbars", &sliderValues[i], MAX_SLIDER_VALUE, createNewFace); } // You can reset the sliders by clicking on the mean image. setMouseCallback("Result", resetSliderValues); cout << "Usage:" << endl << "\tChange the weights using the sliders" << endl << "\tClick on the result window to reset sliders" << endl << "\tHit ESC to terminate program." << endl; waitKey(0); destroyAllWindows(); }
Python
if __name__ == '__main__': # Number of EigenFaces NUM_EIGEN_FACES = 10 # Maximum weight MAX_SLIDER_VALUE = 255 # Directory containing images dirName = "images" # Read images images = readImages(dirName) # Size of images sz = images[0].shape # Create data matrix for PCA. data = createDataMatrix(images) # Compute the eigenvectors from the stack of images created print("Calculating PCA ", end="...") mean, eigenVectors = cv2.PCACompute(data, mean=None, maxComponents=NUM_EIGEN_FACES) print ("DONE") averageFace = mean.reshape(sz) eigenFaces = []; for eigenVector in eigenVectors: eigenFace = eigenVector.reshape(sz) eigenFaces.append(eigenFace) # Create window for displaying Mean Face cv2.namedWindow("Result", cv2.WINDOW_AUTOSIZE) # Display result at 2x size output = cv2.resize(averageFace, (0,0), fx=2, fy=2) cv2.imshow("Result", output) # Create Window for trackbars cv2.namedWindow("Trackbars", cv2.WINDOW_AUTOSIZE) sliderValues = [] # Create Trackbars for i in xrange(0, NUM_EIGEN_FACES): sliderValues.append(MAX_SLIDER_VALUE/2) cv2.createTrackbar( "Weight" + str(i), "Trackbars", MAX_SLIDER_VALUE/2, MAX_SLIDER_VALUE, createNewFace) # You can reset the sliders by clicking on the mean image. cv2.setMouseCallback("Result", resetSliderValues); print('''Usage: Change the weights using the sliders Click on the result window to reset sliders Hit ESC to terminate program.''') cv2.waitKey(0) cv2.destroyAllWindows()
The above code does the following.
- Set the number of Eigenfaces (NUM_EIGEN_FACES) to 10 and the max value of the sliders (MAX_SLIDER_VALUE) to 255. These numbers are not set in stone. Change these numbers to see how the application changes.
- Read Images : Next we read all images in the specified directory using the function readImages. The directory contains images that are aligned. The center of the left and the right eyes in all images are the same. We add these images to a list ( or vector ). We also flip the images vertically and add them to the list. Because the mirror image of a valid facial image, we just doubled the size of our dataset and made it symmetric at that same time.
- Assemble Data Matrix: Next, we use the function createDataMatrix to assemble the images into a data matrix. Each row of the data matrix is one image. Let’s look into the createDataMatrix function
C++
// Create data matrix from a vector of images static Mat createDataMatrix(const vector<Mat> &images) { cout << "Creating data matrix from images ..."; // Allocate space for all images in one data matrix. // The size of the data matrix is // // ( w * h * 3, numImages ) // // where, // // w = width of an image in the dataset. // h = height of an image in the dataset. // 3 is for the 3 color channels. // numImages = number of images in the dataset. Mat data(static_cast<int>(images.size()), images[0].rows * images[0].cols * 3, CV_32F); // Turn an image into one row vector in the data matrix for(unsigned int i = 0; i < images.size(); i++) { // Extract image as one long vector of size w x h x 3 Mat image = images[i].reshape(1,1); // Copy the long vector into one row of the destm image.copyTo(data.row(i)); } cout << " DONE" << endl; return data; }
Python
def createDataMatrix(images): print("Creating data matrix",end=" ... ") ''' Allocate space for all images in one data matrix. The size of the data matrix is ( w * h * 3, numImages ) where, w = width of an image in the dataset. h = height of an image in the dataset. 3 is for the 3 color channels. ''' numImages = len(images) sz = images[0].shape data = np.zeros((numImages, sz[0] * sz[1] * sz[2]), dtype=np.float32) for i in xrange(0, numImages): image = images[i].flatten() data[i,:] = image print("DONE") return data
- Calculate PCA : Next we calculate the PCA using the PCA class in C++ (see lines 19-23 in the main function above) and the PCACompute function in Python (see line 23 in the main function above). As an output of PCA, we obtain the mean vector and the 10 Eigenvectors.
- Reshape vectors to obtain Average Face and EigenFaces : The mean vector and every Eigenvector is vector of length w * h * 3, where w is the width, h is the height and 3 is the number of color channels of any image in the dataset. In other words, they are vectors of 30k elements. We reshape them to the original size of the image to obtain the average face and the EigenFaces. See line 24-35 in the C++ code and lines 26-32 in Python code.
- Create new face based on slider values. A new face can be created by adding weighted EigenFaces to the average face using the function createNewFace. In OpenCV, slider values cannot be negative. So we calculate the weights by subtracting MAX_SLIDER_VALUE/2 from the current slider value so we can get both positive and negative values.
C++
void createNewFace(int ,void *) { // Start with the mean image Mat output = averageFace.clone(); // Add the eigen faces with the weights for(int i = 0; i < NUM_EIGEN_FACES; i++) { // OpenCV does not allow slider values to be negative. // So we use weight = sliderValue - MAX_SLIDER_VALUE / 2 double weight = sliderValues[i] - MAX_SLIDER_VALUE/2; output = output + eigenFaces[i] * weight; } resize(output, output, Size(), 2, 2); imshow("Result", output); }
Python
def createNewFace(*args): # Start with the mean image output = averageFace # Add the eigen faces with the weights for i in xrange(0, NUM_EIGEN_FACES): ''' OpenCV does not allow slider values to be negative. So we use weight = sliderValue - MAX_SLIDER_VALUE / 2 ''' sliderValues[i] = cv2.getTrackbarPos("Weight" + str(i), "Trackbars"); weight = sliderValues[i] - MAX_SLIDER_VALUE/2 output = np.add(output, eigenFaces[i] * weight) # Display Result at 2x size output = cv2.resize(output, (0,0), fx=2, fy=2) cv2.imshow("Result", output). | https://learnopencv.com/eigenface-using-opencv-c-python/ | CC-MAIN-2021-17 | refinedweb | 2,077 | 56.55 |
.
Hope this helps.
Keith Hasselstrom
OK...what a lessoned learned. I had some time to kill so I think I can help out. I found a package that allows access to the registry. I downloaded the zip file. But the package is called JNI Registry. I can return email you a copy. My email is kmhasselstrom@tasc.com. After setting up the class names it was very easy to traverse the registry.
The code to get my Oracle home on my windows 2000 box is posted below. I have several Oracle installs so you may want to write some code to read all the Oracle homes and get all the values. Then look for several TNS names etc....
If you get a java.lang.path error try this url for help:
Hope this helps...
Keith
import java.util.*;
import javax.naming.*;
import com.ice.jni.registry.*;
public class WinRegAccess extends Object {
public static void main(String[] args) throws RegistryException{
RegistryKey reg = Registry.HKEY_LOCAL_MACHIN
RegistryKey reg2 = reg.openSubKey("ORACLE");
RegistryKey reg3 = reg2.openSubKey("HOME2");
System.out.println(reg3.ge
}
} | https://www.experts-exchange.com/questions/20138677/how-to-get-TNSNAMES-entries-list-using-java-to-access-oracle.html | CC-MAIN-2017-51 | refinedweb | 178 | 71.51 |
Remove PDB disordered atoms
Contributed by Ramon Crehuet with disordered atoms. Each disordered atom has a property indicating its alternative positions: atom.altloc. Usually there are only two alternative positions labelled 'A' and 'B'. The key is to save a PDB with the optional "select" argument. This argument needs to return a True value for the atoms that have to be saved. In the following example we save all not-disordered atoms and the 'A' positions of the disordered ones.
from Bio.PDB import * parser=PDBParser() s=parser.get_structure('my_pdb', 'my_pdb.pdb') io=PDBIO() class NotDisordered(Select): def accept_atom(self, atom): return not atom.is_disordered() or atom.get_altloc()=='A' io=PDBIO() io.set_structure(s) io.save("ordered.pdb", select=NotDisordered())
Discussion
It is trivial to change that to save 'B' altloc positions. One can even do more complicated selections based on other atom properties. The key is to generate a class that returns True or False for a given atom. One could also think of deleting atoms with 'B' values in atom.altloc.
for atom in all_atoms: # all_atoms is a list containg all atoms if atom.altloc=='B': del atom
but that does not work, because it only deletes the local variable and not the PDB structure. | http://www.biopython.org/w/index.php?title=Remove_PDB_disordered_atoms&direction=prev&oldid=3210 | CC-MAIN-2014-42 | refinedweb | 207 | 51.44 |
AWS Amplify is a framework that lets us develop a web or mobile application quickly. In this tutorial, we are going to continue to learn how to perform CRUD operations with the database by using GraphQL mutations. AWS Amplify has a complete toolchain wiring and managing APIs with GraphQL. The API we will be creating in this tutorial is a GraphQL API using AWS AppSync (a managed GraphQL service) and the database will be Amazon DynamoDB (a NoSQL database).
Please before you begin this tutorial to follow the part 1 where we discussed the setting up Amplify as a framework as well as email authentication with custom UI.
Create a GraphQL API
To start creating an API and connect the database run the below command in a terminal window.
amplify add api
Then select the service
GraphQL from the prompt.
This CLI execution automatically does a couple of things. First, it creates a fully functional GraphQL API including data sources, resolvers with basic schema structure for queries, mutations, and subscriptions. It also downloads client-side code and configuration files that are required in order to run these operations by sending requests. The above command will prompt us to choose between what type of API we want to write in. Enter a profile API name. In the below case, we are leaving the profile name to default.
Next, it will again give us two options as to how we want to authenticate the AWS AppSync API. In a real-time application, we have different users accessing the database and making requests to it. Choose the option Amazon Cognito User Pool. This is a more pragmatic approach. Since we have already configured Amazon Cognito User Pool with the authentication module, we do not have to configure it here.
For the next two questions Do you want to configure advanced settings for the GraphQL API and Do you have an annotated GraphQL schema? the answer is
N or no. Amplify comes with pre-defined schemas that can be changed later.
When prompted Choose a schema template, select the option Single object with fields.
Before we proceed, let’s edit the GraphQL schema created by this process. Go to the React Native project, and from the root directory, open the file
amplify/backed/api/[API_NAME]/schema.graphql.
The default model created by the AppSync is the following:
type Todo @model { id: ID! name: String! description: String }
Currently, a warning must have prompted when finished the process in the CLI that is described as:
The following types do not have '@auth' enabled. Consider using @auth with @model - Todo
Since we have the authentication module already enabled we can add the
@auth directive in the
schema.graphql file. By default, enabling owner authorization allows any signed-in user to create records.
type Todo @model @auth(rules: [{ allow: owner }]) { id: ID! name: String! description: String }
If you’re not familiar with GraphQL models and its types here’s a brief overview.
A
type in a GraphQL schema is a piece of data that’s stored in the database. Each type can have a different set of fields. Think of the
type as an object coming from the JavaScript background. For example, in the above schema for the
Todo model is the type that has three fields:
id,
name and
description. Also, the
@model directive is used for storing types in Amazon DynamoDB. This is the database used by Amazon when storing our app data.
Every type in a database generates a unique identity to each piece of information stored to further identify and persist in CRUD operations through HTTP requests. In this case, the id is generated by Amplify and has a value of a built-in type of
id which in GraphQL terminology, is known as a scalar type.
The exclamation mark
! signifies that the field is required when storing the data and it must have a value. In the above schema, there are two required fields:
id and
name for the Todo type.
Save this file and all the changes we have just made are now saved locally.
Publish API to AWS Cloud
To publish all the changes we have made (or left as default) in the local environment to AWS Cloud, run the command
amplify push from the terminal window.
On running the command, as a prompt, it returns a table with information about resources that we have used and modified or enabled. The name of these resources is described in the Category section.
The Resource name in the above table is the API name chosen in the previous section.
The next column is the type of operation needed to send the API—currently, Create. The provider plugin column signifies that these resources are now being published to the cloud. Press
Y to continue.
The Amplify CLI interface will now check for the schema and then compile it for any errors before publishing final changes to the cloud.
In the next step, it prompts us to choose whether we want to generate code for the newly created GraphQL API. Press
Y. Then choose JavaScript as the code generation language.
For the third prompt, let the value be default and press enter. This will create a new folder inside the
src directory that contains the GraphQL schema, query, mutations, and subscriptions as JavaScript files for the API we have created in the previous section.
Y to the next question that asks to update all GraphQL related operations. Also, let maximum statement depth be the default value of
2. It will take a few moments to update the resources on the AWS cloud and will prompt with a success message when done.
At the end of the success message, we get a GraphQL API endpoint. This information is also added to the file
aws-exports.js file in the root directory of the React Native project, automatically.
Adding an Input Field in the React Native App
To capture the user input, we are going to use two state variables using React hook
useState. The first state variable is for the name
name field of the todo item and an array called
todos. This array will be used to fetch all the todo items from the GraphQL API and display the items on the UI.
Add the below code before the JSX returned inside the
Home component:
const [name, setName] = useState(''); const [todos, setTodos] = useState([]);
Next, import
TextInput and
TouchableOpacity from React Native to create an input field and pressable button with some custom styling defined in
StyleSheet reference object below the
Home component. Here’s the complete code for
Home.js:
import React, { useState } from 'react'; import { View, Text, TextInput, TouchableOpacity, StyleSheet, Button, ScrollView, Dimensions } from 'react-native'; import { Auth } from 'aws-amplify'; const { width } = Dimensions.get('window'); export default function Home({ updateAuthState }) { const [name, setName] = useState(''); const [todos, setTodos] = useState([]); async function signOut() { try { await Auth.signOut(); updateAuthState('loggedOut'); } catch (error) { console.log('Error signing out: ', error); } } const addTodo = () => {};> </ScrollView> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', marginTop: 20 }, input: { height: 50, borderBottomWidth: 2, borderBottomColor: 'tomato', marginVertical: 10, width: width * 0.8, fontSize: 16 }, buttonContainer: { backgroundColor: 'tomato', marginVertical: 10, padding: 10, borderRadius: 5, alignItems: 'center', width: width * 0.8 }, buttonText: { color: '#fff', fontSize: 24 } });
Make sure you are running the
expo start command in a terminal window to see the results of this step.
Adding a Mutation using the an item and to retrieve the same in the React Native app, let’s add some business logic to communicate with the GraphQL backend with a mutation.
Inside the file
src/graphql/mutation.js there are mutation functions that we can make use of to create, delete, or update a note in the database.
/* eslint-disable */ // this is an auto generated file. This will be overwritten export const createTodo = /* GraphQL */ ` mutation CreateTodo( $input: CreateTodoInput! $condition: ModelTodoConditionInput ) { createTodo(input: $input, condition: $condition) { id name description createdAt updatedAt owner } } `; export const updateTodo = /* GraphQL */ ` mutation UpdateTodo( $input: UpdateTodoInput! $condition: ModelTodoConditionInput ) { updateTodo(input: $input, condition: $condition) { id name description createdAt updatedAt owner } } `; export const deleteTodo = /* GraphQL */ ` mutation DeleteTodo( $input: DeleteTodoInput! $condition: ModelTodoConditionInput ) { deleteTodo(input: $input, condition: $condition) { id name description createdAt updatedAt owner } } `;
This is done by Amplify and to use any of the above mutations, we can directly import the method in the component file. In
Home.js file, import
API and
graphqlOperation from the package
aws-amplify. The
API is the category for AWS resource and the second function imported is the method to run either a mutation or the query. Also, import the mutation
createTodo from
graphql/mutation.js file.
// ... import { Auth, API, graphqlOperation } from 'aws-amplify'; import { createTodo } from '../graphql/mutations';
Let’s add the logic inside the
addTodo custom handler method we defined in the previous section. It’s going to be an asynchronous function to fetch the result from the mutation and update the
todos array. It takes
name as the input where
name is the text of the item.
const addTodo = async () => { const input = { name }; const result = await API.graphql(graphqlOperation(createTodo, { input })); const newTodo = result.data.createTodo; const updatedTodo = [newTodo, ...todos]; setTodos(updatedTodo); setName(''); };
Before we move on to the next section, try adding some data.
Running a Query to Fetch the Data from AWS AppSync
To fetch the data from the database we need to run a query. Similar to mutations, Amplify also takes care of creating initial queries based on GraphQL schema generated.
All the available queries can be found in the
src/graphql/queries.js.
/* eslint-disable */ // this is an auto generated file. This will be overwritten export const getTodo = /* GraphQL */ ` query GetTodo($id: ID!) { getTodo(id: $id) { id name description createdAt updatedAt owner } } `; export const listTodos = /* GraphQL */ ` query ListTodos( $filter: ModelTodoFilterInput $limit: Int $nextToken: String ) { listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) { items { id name description createdAt updatedAt owner } nextToken } } `;
To fetch all the data from the GraphQL API and display it on the device’s screen, let’s use the query from the file above. Import
listTodos inside
Home.js file:
import { listTodos } from '../graphql/queries';
To fetch the data from the database, let’s use the
useEffect hook. Make sure to import it form React library:
import React, { useState, useEffect } from 'react';
Let’s define another handler method called
fetchTodos to fetch the data by running the query
listTodos. It is going to be an asynchronous method, so let’s use the
try/catch block to catch any initial errors when fetching data. Add the following code snippet inside the
Home component:
useEffect(() => { fetchTodos(); }, []); async function fetchTodos() { try { const todoData = await API.graphql(graphqlOperation(listTodos)); const todos = todoData.data.listTodos.items; console.log(todos); setTodos(todos); } catch (err) { console.log('Error fetching data'); } }
The array of data returned from the database looks like the following:
Let’s some JSX to render the data on a device’s screen as well by mapping over the
todos array.> {todos.map((todo, index) => ( <View key={index} style={styles.itemContainer}> <Text style={styles.itemName}>{todo.name}</Text> </View> ))} </ScrollView> </View> );
Also, update the corresponding styles:
const styles = StyleSheet.create({ // ... itemContainer: { marginTop: 20, borderBottomWidth: 1, borderBottomColor: '#ddd', paddingVertical: 10, flexDirection: 'row', justifyContent: 'space-between' }, itemName: { fontSize: 18 } });
Here is the result you are going to get:
Add a Loading Indicator while the Query is Fetching Data
Right now the when the app is refreshed, or when the user logs in, it takes time to make the network call to load the data, and hence, there is a slight delay in rendering list items. Let’s add a loading indicator using
ActivityIndicator from React Native.
// modify the following import statement import { View, Text, TextInput, TouchableOpacity, StyleSheet, Button, ScrollView, Dimensions, ActivityIndicator } from 'react-native';
To know when to display the loading indicator when the query is running, let’s add a new state variable called
false in the
Home component. When fetching the data, initially this value is going to be
true, and only when the data is fetched from the API, its value is again set to
false.
export default function Home({ updateAuthState }) { // ... const [loading, setLoading] = useState(false); // modify the fetchTodos method async function fetchTodos() { try { setLoading(true); const todoData = await API.graphql(graphqlOperation(listTodos)); const todos = todoData.data.listTodos.items; console.log(todos); setTodos(todos); setLoading(false); } catch (err) { setLoading(false); console.log('Error fetching data'); } } // then modify the JSX contents return ( {/* rest remains same */} <ScrollView> {/* rest remains same */} {loading && ( <View style={styles.loadingContainer}> <ActivityIndicator size="large" color="tomato" /> </View> )} {todos.map((todo, index) => ( <View key={index} style={styles.itemContainer}> <Text style={styles.itemName}>{todo.name}</Text> </View> ))} </ScrollView> ) } // also modify the styles const styles = StyleSheet.create({ // ... loadingContainer: { marginVertical: 10 } });
Here is the output:
Running the Delete Mutation to Delete an Item
To delete an item from the
todos array the mutation
deleteTodo needs to be executed. Let’s add a button on the UI using a
TouchableOpacity and
@expo/vector-icons to each item in the list. In the
Home.js component file, start by importing the icon and the mutation.
// ... import { Feather as Icon } from '@expo/vector-icons'; import { createTodo, deleteTodo } from '../graphql/mutations';
Then, define a handler method called
removeTodo that will delete the todo item from the
todos array as well as update the array by using the
filter method on it. The
input for the mutation this time is going to be the
id of the todo item.
const removeTodo = async id => { try { const input = { id }; const result = await API.graphql( graphqlOperation(deleteTodo, { input }) ); const deletedTodoId = result.data.deleteTodo.id; const updatedTodo = todos.filter(todo => todo.id !== deletedTodoId); setTodos(updatedTodo); } catch (err) { console.log(err); } };
Now, add the button where the todo list items are being rendered.
{ todos.map((todo, index) => { return ( <View key={index} style={styles.itemContainer}> <Text style={styles.itemName}>{todo.name}</Text> <TouchableOpacity onPress={() => removeTodo(todo.id)}> <Icon name="trash-2" size={18} </TouchableOpacity> </View> ); }); }
Here is the output you are going to get after this step.
Summary
On completing this tutorial you can observe how simple it is to get started to create a GraphQL API with AWS AppSync and Amplify.
At Instamobile, we are building ready to use React Native apps, backed by various backends, such as AWS Amplify or Firebase, in order to help developers make their own mobile apps much more quickly. | https://www.instamobile.io/react-native-tutorials/aws-appsync-react-native/ | CC-MAIN-2021-31 | refinedweb | 2,386 | 55.34 |
In order to be more “pythonic” while writing python code, many best practices are recommended. Python list comprehensions, like “dictionary comprehension” or “set comprehension” or using “warlus operator(introduced in python 3.8 )” is found in use in many python libraries.
Let’s see the basic construct for a python list comprehension.
How to write
new_list = [ expression(i) for i in old_list if condition(i) ]
The above expression shows the way a python list comprehension is written. Note that the the right hand side of the “=” starts with “[” and ends with “]” . This means that whatever we write inside the brackets, generates a list, which is the output for ny python list comprehension .
Let’s see an example for the same. Here we shall be creating a list of items ( squared by it’s original value -> i*i ) if the value of the item ( i ) is even (i %2 == 0 )
new_list = [ i*i for i in old_list if i%2 ==0 ]
Let’s take a look at the below function
def list_comp(): old_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] new_list = [i * i for i in old_list if i % 2 == 0] return new_list
Now if we execute the below function,
print(list_comp())We will have the below output
[0, 4, 16, 36, 64]
The above function uses an old list to generate a new list after applying a filter which checks if the current item is even .
In the above code our expression is i*i and condition is i%2 == 0. For more details let’s look at the github repository for the code.
When to use list comprehension ?
When we want to achieve the below points we should consider using a list comprehension in python
- create a new list from a computation
- create a list using a declarative approach
- we want to apply some filters while creating the list
Benefits of using list comprehension
- As it is a declarative way of creating a new list while using list comprehension, the code becomes more readable.
- By using list comprehension we can avoid using loops and map() , and therefore not care about initializing a new list before the start of the loop or not care about the order of augments passed inside the map() . And thus we are better off in writing code
- List comprehension also enables us to write code by applying filter-logic to wipe out data that are not important | https://www.codegigs.app/python-list-comprehension/ | CC-MAIN-2022-05 | refinedweb | 405 | 62.11 |
There's always one particular topic that catches the fancy of most C/C++ programmers, and is considered quite complicated and difficult to understand: pointers!
Albeit, whenever C# is discussed, most of the people I have come across are of the opinion (and pretty strong one, if I may add) that C# carries no concept of pointers. In fact, it's done away with it. However, unsafe code is that part of C# programming, which is all about programming with pointers. Unlike it's literal meaning, there is nothing unsafe about programming with pointers.
The reason it is so referred to as is because, unlike the conventional .NET development that is done, unsafe programming requires certain assumptions on the part of the programmer. In this article, I shall start off by differentiating two highly confused terms, unsafe code and unmanaged code. This will be followed by discussion of how to write unsafe code, that is, how to use pointers in C#.
Managed code is that code which executes under the supervision of the CLR. The CLR is responsible for various housekeeping tasks, like:
just to name a few. The user is totally isolated from the how's of the above mentioned tasks. The user doesn't get to manipulate the memory directly, because that is done by the CLR.
On the other hand, unmanaged code is that code which executes outside the context of the CLR. The best example of this is our traditional Win32 DLLs like kernel32.dll, user32.dll, and the COM components installed on our system. How they allocate memory for their usage, how memory is released, how (if any) type verification takes places are some of the tasks that are undertaken by them on their own. A typical C++ program which allocates memory to a character pointer is another example of unmanaged code because you as the programmer are responsible for:
If you notice, all this housekeeping is done by the CLR, as explained above, relieving the programmer of the burden.
It executes under the supervision of the CLR, just like the managed code, but lets you address the memory directly, through the use of pointers, as is done in unmanaged code. Thus, you get the best of both worlds. You might be writing a .NET application that uses the functionality in a legacy Win32 DLL, whose exported functions require the use of pointers. That's where unsafe code comes to your rescue.
Now that we have gone through the distinctions, let's get coding... unarguably the best part, what do you think?
Writing unsafe code requires the use of two special keywords:
unsafe and
fixed.
If we recall, there are three kinds of pointer operators:
*
&
->
Any statement, or a block of code, or a function that uses any of the above
pointer operators is marked as unsafe through the use of the
unsafe keyword,
as shown below:
public unsafe void Triple(int *pInt) { *pInt=(*pInt)*3; }
All the above function does is triple the value passed to it. But notice that the address of the variable, containing the value to be tripled, is passed to the function. The function then does its work. Since the function is using the "*" pointer operator, the function is marked as unsafe, since the memory is being directly manipulated.
However, there is a problem. If you recall from the discussion above, unsafe code is managed code, and hence, is being executed under the CLR's supervision. Now, the CLR is free to move the objects in memory. One plausible reason could be to reduce the memory fragmentation. But in doing so, unknowingly and transparently to the programmer, the variable being pointed to could be get relocated to some other memory locations.
So, if
*pInt pointed to a variable which was at address
1001, and the CLR performs some memory relocation to reduce fragmentation, the
variable which was earlier located at 1001 could, after relocation, be stored
at memory location 2003. This is a catastrophe, since the pointer becomes invalid
as there is nothing at memory location 1001 after relocation! Probably that's
one of the reason usage of pointers has been made to keep a low profile in .NET.
What do you think?
Enter the
fixed keyword. When used for a block of statements, it tells
the CLR that the object in question cannot be relocated, and thus, it ends
up pinning the object. Thus, when pointers are used in C#, the
fixed
keyword is used pretty often to prevent invalid pointers at runtime.
Lets have a look at how it works:
using System; class CData { public int x; } class CProgram { unsafe static void SetVal(int *pInt) { *pInt=1979; } public unsafe static void Main() { CData d = new CData(); Console.WriteLine("Previous value: {0}", d.x); fixed(int *p=&d.x) { SetVal(p); } Console.WriteLine("New value: {0}", d.x); } }
All we do here is assign the address of field
x of class
CData to integer pointer
p, within the fixed block. Now, while statements within the fixed block are
executing, the pointer shall continue to point to the same memory location because
the CLR has been instructed to pin the variable until the fixed block execution
finishes. Once the fixed block is done, the object can be relocated in memory by the CLR.
That's all there is to programming using pointers in C#. Just make sure
that the block is
unsafe and that the object being pointed to is
fixed. And you are ready to
leverage your knowledge of pointers in C# too!
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/cs/unsafe_prog.aspx | crawl-002 | refinedweb | 931 | 62.98 |
Contents
addition: <Number> + <Number> = <Number>
multiplication: <Number> * <Number> = <Number>
subtraction: <Number> - <Number> = <Number>
division: <Number> / <Number> = <Number>
A <name> in Python can be any sequence of letters, numbers, and underscores (_) that does not start with a number. We usually use all lowercase letters for variable names, but capitalization must match exactly. Here are some valid examples of names in Python (but most of these would not be good choices to actually use in your programs):
An assignment statement assigns a value to a variable:
After the assignment statement, the variable <name> refers to the value of the <expression> on the right side of the assignment. An <expression> is any Python construct that has a value.
We can put more than one name on the left side of an assignment statement, and a corresponding number of expressions on the right side:
All of the expressions on the right side are evaluated first. Then, each name on the left side is assigned to reference the value of the corresponding expression on the right side. This is handy for swapping variable values. For example,
would swap the values of s and t so after the assignment statement s now refers to the previous value of t, and t refers to the previous value of s.
Note: what is really going on here is a bit different. The multiple values are packed in a tuple (which is similar to the list data type introduced in Unit 3, but an immutable version of a list), and then unpacked into its components when there are multiple names on the left side. This distinction is not important for what we do in CS101, but does become important in some contexts.
A procedure takes inputs and produces outputs. It is an abstraction that provides a way to use the same code to operate on different data by passing in that data as its inputs.
Defining a procedure:
def <Name>(<Parameters>): <Block>
The <Parameters> are the inputs to the procedure. There is one <Name> for each input in order, separated by commas. There can be any number of parameters (including none).
To produce outputs:
return <Expression>, <Expression>, ...
There can be any number of expressions following the return (including none, in which case the output of the procedure is the special value None).
Using a procedure:
<''Procedure''>(<Input>, <Input>, ...)
The number of inputs must match the number of parameters. The value of each input is assigned to the value of each parameter name in order, and then the block is evaluated.
The if statement provides a way to control what code executes based on the result of a test expression.
if <TestExpression>: <Block>
The code in <Block> only executes if the <TestExpression> has a True value.
Alternate clauses. We can use an else clause in an if statement to provide code that will run when the <TestExpression> has a False value.
if <TestExpression>: <BlockTrue> else: <BlockFalse>
The and and or operators behave similarly to logical conjunction (and) and disjunction (or). The important property they have which is different from other operators is that the second operand expression is evaluated only when necessary.
Loops provide a way to evaluate the same block of code an arbitrary number of times.
A while loop provides a way to keep executing a block of code as long as a test expression is True.
while <TestExpression>: <Block>
If the <TestExpression> evaluates to False, the while loop is done and execution continues with the following statement. If the <TestExpression> evaluates to True, the <Block> is executed. Then, the loop repeats, returning to the <TestExpression> and continuing to evaluate the <Block> as long as the <TestExpression> is True.
A for loop provides a way to execute a block once for each element of a collection:
for <Name> in <Collection>: <Block>
The loop goes through each element of the collection, assigning that element to the <Name> and evaluating the <Block>. The collection could be a String, in which case the elements are the characters of a string; a List, in which case the elements are the elements of the list; a Dictionary, in which case the elements are the keys in the dictionary; or many other types in Python that represent collections of objects.
A string is sequence of characters surrounded by quotes. The quotes can be either single or double quotes, but the quotes at both ends of the string must be the same type. Here are some examples of strings in Python:
length: len(<String>) = <Number>
string concatenation: <String> + <String> = <String>
string multiplication: <String> * <Number> = <String>
The indexing operator provides a way to extract subsequences of characters from a string.
string indexing: <String>[<Number>] = <String>
string extraction: <String>[<Start Number>:<Stop Number>] = <String>
find The find method provides a way to find sub-sequences of characters in strings.
find: <Search String>.find(<Target String>) = <Number>
To find later occurrences, we can also pass in a number to find:
find after: <Search String>.find(<Target String>, <Start Number>) = <Number>
str: str(<Number>) = <String>
ord: ord(<One-Character String>) = <Number>
chr: chr(<Number>) = <One-Character String>
split: <String>.split() = [<String>, <String>, ... ]
A for loop provides a way to execute a block once for each character in a string (just like looping through the elements of a list):
for <*Name*> in <*String*>: <*Block*>
The loop goes through each character of the string in turn, assigning that element to the <Name> and evaluating the <Block>.
A list is a mutable collection of objects. The elements in a list can be of any type, including other lists.
Constructing a list. A list is a sequence of zero or more elements, surrounded by square brackets:
Selecting elements: <List>[<Number>] = <Element>
Selecting sub-sequences: <List>[<Start> : <Stop>] = <List>
Update: <List>[<Number>] = <Value>
Length: len(<List>) = <Number>
Append: <List>.append(<Element>)
Concatenation: <List~1~> + <List~2~> = <List~3~>**
Popping: <List>.pop() = <Element>
Finding: <List>.index(<Value>) = <Number>
Membership: <Value> in <List> = <Boolean>
Non-membership: <Value> not in <List> = <Boolean>
A for loop provides a way to execute a block once for each element of a list:
for <Name> in <List>: <Block> | https://www.udacity.com/wiki/cs101/unit3-python-reference | CC-MAIN-2016-50 | refinedweb | 1,018 | 59.53 |
Created on 2019-05-04 12:33 by CharlieClark, last changed 2020-02-12 09:43 by steve.dower.
Based on a bug report () from a user of the openpyxl library I've identified a bug in the zipfile module that causes the Python process to crash on Windows. Currently tested with Python 3.7.3 (32-bit on Windows 10).
Sample code
import faulthandler
import locale
from zipfile import ZipFile
faulthandler.enable()
locale.setlocale(locale.LC_ALL, 'de_DE')
out = open("out.zip", "wb")
archive = ZipFile(out, "w")
archive.writestr("properties.xml", b"<workbookPr/>")
faulthandler fingers line 1757 as the culprit but running this line locally does not cause the crash. The issue seems to be limited to Windows.
I can't reproduce this error on my system by using the same code.
Could you share the system info with us?
Or would you share the Exception with us ?
I guess it's caused by system setting
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Same environment.
But I still can not reproduce this exception. I guess maybe it's about the local time or timezone problem. I will find a way to figure it out
That's what we thought when we looked at it, but as I said, I couldn't reproduce it with just the `time` call or the `ZInfo` instantiation, so something odd is happening. I do have a German version of Windows as I suspect the original reporter does. You'd think that sort of thing wouldn't matter…
I can reproduce it on Python 3.7.3 german Windows10 enterprise
Windows fatal exception: code 0xc0000374
Current thread 0x00003bc8 (most recent call first):
File "C:\Python37\lib\zipfile.py", line 1757 in writestr
Hi Dominik Geldmacher
May I get your system version? 1809 or 1903?
I guess maybe it's microsoft error
Enterprise 1809 and Professional 1803 (german localized) both reproduce the issue
copy that
I will reset my locale setting to figure it out
winver tells me I have 1809. I'm only using Windows in a VM so I'm not that familiar with its innards.
Also get the error with WinPython 3.6:
Windows fatal exception: code 0xc0000374
Current thread 0x000010c0 (most recent call first):
File "C:\Users\charlieclark\WPy64-3680\python-3.6.8.amd64\lib\zipfile.py", line 1658 in writestr
File "<stdin>", line 1 in <module>
Related to issue bpo-36319
I can confirm the error is caused by time.localtime(time.time()) as indicated by the related bug.
I've also found the crash log. It's in C:\ProgramData\Microsoft\Windows\WER\ReportQueue on my machine. Well, at least that's all I can find.
So does that mean that simply doing:
import locale, time
locale.setlocale(locale.LC_ALL, 'de_DE')
time.localtime(time.time())
is enough to trigger the heap corruption? If yes, then what is the output of:
import locale, time
locale.setlocale(locale.LC_ALL, 'de_DE')
time.strftime('%Z')
import time, locale
locale.setlocale(locale.LC_ALL, 'de_DE')
'de_DE'
time.strftime("%Z")
aborted (disconnected)
Ok, now let's try it using the C runtime directly:)
count: 28
value: b'Mitteleurop\xe4ische Sommerzeit'
Oops, I forgot to add in my snippet, the setlocale() call prior to calling the C strftime() function. So an updated test:
import locale
locale.setlocale(locale.LC_ALL, 'de_DE'))
count: 28
value: b'Mitteleurop\xe4ische Sommerzeit'
count: 28
value: Mitteleuropäische Sommerzeit
count: 28
value: Mitteleuropäische Sommerzeit
> libc = ctypes.cdll.msvcrt
That's the private CRT of Windows, not the Universal CRT for applications. In a release build (python.exe), use ctypes.CDLL('ucrtbase', use_errno=True). In a debug build (python_d.exe), use ctypes.CDLL('ucrtbased', use_errno=True).
I suppose we should use API sets [1] for the release build, such as "api-ms-win-crt-locale-l1-1-0" and
"api-ms-win-crt-time-l1-1-0". But they resolve to "ucrtbase".
[1]:
Thanks for the reminder Eryk Sun. This means the test needs to be run yet one more time :)
import ctypes, locale, struct
crt_time = ctypes.CDLL('api-ms-win-crt-time-l1-1-0', use_errno=True)
locale.setlocale(locale.LC_ALL, 'de_DE')
buf = ctypes.create_string_buffer(1024)
tm = struct.pack('9i', 2019, 5, 6, 9, 50, 4, 0, 126, 1)
print('count:', crt_time.strftime(buf, 1024, b'%Z', tm))
print('value:', buf.value)
wbuf = ctypes.create_unicode_buffer(1024)
print('count:', crt_time.wcsftime(wbuf, 1024, '%Z', tm))
print('value:', wbuf.value)
crt_convert = ctypes.CDLL('api-ms-win-crt-convert-l1-1-0', use_errno=True)
print('count:', crt_convert.mbstowcs(wbuf, buf, 1024))
print('value:', wbuf.value)
The code crashes on this line:
print('count:', crt_time.strftime(buf, 1024, b'%Z', tm))
Thanks for your patience with this Charlie, but please try another run this time without the strftime() and mbstowcs() calls. Honest, we are getting closer!
If the process crashes at the first print statement, I'm not sure how I can run the tests. Or should I try them separately?
You can safely execute each line individually (omitting the aforementioned count/value pairs) or depending on how the copy/paste is being done, just paste the script into a text editor (notepad) and comment out those lines. Then copy-paste that modified script.
This time I'm really attempting to see if the internal encoding/decoding done in the CRT strftime() is failing somehow (it calls wcsftime).
print('count:', crt_time.wcsftime(wbuf, 1024, '%Z', tm)) also fails
but
crt_convert = ctypes.CDLL('api-ms-win-crt-convert-l1-1-0', use_errno=True)
print('count:', crt_convert.mbstowcs(wbuf, buf, 1024))
seems to work okay.
Here is another test, this time removing Python from the equation (mostly :)
import ctypes, struct
crt_locale = ctypes.CDLL('api-ms-win-crt-locale-l1-1-0', use_errno=True)
crt_time = ctypes.CDLL('api-ms-win-crt-time-l1-1-0', use_errno=True)
crt_locale._wsetlocale.restype = ctypes.c_wchar_p
print('old locale:', crt_locale._wsetlocale(0, 0))
tm = struct.pack('9i', 2019, 5, 6, 9, 50, 4, 0, 126, 1)
wbuf = ctypes.create_unicode_buffer(1024)
print('count:', crt_time.wcsftime(wbuf, 1024, '%Z', tm))
print('value:', wbuf.value)
print('new locale:', crt_locale._wsetlocale(0, 'de_DE'))
print('count:', crt_time.wcsftime(wbuf, 1024, '%Z', tm))
print('value:', wbuf.value)
And this is the result.
old locale: C
count: 28
value: Mitteleuropäische Sommerzeit
new locale: de_DE
count: -1
value:
Windows fatal exception: code 0xc0000374
Looks like
print('new locale:', crt_locale._wsetlocale(0, 'de_DE'))
print('count:', crt_time.wcsftime(wbuf, 1024, '%Z', tm))
is the culprit.
Final test, this time, no Python what so ever. I've added a zip containing a simple C program (source and .exe) that performs the same test.
The output should be similar to:
--------
The current locale is now: C
The time zone is: 'Mountain Daylight Time' (22 characters)
--------
The updated locale is now: de_DE
The time zone is: 'Mountain Daylight Time' (22 characters)
--------
If this crashes, the problem is then within the CRT itself :(
This is the result
\issue36792>test.exe
--------
The current locale is now: C
The time zone is: 'Mitteleuropõische Sommerzeit' (28 characters)
--------
The updated locale is now: de_DE
The time zone is: '' (-1 characters)
--------
NB something is wrong with that string. Should be Mitteleuropäsiche Sommerzeit but that could just be an encoding thing.
Thanks again! I will have some more tests for you to try tomorrow as I am out of time for today.
I'm currently of the belief that there is something Python is going to have to do to work around an issue within the CRT, but more testing will prove that theory.
I've added another test executable (issue36792-2.zip) which should bring some insight into where things are going wrong. Please run and post the results.
I have managed to setup a VM that can reproduce the error. Unfortunately, the error (heap corruption) is coming from within the UCRT. Attempting to work around that, I came across another error in the UCRT.
Due to these errors in all available UCRT versions, the only available solution is to re-implement %Z handling in Python's implementation of strftime().
@steve.dower: If you could forward the following information to the interested parties for faster response, it would be great.
Everyone else, what follows contains UCRT internal details which is of no interest to Python.
In wcsftime() [ucrt\time\wcsftime.cpp, line 1018], the call to _mbstowcs_s_l() doesn't handle the error case of EILSEQ. This error happens when the tzname (originally set by __tzset() from the Unicode name in the registry encoded to the ACP) contains an undecodable character. In the 'de_DE' case, \u00E4. _mbstowcs_s_l returns without changing `wnum` (which is 0). The 'Z' case then blindly subtracts 1 (wnum=-1) and advances the string pointer, now pointing *before* the start when the format is just L"%Z" (like Python has). Now when wcsftime() is returning it stores a '\0' at that current position thus causing a heap corruption.
Ok, no deal breaker, we can just update the _tzname array when we call setlocale(). Alas, another error :( If _tzset() is called a second time, it fails when encoding the Unicode name due to an uninitialized variable. In tzset_from_system_nolock() [ucrt\time\tzset.cpp, line 158], the function __acrt_WideCharToMultiByte() [appcrt\locale\widechartomultibyte.cpp] does not set the `lpUsedDefaultChar` flag when FALSE. This is only an issue, it seems, on subsequent calls as `used_default_char` can be non-zero prior to the call. A non-zero value there, causes the tzname to be set to the empty string even if the conversion succeeded.
I've received a detailed response from the UCRT team, and there are a few pieces here.
* the fact that tzname is cached in ACP is known and will be fixed
* the decoding bug is real, but it's due to the experimental UTF-8 support
* the experimental UTF-8 support was enabled because "de_DE" is not a known Windows locale name - try with "de-DE"
Perhaps it would be easy to do the replacement of underscores with hyphens on Windows in this function? I think that's safe enough, yes?
I can confirm that using "de-DE" does indeed avoid the crash.
> * the experimental UTF-8 support was enabled because "de_DE" is not a
> known Windows locale name - try with "de-DE"
>
> Perhaps it would be easy to do the replacement of underscores with hyphens
> on Windows in this function? I think that's safe enough, yes?
>
Even some well known locale names still use the utf-8 code page. Most seem
to uncommon, but at least es-BR (Brazil) does and would still fall victim
to these UCRT bugs.
>
> Perhaps it would be easy to do the replacement of underscores with
> hyphens on Windows in this function? I think that's safe enough, yes?
Recent releases of ucrt implement this translation from underscore to hyphen for us, so this suggestion is no longer always necessary. However, I don't know what the PEP-11 stance is regarding the modern lifecycle policy of Windows 10.?
> Even some well known locale names still use the utf-8 code page. Most
> seem to uncommon, but at least es-BR (Brazil) does and would still
> fall victim to these UCRT bugs.
es-BR is a custom locale for the Spanish language in Brazil, as opposed to the common Portuguese locale (pt-BR). It's a Unicode-only locale, which means its ANSI codepage is 0. Since 0 is CP_ACP, its effective ANSI codepage is the system or process ANSI codepage.
For example:
>>> kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
>>> buf = (ctypes.c_wchar * 10)()
Portuguese in Brazil uses codepage 1252 as its ANSI codepage:
>>> n = kernel32.GetLocaleInfoEx('pt-BR', 0x1004, buf, 10)
>>> buf.value
'1252'
Spanish in Brazil uses CP_ACP:
>>> n = kernel32.GetLocaleInfoEx('es-BR', 0x1004, buf, 10)
>>> buf.value
'0'
hi-IN (Hindi, India) is a common Unicode-only locale:
>>> n = kernel32.GetLocaleInfoEx('hi-IN', 0x1004, buf, 10)
>>> buf.value
'0'
ucrt has switched to using UTF-8 for Unicode-only locales:
>>> locale.setlocale(locale.LC_CTYPE, 'hi_IN')
'hi_IN'
>>> ucrt = ctypes.CDLL('ucrtbase', use_errno=True)
>>> ucrt.___lc_codepage_func()
65001
Note that ucrt uses UTF-8 for Unicode-only locales only when using an explicitly named locale such as "hi_IN", "Hindi_India" or even just "Hindi". On the other hand, if a Unicode-only locale is used implicitly, ucrt instead uses the system ANSI codepage:
>>> locale.setlocale(locale.LC_CTYPE, '')
'Hindi_India.1252'
>>> ucrt.___lc_codepage_func()
1252
I suppose this is for backwards compatibility. Windows 10 at least supports setting the system ANSI codepage to UTF-8, or overriding the process ANSI codepage to UTF-8 via the application manifest "actveCodePage" setting. For the latter, I modified the manifest in a "python_utf8.exe" copy of the normal "python.exe" binary, which is simpler than having to reboot to change the system locale:
C:\>python_utf8 -q
>>> import locale
>>> locale.setlocale(locale.LC_CTYPE, '')
'Hindi_India.utf8'
That the CRT caches the tzname strings as ANSI multibyte strings is frustrating -- whether or not it's buggy. I would expect there to be a _wtzname cache of the native OS strings that wcsftime uses directly, with no potential for failed encodings (e.g. empty strings or mojibake).
It's also strange that it encodes the time-zone name using the system ANSI codepage in the C locale. Normally LC_CTYPE in the C locale uses Latin-1, due to simple casting between WCHAR and CHAR. This leads to mojibake when the ANSI time-zone name gets decoded as Latin-1 by an internal mbstowcs call in wcsftime. I'm not saying one or the other is necessarily right, but more care should haven gone into this. At the very least, if we're stuck with system ANSI tzname strings in the C locale, then a flag should be set that tells wcsftime to decode them as system ANSI strings instead of via mbstowcs.
Also, the timezone name is determined by the preferred UI language of the current user, which is not necessarily compatible with the system ANSI codepage. It's not even necessarily compatible with the user-locale ANSI codepage, as used by setlocale(LC_CTYPE, ""). Windows 10 at least provides an option to sync the user locale with the user preferred UI language. IMO, this is a strong argument in favor of using _wtzname wide-character strings. UI Language (MUI) and locale are not tightly coupled in Windows NLS.
Here's an example where the user's preferred language is Hindi, and the time zone name is "समन्वित वैश्विक समय" (i.e. Coordinated Universal Time), but the system locale is English with codepage 1252 (for Western European languages). This is a normal configuration if the system locale doesn't have beta UTF-8 support enabled, or if the process ANSI codepage isn't overridden to UTF-8 via the "activeCodePage" manifest setting.
The tzname strings normally get set by a one-time _tzset call, and they're only reset if tzset is called manually. tzset uses the system ANSI encoding if LC_CTYPE is the "C" locale (again, normally ucrt uses Latin-1 in the "C" locale). Since the encoding of the Hindi timezone name to codepage 1252 contains the default character ("?"), which is not allowed, tzset sets the tzname strings to empty strings.
import ctypes, locale, time
ucrt = ctypes.CDLL('ucrtbase', use_errno=True)
ucrt.__tzname.restype = ctypes.POINTER(ctypes.c_char_p)
tzname = ucrt.__tzname()
>>> locale.setlocale(locale.LC_CTYPE, 'C')
'C'
>>> ucrt._tzset()
0
>>> tzname[0], tzname[1]
(b'', b'')
>>> time.strftime('%Z')
''
If we update the LC_CTYPE category to use UTF-8, the cached tzname value doesn't get automatically updated, and strftime still returns an empty string:
>>> locale.setlocale(locale.LC_CTYPE, '.utf8')
'Hindi_India.utf8'
>>> tzname[0], tzname[1]
(b'', b'')
>>> time.strftime('%Z')
''
The tzname values get updated if we manually call tzset:
>>> ucrt._tzset()
0
>>> tzname[0].decode('utf-8'), tzname[1].decode('utf-8')
('समन्वित वैश्विक समय', 'समन्वित वैश्विक समय')
However, LC_TIME is still in the "C" locale. strftime uses system ANSI (1252) in this case, so the encoded result from the CRT strftime call ends up using the default character (?):
>>> time.strftime('%Z')
'??????? ??????? ???'
If we set LC_TIME to UTF-8, we finally get a valid result:
>>> locale.setlocale(locale.LC_TIME, '.utf8')
'Hindi_India.utf8'
>>> time.strftime('%Z')
'समन्वित वैश्विक समय'
We wouldn't have to worry about LC_TIME here if Python called C wcsftime instead of C strftime. The problem that bpo-10653 was trying to work around is a design flaw in the C runtime library, and calling strftime is not a solution.
Here's a variation on my example in msg243660, continuing with the current Hindi example. The setup in this example uses UTF-8 as the system ANSI codepage (via python_utf8.exe) and sets LC_CTYPE to the "C" locale. This yields the following monstrosity:
>>> time.strftime('%Z')
'Ã\xa0¤¸Ã\xa0¤®Ã\xa0¤¨Ã\xa0Â¥Â\x8dÃ\xa0¤µÃ\xa0¤¿Ã\xa0¤¤ Ã\xa0¤µÃ\xa0Â¥Â\x88Ã\xa0¤¶Ã\xa0Â¥Â\x8dÃ\xa0¤µÃ\xa0¤¿Ã\xa0¤Â\x95 Ã\xa0¤¸Ã\xa0¤®Ã\xa0¤¯'
It's due to the following sequence of encoding and decoding operations:
>>> mbs_lcctype_utf8 = 'समन्वित वैश्विक समय'.encode('utf-8')
>>> wcs_lcctype_latin1 = mbs_lcctype_utf8.decode('latin-1')
>>> mbs_lctime_utf8 = wcs_lcctype_latin1.encode('utf-8')
This last one is from PyUnicode_DecodeLocaleAndSize and mbstowcs:
>>> py_str_lcctype_latin1 = mbs_lctime_utf8.decode('latin-1')
>>> py_str_lcctype_latin1 == time.strftime('%Z')
True
>?
This needs a separate discussion on python-dev, but for issues like this I think it's fine to blame the underlying platform and recommend getting their updates. We don't have to work around every Windows bug for all time.
I'll read the rest of what's been happening on this issue when I'm less tired, but not quite up to it right now ;) | https://bugs.python.org/issue36792 | CC-MAIN-2020-45 | refinedweb | 2,984 | 58.89 |
My head keeps spinning as I'm reading about Twisted and all that it can do. I think Twisted is a great word for what it does to fire the human neurons in ones brain when one first discovers Twisted (its like discovering a new planet)! I just finished reading the document titled, "Network Programming for the Rest of Us" and its really awesome. Network programming is not for the faint of heart and abstractions such as Deferred and using Event Loops for an asynchronous interdependent world that we now live in is just way way cool (as is the simplicity and the namespace being well done). It may not be as big of a deal for those who have lived closer to the world of networked programming, but I think Twisted represents a major leap for humankind because it truly opens the doors of opportunity for programming really interesting and dynamic applications (especially for those who need to bridge information science with another discipline or two). The Twisted contributors are "gods" IMHO! Thank you thank you thank you!!!! Sergio _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* | http://twistedmatrix.com/pipermail/twisted-python/2004-July/008091.html | CC-MAIN-2015-22 | refinedweb | 192 | 55.68 |
I have a data container which has following requirements:
The solution I have come
up with is as follows:
I meet with the next question later days ago. Why don´t work action
method setTemplate in a block inherit of
Mage_Catalog_Block_Product_Abstract if this block is a child of
Mage_Core_Block_Template. This are my test cases
First
case:
<reference name="before_footer_start">
<block type="newproducts/newproducts" template="template.phtml" /><
Im using Mustache.js to fill dynamically the html content, i know that I
can use the {% templatetag %} tag, but I want to use these
files as Django templates and as Mustach.js templates, and also I found te
template tag too large for programming.
{% templatetag %}
I want to create a new
tag like {% include_template "templates/none/absolute/url.hmtl"
%} or is it possible to e
{% include_template "templates/none/absolute/url.hmtl"
%}
To illustrate my question more clearly, let's suppose I have a
include.html template with content:
{% block test_block
%}This is include{% endblock %}
I have another
template called parent.html with content like this:
This is
parent{% include "include.html" %}
Now I create
a templated called child.html that extends pa
This could be very silly...
If I have such a template class
A,
template <class T1, class T2>struct A{ T1 a; T2 b;};
and a
function works on it,
template <class T1, class T2>void foo(A<T1, T2> *p){}
now I
subclass A,
struct B :
i try to make intensive use of templates to wrap a factory class:
The wrapping class (i.e. classA) gets the wrapped class (i.e. classB)
via an template-argument to provide 'pluggability'.
Additionally i have to provide an inner-class (innerA) that inherits
from the wrapped inner-class (innerB).
The problem is the
following error-message of the g++ "gcc versio
One of the possible forms of template parameter is a class template. The
C++ standard (C++2003) states that an argument for a template template
parameter during the template instantiation is an "id-expression". This
non-terminal is rather wide. It allows destructors, overloaded operators,
etc. For example the following code should compile fine:
template <template <typename
I have to display different medical forms according to which state the
user is in. There is also a default form that many of the states share.
These medical forms are all written in Template Toolkit and they are
included in larger templates. The state is available as a variable in a
normalized form.
I need to select the state-specific template,
if it exists, otherwise fall back t
I have a class Helper:
Helper
template <typename
T, template <typename> E>class Helper { ...};
I have another class template,
Exposure, which is to inherit from Helper while
passing itself as the template template parameter E. I also
need to specialize Exposure. Thus
Exposure
E
It has been a while since I have used templates with C++, but now I
really need them.
I reproduced a problem I am having and I
don't remember how the solution actually went.
#include
<iostream>#include <vector>namespace problem { template <typename T> class data {
public: inline data(T var) | http://bighow.org/tags/Template/1 | CC-MAIN-2017-47 | refinedweb | 519 | 55.74 |
Here is a listing of advanced C++ programming questions on “Floating Point Types” along with answers, explanations and/or solutions:
1. Which of the following is not one of the sizes of the floating point types?
a) short float
b) float
c) long double
d) double
View Answer
Explanation: Floating point types occur in only three sizes-float, long double and double.
2. Which of the following is a valid floating-point literal?
a) f287.333
b) F287.333
c) 287.e2
d) 287.3.e2
View Answer
Explanation: To make a floating point literal, we should attach a suffix of ‘f’ or ‘F’ and there should not be any blank space.
3. What is the range of the floating point numbers?
a) -3.4E+38 to +3.4E+38
b) -3.4E+38 to +3.4E+34
c) -3.4E+38 to +3.4E+36
d) -3.4E+38 to +3.4E+32
View Answer
Explanation: This is the defined range of floating type number sin C++. Also range for +ve and -ve side should be same so the answer is -3.4E+38 to +3.4E+38.
4. Which of three sizes of floating point types should be used when extended precision is required?
a) float
b) double
c) long double
d) extended float
View Answer
Explanation: Float for single precision, double for double precision and long double for extended precision.
5. What is the output of this program?
#include <iostream>
using namespace std;
int main()
{
float num1 = 1.1;
double num2 = 1.1;
if (num1 == num2)
cout << "stanford";
else
cout << "harvard";
return 0;
}
a) harvard
b) stanford
c) compile time error
d) runtime error
View Answer
Explanation: Float store floating point numbers with 8 place accuracy and requires 4 bytes of Memory. Double has 16 place accuracy having the size of 8 bytes.
Output:
$ g++ float3.cpp $ a.out harvard
6. What is the output of this program?
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
cout << setprecision(17);
double d = 0.1;
cout << d << endl;
return 0;
}
a) 0.11
b) 0.10000000000000001
c) 0.100001
d) compile time error
View Answer
Explantion: The double had to truncate the approximatioit’sue to its limited memory, which resulted in a number that is not exactly 0.1.
Output:
$ g++ float2.out $ a.out 0.10000000000000001
7. What is the output of the following program?
#include <iostream>
using namespace std;
int main()
{
float i = 123.0f;
cout << i << endl;
return 0;
}
a) 123.00
b) 1.23
c) 123
d) compile time error
View Answer
Explanation: The value 123 is printed because of its precision.
$ g++ float.cpp $ a.out 123
8. Which is used to indicate single precision value?
a) F or f
b) L or l
c) Either F or for L or l
d) Neither F or for L or l
View Answer
Explanation: Either F or f can be used to indicate single precision values.
9. What is the output of this program?
#include <iostream>
using namespace std;
int main()
{
float f1 = 0.5;
double f2 = 0.5;
if (f1 == 0.5f)
cout << "equal";
else
cout << "not equal";
return 0;
}
a) equal
b) not equal
c) compile time error
d) runtime error
View Answer
Explanation: 0.5f results in 0.5 to be stored in floating point representations.
Output:
$ g++ float.cpp $ a.out equal
10. Which is correct with respect to size of the data types?
a) char > int < float
b) int < char > float
c) char < int < float
d) char < int < double
View Answer
Explanation: The char has less bytes than int and int has less bytes than double whereas int and float can potentially have same sizes.
Sanfoundry Global Education & Learning Series – C++ Programming Language. | https://www.sanfoundry.com/advanced-c-plus-plus-programming-questions-floating-point-types/ | CC-MAIN-2019-09 | refinedweb | 624 | 77.84 |
Why if I have a module like this:
module Demo
suma(a) = a + 1
end
I can access it through Demo.suma(123), if it has not been exported, should not be exported first to be accessed?
Why if I have a module like this:
module Demo
suma(a) = a + 1
end
I can access it through Demo.suma(123), if it has not been exported, should not be exported first to be accessed?
No,
export only affects what you get when you
using. You might find useful.
So there is no way to make something private to the module?
If I understand right, I think Julia takes the Python approach to visibility: that private declarations are just suggestions denoted by a naming convention (e.g. prepending an underscore), but beyond that are not meaningfull.
do you have an example of that in a library or in the stdlib?
Of the underscore convention? Doing a
Base.<tab> at the repl makes me think it’s pretty common in the standard library (I’m greeted with a tonne of underscored names, e.g.
Base._memcpy! and
Base._pointer, which I presume are “private” methods.
The “using” thing is something I just learned too (I’m pretty new to the language myself):
module MyModule function pubfun() println("This is a public function") end function _prifun() println("This is a private function") end export pubfun end # Un-exported stuff stays out of global namespace on "using" using .MyModule pubfun() _prifun() #= This is a public function UndefVarError: _prifun not defined Stacktrace: [1] top-level scope at In[3]:17 =# # But is ultimately still accessible import .MyModule MyModule._prifun() #= This is a private function =#
so I guess I was wrong to say that declaring things private is totally “meaningless”, but clearly the language is using a sort of “house-sitter” philosophy to module-member visibility (i.e. you know what rooms you’re not supposed to be in, but nobody is really stopping you).
I’m a firm believer in house sitter model in any interpreted language. The basic reason is that if you want to call something and the language “doesn’t let you”, you could always just copy and paste the source. Given that, why make life harder for your users? | https://discourse.julialang.org/t/unexported-functions/28061 | CC-MAIN-2022-21 | refinedweb | 378 | 62.98 |
I keep on getting one error when I compile this. I can't figure out what is wrong with it. Please help.
//Write a program that asks the user to enter two integers. //The program should divide the first integer by the second and then display the resulting quotient and remainder. #include <iostream.h> //using namespace std; int main() { //Declare the variables int il, i2, quotient, remainder; // Obtain the data from the user cout<<"Input an integer followed by a return: "; cin>>i1; cout<<"Input an integer followed by a return: "; cin>>i2; // Do the arithmetic quotient= i1/i2; remainder=i1 % i2; // Output the results cout<<"\nThe quotient of " << i1 << " and "<< i2 <<"is"<< i1/i2; cin>>il; cout<<"The quotient of " << i1 << " and "<< i2 <<"is"<< i1/i2; cin>>i2; cout<<"\nThe remainder when "<<i1<<" is divided by "<<i2<<"is"<< remainder; return 0; }
error C2065: 'i1' : undeclared identifier
Error executing cl.exe. | https://www.daniweb.com/programming/software-development/threads/13270/error-message-when-compiling-program | CC-MAIN-2018-30 | refinedweb | 151 | 52.73 |
Quandl aims to give you whatever data you need, in whatever form you need. Stock prices, economic data, commodity futures; R, Python, Excel or JSON API – you choose, and we deliver.
Let’s say you want Facebook’s stock price. The Quandl code for this dataset is WIKI/FB. To download the data from the Quandl website in CSV, XML or JSON format, just go to quandl.com/data/WIKI/FB and click the red download button.
If you’re a programmer, you can get the same data using the Quandl API. All you have to do is type this into your terminal:
curl
This has the advantage that you can easily loop through, not just FB, but 1000s of other stock tickers.
But most data analysts are not programmers, nor do they want to be. They prefer to get data into the analysis tool of their choice, whether that’s R or Python or Excel or Matlab. Quandl makes that easy.
To get the exact same dataset into Python, you simply have to run this piece of code:
import Quandl mydata = Quandl.get("WIKI/FB")
If you prefer R, do this:
mydata = Quandl("WIKI/FB")
Ruby is equally simple:
require 'quandl' Quandl::Dataset.get('WIKI/FB')
In Excel, there’s a QDATA spreadsheet function which grabs a single data point:
= QDATA("WIKI/FB")
And there’s the DOWNLOAD button in the Quandl Excel ribbon which grabs a whole time series.
The above code snippets are just a small sample of the many integrations available on Quandl. We currently have over 25 libraries, for R, Python, Matlab, Excel, Ruby, Stata, Maple, Mathematica, C#, C++, Julia, Clojure, Haskell, PHP and many more. We programmed a few of them ourselves; the wonderful Quandl community programmed the rest.
Check out our full list of integrations here. Here is the documentation for Python, R and Excel.
All our libraries are completely free. Happy data hunting! | https://blog.quandl.com/introduction-to-quandls-libraries | CC-MAIN-2020-34 | refinedweb | 321 | 65.52 |
Search: Search took 0.02 seconds.
- 5 Jan 2011 5:38 AM
- Replies
- 2
- Views
- 610
Hello Condor,
yes indeed. My first thought was not correct.
First I found that there is no easy way to create XML in a cross-browser way.
Thus after I stopped thinking about creating XML on the...
- 5 Jan 2011 3:24 AM
- Replies
- 2
- Views
- 610
Hello to all,
I would like to create an XML on the client side and when the user is ready I will send it over to the server.
The visualization of the XML will be a tree component.
Any changes...
- 4 Nov 2010 6:12 AM
This does not look very nice but it works
myPanel.doLayout();
myPanel.show();
...
- 4 Nov 2010 5:53 AM
Ok here is something else
this works with FireFox but fails with IE since it seems that myPanel must not be hidden when the doLayout is called, otherwise the rendering is really problematic (IE 6...
- 4 Nov 2010 5:44 AM
yes this is where I placed it but I used myPanel (private variable) not this.
I suppose that the this will not be undefined.
- 4 Nov 2010 5:43 AM
OOoops,
now the IE does not work! it is a complete disaster there now since not all of the textareas are visible.
This is a bigger problem in comparison with my original.
- 4 Nov 2010 5:40 AM
I have made it working thanks to you.
But the afterLayout event contained an undefined myPanel.
Instead of placing the myPanel.show() there I placed it at the load event of the store.
This is...
- 4 Nov 2010 5:04 AM
Hello Condor,
I tried this
var myPanel = new Ext.form.FormPanel({
layout: 'table',
wiatMsgTarget: true,
...
- 4 Nov 2010 4:31 AM
Hello,
I am having a a rendering problem between FireFox and IE.
I have a UI that builds itself dynamically after loading.
For example:
var myPanel = new Ext.form.FormPanel({
...
- 3 Nov 2010 7:10 AM
- Replies
- 2
- Views
- 1,717
Hello Condor,
I almost forgot to update this thread.
I imagined that :)
I have found a workaround in the meantime that works ok.
I have made a private variable and I keep the...
- 2 Nov 2010 8:01 AM
- Replies
- 2
- Views
- 1,717
Hello to all,
I have a Store with a write event listener like this:
var jsWriter = new Ext.data.JsonWriter({
returnJson: true,
...
- 18 Oct 2010 4:17 AM
I found the solution.
The server must always return a success: true if this is set for the reader.
Take care not to return the true as a string since this will be taken as a false.
Additionally...
- 15 Oct 2010 3:24 AM
I do not think that I use Ext.Direct as well.
I tried to return the same message only or with a success: true and a total attribute but with no success.
The only change is that I receive a...
- 11 Oct 2010 8:12 AM
For the read it seems that I handle it ok.
If the answer for the read is this:
{"metaData":{"totalProperty":"total","idProperty":"id","root":"remarks","fields":["id","text"],"successProperty"...
- 11 Oct 2010 7:52 AM
Condor,
even when I do not return any answer to the client the alert inside the exception listener is fired.
Why this is happening ?
- 11 Oct 2010 7:21 AM
Sorry Condor,
I haven't thought of specifying this.
I use this
var proxy = new Ext.data.HttpProxy({
api:{
read :...
- 11 Oct 2010 6:40 AM
Hello to All ( and especially to Condor),
I have a store that the reader is configured from the server with meta-data.
I use an Ext.data.HttpProxy and I have registered the following listeners...
- 7 Oct 2010 5:11 AM
- Replies
- 2
- Views
- 1,102
Condor you are correct once again. :)
- 7 Oct 2010 3:12 AM
- Replies
- 2
- Views
- 1,102
Hello to all,
my store initiates a create action although I have made an udpate.
Why ? Do I have to specify something else as well ?
Here is the code:
var jsWriter = new...
- 7 Oct 2010 1:26 AM
- Replies
- 2
- Views
- 1,473
Hello Condor,
yes I have found a way around this by using metadata form the server.
Your post explains better to me why jsonstore was not working with my reader.
It is interesting though that...
- 6 Oct 2010 7:43 AM
- Replies
- 2
- Views
- 1,473
Hello,
I am trying to do my first JsonStore to work but I keep receiving: recordType is undefined.
Here is the the interesting part:
var TestRecord =...
- 6 Oct 2010 2:00 AM
- Replies
- 2
- Views
- 1,130
Hello Condor thank you for the quick reply.
I am using this skeleton that I have found at the tutorials:
Ext.namespace('test');
test.app = function()
{
return {
- 6 Oct 2010 1:45 AM
- Replies
- 2
- Views
- 1,130
Hello to all,
I am really new to EXTJS and I have a very basic problem.
I have read that is god to use namespace and this is what I did.
I want on the other hand to use some hidden variables...
Results 1 to 23 of 23 | http://www.sencha.com/forum/search.php?s=debce1f2d2638e87d83eaae9d09b4f5b&searchid=4212925 | CC-MAIN-2013-48 | refinedweb | 868 | 83.25 |
Run a Simple .jar Application in a Docker Container
Run a Simple .jar Application in a Docker Container
This tutorial shows you how you can run a Hello World .jar application in a Docker container from the command line, without a server.
Join the DZone community and get the full member experience.Join For Free
While I was studying Docker, I was challenged with running a basic “Hello World” .jar application in a container. Almost all resources and tutorials were about how to do it with Maven and run it on a server. I was interested in running it without a server, just out of the command line. So first, a little bit about Docker.
Docker is an open platform for building, shipping, and running distributed applications. Basically, it wraps your application from your environment and contains all that is needed to run this application locally on a developer's machine. It can be deployed to production across a cloud-based infrastructure. This guarantees that the software will always run the same, regardless of its environment. That’s pretty cool to have the possibility to pass your application with all the needed set up for a running environment.
To start with, you need to install the Docker platform for your OS and have Java installed on your machine. Once you have everything installed, you are ready to start and you may go through basic commands.
The first thing you need is to create a basic.java file, HelloWorld.java, and add these lines into it:
public class HelloWorld { public static void main(String[] args){ System.out.println("Hello World :) "); } }
Save and compile it in the command line. From the directory in which you have created your HelloWorld.java, run the command
javac HelloWorld.java.
Once you do this, you will get the HelloWorld.class file, which later we will build in .jar. But before that, we need to create a simple manifest.txt to make it packed right.
So now, in the same directory, create manifest.txt and place the following lines:
Manifest-Version: 1.0 Created-By: Me Main-Class: HelloWorld
Then, in the command line, run the following:
jar cfm HelloWorld.jar manifest.txt HelloWorld.class.
And to check if everything works correctly, type
java -jar HelloWorld.jar.
If everything is okay, you should see the following:
The next step is to start Docker and create a Dockerfile, a text file that contains the instructions (or commands) used to build a Docker image.
To do that, create the file with the name "Dockerfile" and place the following text in it:
FROM java:8 WORKDIR / ADD HelloWorld.jar HelloWorld.jar EXPOSE 8080 CMD java - jar HelloWorld.jar
Don’t forget to leave the empty line at the end of the file.
Now you are ready to create a Docker image, the result of building a Dockerfile and executing the Dockerfile's commands. It is constructed from a root operating system, installed applications, and commands executed in such a way that it can run your application. A Docker image serves as the basis for Docker containers and is the static template from which they are created.
You need to run in command line the following:
docker build -t helloworld
As a result, you should see this:
Then you have to create an account on dockerhub and create the repository "hello-world" to push your image to your repository. Once you register and create a repository, go to command line and log in there with
docker login.
Then pull that repository:
docker pull /hello-world
To push your Docker image to DockerHub you need to figure out your Docker_Image_ID. Run the following:
docker images
So you may find your image and see you Image_Id. Now you need to tag and push your image:
docker tag 4b795844c7ab /hello-world
To read more about working with it, you can go here.
Now you are ready to upload your Docker Image to DockerHub.
Just type:
docker push /hello-world:latest
To check if everything works fine enter:
docker run /hello-world
You must see the output: Hello World :)
Congratulations! You deployed your java.jar to Docker.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/run-simple-jar-application-in-docker-container-1?fromrel=true | CC-MAIN-2020-29 | refinedweb | 712 | 57.37 |
The problem I'm facing is that I'm unable to figure out how to update the figure when I increase/decrease values with my slider.
I am creating an x, y mesh grid, then plotting it, and updating the values within my array to define a new mesh. I would like to be able to move the slider and see a finer/coarser grid and update the plot and axes.
Additionally, I would like the user to be able to move the grid lines interactively with the mouse. This is not included in example code. Does someone know how to implement this?
There are similar questions that have been asked about updating values on a plot with a slider, but perhaps none address this specific problem; can someone help me figure out what I'm doing wrong? I realize I don't have anything that is redrawing the plot (though I have tested various things), but am unsure how to implement this, as M.plotGrid() creates the grid, so it may/may not be as easy as using fig.canvas.draw_idle().
Here is my code:
#Create simple evenly spaced mesh and allow slider to change values
from SimPEG import Mesh, np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
hx = np.r_[0.1,0.1,0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
hy = np.r_[0.1,0.1,0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
M = Mesh.TensorMesh([hx, hy])
M.plotGrid()
#Define slider location, size, and color for adjusting mesh values
axhx = plt.axes([0.25, 0.1, 0.65, 0.03])
axhy = plt.axes([0.25, 0.15, 0.65, 0.03])
xnode_inc = Slider(axhx, 'X mesh Node', 0.1, 1000.0, valinit=0)
anode_inc = Slider(axhy, 'Y mesh Node', 0.1, 1000.0, valinit=0)
def update(val):
framehx = xnode_inc.val + hx
framehy = ynode_inc.val + hy
M = Mesh.TensorMesh([framehx, framehy])
print M, framehx, framehy
M.plotGrid()
xnode_inc.on_changed(update)
ynode_inc.on_changed(update)
plt.show()
I can only give an example of interactively changing a
numpy grid as I don't use
SimPEG. The example is in an Ipython/Jupyter notebook. This is by far the simplest way today to generate interactive sliders, pulldowns, radiobuttons etc, i.e. much improved over the complex setup of similar setup with the original matplotlib sliders. I threw in a combo-box for the colormap just to simplicity of it.
import numpy as np import matplotlib.pyplot as p from ipywidgets import * %matplotlib inline def gridandplot(dx,mp): x=np.arange(0,5,dx) y=np.arange(0,5,dx) x,y=np.meshgrid(x,y) z= np.sin(x)* np.cos(y) if mp=='gray': cmap=p.cm.gray else: cmap= p.cm.jet p.imshow(z,interpolation='none',cmap=cmap) interact(gridandplot, dx=(0.005,0.2,0.001), mp= ('gray','jet')) | https://codedump.io/share/5wxlcAQFhUqe/1/update-values-in-evenly-spaced-mesh-with-slider | CC-MAIN-2017-09 | refinedweb | 498 | 60.51 |
Autocomplete plays an important role in searching for data or any records in the database. So, in this tutorial, I will teach you an advanced method of autocomplete in a textbox using C# and SQL Server. This method has the ability to get the records in every column of the table in the database. It is very helpful because you don’t have to exert much effort when retrieving data or records in the database.
Let’s begin:
Create a database in the SQL Server 2005 Express Edition and name it “dbplace“.
Create a table in the database that you have created.
After creating the database, open Microsoft Visual Studio 2008 and create a new windows form application for c#. Then, do the form just like this.
Go to the solution explorer and hit “code view” to fire the code editor.
In the code editor, declare all classes and variables that are needed.
Note: Put “using System.Data.SqlClient;” above the namespace to access sql server library.
After that, create a method for the autocomplete textbox.
Go back to the design view, establish a connection between SQL server and C#. Then, call a method of an autocomplete textbox.
Go back to the design view again, double-click the button and do the following code for saving the data in the database.
Output:
For all students who need a programmer for your thesis system or anyone who needs a source code in any programming languages. You can contact me @ :
Mobile No. – 09305235027 – TNT
En el caso de no poder ponernos de pie por cualquier inconveniente, asimismo existen ejercicios para efectuar tumbadas.
What’s Happening i’m new to this, I stumbled upon this I have found It positively useful and it has aided me out loads. I am hoping to contribute & help other users like its aided me. Good job. | https://itsourcecode.com/tutorials/csharp/multi-columns-autocomplete-textbox-using-c-sql-server/ | CC-MAIN-2020-05 | refinedweb | 309 | 65.32 |
Pandas Tutorial: DataFrames in Python
Pandas is a popular Python package for data science, and with good reason: it offers powerful, expressive and flexible data structures that make data manipulation and analysis easy, among many other things. The DataFrame is one of these structures.
This tutorial covers Pandas DataFrames, from basic manipulations to advanced operations, by tackling 11 of the most popular questions so that you understand -and avoid- the doubts of the Pythonistas who have gone before you.
Content
- How To Create a Pandas DataFrame
- How To Select an Index or Column From a DataFrame
- How To Add an Index, Row or Column to a DataFrame
- How To Delete Indices, Rows or Columns From a DataFrame
- How To Rename the Columns or Indices of a DataFrame
- How To Format the Data in Your DataFrame
- How To Create an Empty DataFrame
- Does Pandas Recognize Dates When Importing Data?
- When, Why and How You Should Reshape Your DataFrame
- How To Iterate Over a DataFrame
- How To Write a DataFrame to a File
(For more practice, try the first chapter of this Pandas DataFrames course for free!)
What Are Pandas Data Frames?
Before you start, let’s have a brief recap of what DataFrames are.
Those who are familiar with R know the data frame as a way to store data in rectangular grids that can easily be overviewed..
Now, DataFrames in Python are very similar: they come with the Pandas library, and they are defined as a two-dimensional labeled data structures with columns of potentially different types.
In general, you could say that the Pandas DataFrame consists of three main components: the data, the index, and the columns.
- Firstly, the DataFrame can contain data that is:
- a Pandas
DataFrame
- a Pandas
Series: a one-dimensional labeled array capable of holding any data type with axis labels or index. An example of a Series object is one column from a DataFrame.
- a NumPy
ndarray, which can be a record or structured
- a two-dimensional
ndarray
- dictionaries of one-dimensional
ndarray’s, lists, dictionaries or Series.
Note the difference between
np.ndarray and
np.array() . The former is an actual data type, while the latter is a function to make arrays from other data structures.
Structured arrays allow users to manipulate the data by named fields: in the example below, a structured array of three tuples is created. The first element of each tuple will be called
foo and will be of type
int, while the second element will be named
bar and will be a float.
Record arrays, on the other hand, expand the properties of structured arrays. They allow users to access fields of structured arrays by attribute rather than by index. You see below that the
foo values are accessed in the
r2 record array.
- Besides data, you can also specify the index and column names for your DataFrame. The index, on the one hand, indicates the difference in rows, while the column names indicate the difference in columns. You will see later that these two components of the DataFrame will come in handy when you’re manipulating your data.
If you’re still in doubt about Pandas DataFrames and how they differ from other data structures such as a NumPy array or a Series, you can watch the small presentation below:
Note that in this post, most of the times, the libraries that you need have already been loaded in. The Pandas library is usually imported under the alias
pd, while the NumPy library is loaded as
np. Remember that when you code in your own data science environment, you shouldn’t forget this import step, which you write just like this:
import numpy as np import pandas as pd
Now that there is no doubt in your mind about what DataFrames are, what they can do and how they differ from other structures, it’s time to tackle the most common questions that users have about working with them!
1. How To Create a Pandas DataFrame
Obviously, making your DataFrames is your first step in almost anything that you want to do when it comes to data munging in Python. Sometimes, you will want to start from scratch, but you can also convert other data structures, such as lists or NumPy arrays, to Pandas DataFrames. In this section, you’ll will only cover the latter. However, if you want to read more on making empty DataFrames that you can fill up with data later, go to question 7.
Among the many things that can serve as input to make a ‘DataFrame’, a NumPy
ndarray is one of them. To make a data frame from a NumPy array, you can just pass it to the
DataFrame() function in the
data argument.
Pay attention to how the code chunks above select elements from the NumPy array to construct the DataFrame: you first select the values that are contained in the lists that start with
Row1 and
Row2, then you select the index or row numbers
Row1 and
Row2 and then the column names
Col1 and
Col2.
Next, you also see that, in the DataCamp Light chunk above, you printed out a small selection of the data. This works the same as subsetting 2D NumPy arrays: you first indicate the row that you want to look in for your data, then the column. Don’t forget that the indices start at 0! For
data in the example above, you go and look in the rows at index 1 to end and you select all elements that come after index 1. As a result, you end up selecting
1,
2,
3 and
4.
This approach to making DataFrames will be the same for all the structures that
DataFrame() can take on as input.
Try it out in the code chunk below:
Remember that the Pandas library has already been imported for you as
pd.
Note that the index of your Series (and DataFrame) contains the keys of the original dictionary, but that they are sorted: Belgium will be the index at 0, while United States will be the index at 3.
After you have created your DataFrame, you might want to know a little bit more about it. You can use the
shape property or the
len() function in combination with the
.index property:
These two options give you slightly different information on your DataFrame: the
shape property will give you the dimensions of your DataFrame. That means that you will get to know the width and the height of your DataFrame. On the other hand, the
len() function, in combination with the
index property, will only give you information on the height of your DataFrame.
This all is totally not extraordinary, though, as you explicitly give in the
index property.
You could also use
df[0].count() to get to know more about the height of your DataFrame, but this will exclude the
NaN values (if there are any). That is why calling
.count() on your DataFrame is not always the better option.
If you want more information on your DataFrame columns, you can always execute
list(my_dataframe.columns.values). Try this out for yourself in the DataCamp Light block above!
Fundamental DataFrame Operations
Now that you have put your data in a more convenient Pandas DataFrame structure, it’s time to get to the real work!
This first section will guide you through the first steps of working with DataFrames in Python. It will cover the basic operations that you can do on your newly created DataFrame: adding, selecting, deleting, renaming, … You name it!
2. How To Select an Index or Column From a Pandas DataFrame
Before you start with adding, deleting and renaming the components of your DataFrame, you first need to know how you can select these elements. So, how do you do this?
Even though you might still remember how to do it from the previous section: selecting an index, column or value from your DataFrame isn’t that hard, quite the contrary. It’s similar to what you see in other languages (or packages!) that are used for data analysis. If you aren’t convinced, consider the following:
In R, you use the [,] notation to access the data frame’s values.
Now, let’s say you have a DataFrame like this one
A B C 0 1 2 3 1 4 5 6 2 7 8 9
And you want to access the value that is at index 0, in column ‘A’.
There are various options that exist to get your value
1 back:
The most important ones to remember are, without a doubt,
.loc[] and
.iloc[]. The subtle differences between these two will be discussed in the next sections.
Enough for now about selecting values from your DataFrame. What about selecting rows and columns? In that case, you would use:
For now, it’s enough to know that you can either access the values by calling them by their label or by their position in the index or column. If you don’t see this, look again at the slight differences in the commands: one time, you see
[0][0], the other time, you see
[0,'A'] to retrieve your value
1.
3. How To Add an Index, Row or Column to a Pandas DataFrame
Now that you have learned how to select a value from a DataFrame, it’s time to get to the real work and add an index, row or column to it!
Adding an Index to a DataFrame
When you create a DataFrame, you have the option to add input to the ‘index’ argument to make sure that you have the index that you desire. When you don’t specify this, your DataFrame will have, by default, a numerically valued index that starts with 0 and continues until the last row of your DataFrame.
However, even when your index is specified for you automatically, you still have the power to re-use one of your columns and make it your index. You can easily do this by calling
set_index() on your DataFrame. Try this out below!
Adding Rows to a DataFrame
Before you can get to the solution, it’s first a good idea to grasp the concept of
loc and how it differs from other indexing attributes such as
.iloc[] and
.ix[]:
.loc[]works on labels of your index. This means that if you give in
loc[2], you look for the values of your DataFrame that have an index labeled
2.
.iloc[]works on the positions in your index. This means that if you give in
iloc[2], you look for the values of your DataFrame that are at index ’2`.
.ix[]is a more complex case: when the index is integer-based, you pass a label to
.ix[].
ix[2]then means that you’re looking in your DataFrame for values that have an index labeled
2. This is just like
.loc[]! However, if your index is not solely integer-based,
ixwill work with positions, just like
.iloc[].
This all might seem very complicated. Let’s illustrate all of this with a small example:
Note that in this case you used an example of a DataFrame that is not solely integer-based as to make it easier for you to understand the differences. You clearly see that passing
2 to
.loc[] or
.iloc[]/
.ix[] does not give back the same result!
- You know that
.loc[]will go and look at the values that are at label
2. The result that you get back, will be
48 1 49 2 50 3
.iloc[]will go and look at the positions in the index. When you pass
2, you will get back:
48 7 49 8 50 9
.ix[]will have the same behavior as
ilocand look at the positions in the index. You will get back the same result as
.iloc[].
Now that the difference between
.iloc[],
.loc[] and
.ix[] is clear, you are ready to give adding rows to your DataFrame a go!
Tip: as a consequence of what you have just read, you understand now also that the general recommendation is that you use
.loc to insert rows in your DataFrame. That is because if you would use
df.ix[], you might try to reference a numerically valued index with the index value and accidentally overwrite an existing row of your DataFrame. You better avoid this!
You can see why all of this can be confusing, right?
Adding a Column to Your DataFrame
In some cases, you want to make your index part of your DataFrame. You can easily do this by taking a column from your DataFrame or by referring to a column that you haven’t made yet and assigning it to the
.index property, just like this:
In other words, you tell your DataFrame that it should take column
A as its index.
However, if you want to append columns to your DataFrame, you could also follow the same approach as when you would add an index to your DataFrame: you use
.loc[] or
.iloc[]. In this case, you add a Series to an existing DataFrame with the help of
.loc[]:
Remember a Series object is much like a column of a DataFrame; That explains why you can easily add a Series to an existing DataFrame. Note also that the observation that was made earlier about
.loc[] still stays valid, also when you’re adding columns to your DataFrame!
Resetting the Index of Your DataFrame
When your index doesn’t look entirely the way you want it to, you can opt to reset it. You can easily do this with
.reset_index(). However, you should still watch out, as you can pass several arguments that can make or break the success of your reset:
Now try replacing the
drop argument by
inplace in the code chunk above and see what happens!
Note how you use the
drop argument to indicate that you want to get rid of the index that was there. If you would have used
inplace, the original index with floats is added as an extra column to your DataFrame.
4. How to Delete Indices, Rows or Columns From a Pandas Data Frame
Now that you have seen how to select and add indices, rows, and columns to your DataFrame, it’s time to consider another use case: removing these three from your data structure.
Deleting an Index from Your DataFrame
If you want to remove the index from your DataFrame, you should reconsider because DataFrames and Series always have an index.
However, what you *can* do is, for example:
- resetting the index of your DataFrame (go back to the previous section to see how it is done) or
- remove the index name, if there is any, by executing
del df.index.name,
- remove duplicate index values by resetting the index, dropping the duplicates of the index column that has been added to your DataFrame and reinstating that duplicateless column again as the index:eyJsYW5ndWFnZSI6InB5dGhvbiIsInByZV9leGVyY2lzZV9jb2RlIjoiaW1wb3J0IG51bXB5IGFzIG5wXG5pbXBvcnQgcGFuZGFzIGFzIHBkIiwic2FtcGxRmLl9fX19fX19fX19fLmRyb3BfZHVwbGljYXRlcyhzdWJzZXQ9J2luZGV4Jywga2VlcD0nbGFzdCcpLnNldF9pbmRleCgnaW5kZXgnKSIsInNvbHV0aW9RmLnJlc2V0X2luZGV4KCkuZHJvcF9kdXBsaWNhdGVzKHN1YnNldD0naW5kZXgnLCBrZWVwPSdsYXN0Jykuc2V0X2luZGV4KCdpbmRleCcpIiwic2N0IjoicmVzZXRfaW5kZXhfbXNnPVwiRGlkIHlvdSByZXNldCB0aGUgaW5kZXggd2l0aCBgcmVzZXRfaW5kZXgoKWA/XCJcbnRlc3RfZnVuY3Rpb24oXCJkZi5yZXNldF9pbmRleFwiLCBub3RfY2FsbGVkX21zZyA9IHJlc2V0X2luZGV4X21zZywgaW5jb3JyZWN0X21zZyA9IHJlc2V0X2luZGV4X21zZylcbnN1Y2Nlc3NfbXNnKFwiV29uZGVyZnVsIVwiKSJ9
- and lastly, remove an index, and with it a row. This is elaborated further on in this tutorial.
Now that you know how to remove an index from your DataFrame, you can go on to removing columns and rows!
Deleting a Column from Your DataFrame
To get rid of (a selection of) columns from your DataFrame, you can use the
drop() method:
You might think now: well, this is not so straightforward; There are some extra arguments that are passed to the
drop() method!
- The
axisargument is either 0 when it indicates rows and 1 when it is used to drop columns.
- You can set
inplaceto True to delete the column without having to reassign the DataFrame.
Removing a Row from Your DataFrame
You can remove duplicate rows from your DataFrame by executing
df.drop_duplicates(). You can also remove rows from your DataFrame, taking into account only the duplicate values that exist in one column.
If there is no uniqueness criterion to the deletion that you want to perform, you can use the
drop() method, where you use the
index property to specify the index of which rows you want to remove from your DataFrame:
After this command, you might want to reset the index again.
Tip: try resetting the index of the resulting DataFrame for yourself! Don’t forget to use the
drop argument if you deem it necessary.
5. How to Rename the Index or Columns of a Pandas DataFrame
To give the columns or your index values of your dataframe a different value, it’s best to use the
.rename() method.
Tip: try changing the
inplace argument in the first task (renaming your columns) to
False and see what the script now renders as a result. You see that now the DataFrame hasn’t been reassigned when renaming the columns. As a result, the second task takes the original DataFrame as input and not the one that you just got back from the first
rename() operation.
Beyond The Pandas DataFrame Basics
Now that you have gone through a first set of questions about Pandas’ DataFrames, it’s time to go beyond the basics and get your hands dirty for real because there is far more to DataFrames than what you have seen in the first section.
6. How To Format The Data in Your Pandas DataFrame
Most of the times, you will also want to be able to do some operations on the actual values that are contained within your DataFrame. In the following sections, you’ll cover several ways in which you can format your DataFrame’s values
Replacing All Occurrences of a String in a DataFrame
To replace certain strings in your DataFrame, you can easily use
replace(): pass the values that you would like to change, followed by the values you want to replace them by.
Just like this:
Note that there is also a
regex argument that can help you out tremendously when you’re faced with strange string combinations:
In short,
replace() is mostly what you need to deal with when you want to replace values or strings in your DataFrame by others!
Removing Parts From Strings in the Cells of Your DataFrame
Removing unwanted parts of strings is cumbersome work. Luckily, there is an easy solution to this problem!
You use
map() on the column
result to apply the lambda function over each element or element-wise of the column. The function in itself takes the string value and strips the
+ or
- that’s located on the left, and also strips away any of the six
aAbBcC on the right.
Splitting Text in a Column into Multiple Rows in a DataFrame
This is somewhat a more difficult formatting task. However, the next code chunk will walk you through the steps:
In short, what you do is:
- First, you inspect the DataFrame at hand. You see that the values in the last row and in the last column are a bit too long. It appears there are two tickets because a guest has taken a plus-one to the concert.
- You take the
Ticketcolumn from the DataFrame
dfand strings on a space. This will make sure that the two tickets will end up in two separate rows in the end. Next, you take these four values (the four ticket numbers) and put them into a Series object:
0 1 0 23:44:55 NaN 1 66:77:88 NaN 2 43:68:05 56:34:12
NaNvalues in there! You have to stack the Series to make sure you don’t have any
NaNvalues in the resulting Series.
0 0 23:44:55 1 0 66:77:88 2 0 43:68:05 1 56:34:12
0 23:44:55 1 66:77:88 2 43:68:05 2 56:34:12 dtype: object
Ticketcolumn.
Applying A Function to Your Pandas DataFrame’s Columns or Rows
You might want to adjust the data in your DataFrame by applying a function to it. Let’s begin answering this question by making your own lambda function:
doubler = lambda x: x*2
Tip: if you want to know more about functions in Python, consider taking this Python functions tutorial.
Note that you can also select the row of your DataFrame and apply the
doubler lambda function to it. Remember that you can easily select a row from your DataFrame by using
.loc[] or
.iloc[].
Then, you would execute something like this, depending on whether you want to select your index based on its position or based on its label:
df.loc[0].apply(doubler)
Note that the
apply() function only applies the
doubler function along the axis of your DataFrame. That means that you target either the index or the columns. Or, in other words, either a row or a column.
However, if you want to apply it to each element or element-wise, you can make use of the
map() function. You can just replace the
apply() function in the code chunk above with
map(). Don’t forget to still pass the
doubler function to it to make sure you multiply the values by 2.
Let’s say you want to apply this doubling function not only to the
A column of your DataFrame, but to the whole of it. In this case, you can use
applymap() to apply the
doubler function to every single element in the entire.
7. How To Create an Empty DataFrame
The function that you will use is the Pandas
Dataframe() function: it requires you to pass the data that you want to put in, the indices and the columns.
Remember that the data that is contained within the data frame doesn’t have to be homogenous. It can be of different data types!
There are several ways in which you can use this function to make an empty DataFrame. Firstly, you can use
numpy.nan to initialize your data frame with
NaNs. Note that
numpy.nan has type
float.
Right now, the data type of the data frame is inferred by default: because
numpy.nan has type float, the data frame will also contain values of type float. You can, however, also force the DataFrame to be of a certain type by adding the attribute
dtype and filling in the desired type. Just like in this example:
Note that if you don’t specify the axis labels or index, they will be constructed from the input data based on common sense rules.
8. Does Pandas Recognize Dates When Importing Data?
Pandas can recognize it, but you need to help it a tiny bit: add the argument
parse_dates when you’reading in data from, let’s say, a comma-separated value (CSV) file:
import pandas as pd pd.read_csv('yourFile', parse_dates=True) # or this option: pd.read_csv('yourFile', parse_dates=['columnName'])
There are, however, always weird date-time formats.
No worries! In such cases, you can construct your own parser to deal with this. You could, for example, make a lambda function that takes your DateTime and controls it with a format string.
import pandas as pd dateparser = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') # Which makes your read command: pd.read_csv(infile, parse_dates=['columnName'], date_parser=dateparse) # Or combine two columns into a single DateTime column pd.read_csv(infile, parse_dates={'datetime': ['date', 'time']}, date_parser=dateparse)
9. When, Why And How You Should Reshape Your Pandas DataFrame
Reshaping your DataFrame is basically transforming it so that the resulting structure makes it more suitable for your data analysis. In other words, reshaping is not so much concerned with formatting the values that are contained within the DataFrame, but more about transforming the shape of it.
This answers the when and why. But how would you reshape your DataFrame?
There are three ways of reshaping that frequently raise questions with users: pivoting, stacking and unstacking and melting.
Pivotting Your DataFrame
You can use the
pivot() function to create a new derived table out of your original one. When you use the function, you can pass three arguments:
values: this argument allows you to specify which values of your original DataFrame you want to see in your pivot table.
columns: whatever you pass to this argument will become a column in your resulting table.
index: whatever you pass to this argument will become an index in your resulting table.
When you don’t specifically fill in what values you expect to be present in your resulting table, you will pivot by multiple columns:
Note that your data can not have rows with duplicate values for the columns that you specify. If this is not the case, you will get an error message. If you can’t ensure the uniqueness of your data, you will want to use the
pivot_table method instead:
Note the additional argument
aggfunc that gets passed to the
pivot_table method. This argument indicates that you use an aggregation function used to combine multiple values. In this example, you can clearly see that the
mean function is used.
Using
stack() and
unstack() to Reshape Your Pandas DataFrame
You have already seen an example of stacking in the answer to question 5! In essence, you might still remember that, when you stack a DataFrame, you make it taller. You move the innermost column index to become the innermost row index. You return a DataFrame with an index with a new inner-most level of row labels.Go back to the full walk-through of the answer to question 5 if you’re unsure of the workings of
stack().
The inverse of stacking is called unstacking. Much like
stack(), you use
unstack() to move the innermost row index to become the innermost column index.
For a good explanation of pivoting, stacking and unstacking, go to this page.
Reshape Your DataFrame With
melt()
Melting is considered useful in cases where you have a data that has one or more columns that are identifier variables, while all other columns are considered measured variables.
These measured variables are all “unpivoted” to the row axis. That is, while the measured variables that were spread out over the width of the DataFrame, the melt will make sure that they will be placed in the height of it. Or, yet in other words, your DataFrame will now become longer instead of wider.
As a result, you just have two non-identifier columns, namely, ‘variable’ and ‘value’.
Let’s illustrate this with an example:
If you’re looking for more ways to reshape your data, check out the documentation.
10. How To Iterate Over a Pandas DataFrame
You can iterate over the rows of your DataFrame with the help of a
for loop in combination with an
iterrows() call on your DataFrame:
iterrows() allows you to efficiently loop over your DataFrame rows as (index, Series) pairs. In other words, it gives you (index, row) tuples as a result.
11. How To Write a Pandas DataFrame to a File
When you have done your data munging and manipulation with Pandas, you might want to export the DataFrame to another format. This section will cover two ways of outputting your DataFrame: to a CSV or to an Excel file.
Output a DataFrame to CSV
To write a DataFrame as a CSV file, you can use
to_csv():
import pandas as pd df.to_csv('myDataFrame.csv')
That piece of code seems quite simple, but this is just where the difficulties begin for most people because you will have specific requirements for the output of your data. Maybe you don’t want a comma as a delimiter, or you want to specify a specific encoding, …
Don’t worry! You can pass some additional arguments to
to_csv() to make sure that your data is outputted the way you want it to be!
- To delimit by a tab, use the
separgument:
import pandas as pd df.to_csv('myDataFrame.csv', sep='\t')
encodingargument:
import pandas as pd df.to_csv('myDataFrame.csv', sep='\t', encoding='utf-8')
NaNor missing values to be represented, whether or not you want to output the header, whether or not you want to write out the row names, whether you want compression, … Read up on the options here.
Writing a DataFrame to Excel
Similarly to what you did to output your DataFrame to CSV, you can use
to_excel() to write your table to Excel. However, it is a bit more complicated:
import pandas as pd writer = pd.ExcelWriter('myDataFrame.xlsx') df.to_excel(writer, 'DataFrame') writer.save()
Note, however, that, just like with
to_csv(), you have a lot of extra arguments such as
startcol,
startrow, and so on, to make sure output your data correctly. Go to this page to read up on them.
If, however, you want more information on IO tools in Pandas, you check out this page.
Python For Data Science Is More Than DataFrames
That’s it! You've successfully completed the Pandas DataFrame tutorial!
The answers to the 11 frequently asked Pandas questions represent important functions that you will need to import, clean and manipulate your data for your data science work. Are you not sure that you have gone deep enough into this matter? Our Importing Data In Python course will help you out! If you’ve got the hang out of this, you might want to see Pandas at work in a real-life project. The Importance of Preprocessing in Data Science and the Machine Learning Pipeline tutorial series is a must-read and the open course Introduction to Python & Machine Learning is a must-complete. | https://www.datacamp.com/community/tutorials/pandas-tutorial-dataframe-python?utm_campaign=Revue%20newsletter&utm_medium=Newsletter&utm_source=The%20Data%20Science%20Roundup | CC-MAIN-2018-34 | refinedweb | 4,927 | 68.2 |
Eclipse Community Forums - RDF feed Eclipse Community Forums RCP: Cannot inject invisible parts <![CDATA[I am facing a trouble that i can't understand. Here's my problem: I have a part stack with 2 parts: PartStack -> Part A -> Part B A and B are noted with @Creatable and @Singleton And i have a class which manage my views like that: public class Manager { @Inject private A a; @Inject private B b; When I make A and B visible at least one time, i can instantiate this class without problem, but when those classes were never been visible, i got the message : "no actual value was found for the argument" for the Injected classes. I figured out that this comes when the class wasn't instantiated and never got inserted on context, but even when i force the instantiation, i got the error. I don't know if I make myself clear but I would like to know what process the framework do to insert the class on context, or if there is something i'm doing wrong. Thanks.]]> Rafael Fogel 2013-01-17T12:53:50-00:00 Re: RCP: Cannot inject invisible parts <![CDATA[Remove the @Creatable and @Singleton, that is not what they are for. E4 Dependency Injection]]> Joseph Carroll 2013-01-17T15:35:48-00:00 Re: RCP: Cannot inject invisible parts <![CDATA[I don't get it. Without those notes I can't inject my classes. Classes annotated with @Creatable will be automatically created by the injector if an instance was not present in the injection context. The automatically-generated instance is not stored in the context. How do I inject my classes then?]]> Rafael Fogel 2013-01-17T16:32:01-00:00 Re: RCP: Cannot inject invisible parts <![CDATA[The framework takes care of it. @Creatable is for resources not in the context *AND* not referenced in the running model. Your part class is referenced in your MPart from the running model. The framework automatically creates it for you.]]> Joseph Carroll 2013-01-17T17:31:05-00:00 Re: RCP: Cannot inject invisible parts <![CDATA[Ok, i am starting on rcp and it isn't very clear to me. I am accessing this class this way: Manager manager = ContextInjectionFactory.make(Manager.class, context); Without those notes, I can't do it. How do you suggest I access this class? ( assuming I won't just instantiate like a pojo ) ]]> Rafael Fogel 2013-01-18T13:07:51-00:00 Re: RCP: Cannot inject invisible parts <![CDATA[MParts usually are created by the framework (renderer). The creation involves instantiating the contribution object (the URI class), constructing the runtime representation of MPart and putting it to the context. This creation follows the lazy loading approach in that only parts that are visible are created, otherwise Eclipse would start in 10 minutes if it had to instantiate each and every view in the model (which is an MPart). So it creates only what is visible. The 'one time visible' situation may happen because when you try to force the creation through @Creatable the contribution object is not created. Usually it is not a good idea to force the creation of parts when they are not visible yet, though it depends on the case. If you want to do some form of processing on the part you can register a listener (IEventBroker) on part creation and do your stuff there, and let the renderer (LazyStackRenderer) decide when to instantiate the part. That said, @Creatable is used to do a CIF.make on a class and @Singleton is used to prevent multiple instances in a given scope.]]> Sopot Cela 2013-01-18T13:23:57-00:00 Re: RCP: Cannot inject invisible parts <![CDATA[Now it's way more clear to me. Thanks for the support, Sopot]]> Rafael Fogel 2013-01-18T17:59:30-00:00 | http://www.eclipse.org/forums/feed.php?mode=m&th=449609&basic=1 | CC-MAIN-2016-36 | refinedweb | 643 | 63.59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.