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 |
|---|---|---|---|---|---|
Migration and Conversion Utilities
This chapter discusses some specialized tools and techniques that can be used when migrating a Caché database to a new system..
Using cdbmerge To Consolidate Database Extents Into One File describes the cdbmerge utility, which that is useful if you use Caché extents. In past releases, Caché allowed a single database to span multiple files called extents, partly to avoid the limitations of disk hardware and filesystems at that time. These limitations no longer apply, and Caché no longer supports extents. The cdbmerge utility enables you to consolidate an extent-style database into a single database file.
Converting FileMan Files into Caché Classes — describes FileMan Mapping Utility, which).
Using cvendian to Convert Between Big-Endian and Little-Endian Systems
Caché provides a utility to convert the byte order of a Caché database from Big-endian (that is, most-significant byte first) to Little-endian (that is, least-significant byte first), and vice versa. It is called cvendian, for convert endian. This is useful when moving a database among platforms of the two types. It also provides an option to report on the byte order of a given database.
For information about the Endianness of supported platforms, see “Platform Endianness” in the online InterSystems Supported Platforms
document for this release.
This utility cannot be used on a mounted database.
Location of Utility
The cvendian utility is the file install-dir\Bin\cvendian.exe.
Conversion Process
You can run cvendian on either the system that has the files to be converted or the system that will be using the converted files.
For example, to convert a database from a Little-endian to a Big-endian system, you can perform the conversion on the Little-endian system and then transfer the database to the Big-endian system, or you can transfer the file first, and then convert it.
This utility does not work for backup and journal files. You must restore databases on a platform of the same endian, move the restored databases to the different endian platform, and then use the cvendian utility to convert the databases.
To convert a database, the process is:
Make a copy of your database files, because the utility replaces the source files with the converted files.
Run cvendian using the syntax described in the “Utility Syntax” section.
Utility Syntax
With the cvendian endian utility, you can specify the desired byte order, or you can report the current byte order without conversion. Use the following syntax:
cvendian [-option] file
The option argument is one of the following:
-big — convert the database to Big-endian
-little — convert the database to Little-endian
-report — report the byte order of the database
You can shorten the options to their initial letter. If this is a conversion request (-big or -little), and the database already has the specified byte order, the utility displays a warning message and stops processing.
If you do not provide the option argument, the utility converts the database from the existing byte order to the other byte order. It is recommended, however, that you use the option argument.
The file argument is the file to convert, and can include a complete pathname.
The utility performs the following actions:
Auto-detects the byte order of the database
Displays endian information and other information
Performs the conversion
Displays a message indicating success or failure
Example
For example, suppose you are converting a database for use on IBM AIX® for Power System-64 from Windows Server 2016. This means you must convert from Little-endian (for Intel) to Big-endian (for POWER). The output from running cvendian on the Windows system before moving the file to the AIX system looks similar to this:
C:\CacheSys\Bin>cvendian -big c:\temp\powerdb\cache.dat This database is little-endian. This database has a block size of 8192 bytes. This database has 1 volume and 1 map. The last block in the primary volume is 18176. Original manager directory is c:\temp\powerdb\ No extension volumes. Done converting c:\temp\powerdb\cache.dat to big-endian C:\CacheSys\Bin>
You can now move the converted database file to the AIX system.
Using cdbmerge To Consolidate Database Extents Into One File
Historically, Caché allowed databases to span multiple files called extents. This was due, in part, because of the disk hardware and filesystems were unable to support files large enough to contain the entirety of a database.
Advances in storage technology and in filesystem capabilities have removed that impediment. As a result, the support for extents is no longer needed. In Caché version 2010.1, support for extents was deprecated; in version 2014.1, it was removed entirely.
Occasionally, however, it is necessary to mount and read extent-style databases. To address this issue, beginning with version 2012.2.4, InterSystems provides a stand-alone utility to consolidate a directory containing a database and its extents into a single cache.dat database file. That utility is called cdbmerge. It is located in the Bin subdirectory of <install_dir>.
To effect this conversion, do the following:
Restore the database and extents to be consolidated to its own directory.
Run the cdbmerge utility on that directory.
Configure and mount the converted database on Caché.
The cdbmerge command has two forms:
cdbmerge <Original_Dir> cdbmerge -srcdir <Original_Dir> -destdir <Final_Dir>
where
<Original_Dir> is the location of the directory containing the base cache.dat file and its associated extents
<Final_Dir> is the (optional) location of the merged cache.dat. If not specified, the database will be merged in place.
InterSystems recommends having a copy of the <Original_Dir> available before doing the merge as a safeguard against unexpected errors.
Converting FileMan Files into Caché Classes
FileMan is a set of utilities that provide metadata storage, access, and manipulation for MUMPS applications. This section describes how to map FileMan files to Caché classes. The FileMan source code is in the public domain and is not provided by InterSystems. However, Caché provides the FileMan Mapping Utility, which reads files created by FileMan and generates Caché classes that map them.
This section discusses the following topics:
An overview of the FileMan mapping utility
How to access the FileMan mapping wizard
How to specify the default settings for the FileMan mapping wizard
How to map FileMan files to Caché classes via the wizard
How to use the API for the FileMan mapping utility
Next steps after using the FileMan mapping utility
Notes on how FileMan files are mapped
Available classes that you can use to perform advanced queries
This section assumes that the FileMan globals (^DD and ^DIC) are already loaded into the desired namespace in your system.
Overview of the FileMan Mapping Utility
The FileMan wizard enables you to quickly and easily create custom class mappings for your FileMan files. The classes created by the mapping utility enable you to access the file data via ObjectScript and via SQL. You can map just one, many, or all FileMan files in a namespace. For each file, you can control details such as the following:
Which fields are mapped
Whether the classes are read-only or have write access
Formats for the names of the generated classes and properties (tables and fields)
The superclass list for the generated classes
Whether word-processing fields are mapped as list collections or as child tables
Accessing the FileMan Wizard
To access the FileMan wizard:
Open the Management Portal.
Click System Explorer > SQL.
Check the namespace in the header. Click Switch to change to the correct namespace, if necessary.
Click Wizard > FileMan.
On this page, you can do the following:
Specify the default settings to use when mapping FileMan files.
Map one, some, or all of the FileMan files in the current namespace, thus generating Caché classes.
View the log for past mapping activities.
View any background tasks.
Specifying the Default Settings
The FileMan wizard uses many settings that control how it generates classes. It is worthwhile to review these settings, modify them to values that you use most of the time, and save these as the default settings.
To modify the settings:
Open the Management Portal.
Click System Administration > Configuration > SQL and Object Settings > FileMan Conversion Settings.
Make changes as needed and click Save.
Or access the wizard as described in “Accessing the FileMan Wizard”, modify the values on the first page, and then click Save As Default.
The available settings are as follows:
Owner of the Classes Created — Specifies the username to use as the owner of the classes created. The default is the current value in $Username.
Package Name to Create the Classes in — Specifies the name of the package to create the classes in.Note:
If you previously mapped to one package and map the FileMan files again to a new package, the old classes are not automatically deleted.
Super Classes — Specifies the superclass list for each of the mapped classes. Specify a string with a comma-separated list of class names.
Table Name Format Based on the File Name and Number — Specifies the format of the generated table name. For this setting, specify a string that uses the following keywords along with any characters that are valid to use as table names:
<FILENAME> — Replaced with the name of the FileMan file
<FILENUMBER> — Replaced with the file number
If you use <FILENAME>, any decimal place characters in the file number are converted to underscore characters.
See the examples for Child Table Name Format Based on the File Name and Number.
Child Table Name Format Based on the File Name and Number — Specifies the format of the generated child table names. For this setting, specify a string that uses the following keywords along with any characters that are valid to use as table names:
<FILENAME> — Replaced with the name of the FileMan file
<FILENUMBER> — Replaced with the file number
<PARFILENAME> — Replaced with the name of the parent file
<PARFILENUMBER> — Replaced with the file number of the parent file
If you use <FILENAME> or <PARFILENUMBER>, any decimal place characters in the file number are converted to underscore characters.
Some examples of this setting:
SUB_<FILENAME> — In this example, the table name of a child table is the string SUB_followed by the name of the file. For example: SUB_ACCESSIBLE_FILE
f<PARFILENUMBER>c<FILENUMBER> — In this example, the table name of a child table is the string f, followed by the number of the parent file, followed by c, followed by the number of this file. For example: f200c200_032
<FILENAME> — In this example, the child table name is simply the same as the filename.
Maximum length of Property, Trigger, and Foreign Key names — Specifies the maximum length of property names, foreign key names, and trigger names produced by this utility. The default is 180, which corresponds to an increase in the length of Caché class member names in a recent release. Use this option if you want to keep the names of these items at the previous shorter maximum (31 characters).
Field Name Format Based on the Fileman Field Name — Specifies how the utility will generate the SQL field name. Choose of the following:
Exact — The SQL field name will use exactly the same case as the FileMan field name. For example, FileMan field 'DEA EXPIRATION DATE' becomes SQL field name 'DEA_EXPIRATION_DATE'.
Upper — Letters in the FileMan field name are folded to upper case to generate the SQL field name. For example, FileMan field 'DEA expiration date' becomes SQL field name 'DEA_EXPIRATION_DATE'.
Lower — Letters in the FileMan field name are folded to lower case to generate the SQL field name. For example, FileMan field 'DEA EXPIRATION DATE' becomes SQL field name 'dea_expiration_date'.
Pascal — The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. Also, spaces and underscored are removed. For example, FileMan field 'DEA EXPIRATION DATE' becomes the SQL field name 'DeaExpirationDate'.
Camel — Thee first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. Also, spaces and underscored are removed. For example, FileMan field 'DEA EXPIRATION DATE' becomes the SQL field name 'deaExpirationDate'.
Datatype to use for FileMan Date fields — Specifies the data type to use when mapping FileMan DATE fields. The default is %Library.FilemanDate
.
Datatype to use for FileMan DateTime fields — Specifies the data type to use when mapping FileMan DATE/TIME fields. The default is %Library.FilemanTimeStamp
.
Define STRICTDATA=1 for %FilemanData* datatypes — Specifies whether the generated classes include STRICTDATA=1 in the definitions of any properties of type %Library.FilemanDate
and %Library.FilemanTimeStamp
.
This STRICTDATA parameter affects the LogicalToOdbc() and LogicalToDisplay() methods for these data types. When STRICTDATA=0, the default, the methods will contain the same code they did previously. When STRICTDATA=1, the code in the LogicalToFormat() methods that handles invalid Logical date and time values is removed. Use STRICTDATA=1 if your database contains invalid or incomplete date or time values, and you do not want assumptions made about what the correct data should be.
Expand Pointers? — Specifies whether the utility creates additional computed properties to expand the pointer field. Select one of the following options:
No — The utility does not add any computed properties to expand the pointer field.
Yes(1) - As FIELD and FIELD_NAME — The utility adds a computed property that expands the pointer field and is equal to the NAME (.01) field in the referenced file.
Yes(2) - As FIELDID and FIELD — The utility adds a computed property that expands the pointer field and is equal to the NAME (.01) field in the referenced file. The naming conventions used for this option is the pointer field will be named after the referenced file with “_ID” appended to the field name.
Yes(3) - As FIELD_fPointerFilenID and FIELD – This option is the same as 2 except that the name of the reference field will be <Field>_f<pointed-to-file-id#>ID.
Expand Set Of Codes fields — Specifies whether to define an expanded SOC (SetOfCodes) table for each Set Of Codes field that is mapped.
If this option is Yes, then for each such field that is mapped to a class, the utility will generate a read-only class/table that maps to the CODE and MEANING of the Set Of Codes. The name of the table is <tablename>_SOC_<fieldname>. The SOC table has two fields. CODE maps to the name of the CODE and MEANING is the external meaning for the CODE. This table is mapped directly to the ^DD global, so any updates to the definition in the ^DD global will be immediately reflected in the data returned by the table.
If this option is No (the default), these SOC class/tables will not be created.
Create Value for Variable Pointer fields? — Specifies how to handle variable pointer fields. If this option is selected, then for each variable pointer field mapped, FM2Class will also create a computed property that expands the variable pointer field value and is equal to the .01 field in the referenced file. This field will be named <Variable_Pointer_Field_VALUE>.
For example, an FM variable pointer field WHO is defined to point to either the EMPLOYEE file or the PATIENT file. By default, FM2Class creates two fields, one that points to the EMPLOYEE file and another one that points to the PATIENT file. Only one of these fields will be non-NULL. If WHO is an EMPLOYEE, the WHO_EMPLOYEE field will contain the ID/IEN of the EMPLOYEE. If WHO is a PATIENT, WHO_PATIENT will contain the ID/IEN of the PATIENT.
If this setting is selected, FM2Class also creates third field, WHO_VALUE, which computes to the .01 field of the EMPLOYEE record if the WHO points to an EMPLOYEE, or the .01 field of the PATIENT record if WHO points to a PATIENT. If this setting is cleared, FM2Class does not create this third field.
Define Set Of Codes fields as type? — Specifies the data type to use when mapping a Set Of Codes field. The options are %Library.EnumString
(the default) and %Library.String
.
Using %Library.EnumString
provides an advantage because it provides the OdbcToLogical() and LogicalToOdbc() methods, which allow you to use the meaning of the Set Of Codes, rather than the code value from xDBC client applications.
Define Required Properties for — Controls which required FileMan fields are defined as required properties.
If this setting is REQUIRED FIELDS (the default), FileMan fields marked as required are defined as required properties.
If this setting is REQUIRED IDENTIFIERS, only FileMan fields defined as Required Identifiers are defined as required properties.
Extended Mapping — Specifies a string to be inserted into the global name in the map definitions for extended mapping purposes. For example, you might specify ["SD"] and your global is mapped as ^["SD"]LR(...) instead of ^LR(...).
This can be any valid string that can be used for extended global mapping and must include the [...] or |...| brackets.
Name of the IEN Field — Specifies the name of the IEN field, which is IEN by default.
Retain Class? — Specifies whether to recreate the entire class if it already exists.
If this setting is No, the utility deletes and recreates the class, which means that SQL privileges and any add-ons to the class are lost.
If this setting is Yes, the utility recreates the properties, storage, indexes, foreign keys, and so on, rather than the entire class. Notes:
You must have run the FM2Class utility at least once with the Caché 2010.2 or higher before manually adding your own items to the class definition; this is necessary because earlier versions do not save the required metadata needed for this feature.
After mapping a class, if you move the class to another namespace or another system, and attempt to map it again from the new location with the Retain Class? set to Yes, you must also manually move/copy the ^oddFMD global too, because this global stores the metadata required by the Retain Class? feature.
The Retain Class? feature is not meant to work with SOC classes produced when you set the Expand Set Of Codes fields to Yes; that is, if you add your own parameters, properties, indices, and so on to these classes, those changes are not retained, even if Retain Class? is set to Yes.
Recursion — Controls whether sub-files and pointer are also mapped:
If this setting is No recursion, only this file is mapped. No sub-files or pointers are mapped.
If this setting is Partial recursion, the file is mapped, along with one level of sub-files and pointers.
If this setting is Full recursion, the file is mapped, along with all sub-files and pointers. This is the default.
Word-Processing Fields Conversion – Specifies how to map word-processing fields. Select Convert as child tables > Convert as list collections, or Convert as list collections and child tables.
Read Only? — Specifies whether the generated classes should be read-only.
Log File — Specifies the name of the file into which the utility should log output. Click Browse... and select a file. Or type a filename.
Compile Classes? — Specifies whether to compile the classes after creating them.
Compile Flags — Specifies any class compiler qualifiers and/or flags.
Delete Flags — Specifies any class deletion qualifiers and/or flags.
Display Result — Controls how the results are displayed. Select Full screen display (the default), Minimal screen display, or No screen display.
Mapping FileMan Files
To map FileMan files to Caché classes:
Access the FileMan wizard (see “Accessing the FileMan Wizard”).
Optionally change settings on the first page of the wizard. For information on the settings, see the previous section, “Specifying the Default Settings”.
Click Next.
You use the next page of the wizard to specify which files to map.
Enter a complete or partial file name and click Search.
The wizard displays all the FileMan files in this namespace that start with the given string.
Do one of the following:
Click Map All. The wizard prompts you for confirmation. Click OK.
The wizard immediately starts a background task that maps the files. The remaining steps in this section do not apply in this case.
Click Select All. Then click Next.
Click the Select link for one or more files. For each file, the wizard displays a list of the fields to map (all fields by default). Optionally double-click a field if you do not want to map it. When you are done selecting files and their fields, click Add to Cart.
Click the Add to Cart link for one or more files. With this option, all fields are mapped, but the wizard operates more quickly because it does not need to retrieve the fields at this stage. After selecting the files, click Next.
Review the selected files.
The wizard displays your selected files in a tree, with fields for each file. If you want to remove any of them, click a file name then click the "Remove" link above the tree. If you click a field then click "Remove" then the file name for that field is removed too. If you want to empty the Cart (remove all of them), just click the "Clear Cart" link above the tree.
Optionally do any of the following:
Remove a file, by clicking the file name and then clicking the Remove link above the tree.
Remove a field, by clicking the field name and then clicking the Remove link.
Remove all files, by clicking Clear Cart. (If you do this, the wizard returns to the previous page.)
Click Finish.
The wizard then starts the background job that map the files.
Programmatic Access
The FileMan wizard uses the %fm2class routine, which is installed as part of Caché and Ensemble 2009.1.
You can also obtain this routine as an XML file and install it in Caché or Ensemble version 5.0.* or higher.
This section describes how to install this routine, if needed, and how to use it. Rather than invoking the routine directly, you use the methods in $SYSTEM.OBJ.FM2Class.
System Requirements
You must be running a standard Caché or Ensemble installation, version 5.0.* or higher.
You need a working FileMan installation.
Installing the Routine on Earlier Product Versions
The %fm2class routine is delivered as an XML file that can be loaded into the system. To install on Caché or Ensemble version 5.1 or higher:
First make sure the CACHELIB database is not mounted read only.
Then load the XML file into the %SYS namespace using the following command:
Do $SYSTEM.OBJ.Load("C:\Kits\FM2Class_v101.xml","psc")
Replace "C:\Kits\" with your actual path name. You are now ready to run the utility.
To install on Caché or Ensemble version 5.0, contact InterSystems Support for assistance.
Specifying Configuration Settings
The %fm2class routine uses the same settings that you specify in the FileMan wizard, as shown in the following table. For any setting that is displayed as a drop-down list, the following table indicates the corresponding values to use. For all yes/no settings, 1 means yes, and 0 means no. For other settings, use the same value as documented for the wizard.
To modify the default settings, use a command like the following:
Set ^%SYS("sql","fm2class",setting) = value
Where setting is an internal setting name as shown in the previous table, and value is the value to assign to it.
When you use the %fm2class routine, you can pass in an array of the following format:
arrayName(setting) = value
For example:
%fm("display")=1 %fm("package")="VISTA" %fm("superClasses")="%XML.Adaptor" %fm("wpIsList")= 1
Mapping FileMan Files Programmatically
As noted earlier, rather than invoking the %fm2class routine directly, you use methods in %System.OBJ.FM2Class, as follows:
To map all FileMan files in the current namespace:
Do $SYSTEM.OBJ.FM2Class.All(.fmSettings, .classCount)
To map one FileMan file:
Do $SYSTEM.OBJ.FM2Class.One(fileNumber,.fmSettings,.fmFields,.classCount)
To map some of FileMan files in the current namespace:
Do $SYSTEM.OBJ.FM2Class.Some(fileList,.fmSettings,.fmFields,.classCount)
The arguments are as follows:
fmSettings is an optional array passed by reference with any settings you would like the utility to use, as described earlier in this section.
classCount is optional and is also passed by reference. It returns the number of classes created by the mapper utility.
fileNumber is the FileMan file number of the file you want to map.
fmFields, if defined, limits the fields in the file that are mapped. This is an array of the form fmFields(file-number,field-number). Any required fields and fields defined in this array are mapped in the class definition. If this array is empty or not defined, all fields in the file are mapped. This array is passed by reference.
fileList is the FileMan file numbers of the files you want to map. Specify a comma-delimited list of file number or ranges of file numbers. Or specify an array of file numbers passed by reference.
The class %System.OBJ.FM2Class also provides the methods Version() and GetVersion().
Next Steps
After using the conversion utility, you should verify that you have SQL access to the generated classes. To do so, use Management Portal. At a minimum, check that you can do the following:
Browse the schema.
Execute SQL queries against the new classes.
It may also be necessary to create global and routine mappings in the namespace. Check the routines used in your generated classes to be sure that all of them are available in this namespace.
Notes
This section contains notes about how the %fm2class routine generates Caché class definitions.
-
How the utility maps variable pointer fields
How the utility maps new-style cross-references
How the utility maps cross-references that use DUZ(9)
Basics
To orient yourself, you may find it helpful to compare a simple FileMan file to the resulting Caché class definitions.
Consider the simple example of a file called PostalCode. If we look at the file attributes for this file (via the FileMan Data Dictionary Utility), we see the cross-references and indices for this file. For example:
The same utility also shows us the definitions of the fields in this file. In this case, the titles of the fields are as follows (when listed alphabetically)
City
City Abbrevation
City Key
County
Inactive Date
Mail Code
Preferred City Key
State
Unique Key (VA)
The FileMan Data Dictionary Utility also shows that the PostalCode file includes two pointers:
A pointer to the County Code file
A pointer to the State file
If we map this file, five classes are created. This includes a class to represent PostalCode, as well as classes to which this class refers. In Studio, we would see the following, if we had specified TEST as the package name:
The class definition for TEST.POSTALCODE is too long to show, but the details are summarized here:
The DATECREATED class parameter is set equal to the time when the class was created or updated.
The FILEMANFILENAME parameter is set equal to "POSTAL CODE" and the FILEMANFILENUMBER parameter is set equal to 5.12. These two parameters indicate the FileMan file from which this class was mapped.
The class includes the following properties:
CITY
CITYABBREVIATION
CITYKEY
COUNTY
IEN
INACTIVEDATE
MAILCODE
PREFERREDCITYKEY
STATE
UNIQUEKEYVA
The definitions of these properties are derived from the definitions of the corresponding fields. Also note that the FileMan Internal Entry Number is represented explicitly as a property.
Descriptive text is carried over and is used as comments. For example:
/// FileMan Field Label: 'STATE' FileMan Field Number: '3' /// This field contains a pointer to the State File to represent the state /// associated with this Postal Code. Property STATE As TEST.STATE [ SqlColumnNumber = 6, SqlFieldName = STATE ];
Several of these properties (like this one) are references to the other generated classes. This representation addresses the cross-references defined in the PostalCode file.
This utility creates foreign key constraints for each pointer field created. The foreign key constraint simply references the ID of the referenced table.
In this example, the class includes the following foreign keys to represent the pointer references in the PostalCode file:
FKeyCOUNTY(COUNTY), which references TEST.COUNTYCODE()
FKeySTATE(STATE), which references TEST.STATE()
Also see the section “Mapping of Variable Pointer Fields,” later in this section.
The class includes one index:
Index IDKeyIndex On IEN
Finally, the class includes three triggers that act when filing is performed through the FileMan filer:
BeforeDeleteFiling
BeforeInsertFiling
BeforeUpdateFiling
Mapping of Variable Pointer Fields
Each variable pointer field in the file that is mapped to a Caché class defines a property in the class that is marked with the SqlComputed keyword. For each file to which this variable pointer field refers, an additional property is created in the class, and this property is marked with the SqlComputed and Calculated keywords. If VariablePointerFieldName is the name of the variable pointer field, and PointerFileName is the name of the file to which it points, the added property is VariablePointerFieldNamePointerFileName; the SQL field name for this property is VariablePointerFieldName_PointerFileName.
For example, suppose the file ABC includes a variable pointer field called VP. The VP field can point to the Red, White, or Blue files. This creates the following properties in the class definition:
In all cases, the VP field is computed and stored automatically.
In addition to defining the three reference fields VP_Red, VP_White, and VP_Blue, the utility also creates three foreign key constraints in the ABC class for these references. This is done to ensure referential integrity is maintained between the files.
Mapping of New-Style Cross-References
This utility converts new-style cross-references to index maps if the cross-reference is defined by simple set/kill logic. This allows the Caché query optimizer to choose a new-style cross-reference index (if one exists) and increase query performance in some cases.
Mapping of Cross-References That Use DUZ(9)
As of 2017.1, FM2Class maps a cross-reference (original or new style) that was previously not mapped because the cross-reference subscripts included a reference to the variable DUZ(9) or the subscript had the form +$G(varname), where varname represents any variable reference.
If you have such cross-reference definitions, make sure that the DUZ(9) variable, or possibly any variable referenced by +$G(varname) is defined in any process running SQL queries against tables with indices mapped from these cross-references. To set DUZ(9) for a process connecting via xDBC, use $SYSTEM.SQL.SetServerInitCode().
Advanced Queries
You can use the classes %FileMan.File
and %FileMan.Field
to query the FileMan data dictionary.
Also, you can use the classes %FileMan.MappedFile
and %FileMan.MappedField
to view metadata regarding the mapping between FileMan and the class definition.
For information on the %FileMan classes, see the Intersystems Class Reference.
WebLink Developer Tags for Conversion to CSP
The tags listed in this section have been superseded by CSP tags. They are documented here to assist in migrating applications from Weblink Developer to Caché Server Pages (CSP).
For more information on each tag, please see the Weblink Developer Guide
.
<WLD:A>...</WLD:A>
This rule implements the action= mechanism of WLD.
<WLD:ACTIONSCRIPT>...</WLD:ACTIONSCRIPT>
The <CSP:METHOD> tag is superseded by the <SCRIPT LANGUAGE=CACHE METHOD> tag.
<WLD:DHTMLGRID>...</WLD:DHTMLGRID>
This rule implements the <WLD:DHTMLGRID> tag.
<WLD:END>
Required. This tag should be put at the very end of any page that uses the WLD functionality, just before the </BODY> tag.
<WLD:ERROR>
The <WLD:ERROR> tag displays the Error variable as an alert, as per Developer.
<WLD:FOCUS>
The <WLD:FOCUS> tag forces focus onto a field, as per WebLink Developer. Note the execution is carried out in the <WLD:END> tag.
<WLD:GRID>...</WLD:GRID>
This rule implements the standard <WLD:GRID> tag.
<WLD:GRID>...<WLD:GRIDDATA>...</WLD:GRIDATA>
The purpose of this empty rule is to instantiate the <WLD:GRIDDATA> tag into the DOM.
<WLD:GRID>...<WLD:GRIDHEADING>...</WLD:GRIDHEADING>
The purpose of this empty rule is to instantiate the <WLD:GRIDHEADING> tag into the DOM.
<LIST>...<WLD:OPTIONS>
The <WLD:OPTIONS> tag generates options from the LIST array.
<WLD:PostPageScript>...</WLD:PostPageScript>
Script to run after this page.
<WLD:PrePageScript>...</WLD:PrePageScript>
Script to run before this page.
<WLD:SHOWLV>
The WLDSHOWLV displays all request and session object contents.
<WLD:START>
Required. This tag should be put at the start of any page that uses the WLD functionality.
<TEXTAREA>...<WLD:WRITETEXT>
The WLD:WRITETEXT generates text from the TEXTAREA array.
<XSQL:QUERY>...</XSQL:QUERY>
Oracle XSQL tag
<INPUT TYPE=WLDCHECKBOX>
This rule implements the mechanisms for emulating WLD's CHECKBOX button interface.
<INPUT SRC TYPE=WLDIMAGE>
This rule implements the mechanisms for supporting WLD's NEXTPAGE= and ACTION= within a <input type=image> tag. | https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=GSTU_convert | CC-MAIN-2021-43 | refinedweb | 5,449 | 55.24 |
notes on my experience creating a RESTful API
Expand Messages
- Leigh Dodds surveyed web services APIs for XTech 2005:
I wrote a detailed response based on my experience creating the Webjay API:
One point I didn't make in my response is how embryonic RESTful web
services are. The ideas which are common currency here have not been
accepted by implementors. I know this because implementing them
frequently led me to bits of technology that were blatantly broken from
a RESTful perspective, yet the bugs were not known.
For example, PUT handling in PHP is treated as a synonym for file
uploading. The RESTful idea that PUT is only different from POST in
terms of what it implies about state just didn't exist once I wandered
from these environs over to #php.
Similarly, using a broad range of response status codes meant that many
user agents overwrote my error messages, so that I couldn't have an
interface which was both user friendly and RESTful. I'm not just
talking about browsers, either -- lwp-request makes the same mistake.
Another problem was that there was no prior art to glean design patterns hope these comments won't be interpreted as a bitter rant. These are
just my notes from the field.
- Lucas
[1].
- Lukas
On Sep 3, 2005, at 12:06 AM, Lucas Gonze wrote:
>
> Another problem was that there was no prior art to glean design
> patterns
> from.
Yes, that is IMHO one of the biggest problems you face once you
actually start to implement a system. I am having similar problems
right now, especially with making principled (as opposed to
arbitrary) decisions when there are several choices to implement a
certain functionality.
What I would like to work an (and hopefully will) is a methodology
for developing RESTful networked systems, including design principles
(beyond RESTs architectural constraints). Ideally this would also
include the issue of domain driven design, where the domain model
should not only be used to derive MIME type or RDF namespace
semantics but also the actual deployment of components [obviously not
cooked yet, but that's where I would like to think (one of) the major design principle is the goal to minimize
the impact that domain model changes have on the components (it is an
advantage if you can deploy them once an then more or less 'forget
about them' since you know that
- they are immune to backward compatible changes to the
message semantics since they will ignore whatever they do
not understand (partial understanding)
- they do not make (heavy) use of hardwired URIs but instead
discover them from the hypertext they process
- can be functionally extended by sending them code (assuming
you had built in things similar to JavaScript engines[1] into your
clients before you deployed them; that way using the browser
style for non-human controlled client components)
[1] One thing I have been thinking about is an engine that would
provide to the client the capability to transform RDF graphs it
receives from newer namespace versions to the one it understands,
given the server would send the code to do the transformation.
>
> I hope these comments won't be interpreted as a bitter rant. These
> are
> just my notes from the field.
>
Jan
> - Lucas
>
> [1].
>
>
>
> ------------------------ Yahoo! Groups Sponsor --------------------
> ~-->
> Most low income households are not online. Help bridge the digital
> divide today!
>
> --------------------------------------------------------------------
> ~->
>
>
> Yahoo! Groups Links
>
>
>
>
>
>
>
>
________________________________________________________________________
_______________
Jan Algermissen, Consultant & Programmer
Tugboat Consulting, 'Applying Web technology to enterprise IT'
Your message has been successfully submitted and would be delivered to recipients shortly. | https://groups.yahoo.com/neo/groups/rest-discuss/conversations/topics/5203?xm=1&o=1&m=p&tidx=1 | CC-MAIN-2015-11 | refinedweb | 593 | 50.4 |
RESTful Access to JMX Instrumentation, second part
By jeanfrancoisdenise on Jun 03, 2008
This post is an answer to William Vambenepe who recently wrote an interesting post related to JSR 262 and the REST access to JMX I discussed a few months ago. William shows some interest in the REST adaptor for JMX and asks for the next steps. Here they are...
A bit of context
The REST approach is a possible solution for interaction with JMX agents mostly due to the fact that monitoring and management is increasingly present in our systems at a much higher level than it used to be.
The data exposed tends to be directly understandable. There is no need for complex processing on the client side to understand what is going on. Why is this possible? I think that it comes from the fact that the new trend in Monitoring and Management consoles (consoles such as JConsole or Visual VM), is to display "raw" data.
This raw data is interpreted by only viewing or displaying it graphically. It makes MBean designers think more and more about their MBean interfaces as human-readable APIs. My colleague Daniel Fuchs shows the limits of this approach in a recent blog entry. But I also remember Daniel saying a few years ago that people will soon start to design MBeans to comply with JConsole's capabilities. I think that he was absolutely right. This is what is emerging now.
So it seems an appropriate time to build an HTTP based access, along standardized lines, to allow web designers to benefit from this valuable management information by making it possible to embed it directly in Web pages.
My previous post.
Security
HTTPS and Basic AUTH you provide an access and password file when starting the JVM.
Snapshot of values
Currently we can't retrieve a complex MBean attribute atomically. Say that we want to retrieve all the values contained in the HeapMemoryUsage attribute of the Memory MBean. This attribute is of type CompositeData. The well-known URLs (that point to plain text data) associated to this attribute are the following:
Currently, we can only retrieve committed, init, max and used individually.
If we introduce a new query parameter named capture, we could ask the adaptor to construct a frozen view of an attribute value (or more generally of a sub-tree). We could then retrieve the values located in the snapshot.
In practice:
GET
Returned resource :
<ul> <li></li> <li></li> <li></li> <li></li> </ul>
The returned URLs reference the captured data. We now have the freedom to analyze the values outside the ever-changing real world. This pattern could also be applied higher up in the tree (at the MBean level, for example) to create a snapshot of multiple attributes.
Notifications
We could map from JMX Notifications to atom feeds. This could be a good approach. However, here I would like to keep it simple and carry on with the resource-centric approach and try not to break the model. I would like to make the number of required technologies as minimal as possible. Relying on HTTP(S) with a bit of HTML/XML should be the maximum we allow ourselves... ;-)
So, how can we proceed? JMX MBeans are the event sources. Clients generally subscribe to MBean notifications then pull notifications from the MBean server. Pulling seems very appropriate in our web context. Pushing has never really worked..
If we agree with what has been said previously, we can attach a rolling buffer to each MBean resource that contains the last n emitted notifications (10 is a possible default value). This buffer can be pointed to using the URL scheme we have already put in place.
Here is an example URL for retrieving notifications:
If events occur, the list of emitted notifications is returned in the GET response.
<ul> <li> Notification 1 </li> <li> Notification 2 </li> ... <li> Notification N </li> </ul>
Representation of notifications.
<ul> <li></li> <li></li> <li></li> <li><...possible path if complex type></li> ... user data URL continue if complex content. </ul>
Custom notifications
If the emitted notification is custom-built, and some getters are exposed, then the added field is discovered and exposed. For example, the following notification defines a getPriority field:
public class PriorityNotification extends Notification { ... public int getPriority() { ... } }
This will be returned as follows:
<ul> <li></li> <li></li> <li></li> <li></li> <li><...possible path if complex type></li> </ul>
Filtering based on emission time
You could argue that only keeping 10 notifications is insufficient and that all notifications should be stored. OK, but in this case, we would like to be able to filter out the old ones. That can be done by adding a since query parameter when getting notifications. For example:
We just need to agree on a date format.
Notification retrieval scope
This approach allows us to express a homogenous "retrieval scope”. By choosing a location in the tree (a URL where we can get notifications), we can retrieve notifications emitted by :
MBean servers (all MBeans, and potentially all attributes too, could add a JMX pattern to narrow the scope)
MBeans
MBean attributes (equivalent to AttributeChange).
Information inside an attribute value (namely, is it a real scope, and do we want it?)
Conclusion
It seems that things are still being kept simple here without compromising the JMX technology's philosophy. Or perhaps not, and you think it is already too complicated and I should stop mining this seam... just let me know and I will down tools! ;-)
What do we have on the plate for the next post? Setting attributes and invoking MBean operations. If you have some ideas, please let me know. They are tough ones!
Thanks.
Jean-François Denise
jean-francois.denise@sun.com | https://blogs.oracle.com/jmxnetbeans/tags/http | CC-MAIN-2015-11 | refinedweb | 962 | 56.45 |
Teleconference.2008.05.21/Minutes
These minutes have been approved by the Working Group and are now protected from editing. (See IRC log of approval discussion.)
Contents
- Present
- Boris Motik, Evan Wallace, Sandro Hawke, Jeff Pan, Rinke Hoekstra, Zhe Wu, Ian Horrocks, Jie Bao, Jeremy Carroll, Bernardo Cuenca Grau, Alan Ruttenberg, Markus Krötzsch, Uli Sattler, Bijan Parsia, Achille Fokoue
- Regrets
- Peter Patel-Schneider (on a plane)
- Michael Schneider (traveling)
- Elisa Kendall (speaking at Semantic Technology Conference, see)
- Deborah McGuinness (also speaking at Semantic Technology Conference, by the way, the meeting is great!)
- Mike Smith (also at SemTech)
- Ivan Herman (SemTech)
- Carsten Lutz (traveling)
- Martin Dzbor (speaking at an outreach event in London)
- Chair
- Ian Horrocks
- Scribe
- Jeff Pan
ADMIN (20 min)
Agenda amendments?
Accept Previous Minutes
PROPOSED: Accept Previous Minutes (07 May) accepted
RESOLVED: Accept Previous Minutes (07 May)
Action items status
Action 129 Done
Action 131 Done
Action 133 Done
Action 142 Done
Action 145: done
Action 146: done
Action 149: done
Ian Horrocks: any comments on Jeremy's review on RIF?
... any pointer?
Action 139: continue
Action 143: continue
Action 112: continue
Action 144: close
Action 147: continue
Ian Horrocks: Jeremy's review on RIF
Alan Ruttenberg: get rid of stuffs that are not related to this WG
Ian Horrocks: any comments?
Jeremy Carroll: ok
PROPOSED: Jeremy's e-mail is official WG view, except point B
RESOLVED: Jeremy's e-mail is official WG view, except point B
General Discussion: Issue 97
Ian Horrocks: there is a written proposal from Sandro
pointer?
Ian Horrocks: comments?
Bijan Parsia: agree with sandro in general
... GRDDL is not clear what are required though
... sandro's proposal is as good as anything else
Ian Horrocks: any comments on ording?
Bijan Parsia: parallel way is fine as long as it is clear
Ian Horrocks: not asking to come up with implementation might not be proper
PROPOSED: proceed on parallel version of Sandro's suggestion for handling GRDDL Issue 97, as per
RESOLVED: proceed on parallel version of Sandro's suggestion for handling GRDDL Issue 97, as per
Issues
Proposals To Resolve Issues
Issue 4
Issue 4 allow reordering in functional syntax, per Alan's email
Ian Horrocks: we could resolve this without taking any action
PROPOSED: Issue 4 allow reordering in functional syntax, per Alan's email
PROPOSED: resolve Issue 4 as per
RESOLVED: resolve Issue 4 as per
Issue 71
Alan Ruttenberg: some comments from SWCG
Sandro Hawke: seems that both OWL and RIF are working this
... which one comes up with a proposal will be the one
... need to have a join TF
Alan Ruttenberg: how about name space?
Sandro Hawke: there are some problem of RDF name space
(jeremy, could you summarise your comments please?)
Ian Horrocks: who else should be in the TF?
... besides sandro
Sandro Hawke: Boris has been working on the texts
Ian Horrocks: good to keep the process lightweight
Sandro Hawke: there is a dependency on the XML WG too
Ian Horrocks: could we agree on bijan's proposal?
Bijan Parsia: we could have a TF when people disagree
Ian Horrocks: who will work on this?
Alan Ruttenberg: we need to work out a solution for the namespace
Sandro Hawke: we could leave the namespace as an open issue
OWL functionality, not an RDF one, whereas the class of allinternationalizedstrings is possibly an RDF concept
Sandro Hawke: I heard bijan would like to act on it
are not defined and SHOULD generate a warning when encountered,but should otherwise behave normally.
Boris Motik: no opinion on namespace; also busy with other work in the WG
Alan Ruttenberg: anyone on call can work on this?
ACTION: Bao create a new document as the spec for owl:internationalizedString / rif:text, including open issue discussion of namespace
new document as the spec for owl:internationalizedString / rif:text, including open issue discussion of namespace [on Jie Bao- due 2008-05-28].
ACTION: jie bao to edit langed literal document
Issue 123
Boris Motik: OWL-R-DL support some QCRs
... OWL-R-Full should cover the same set of features
... To address Issue 123 only some editorial work is needed
People agreed that to address Issue 123 only some editorial work is needed
Issue Discussions
Issue 111
imports and versioning today out-of-order. This is a fresh issue that, given the recent discussion, might be gotten out of the wayquickly.
Bijan Parsia: the processing model is unclear
... adding more properties without semantics is worrying
Alan Ruttenberg: tend to agree with bijan
... not sure what to do with imports
Boris Motik: signal to tools are not needed
"it's just a syntax error" to give DL to an EL++ system --- of course you want to give the user a better error message, don'tyou?
Bijan Parsia: useful to distinguish DL and Full semantics
... also might be useful in some use cases
is that this is defined by the syntax itself. There is no need to say "this ontology should be interpreted as EL++": if it fallsinto the EL++ fragment, it is an EL++ ontology.
about "it's just a syntax error" to give DL to an EL++ system --- of course you want to give the user a better error message, don'tyou?
Uli Sattler: should not have any semantics; it would be helpful to signal sth
Ian Horrocks: continue discussion by emails
Issue 124
Boris Motik: this is not intended to be used by people
... mainly for some process in the background e.g. moving expressions from one side to the other
... so the complement is implicitly there and it should be in the language
Bijan Parsia: support it strongly
Ian Horrocks: too less time to allow detailed discussions on the remaining actions
(better next time then)
Bijan Parsia: any plan for republication?
Ian Horrocks: should get the reviews first | http://www.w3.org/2007/OWL/wiki/index.php?title=Teleconference.2008.05.21/Minutes&redirect=no | CC-MAIN-2014-10 | refinedweb | 970 | 54.26 |
\input texinfo @setfilename cpp.info @settitle The C Preprocessor @ifinfo @dircategory Programming @direntry * Cpp: (cpp). The GNU C preprocessor. @end direntry @end ifinfo @c @smallbook @c @cropmarks @c @finalout @setchapternewpage odd @ifinfo This file documents the GNU C Preprocessor. Copyright 1987, 1989, 1991, 1992, 1993, 1994, 1995, 1997, 1998 @titlepage @c @finalout @title The C Preprocessor @subtitle Last revised September 1998 @subtitle for GCC version 2 @author Richard M. Stallman @page @vskip 2pc This booklet is eventually intended to form the first chapter of a GNU C Language manual. @vskip 0pt plus 1filll Copyright @copyright{} 1987, 1989, 1991 @page @node Top, Global Actions,, (DIR) @chapter The C Preprocessor The C preprocessor is a @dfn{macro processor} that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define @dfn{macros}, which are brief abbreviations for longer constructs. The C preprocessor provides four separate facilities that you can use as you see fit: @itemize @bullet @item Inclusion of header files. These are files of declarations that can be substituted into your program. @item Macro expansion. You can define @dfn{macros}, which are abbreviations for arbitrary fragments of C code, and then the C preprocessor will replace the macros with their definitions throughout the program. @item Conditional compilation. Using special preprocessing directives, you can include or exclude parts of the program according to various conditions. @item Line control. If you use a program to combine or rearrange source files into an intermediate file which is then compiled, you can use line control to inform the compiler of where each source line originally came from. @end itemize C preprocessors vary in some details. This manual discusses the GNU C preprocessor, the C Compatible Compiler Preprocessor. The GNU C preprocessor provides a superset of the features of ANSI Standard C@. ANSI Standard C requires the rejection of many harmless constructs commonly used by today's C programs. Such incompatibility would be inconvenient for users, so the GNU C preprocessor is configured to accept these constructs by default. Strictly speaking, to get ANSI Standard C, you must use the options @samp{-trigraphs}, @samp{-undef} and @samp{-pedantic}, but in practice the consequences of having strict ANSI Standard C make it undesirable to do this. @xref{Invocation}.. @menu * Global Actions:: Actions made uniformly on all input files. * Directives:: General syntax of preprocessing directives. * Header Files:: How and why to use header files. * Macros:: How and why to use macros. * Conditionals:: How and why to use conditionals. * Combining Sources:: Use of line control when you combine source files. * Other Directives:: Miscellaneous preprocessing directives. * Output:: Format of output from the C preprocessor. * Invocation:: How to invoke the preprocessor; command options. * Concept Index:: Index of concepts and terms. * Index:: Index of directives, predefined macros and options. @end menu @node Global Actions, Directives, Top, Top @section Transformations Made Globally Most C preprocessor features are inactive unless you give specific directives to request their use. (Preprocessing directives are lines starting with @samp{#}; @pxref{Directives}). But there are three transformations that the preprocessor always makes on all the input it receives, even in the absence of directives. @itemize @bullet @item All C comments are replaced with single spaces. @item Backslash-Newline sequences are deleted, no matter where. This feature allows you to break long lines for cosmetic purposes without changing their meaning. @item Predefined macro names are replaced with their expansions (@pxref{Predefined}). @end itemize The first two transformations are done @emph{before} nearly all other parsing and before preprocessing directives are recognized. Thus, for example, you can split a line cosmetically with Backslash-Newline anywhere (except when trigraphs are in use; see below). @example /* */ # /* */ defi\ ne FO\ O 10\ 20 @end example @noindent is equivalent into @samp{#define FOO 1020}. You can split even an escape sequence with Backslash-Newline. For example, you can split @code{"foo\bar"} between the @samp{\} and the @samp{b} to get @example "foo\\ bar" @end example @noindent This behavior is unclean: in all other contexts, a Backslash can be inserted in a string constant as an ordinary. @itemize @bullet @item C comments and predefined macro names are not recognized inside a @samp{#include} directive in which the file name is delimited with @samp{<} and @samp{>}. @item C comments and predefined macro names are never recognized within a character or string constant. (Strictly speaking, this is the rule, not an exception, but it is worth noting here anyway.) @item Backslash-Newline may not safely be used within an ANSI ``trigraph''. Trigraphs are converted before Backslash-Newline is deleted. If you write what looks like a trigraph with a Backslash-Newline inside, the Backslash-Newline is deleted as usual, but it is then too late to recognize the trigraph. This exception is relevant only if you use the @samp{-trigraphs} option to enable trigraph processing. @xref{Invocation}. @end itemize @node Directives, Header Files, Global Actions, Top @section Preprocessing Directives @cindex preprocessing directives @cindex directives Most preprocessor features are active only if you use preprocessing directives to request their use. Preprocessing directives are lines in your program that start with @samp{#}. The @samp{#} is followed by an identifier that is the @dfn{directive name}. For example, @samp{#define} is the directive that defines a macro. Whitespace is also allowed before and after the @samp{#}. The set of valid directive names is fixed. Programs cannot define new preprocessing directives. Some directive names require arguments; these make up the rest of the directive line and must be separated from the directive name by whitespace. For example, @samp{#define} must be followed by a macro name and the intended expansion of the macro. @xref @samp{#} and the directive name cannot come from a macro expansion. For example, if @samp{foo} is defined as a macro expanding to @samp{define}, that does not make @samp{#foo} a valid preprocessing directive. @node Header Files, Macros, Directives, Top @section Header Files @cindex header file A header file is a file containing C declarations and macro definitions (@pxref{Macros}) to be shared between several source files. You request the use of a header file in your program with the C preprocessing directive @samp{#include}. @menu * Header Uses:: What header files are used for. * Include Syntax:: How to write @samp{#include} directives. * Include Operation:: What @samp{#include} does. * Once-Only:: Preventing multiple inclusion of one header file. * Inheritance:: Including one header file in another header file. @end menu @node Header Uses, Include Syntax, Header Files, Header Files @subsection Uses of Header Files Header files serve two kinds of purposes. @itemize @bullet @item @findex in C compilation as copying the header file into each source file that needs it.. The usual convention is to give header files names that end with @file{.h}. Avoid unusual characters in header file names, as they reduce portability. @node Include Syntax, Include Operation, Header Uses, Header Files @subsection The @samp{#include} Directive @findex #include Both user and system header files are included using the preprocessing directive @samp{#include}. It has three variants: @table @code @item #include <@var{file}> This variant is used for system header files. It searches for a file named @var{file} in a list of directories specified by you, then in a standard list of system directories. You specify directories to search for header files with the command option @samp{-I} (@pxref{Invocation}). The option @samp{-nostdinc} inhibits searching the standard system directories; in this case only the directories you specify are searched. The parsing of this form of @samp{#include} is slightly special because comments are not recognized within the @samp{<@dots{}>}. Thus, in @samp{#include <x/*y>} the @samp{/*} does not start a comment and the directive specifies inclusion of a system header file named @file{x/*y}. Of course, a header file with such a name is unlikely to exist on Unix, where shell wildcard features would make it hard to manipulate.@refill The argument @var{file} may not contain a @samp{>} character. It may, however, contain a @samp{<} character. @item #include "@var{file}" This variant is used for header files of your own program. It searches for a file named @var{file} first in the current directory, then in the same directories used for system header files. The current directory is the directory of the current input file. It is tried first because it is presumed to be the location of the files that the current input file refers to. (If the @samp{-I-} option is used, the special treatment of the current directory is inhibited.) The argument @var{file} may not contain @samp{"} characters. If backslashes occur within @var{file}, they are considered ordinary text characters, not escape characters. None of the character escape sequences appropriate to string constants in C are processed. Thus, @samp{#include "x\n\\y"} specifies a filename containing three backslashes. It is not clear why this behavior is ever useful, but the ANSI standard specifies it. @item #include @var{anything else} @cindex computed @samp{#include} This variant is called a @dfn{computed #include}. Any @samp{#include} directive whose argument does not fit the above two forms is a computed include. The text @var{anything else} is checked for macro calls, which are expanded (@pxref{Macros}). When this is done, the result must fit one of the above two variants---in particular, the expanded text must in the end be surrounded by either quotes or angle braces.. @end table @node Include Operation, Once-Only, Include Syntax, Header Files @subsection How @samp{#include} Works, given a header file @file{header.h} as follows, @example char *test (); @end example @noindent and a main program called @file{program.c} that uses the header file, like this, @example int x; #include "header.h" main () @{ printf (test ()); @} @end example @noindent the output generated by the C preprocessor for @file{program.c} as input would be @example int x; char *test (); main () @{ printf (test ()); @} @end example. It is possible for a header file to begin or end a syntactic unit such as a function definition, but that would be very confusing, so don't do it. The line following the @samp{#include} directive is always treated as a separate line by the C preprocessor even if the included file lacks a final newline. @node Once-Only, Inheritance, Include Operation, Header Files @subsection Once-Only Include Files @cindex repeated inclusion @cindex including just once Very often, one header file includes another. It can easily result that a certain header file is included more than once. This may lead to errors, if the header file defines structure types or typedefs, and is certainly wasteful. Therefore, we often wish to prevent multiple inclusion of a header file. The standard way to do this is to enclose the entire real contents of the file in a conditional, like this: @example #ifndef FILE_FOO_SEEN #define FILE_FOO_SEEN @var{the entire file} #endif /* FILE_FOO_SEEN */ @end example The macro @code{FILE_FOO_SEEN} indicates that the file has been included once already. In a user header file, the macro name should not begin with @samp{_}. In a system header file, this name should begin with @samp{__} @samp{#ifndef} conditional, then it records that fact. If a subsequent @samp{#include} specifies the same file, and the macro in the @samp{#ifndef} is already defined, then the file is entirely skipped, without even reading it. @findex #pragma once There is also an explicit directive to tell the preprocessor that it need not include a file more than once. This is called @samp{#pragma once}, and was used @emph{in addition to} the @samp{#ifndef} conditional around the contents of the header file. @samp{#pragma once} is now obsolete and should not be used at all. @findex #import In the Objective C language, there is a variant of @samp{#include} called @samp{#import} which includes a file, but does so at most once. If you use @samp{#import} @emph{instead of} @samp{#include}, then you don't need the conditionals inside the header file to prevent multiple execution of the contents. @samp{#import} is obsolete because it is not a well designed feature. It requires the users of a header file---the applications programmers---to know that a certain header file should only be included once. It is much better for the header file's implementor to write the file so that users don't need to know this. Using @samp{#ifndef} accomplishes this goal. @node Inheritance,, Once-Only, Header Files @subsection Inheritance and Header Files @cindex inheritance @cindex overriding a header file @dfn{Inheritance} is what happens when one object or file derives some of its contents by virtual copying from another object or file. In the case of C header files, inheritance means that one header file includes another header file and then replaces or adds something. If the inheriting header file and the base header file have different names, then inheritance is straightforward: simply write @samp{#include "@var{base}"} in the inheriting file. Sometimes it is necessary to give the inheriting file the same name as the base file. This is less straightforward. For example, suppose an application program uses the system header @file{sys/signal.h}, but the version of @file{/usr/include/sys/signal.h} on a particular system doesn't do what the application program expects. It might be convenient to define a ``local'' version, perhaps under the name @file{/usr/local/include/sys/signal.h}, to override or add to the one supplied by the system. You can do this by compiling with the option @samp{-I.}, and writing a file @file{sys/signal.h} that does what the application program expects. But making this file include the standard @file{sys/signal.h} is not so easy---writing @samp{#include <sys/signal.h>} in that file doesn't work, because it includes your own version of the file, not the standard system version. Used in that file itself, this leads to an infinite recursion and a fatal error in compilation. @samp{. @findex #include_next The clean way to solve this problem is to use @samp{#include_next}, which means, ``Include the @emph{next} file with this name.'' This directive works like @samp{#include} except in searching for the specified file: it starts searching the list of header file directories @emph{after} the directory in which the current file was found. Suppose you specify @samp{-I /usr/local/include}, and the list of directories to search also includes @file{/usr/include}; and suppose both directories contain @file{sys/signal.h}. Ordinary @samp{#include <sys/signal.h>} finds the file under @file{/usr/local/include}. If that file contains @samp{#include_next <sys/signal.h>}, it starts searching after that directory, and finds the file in @file{/usr/include}. @node Macros, Conditionals, Header Files, Top @section Macros A macro is a sort of abbreviation which you can define once and then use later. There are many complicated features associated with macros in the C preprocessor. @menu * Simple Macros:: Macros that always expand the same way. * Argument Macros:: Macros that accept arguments that are substituted into the macro expansion. * Predefined:: Predefined macros that are always available. * Stringification:: Macro arguments converted into string constants. * Concatenation:: Building tokens from parts taken from macro arguments. * Undefining:: Cancelling a macro's definition. * Redefining:: Changing a macro's definition. * Macro Pitfalls:: Macros can confuse the unwary. Here we explain several common problems and strange features. @end menu @node Simple Macros, Argument Macros, Macros, Macros @subsection Simple Macros @cindex simple macro @cindex manifest constant A @dfn{simple macro} is a kind of abbreviation. It is a name which stands for a fragment of code. Some people refer to these as @dfn{manifest constants}. Before you can use a macro, you must @dfn{define} it explicitly with the @samp{#define} directive. @samp{#define} is followed by the name of the macro and then the code it should be an abbreviation for. For example, @example #define BUFFER_SIZE 1020 @end example @noindent defines a macro named @samp{BUFFER_SIZE} as an abbreviation for the text @samp{1020}. If somewhere after this @samp{#define} directive there comes a C statement of the form @example foo = (char *) xmalloc (BUFFER_SIZE); @end example @noindent then the C preprocessor will recognize and @dfn{expand} the macro @samp{BUFFER_SIZE}, resulting in @example foo = (char *) xmalloc (1020); @end example that ends the string or character constant. Comments within a macro definition may contain Newlines, which make no difference since the comments are entirely replaced with Spaces regardless of their contents. Aside from the above, there is no restriction on what can go in a macro body. Parentheses need not balance. The body need not resemble valid C code. (But if it does not, you may get error messages from the C compiler when you use the macro.) The C preprocessor scans your program sequentially, so macro definitions take effect at the place you write them. Therefore, the following input to the C preprocessor @example foo = X; #define X 4 bar = X; @end example @noindent produces as output @example foo = X; bar = 4; @end example After the preprocessor expands a macro name, the macro's definition body is appended to the front of the remaining input, and the check for macro calls continues. Therefore, the macro body can contain calls to other macros. For example, after @example #define BUFSIZE 1020 #define TABLESIZE BUFSIZE @end example @noindent the name @samp{TABLESIZE} when used in the program would go through two stages of expansion, resulting ultimately in @samp{1020}.. @xref{Cascaded Macros}. @node Argument Macros, Predefined, Simple Macros, Macros @subsection Macros with Arguments @cindex macros with argument @cindex arguments in macro definitions @cindex function-like macro A simple macro always stands for exactly the same text, each time it is used. Macros can be more flexible when they accept @dfn{arguments}. Arguments are fragments of code that you supply each time the macro is used. These fragments are included in the expansion of the macro according to the directions in the macro definition. A macro that accepts arguments is called a @dfn{function-like macro} because the syntax for using it looks like a function call. @findex #define To define a macro that uses arguments, you write a @samp{#define} directive with a list of @dfn{argument names} in parentheses after the name of the macro. The argument names may be any valid C identifiers, separated by commas and optionally whitespace. The open-parenthesis must follow the macro name immediately, with no space in between. For example, here is a macro that computes the minimum of two numeric values, as it is defined in many C programs: @example #define min(X, Y) ((X) < (Y) ? (X) : (Y)) @end example @noindent (This is not the best way to define a ``minimum'' macro in GNU C@. @xref{Side Effects}, for more information.) To use a macro that expects arguments, you write the name of the macro followed by a list of @dfn{actual arguments} in parentheses, separated by commas. The number of actual arguments you give must match the number of arguments the macro expects. Examples of use of the macro @samp{min} include @samp{min (1, 2)} and @samp{min (x + 28, *p)}. The expansion text of the macro depends on the arguments you use. Each of the argument names of the macro is replaced, throughout the macro definition, with the corresponding actual argument. Using the same macro @samp{min} defined above, @samp{min (1, 2)} expands into @example ((1) < (2) ? (1) : (2)) @end example @noindent where @samp{1} has been substituted for @samp{X} and @samp{2} for @samp{Y}. Likewise, @samp{min (x + 28, *p)} expands into @example ((x + 28) < (*p) ? (x + 28) : (*p)) @end example Parentheses in the actual arguments must balance; a comma within parentheses does not end an argument. However, there is no requirement for brackets or braces to balance, and they do not prevent a comma from separating arguments. Thus, @example macro (array[x = y, x + 1]) @end example @noindent passes two arguments to @code{macro}: @samp{array[x = y} and @samp{x + 1]}. If you want to supply @samp{array[x = y, x + 1]} as an argument, you must write it as @samp{array[(x = y, x + 1)]}, which is equivalent C code. After the actual arguments are substituted into the macro body, the entire result is appended to the front of the remaining input, and the check for macro calls continues. Therefore, the actual arguments can contain calls to other macros, either with or without arguments, or even to the same macro. The macro body can also contain calls to other macros. For example, @samp{min (min (a, b), c)} expands into this text: @example ((((a) < (b) ? (a) : (b))) < (c) ? (((a) < (b) ? (a) : (b))) : (c)) @end example @noindent (Line breaks shown here for clarity would not actually be generated.) @cindex blank macro arguments @cindex space as macro argument If a macro @code{foo} takes one argument, and you want to supply an empty argument, you must write at least some whitespace between the parentheses, like this: @samp{foo ( )}. Just @samp{foo ()} is providing no arguments, which is an error if @code{foo} expects an argument. But @samp{foo0 ()} is the correct way to call a macro defined to take zero arguments, like this: @example #define foo0() @dots{} @end example If you use the macro name followed by something other than an open-parenthesis (after ignoring any spaces, tabs and comments that follow), it is not a call to the macro, and the preprocessor does not change what you have written. Therefore, it is possible for the same name to be a variable or function in your program as well as a macro, and you can choose in each instance whether to refer to the macro (if an actual argument list follows) or the variable or function (if an argument list does not follow). Such dual use of one name could be confusing and should be avoided except when the two meanings are effectively synonymous: that is, when the name is both a macro and a function and the two have similar effects. You can think of the name simply as a function; use of the name for purposes other than calling it (such as, to take the address) will refer to the function, while calls will expand the macro and generate better but equivalent code. For example, you can use a function named @samp{min} in the same source file that defines the macro. If you write @samp{&min} with no argument list, you refer to the function. If you write @samp{min (x, bb)}, with an argument list, the macro is expanded. If you write @samp{(min) (a, bb)}, where the name @samp{min} is not followed by an open-parenthesis, the macro is not expanded, so you wind up with a call to the function @samp{min}. You may not define the same name as both a simple macro and a macro with arguments. In the definition of a macro with arguments, the list of argument names must follow the macro name immediately with no space in between. If there is a space after the macro name, the macro is defined as taking no arguments, and all the rest of the line is taken to be the expansion. The reason for this is that it is often useful to define a macro that takes no arguments and whose definition begins with an identifier in parentheses. This rule about spaces makes it possible for you to do either this: @example #define FOO(x) - 1 / (x) @end example @noindent (which defines @samp{FOO} to take an argument and expand into minus the reciprocal of that argument) or this: @example #define BAR (x) - 1 / (x) @end example @noindent (which defines @samp{BAR} to take no argument and always expand into @samp{(x) - 1 / (x)}). Note that the @emph{uses} of a macro with arguments can have spaces before the left parenthesis; it's the @emph{definition} where it matters whether there is a space. @node Predefined, Stringification, Argument Macros, Macros @subsection Predefined Macros @cindex predefined macros Several simple macros are predefined. You can use them without giving definitions for them. They fall into two classes: standard macros and system-specific macros. @menu * Standard Predefined:: Standard predefined macros. * Nonstandard Predefined:: Nonstandard predefined macros. @end menu @node Standard Predefined, Nonstandard Predefined, Predefined, Predefined @subsubsection Standard Predefined Macros @cindex standard predefined macros The standard predefined macros are available with the same meanings regardless of the machine or operating system on which you are using GNU C@. Their names all start and end with double underscores. Those preceding @code{__GNUC__} in this table are standardized by ANSI C; the rest are GNU C extensions. @table @code @item __FILE__ @findex __FILE__ This macro expands to the name of the current input file, in the form of a C string constant. The precise name returned is the one that was specified in @samp{#include} or as the input file name argument. @item __LINE__ @findex __LINE__ This macro expands to the current input line number, in the form of a decimal integer constant. While we call it a predefined macro, it's a pretty strange macro, since its ``definition'' changes with each new line of source code. This and @samp{__FILE__} A @samp{#include} directive changes the expansions of @samp{__FILE__} and @samp{__LINE__} to correspond to the included file. At the end of that file, when processing resumes on the input file that contained the @samp{#include} directive, the expansions of @samp{__FILE__} and @samp{__LINE__} revert to the values they had before the @samp{#include} (but @samp{__LINE__} is then incremented by one as processing moves to the line after the @samp{#include}). The expansions of both @samp{__FILE__} and @samp{__LINE__} are altered if a @samp{#line} directive is used. @xref{Combining Sources}. @item __DATE__ @findex __DATE__ This macro expands to a string constant that describes the date on which the preprocessor is being run. The string constant contains eleven characters and looks like @w{@samp{"Feb 1 1996"}}. @c After reformatting the above, check that the date remains `Feb 1 1996', @c all on one line, with two spaces between the `Feb' and the `1'. @item __TIME__ @findex __TIME__ This macro expands to a string constant that describes the time at which the preprocessor is being run. The string constant contains eight characters and looks like @samp{"23:59:01"}. @item __STDC__ @findex __STDC__ This macro expands to the constant 1, to signify that this is ANSI Standard C@. (Whether that is actually true depends on what C compiler will operate on the output from the preprocessor.) On some hosts, system include files use a different convention, where @samp{_ @samp{-traditional} option is used. @item __STDC_VERSION__ @findex __STDC_VERSION__ This macro expands to the C Standard's version number, a long integer constant of the form @samp{@var{yyyy}@var{mm}L} where @var{yyyy} and @var{mm} are the year and month of the Standard version. This signifies which version of the C Standard the preprocessor conforms to. Like @samp{__STDC__}, whether this version number is accurate for the entire implementation depends on what C compiler will operate on the output from the preprocessor. This macro is not defined if the @samp{-traditional} option is used. @item __GNUC__ @findex __GNUC__ This macro is defined if and only if this is GNU C@. This macro is defined only when the entire GNU C compiler is in use; if you invoke the preprocessor directly, @samp{__GNUC__} is undefined. The value identifies the major version number of GNU CC (@samp{1} for GNU CC version 1, which is now obsolete, and @samp{2} for version 2). @item __GNUC_MINOR__ @findex __GNUC_MINOR__ The macro contains the minor version number of the compiler. This can be used to work around differences between different releases of the compiler (for example, if gcc 2.6.3 is known to support a feature, you can test for @code{__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6)}). The last number, @samp{3} in the example above, denotes the bugfix level of the compiler; no macro contains this value. @item __GNUG__ @findex __GNUG__ The GNU C compiler defines this when the compilation language is C++; use @samp{__GNUG__} to distinguish between GNU C and GNU C++. @item __cplusplus @findex __cplusplus The draft ANSI standard for C++ used to require predefining this variable. Though it is no longer required, GNU C++ continues to define it, as do other popular C++ compilers. You can use @samp{__cplusplus} to test whether a header is compiled by a C compiler or a C++ compiler. @item __STRICT_ANSI__ @findex __STRICT_ANSI__ GNU C defines this macro if and only if the @samp{-ansi} switch was specified when GNU C was invoked. Its definition is the null string. This macro exists primarily to direct certain GNU header files not to define certain traditional Unix constructs which are incompatible with ANSI C@. @item __BASE_FILE__ @findex __BASE_FILE__ This macro expands to the name of the main input file, in the form of a C string constant. This is the source file that was specified as an argument when the C compiler was invoked. @item __INCLUDE_LEVEL__ @findex __INCLUDE_LEVEL_ This macro expands to a decimal integer constant that represents the depth of nesting in include files. The value of this macro is incremented on every @samp{#include} directive and decremented at every end of file. For input files specified by command line arguments, the nesting level is zero. @item __VERSION__ @findex __VERSION__ This macro expands to a string constant which describes the version number of GNU C@. The string is normally a sequence of decimal numbers separated by periods, such as @samp{"2.6.0"}. @item __OPTIMIZE__ @findex __OPTIMIZE__ GNU CC defines this macro in optimizing compilations. It causes certain GNU header files to define alternative macro definitions for some system library functions. You should not refer to or test the definition of this macro unless you make very sure that programs will execute with the same effect regardless. @item __CHAR_UNSIGNED__ @findex __CHAR_UNSIGNED__ GNU C defines this macro if and only if the data type @code{char} is unsigned on the target machine. It exists to cause the standard header file @file{limits.h} to work correctly. You should not refer to this macro yourself; instead, refer to the standard macros defined in @file{limits.h}. The preprocessor uses this macro to determine whether or not to sign-extend large character constants written in octal; see @ref{#if Directive,,The @samp{#if} Directive}. @item __REGISTER_PREFIX__ @findex __REGISTER_PREFIX__ This macro expands to a string (not a string constant) describing the prefix applied to CPU registers in assembler code. You can use it to write assembler code that is usable in multiple environments. For example, in the @samp{m68k-aout} environment it expands to the null string, but in the @samp{m68k-coff} environment it expands to the string @samp{%}. @item __USER_LABEL_PREFIX__ @findex __USER_LABEL_PREFIX__ Similar to @code{__REGISTER_PREFIX__}, but describes the prefix applied to user generated labels in assembler code. For example, in the @samp{m68k-aout} environment it expands to the string @samp{_}, but in the @samp{m68k-coff} environment it expands to the null string. This does not work with the @samp{-mno-underscores} option that the i386 OSF/rose and m88k targets provide nor with the @samp{-mcall*} options of the rs6000 System V Release 4 target. @end table @node Nonstandard Predefined,, Standard Predefined, Predefined @subsubsection Nonstandard Predefined Macros The C preprocessor normally has several predefined macros that vary between machines because their purpose is to indicate what type of system and machine is in use. This manual, being for all systems and machines, cannot tell you exactly what their names are; instead, we offer a list of some typical ones. You can use @samp{cpp -dM} to see the values of predefined macros; see @ref{Invocation}. Some nonstandard predefined macros describe the operating system in use, with more or less specificity. For example, @table @code @item unix @findex unix @samp{unix} is normally predefined on all Unix systems. @item BSD @findex BSD @samp{BSD} is predefined on recent versions of Berkeley Unix (perhaps only in version 4.3). @end table Other nonstandard predefined macros describe the kind of CPU, with more or less specificity. For example, @table @code @item vax @findex vax @samp{vax} is predefined on Vax computers. @item mc68000 @findex mc68000 @samp{mc68000} is predefined on most computers whose CPU is a Motorola 68000, 68010 or 68020. @item m68k @findex m68k @samp{m68k} is also predefined on most computers whose CPU is a 68000, 68010 or 68020; however, some makers use @samp{mc68000} and some use @samp{m68k}. Some predefine both names. What happens in GNU C depends on the system you are using it on. @item M68020 @findex M68020 @samp{M68020} has been observed to be predefined on some systems that use 68020 CPUs---in addition to @samp{mc68000} and @samp{m68k}, which are less specific. @item _AM29K @findex _AM29K @itemx _AM29000 @findex _AM29000 Both @samp{_AM29K} and @samp{_AM29000} are predefined for the AMD 29000 CPU family. @item ns32000 @findex ns32000 @samp{ns32000} is predefined on computers which use the National Semiconductor 32000 series CPU. @end table Yet other nonstandard predefined macros describe the manufacturer of the system. For example, @table @code @item sun @findex sun @samp{sun} is predefined on all models of Sun computers. @item pyr @findex pyr @samp{pyr} is predefined on all models of Pyramid computers. @item sequent @findex sequent @samp{sequent} is predefined on all models of Sequent computers. @end table These predefined symbols are not only nonstandard, they are contrary to the ANSI standard because their names do not start with underscores. Therefore, the option @samp{-ansi} inhibits the definition of these symbols. This tends to make @samp{-ansi} useless, since many programs depend on the customary nonstandard predefined symbols. Even system header files check them and will generate incorrect declarations if they do not find the names that are expected. You might think that the header files @samp{-ansi}. We intend to avoid such problems on the GNU system. What, then, should you do in an ANSI C program to test the type of machine it will run on? GNU C offers a parallel series of symbols for this purpose, whose names are made from the customary ones by adding @samp{__} at the beginning and end. Thus, the symbol @code{__vax__} would be available on a Vax, and so on. The set of nonstandard predefined names in the GNU C preprocessor is controlled (when @code{cpp} is itself compiled) by the macro @samp{CPP_PREDEFINES}, which should be a string containing @samp{-D} options, separated by spaces. For example, on the Sun 3, we use the following definition: @example #define CPP_PREDEFINES "-Dmc68000 -Dsun -Dunix -Dm68k" @end example @noindent This macro is usually specified in @file{tm.h}. @node Stringification, Concatenation, Predefined, Macros @subsection Stringification @cindex stringification @dfn{Stringification} means turning a code fragment into a string constant whose contents are the text for the code fragment. For example, stringifying @samp{foo (z)} results in @samp{"foo (z)"}. In the C preprocessor, stringification is an option available when macro arguments are substituted into the macro definition. In the body of the definition, when an argument name appears, the character @samp{#} before the name specifies stringification of the corresponding actual argument when it is substituted at that point in the definition. The same argument may be substituted in other places in the definition without stringification if the argument name appears in those places with no @samp{#}. Here is an example of a macro definition that uses stringification: @smallexample @group #define WARN_IF(EXP) \ do @{ if (EXP) \ fprintf (stderr, "Warning: " #EXP "\n"); @} \ while (0) @end group @end smallexample @noindent Here the actual argument for @samp{EXP} is substituted once as given, into the @samp{if} statement, and once as stringified, into the argument to @samp{fprintf}. The @samp{do} and @samp{while (0)} are a kludge to make it possible to write @samp{WARN_IF (@var{arg});}, which the resemblance of @samp{WARN_IF} to a function would make C programmers want to do; see @ref{Swallow Semicolon}. The stringification feature is limited to transforming one macro argument into one string constant: there is no way to combine the argument with other text and then stringify it all together. But the example above shows how an equivalent result can be obtained in ANSI Standard C using the feature that adjacent string constants are concatenated as one string constant. The preprocessor stringifies the actual value of @samp{EXP} into a separate string constant, resulting in text like @smallexample @group do @{ if (x == 0) \ fprintf (stderr, "Warning: " "x == 0" "\n"); @} \ while (0) @end group @end smallexample @noindent but the C compiler then sees three consecutive string constants and concatenates them into one, producing effectively @smallexample do @{ if (x == 0) \ fprintf (stderr, "Warning: x == 0\n"); @} \ while (0) @end smallexample Stringification in C involves more than putting doublequote characters around the fragment; it is necessary to put backslashes in front of all doublequote characters, and all backslashes in string and character constants, in order to get a valid C string constant with the proper contents. Thus, stringifying @samp{p = "foo\n";} results in @samp{"p = \"foo\\n\";"}. However, backslashes that are not inside of string or character constants are not duplicated: @samp{\n} by itself stringifies to @samp{"\n"}. Whitespace (including comments) in the text being stringified is handled according to precise rules. All leading and trailing whitespace is ignored. Any sequence of whitespace in the middle of the text is converted to a single space in the stringified result. @node Concatenation, Undefining, Stringification, Macros @subsection Concatenation @cindex concatenation @cindex @samp{##} @dfn{Concatenation} means joining two strings into one. In the context of macro expansion, concatenation refers to joining two lexical units into one longer one. Specifically, an actual argument to the macro can be concatenated with another actual argument or with fixed text to produce a longer name. The longer name might be the name of a function, variable or type, or a C keyword; it might even be the name of another macro, in which case it will be expanded. When you define a macro, you request concatenation with the special operator @samp{##} in the macro body. When the macro is called, after actual arguments are substituted, all @samp{##} operators are deleted, and so is any whitespace next to them (including whitespace that was part of an actual argument). The result is to concatenate the syntactic tokens on either side of the @samp{##}. Consider a C program that interprets named commands. There probably needs to be a table of commands, perhaps an array of structures declared as follows: @example struct command @{ char *name; void (*function) (); @}; struct command commands[] = @{ @{ "quit", quit_command@}, @{ "help", help_command@}, @dots{} @}; @end example: @example #define COMMAND(NAME) @{ #NAME, NAME ## _command @} struct command commands[] = @{ COMMAND (quit), COMMAND (help), @dots{} @}; @end example The usual case of concatenation is concatenating two names (or a name and a number) into a longer name. But this isn't the only valid case. It is also possible to concatenate two numbers (or a number and a name, such as @samp{1.5} and @samp{e3}) into a number. Also, multi-character operators such as @samp{+=} can be formed by concatenation. In some cases it is even possible to piece together a string constant. However, two pieces of text that don't together form a valid lexical unit cannot be concatenated. For example, concatenation with @samp{x} on one side and @samp{+} on the other is not meaningful because those two characters can't fit together in any lexical unit of C@. The ANSI standard says that such attempts at concatenation are undefined, but in the GNU C preprocessor it is well defined: it puts the @samp{x} and @samp{+} side by side with no particular special results. Keep in mind that the C preprocessor converts comments to whitespace before macros are even considered. Therefore, you cannot create a comment by concatenating @samp{/} and @samp{*}: the @samp{/*} sequence that starts a comment is not a lexical unit, but rather the beginning of a ``long'' space character. Also, you can freely use comments next to a @samp{##} in a macro definition, or in actual arguments that will be concatenated, because the comments will be converted to spaces at first sight, and concatenation will later discard the spaces. @node Undefining, Redefining, Concatenation, Macros @subsection Undefining Macros @cindex undefining macros To @dfn{undefine} a macro means to cancel its definition. This is done with the @samp{#undef} directive. @samp{#undef} is followed by the macro name to be undefined. Like definition, undefinition occurs at a specific point in the source file, and it applies starting from that point. The name ceases to be a macro name, and from that point on it is treated by the preprocessor as if it had never been a macro name. For example, @example #define FOO 4 x = FOO; #undef FOO x = FOO; @end example @noindent expands into @example x = 4; x = FOO; @end example @noindent In this example, @samp{FOO} had better be a variable or function as well as (temporarily) a macro, in order for the result of the expansion to be valid C code. The same form of @samp{#undef} directive will cancel definitions with arguments or definitions that don't expect arguments. The @samp{#undef} directive has no effect when used on a name not currently defined as a macro. @node Redefining, Macro Pitfalls, Undefining, Macros @subsection Redefining Macros @cindex redefining macros @dfn{Redefining} a macro means defining (with @samp{#define}) a name that is already defined as a macro. A redefinition is trivial if the new definition is transparently identical to the old one. You probably wouldn't deliberately write a trivial redefinition, but they can happen automatically when a header file is included more than once (@pxref{Header Files}), so they are accepted silently and without effect. Nontrivial redefinition is considered likely to be an error, so it provokes a warning message from the preprocessor. However, sometimes it is useful to change the definition of a macro in mid-compilation. You can inhibit the warning by undefining the macro with @samp{#undef} before the second definition. In order for a redefinition to be trivial, the new definition must exactly match the one already in effect, with two possible exceptions: @itemize @bullet @item Whitespace may be added or deleted at the beginning or the end. @item Whitespace may be changed in the middle (but not inside strings). However, it may not be eliminated entirely, and it may not be added where there was no whitespace at all. @end itemize Recall that a comment counts as whitespace. @node Macro Pitfalls,, Redefining, Macros @subsection Pitfalls and Subtleties of Macros @cindex problems with macros @cindex pitfalls of macros In this section we describe some special rules that apply to macros and macro expansion, and point out certain cases in which the rules have counterintuitive consequences that you must watch out for. @menu * Misnesting:: Macros can contain unmatched parentheses. * Macro Parentheses:: Why apparently superfluous parentheses may be necessary to avoid incorrect grouping. * Swallow Semicolon:: Macros that look like functions but expand into compound statements. * Side Effects:: Unsafe macros that cause trouble when arguments contain side effects. * Self-Reference:: Macros whose definitions use the macros' own names. * Argument Prescan:: Actual arguments are checked for macro calls before they are substituted. * Cascaded Macros:: Macros whose definitions use other macros. * Newlines in Args:: Sometimes line numbers get confused. @end menu @node Misnesting, Macro Parentheses, Macro Pitfalls, Macro Pitfalls @subsubsection Improperly Nested Constructs Recall actual arguments. For example, @example #define double(x) (2*(x)) #define call_with_1(x) x(1) @end example @noindent would expand @samp{call_with_1 (double)} into @samp{(2*(1))}. Macro definitions do not have to have balanced parentheses. By writing an unbalanced open parenthesis in a macro body, it is possible to create a macro call that begins inside the macro body but ends outside of it. For example, @example #define strange(file) fprintf (file, "%s %d", @dots{} strange(stderr) p, 35) @end example @noindent This bizarre example expands to @samp{fprintf (stderr, "%s %d", p, 35)}! @node Macro Parentheses, Swallow Semicolon, Misnesting, Macro Pitfalls @subsubsection Unintended Grouping of Arithmetic , @example #define ceil_div(x, y) (x + y - 1) / y @end example @noindent whose purpose is to divide, rounding up. (One use for this operation is to compute how many @samp{int} objects are needed to hold a certain number of @samp{char} objects.) Then suppose it is used as follows: @example a = ceil_div (b & c, sizeof (int)); @end example @noindent This expands into @example a = (b & c + sizeof (int) - 1) / sizeof (int); @end example @noindent which does not do what is intended. The operator-precedence rules of C make it equivalent to this: @example a = (b & (c + sizeof (int) - 1)) / sizeof (int); @end example @noindent But what we want is this: @example a = ((b & c) + sizeof (int) - 1)) / sizeof (int); @end example @noindent Defining the macro as @example #define ceil_div(x, y) ((x) + (y) - 1) / (y) @end example @noindent provides the desired result. Unintended grouping can result in another way. Consider @samp{sizeof ceil_div(1, 2)}. That has the appearance of a C expression that would compute the size of the type of @samp{ceil_div (1, 2)}, but in fact it means something very different. Here is what it expands to: @example sizeof ((1) + (2) - 1) / (2) @end example @noindent This would take the size of an integer and divide it by two. The precedence rules have put the division outside the @samp{sizeof} when it was intended to be inside. Parentheses around the entire macro definition can prevent such problems. Here, then, is the recommended way to define @samp{ceil_div}: @example #define ceil_div(x, y) (((x) + (y) - 1) / (y)) @end example @node Swallow Semicolon, Side Effects, Macro Parentheses, Macro Pitfalls @subsubsection Swallowing the Semicolon @cindex semicolons (after macro calls) Often it is desirable to define a macro that expands into a compound statement. Consider, for example, the following macro, that advances a pointer (the argument @samp{p} says where to find it) across whitespace characters: @example #define SKIP_SPACES(p, limit) \ @{ register char *lim = (limit); \ while (p != lim) @{ \ if (*p++ != ' ') @{ \ p--; break; @}@}@} @end example @noindent Here Backslash-Newline is used to split the macro definition, which must be a single line, so that it resembles the way such C code would be laid out if not part of a macro definition. A call to this macro might be @samp{SKIP_SPACES (p, lim)}. Strictly speaking, the call expands to a compound statement, which is a complete statement with no need for a semicolon to end it. But it looks like a function call. So it minimizes confusion if you can use it like a function call, writing a semicolon afterward, as in @samp{SKIP_SPACES (p, lim);} But this can cause trouble before @samp{else} statements, because the semicolon is actually a null statement. Suppose you write @example if (*p != 0) SKIP_SPACES (p, lim); else @dots{} @end example @noindent The presence of two statements---the compound statement and a null statement---in between the @samp{if} condition and the @samp{else} makes invalid C code. The definition of the macro @samp{SKIP_SPACES} can be altered to solve this problem, using a @samp{do @dots{} while} statement. Here is how: @example #define SKIP_SPACES(p, limit) \ do @{ register char *lim = (limit); \ while (p != lim) @{ \ if (*p++ != ' ') @{ \ p--; break; @}@}@} \ while (0) @end example Now @samp{SKIP_SPACES (p, lim);} expands into @example do @{@dots{}@} while (0); @end example @noindent which is one statement. @node Side Effects, Self-Reference, Swallow Semicolon, Macro Pitfalls @subsubsection Duplication of Side Effects @cindex side effects (in macro arguments) @cindex unsafe macros Many C programs define a macro @samp{min}, for ``minimum'', like this: @example #define min(X, Y) ((X) < (Y) ? (X) : (Y)) @end example When you use this macro with an argument containing a side effect, as shown here, @example next = min (x + y, foo (z)); @end example @noindent it expands as follows: @example next = ((x + y) < (foo (z)) ? (x + y) : (foo (z))); @end example @noindent where @samp{x + y} has been substituted for @samp{X} and @samp{foo (z)} for @samp{Y}. The function @samp{foo} is used only once in the statement as it appears in the program, but the expression @samp{foo (z)} has been substituted twice into the macro expansion. As a result, @samp{foo} might be called two times when the statement is executed. If it has side effects or if it takes a long time to compute, the results might not be what you intended. We say that @samp{min} is an @dfn{unsafe} macro. The best solution to this problem is to define @samp{min} in a way that computes the value of @samp{foo (z)} only once. The C language offers no standard way to do this, but it can be done with GNU C extensions as follows: @example #define min(X, Y) \ (@{ typeof (X) __x = (X), __y = (Y); \ (__x < __y) ? __x : __y; @}) @end example If you do not wish to use GNU C extensions, the only solution is to be careful when @emph{using} the macro @samp{min}. For example, you can calculate the value of @samp{foo (z)}, save it in a variable, and use that variable in @samp{min}: @example #define min(X, Y) ((X) < (Y) ? (X) : (Y)) @dots{} @{ int tem = foo (z); next = min (x + y, tem); @} @end example @noindent (where we assume that @samp{foo} returns type @samp{int}). @node Self-Reference, Argument Prescan, Side Effects, Macro Pitfalls @subsubsection Self-Referential Macros @cindex self-reference A @dfn{self-referential} macro is one whose name appears in its definition. A special feature of ANSI Standard C is that the self-reference is not considered a macro call. It is passed into the preprocessor output unchanged. Let's consider an example: @example #define foo (4 + foo) @end example @noindent where @samp{foo} is also a variable in your program. Following the ordinary rules, each reference to @samp{foo} will expand into @samp{(4 + foo)}; then this will be rescanned and will expand into @samp{(4 + (4 + foo))}; and so on until it causes a fatal error (memory full) in the preprocessor. However, the special rule about self-reference cuts this process short after one step, at @samp{(4 + foo)}. Therefore, this macro definition has the possibly useful effect of causing the program to add 4 to the value of @samp{foo} wherever @samp{foo} is referred to. In most cases, it is a bad idea to take advantage of this feature. A person reading the program who sees that @samp{foo} is a variable will not expect that it is a macro as well. The reader will come across the identifier @samp{foo} in the program and think its value should be that of the variable @samp{foo}, whereas in fact the value is four greater. The special rule for self-reference applies also to @dfn{indirect} self-reference. This is the case where a macro @var{x} expands to use a macro @samp{y}, and the expansion of @samp{y} refers to the macro @samp{x}. The resulting reference to @samp{x} comes indirectly from the expansion of @samp{x}, so it is a self-reference and is not further expanded. Thus, after @example #define x (4 + y) #define y (2 * x) @end example @noindent @samp{x} would expand into @samp{(4 + (2 * x))}. Clear? But suppose @samp{y} is used elsewhere, not from the definition of @samp{x}. Then the use of @samp{x} in the expansion of @samp{y} is not a self-reference because @samp{x} is not ``in progress''. So it does expand. However, the expansion of @samp{x} contains a reference to @samp{y}, and that is an indirect self-reference now because @samp{y} is ``in progress''. The result is that @samp{y} expands to @samp{(2 * (4 + y))}. It is not clear that this behavior would ever be useful, but it is specified by the ANSI C standard, so you may need to understand it. @node Argument Prescan, Cascaded Macros, Self-Reference, Macro Pitfalls @subsubsection Separate Expansion of Macro Arguments @cindex expansion of arguments @cindex macro argument expansion @cindex prescan of macro arguments is scanned again for macros to expand. The result is that the actual arguments are scanned @emph{twice} to expand macro calls in them. Most of the time, this has no effect. If the actual argument contained any macro calls, they are expanded during the first scan. The result therefore contains no macro calls, so the second scan does not change it. If the actual argument were substituted as given, with no prescan, the single remaining scan would find the same macro calls and produce the same results. You might expect the double scan to change the results when a self-referential macro is used in an actual argument of another macro (@pxref{Self-Reference}): the self-referential macro would be expanded once in the first scan, and a second time in the second scan. But this is not what happens. The self-references that do not expand in the first scan are marked so that they will not expand in the second scan either. The prescan is not done when an argument is stringified or concatenated. Thus, @example #define str(s) #s #define foo 4 str (foo) @end example @noindent expands to @samp{"foo"}. Once more, prescan has been prevented from having any noticeable effect. More precisely, stringification and concatenation use the argument as written, in un-prescanned form. The same actual argument would be used in prescanned form if it is substituted elsewhere without stringification or concatenation. @example #define str(s) #s lose(s) #define foo 4 str (foo) @end example expands to @samp{"foo" lose(4)}. You might now ask, ``Why mention the prescan, if it makes no difference? And why not skip it and make the preprocessor faster?'' The answer is that the prescan does make a difference in three special cases: @itemize @bullet @item Nested calls to a macro. @item Macros that call other macros that stringify or concatenate. @item Macros whose expansions contain unshielded commas. @end itemize We say that @dfn{nested} calls to a macro occur when a macro's actual argument contains a call to that very macro. For example, if @samp{f} is a macro that expects one argument, @samp{f (f (1))} is a nested pair of calls to @samp{f}. The desired expansion is made by expanding @samp{f (1)} and substituting that into the definition of @samp{f}. The prescan causes the expected result to happen. Without the prescan, @samp{f (1)} itself would be substituted as an actual argument, and the inner use of @samp{f} would appear during the main scan as an indirect self-reference and would not be expanded. Here, the prescan cancels an undesirable side effect (in the medical, not computational, sense of the term) of the special rule for self-referential macros. But prescan causes trouble in certain other cases of nested macro calls. Here is an example: @example #define foo a,b #define bar(x) lose(x) #define lose(x) (1 + (x)) bar(foo) @end example @noindent We would like @samp{bar(foo)} to turn into @samp{(1 + (foo))}, which would then turn into @samp{(1 + (a,b))}. But instead, @samp{bar(foo)} expands into @samp{lose(a,b)}, and you get an error because @code{lose} requires a single argument. In this case, the problem is easily solved by the same parentheses that ought to be used to prevent misnesting of arithmetic operations: @example #define foo (a,b) #define bar(x) lose((x)) @end example The problem is more serious when the operands of the macro are not expressions; for example, when they are statements. Then parentheses are unacceptable because they would make for invalid C code: @example #define foo @{ int a, b; @dots{} @} @end example @noindent In GNU C you can shield the commas using the @samp{(@{@dots{}@})} construct which turns a compound statement into an expression: @example #define foo (@{ int a, b; @dots{} @}) @end example Or you can rewrite the macro definition to avoid such commas: @example #define foo @{ int a; int b; @dots{} @} @end example There is also one case where prescan is useful. It is possible to use prescan to expand an argument and then stringify it---if you use two levels of macros. Let's add a new macro @samp{xstr} to the example shown above: @example #define xstr(s) str(s) #define str(s) #s #define foo 4 xstr (foo) @end example This expands into @samp{"4"}, not @samp{"foo"}. The reason for the difference is that the argument of @samp{xstr} is expanded at prescan (because @samp{xstr} does not specify stringification or concatenation of the argument). The result of prescan then forms the actual argument for @samp{str}. @samp{str} uses its argument without prescan because it performs stringification; but it cannot prevent or undo the prescanning already done by @samp{xstr}. @node Cascaded Macros, Newlines in Args, Argument Prescan, Macro Pitfalls @subsubsection Cascaded Use of Macros @cindex cascaded macros @cindex macro body uses macro A @dfn{cascade} of macros is when one macro's body contains a reference to another macro. This is very common practice. For example, @example #define BUFSIZE 1020 #define TABLESIZE BUFSIZE @end example. This makes a difference if you change the definition of @samp{BUFSIZE} at some point in the source file. @samp{TABLESIZE}, defined as shown, will always expand using the definition of @samp{BUFSIZE} that is currently in effect: @example #define BUFSIZE 1020 #define TABLESIZE BUFSIZE #undef BUFSIZE #define BUFSIZE 37 @end example @noindent Now @samp{TABLESIZE} expands (in two stages) to @samp{37}. (The @samp{#undef} is to prevent any warning about the nontrivial redefinition of @code{BUFSIZE}.) @node Newlines in Args,, Cascaded Macros, Macro Pitfalls @subsection Newlines in Macro Arguments @cindex newlines in macro arguments: @example #define ignore_second_arg(a,b,c) a; c ignore_second_arg (foo (), ignored (), syntax error); @end example @noindent The syntax error triggered by the tokens @samp{syntax error} results in an error message citing line four, even though the statement text comes from line five. @node Conditionals, Combining Sources, Macros, Top @section Conditionals @cindex conditionals In a macro processor, a @dfn{conditional} is a directive that allows a part of the program to be ignored during compilation, on some conditions. In the C preprocessor, a conditional can test either an arithmetic expression or whether a name is defined as a macro. A conditional in the C preprocessor resembles in some ways an @samp{if} statement in C, but it is important to understand the difference between them. The condition in an @samp. @menu * Uses: Conditional Uses. What conditionals are for. * Syntax: Conditional Syntax. How conditionals are written. * Deletion: Deleted Code. Making code into a comment. * Macros: Conditionals-Macros. Why conditionals are used with macros. * Assertions:: How and why to use assertions. * Errors: #error Directive. Detecting inconsistent compilation parameters. @end menu @node Conditional Uses @subsection Why Conditionals are Used Generally there are three kinds of reason library routines that do not exist on the other system. When this happens, it is not enough to avoid executing the invalid code: merely having it in the program makes it impossible to link the program and run it. With a preprocessing conditional, the offending code can be effectively excised from the program when it is not valid. @item You may want to be able to compile the same source file into two different programs. Sometimes the difference between the programs is that one makes frequent time-consuming consistency checks on its intermediate data, or prints the values of those data for debugging, while the other does not. @item A conditional whose condition is always false is a good way to exclude code from the program but keep it as a sort of comment for future reference. @end itemize Most simple programs that are intended to run on only one machine will not need to use preprocessing conditionals. @node Conditional Syntax @subsection Syntax of Conditionals @findex #if A conditional in the C preprocessor begins with a @dfn{conditional directive}: @samp{#if}, @samp{#ifdef} or @samp{#ifndef}. @xref{Conditionals-Macros}, for information on @samp{#ifdef} and @samp{#ifndef}; only @samp{#if} is explained here. @menu * If: #if Directive. Basic conditionals using @samp{#if} and @samp{#endif}. * Else: #else Directive. Including some text if the condition fails. * Elif: #elif Directive. Testing several alternative possibilities. @end menu @node #if Directive @subsubsection The @samp{#if} Directive The @samp{#if} directive in its simplest form consists of @example #if @var{expression} @var{controlled text} #endif /* @var{expression} */ @end example The comment following the @samp{#endif} is not required, but it is a good practice because it helps people match the @samp{#endif} to the corresponding @samp{#if}. Such comments should always be used, except in short conditionals that are not nested. In fact, you can put anything at all after the @samp{#endif} and it will be ignored by the GNU C preprocessor, but only comments are acceptable in ANSI Standard C@. @var{expression} is a C expression of integer type, subject to stringent restrictions. It may contain @itemize @bullet @item Integer constants, which are all regarded as @code{long} or @code{unsigned long}. @item Character constants, which are interpreted according to the character set and conventions of the machine and operating system on which the preprocessor is running. The GNU C preprocessor uses the C data type @samp{char} for these character constants; therefore, whether some character codes are negative is determined by the C compiler used to compile the preprocessor. If it treats @samp{char} as signed, then character codes large enough to set the sign bit will be considered negative; otherwise, no character code is considered negative. @item Arithmetic operators for addition, subtraction, multiplication, division, bitwise operations, shifts, comparisons, and logical operations (@samp{&&} and @samp{||}). @item Identifiers that are not macros, which are all treated as zero(!). @item Macro calls. All macro calls in the expression are expanded before actual computation of the expression's value begins. @end itemize Note that @samp{sizeof} operators and @code{enum}-type values are not allowed. @code{enum}-type values, like all other identifiers that are not taken as macro calls and expanded, are treated as zero. The @var{controlled text} inside of a conditional can include preprocessing directives. Then the directives inside the conditional are obeyed only if that branch of the conditional succeeds. The text can also contain other conditional groups. However, the @samp{#if} and @samp{#endif} directives must balance. @node #else Directive @subsubsection The @samp{#else} Directive @findex #else The @samp{#else} directive can be added to a conditional to provide alternative text to be used if the condition is false. This is what it looks like: @example #if @var{expression} @var{text-if-true} #else /* Not @var{expression} */ @var{text-if-false} #endif /* Not @var{expression} */ @end example If @var{expression} is nonzero, and thus the @var{text-if-true} is active, then @samp{#else} acts like a failing conditional and the @var{text-if-false} is ignored. Contrariwise, if the @samp{#if} conditional fails, the @var{text-if-false} is considered included. @node #elif Directive @subsubsection The @samp{#elif} Directive @findex #elif One common case of nested conditionals is used to check for more than two possible alternatives. For example, you might have @example #if X == 1 @dots{} #else /* X != 1 */ #if X == 2 @dots{} #else /* X != 2 */ @dots{} #endif /* X != 2 */ #endif /* X != 1 */ @end example Another conditional directive, @samp{#elif}, allows this to be abbreviated as follows: @example #if X == 1 @dots{} #elif X == 2 @dots{} #else /* X != 2 and X != 1*/ @dots{} #endif /* X != 2 and X != 1*/ @end example @samp{#elif} stands for ``else if''. Like @samp{#else}, it goes in the middle of a @samp{#if}-@samp{#endif} pair @samp{#if}-@samp{#endif} group. Then the text after each @samp{#elif} is processed only if the @samp{#elif} condition succeeds after the original @samp{#if} and any previous @samp{#elif} directives within it have failed. @samp{#else} is equivalent to @samp{#elif 1}, and @samp{#else} is allowed after any number of @samp{#elif} directives, but @samp{#elif} may not follow @samp{#else}. @node Deleted Code @subsection Keeping Deleted Code for Future Reference @cindex commenting out code If you replace or delete a part of the program but want to keep the old code around as a comment for future reference, the easy way to do this is to put @samp{#if 0} before it and @samp{#endif} after it. This is better than using comment delimiters @samp{/*} and @samp{*/} since those won't work if the code already contains comments (C comments do not nest). This works even if the code being turned off contains conditionals, but they must be entire conditionals (balanced @samp{#if} and @samp{#endif}). Conversely, do not use @samp{#if 0} for comments which are not C code. Use the comment delimiters @samp{/*} and @samp{*/} instead. The interior of @samp{#if 0} must consist of complete tokens; in particular, singlequote characters must balance. But comments often contain unbalanced singlequote characters (known in English as apostrophes). These confuse @samp{#if 0}. They do not confuse @samp{/*}. @node Conditionals-Macros @subsection Conditionals and Macros Conditionals are useful in connection with macros or assertions, because those are the only ways that an expression's value can vary from one compilation to another. A @samp{#if} directive whose expression uses no macros or assertions is equivalent to @samp{#if 1} or @samp{#if 0}; you might as well determine which one, by computing the value of the expression yourself, and then simplify the program. For example, here is a conditional that tests the expression @samp{BUFSIZE == 1020}, where @samp{BUFSIZE} must be a macro. @example #if BUFSIZE == 1020 printf ("Large buffers!\n"); #endif /* BUFSIZE is large */ @end example (Programmers often wish they could test the size of a variable or data type in @samp{#if}, but this does not work. The preprocessor does not understand @code{sizeof}, or typedef names, or even the type keywords such as @code{int}.) @findex defined The special operator @samp{defined} is used in @samp{#if} expressions to test whether a certain name is defined as a macro. Either @samp{defined @var{name}} or @samp{defined (@var{name})} is an expression whose value is 1 if @var{name} is defined as macro at the current point in the program, and 0 otherwise. For the @samp{defined} operator it makes no difference what the definition of the macro is; all that matters is whether there is a definition. Thus, for example,@refill @example #if defined (vax) || defined (ns16000) @end example @noindent would succeed if either of the names @samp{vax} and @samp{ns16000} is defined as a macro. You can test the same condition using assertions (@pxref{Assertions}), like this: @example #if #cpu (vax) || #cpu (ns16000) @end example If a macro is defined and later undefined with @samp{#undef}, subsequent use of the @samp{defined} operator returns 0, because the name is no longer defined. If the macro is defined again with another @samp{#define}, @samp{defined} will recommence returning 1. @findex #ifdef @findex #ifndef Conditionals that test whether just one name is defined are very common, so there are two special short conditional directives for this case. @table @code @item #ifdef @var{name} is equivalent to @samp{#if defined (@var{name})}. @item #ifndef @var{name} is equivalent to @samp{#if ! defined (@var{name})}. @end table Macro definitions can vary between compilations for several reasons. @itemize @bullet @item Some macros are predefined on each kind of machine. For example, on a Vax, the name @samp{vax} is a predefined macro. On other machines, it would not be defined. @item Many more macros are defined by system header files. Different systems and machines define different macros, or give them different values. It is useful to test these macros with conditionals to avoid using a system feature on a machine where it is not implemented. @item Macros are a common way of allowing users to customize a program for different machines or applications. For example, the macro @samp{BUFSIZE} might be defined in a configuration file for your program that is included as a header file in each source file. You would use @samp{BUFSIZE} in a preprocessing conditional in order to generate different code depending on the chosen configuration. @item Macros can be defined or undefined with @samp{-D} and @samp{-U} command compiler command options. @xref{Invocation}. @end itemize @ifinfo Assertions are usually predefined, but can be defined with preprocessor directives or command-line options. @end ifinfo @node Assertions @subsection Assertions @cindex assertions @dfn{Assertions} are a more systematic alternative to macros in writing conditionals to test what sort of computer or system the compiled program will run on. Assertions are usually predefined, but you can define them with preprocessing directives or command-line options. @cindex predicates @dfn{predicate}. An assertion looks like this: @example #@var{predicate} (@var{answer}) @end example @noindent You must use a properly formed identifier for @var{predicate}. The value of @var{answer} can be any sequence of words; all characters are significant except for leading and trailing whitespace, and differences in internal whitespace sequences are ignored. Thus, @samp{x + y} is different from @samp{x+y} but equivalent to @samp{x + y}. @samp{)} is not allowed in an answer. @cindex testing predicates Here is a conditional to test whether the answer @var{answer} is asserted for the predicate @var{predicate}: @example #if #@var{predicate} (@var{answer}) @end example @noindent There may be more than one answer asserted for a given predicate. If you omit the answer, you can test whether @emph{any} answer is asserted for @var{predicate}: @example #if #@var{predicate} @end example @findex #system @findex #machine @findex #cpu Most of the time, the assertions you test will be predefined assertions. GNU C provides three predefined predicates: @code{system}, @code{cpu}, and @code{machine}. @code{system} is for assertions about the type of software, @code{cpu} describes the type of computer architecture, and @code{machine} gives more information about the computer. For example, on a GNU system, the following assertions would be true: @example #system (gnu) #system (mach) #system (mach 3) #system (mach 3.@var{subversion}) #system (hurd) #system (hurd @var{version}) @end example @noindent and perhaps others. The alternatives with more or less version information let you ask more or less detailed questions about the type of system software. On a Unix system, you would find @code{#system (unix)} and perhaps one of: @code{#system (aix)}, @code{#system (bsd)}, @code{#system (hpux)}, @code{#system (lynx)}, @code{#system (mach)}, @code{#system (posix)}, @code{#system (svr3)}, @code{#system (svr4)}, or @code{#system (xpg4)} with possible version numbers following. Other values for @code{system} are @code{#system (mvs)} and @code{#system (vms)}. @strong{Portability note:} Many Unix C compilers provide only one answer for the @code{system} assertion: @code{#system (unix)}, if they support assertions at all. This is less than useful. An assertion with a multi-word answer is completely different from several assertions with individual single-word answers. For example, the presence of @code{system (mach 3.0)} does not mean that @code{system (3.0)} is true. It also does not directly imply @code{system (mach)}, but in GNU C, that last will normally be asserted as well. The current list of possible assertion values for @code{cpu} is: @code{#cpu (a29k)}, @code{#cpu (alpha)}, @code{#cpu (arm)}, @code{#cpu (clipper)}, @code{#cpu (convex)}, @code{#cpu (elxsi)}, @code{#cpu (tron)}, @code{#cpu (h8300)}, @code{#cpu (i370)}, @code{#cpu (i386)}, @code{#cpu (i860)}, @code{#cpu (i960)}, @code{#cpu (m68k)}, @code{#cpu (m88k)}, @code{#cpu (mips)}, @code{#cpu (ns32k)}, @code{#cpu (hppa)}, @code{#cpu (pyr)}, @code{#cpu (ibm032)}, @code{#cpu (rs6000)}, @code{#cpu (sh)}, @code{#cpu (sparc)}, @code{#cpu (spur)}, @code{#cpu (tahoe)}, @code{#cpu (vax)}, @code{#cpu (we32000)}. @findex #assert You can create assertions within a C program using @samp{#assert}, like this: @example #assert @var{predicate} (@var{answer}) @end example @noindent (Note the absence of a @samp{#} before @var{predicate}.) @cindex unassert @cindex assertions, undoing @cindex retracting assertions @findex #unassert Each time you do this, you assert a new true answer for @var{predicate}. Asserting one answer does not invalidate previously asserted answers; they all remain true. The only way to remove an assertion is with @samp{#unassert}. @samp{#unassert} has the same syntax as @samp{#assert}. You can also remove all assertions about @var{predicate} like this: @example #unassert @var{predicate} @end example You can also add or cancel assertions using command options when you run @code{gcc} or @code{cpp}. @xref{Invocation}. @node #error Directive @subsection The @samp{#error} and @samp{#warning} Directives @findex #error The directive @samp{#error} causes the preprocessor to report a fatal error. The rest of the line that follows @samp{#error} is used as the error message. The line must consist of complete tokens. @noindent @xref{Nonstandard Predefined}, for why this works. If you have several configuration parameters that must be set up by the installation in a consistent way, you can use conditionals to detect an inconsistency and report it with @samp{#error}. For example, @smallexample #if HASH_TABLE_SIZE % 2 == 0 || HASH_TABLE_SIZE % 3 == 0 \ || HASH_TABLE_SIZE % 5 == 0 #error HASH_TABLE_SIZE should not be divisible by a small prime #endif @end smallexample @findex #warning The directive @samp{#warning} is like the directive @samp{#error}, but causes the preprocessor to issue a warning and continue preprocessing. The rest of the line that follows @samp{#warning} is used as the warning message. You might use @samp{#warning} in obsolete header files, with a message directing the user to the header file which should be used instead. @node Combining Sources, Other Directives, Conditionals, Top @section Combining Source Files @cindex line control One of the jobs of the C preprocessor is to inform the C compiler of where each line of C code came from: which source file and which line number. C code can come from multiple source files if you use @samp{#include}; both @samp{#include} and the use of conditionals and macros can cause the line number of a line in the preprocessor by which you can control the feature explicitly. This is useful when a file for input to the C preprocessor is the output from another program such as the @code{bison} parser generator, which operates on another file that is the true source file. Parts of the output from @code{bison} are generated from scratch, other parts come from a standard parser file. The rest are copied nearly verbatim from the source file, but their line numbers in the @code{bison} output are not the same as their original line numbers. Naturally you would like compiler error messages and symbolic debuggers to know the original source file and line number of each line in the @code{bison} input. @findex #line @code{bison} arranges} Here @var{linenum} is a decimal integer constant. This specifies that the line number of the following line of input, in its original source file, was @var{linenum}. @item #line @var{linenum} @var{filename} Here @var{linenum} is a decimal integer constant and @var{filename} is a string constant. This specifies that the following line of input came originally from source file @var{filename} and its line number there was @var{linenum}. Keep in mind that @var{filename} is not just a file name; it is surrounded by doublequote characters so that it looks like a string constant. @item #line @var{anything else} @var{anything else} is checked for macro calls, which are expanded. The result should be a decimal integer constant followed optionally by a string constant, as described above. @end table @samp{#line} directives alter the results of the @samp{__FILE__} and @samp{__LINE__} predefined macros from that point on. @xref{Standard Predefined}. The output of the preprocessor (which is the input for the rest of the compiler) contains directives that look much like @samp{#line} directives. They start with just @samp{#} instead of @samp{#line}, but this is followed by a line number and file name as in @samp{#line}. @xref{Output}. @node Other Directives, Output, Combining Sources, Top @section Miscellaneous Preprocessing Directives @cindex null directive This section describes three additional preprocessing directives. They are not very useful, but are mentioned for completeness.. @findex #pragma The ANSI standard specifies that the effect of the @samp{#pragma} directive is implementation-defined. In the GNU C preprocessor, @samp{#pragma} directives are not used, except for @samp{#pragma once} (@pxref{Once-Only}). However, they are left in the preprocessor output, so they are available to the compilation pass. @findex #ident The @samp{#ident} directive is supported for compatibility with certain other systems. It is followed by a line of text. On some systems, the text is copied into a special place in the object file; on most systems, the text is ignored and this directive has no effect. Typically @samp{#ident} is only used in header files supplied with those systems where it is meaningful. @node Output, Invocation, Other Directives, Top @section C Preprocessor Output @cindex output format The output from the C preprocessor looks much like the input, except that all preprocessing directive lines have been replaced with blank lines and all comments with spaces. Whitespace within a line is not altered; however, unless @samp{-traditional} is used, spaces may be inserted into the expansions of macro calls to prevent tokens from being concatenated. Source file name and line number information is conveyed by lines of the form @example # @var{linenum} @var{filename} @var{flags} @end example @noindent which are inserted as needed into the middle of the input (but never within a string or character constant). Such a line means that the following line originated in file @var{filename} at line @var{linenum}. C@. @c maybe cross reference NO_IMPLICIT_EXTERN_C @end table @node Invocation, Concept Index, Output, Top @section Invoking the C Preprocessor @cindex invocation of the preprocessor Most often when you use the C preprocessor you will not have to invoke it explicitly: the C compiler will do so automatically. However, the preprocessor is sometimes useful on its own. @samp{-}, which as @var{infile} means to read from standard input and as @var{outfile} means to write to standard output. Also, if @var{outfile} or both file names are omitted, the standard output and standard input are used for the omitted file names. @cindex options Here is a table of command options accepted by the C preprocessor. These options can also be given when compiling a C program; they are passed along automatically to the preprocessor when it is invoked by the compiler. @table @samp @item -P @findex -P Inhibit generation of @samp{#}-lines with line-number information in the output from the preprocessor (@pxref{Output}). This might be useful when running the preprocessor on something that is not C code and will be sent to a program which might be confused by the @samp{#}-lines. @item -C @findex -C Do not discard comments: pass them through to the output file. Comments appearing in arguments of a macro call will be copied to the output before the expansion of the macro call. @item -traditional @findex -traditional Try to imitate the behavior of old-fashioned C, as opposed to ANSI C@. @itemize @bullet @item Traditional macro expansion pays no attention to singlequote or doublequote characters; macro argument symbols are replaced by the argument values even when they appear within apparent string or character constants. @item Traditionally, it is permissible for a macro expansion to end in the middle of a string or character constant. The constant continues into the text surrounding the macro call. @item However, traditionally the end of the line terminates a string or character constant, with no error. @item In traditional C, a comment is equivalent to no text at all. (In ANSI C, a comment counts as whitespace.) @item Traditional C does not have the concept of a ``preprocessing number''. It considers @samp{1.0e+4} to be three tokens: @samp{1.0e}, @samp{+}, and @samp{4}. @item A macro is not suppressed within its own definition, in traditional C@. Thus, any macro that is used recursively inevitably causes an error. @item The character @samp{#} has no special meaning within a macro definition in traditional C@. @item In traditional C, the text at the end of a macro expansion can run together with the text after the macro call, to produce a single token. (This is impossible in ANSI C@.) @item Traditionally, @samp{\} inside a macro argument suppresses the syntactic significance of the following character. @end itemize @cindex Fortran @cindex unterminated Use the @samp{-traditional} option when preprocessing Fortran code, so that singlequotes and doublequotes within Fortran comment lines (which are generally not recognized as such by the preprocessor) do not cause diagnostics about unterminated character or string constants. However, this option does not prevent diagnostics about unterminated comments when a C-style comment appears to start, but not end, within Fortran-style commentary. So, the following Fortran comment lines are accepted with @samp{-traditional}: @smallexample C This isn't an unterminated character constant C Neither is "20000000000, an octal constant C in some dialects of Fortran @end smallexample However, this type of comment line will likely produce a diagnostic, or at least unexpected output from the preprocessor, due to the unterminated comment: @smallexample C Some Fortran compilers accept /* as starting C an inline comment. @end smallexample @cindex g77 Note that @code{g77} automatically supplies the @samp{-traditional} option when it invokes the preprocessor. However, a future version of @code{g77} might use a different, more-Fortran-aware preprocessor in place of @code{cpp}. @item -trigraphs @findex -trigraphs Process ANSI standard trigraph sequences. These are three-character sequences, all starting with @samp{??}, that are defined by ANSI C to stand for single characters. For example, @samp{??/} stands for @samp{\}, so @samp{'??/n'} is a character constant for a newline. Strictly speaking, the GNU C preprocessor does not support all programs in ANSI Standard C unless @samp{-trigraphs} is used, but if you ever notice the difference it will be with relief. You don't want to know any more about trigraphs. @item -pedantic @findex -pedantic Issue warnings required by the ANSI C standard in certain cases such as when text other than a comment follows @samp{#else} or @samp{#endif}. @item -pedantic-errors @findex -pedantic-errors Like @samp{-pedantic}, except that errors are produced rather than warnings. @item -Wtrigraphs @findex -Wtrigraphs Warn if any trigraphs are encountered. Currently this only works if you have turned trigraphs on with @samp{-trigraphs} or @samp{-ansi}; in the future this restriction will be removed. @item -Wcomment @findex -Wcomment @ignore @c "Not worth documenting" both singular and plural forms of this @c option, per RMS. But also unclear which is better; hence may need to @c switch this at some future date. pesch@cygnus.com, 2jan92. @itemx -Wcomments (Both forms have the same effect). @end ignore Warn whenever a comment-start sequence @samp{/*} appears in a @samp{/*} comment, or whenever a Backslash-Newline appears in a @samp{//} comment. @item -Wall @findex -Wall Requests both @samp{-Wtrigraphs} and @samp{-Wcomment} (but not @samp{-Wtraditional} or @samp{-Wundef}). @item -Wtraditional @findex -Wtraditional Warn about certain constructs that behave differently in traditional and ANSI C@. @item -Wundef @findex -Wundef Warn if an undefined identifier is evaluated in an @samp{#if} directive. @item -I @var{directory} @findex -I Add the directory @var{directory} to the head of the list of directories to be searched for header files (@pxref{Include Syntax}). specified. In addition, the @samp{-I-} option inhibits the use of the current directory as the first search directory for @samp{#include "@var{file}"}. Therefore, the current directory is searched only if it is requested explicitly with @samp{-I.}. Specifying both @samp{-I-} and @samp{-I.} allows you to control precisely which directories are searched before the current one and which are searched after. @item -nostdinc @findex -nostdinc Do not search the standard system directories for header files. Only the directories you have specified with @samp{-I} options (and the current directory, if appropriate) are searched. @item -nostdinc++ @findex -nostdinc++ Do not search for header files in the C++-specific standard directories, but do still search the other standard directories. (This option is used when building the C++ library.) @item -remap @findex -remap When searching for a header file in a directory, remap file names if a file named @file{header.gcc} exists in that directory. This can be used to work around limitations of file systems with file name restrictions. The @file{header.gcc} file should contain a series of lines with two tokens on each line: the first token is the name to map, and the second token is the actual name to use. @item -D @var{name} @findex -D Predefine @var{name} as a macro, with definition @samp{1}. @item -D @var{name}=@var{definition} Predefine @var{name} as a macro, with definition @var{definition}. There are no restrictions on the contents of @var{definition}, but if you are invoking the preprocessor from a shell or shell-like program you may need to use the shell's quoting syntax to protect characters such as spaces that have a meaning in the shell syntax. If you use more than one @samp{-D} for the same @var{name}, the rightmost definition takes effect. @item -U @var{name} @findex -U Do not predefine @var{name}. If both @samp{-U} and @samp{-D} are specified for one name, the @samp{-U} beats the @samp{-D} and the name is not predefined. @item -undef @findex -undef Do not predefine any nonstandard macros. @item -gcc @findex -gcc Define the macros @var{__GNUC__} and @var{__GNUC_MINOR__}. These are defined automatically when you use @samp{gcc -E}; you can turn them off in that case with @samp{-no-gcc}. @item -A @var{predicate}(@var{answer}) @findex -A Make an assertion with the predicate @var{predicate} and answer @var{answer}. @xref{Assertions}. @noindent You can use @samp{-A-} to disable all predefined assertions; it also undefines all predefined macros and all macros that preceded it on the command line. @item -dM @findex -dM Instead of outputting the result of preprocessing, output a list of @samp{#define} directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor; assuming you have no file @samp{foo.h}, the command @example touch foo.h; cpp -dM foo.h @end example @noindent will show the values of any predefined macros. @item -dD @findex -dD Like @samp{-dM} except in two respects: it does @emph{not} include the predefined macros, and it outputs @emph{both} the @samp{#define} directives and the result of preprocessing. Both kinds of output go to the standard output file. @item -dI @findex -dI Output @samp{#include} directives in addition to the result of preprocessing. @item -M [-MG] @findex -M Instead of outputting the result of preprocessing, output a rule suitable for @code{make} describing the dependencies of the main source file. The preprocessor outputs one @code{make} rule containing the object file name for that source file, a colon, and the names of all the included files. If there are many included files then the rule is split into several lines using @samp{\}-newline. @samp{-MG} says to treat missing header files as generated files and assume they live in the same directory as the source file. It must be specified in addition to @samp{-M}. This feature is used in automatic updating of makefiles. @item -MM [-MG] @findex -MM Like @samp{-M} but mention only the files included with @samp{#include "@var{file}"}. System header files included with @samp{#include <@var{file}>} are omitted. @item -MD @var{file} @findex -MD Like @samp{-M} but the dependency information is written to @var{file}. This is in addition to compiling the file as specified---@samp{-MD} does not inhibit ordinary compilation the way @samp{-M} does. When invoking @code{gcc}, do not specify the @var{file} argument. @code{gcc} will create file names made by replacing ".c" with ".d" at the end of the input file names. In Mach, you can use the utility @code{md} to merge multiple dependency files into a single dependency file suitable for using with the @samp{make} command. @item -MMD @var{file} @findex -MMD Like @samp{-MD} except mention only user header files, not system header files. @item -H @findex -H Print the name of each header file used, in addition to other normal activities. @item -imacros @var{file} @findex -imacros. @item -include @var{file} @findex -include Process @var{file} as input, and include all the resulting output, before processing the regular input file. @item -idirafter @var{dir} @findex -idirafter } @findex -iprefix Specify @var{prefix} as the prefix for subsequent @samp{-iwithprefix} options. @item -iwithprefix @var{dir} @findex -iwithprefix Add a directory to the second include path. The directory's name is made by concatenating @var{prefix} and @var{dir}, where @var{prefix} was specified previously with @samp{-iprefix}. @item -isystem @var{dir} @findex -isystem Add a directory to the beginning of the second include path, marking it as a system directory, so that it gets the same special treatment as is applied to the standard system directories. @item -x c @itemx -x c++ @itemx -x objective-c @itemx -x assembler-with-cpp @findex -x c @findex -x objective-c @findex : @samp{.c}, @samp{.cc}, @samp{.m}, or @samp{.S}. Some other common extensions for C++ and assembly are also recognized. If cpp does not recognize the extension, it will treat the file as C; this is the most generic mode. @strong{Note:} Previous versions of cpp accepted a @samp{-lang} option which selected both the language and the standards conformance level. This option has been removed, because it conflicts with the @samp{-l} option. @item -std=@var{standard} @itemx -ansi @findex -std @findex -ansi Specify the standard to which the code should conform. Currently cpp only knows about the standards for C; other language standards will be added in the future. @var{standard} may be one of: @table @code @item iso9899:1990 The ISO C standard from 1990. @item iso9899:199409 @itemx c89 The 1990 C standard, as amended in 1994. @samp{c89} is the customary shorthand for this version of the standard. The @samp{-ansi} option is equivalent to @samp{-std=c89}. @item iso9899:199x @itemx c9x The revised ISO C standard, which is expected to be promulgated some time in 1999. It has not been approved yet, hence the @samp{x}. @item gnu89 The 1990 C standard plus GNU extensions. This is the default. @item gnu9x The 199x C standard plus GNU extensions. @end table @item -Wp,-lint @findex -lint Look for commands to the program checker @code{lint} embedded in comments, and emit them preceded by @samp{#pragma lint}. For example, the comment @samp{/* NOTREACHED */} becomes @samp{#pragma lint NOTREACHED}. Because of the clash with @samp{-l}, you must use the awkward syntax above. In a future release, this option will be replaced by @samp{-flint} or @samp{-Wlint}; we are not sure which yet. @item -$ @findex -$ Forbid the use of @samp{$} in identifiers. The C standard does not permit this, but it is a common extension. @end table @node Concept Index, Index, Invocation, Top @unnumbered Concept Index @printindex cp @node Index,, Concept Index, Top @unnumbered Index of Directives, Macros and Options @printindex fn @contents @bye | http://opensource.apple.com//source/gcc/gcc-937.2/gcc/cpp.texi | CC-MAIN-2016-36 | refinedweb | 15,320 | 52.6 |
/* * , 1990, 1993 * - *[] = "@(#)inet_addr.c 8.1 (Berkeley) 6/17/93"; static char rcsid[] = "$Id: inet_addr.c,v 1.2 1999/10/14 21:56:45 wsanchez Exp $"; #endif /* LIBC_SCCS and not lint */ #include <sys/param.h> #include <netinet/in.h> #include <arpa/inet.h> #include <ctype.h> #include "portability.h" /* these are compatibility routines, not needed on recent BSD releases */ /* * Ascii internet address interpretation routine. * The value returned is in network order. */ u_long inet_addr(cp) register const char *cp; { struct in_addr val; if (inet_aton(cp, &val)) return (val.s_addr); return (INADDR_NONE); } /* * Check whether "cp" is a valid ascii representation * of an Internet address and convert to a binary address. * Returns 1 if the address is valid, 0 if not. * This replaces inet_addr, the return value from which * cannot distinguish between failure and a local broadcast address. */ int inet_aton(cp, addr) register const char *cp; struct in_addr *addr; { register u_long val; register int base, n; register char c; u_int parts[4]; register u_int *pp = parts; c = *cp; for (;;) { /* * Collect number up to ``.''. * Values are specified as for C: * 0x=hex, 0=octal, isdigit=decimal. */ if (!isdigit(c)) return (0); val = 0; base = 10; if (c == '0') { c = *++cp; if (c == 'x' || c == 'X') base = 16, c = *++cp; else base = 8; } for (;;) { if (isascii(c) && isdigit(c)) { val = (val * base) + (c - '0'); c = *++cp; } else if (base == 16 && isascii(c) && isxdigit(c)) { val = (val << 4) | (c + 10 - (islower(c) ? 'a' : 'A')); c = *++cp; } else break; } if (c == '.') { /* * Internet format: * a.b.c.d * a.b.c (with c treated as 16 bits) * a.b (with b treated as 24 bits) */ if (pp >= parts + 3) return (0); *pp++ = val; c = *++cp; } else break; } /* * Check for trailing characters. */ if (c != '\0' && (!isascii(c) || !isspace(c))) return (0); /* * Concoct the address according to * the number of parts specified. */ n = pp - parts + 1; switch (n) { case 0: return (0); /* initial nondigit */ case 1: /* a -- 32 bits */ break; case 2: /* a.b -- 8.24 bits */ if (val > 0xffffff) return (0); val |= parts[0] << 24; break; case 3: /* a.b.c -- 8.8.16 bits */ if (val > 0xffff) return (0); val |= (parts[0] << 24) | (parts[1] << 16); break; case 4: /* a.b.c.d -- 8.8.8.8 bits */ if (val > 0xff) return (0); val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); break; } if (addr) addr->s_addr = htonl(val); return (1); } | http://opensource.apple.com/source/Libinfo/Libinfo-330.7/dns.subproj/inet_addr.c | CC-MAIN-2013-48 | refinedweb | 395 | 66.33 |
Volume of Box coderinme
Write a program to make use of a parameterized method inside a class. Take the following case: Create a class Box and define a method in this class which will return the volume of the box. Initialize two objects for your class and print out the volumes respectively.
If box is of different sides then it forms a cuboid:
Volume of a cuboid = length × breadth × height
If box is of same sides then it forms a cube:
Volume of a cube = side × side × side
Program:
class Box { private double x,y,z; public Box(double a,double b,double c) { x=a; y=b; z=c; } public double getVolume() { return(x*y*z); } } public class Q25 { public static void main(String[] args) { Box b1=new Box(3,4.4,5.6); Box b2=new Box(2,5.2,2.1); System.out.println("The volume of first box="+b1.getVolume()); System.out.println("The volume of second box="+b2.getVolume()); } } | https://coderinme.com/volume-of-box-coderinme/ | CC-MAIN-2019-09 | refinedweb | 164 | 69.52 |
If you remember the post where we talk about how to connect Spark Streaming and Twitter, we said that the limit for performing analytics was up to your imagination.
In this post we’re going to propose some example that works for illustrating the idea of keeping a state based on the defined stream feed. Speaking plainly, we’ll see how popular is some Twitter topic compared to another one: Android vs IOS.
Stateful
The main idea is to have some S entity which state is fed by V-typed elements that are received and processed for each batch in the stream.
The way that the state is updated for a concrete instant Tn is by applying a user defined function that takes as parameters both the state that was at Tn-1 instant and the value set that provides the batch received at Tn instant:
A more casual notation for a common ‘scalero’ would be
type StateUpdate[S] = (Option[S],Seq[V]) => Option[S]
Why
Option[S]? For a good main reason: initially, when we first start listening on the stram, we don’t have any
S state, so a
(S,Seq[V]) => S function wouldn’t make sense.
And in practice?
Spark’s API for pair DStreams (
PairDStreamFunctions) provides the following method for doing so:
def updateStateByKey[S] (updateFunc: (Seq[V], Option[S]) ⇒ Option[S]) (implicit arg0: ClassTag[S]): DStream[(K, S)]
So for a
DStream which is able to classify the elements by using a function that provides a key (we’ll see an example later on), we’ll be able to apply this method and get an
S state (most of the cases, this state will refer to some aggregation over the values) for each key.
The method is overloaded, so you can specify a different partition apart from
HashPartitioner, indicate a custom partition number or set an initial state (
RDD[(K,S)]. Remember that, otherwise, initially our state for all
K keys will be
None).
The example
Let’s suppose we want to measure how strong is the rivalry between Android and IOS and we want to know which is the top trending topic at Twitter (in this example we won’t distinguish between against and in favour mentions).
Using the same project we proposed for the previous Spark + Twitter example, we’ll change the
Boot.scala file so it looks like more to the following gist contents.
At first place, we have to enable the checkpointing dir and tweet filters that we are interested in:
// Set checkpoint dir ssc.checkpoint("/tmp") // Add filters ... val Android = "android" val IOS = "ios" filter( Android, IOS )
We’ll next group our tweets based on whether these tweets contain the ‘Android’ or ‘IOS’ filter (if the tweet contains both, it will be counted in both sides). The result we get is another
DStream but that contains key-value pairs (filter-tweet):
val groupedTweets = stream.flatMap{content => List(Android, IOS).flatMap(key => if (content.getText.contains(key)) Option(key -> content) else None) }
Once we have grouped the tweets, we create a new
DStream from the previous one by using the function we defined at the beginning of this post
updateStateByKey, so the
S state that we were talking about would be the sum of tweets for each key word:
val aggregatedTweets: DStream[(String,Long)] = groupedTweets.updateStateByKey{ (newTweets, previousState) => val newTweetsAmount = newTweets.size.toLong previousState.fold( Some(newTweetsAmount))(previousSize => Some(previousSize + newTweetsAmount)) }
The only ‘tricky’ part to understand could be the
fold code part, but it’s simple. It actually indicates that, in case of having a previous amount (previous state) we just add the new amount to it. Otherwise, we use the new amount.
Apart from this, we make our snippet work by printing these figures and we start listening at the stream:
// And add actions to perform (like printing the aggregatedTweets) ... aggregatedTweets.foreachRDD{ results => results.foreach{ case (team, amount) => logger.info(s">>> $team : $amount") } } // ... and begin listening listen()
Can you think about another way to make the stream more interesting? Playing with tweets geo-location on a heat map, for example? 😉
Easy peasy! | https://scalerablog.wordpress.com/2016/05/02/spark-streaming-stateful-streams-android-vs-ios/ | CC-MAIN-2018-05 | refinedweb | 684 | 58.72 |
How can I concatenate i + name + letter + i?
for(int i = 0; i < 10; ++i){
//I need a const char* to pass as a parameter to another function
const char* name = "mki";
//The letter is equal to "A" for the first 2, "B" for the second 3,
//"C" for the following 4 ...
const char* final_string = ???
}
std::to_string(i)
to_string is undefined for std
You have an older version of VC++ that does not support the current C++ standard. In that case, you have to do it the old-fashioned way.
#include <sstream> std::ostringstream o; o << "mki" << i << "abc"; std::string s=o.str(); | https://codedump.io/share/YCrTt82wXlmw/1/how-can-i-concatenate-string--int--string-in-c | CC-MAIN-2016-50 | refinedweb | 104 | 80.62 |
I wrote a simple bit array class declared in BitArray.h and defined in BitArray.cpp. I used G++ 2.95.3 20010315 (SuSE) to compile it. When compiled with -DDEBUG a small main function was also compiled, and everything was fine.
However when I use it in programs written in other files, the linker can't find any of the methods, e.g.
[test.cpp]
-------------------------------------
#include "BitArray.h"
#include <stdlib.h>
#include <iostream.h>
int main (int argc, char** argv)
{
BitArray b(1024); // 1024 bit array
// print bit (0 or 1) at index 0
cout << b.bitAt (0) << endl;
// find index of first occurence of bit
// 1 starting at index 0
cout << b.findBit (0, 1) << endl;
return EXIT_SUCCESS;
}
When I compile with the following
g++ -c BitArray.cpp
g++ test.cpp BitArray.o
I get:
/tmp/cc31oTBq.o: In function `main':
/tmp/cc31oTBq.o(.text+0x2f): undefined reference to `BitArray::bitAt(unsigned int) const'
collect2: ld returned 1 exit status
However the exact same code in the main function in BitArray.cpp works.
Can anyone tell me what's going on?!! | http://cboard.cprogramming.com/linux-programming/13867-problem-linking-files-cplusplus-printable-thread.html | CC-MAIN-2016-18 | refinedweb | 183 | 70.6 |
tensorflow::
ops:: Restore
#include <io_ops.h>
Restores a tensor from checkpoint files.
Summary
Reads a tensor stored in one or several files. If there are several files (for instance because a tensor was saved as slices),
file_pattern may contain wildcard symbols (
* and
?) in the filename portion only, not in the directory portion.
If a
file_pattern matches several files,
preferred_shard can be used to hint in which file the requested tensor is likely to be found. This op will first open the file at index
preferred_shard in the list of matching files and try to restore tensors from that file. Only if some tensors or tensor slices are not found in that first file, then the Op opens all the files. Setting
preferred_shard to match the value passed as the
shard input of a matching
Save Op may speed up Restore. This attribute only affects performance, not correctness. The default value -1 means files are processed in order.
See also
RestoreSlice. | https://www.tensorflow.org/versions/r1.5/api_docs/cc/class/tensorflow/ops/restore | CC-MAIN-2018-34 | refinedweb | 160 | 74.9 |
C++ is one of the most popular programming languages worldwide. Like other programming languages, it also provides different ways to create functions to perform different tasks through the code. These functions in C++ are specific to the data type you pass in as arguments. But there might be scenarios when a programmer would need generic programming, and that’s where templates in C++ come into the picture. For instance, a programmer might need to use a sort() function to sort data of different types. Usually, the programmer would have to create and use other functions for each data type. The templates in C++ help overcome this challenge.
What Are Templates in C++?
Templates in C++ act as the foundation of generic programming. It is a simple yet powerful tool that basically acts like a blueprint for creating generic functions or classes. While using a template in C++, you pass a data type as a parameter. Thus, instead of maintaining multiple codes, you have to write one code and give the data type you want to use. C++ templates use two primary keywords, ‘template’ and ‘typename,’ where the ‘typename’ can be replaced with the ‘class’ keyword.
How Do C++ Templates Work?
The templates in C++ are expanded during compile-time. At the very core, they work like macros except for a single significant difference. Unlike macros, the type checking in C++ templates is done before template expansion. This allows the compiled code to have multiple copies of the same class.
What Are Function Templates in C++?
You use C++ function templates for creating functions that can be used with different data types. A function template is used to perform the same function on multiple data types. An alternative approach to this is using function overloading. However, using a function template is the better approach to writing less and more maintainable code. The basic syntax of a function template is:
template <class type> ret-type func-name(parameter_list) {
// body of function
}
In the syntax mentioned above, type is just a placeholder that the compiler will automatically replace with the actual data type. The keyword class in the syntax is used to specify a generic type and be replaced by a typename.
Example: Declaring a Function Template in C++
In the below example, you must create a function template in C++ and use it to find the larger value for different data types.
#include <iostream>
using namespace std;
template <class Ttype>
Ttype MaxVal(Ttype i, Ttype j){
return (i > j)? i: j;
}
int main(){
cout << MaxVal<int>(5, 8) << endl; // Call myMax for int
cout << MaxVal<double>(6.5, 4.0) << endl; // call myMax for double
cout << MaxVal<char>('f', 'k') << endl; // call myMax for char
return 0;
}
Output
What Are Class Templates in C++?
The class templates in C++ make the class using it generic. It operates similarly to function templates except that it is used on the entire class instead of a single function. The basic syntax of declaring a class template is:
template<class type>
class class_name
{
.
.
}
Once the class is created, you can declare the data type while declaring the class instance.
Example: Declaring a Class Template in C++
#include <iostream>
using namespace std;
template <class Ttype>
class Array{
private:
Ttype *pointr;
int size;
public:
Array(Ttype arr[], int s);
void print();
};
template <class Ttype>
Array<Ttype>::Array(Ttype arr[], int s) {
pointr = new Ttype[s];
size = s;
for(int i = 0; i < size; i++)
pointr[i] = arr[i];
}
template <class Ttype>
void Array<Ttype>::print() {
for (int i = 0; i < size; i++)
cout<<" "<<*(pointr + i);
cout<<endl;
}
int main(){
int arr[5] = {1, 2, 3, 4, 5};
Array<int> a(arr, 5);
a.print();
return 0;
}
Output
Passing Multiple Arguments to Templates in C++
Similar to normal functions and classes, you can pass multiple data types as arguments to templates. Now, look at an example that takes multiple arguments.
#include<iostream>
using namespace std;
template<class Ttype, class Utype>
class A{
Ttype x;
Utype y;
public:
A(){ cout<<"The Constructor is Called"<<endl; }
};
int main() {
A<char, char> a;
A<int, double> b;
return 0;
}
Output
How to Specify Default Arguments for Templates in C++?
Similar to normal parameters, you can specify default arguments for templates. Here’s an example to demonstrate specifying a default argument for templates in C++.
#include<iostream>
using namespace std;
template<typename Ttype, typename Utype = char>
class Example{
public:
Ttype i;
Utype j;
Example() { cout<<"The Constructor is Called"<<endl; }
};
int main() {
Example<char> a;
return 0;
}
Output
What Is the Difference Between Function Overloading and Templates in C++?
Like function overloading, templates in C++ also allow polymorphism. However, there is a fundamental difference between the two. You use the function overloading when you want to perform similar operations. On the other hand, templates in C++ are used to perform precisely identical operations on different data types.
What Is Template Specialization?
Template specialization in C++ is to declare different codes or behavior for a specific data type. This means you can create a specialized version of a function when executed with a particular data type. The code depicted below demonstrates the use of template specialization in C++.
#include <iostream>
using namespace std;
template <typename Ttype>
void Example(Ttype t)
{
cout << "The standard example template: "
<< t << endl;
}
template<>
void Example(int t)
{
cout << "Specialized example template for int: "
<< t << endl;
}
int main()
{
Example<char>('x');
Example<int>(12);
Example<float>(15.30);
}
Output
As you can see in the output, the template is executed similarly for char and float data types but differently for the int data type.
Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!
Conclusion
In this article, you have learned everything about templates in C++. You also looked into examples for both types of templates: function and class. You created your templates and used them to execute them with different data types.
You can use the templates in C++ to achieve a special kind of polymorphism. If you are new to C++ programming and interested in learning about other fundamental concepts of C++, you can refer to our C++ Tutorial for Beginners. The tutorial is specifically designed for beginners and contains guides for various basic concepts. To put it simply, the tutorial is well adept at helping you excel in the field of C++ programming. Enroll in Simplilearn’s Full Stack Web Development Program to learn modern coding techniques with bootcamp-level intensity.
Have any questions for us? Leave them in the comments section of this write-up, and our experts will get back to you on the same, as soon as possible. | https://www.simplilearn.com/tutorials/cpp-tutorial/templates-in-cpp | CC-MAIN-2021-49 | refinedweb | 1,115 | 53.81 |
Hi all,
Today I installed jdk1.8.0_20 on my computer and typed a simple example code in MyEclipse 6.0 IDE, the code listed below:
import java.util.List;
public class Test5
{
public static void main(String[] args)
{
List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
features.forEach(n -> System.out.println(n));
}
}
the MyEclipse Editor shows some errors like "Arrays can not be resolved" and "n can not be resolved".
I did use jdk 8 in the build path, but it seems like the jdk 8 did not function properly.
I don't know what's the problem. Any idea? pls help.
yhqian99 | http://www.javaprogrammingforums.com/collections-generics/39122-iterating-over-collections-java-8-a.html | CC-MAIN-2017-39 | refinedweb | 111 | 76.32 |
CodePlexProject Hosting for Open Source Software
hi guys,
I am planning to use web api on my next project. honestly, I haven't tried it yet so I am asking this question without knowing the web api system in details. I only watched couple of talks which glenn block did at mix and devdays.
We, as company, will open our product data and don't waht anybody to consume our data. So we are planning to create API key system. Structure of the system is not a problem but how can we intercept the request so that we can verify that it is legit? if it
is legit, continue to work. if it is not throw an exception (but which exception, I don't know:s should I use faults here)
can our urls look like following;
actually rob jacobs has written a great blog post on this;
and also there is a project template up on the vs gallery;
I am just wondering if this thing fits in the structure of web api? (also, I am not sure, if I should use web api on my project. we will only open our data in xml and json format as I indicated an exmaple url that I would like to create)
thanks in advance.
I am actually doing something similar, this is only some prototype code, but it seems to serve our needs.
Here is the DelegatingChannel that validates an API Key. It is the first thing that runs on every request, and returns a 401 Unauthorized if the ApiKey isn't present/valid.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
namespace WebAPIWebApp {
public class ApiKeyVerificationChannel : DelegatingChannel {
public ApiKeyVerificationChannel(HttpMessageChannel innerChannel)
: base(innerChannel) {
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
if(request.RequestUri.AbsolutePath.IndexOf("favicon.ico") >= 0)
return Task.Factory.StartNew(() => {
return new HttpResponseMessage(System.Net.HttpStatusCode.NotFound, "Not Found");
});
if (request.RequestUri.Segments.Length == 1 && string.IsNullOrWhiteSpace(request.RequestUri.AbsolutePath.Replace("/", ""))) {
return base.SendAsync(request, cancellationToken);
}
var apiKey = ApiKeyManager.GetKey(request);
if(apiKey == null)
return Task.Factory.StartNew(() => {
return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized, "Invalid API Key");
});
return base.SendAsync(request, cancellationToken);
}
}
}
Then I've got some custom logic in the ApiKeyManager.GetKey method that checks for a valid key in the QueryString, Custom Header, or Authorization header.
I add it in the Global.asax file like this:
var config = (HttpHostConfiguration)HttpHostConfiguration.Create();
// Make my NewtonsoftJsonFormatter the first one so that it gets called before built in JsonFormatter
config.OperationHandlerFactory.Formatters.Insert(0, new NewtonsoftJsonFormatter());
config.OperationHandlerFactory.Formatters.Add(new JsonPFormatter());
config.AddMessageHandlers(typeof(UriFormatExtensionMessageChannel), typeof(LoggingChannel), typeof(ApiKeyVerificationChannel));
Only thing I did run across was the inability to "pass the Api Key along" with the request. So I use the ApiKeyManager.GetKey() method to get the key again in each WebInvoke method.
Again, I've only been working with the Web Api for a couple days some I might be going about it wrong, but seems to work for us.
Out of curiousity, if the API key is passed using JavaScript, how would you prevent somebody from doing a "View Source" to see what the API key is and then spoofing whatever site was assigned that key?
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://wcf.codeplex.com/discussions/257491 | CC-MAIN-2017-09 | refinedweb | 588 | 51.65 |
Do You Ever Want To Know What Is Really A Functional Programming Is?
Functional programming is a very funny paradigm. On the one hand, everyone knows about it, and everyone likes to use all sorts of pattern matching and lambdas, on the other hand, few people usually write in a pure FP language. Therefore, the understanding that this is going back more to myths and urban legends, which are very far from the truth, and people have the opinion that “FP is suitable for all fractal calculation programs isolated from life, but for real problems, there is a proven track record OOP time-tested in battle.”
Although people usually recognize the convenience of FP features, it’s much nicer to write:
int Factorial(int n) { Log.Info($"Computing factorial of {n}"); return Enumerable.Range(1, n).Aggregate((x, y) => x * y); }
Than terrible imperative programs like so:
int Factorial(int n) { int result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; }
Why? On the one hand, yes. On the other hand, it is the second program, in contrast to the first, that is functional.
- How so, isn’t it the other way around? A beautiful fluent interface, data transformation, and lambda is functional, and the dirty cycles that mutate local variables are a legacy of the past? So, it turns out that no.
So why is this so? The fact is that, according to the generally accepted definition, a program is considered to be written in a functional style when it consists only of pure functions. So we write:
- A functional program is a program consisting of pure functions.
- Ok, we knew that but what is a pure function? A pure function is a function whose call result is referentially transparent. Or, if formally:
The function f is pure if the expression f (x) is referentially transparent for all referentially transparent x.
And here the differences begin with what people usually represent as a “pure function”. Isn’t a pure function a state that does not mutate? Or is it not getting into global variables? And what is this “link transparency” like that? In fact, there really is a correlation with these things, but the very essence of purity is not to mutate anything, but this very transparency.
So what is it?
Reference transparency is a property in which replacing an expression with the calculated result of this expression does not change the desired properties of the program
This means that if we have somewhere written var x = foo () then we can always replace it with var x = result_of_foo and the behavior of the program will not change. This is precisely the main requirement for cleanliness. FP does not impose any other requirements (like immutability). The only point here is philosophical, which is considered “program behavior”. It can be defined intuitively as properties that are critically important for us to observe. For example, if the code execution generates a little more or a little less heat on the CPU, then we probably don’t care (although if not, we can work with it in a special way). But if our program stopped going to the database and cached one old value, then this really worries us!
Let’s get back to our examples. Let’s check if our rule is satisfied with the first function? It turns out that no, because if we replace Factorial (5) somewhere with 120, then the behavior of the program will change – the information that was previously written will not be written to the logs (although if we go from the position “yes, and to hell with them, with logs” and if we don’t consider this the desired behavior, the program can be considered clean, but we probably didn’t just write that line in the function, and we would like to see the logs, so we consider this point of view unlikely).
- What about the second option? In the second case, everything remains as it was: you can replace all occurrences with the result of the function and nothing will change.
It is important to note that this property should work in the opposite direction, that is, we should be able to change all var x = result_of_foo to var x = foo () without changing the behavior of the program. This is called “Equational reasoning,” that is, “Reasoning in terms of equivalence.” Within the framework of this paradigm, what functions, what values are the same thing, and you can change one to the other is completely painless.
This is an important consequence: the program does not have to work with immutable data in order to be considered functional. It is enough that these changes are not visible to an outside observer. To do this, they even came up with a special mechanism called ST, which at the level of types helps you prevent accidentally mutable leaking out. A typical example is writing a quick-sorting insert and forgot to copy the input array: ST helps turn this into a compilation error. Immutability is an important convenient property, but no one forces you to use it only, if necessary, you can mutate into a tail and mane, the main thing is not to violate link transparency.
Why is it necessary
Probably the most important question. Why be so tormented? Copy data instead of changing directly, wrapping objects in these STs of yours so that the changes (if any) do not leak out, and that’s all… The answer is for a better composition. At one time, goto was very disliked precisely because it was very difficult to understand with it how the program actually behaves and what the data and control flow really is, and it was difficult to reuse a function written with goto because then he knew how even in the middle of the function body jump without any problems.
With Equational reasoning, it’s always easy to understand what is happening: you can replace the result with a function and that’s it. You do not need to think in what order the functions are calculated, you do not have to worry about how it will lead if you change a couple of lines in places, the program simply passes the results of some functions to others.
As an example of why this is good, I can cite an incident from my life that happened just a couple of months ago. I wrote the most typical OOP code in C#, and I needed to get into the old piece where such code was written (the example is simplified)
var something = function(); DoStuff(this.Field, something);
And I needed to refactor them a bit during the task, which I did:
DoStuff(this.Field, function());
The changes passed the tests successfully, the changes passed the review code was frozen, after which strange falls began on the test bench. After a couple of hours of debugging, it turned out that something like this was done in the gut function:
... что-то считаем this.Field = GetUpdatedVersion(this.Field, localData) // opps ... продолжаем считать и возвращаем результат
Accordingly, if earlier from the point of view of the compiler it looked like this:
var something = function(); var arg1 = this.Field; // after calling function - a new value! var arg2 = something; DoStuff(arg1, arg2);
Then after refactoring the following
var arg1 = this.Field; // before calling function - the old value remains! var arg2 = function(); DoStuff(arg1, arg2);
Accordingly, if earlier the DoStuff function was called with the updated version of the field, then after refactoring it started to be called from the old one.
What morality can be endured here? “Nefig write functions that mutate and return data?” I agree and note that link transparency is the next logical step in this direction. In a functional program, interchanging any two independent lines will never lead to a change in the semantics of the program.
- In general, AF is aimed at making it possible to judge the behavior of a function by observing only one of them. If you, like me, write in some C # in the usual imperative style, you also need to understand how your DI works, what function or DoStuff specifically does, whether it is safe to call this function from different threads or not. In FP, you look at one function, look at its data, and this information is enough for you to fully understand how it works.
That is, this style is aimed at a more convenient separation of program parts from each other. This greatly simplifies the understanding of the code for people who have not written it. By tradition, I note that you can be this someone in six months. The larger the project, the stronger the effect. As far as I saw, in fairly large projects with hundreds of thousands of lines, people themselves ultimately reinvent the same principles, despite the fact that the language and platform usually abut quite strongly. Because it is simply impossible to debug large programs when everything interacts with everything. The purity of a function, when its call simply returns the result, and does not write boring stories and does not send emails to mail, helps a lot in this. Any developer of a large project will tell you that well-defined contracts and small stateless modules are the easiest and most convenient to work with. A functional approach merely develops this idea to a logical point – all functions must be clean and not dependent on any state.
How are these principles reflected in the code?
As a comparison, I can offer you such an example, which I took from the Scala Red Book (an absolutely gorgeous book, very intelligibly and interestingly talks about FP, with cool tasks). However, for clarity, I adapted the text and code to C#.
Suppose we have a coffee shop and we want people to order coffee. Nothing more is needed, a very simple requirement.
OOP option
Ok, as we were told, we write:
public class Cafe { public Coffee BuyCoffee(CreditCard card) { var cup = new Coffee() card.Charge(cup.Price) return cup } }
The line card. Charge (cup.Price) is an example of a side effect. Payment by credit card involves some interaction with the outside world – for example, for this you may need to contact the credit card issuing company through any web service, authorize the transaction and all that. It is called a side effect because all these actions are not related to creating a Coffee instance, that is, they are, as it were, on the side of the main result of the “return a cup of coffee” function.
As a result, the code is difficult to test due to a side effect. Any experienced OOP developer will say, “Yes, you make an interface to write off money!”. A reasonable requirement, we will do so:
public class Cafe { public Coffee BuyCoffee(CreditCard card, IPaymentProvider paymentProvider) { var cup = new Coffee() paymentProvider.Charge(card, cup.Price) return cup } }
Despite the side effects, we now have the opportunity to test the purchase process: it’s enough to test the IPaymentProvider interface in the tests. But there are drawbacks.
- First of all, we had to introduce IPaymentProvider, although if it weren’t for the tests, one specific implementation would suit us perfectly.
- Secondly, it can be inconvenient to use a mok implementing the necessary functionality. A typical example is InMemory DB, where we wipe the Insert / Save /… methods, and then we get the internal state (usually in the form of lists) and see that everything is saved where necessary. Is it necessary to say that inspecting the internal state of objects is not good? And yes, you can certainly use some kind of framework that will do most of the work for us, but not all, and drag the whole framework just to test that we can buy a cup of coffee that looks like overkill.
- Well, and thirdly, there are problems with reusing this function. Suppose we want to buy N cups of coffee. In the current interfaces, we have no easy way to do this except to write a completely new function (unless of course, we want to push our payment gateway with the same type of request):
public class cafe { public Coffee BuyCoffee (CreditCard card, IPaymentProvider paymentProvider) { var cup = new Coffee () paymentProvider.Charge (card, cup.Price) return cup } public Coffee [] BuyCoffees (int count, CreditCard card, IPaymentProvider paymentProvider) { // we now also need to handle the case of 0 cups, // so as not to accidentally set a check for 0 rubles if (count == 0) return Array.Empty <Coffee> (); var cups = Enumerable.Range (0, count) .Select (_ => new Coffee ()). ToArray (); paymentProvider.Charge (card, cups [0] .Price * count) return cups } }
Even for such a simple case, we had to copy-paste the code. And if in this case, it is not very important, then in the case of complex, weighty logic, it can be much more painful.
FP option
How do we write code so that we don’t encounter these problems? A functional approach – instead of actually debiting funds, simply invoice and let the calling code decide for itself what to do with these. Then our function will look like:
public class Cafe { public (Coffee, Charge) BuyCoffee(CreditCard card) { var cup = new Coffee() return (cup, new Charge(card, cup.Price)) } }
Yes, that’s so simple. Now the calling code, if it is a real application, can make a transaction and write off money. But if this is a test, then it just can check the returned Charge object for all its properties. No more mods needed: we separated the invoicing events and the interpretation of this invoice. A charge is a simple DTO that stores which card you need to charge. It is easy to see that our function has become pure. It simply returns a tuple of two objects, which are a simple description of the data. We can replace the call of this function with the result, and the meaning of the program will not change. And we at this level no longer need any payment provider, cheers!
What about buying N cups of coffee? Due to the fact that we got rid of the effects, we do not need to be afraid that N calls of BuyCoffee will spam our payment gateway, so we just reuse it.
public class Cafe { public (Coffee, Charge) BuyCoffee(CreditCard card) { var cup = new Coffee() return (cup, new Charge(card, cup.Price)) } public (Coffee[], Charge) BuyCoffees(int count, CreditCard card) { var (coffees, charges) = Enumerable.Range(0, count) .Select(_ => BuyCoffee(card)) .Unzip(); return (coffees, charges.Aggregate((c1, c2) => c1.Сombine(c2)) } }
Well, we show the Combine helper function:
public class Charge { public CreditCard Card { get; set; } public double Amount { get; set; } public Charge(CreditCard card, double amount) { Card = card; Amount = amount; } public Charge Combine(Charge other) { if (Card != other.Card) throw new ArgumentException("Can't combine charges to different cards"); return new Charge(Card, Amount + other.Amount); } }
Moreover, this helper function allows us to do many other cool things. For example, now we are able to minimize the number of interactions with a payment gateway by combining cards by customer:
IEnumerable<Charge> Coalesce(IEnumerable<Charge> charges) => charges.GroupBy(x => x.Card).Select(g => g.Aggregate((c1, c2) => c1.Combine(c2))
This is just a shortlist of the benefits that cleanliness provides. And yes, note that the language is used the same, both there and there, all the difference is only in the approach.
I predict that they may object to me that the problem has not been solved, and now the code above should do this decommissioning, only now the logic is a little blurred, and we just simplified the tests of our Cafe class a little bit. In fact, this is not so, because the code above can also convey the decision of what to do next, and that code is even further, and so on to a service that will actually do something with this data (but there it can be made tested without Mokov, more about this in another article).
- The second objection may be that in the OOP version we could configure IPaymentProvider to deal with transactions, but there are also difficulties: you need to configure timeouts, select values so that the batching is effective and the latency of the operation does not increase much, plus you will still be afraid of “bad” implementations that will not be engaged in batch, and so on. In general, whatever one may say, this approach is significantly worse.
The separation of task execution into creating a descriptor of this task and interpretation seems to be a very insignificant shift from empty to empty, but this is a very important thing that can hardly be overestimated. Delaying the decision “what should we do with this data” opens up a lot of room for action, and makes many things like canceling or retrying a lot more trivial. The concept, in my opinion, is similar in power to RAII: one simple rule and a lot of far-reaching good consequences.
Is that all?
From the point of view of the very essence of AF – yes, that’s it. Lack of effects is the only requirement that must be observed for the program to be functional. But historically, FP languages have more extensive restrictions, and they usually come up with restrictions for a reason, but in order to get benefits from this. The restriction on the types of variables (it is impossible to put a string in an int variable) allows you to write more reliable programs, the restrictions on changing the control flow (for example, the goto prohibition) lead to a simplification of the understanding of programs, the restriction on templating (Templates vs Generics) makes it easier to write generalized code and have better error messages, and so on.
One of the coolest advantages of common FP languages, in my opinion, is the value of function and type signatures. The fact is that, unlike “dirty” functions, a pure signature usually gives so much information that the number of possible options for its implementation is reduced to miserable units, and in extreme cases the compiler can generate the body of the function according to its signature. Why does this not work in imperative programs? Because there void UpdateOrders () and void UpdateUsers () have the same signature () -> (), but a completely different value. In the FP, they will be of type () -> OrdersUpdate and () -> UsersUpdate. Precisely because functions are only allowed to calculate the value (and not to make arbitrary game), we can confidently judge many of its properties by simply looking at the signature.
What does this give us? Well, for example, suppose we have such a function (Rust example)
// accept an array of objects, some other object, and return a value of the same type fn foo <T> (a: & [T], b: T) -> T {... some kind of body ...}
I do not know what is inside this function, but by the signature, I see that the result will be one of the elements of the array, or in the case of an empty array – the element b that I passed. How do I know that? From there, the function does not make any assumptions about the type T. Therefore, it cannot create an instance on its own. Therefore, the only way to get a value of the same type is to take one of the objects that we passed to it.
Accordingly, I can write such a test
let a = [1,2,3,4,5]; let b = foo(a, 10); assert!(b == 10 || a.iter().any(|x| x == b))
This test will be performed for any implementation of this function unless it calls UB and returns at least some value (does not panic and does not go into perpetual cycles). But we can safely assume that she does not do this, because it is unlikely that someone in their right mind would write a function that for some reason takes an array of any objects, but always panics (I remind you that we don’t know anything about the transferred objects, so panic only in some cases the function cannot).
Now let’s remove the second parameter and see what happens:
fn foo<T>(a: &[T]) -> T { ...какое-то тело... }
Please note that for an empty array, this function will throw an exception, panic, go into the eternal cycle or do something else bad. Or, formally speaking, it returns the Bottom type ⊥. How do I know that? And because the function was obligated to return the value of T, and we did not pass one to it. That is, its contract cannot be observed for any value of argument a. Thus, the function is partially recursive, and therefore not defined for empty arrays. And on vague arguments, functions usually panic.
In general, looking at this signature it is immediately clear that we should check the array beforehand for emptiness before calling such a function.
Why did I take for example Rust and not the same sycharp? And because his type of system is not powerful enough to guarantee this behavior. An example of a function that fails the test:
T Foo<T>(List<T> list, T value) => default(T);
I would like to rely on the type system in the sisharpa, but I can’t. You need to go watch the implementation of the function. And as soon as we went to see the implementation, we lost the main advantage that programming in high-level languages gives us – the ability to encapsulate complexity and hide it behind a beautiful interface. The less information we need to understand how this or that code works, the easier and easier it is to make changes, and the more reliable the software is.
Do you know what the function will look like in the raster, which if the array is empty will return the default value of T? Like this:
fn foo<T: Default>(a: &[T]) -> T { ...какое-то тело... }
It can still fall with panic on an empty array, but given that the author clearly requested the possibility of creating a default value of this type, it is reasonable to assume that this is what happens in the body. In the end, this is superfluous writing, so if the author wrote it, then somehow it most likely uses it. And the only reasonable use of such an argument is to return the default value when the array is empty. And we immediately see this requirement in the signature. Just excellent after all! Let me remind you that in the sharp you need to go to the function body and see the default (T) call there.
- In the functional paradigm, in 99% of cases, you just need to look at the signature of the functions to understand how it works. It may seem implausible boasting, but it is. Haskell community brought this idea to the absolute and created a Google search engine that allows you to search for functions in libraries by its signature. And it works great.
For example (a -> Bool) -> [a] -> [a] (a function that takes two arguments: a predicate and a list, returns a list of the same elements as the result) in the expected way finds the filter and takeWhile functions.
To fix, I propose a small riddle. Think about what this function is? It takes a string and returns absolutely any type.
fn bar <T> (s: String) -> T {...} // raster version bar :: String -> a // Haskell option
Answer:
If you think about it, then we have no way to make an object about the type of which we do not know anything. Because the only thing this function can do is never return the result. That is, to return the eternal cycle or panic known to us ⊥. But remember that the function also takes a string variable. There is no sense in transmitting it for a cycle, so you can be almost sure that this function is engaged in throwing panic:
fn bar<T>(s: String) -> T { panic!(s); }
If you thought about reflection and creating a type in runtime, this is basically a possible outcome (although it is still not in the rasta and in the Haskell), but then it is not clear why the string parameter is needed. Although if you really try, you can imagine such a function. So in principle, if this is your option, then feel free to add yourself a point, this is also a possible option for languages that allow this.
The skill to think of what a function does by signature is very helpful because you do not need to go into the body of functions to understand what it can do and what not. Even if the function foo from the example above takes 1000 lines, it is still obliged to return either one of the elements of the passed array or the second argument. There are no other options. And you do not need to read 1000 lines to understand this. You just know this by looking at the signature of the function.
Can a purely functional language do something useful?
This question has worried me since I knew about functional languages. “Damn,” I thought, “But I need to go to the database, make an HTTP request, write to the console in the end. But the pure language does not allow this. It’s probably suitable only for factorials.”
As it turned out, the FP language itself really can’t do all this, But here smart guys took it and figured out how to get around it. They said, “Okay, the program cannot do dirty actions. But, what if we separate the creation of the computation descriptor and its interpretation (just like in our cafe example)? And then it turns out that the whole program is clean, and the runtime that runs is unclean all the dirty work! “
- What does it look like? Well, take for example the type of IO responsible for interacting with the outside world. This is the same type as our Charge from the example above, but instead of writing off the card, it describes input/output. IO itself does nothing if we write print “Hello world” nothing happens in the Haskell. But if we write main = print “Hello world” then the text will magically appear on the screen. How does this happen?
And the thing is that the Haskell runtime is engaged in the interpretation of this IO. That is, all the described actions occur outside the main function. That is, from our entire program we are assembling a giant state machine, which the runtime then begins to interpret. And this runtime is allowed to do “dirty” things – go to the database, print on the screen, and do whatever. But in terms of code, we never do anything.
If we want to go to the base in the Haskell, then we create the Go to VBase object, which by itself does nothing. But when the interpreter executing the main function encounters this value, it will physically go to the base.
If you use the analogy, then the Haskell program is an algorithm written on a piece of paper, and runtime is a robot that executes this algorithm. By itself, the leaflet does nothing and simply lies inactive. From the point of view of the algorithm, we cannot do anything, we can only make another leaflet with a different set of commands. And until the robot comes to interpret our notes, the leaflet remains completely inactive.
I guess I just confused you with this analogy, so let’s show an example. Here is a Rust program:
fn main() { let _ = print!("Hello "); println!("world!"); }
And she displays “Hello world!” Now let’s try to write a similar program in Haskell:
main :: IO () main = do let _ = print "Hello " print "world!"
And she displays “world!”. In fact, the difference between the behavior of these programs is the quintessence of the difference between a clean and an unclean program. In the case of Haskell, we created a “deduce Hello” descriptor but did not use it in any way. This descriptor was not interpreted and no inscription appeared on the screen. As a result of main, we returned the only descriptor with the world ! which was executed. On the other hand, in the case of a program in Rust, the call to print! in itself is an action, and we can’t cancel it or transform it in any other way.
It is the ability to work with effects as values (to throw out the fact that we wanted to display something) make life very simple and makes bugs impossible like what I showed in the first section. And when they talk about “Effects Control in FP” they mean exactly that. Looking ahead, you can describe the effects of functions in the style of “this function writes to the database (and only to that table), uses HTTP (but only through this proxy, and to this site), can write logs and read configs. And that’s it this will be checked during the build, and if you try to go to the wrong site or read the config without annotating such a possibility in the signature, it will lead to a compile-time error.
Conclusion
As you can see, all the opposition of OOP and FI is completely artificial. You can write in that and in a different style in the same language, and in principle even combine. The whole question is whether the language encourages writing in this style or vice versa. For example, writing object-oriented in ANSI C is possible, but very painful. But in Java it’s easy. Writing Java in a purely functional style, on the other hand, is tough, but using Scala or Haskell is easy. Therefore, the question is rather that there are two tools, one is common and supported by many languages, the other is more interested in a whole range of properties, but it is not supported everywhere. Well, then your choice as a developer is which tool suits you best according to the situation.
- Personally, I see for myself a lot of advantages in the functional paradigm in terms of code support. I am very tired of the fact that the rearrangement of two disconnected lines in some places can break something in a completely third place. I’m tired of configuring Moki and DI. I don’t want to catch errors in the runtime “The method was not locked” / “The type was not registered” / “…”, in the end, I did not choose a statically typed language for that.
Of course, FI is not a silver bullet, it has its own limitations, and it also has room to grow. But in my opinion, it is much more interesting than the current approaches. The “chips” of FP languages like lambdas, pattern matches, ADTs and other things have not been surprising in the mainstream languages for a long time. But this is all husk, and it becomes a really powerful tool only in conjunction with the most important idea of FP – the idea of link transparency. | https://www.smartspate.com/do-you-ever-want-to-know-what-is-really-a-functional-programming-is/ | CC-MAIN-2020-29 | refinedweb | 5,188 | 69.21 |
Task
- Package
- purescript-task
- Repository
- ursi/purescript-task
#Task Source
newtype Task x a
A
Task x a represents an asynchronous computation that can either succeed with a value of type
a, or fail with a value of type
x.
If you're coming from Elm and it seems like a lot of the functions are missing, that's because their equivalents are hiding in the type class instances. They have been annotated below.
Instances
Functor (Task x)
Apply (Task x)
Task.mapN->
liftN
Applicative (Task x)
Task.succeed->
pure
Task.sequence-> For this, we use the
sequencefunction that is a member of the Traversable type class. Note: we are not using a
Traversableinstance of
Task, we're using the
Traversableinstance of whatever we want to sequence over. So while Elm's
Task.sequenceonly works over
Lists, we can sequence over anything that has a
Traversableinstance.
Bind (Task x)
Task.andThen->
bind(the only difference is the order of the arguments)
Monad (Task x)
Alt (Task x)
(Semigroup a) => Semigroup (Task x a)
(Monoid a) => Monoid (Task x a)
Bifunctor Task
Task.mapError:
lmap, which isn't a member of
Bifunctordirectly, but uses the
Bifunctorinstance.
MonadEffect (Task x)
MonadThrow x (Task x)
Task.fail->
throwError
MonadError x (Task x)
Parallel (ParTask x) (Task x)
#capture Source
#Canceler Source
#makeTask Source
makeTask :: forall a x. (Callback a -> Callback x -> Effect Canceler) -> Task x a
To use
makeTask, you need to create a function that takes a callback for both success and failure, and returns an effect that will cancel a task in the event of an error during parallel execution. If you do not need or do not care about cancelling a task, you can use
pure $ pure unit.
Here is how you would make a simple waiting task using js-timers:
wait :: ∀ x. Int -> Task x Unit wait ms = makeTask \aC _ -> do id <- setTimeout ms $ aC unit pure $ clearTimeout id
#liftEither Source
liftEither :: forall a x. Either x a -> Task x a
#ForeignCallback Source
type ForeignCallback a = EffectFn1 a Unit
#fromForeign Source
fromForeign :: forall x a. (ForeignCallback a -> ForeignCallback x -> Effect Canceler) -> Task x a
A convenience function for creating tasks from JavaScript functions that take callbacks.
// JavaScript exports.waitImpl = ms => cb => () => { const id = setTimeout(cb, ms); return () => clearTimeout(id); }; -- PureScript foreign import waitImpl :: Int -> ForeignCallback Unit -> Effect Canceler wait :: ∀ x. Int -> Task x Unit wait ms = fromForeign \cb _ -> waitImpl ms cb
#Promise Source
#fromPromise Source
fromPromise :: forall x a. Effect (Promise x a) -> Task x a
A convenience function for creating tasks from JavaScript promises.
fetch :: String -> Task Error Json fetch = fromPromise <<< fetchImpl
#toPromise Source
#ParTask Source
newtype ParTask x a
ParTask is the applicative that lets you run tasks in parallel via the parallel library.
You may not need to work with any
ParTask values directly. One of the most useful functions parSequence, which can take an array of
Task x a and executes them all in parallel, returning a
Task x (Array a).
If tasks are executing in parallel via
ParTask's
Apply instance (as is the case with
parSequence), when one of them fails, the cancelers are called for all the task that are currently running.
Instances
Re-exports from Control.
Monad.
Error. Class
#throwError Source
throwError :: forall e m a. MonadThrow e m => e -> m a
Re-exports from Data.
Bifunctor
- Modules
- Task
- Task.
Class
- Task.
Common
Task.map->
map | https://pursuit.purescript.org/packages/purescript-task/0.3.1/docs/Task | CC-MAIN-2021-21 | refinedweb | 567 | 62.68 |
- NAME
- DESCRIPTION
- About the new versioning system
- Incompatible Changes
- Core Changes
- Threads
- Compiler
- Regular Expressions
- Improved malloc()
- Quicksort is internally implemented
- Reliable signals
- Reliable stack pointers
- Behavior of local() on composites is well-defined
- %! is transparently tied to the Errno module
- Pseudo-hashes are supported
- EXPR foreach EXPR is supported
- Slice notation on glob elements is supported
- Keywords can be globally overridden
- $^E is meaningful on Win32
- foreach (1..1000000) optimized
- Foo:: can be used as implicitly quoted package name
- exists $Foo::{Bar::} tests existence of a package
- Better locale support
- Experimental support for 64-bit platforms
- prototype() returns useful results on builtins
- Re-blessing in DESTROY() supported for chaining DESTROY() methods
- All printf format conversions are handled internally
- New INIT keyword
- New lock keyword
- Tied arrays are now fully supported
- Tied handles support is better
- Supported Platforms
- Modules and Pragmata
- Utility Changes
- API Changes
- Documentation Changes
- New Diagnostics
- Obsolete Diagnostics
- BUGS
- SEE ALSO
- HISTORY
NAME
perldelta - what's new for perl5.005
DESCRIPTION
This document describes differences between the 5.004 release and this one.
[XXX this needs more verbose summaries of the sub topics, instead of just the "See foo." Scheduled for a second iteration. GSAR]
About the new versioning system
Incompatible Changes.
Default installation structure has changed
The new Configure defaults are designed to allow a smooth upgrade from 5.004 to 5.005, but you should read INSTALL for a detailed discussion of the changes in order to adapt them to your system.
Perl Source Compatibility
When none of the experimental features are enabled, there should be no user-visible Perl source compatibility issue.
If threads are enabled, then some caveats apply.
@_ and
$_ become lexical variables. The effect of this should be largely transparent to the user, but there are some boundary conditions under which user will need to be aware of the issues. [XXX Add e.g. here.]
C Source Compatibility
- Core sources now require ANSI C compiler
-
- Enabling threads has source compatibility issues
-
Binary Compatibility
This version is NOT binary compatible with older versions. All extensions will need to be recompiled..
Relaxed new mandatory warnings introduced in 5.004
Many new warnings that were introduced in 5.004 have either been made optional. Some of these warnings are still present, but perl's new features make them less often a problem. See "New Diagnostics".
Licensing
Perl has a new Social Contract for contributors.
Perl's documentation license has changed.
Core Changes
Threads
WARNING: Threading is considered an experimental feature. Details of the implementation may change without notice. There are known limitations and bugs.
See README.threads.
Compiler
WARNING: The Compiler and related tools are considered experimental. Features may change without notice, and there are known limitations and bugs.
B::Lint is an experimental module to detect and warn about suspicious code, especially the cases that the -w switch does not detect.
B::Deparse can be used to demystify perl code.
See
ext/B/README.
Regular Expressions
Improved malloc()
See banner at the beginning of
malloc.c for details.
Quicksort is internally implemented
See
perlfunc/sort.
Reliable signals
Via Thread::Signal.
Via switched runtime op loop.
Reliable stack pointers
The internals now reallocate the perl stack only at predicatable times. In particular, magic calls never trigger reallocations of the stack, because all reentrancy of the runtime is handled using a "stack of stacks". This should improve reliability of cached stack pointers in XSUBs.
Behavior of local() on composites is well-defined
See "local" in perlfunc.
%! is transparently tied to the Errno module
Pseudo-hashes are supported
EXPR foreach EXPR is supported
Slice notation on glob elements is supported
[XXX See what?]
Keywords can be globally overridden
$^E is meaningful on Win32
foreach (1..1000000) optimized
foreach (1..1000000) is now optimized into a counting loop. It does not try to allocate a 1000000-size list anymore.
Foo:: can be used as implicitly quoted package name
[XXX See what?]
exists $Foo::{Bar::} tests existence of a package
[XXX See what?]
Better locale support
See perllocale. perlfunc.
Re-blessing in DESTROY() supported for chaining DESTROY() methods
See "Destructors" in perlobj.
All
printf format conversions are handled internally
See "printf" in perlfunc.
New
INIT keyword
INIT subs are like
BEGIN and
END, but they get called just before the perl runtime begins execution.
[XXX Needs to be documented in perlsub or perlmod.]
New
lock keyword
To minimize impact on source compatibility this keyword is "weak", i.e., any user-defined subroutine of the same name overrides it, unless a
use Thread has been seen.
Tied arrays are now fully supported
See Tie::Array.
Tied handles support is better
Several missing hooks have been added. There is also a new base class for TIEARRAY implementations. See Tie::Array.
Supported Platforms
Configure has many incremental improvements. Site-wide policy for building perl can now be made perlsistent, via Policy.sh. Configure also records the command-line arguments used in config.sh.
New Platforms
BeOS is now supported. See README.beos.
DOS is now supported under the DJGPP tools. See README.dos.
Changes in existing support
Win32 support has been vastly enhanced. Support for Perl Object, a C++ encapsulation of Perl. GCC and EGCS are now supported on Win32. [XXX Perl Object needs a big explanation elsewhere, and a pointer to that location here.]
VMS configuration system has been rewritten. See README.vms.
OpenBSD better supported. [XXX what others?]
Modules and Pragmata
New Modules
- B
Perl compiler and tools. See [XXX what?].
- Data::Dumper
A module to pretty print Perl data. See Data::Dumper.
- Errno
A module to look up errors more conveniently. See Errno.
- File::Spec
A portable API for file operations.
- ExtUtils::Installed
Query and manage installed modules.
- ExtUtils::Packlist
Manipulate .packlist files.
- Fatal
Make functions/builtins succeed or die.
- IPC::SysV
Constants and other support infrastructure for System V IPC operations in perl.
- Test
A framework for writing testsuites.
- Tie::Array
Base class for tied arrays.
- Tie::Handle
Base class for tied handles.
- Thread
Perl thread creation, manipulation, and support.
- attrs
Set subroutine attributes.
- fields
Compile-time class fields.
- re
Various pragmata to control behavior of regular expressions.
Changes in existing modules
- CGI
CGI has been updated to version 2.42.
- POSIX
POSIX now has its own platform-specific hints files.
- DB_File
DB_File supports version 2.x of Berkeley DB. See
ext/DB_File.
- CPAN
[XXX What?]
- Cwd
Cwd::cwd is faster on most platforms.
- Benchmark
Keeps better time.
Utility Changes
h2ph and related utilities have been vastly overhauled.
perlcc, a new experimental front end for the compiler is available.
The crude GNU configure emulator is now called configure.gnu.
API Changes
Incompatible Changes
Deprecations, Extensions
C++ Support
Documentation Changes
Config.pm now has a glossary of variables.
Porting/patching.pod has detailed instructions on how to create and submit patches for perl.
New Diagnostics
- attrs).
- Bad index while coercing array into hash
(F) The index looked up in the hash found as the 0'th element of a pseudo-hash is not legal. Index values must be at 1 or greater. See perlref.
- Bareword "%s" refers to nonexistent package
(W) You used a qualified bareword of the form
Foo::, but the compiler saw no other uses of that namespace before that point. Perhaps you need to predeclare a package?
-);
- Can't coerce array into hash
(F) You used an array where a hash was expected, but the array has no information on how to map from keys to array indices. You can do that only with arrays that have a hash reference at index 0.
- Can't goto subroutine from an eval-string
(F) The "goto subroutine" call can't be used to jump out of an eval "string". (You can use it to jump out of an eval {BLOCK}, but you probably don't want to.)
- Can't use %%! because Errno.pm is not available
(F) The first time the %! hash is used, perl automatically loads the Errno.pm module. The Errno module is expected to tie the %! hash to provide symbolic names for
$!errno values.
- Can't use %%! because Errno.pm is not available
(F) The first time the %! hash is used, perl automatically loads the Errno.pm module. The Errno module is expected to tie the %! hash to provide symbolic names for
$!errno values.
- Cannot find an opnumber for "%s"
(F) A string of a form
CORE::wordwas given to prototype(), but there is no builtin with the name
word.
- "=\]".
- %s: Eval-group in insecure regular expression
(F) Perl detected tainted data when trying to compile a regular expression that contains the
(?{ ... })zero-width assertion, which is unsafe. See "(?{ code })" in perlre, and perlsec.
- %s: Eval-group not allowed, use re 'eval'
(F) A regular expression contained the
(?{ ... })zero-width assertion, but that construct is only allowed when the
use re 'eval'pragma is in effect. See "(?{ code })" in perlre.
-');
- Illegal hex digit ignored
(W) You may have tried to use a character other than 0 - 9 or A - F in a hexadecimal number. Interpretation of the hexadecimal number stopped before the illegal character.
- No such array field
(F) You tried to access an array as a hash, but the field name used is not defined. The hash at index 0 should map all valid field names to array indices for that to work.
-.
- Out of memory during ridiculously large request
(F) You can't allocate more than 2^31+"small amount" bytes. This error is most likely to be caused by a typo in the Perl program. e.g.,
$arr[time]instead of
$arr[$time].
- Range iterator outside integer range
(F) One (or both) of the numeric arguments to the range operator ".." are outside the range which can be represented by integers internally. One possible workaround is to force Perl to use magical string increment by prepending "0" to your numbers.
- Recursive inheritance detected while looking for method '%s' in package '%s'
(F) More than 100 levels of inheritance were encountered while invoking a method. Probably indicates an unintended loop in your inheritance hierarchy.
-
- Undefined value assigned to typeglob
(W) An undefined value was assigned to a typeglob, a la
*foo = undef. This does nothing. It's possible that you really mean
undef *foo.
- perllocale section LOCALE PROBLEMS.
Obsolete Diagnostics
- Can't mktemp()
(F) The mktemp() routine failed for some reason while trying to process a -e switch. Maybe your /tmp partition is full, or clobbered.
- Can't write to temp file for -e: %s
(F) The write routine failed for some reason while trying to process a -e switch. Maybe your /tmp partition is full, or clobbered.
- Cannot open temporary file
(F) The create routine failed for some reason while trying to process a -e switch. Maybe your /tmp partition is full, or clobbered.
2 POD Errors
The following errors were encountered while parsing the POD:
- Around line 43:
'=item' outside of any '=over'
- Around line 47:
You forgot a '=back' before '=head2' | https://metacpan.org/pod/release/GSAR/perl5.004_72/pod/perldelta.pod | CC-MAIN-2016-44 | refinedweb | 1,822 | 59.4 |
by Nick Karnik
How to build your own React boilerplate
What is a Boilerplate?
In programming, the term boilerplate code refers to blocks of code used over and over again.
Let’s assume your development stack consists of several libraries, such as React, Babel, Express, Jest, Webpack, etc. When you start a new project, you initialize all these libraries and configure them to work with each other.
With every new project that you start, you will be repeating yourself. You could also introduce inconsistencies in how these libraries are set up in each project. This can cause confusion when you switch between projects.
This is where boilerplates come in. A boilerplate is a template that you can clone and reuse for every project.
The modular Javascript ecosystem simplifies application development through various libraries, frameworks and tools. Boilerplates can be daunting if you don’t understand the fundamentals of their underlying components. Let’s learn about these basic building blocks while creating our own..
Readme File
Every project should contain a landing page with useful instructions for other developers. Let’s create a README.md file under the project root with the following content:
# React-BoilerplateThis is my react-boilerplate
## Setupnpm installnpm run buildnpm start
GitHub displays the contents of the readme file on the landing page for the project.
Now, commit the above changes to Git:
git add .git commit -m "created readme"
At the end of each section, you should commit your code to Git.
Folder Structure
Create the following folder structure for your project:
react-boilerplate |--src |--client |--server
with the command:
mkdir -p src/client src/server
This folder structure is basic and will evolve as you integrate other libraries in the project.
Git Ignore
Once we build our project, there will be a few auto-generated files and folders. Let’s tell Git to ignore some of those files that we can think of ahead of time.
Create .gitignore under the root folder with the following content:
# Nodenode_modules/
# Webstorm.idea/
# Projectdist/
Node Package Manager
The starting point for a node project is to initialize its package manager which creates a file called package.json. This file must be checked into Git.
It generally contains:
- A description of your project for NPM
- List of references to all installed packages
- Custom command line scripts
- Configuration for installed packages
Go to your project root and type the following:
npm init
Fill out all the details, and after you accept them, npm will create a package.json file that looks something like:
{ "name": "react-boilerplate", "version": "1.0.0", "description": "Basic React Boilerplate", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+" }, "keywords": [ "Node", "React" ], "author": "Nick Karnik", "license": "Apache-2.0", "bugs": { "url": "" }, "homepage": ""}
Static Content
Let’s create a static HTML file src/client/index.html with the following content:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>React Boilerplate</title></head><body> <div id="root"> Welcome to React Boilerplate! </div></body></html>
Express Web Server
To serve the static file above, we need to create a web server in ExpressJS.
NPM v5 automatically saves installed packages under the dependencies section in package.json so the --save attribute is not necessary
npm install express
I would recommend following a file naming convention where file names are lower case and multiple words are separated by a dot. You will avoid running into case sensitivity issues across platforms, and will also simplify naming files with multiple words across larger teams.
Create a file src/server/web.server.js and add the following code to host a web server via an express app and serve the static HTML file:
const express = require('express')
export default class WebServer { constructor () { this.app = express() this.app.use(express.static('dist/public')) }
start () { return new Promise((resolve, reject) => { try { this.server = this.app.listen(3000, function () { resolve() }) } catch (e) { console.error(e) reject(e) } }) }
stop () { return new Promise((resolve, reject) => { try { this.server.close(() => { resolve() }) } catch (e) { console.error(e.message) reject(e) } }) }}
We have created a simple web server above with a start and stop command.
Startup File
Next, we need to create an index file which will initialize various high-level components. In our example, we’re going to initialize the web server. However, as your project grows, you can also initialize other components such as configuration, database, logger, etc.
Create a file src/server/index.js with the following code:
import WebServer from './web.server'
let webServer = new WebServer();webServer.start() .then(() => { console.log('Web server started!') }) .catch(err => { console.error(err) console.error('Failed to start web server') });
Babel
To run the above ES6 code, we need to transform it to ES5 first via Babel. Let’s install Babel and the babel-preset-env dependency which supports ES2015 transpilation:
npm i babel-cli babel-preset-env --save-dev
Create a Babel configuration file called .babelrc under the root and add the following details to it:
{ "presets": ["env"]}
The env preset implicitly includes babel-preset-es2015, babel-preset-es2016, and babel-preset-es2017 together, which means you can run ES6, ES7 and ES8 code.
Build Commands
Let’s create commands to build the server and client components of the project and start the server. Under the scripts section of package.json, remove the line with the test command and add the following:
"scripts": { "build": "npm run build-server && npm run build-client", "build-server": "babel src/server --out-dir ./dist", "build-client": "babel src/client --copy-files --out-dir ./dist/public", "start": "node ./dist/index.js"}
The build command above will create a dist/public folder under the root. The build-client command is simply copying the index.html file to the dist/public folder.
Starting up
You can run the Babel transpiler on the code above and start the web server by using the following commands:
npm run buildnpm start
Open your browser and navigate to. You should see the output of your static HTML file.
You can stop the web server by pressing <Ctrl> C
Test Harness: Jest
I cannot stress enough the importance of introducing unit tests at the beginning of a project. We’re going to use the Jest Testing Framework which is designed to be fast and developer friendly.
First, we need to install Jest and save it to development dependencies.
npm i jest --save-dev
Unit Tests
Let’s add two test cases to start and stop the web server.
For test files, you should add a .test.js extension. Jest will scan the src folder for all files containing .test in the filename, you can keep your test cases under the same folder as the files they’re testing.
Create a file called src/server/web.server.test.js and add the following code:
import WebServer from './web.server'
describe('Started', () => { let webServer = null
beforeAll(() => { webServer = new WebServer() })
test('should start and trigger a callback', async () => { let promise = webServer.start() await expect(promise).resolves.toBeUndefined() })
test('should stop and trigger a callback', async () => { let promise = webServer.stop() await expect(promise).resolves.toBeUndefined() })})
Test Command
Let’s add an npm command to run the test under the scripts section of package.json. By default, Jest runs all files with the word .test in their file name. We want to limit it to running tests under the src folder.
"scripts": {... "test": "jest ./src"...}
Babel-jest is automatically installed when installing Jest and will automatically transform files if a Babel configuration exists in your project.
Let’s run our tests via the following command:
npm test
Our application is set up to serve a static HTML file via an Express web server. We have integrated Babel to enable ES6 and Jest for unit testing. Let’s shift our focus to the front-end setup.
React Setup
Install the react and react-dom libraries:
npm i react react-dom
Create a file called src/client/app.js with:
import React, {Component} from 'react'
export default class App extends Component { render() { return <div>Welcome to React Boilerplate App</div> }}
Let’s render the App via an index file under src/client/index.js with:
import React from 'react'import ReactDOM from 'react-dom'import App from './app'
ReactDOM.render(<App />, document.getElementById('root'))
Babel React
If you execute npm run build-client, you will get an error because we haven’t told Babel how to handle React / JSX.
Let’s fix that by installing the babel-preset-react dependency:
npm install --save-dev babel-preset-react
We also need to modify the .babelrc config file to enable transpiling react:
{ "presets": ["env", "react"]}
Now, when you run npm run build-client, it will create app.js and index.js under dist/public with ES6 code transpiled to ES5.
Load Script in HTML
To connect our React App to the HTML file, we need to load index.js in our index.html file. Don’t forget to empty the text of the #root node since the React App will be mounted to it:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>React Boilerplate</title></head><body> <div id="root"></div> <script src="index.js"></script></body></html>
Run Server
If you fire up your web server and go to, you will see a blank page with an error in the console.
Uncaught ReferenceError: require is not defined.
This is because Babel is just a transpiler. In order to support dynamically loading modules, we will need to install Webpack.
Start by changing the build commands under scripts in package.json to build-babel:
"scripts": { "build-babel": "npm run build-babel-server && npm run build-babel-client", "build-babel-server": "babel src/server --out-dir ./dist", "build-babel-client": "babel src/client --copy-files --out-dir ./dist/public", "start": "node ./dist/index.js", "test": "jest ./src" }
Webpack
Webpack allows us to easily modularize our code and bundle it into a single Javascript file. It is supported by numerous plugins, and chances are that there’s a plugin for almost any build task you can think of. Start by installing Webpack:
This tutorial was published right before webpack v4 was released, so we will explicitly install webpack v3.
npm i webpack@^3
By default, Webpack looks for a configuration file called webpack.config.js, so let’s create it in the root folder and define two entry points, one for the web application and the other for the web server. Let’s create two config objects and export them as a collection:
const client = { entry: { 'client': './src/client/index.js' }};
const server = { entry: { 'server': './src/server/index.js' }};
module.exports = [client, server];
Now, let’s specify where Webpack will output the bundle and set the target build so that it ignores native node modules like ‘fs’ and ‘path’ from being bundled. For client, we will set it to web, and for server we will set it to node.
let path = require('path');
const client = { entry: { 'client': './src/client/index.js' }, target: 'web', output: { filename: '[name].js', path: path.resolve(__dirname, 'dist/public') }};
const server = { entry: { 'server': './src/server/index.js' }, target: 'node', output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') }};
module.exports = [client, server];
Babel Loader
Before we can run Webpack, we need configure it to handle ES6 and JSX code. This is done via loaders. Let’s start by installing babel-loader:
npm install babel-loader --save-dev
We need to modify the Webpack configuration to include babel-loader to run on all .js files. We will create a shared object defining the module section that we can re-use for both targets.
const path = require('path');
const moduleObj = { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ["babel-loader"], } ],};
const client = { entry: { 'client': './src/client/index.js', }, target: 'web', output: { filename: '[name].js', path: path.resolve(__dirname, 'dist/public') }, module: moduleObj};
const server = { entry: { 'server': './src/server/index.js' }, target: 'node', output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') }, module: moduleObj}
module.exports = [client, server];
For merging nested shared objects, I would recommend checking out the Webpack Merge module.
Excluding Files
Webpack will bundle referenced libraries, which means everything that is included from node_modules will be packaged. We don’t need to bundle external code, as those packages are generally minified, and they will also increase the build time and size.
Let’s configure Webpack to exclude all packages under the node_modules folder. This is easily accomplished via the webpack-node-externals module:
npm i webpack-node-externals --save-dev
Followed by configuring webpack.config.js to use it:
let path = require('path');let nodeExternals = require('webpack-node-externals');
const moduleObj = { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ["babel-loader"], } ],};
const client = { entry: { 'client': './src/client/index.js', }, target: 'web', output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') }, module: moduleObj};
const server = { entry: { 'server': './src/server/index.js' }, target: 'node', output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') }, module: moduleObj, externals: [nodeExternals()]}
module.exports = [client, server];
Update Build Command
Finally, we need to make changes to the scripts section under package.json to include a build command that uses Webpack, and to rename index.js to server.js for npm start as that’s what Webpack is configured to output.
"scripts": { "build": "webpack", "build-babel": "npm run build-babel-server && npm run build-babel-client", "build-babel-server": "babel src/server --out-dir ./dist", "build-babel-client": "babel src/client --copy-files --out-dir ./dist/public", "start": "node ./dist/server.js", "test": "jest ./src" }
Build Clean
Let’s add a command to clean our dist and node_modules folders so we can do a clean build and ensure our project still works as expected. Before we can do that, we need to install a package called rimraf (which is the rm -rfcommand).
npm install rimraf
The scripts section should now contain:
"scripts": {..."clean": "rimraf dist node_modules",...}
Clean Build with Webpack
You can now successfully clean and build your project using Webpack:
npm run cleannpm installnpm run build
This will create dist/server.js and dist/public/client.js under the root folder.
HTML Webpack Plugin
However, you may have noticed that index.html is missing. This is because, previously, we asked Babel to copy files that weren’t transpiled. However, Webpack isn’t able to do that, so we need to use the HTML Webpack Plugin.
Let’s install the HTML Webpack Plugin:
npm i html-webpack-plugin --save-dev
We need to include the plugin at the top of the webpack config file:
const HtmlWebPackPlugin = require('html-webpack-plugin')
Next, we need to add a plugins key to the client config:
const client = { entry: { 'client': './src/client/index.js' }, target: 'web', output: { filename: '[name].js', path: path.resolve(__dirname, 'dist/public') }, module: moduleObj, plugins: [ new HtmlWebPackPlugin({ template: 'src/client/index.html' }) ]}
Before we build the project, let’s modify our HTML file and remove the reference to the index.js script, because the above plugin will add that for us. This is especially useful when there are one or more files with dynamic filenames (for instance when files are generated with a unique timestamp for cache busting).
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>React Boilerplate</title></head><body> <div id="root"></div></body></html>
Lets’s rebuild the project:
npm run cleannpm installnpm run build
And, verify that our existing tests are still running:
npm test
We have further updated the boilerplate to integrate React and Webpack, created additional NPM commands, dynamically referenced index.js in the HTML file, and exported it.
Enzyme Setup
Before we add a React test, we need to integrate Enzyme, which will allow us to assert, manipulate and traverse react components.
Let’s start by installing Enzyme and enzyme-adapter-react-16, which is required to connect Enzyme to a project using react v16 and above.
enzyme-adapter-react-16 has peer dependencies on react, react-dom, and react-test-renderer
npm i --save-dev enzyme enzyme-adapter-react-16 react-test-renderer
Create a file src/enzyme.setup.js with the following content:
import Enzyme from 'enzyme'import Adapter from 'enzyme-adapter-react-16'
Enzyme.configure({ adapter: new Adapter()})
We need to configure Jest to use src/enzyme.setup.js in package.json by adding the following section under the root object:
{..."jest": { "setupTestFrameworkScriptFile": "./src/enzyme.setup.js" }...}
React Component Test
Let’s test the App Component and ensure that it renders the expected text. In addition, we will take a snapshot of that component so we can ensure that its structure hasn’t changed with every test run.
Create a test case under src/client/app.test.js with the following content:
import App from './app'import React from 'react'import {shallow} from 'enzyme'
describe('App', () => { test('should match snapshot', () => { const wrapper = shallow(<App/>)
expect(wrapper.find('div').text()).toBe('Welcome to React Boilerplate App') expect(wrapper).toMatchSnapshot() })})
If we run this test now, it will pass with a warning:
Let’s fix that by installing a polyfill called raf:
npm i --saveDev raf
And changing the Jest configuration under package.json to:
{..."jest": { "setupTestFrameworkScriptFile": "./src/enzyme.setup.js", "setupFiles": ["raf/polyfill"] }...}
Now, you can verify that all our tests are passing:
npm test
After running the react test, you will notice a new file at src/client/snapshots/app.test.js.snap. It contains the serialized structure of our react component. It must be checked into Git so it can be used to compare against the dynamically generated snapshot during a test run.
Final Run
Let’s start the web server one more time and navigate to to ensure everything works:
npm start
I hope this article has given you insights into streamlining the process of starting a new project from scratch with Express | React | Jest | Webpack | Babel. It is a good idea to create your own reusable boilerplate so you understand what goes on under the hood, and at the same time get a head-start when creating new projects.
We have barely scratched the surface and there is a lot of room for improvement to make this boilerplate production ready.
Here are some things for you to try:
- Enable cache busting in Webpack
- CSS file bundling using css-loader in webpack
- Enable source maps in webpack
- Add debug commands to package.json
- Hot module replacement
- Auto-restart web server when changes are detected via nodemon
If you would like to learn more about the react ecosystem, I would highly recommend taking The Complete React Web Developer Course by Andrew Mead.
If this article was helpful, ??? and Follow me on Twitter.
| https://www.freecodecamp.org/news/how-to-build-your-own-react-boilerplate-2f8cbbeb9b3f/ | CC-MAIN-2021-04 | refinedweb | 3,106 | 57.67 |
Let’s Build a Web App with Vue, Chart.js and an API Part II
Jakub Juszczak
・8 min read
In case you missed the first part, you can find it here. First of all, wow! Thanks for all the feedback and twitter messages! 💠I never imagined to reach such a wide audience. But enough of that. Let's get to work 💪.
âš¡ Quickstart
So, we are building npm-stats.org. A small web application build with Vue.js, vue-chartjs and the npm API, to grab the download statistics of packages and generate charts based on them.
What we have done so far
A small recap of what we have build in Part 1:
- ✅ Create a vue.js application with
vue-init
- ✅ Install dependencies and setup the
vue-router
- ✅ Create a Line Chart component with
vue-chartjs
- ✅ Make an API call to npm and render the daily downloads statistics of the last-month
This is quite a lot. In the end we had our app running. However there is always space for improvement!
What we will do today:
- âš™ Add settings to change the start and end period
- 📆 Integrate an external datepicker component
- 📈 Mutate our data to add a yearly statistics chart
- 🔨 Refactor our methods and DRY out a bit so we can easily add more charts
âš™ Settings
Right now our default period is set to
last-month but it would be awesome if we could set the startPeriod and endPeriod. This way we could inspect the statistics for a whole year or more.
For this purpose we need to add two additional input fields and data models. But for a better user experience we will pull in an external datepicker component. We don't have to reinvent the wheel right? 👨”🔬 And to format our date properly we will also pull in moment.js
📆 Install dependencies
yarn add vuejs-datepicker moment
Todos for our Start.vue:
- Import the datepicker
- Add two datepicker fields for the start and end period
- Add two data models
// Start.vue <template> ... <datepicker placeholder="Start Date" v-</datepicker> <datepicker placeholder="Start Date" v-</datepicker> ... </template> <script> import axios from 'axios' import Datepicker from 'vuejs-datepicker' import LineChart from '@/components/LineChart' export default { components: { LineChart, Datepicker }, data () { return { package: null, packageName: '', loaded: false, downloads: [], labels: [], showError: false, errorMessage: 'Please enter a package name', periodStart: '', periodEnd: new Date() } }, ..... } </script>
We also removed our old
period data model which was set to
last-month. As the period will now be composed of
periodStart and
periodEnd. We also set the
periodEnd to the current day. As most of the time you will only change the start date.
We need a format like this:
2017-04-18:2017-04-30. However if we now select a date we get something like this:
2017-04-17T22:00:00.000Z. A
Date() with the time attributes, which we don't need. This is a nice job for
moment.js.
Computing the period
For this case we have computed properties which are a pleasure to work with. To keep things a bit cleaner, we will create three properties. A formatted startDate, a formatted endDate and the composed period.
computed: { _endDate () { return moment(this.periodEnd).format('YYYY-MM-DD') }, _startDate () { return moment(this.periodStart).format('YYYY-MM-DD') }, period () { return this.periodStart ? `${this._startDate}:${this._endDate}` : 'last-month' } },
As we want to persist the default behaviour of fetching data of the last month if no start date is set, we add our condition to the
period property.
And thats it! We don't need to change our request, as we simply replaced the content of
period which we are using in our request. You can check the code on github in this feature branch
📈 More charts
Well, the chart with the daily statistics is great. But we can generate more! We have all data we need for that. We will not transform and group our data, so we can pass it to another line chart for yearly statistics. And we will refactor a bit our code.
All this data
So, our data we get from the npm api looks like this:
data: [ {day: "2017-04-18", downloads: 16280}, {day: "2017-04-19", downloads: 14280}, {day: "2017-04-20", downloads: 17280} ]
But to pass it to our chart we need two arrays, one which the labels (day) and one with the data (downloads). For the daily statistics, it was pretty easy. As we could simply use
map() to get the data and labels. However now we need to do more.
- Format our
daykey to a year.
- For the labels, remove the duplicates so we have only the unique years
- Sum all the downloads in the same year.
☠But first, it is a good time to refactor some bits of our code. We see that step 1 is to format our date to a year. And later if we want monthly statistics we need to format it to a month format and so on. So it is a good time to introduce a helper method and extract the logic from the Start.vue file.
So we create
src/utils/dateFormatter.js which will help us to format our date.
import moment from 'moment' export const dateToYear = date => moment(date).format('YYYY') export const dateToMonth = date => moment(date).format('MMM YYYY') export const dateToWeek = date => moment(date).format('GGGG-[W]WW') export const dateToDay = date => moment(date).format('YYYY-MM-DD') export const dateBeautify = date => moment(date).format('Do MMMM YYYY')
And in our Start.vue we can now remove the
moment import and import our helper modules and replace the moment statements with them. (In our
_startPeriod and
_endPeriod. And we add a new computed property to which will replace the
period in our chart container.
import { dateToYear, dateToDay, dateBeautify } from '../utils/dateFormatter' computed: { _endDate () { return dateToDay(this.periodEnd) }, _startDate () { return dateToDay(this.periodStart) }, period () { return this.periodStart ? `${this._startDate}:${this._endDate}` : 'last-month' }, formattedPeriod () { return this.periodStart ? `${dateBeautify(this._startDate)} - ${dateBeautify(this._endDate)}` : 'last-month' } },
Time to transform
Now we create three new data models
rawData which will hold our downloads data we get from the api call,
downloadsYear: [] and
labelsYear: []. And we create a new method called
formatYear() .
In our axios request promise we then assign the data.downloads to
rawData and call
formatYear().
axios.get(`{this.period}/${this.package}`) .then(response => { this.rawData = response.data.downloads // 🆕 this.downloads = response.data.downloads.map(entry => entry.downloads) this.labels = response.data.downloads.map(entry => entry.day) this.packageName = response.data.package this.formatYear() // 🆕 this.setURL() this.loaded = true })
Now we will create two additional helper methods. Because we want different data transformations in the future. Like weekly stats and monthly. And to keep our component clean we extract those into a separate file.
So we create our
src/utils/downloadFormatter.js which will contain two methods:
- removeDuplicate (a, b) {..}
- getDownloadsPerYear(data) {...}
In our Start.vue we import both modules and now we can use them in our
formatYear() method.
formatYear () { this.labelsYear = this.rawData .map(entry => dateToYear(entry.day)) .reduce(removeDuplicate, []) this.downloadsYear = getDownloadsPerYear(this.rawData) },
Now thats a bit tricky now. Normally I write down my methods and clean then up later. However I hope you can follow me here.
First we need to get the years, right? So we use again
map() to get the
day key like we did in the request for our daily statistics. But now we format it with our
dateToYear() helper. So now our data will look like this:
data: [ {day: "2017", downloads: 16280}, {day: "2017", downloads: 14280}, {day: "2017", downloads: 17280} ]
And now we will use
reduce() to remove the duplicated years. Because our labels array will have only unique years. And as we may use this more then once, we extracted it into our
downloadFormatter.js
In our downloadFormatter.js we now finish our removeDuplicate function.
export function removeDuplicate (a, b) { if (a.indexOf(b) < 0) { a.push(b) } return a }
Now our
this.labelYear array will contain only unique years. And it's time to group and transform our data. For this we will again use
map() and
reduce() and
filter().
The
rawData looks like this:
data: [ {day: "2017-04-18", downloads: 16280}, {day: "2017-04-19", downloads: 14280}, {day: "2017-04-20", downloads: 17280} ]
So first we need to find the unique dates again. Which we do with
reduce() then we chain a
map() to it and return an object with the date and the downloads which are in that date. Thats why we use
filter() there and our
dateToYear() helper.
However our data will look now like this:
But as we don't need the date now, we
map it to only the downloads and then use
reduce() to sum it up. Now our object will contain the sum of all downloads of the year. However it is nested and we still have the date key.
But a last
map() will fix this.
export const getDownloadsPerYear = (data) => { // Find unique dates return data.reduce((date, current) => { if (date.indexOf(dateToYear(current.day)) < 0) { date.push(dateToYear(current.day)) } return date }, []) .map((date) => { return { date: date, downloads: data.filter(el => dateToYear(el.day) === date) .map(el => el.downloads) .reduce((total, download) => total + download) } }) .map(element => element.downloads) }
Chart time
Now we have our transformation done and can copy the template for our first chart and pass in the
downloadsYear props.
You can check the source up to this point at this feature branch
🔨 Refactor and more charts
As we now finished our data transformer it is pretty easy to add new charts. Like weekly statistics and monthly. We could duplicate our
getDownloadsPerYear() method and change our
dateToYear() helper to
dateToMonth(). But, this is not very DRY. Because we end up with multiple methods which are doing pretty much the same.
So let's refactor our specific
getDownloadsPerYear() method to a more general one. The only thing, that would change it our dateFormatter helper. So we should make it an argument you can pass to our method.
- Rename our method to something more general like
groupData
- Add a second argument which will be our helper function
- ???
- Profit!
export const groupData = (data, dateFormatter) => { return data.reduce((date, current) => { if (date.indexOf(dateFormatter(current.day)) < 0) { date.push(dateFormatter(current.day)) } return date }, []) .map((date) => { return { date: date, downloads: data.filter(el => dateFormatter(el.day) === date) .map(el => el.downloads) .reduce((total, download) => total + download) } }) .map(element => element.downloads) }
In our Start.vue we now need to pass our helper function.
this.downloadsYear = groupData(this.rawData, dateToYear)
Now we can do this for our monthly and weekly data too, with only swapping out the
dateToYear
You can find the source up to this point in this feature branch with some additions like a loading indicator and a new fetch of the data if the datepicker value changed, which I did not covered here.
I hope you enjoyed it and learned something. Feel free to leave me feedback! ✌ You can follow me on twitter and github
(open source and trusted by devs everywhere ❤️)
The Many Flavors of Technical Presentations
Learn about various technical presentation formats to choose the best one for you
| https://dev.to/apertureless/lets-build-a-web-app-with-vue-chartjs-and-an-api-part-ii | CC-MAIN-2019-35 | refinedweb | 1,885 | 67.55 |
I need to edit the "Add Object" action in the admin. It needs to redirect the user to a custom cause the logic required for adding objects is too complex to be managed in the admin. So, how do I make this possible? i.e:
The picture shows a django-suit admin, but the question is the same. How can I make that button redirect to a custom url? Or, how can I create a similar button that redirects to a custom url (I could disable the default create and leave only the custom button).
Override
change_list_template html, the block
object-tools-items. It's where add button is placed.
class MyModelAdmin(admin.ModelAdmin): change_list_template = 'change_list.html'
In your
change_list.html
{% extends "admin/change_list.html" %} {% load i18n admin_static admin_list %} {% block object-tools-items %} {% if has_add_permission %} <li> <a href="your/custom/url" class="addlink"> {% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %} </a> </li> {% endif %} {% endblock %}
You need to add your new html in any dir that is included on
TEMPLATE_DIRS options. But, you should do it inside your model's app.
-app -templates -admin change_list.html
Add above dir in TEMPLATE DIRS paths. | https://codedump.io/share/RrMWrI1Wpqwj/1/django-customize-action-for-model | CC-MAIN-2017-13 | refinedweb | 195 | 68.87 |
This page provides a high-level overview of the internals of doxygen, with links to the relevant parts of the code. This document is intended for developers who want to work on doxygen. Users of doxygen are referred to the User Manual.
The generic starting point of the application is of cource the main() function.
Configuration file data is stored in singleton class Config and can be accessed using wrapper macros Config_getString(), Config_getInt(), Config_getList(), Config_getEnum(), and Config_getBool() depending on the type of the option.
The format of the configuration file (options and types) is defined by the file
config.xml. As part of the build process, the python script
configgen.py will create a file configoptions.cpp from this, which serves as the input for the configuration file parser that is invoked using Config::parse(). The script
configgen.py will also create the documentation for the configuration items, creating the file
config.doc.
After the configuration is known, the input files are searched using searchInputFiles() and any tag files are read using readTagFile()
The function parseFiles() takes care of parsing all files. It uses the ParserManager singleton factory to create a suitable parser object for each file. Each parser implements the abstract interface ParserInterface.
If the parser indicates it needs preprocessing via ParserInterface::needsPreprocessing(), doxygen will call preprocessFile() on the file.
A second step is to convert multiline C++-style comments into C style comments for easier processing later on. As side effect of this step also aliases (ALIASES option) are resolved. The function that performs these 2 tasks is called convertCppComments().
Note: Alias resolution should better be done in a separate step as it is now coupled to C/C++ code and does not work automatically for other languages!
The third step is the actual language parsing and is done by calling ParserInterface::parseInput() on the parser interface returned by the ParserManager.
The result of parsing is a tree of Entry objects. These Entry objects are wrapped in a EntryNav object and stored on disk using Entry::createNavigationIndex() on the root node of the tree.
Each Entry object roughly contains the raw data for a symbol and is later converted into a Definition object.
When a parser finds a special comment block in the input, it will do a first pass parsing via parseCommentBlock(). During this pass the comment block is split into multiple parts if needed. Some data that is later needed is extracted like section labels, xref items, and formulas. Also Markdown markup is processed using processMarkdown() during this pass.
The Entry objects created and filled during parsing are stored on disk (to keep memory needs low). The name, parent/child relation, and location on disk of each Entry is stored as a tree of EntryNav nodes, which is kept in memory.
Doxygen does a number of tree walks over the EntryNav nodes in the tree to build up the data structures needed to produce the output.
The resulting data structures are all children of the generic base class called Definition which holds all non-specific data for a symbol definition.
Definition is an abstract base class. Concrete subclasses are
For doxygen specific concepts the following subclasses are available
Finally the data for members of classes, namespaces, and files is stored in the subclass MemberDef.
Within doxygen there are a number of ways to obtain debug output. Besides the invasive method of putting print statements in the code there are a number of easy ways to get debug information.
.lfiles
flex / lexcommand. The result is that of each input line the (lex) rule(s) that are applied on it are shown.
.lfile
Propertiesof this file
Write used lex rulesto
Yes
.lfile is newer than the corresponding
.cppfile or remove the corresponding
.cppfile
perlscript is given to toggle the possibility of having the rules debug information.
LEX="flex -d"with the
makecommand on the command line. In this case the
.lthat are converted to the corresponding
.cppfiles during this
makeget the rules debug information.
make.
.lfiles that are rebuild to
.cppfiles so be sure that only the
.lfiles(s) of which you want to have the rules debug information is (are) newer than the corresponding
.cppfile(s).
-doption with the following possibilities (each option has to be preceded by
-d):
#definestatements etc., definitions in the doxygen configuration file like:
EXPAND_ONLY_PREDEF,
PREDEFINEDand
MACRO_EXPANSION.
MULTILINE_CPP_IS_BRIEFis set to
NO).
ALIASES)
\cond ... \endcondblocks)
"."(dot).
lexfiles used. When a lexer is started and when a lexer ends the name of the
lexfile is given so it is possible to see in which lexer the problem occurs. This makes it easier to select the file to be compiled in
lexdebug mode.
TODO | https://fossies.org/dox/doxygen-1.8.14.src/ | CC-MAIN-2018-51 | refinedweb | 778 | 56.96 |
Automatic file closure. The statement try with resources. Examples
Contents
- 1. Automatically close a file using a try block. The statement try with resources
- 2. Using the try statement with resources. Converting file contents to an array of strings. Example
- 3. A try statement with resources that contains multiple file objects. Example
- Related topics
Search other websites:
1. Automatically close a file using a try block. The statement try with resources
Any file that is opened and used must be closed by calling the close() method. If this is not done, then it can memory leak and related complications.
JDK 7 introduces a new ability to control file input/output streams – automatic resource management (ARM) or automatic process termination. This feature is based on an improved version of the try statement and consists in preventing cases of erroneous non-closing of a file (not freeing up a resource).
The general form of the try statement, which provides automatic resource management, is as follows:
try (resource_specification) { // using of resource // ... }
here resource_specification is an operator that declares and initializes such a resource as an input/output stream to a file. A variable is declared in the resource_specification statement, which is a reference to a managed object. In the case of a file, a variable is declared, which is a reference to a file object.
The above statement is also called a try statement with resources.
Another form of using the try statement with resources is possible. With this specification, a try statement with resources can contain catch and finally blocks.
try (resource_specification) { // using a resource // ... } catch (...) { // error processing // ... } finally { // finally block // ... }
⇑
2. Using the try statement with resources. Converting file contents to an array of strings. Example
The example demonstrates the GetLinesFromFile() function, which converts the contents of a text file into an array of strings of type String[]. The function uses a try statement with resources, in which a file object named fr appears as a resource. There is no call to fr.close() in the try statement. This method will be called automatically.
import java.io.*; ... // Get file lines as an array of String[] public static String[] GetLinesFromFile(String filename) throws IOException { // Declare internal variables String lines[] = null; // array of lines - result String lines2[] = null; // additional array of lines String s; // additional variable - line int symbol; // Statement try with resources. // A fr file object is created that is associated with the textfile.txt file try (FileReader fr = new FileReader(filename)) { // Initialization before entering the loop lines = new String[0]; // create an array of 0 strings s = ""; // The cycle of reading characters from a file and creating an array of lines[] do { // Read character from file symbol = fr.read(); if ((char)symbol == '\n') { // delete character '\n' s = s.substring(0,s.length()-1); // add string s to the array of strings lines[] lines2 = new String[lines.length+1]; // create a new array lines2[] for (int i=0; i<lines.length; i++) lines2[i] = lines[i]; lines2[lines.length] = s; lines = lines2; // clear the string s s = ""; } else { s = s + (char)symbol; } } while (fr.ready()); // there is no need to close the file, // method fr.close() will be called automatically } catch (FileNotFoundException e) { System.out.println("File not found."); return null; } catch (IOException e) { System.out.println("I/O error."); return null; } return lines; }
Using the GetLinesFromFile() method can be, for example, like this
public static void main(String[] args) throws IOException { String lines[]; lines = GetLinesFromFile("textfile.txt"); if (lines!=null) { // Display the array lines[] System.out.println("The content of file \"textfile.txt\""); for (int i=0; i<lines.length; i++) System.out.println(lines[i]); } }
⇑
3. A try statement with resources that contains multiple file objects. Example
In the try statement, several file objects (resources) can be created simultaneously. In the following example, the CopyTextFiles() function is declared, which implements copying text files.
The function implements a try statement with resources that manages two resources simultaneously. The first fr resource is the file object that is the source (original file). The second resource fw is the file object, which is the receiver or copy.
The function text is as follows.
import java.io.*; public static void CopyTextFiles(String filename1, String filename2) throws IOException { try (FileReader fr = new FileReader(filename1); FileWriter fw = new FileWriter(filename2)) { int symbol; do { symbol = fr.read(); fw.write(symbol); } while (fr.ready()); // No need to call the fr.close () and fw.close () methods, // these methods will be called automatically } catch (IOException e) { System.out.println("Error: " + e.getMessage()); return; } }
A function call from another code can be, for example,
public static void main(String[] args) throws IOException { CopyTextFiles("textfile.txt", "textfile3.txt"); }
⇑
Related topics
- Java I/O system. Streams. Byte streams. Character streams. Standard streams
- Work with the console. Classes InputStreamReader, PrintStream. Creating an input/output stream associated with the console. Redirecting input/output streams
- Examples of implementation of operations that modify text files. Classes FileReader, FileOutputStream, PrintStream
⇑ | https://www.bestprog.net/en/2020/07/12/java-automatic-file-closure-the-statement-try-with-resources-examples/ | CC-MAIN-2022-27 | refinedweb | 822 | 51.65 |
| |
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent
my employer's view in any way.
When I released CMSImport 1.0 two months ago, I briefly described the FieldAdapters feature that I was going to build for version 1.1. Today I want to go more into detail about the FieldAdapters feature for CMSImport.
The reason I started to think about fieldadapters was because I wanted to solve a very common problem. As you might know Umbraco only accepts three kinds of data; string, integer and datetime. What happens when you try to map a boolean value to a yes/no Umbraco datatype? An exception is thrown. The following screenshot contains several products that we want to import into Umbraco.
When we’ve mapped the InStore column to a yes/no datatype the import will fail because it can’t map the boolean value to a 0 or 1 and we will see the following ugly screen
Yes a fieldadapter inspects the value and tries to parse it, in this case it will try to pares a true/false value to 1/0, best to explain by exploring the source code. The whole feature is based on the new IFieldAdapter interface.
using System;
namespace CMSImportLibrary.Interfaces
{
/// <summary>
/// Implement the IFieldAdapter interface to convert an mallformed field to a correct type.
/// </summary>
public interface IFieldAdapter
{
/// <summary>
/// Contains the GUID of the datatype we want to parse using this FieldAdapter
/// </summary>
Guid DataTypeId { get; }
/// <summary>
/// Parse the data
/// </summary>
/// <param name="value">The value to parse</param>
/// <returns></returns>
object Parse(object value);
}
}
As you can see in the code snippet the interface contains the property DataTypeId. The value needs to correspondent to the Id (GUID) of the datatype you are creating the fieldadapter for. During the import a factory inspects the underlying datatype of the document property, if a fieldadapter is found it will execute the Parse method. This will work on all Umbraco datatypes (also custom datatypes or datatypes from third party packages) as long as you know the Id of the datatype. You can find the id by opening the datatype in Umbraco, there you see the RenderControl .
When opening the source code of the rendercontrol you’ll see the Id of the datatype (a GUID). Don’t worry if you can’t open the source code of the datatype i’ll add the Id’s of all known datatypes to the documentation of CMSImport and I’ll make a free tool that shows the Id of any datatype.
Now enough with all the boring stuff, let’s see the fieldadapter in action. Below you’ll see the implementation of the BooleanFieldAdapter. I’ve mapped the id of the True/false datatype to the DataTypeId property so CMSImport knows that it needs to call the Parse method during the mapping of a yes/no document property. In the Parse method I simply check if the value is already in the correct format , if not it will try to convert the value to 1 or 0 and return that , otherwise it will just return the original value.
using System;
using CMSImportLibrary.Interfaces;
namespace CMSImportLibrary.FieldAdapters.DefaultFieldAdapters
{
public class BooleanFieldAdapter : IFieldAdapter
{
#region IFieldAdapter Members
public Guid DataTypeId
{
get { return new Guid("38b352c1-e9f8-4fd8-9324-9a2eab06d97a"); }
}
public object Parse(object value)
{
if (!(value.Equals("0") || value.Equals("1")))
{
bool boolValue = false;
if (bool.TryParse(value.ToString(), out boolValue))
{
return boolValue ? 1 : 0;
}
}
return value;
}
#endregion
}
}
Now when we run the import again it will just import the data without any errors, just by adding a few lines of code, isn’t that powerful?
Now that we have this mechanism we can also use it to modify data during the import. Let’s say we import a piece of content from an old site that contains an image tag. This will just run fine but when you have a reference to an image on your old site and you delete that old site all the references to the images are dead. FieldAdapters can help solve this issue by inspecting the text, extract the image tags, import these images into the media library and update the image tag with a reference to the media item. This will really help keep your site consistent. The same applies for Upload fields.
All FieldAdapters that fix errors (Like the BooleanFieldAdapter) will be included into the free version of CMSImport. FieldAdapters that helps you updating the content will only be included in the PRO version of CMSImport. And again you can also create your own FieldAdapters, free for both versions.
This will be the major feature of the V1.1 release of CMSImport. Please let me know what you think about this feature.
With Taskscheduler you can schedule url's/pages to be executed on a certain date and time. It’s a simplified version of the Windows task scheduler, build on top of the Umbraco scheduler functionality. If you’ve used CMSImport PRO, the package should look familiar because TaskScheduler is based on the scheduled import functionality of CMSImport PRO. When you installed the package and browse to the developer section you’ll notice the new Scheduled Tasks tree. From here you can create new Scheduled tasks, or browse to existing ones..:57 (GMT Daylight Time, UTC+01:00) | http://www.richardsoeteman.net/default,month,2010-04.aspx | CC-MAIN-2017-30 | refinedweb | 889 | 62.27 |
See Also edit
- A brief introduction to closures and continuations for event-based programming
- The title says it all.
- Emulating Closures in Tcl
- Simple Closures and Objects
- Playing Scheme
- sproc
- AMG: I'm pretty sure it provides closures.
- stowroutine, by PYK
- Procedures that get their own namespaces to play in.
- a collection of Tcl utilities
, by The Computer Architecture Group at the University of Heidelberg
- Includes a closure package.
Further Reading edit
Description editAlthough closures are closely associated with lexical scoping, that's more of an artifact of the languages that currently implement them than of some intrinsic relationship between the two things.
A Tcl Chatroom Discussion edit
- dkf
- Aliases are sort-of poor-mans closures. If we had real closures, we'd use them.
- suchenwi
- What prevents us from having them?
- dkf
- Lifespan issues mainly.
- am
- Why are aliases not closures - sorry, I think I have asked this before, but I do not fully grasp the concept of a closure
- dkf
- If we could be sure that the closure would go away as soon as it was no longer needed, they'd be trivial to add. A closure is really a piece of stack frame that is not on the stack. Or something like that. (The really strange things are continuations, but we're not dealing with those now.) Now it would be pretty easy to create a new closure object and commands to manipulate that, but ensuring that it doesn't go away at the wrong moment is not entirely trivial.
- suchenwi
- Could static variables be called atomar closures? I meant in the sense that they're local to a function, but persistent between calls.
- dkf
- C's static variables? Sort of. Not that they're exactly that. Closures are really a bit antithetical to C anyway.
- dkf
- However, I could envision a closure/stack-frame object that you'd access through upvar A proper closure keeps track of all enclosing stack frames, but that's probably more than is needed for most purposes. Then you could also store the object as an argument to the proc using aliases...
Misc editglennj: It took me a while to figure out how aliases could work like closures in the above discussion. I think I came up with an example: a procedure returns the number of times it's been invoked:
# the first time, send "0" to the aliased proc interp alias {} countMe {} _countMe 0 proc _countMe {count} { # for the next invocation, reset the alias interp alias {} countMe {} _countMe [incr count] return $count } puts [countMe] ;# ==> 1 puts [countMe] ;# ==> 2 puts [countMe] ;# ==> 3
Todd Coram:While playing with PostgreSQL, I got tired of passing around the connection id to each postgres tcl command (plus there was some other contextual info I wanted to keep around with each connection).Objectifying the postgres interface seemed over-kill and keeping state in a single namespace prevented me from keeping more than one database connection open at a time. I could have used the classic objectifying technique of keeping the instance info in array, but this felt clumsy. I could have curried the connection id to postgres commands, but that felt too restricting.Closures are neat because they give you a way to let functions carry a bit of state with it. Tcl Namespaces give you most of what you need, but you start to bleed into object land when you try to create more than one exclusive set of variables.So, thus was born this late night hacked attempt at emulating closures in Tcl:
# Create a proc named 'name' that will create a closure over the supplied # 'variables' definition for the 'lambda_proc'. Any supplied variables in # 'arglist' can be used to initialize 'variables' during the closure # definition. # proc make-closure-proc {name arglist variables lambda_proc} { set invoke_context [uplevel namespace current] set name_context ${invoke_context}::$name # Create a namespace called $name_context to hold auto_cnt # namespace eval $name_context { if {![info exists auto_cnt]} { variable auto_cnt -1} } # Now, build a proc in invocation context that will create # closures. We do this by substituting all of the passed # parameters (name, arglist, variables, lambda_proc) and the # $name_context. # # The resulting proc will: # 1. Accept $arglist as initializers for the closures. # 2. Create a unique closure_name from the auto_cnt variable. # 3. Create a namespace for the closure. # 4. Evaluate the $variables (optionally evaluating them with # $arglist). # 5. Create an alias called 'dispatch' for the lambda_proc. # 6. Return the alias. # namespace eval $invoke_context \ [subst -nocommands -nobackslashes { proc $name {$arglist} { set closure_name \ ${name_context}::$name[incr ${name_context}::auto_cnt] eval [subst { namespace eval [set closure_name] { $variables } }] namespace eval [set closure_name] { # Curry a dispatcher for the lambda_proc. # curry [namespace current]::dispatch [$lambda_proc] } return [set closure_name]::dispatch} }] } proc delete-closure {name} { namespace delete [namespace qualifiers $name] }I used a curry proc to create the dispatcher (I really don't create a curry and perhaps namespace code could accomplish a similiar thing, but I had a curry proc handy, so there):
proc curry {new args} { uplevel [list interp alias {} $new {}] $args }And a lambda proc to pass to the make-closure-proc:
proc lambda {arglst body} { set level [info level 0] set name [string map {\n _ \t _ \" _ " " _ \; _ $ _ : _ \{ _ \} _ \[ _ \] _} $level] set invoke_context [uplevel namespace current] proc ${invoke_context}::$name $arglst $body return ${invoke_context}::$name }Here is a (contrived) example of how to create and use the closures:
make-closure-proc make-logputs {_level _filename} { variable fd [open $_filename w] variable filename $_filename variable level $_level } { lambda {cmd {str ""}} { variable fd; variable filename; variable level switch -- $cmd { puts { puts "Writing ($level to $filename) $str" puts $fd "([clock format [clock seconds]] - $level) $str" } close { close $fd } } } } set info [make-logputs INFO info.out] set warn [make-logputs WARN warn.out] $info puts "Some info: hello world" $info puts "blech" $warn puts "You have been warned!" $info close $warn close delete-closure $info delete-closure $warn
GN There is a strong relation between objects and closures. a classical paper is from Uday Reddy "Objects as closures: abstract semantics of object-oriented languages", who defines objects as an "message environment" (binding messages to methods) with an hidden local environment (binding instance variables to values).This is pretty close to the notion of objects in XOTcl; the example above can be written much simpler with XOTcl (certainly with other oo languages as well):
package require XOTcl; namespace import -force xotcl::* Class Logger -parameter {level filename} Logger instproc init {} { my instvar fd filename set fd [open $filename w] } Logger instproc puts {str} { my instvar level filename fd puts "Writing ($level to $filename) $str" puts $fd "([clock format [clock seconds]] - $level) $str" } Logger instproc close {} { my instvar fd close $fd } set info [Logger new -level INFO -filename info.out] set warn [Logger new -level WARN -filename warn.out] $info puts "Some info: hello world" $info puts "blech" $warn puts "You have been warned!" $info close $warn close $info destroy $warn destroy
TV Isn't closure like in physics where you'd have a mathematical construct which is 'closed', which is usually pretty darn hard and often quite useless except probably in some essential fundamental cases.DKF: That's essentially unrelated. (And that's a maths/topology concept which physics has borrowed.)
See custom curry and the references there for an explanation of curry and currying function.
RS asks: Could one say the following are (rudimentary) examples of closures?1. Default arguments (in danger to be overwritten by caller);
proc foo {a b {c 1} {d 2} {e 3}} {...}2. Name-value map in an explicit argument
set closure [list c 1 d 2 e 3] ... proc bar {a b closure} { foreach {name value} $closure {set $name $value} ... }3. Closure values passed in over an alias:
proc _grill {c d e a b} {...} ... interp alias {} grill {} _grill 1 2 3
Zarutians first attempt at closures:
package require Tcl 8.4 proc closure_var args { set varname [lindex $args 0] set value [lindex $args 1] upvar $varname breyta set breyta $value trace remove variable breyta {write} update_closure_var ; # to prevent multiple trace clones trace add variable breyta {write} update_closure_var } proc update_closure_var {varname1 varname2 op} { if {$varname2 != ""} { set varname "[set varname1]([set varname2])" } else { set varname $varname1 } upvar $varname" set blu 234 }The above implemention doesn't handle that when other sub-procs upvar a closure_var . The next implemention of closures from Zarutian will have that fixed.Zarutians second attempt at closures
package require Tcl 8.4 proc closure_var args { set varname [lindex $args 0] set value [lindex $args 1] upvar $varname breyta set breyta $value trace remove variable breyta {write} [list update_closure_var $varname]; # to prevent multiple trace clones trace add variable breyta {write} [list update_closure_var $varname] } proc update_closure_var {originalVarname varname1 varname2 op} { if {$varname2 != ""} { set varname "[set varname1]([set varname2])" } else { set varname $varname1 } upvar 1 $originalVarname" debug $temp decr blu } proc decr {varname {delta 1}} { upvar 1 $varname var set var [expr $var - $delta] }This implemention should work fine with other sub-procs upvaring closure_vars. But these two implementions have one catch/issue: namely that every previus value of a closure_var is saved too. I am trieing find out how it is possible to get the old value of a variable before it is updated to the new value so I can fix that catch/issueJust to be sure: isn't a closure just a procedure with some state saved with it, no?
SS 2004-12-30: For the Tcl semantic, lexical binding is hard because it's not possible to tell from the source code what's a reference to a variable and what is not. Still it's possible to capture the context of a lambda's creation saving the current stack frame, thus allowing for real closures (procedures where if some variable can't be resolved in the local context, will try to access the stack frame that was active at the procedure creation time). Because of the way Tcl works and the fact it's so dynamic I'm not sure closures may significantly help Tcl programming, but when they are used as objects. It's a more interesting addition to have an object system with garbage collection. Because in most Tcl objects systems objects are "callable", like in [$o a b c], objects can be used to do most of the things you may like to do with closures, they are very similar to procedures but can take/alter their internal state. Of course this is possible to do even with OOP systems not having garbage collection, but the programming style that closures make possible is often about to capture some information to semplify/specialize the next uses of a given procedure, it's hard to think at this programming style as comfortable if you have to clean by hand the objects.
Zarutian 2005-01-02:Append this to my second attempt at closures:
proc closure {name args body} { set locals [uplevel 1 [list info locals]] foreach loco $locals { set body "[list closure_var $loco [uplevel 1 [list set $loco]]]\n[set body]" } proc $name $args $body }and I think you have got something like that SS described above.
SS 2005-01-03: Yeah this is a smart idea, to capture the context. Still there are a few things to fix, and many other things that we can't fix at all. What should be fixed is that this way you set the locals variables even if the name is the same as one of the procedure arguments, that's not correct: if there is an argument with that name, the symbol should be bound to it. Second, in real closures, many closures can *share* the environment, and can modify it (and every other closure bound to the same external variables will see the change). We can't get that far with Tcl of course, but still your exercise is very interesting and valuable IMHO.DKF: I use something very much like closures in my oo2 code. Basically, dict's update and with (together with some wrapping scripts) allow for closure-like behaviour very easily. The complexity is that the closure is actually stored in a "global" variable, but as long as you ignore the man behind the curtain, you're OK... ;^)Zarutian: As I understand it Tcl procedure's enviroment is three leveled: global, local to procedure's namespace, local to procedure's level/callstack.Then when variable lookup is performed (either because of Tcl's seventh substitution rule or procedure set is invoked) inside a procedure's body (the procedure was called) the interpreter first looks for the variable in local callstack scope then in procedure's namespace (if that variable name was marked by calling the procedure 'variable') and at last in the global namespace (likewise if the variable name was marked by calling the procedure 'global').Where other scripting languages like Lua and Lisp variants use linked tables/hashmaps/dictionaries and lookup the variable's value in the parent table of the current variable|value binding table if not found in current until the top most variable|value binding table is reached. (Hmm... the preceeding sentence may be unclear because of my lack of skill writing English)Here above I have descriped two possible ways to look up values for variables. So I ask what are the 'pros' and 'cons' of each?In my opinion I think the latter method enables more flexibility of variable lookup for value. {IS: Að mínu áliti held ég að síðari aðferðin gefi kost á meiri liðleika til að fletta upp gildi breytu.}
SS 2005-02-23:This is a proposal for closures I made in comp.lang.tcl:From time to time there is this discussion about adding closures to Tcl, but usually the idea is to make they similar to languages like Scheme, i.e. closures with lexical scoping. My opinion is that this is very hard to do with Tcl, and even not in the spirit of the language. In a Tcl program, what part of a procedure body is a variable is not defined until execution, for example:
set a 10 closure {x} { incr a }Then I define incr to be like puts, and a is no longer a variable. It was already suggested that in Tcl closures should not have any kind of creation-time resolution rule, but that the context where they are defined should be captured as a whole, and used when the closure is running to resolve "unbound symbols" (that are better referred as variables and procedures not otherwise defined during execution in Tcl slang). Still there is the problem that to similuate the lexical scoping you have to take *references* to the shared environment, so that:
set a 10 set foo [closure {x} { incr a $x }] set bar [closure {x} { incr a $x }] $foo 1;# -> 11 $bar 1;# -> 12foo and bar will share the same 'a'.I think this is a all to complex and UnTclish, so I tried to design a new semantic for closures.The semantic is based on a single command, closure, that can set/get closure variables in the scope of the current procedure, together with a minimal change in proc and lambda (I know we don't have lambda... but still there is a way Tcl users already think about it and should change).Basically, to set a closure variable, there is to write the following command:
closure set x 10This will set $x inside the closure of the current procedure. This $x will be persistent accross different calls of this procedure, and all this environment will be destroied once the procedure itself is destroied. The procedure can test for the existence of a closure variable with [closure exists x], can get the value with [closure get x] and so on.The change required to the proc is that it can take an optional further argument, a Tcl list of key/value pairs used to inizialize the closure at procedure creation time.so:
proc foo {} { .... } {x 10 y 20}will create the procedure foo with x=10 and y=20 inside the closure. The same for lambda.The following is an example of procedure that returns a progressive integer number every time it's called:
proc counter {} { if {![closure exists x]} { set x 0 } set x [closure get x] closure set x [expr $x+1] return $x }Of course it's better to use the optional argument to proc and write it as:
proc counter {} { set x [closure get x] closure set x [expr $x+1] return $x } {x 0}Of course for this to be very useful, lambda it's needed. This version of lambda, like proc, should accept the optional argument to initialize the closure. This is an example:
proc createAdder {x} { lamba {y} {expr $y+[closure get $x]} [list x $x] } set f [createAdder 5] $f 10 ;# -> 15I think that this design can do everything lexical scoping is able to do, but with a command-based interface that plays better with Tcl.This kind of closures will be added into the Jim interpreter, a small footprint Tcl interpreter I'm writing. This interpreter is already working and I'll be happy to send a preview tar.gz to interested people (the license is the APACHE2, so it's possible to use Jim in commercial projects if needed).Regards,
Salvatoreand then I replyed to myself with this message:I forgot to include a couple of points.The closure command can also access closures of external procedures:
[closure in $procName get/set x ...] and so on.This makes possible to share the environment if really needed. Example:
proc createAdder {x} { set a [lamba {y} {expr $y+[closure get $x]} [list x $x]] set b [lamba {incr} {closure in $a set x $incr} [list a $a]] list $a $b }This returns one closure to add and one to change the increment performed by the first closure.Also it is worth to note that this way to do closures don't play well with functions as values nor with lambas based on auto expansion, because full closures need to be able to modify their environment so they can not be immutable values.Ciao,
Salvatore
NEM offers the following as a simple closure-like thing:
proc closure {name arglist body} { if {![string match ::* $name]} { # Not fully qualified set ns [uplevel 1 namespace current] set name ${ns}::$name } else { set name $name } set sname [namespace tail $name] # Just create a proc as usual, but a namespace along with it namespace eval $name [list proc $sname $arglist $body] interp alias {} $name {} ${name}::$sname }and a test:
closure make-counter {start} { variable id if {![info exists id]} { set id 0 } incr id closure counter-$id {{amount 1}} [string map [list %S $start] { variable counter if {![info exists counter]} { set counter %S } incr counter $amount }] return [namespace current]::counter-$id }Could do with a bit of tarting up, and it's not as powerful as closures in Scheme, which get a lot of their power from lexical scoping. Still, it goes quite a long way, I think. Oh, and you can do drop-dead simple ensembles too:
(tile) 57 % closure MyEnsemble {method args} { closure say {message} { puts "Say: $message" } closure sing {message} { puts "Sing: $message!" } $method {*}$args } ::::MyEnsemble (tile) 58 % MyEnsemble wrong # args: should be "::::MyEnsemble::MyEnsemble method ..." (tile) 59 % MyEnsemble say Hello Say: Hello (tile) 60 % MyEnsemble sing "Tra-la-la" Sing: Tra-la-la!
Sarnold 2010-02-05: Here is my own implementation of simple closures. To use them you will have to store them in a variable and pass its name to a custom applyc (apply-closure) proc, which saves the environment in the variable holding the closure. The closure proc creates a closure (a list) by passing to it a variable list for the environment. (this is AFAIK the way you create closures in PHP)
package require Tcl 8.5 proc closure {arglist args} { # returns a list of 4 elements: # - the argument list of apply # - the closure var list # - the closure vars initial values (to be updated by applyc) # - the body switch -- [llength $args] { 1 {return [list $arglist "" "" [lindex $args 0]]} 2 {lassign $args varlist body} default {error "bad arguments to proc closure"} } if {[llength $varlist]==0} {return [list $arglist "" "" $body]} foreach var $varlist { lappend data [uplevel 1 set $var] set body "upvar 1 closure_$var $var\n$body" } list $arglist $varlist $data $body } proc applyc {name args} { upvar 1 $name _closure lassign $_closure arglist varlist data body foreach var $varlist val $data { set closure_$var $val } # call the lambda set res [apply [list $arglist $body] {*}$args] # variable updates are saved in local vars foreach var $varlist { # retrieve them lappend values [set closure_$var] } # save them as third element of _closure lset _closure 2 $values set res } set x 1 set accu [closure {num} {x} {incr x $num}] puts $accu puts [applyc accu 2] puts [applyc accu 3];#should increase value proc lam {lam} {applyc lam 2} puts [lam $accu] puts [lam $accu];#should print the sameNEM 2010-02-06: This is essentially how dictutils works, except that in that implementation the lambda expression and the variable environment (a dict) are separate arguments to the apply command. Both have the nice property that updates are only committed to the environment if no error is thrown in the body of the lambda. Both however need a little work to ensure that the lambda expression can be byte-compiled properly.Thinking some more, a minimal closure construct that does the job and should be properly byte-compiled (but still not entirely optimised) is the following:
proc closure {env params body} { set ns [uplevel 1 { namespace current }] set body [list with __scope__ $body] set lambda [list $params $body $ns] return [list $env $lambda] } proc with {scopeVar body} { uplevel 1 [list upvar 1 $scopeVar __scope__] uplevel 1 [list dict with __scope__ $body] } proc applyc {closureVar args} { upvar 1 $closureVar closure lassign $closure __scope__ lambda try { apply $lambda {*}$args } on ok result { set closure [list $__scope__ $lambda]; return $result } } # EXAMPLE set counter [closure {i 0} {{n 1}} { incr i $n }] applyc counter ;# -> 1 applyc counter ;# -> 2 applyc counter 4 ;# -> 6 etc | http://wiki.tcl.tk/3330?redir=13631 | CC-MAIN-2016-44 | refinedweb | 3,688 | 53.55 |
6593/how-to-connect-two-instances-of-hyperledger-fabric
I have an instance of Hyperledger Fabric running on Ubuntu and another running on Windows. What changes i have to make on both machines so that these two share their public ledger together? And where do i need to make these changes?
Before getting on with your question, let me first tell you about the Hyperledger Fabric network entities:
Network peer - used to maintain chaincodes (smart contracts), keeps replicated copy of the the ledger and most recent status update.
Ordering service/ Consensus - key objective of it is to specify total order on incoming transactions and cut the block, which will be distributed among all peers.
In your case, I'd assume two instances simply means that you have two different organizations. So what you need to do is to:
Define/decide where you would like to run ordering service which will take care of transactions order.
Define a channel with two organizations
In configtx.yaml you need to specify the address of the ordering service.
Create a channel to generate genesis block
Join all peers for both organization using the genesis block
When you create a channel, you will ...READ MORE
you can use proof of Authority consensus ...READ MORE
In a Dev environment, you can first ...READ MORE
You need to map ~/.composer/cards of your Docker host ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
I know it is a bit late ...READ MORE
Best practice would be to leverage an ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/6593/how-to-connect-two-instances-of-hyperledger-fabric?show=6596 | CC-MAIN-2019-51 | refinedweb | 289 | 66.74 |
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int oflag,...);
int open64(const char *pathname, int oflag,...);
DESCRIPTION
The
The
The
The file offset used to mark the current position within the file is set to the beginning of the file.
The file status flags and file access modes of the open file description are set according to the value of oflag. The value of oflag is the bitwise inclusive-OR of values from the following lists.
Applications must specify exactly one of the following three values (file access modes) in the value of oflag:
- O_RDONLY
Open for reading only.
- O_WRONLY
Open for writing only.
- O_RDWR
Open for both reading and writing.
Any combination of the following file status flags may be specified as well:
- O_APPEND
If set, the file offset is set to the end of the file prior to each write.
- O_ASYNC
If the specified path refers to a communications device, enables delivery of SIGIO signals when data is available on the device. Refer to /dev/com for more information. This flag is ignored for other types of file.
- O_BINARY
If set, causes the file to be opened in binary mode. Refer to PORTING ISSUES for more information.
- O_CREAT
If the file exists, this flag has no effect except as noted under O_EXCL. Otherwise, the file is created; the user ID of the file is set to the effective user ID of the process; the group ID is set to the effective group ID of the process; and the access permission bits of the file mode are set to the value of the third argument taken as type mode_t modified as follows: a bitwise-AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. This,. Refer to
chmod(), umask(), and struct stat for more information on the mode bits. Upon successful completion, open()marks for update the st_atime, st_ctime and st_mtime fields of the file.
- O_EXCL
If O_CREAT and O_EXCL are set,
open()fails if the file exists. The check for the existence of the file and the creation of the file if it does not exists is atomic with respect to other processes executing open()naming the same file name in the same directory with O_EXCL and O_CREAT set. If O_CREAT is not set, the effect is undefined.
- O_LARGEFILE
Sets the file descriptor to indicate a large file aware application.
- O_NOCTTY
If set and the specified path refers to a terminal device,
open()does not cause the terminal to become the controlling terminal for the process. This flag is currently ignored by the NuTCRACKER Platform.
- O_NONBLOCK
When opening a FIFO with O_RDONLY or O_WRONLY set:
- If O_NONBLOCK is set, then an
open()for reading only returns without delay, and an open()for writing only returns an error if no process currently has the file open for reading. If O_NONBLOCK is clear, then an open()for reading only blocks the calling thread until a thread opens the file for writing, and an open()for writing only blocks the calling thread until a thread opens the file for reading.
When opening a device that supports non-blocking opens (for example, communications ports):
- If O_NONBLOCK is set, the
open()function returns without blocking for the device to be ready or available. Subsequent behavior of the device is device-specific. If O_NONBLOCK is clear, the open()function blocks the calling thread until the device is ready or available before returning.
Otherwise, the behavior of O_NONBLOCK is unspecified.
- O_RANDOM
If set, indicates that the file is accessed randomly. The system can use this as a hint to optimize file caching. This corresponds to the Win32 flag FILE_FLAG_RANDOM_ACCESS.
- O_SEQUENTIAL
If set, indicates that the file is accessed sequentially from beginning to end. The system can use this as a hint to optimize file caching. This corresponds to the Win32 flag FILE_FLAG_SEQUENTIAL_SCAN.
- O_SHORT_LIVED
If set, indicates that the file is being used for temporary storage. File systems try to keep all of the file in memory for quicker access rather than flushing the data back to mass storage. This corresponds to the Win32 flag FILE_ATTRIBUTE_TEMPORARY.
- O_SYNC
If set, write I/O operations on the file descriptor complete only when the data has actually be written to the mass storage device.
- O_TEMPORARY
If set, the file is deleted when the last file descriptor referring to it is closed. This corresponds to the Win32 flag FILE_FLAG_DELETE_ON_CLOSE.
- O_TEXT
If set, causes the file to be opened in text mode. Refer to PORTING ISSUES for more information.
- O_TRUNC
If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, its length is truncated to 0 and the mode and owner are unchanged. It has no affect on FIFO special files or terminal device files. Its affect on other file types is undefined. The result of using O_TRUNC with O_RDONLY is undefined.
PARAMETERS
- pathname
Is the name of the file to open.
- oflag
Is the bitwise inclusive-OR of the file access modes and file status flags, as defined in the DESCRIPTION section.
- mode
Specifies what permissions the file has when it is created.
RETURN VALUES
If successful,
- EACCES
The file does not exist and the parent directory denies write permission of the file to be created.
A component of the path name prefix denies search permission.
The file exists and the permissions specified by oflag are denied.
O_TRUNC is specified and write permission is denied.
- EEXIST
O_CREAT and O_EXCL are set, and the named file exists.
- EFAULT
The pathname parameter is not a valid pointer.
- EINTR
The call was interrupted by a signal.
- EINVAL
The oflag parameter contains invalid flags, or flags specified in oflag are invalid for pathname.
- EISDIR
The oflag parameter specifies O_WRONLY or O_RDWR and the named file is a directory.
- EMFILE
This process is currently using too many open file descriptors.
- ENAMETOOLONG
The pathname parameter string length exceeds PATH_MAX or a path name component is longer than NAME_MAX.
- ENFILE
Too many files are currently open within the system.
- ENOENT
O_CREAT is not set and the named file does not exist.
O_CREAT is set and either the pathname prefix does not exist or the pathname parameter points to an empty string.
- ENOMEM
The system is unable to allocate memory for the descriptor.
- ENOSPC
O_CREAT is set, and the directory that would contain the file cannot be extended.
- ENOTDIR
A component of the pathname prefix is not a directory.
- ENXIO
O_NONBLOCK is set, the named file is a FIFO, O_WRONLY is set, and no process has the file open for reading.
- EOVERFLOW
The named file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
- EROFS
The named file resides on a read-only file system; if the file does not exist, either O_WRONLY, O_RDWR, O_CREAT, or O_TRUNC is set in the oflag parameter.
CONFORMANCE
POSIX.1 (1996), with exceptions.
MULTITHREAD SAFETY LEVEL
Async-signal-safe.
PORTING ISSUES
The NuTCRACKER Platform supports
Refer to Security and File Management in the Windows Concepts chapter of the MKS Toolkit UNIX to Windows Porting Guide for a detailed discussion of file security and file handling issues, such as text and binary mode.
The test which causes the EOVERFLOW error condition to
be returned can be disabled by using the
AVAILABILITY
MKS Toolkit for Professional Developers
MKS Toolkit for Enterprise Developers
MKS Toolkit for Enterprise Developers 64-Bit Edition
SEE ALSO
- Functions:
chmod(), close(), creat(), dup(), dup2(), fcntl(), fpathconf(), fstat(), lseek(), read(), select(), stat(), umask(), write()
- Miscellaneous:
- lf64, struct stat
MKS Toolkit 9.2 Documentation Build 16. | http://www.mkssoftware.com/docs/man3/open.3.asp | crawl-001 | refinedweb | 1,285 | 63.8 |
I am trying to build a function that dynamically deletes and orders rows based on the column numbers it is passed in. So far I have defined the following:
import csv
def delete(rows_to_keep):
with open('file.csv','r') as source:
rdr= csv.reader( source )
with open('reordered.csv','w') as result:
wtr= csv.writer( result, delimiter=',', lineterminator='\n' )
for r in rdr:
wtr.writerow( ... )
rows_to_keep = [1, 3, 5, 6]
delete()
... = r[1], r[3], r[5], r[6]
wtr.writerow( r[1], r[3], r[5], r[6] )
Use
rows_to_keep in a loop to build a list with the new sequence of values you want to write out. Then pass that list to
writerow(); it doesn't accept an arbitrary number of arguments, so you must call it with a list one way or another. Something like this:
rows_to_keep = [1, 3, 5, 6] ... for row in rdr: newrow = list() for n in rows_to_keep: newrow.append(row[n]) wtr.writerow(newrow)
PS. Or use a comprehension if you prefer. Same result (if used correctly).
for row in rdr: newrow = [row[n] for n in rows_to_keep] wrt.writerow(newrow) | https://codedump.io/share/bplPQKMsHNUh/1/dynamic-arguments-in-python-write | CC-MAIN-2018-09 | refinedweb | 188 | 77.64 |
got most of this too work, i talked to my teacher and he gave me some hints but i cannot get it full. The idea is to get the program to count specifically how many "a"'s there continueing through all the 26 letters. I cannot figure out exactly out how to get that part to work. I want to use the function "tolower" to get the letters all lower case when going into the program. we just need to count the number of each specific letter not distinguish between upper and lower case. A file is being read into a file.
here the code
Code:#include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; void printArray(const int [], int); int main () { unsigned int strlength; int alphabet[26] = {0}; int charnum = 0; char fileName[30]; char str[26]; char letter = 'a'; cout << "Enter the name of the input file"; // opens file cin >> fileName; ifstream infile(fileName); if ( !infile ) { cerr << "Cannot open the input file .\n "; // error occurs if bad file name return (1); } while ((infile >> str) && (*str != EOF)) // continues until end of file { //counts char without spaces string line; getline(infile, line); int lentemp = line.size(); charnum += lentemp; } cout << "The number of char without spaces is " << charnum << endl; while ((infile >> str) && (*str != EOF))//counting the number of each letter { if (97 <= (static_cast<int>(tolower('a'))) <= 122) alphabet[static_cast<int>('a') - 97]++; } printArray(alphabet, 26 ); // prints historgram for frequency of letter infile.close (); for (int i = 1; i <= 26; i++) { cout << "alpha[ " << i << "] = " << alphabet[i] << endl; } return ( 0 ); } void printArray(const int a[], int size) // function for historgram { for (int i= 0; i < size; i++) { if ( i % 20 == 0 ) cout << endl; cout << setw(2) << a[i]; } } Thats the entire program the part im having problems with isalphabet is an array that should count all the letters from a to z and count the occurance of each.alphabet is an array that should count all the letters from a to z and count the occurance of each.Code:while ((infile >> str) && (*str != EOF))//counting the number of each letter { if (97 <= (static_cast<int>(tolower('a'))) <= 122) alphabet[static_cast<int>('a') - 97]++; }
please help, im very confused
thanks very much
goo | http://cboard.cprogramming.com/cplusplus-programming/64798-help-letter-counting-part-program.html | CC-MAIN-2014-35 | refinedweb | 370 | 66.98 |
Question
The Insurance Institute for Highway Safety crashed the 2010 Ford Fusion four times at 5 miles per hour. The cost of repair for each of the four crashes are as follows:
Compute the range, sample variance, and sample standard deviation cost of repair.
.png)
.png)
Answer to relevant QuestionsThe following data represent the monthly cell phone bill for my wife's phone for six randomly selected months: Compute the range, sample variance, and sample standard deviation phone bill. The following data represent the pulse rates (beats per minute) of nine students enrolled in a section of Sullivan’s course in Introductory Statistics. Treat the nine students as a population. Student ...You have received a year- end bonus of $5000. You decide to invest the money in the stock market and have narrowed your investment options down to two mutual funds. The following data represent the historical quarterly rates ...Lawrence Summers (former secretary of the treasury and former president of Harvard) infamously claimed that women have a lower standard deviation IQ than men. He went on to suggest that this was a potential explanation as to ...The data set on the left represents the annual rate of return (in percent) of eight randomly sampled bond mutual funds, and the data set on the right represents the annual rate of return (in percent) of eight randomly ...
Post your question | http://www.solutioninn.com/the-insurance-institute-for-highway-safety-crashed-the-2010-ford-fusion | CC-MAIN-2017-04 | refinedweb | 228 | 52.39 |
Difference between revisions of "DIP82"
Latest revision as of 04:57, 27 September 2015
Abstract
Provides a way to handle unittest blocks inside of templates which works with ddoc without compiling the unittest blocks into each instantiation.
Rationale
At present, unittest blocks inside of a templated type are compiled into every instantation, which only works with tests that are generic, which most tests aren't, and it almost never works with examples and thus doesn't work for ddoc-ed unittest blocks.
So, at present, ddoc-ed unittest blocks cannot be used inside of templated types, and most unittest blocks for templated types cannot go inside of the types that they test, because they end up being compiled into every template instantiation, which means that they are compiled and run far more times than necessary, and they get compiled into and run in every program that instantiates the template instead of just with the module in which they're defined. The result of this is that most unittest blocks that test templated types need to be put outside of the template, making it so that we lose out on ddoc-ed unittest blocks and making the unit tests far less maintainable, because they're not right after the functions that they're testing like they would normally be (and of course, because the examples aren't inside of ddoc-ed unittest blocks, the risk of them being incorrect increases).
To be able to have ddoc-ed unittest blocks inside of templates as well as have all of the tests right next to the functions that they're testing, we need a way to declare unittest blocks inside of a template such that they exist regardless of whether the template is instantiated and such that they are only compiled once regardless of how many times the template is instantiated.
Description
This DIP proposes adding the concept of a static unittest block.
static unittest { // my test code... }
This would only apply inside of templates (outside of templates, a static unittest block would be identical to a normal one). Inside of a template, a static unittest block is a unittest block which is compiled in regardless of whether the template is instantiated, and it is not considered to be part of the template as far as compilation goes aside from the fact that it is scoped within the template. If it has a ddoc comment on it, it will then be used as an example in the preceding ddoc comment as would normally occur.
The result of this is that a static unittest block can have non-generic tests of the template which aren't compiled into each instantation of the template. It means that the unittest blocks will be compiled into the unittest build of the module that they're in, not into the code that instantiates the template. It also means that if they instantiate the template (as they would normally do if they're testing it), then that template will be instantiated in the unittest build of that module even if nothing else in the code references that template. So, the programmer will not have to put additional unittest blocks outside of the template to instantiate the template or to do any kind of testing on the template. All of the unittest blocks that test that template and/or test an example from the documentation of a symbol within the template can be internal to that template.
Non-static unittest blocks will function exactly as they have, even if they are inside of a template, meaning that anyone who wants a unittest block to be compiled into each instantiation of a template and run for each instantiation of the template can just declare a non-static unittest block inside the template as they have done up until now. So, the programmer then has control over whether a given unittest block is compiled into each instantiaton of the template (non-static unittest) or whether it's compiled exactly once inside of the module that it's declared in (static unittest).
Take the following code:
import std.stdio; /++ +/ struct S(T) { public: /++ Returns the value of foo. +/ @property T foo() { return _foo; } /// unittest { writeln("Testing foo in an example"); assert(S!int(5).foo == 5); assert(S!string("hello world").foo == "hello world"); assert(S!bool(true).foo == true); } unittest { writefln("Testing foo"); assert(S!dchar('W').foo == 'W'); } unittest { writefln("Testing %s.foo", S.stringof); assert(S(T.init).foo == T.init); } private: T _foo; }
If this code is compiled with -unittest -main and run, it won't print anything, because nothing has instantiated S outside of S. If this unittest block were added after the template
unittest { S!int s; }
then the unit test build would print
Testing foo in an example Testing foo Testing S!int.foo Testing foo in an example Testing foo Testing S!string.foo Testing foo in an example Testing foo Testing S!bool.foo Testing foo in an example Testing foo Testing S!dchar.foo
Because S has four different instantiations in this code (int, string, bool, and dchar), all three of the unittest blocks are compiled and run four times each.
If this DIP were implemented, and static were added to two of the unittest blocks like so
import std.stdio; /++ +/ struct S(T) { public: /++ Returns the value of foo. +/ @property T foo() { return _foo; } /// static unittest { writeln("Testing foo in an example"); assert(S!int(5).foo == 5); assert(S!string("hello world").foo == "hello world"); assert(S!bool(true).foo == true); } static unittest { writefln("Testing foo"); assert(S!dchar('W').foo == 'W'); } unittest { writefln("Testing %s.foo", S.stringof); assert(S(T.init).foo == T.init); } private: T _foo; } unittest { }
then instead of nothing being printed, something like this would print
Testing foo in an example Testing foo Testing S!int.foo Testing S!string.foo Testing S!bool.foo Testing S!dchar.foo
This exact ordering assumes that the static unittest blocks are run prior to any of the instantiations' unittest blocks being run, which is probably best but doesn't necessarily matter. What matters is that the static unittest blocks are now compiled and run only once, and they are compiled in even though S has not been instantiated by any code outside of S - and of course, because the static unittest blocks instantiate S, the non-static unittest blocks inside of S get compiled and run for each instantiation. So, with this change, it's reasonable to use ddoc-ed unittest blocks inside of a templated type, and it's no longer necessary to put any unittest blocks outside of a templated type in order to test it.
While the primary gain here is with templated types, for consistency, it shouldn't matter whether a static unittest is inside of a templated type - just that it's inside of a template. A static unittest block should be compiled into the module that it's in whenever -unittest is used, regardless of whether the unittest block is inside of a type. All of these examples would result in the static unittest blocks being compiled exactly once whether the template is instantiated elsewhere or not:
template S(T) { struct S { //... } static unittest { writeln("I'm only compiled and run once!"); } }
template S(T) { struct S { //... static unittest { writeln("I'm only compiled and run once!"); } } }
template map(alias pred) //if(...) { auto map(R)(R range) //if(...) { //... } static unittest { writeln("I'm only compiled and run once!"); } }
Impact
With static unittest blocks, it becomes possible to put non-generic unit tests inside of templates, which will improve maintainability and allow us to have ddoc-ed unittest blocks for examples inside of templated types, whereas right now, we really can't. All of those unittest blocks end up outside of the templated type, and we're worse off for it. This DIP fixes that, and it fits in very well with how static is used elsewhere in the language. And because it only affects unittest blocks which are marked as static inside of templates, we don't lose the ability to have generic unittest blocks like we do now. Flexibility and power is increased without losing any flexibility or power. The increase in complexity to the language is very minor, and code that uses static unittest blocks will actually become simpler and easier to maintain. Several modules in Phobos would already benefit from this (e.g. std.container for its containers and std.datetime for its *Interval types) as would any code which declares a templated type.
This document has been placed in the Public Domain. | https://wiki.dlang.org/?title=DIP82&diff=6684&oldid=6682 | CC-MAIN-2019-43 | refinedweb | 1,444 | 59.03 |
Monday, we launched the Razor DotNetNuke Hackathon with a meeting of SEADUG (Seattle DotNetNuke User Group) held at Microsoft offices in beautiful downtown Bellevue.
For those of you proposing to write Razor “scripts” as part of the Hackathon, I have decided to write a series of short Tips and Tricks.
In this fourth post I will cover how you can go about extending the provided helpers to provide a simpler API for the scripts to consume.
The DotNetNukeWebPage class, which is the base class for all Razor scripts used in DotNetNuke has three additional properties.
1: Protected Friend Property Dnn As DnnHelper
2: Protected Friend Property Html As HtmlHelper
3: Protected Friend Property Url As UrlHelper
In this tip we are going to extend the Dnn property to add an extra method. The Dnn property is an instance of the DnnHelper class which is defined in the DotNetNuke.Web.Razor library.
1: Public Class DnnHelper
2:
3: Private _context As ModuleInstanceContext
4:
5: Public Sub New(ByVal context As ModuleInstanceContext)
6: _context = context
7: End Sub
8:
9: Public ReadOnly Property [Module] As ModuleInfo
10: Get
11: Return _context.Configuration
12: End Get
13: End Property
14:
15: Public ReadOnly Property Tab As TabInfo
16: Get
17: Return _context.PortalSettings.ActiveTab
18: End Get
19: End Property
20:
21: Public ReadOnly Property Portal As PortalSettings
22: Get
23: Return _context.PortalSettings
24: End Get
25: End Property
26:
27: Public ReadOnly Property User As UserInfo
28: Get
29: Return _context.PortalSettings.UserInfo
30: End Get
31: End Property
32:
33: End Class
Imagine that you want to write a script which lists all of the roles on the site. You could use the full DotNetNuke API in your Razor script as shown in Figure 3
There is nothing wrong with this – it works. But what if you could have a much simpler script to do the same task (Figure 4).
For beginner developers who are trying their hand at DotNetNuke development using the Razor Host module, this is much more intuitive. But GetRoles() is not a member of the DnnHelper class, and I don’t want to modify a core class. This is where the wonders of Extension methods comes in. Since C# 3 (or VB 9) which shipped with Visual Studio 2008, we have been able to add functionality to existing classes, without modifying the class directly.
In a separate project, I added a class DnnHelperExtensions, where I defined the following extension method (Figure 5).
1: public static class DnnHelperExtensions
2: {
3: public static List<String> GetRoles(this DnnHelper helper)
4: {
5: var controller = new RoleController();
6: var _roles = new List<String>(controller.GetRoleNames(
7: helper.Portal.PortalId
8: ));
9:
10: return _roles;
11: }
12: }
This method hides the DotNetNuke complexity from the scripter. We don’t need to worry about what namespace(s) to include in our script and we don’t care that GetRoleNames needs a PortalId as the helper method takes care of it.
There is one final step that we need to do to get this to work. We need to add a reference to the Helpers namespace in the web.config file that lives in the RazorModules folder.
1: <system.web.webPages.razor>
2: <pages pageBaseType="DotNetNuke.Web.Razor.DotNetNukeWebPage">
3: <namespaces>
4: <add namespace="Microsoft.Web.Helpers" />
5: <add namespace="WebMatrix.Data" />
6: <add namespace="DotNetNuke.Web.Razor.Helpers" />
7: </namespaces>
8: </pages>
9: </system.web.webPages.razor>
In the final release of the Razor Host Module, we will add the DotNetNuke.Web.Razor.Helpers namespace to the web.config included, and we will start to flesh out the DnnHelper class with some more intuitive methods.
However, if ever ever feel that something is missing you can create your own. Just make sure that all your helper Extension Methods are in the same namespace and all you will need to do is add the assembly to the bin folder, and they will just work.. | http://www.dnnsoftware.com/community-blog/cid/136303 | CC-MAIN-2018-26 | refinedweb | 661 | 62.07 |
We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values – root and extension.
Table of Contents
Getting File Extension in Python
Here is a simple program to get the file extension in Python.
import os # unpacking the tuple file_name, file_extension = os.path.splitext("/Users/pankaj/abc.txt") print(file_name) print(file_extension) print(os.path.splitext("/Users/pankaj/.bashrc")) print(os.path.splitext("/Users/pankaj/a.b/image.png"))
Output:
File Extension in Python
- In the first example, we are directly unpacking the tuple values to the two variables.
- Note that the .bashrc file has no extension. The dot is added to the file name to make it a hidden file.
- In the third example, there is a dot in the directory name.
Get File Extension using Pathlib Module
We can also use pathlib module to get the file extension. This module was introduced in Python 3.4 release.
>>> import pathlib >>> pathlib.Path("/Users/pankaj/abc.txt").suffix '.txt' >>> pathlib.Path("/Users/pankaj/.bashrc").suffix '' >>> pathlib.Path("/Users/pankaj/.bashrc") PosixPath('/Users/pankaj/.bashrc') >>> pathlib.Path("/Users/pankaj/a.b/abc.jpg").suffix '.jpg' >>>
Conclusion
It’s always better to use the standard methods to get the file extension. If you are already using the os module, then use the splitext() method. For the object-oriented approach, use the pathlib module. | https://www.journaldev.com/32081/get-file-extension-in-python | CC-MAIN-2021-17 | refinedweb | 235 | 51.44 |
69172/how-to-create-a-not-null-column-in-case-class-in-spark
Hi@Deepak,
In your test class you passed empid as string, that's why it shows nullable=true. So you have to import the below package.
import org.apache.spark.sql.types
You can use these kind of codes in your program.
df.withColumn("empid", $"empid".cast(IntegerType))
df.withColumn("username", $"username".cast(StringType))
You can select the column and apply ...READ MORE
spark do not have any concept of ...READ MORE
Yes, you can go ahead and write ...READ MORE
you can access task information using TaskContext:
import org.apache.spark.TaskContext
sc.parallelize(Seq[Int](), ...READ MORE
You can do it dynamically be setting ...READ MORE
Hey,
You can try this code to get ...READ MORE
Hi,
Paired RDD is a distributed collection of ...READ MORE
Hi,
If you have a file with id ...READ MORE
val coder: (Int => String) = v ...READ MORE
Hi,
In Spark, fill() function of DataFrameNaFunctions class is used to replace ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/69172/how-to-create-a-not-null-column-in-case-class-in-spark?show=69204 | CC-MAIN-2021-49 | refinedweb | 196 | 68.26 |
bsqldb man page
bsqldb — batch SQL script processor using DB-Library
Synopsis
- . Overrides -h.
- -t field_term
Specifies the field terminator. Default is two spaces (' '). Recognized escape sequences are tab ('\t'), carriage return ('\r'), newline ('\n'), and backslash ('\\').
- -v
Verbose mode, for more information about the DB-Library interaction. This also reports the result set metadata, including and return code. All verbose data are written to standard error (or -e), so as not to interfere with the data stream.
- -R pivot_description
Specify pivot trasformation. The format is ⟨down columns⟩ ⟨across columns⟩ ⟨function⟩ ⟨value⟩. -i, -o, and -e ⟨jklowden@freetds.org⟩.
Bugs
Microsoft servers as of SQL Server 7.0 SP 3 do not return output parameters unless the RPC functions are used. This means bsqldb cannot return output parameters for stored procedures with these servers.
Referenced By
datacopy(1). | https://www.mankier.com/1/bsqldb | CC-MAIN-2018-09 | refinedweb | 138 | 53.47 |
I've got a list of toys, and each of those toys has a color associated with it. Each toy is unique, but some of them may have the same color. I want to group all of the toys by their color and put them into sublists. So essentially, I want a list of all the toys grouped by color.
I've seen a few posts on how to do this with a Boolean or a finite number of values, but I want to be able to do it with any color, or rather, any string.
Try this:
from collections import defaultdict toys_color = defaultdict(list) for toy in toys: toys_color[toy.color].append(toy) list_toys_color = list(toys_color.items())
If you don't want the color with each group, use this line instead:
list_toys_color = list(toys_color.values()) | https://codedump.io/share/DZnXcYPFsBPC/1/create-sublists-based-on-property-in-python | CC-MAIN-2017-13 | refinedweb | 136 | 72.66 |
Last edited 3/6/12. Code by Steven Lewis. Corresponding PI Brian Kuhlman bkuhlman@email.unc.edu.
The code is at
rosetta/rosetta_source/src/apps/public/scenarios/FloppyTail/; there's an integration test+demo at
rosetta/rosetta_source/test/integration/tests/FloppyTail/. Note that the integration test is vastly under-cycled relative to getting it to do anything useful: the number of cycles it demonstrates should be sufficient to show some remodeling but not enough to get anywhere useful. To run that demo, go to that directory and run
[path to executeable] -database [path to database] (at-symbol)options
You may want to look at the online supplemental info for that paper for a different presentation of how the code works.
This paper uses FloppyTail but is not related to development.
This code was written for a relatively singular application. The system in question was a protein with a long (dozens of residues) flexible tail, which was not seen in crystal structures. Biochemical evidence suggested a particular binding site for the tail on a known binding partner (the two binding partners also had a known binding interface separate from this tail). The code was intended to model the reach of the long flexible tail and determine whether the hypothesized binding site was plausible.
The protocol is more useful for testing hypotheses about possible conformations, and exploring accessible conformation space, than for finding "the one true binding mode". If your tail is truly that flexible it might not have a "one true binding mode."
The algorithm is fairly simple: small/shear/fragment moves in centroid mode to collapse the tail into some sort of folded conformation from an initially straight-out-into-space extended conformation, and small/shear moves with repacking to refine its position. This is conceptually similar to how abinitio folding works, although it is not refined for that purpose (and does not contain temperature scheduling, etc).
The code is compatible with constraints during the centroid phase (passed in via commandline). Early modeling proceeded using constraints and some small hacks to help guide models to the hypothesized tail-binding site. Ultimately this was not necessary for the original system, but the code retains the ability to use constraints, etc. Your mileage may vary. UPDATE: The code is compatible with constraints in both phases.
This code is NOT intended to do "half-abinitio" where you know half a structure and want to fold the other half. Although it is modeled on abinitio, it is only tested on a truly floppy tail, and I have no idea if it is able to fold compact structures. It is resolutely not supported for that purpose.
See test/integration/tests/FloppyTail/ for example usage. Basically all you need is an input structure.
This code was intended for a single purpose, but it may work if you have a similarly flexible tail. It can also model internal flexible regions between domains.
FloppyTail supports three types of options: general rosetta options (packing, etc.), generic protocol options like "how many cycles" borrowed from the (unreleased) AnchoredDesign application, and FloppyTail specific options.
FloppyTail options
AnchoredDesign options (borrowed for simplicity, not tied to AnchoredDesign in any other way); all are in the AnchoredDesign namespace
General options: All packing namespace options loaded by the PackerTask are respected. jd2 namespace options are respected. Anything very low-level, like the database paths, is respected.
For release 3.4, FloppyTail supports multiple flexible linkers. To use these, you have to write your own MoveMap file to tell FloppyTail what is flexible, and pass it in via the flag in:file:movemap. The formatting is described in the header to the function core::kinematics::MoveMap::init_from_file (probably at core/kinematics/MoveMap.hh). Briefly, do this:
20 30 BBCHI 54 67 BBCHI
to define flexible regions running from residues 20 to 30 and 54 to 67. This is in internal Rosetta residue numbering (from 1), not PDB numbering.
To use this feature you must also NOT use the following flags, because the movemap handles these data, so the program is set up to ignore inputs from these flags if passing a movemap.
You'll be using this application to model mostly unstructured regions. You should not put a lot of stock in any individual model. This is not the sort of application where you'll run it 10 times and then take the best-scoring result as an accurate guess for the actual protein structure.
In general you should pick some metric predicted by the model (if you read the paper, you'll see that it was a distance between two residues later found to be chemically crosslinkable). You can then mine the model population to see what this metric looks like in the top-scoring fraction of models. The extra_analysis functionality will facilitate this. I suggest histograms.
For 3.2, there was a major under-the-hood change which decreases runtime, scaling favorably for very long tails. For the publication case it decreases runtime 10-25%.
For 3.3, the publication flag was added for simplicity. The C_root flag was added to speed computation on non-c-terminal tails. Constraints work in fullatom mode. Full support for domain assembly (internal linkers) was added.
For 3.4, I added the ability to specify a custom MoveMap, which also allows for multiple rigid and flexible regions. | https://www.rosettacommons.org/manuals/archive/rosetta3.4_user_guide/d8/d39/_floppy_tail.html | CC-MAIN-2016-36 | refinedweb | 889 | 55.54 |
Re: How to pass information, classes between forms in Windows Application mode
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Tue, 22 Jul 2008 22:49:35 +0100
raylopez99 <raylopez99@xxxxxxxxx> wrote:
Alternatively, Form2 could have a parameterless constructor and you
could set properties, or call methods to pass it the information.
Constructors aren't the only way to pass information between objects.
What are the other ways?
I just listed two: call a method, set a property. You mentioned some
others yourself. My point is that your claim on the first message of
this thread:
<quote>
If you want to pass information between two forms comprised of
classes, whether or not they are parent/child, modal or modeless,
dialog or non-dialog you have to use the non-normal/ non-default or
parametricized or parameter constructor, not a default (no parameter)
normal constructor.
</quote>
is incorrect. A constructor is *one* way of passing information, but
not the only way.
Passing a class that has a method X that
accepts other classes is of course one way, but for all practical
purposes it's the same as the parameterized copy constructor
Be careful here - you haven't created any copy constructors. Giving
constructors parameters isn't the same as creating a copy constructor.
with the important difference of course that you can call this method
X many times, not just once. Another way is the inheritance of forms,
Form2: Form1 as you discuss below and as I further comment below.
Another way maybe is the publisher-subscriber events/delegates model?
But I'm not sure, since Forms, unlike Console mode, has some tricks
to it (discussed below).
There's not really a "Console mode" beyond whether or not a console is
allocated at startup. You can display GUIs in console applications.
Furthermore, the language itself really doesn't care about all of this
- parameter passing, constructors etc remain consistent whatever you're
doing (with some oddities around remoting and the like, admittedly).
I'm not entirely sure you're correct [UPDATE: after running the tests
below, I'm sure that a person--not you--but a person who says an
object that is passed to Form2 using the parametric constructor of
Form2 from Form1 is not passing the true object but a copy of the
object is not correct]
You're neither passing "the true object" nor a copy of the object.
You're passing a reference to the object.
Yes, because we're dealing with a managed language C#. Is that your
point? OK. A small point but noted.
No, it's not a small point at all. It lies at the heart of what you're
seeing when it comes to what you're calling data binding.
if you say myClass2_that_exists_in_Form2 cannot
"actually refer to the Form1.myClass1 'variable' from Form2, since we
are passing by value, so it must refer to it.
No, not at all. You have passed the current value of the variable as
the argument. If you change the value of Form1.myClass1, there will be
no way for Form2 to retrieve it. It doesn't have access to the
*variable*.
Not true. You might have something else in mind. I am finding out
that both in what I call the non-inherited model of Form1: Form and
Form2: Form, where I use a parameterized constructor to pass the
class2 that has the information in it, and the inhereited model of
Form2: Form1, that you suggested, I am getting "data binding" between
the two forms in both directions.
No, you're not. You can't make any changes to the *variable* of one of
the forms. Sure, you can make changes to the object that the variable
originally refers to, but you can't make the variable refer to a
different object completely (unless you use a ref parameter to start
with, of course - and then only during that call).
That is, with one small, trivial
bug exception that I discuss below with inherited controls, I am
getting both the public variable arr2 of Class2 to 'update' in both
the Form1 (parent) and Form2 (child) when I make a change to arr2 in
either parent or child forms (Forms 1 or Form 2, respectively).
Well, you haven't shown any code with a variable called arr2 in.
However, I strongly *strongly* suspect that you're not changing the
value of the variable - you're changing the contents of the array.
Unless you have
arr2 = [some value];
you're not changing the value of arr2. Certainly this:
arr2[0] = [some value];
isn't doing it. The value of arr2 is just a reference - and that
reference doesn't get changed just because you're changing the contents
of the array, any more than your home address changes if you decorate a
bedroom.
It's very important to understand the difference between a variable,
its value, and the object it happens to refer to at a particular point
in time.
That
is data binding in both directions. It's working. The small
exception? When I inherit forms, Form 2 gets all the controls from
Form1 (which BTW is very confusing and I would never do this in
practice, but it's just a demo), and because of some obscure way form
controls are instantiated, or perhaps something else, when I try and
update arr2 using the inherited child form control button (but not the
parent form control button), I get an 'old' value. But this is a
minor bug or rather just an inherited control problem, or some small
thing. The main thing is that using my system or your system I am
getting data binding in both directions.
Another use of incorrect terminology: data binding isn't what you think
it is.
However, you can't take
an arbitrary reference to an instance of Form1 and access its myClass1
variable from Form2, while the variable is private.
Yes. You keep saying this, and this is a newbie point well taken, but
we (I) am beyond that. One funny thing I keep forgetting is that C#
likes to always express access modifiers everywhere, with no access
modifier being private by default. But for this example I set
everything to public, using keyword 'public'. Everything, so this
point is moot? (but see the note at the end here about 'class0')
When the fields are public then yes, you can change the values of
variables (so long as you have a reference to an instance of the
containing class, of course).
But, as we know, if you add the "ref" keyword, and with a
helper function we can change a class (we can put the helper function
in another class, or as a standalone function, that accepts 'ref
Class2'), however, the issue here is (and this may or may not be what
you have in mind) whether to use the above example
"myClass2_that_exists_in_Form2" can permanently change any public
variable in class "passClass2[1]_from_Form1", via changes made in
Form2, rather than Form1. [CHANGED TO '2' from '1' to be consistent]
Reference parameters do effectively change the situation somewhat, but
it's important to note that Form2 doesn't really know that it's
Form1.myClass1 that's been passed to it by reference. It could be a
local variable, or a variable from something completely different.
It could be, but for some reason, like I said, when you change the
parameter in Form 2, form Form1 is also updated, even when the forms
are not inherited. If you feel this fact is shocking, unjustified,
unexplained or whatever, let me know and I'll post the code. I think
it's routine myself--just conventional data binding when you pass one
class (or variable) to another. I'll tell you what I feel is
shocking, below (keep reading--keyword 'class0' and 'nested classes').
Yes, nested classes have access to private members in their enclosing
class. That's not shocking to me, because it's part of the spec. As for
the rest, it's a simple matter of understanding the difference between
an object and a reference.
Rather than me explaining reference parameters here, I suggest you read
my article on them:
This is the article that I mentioned that I already have btw. It
doesn't explain much for this forms example.
Your forms example is still massively incomplete.
You still seem confused about the difference between passing a
reference by value and passing a parameter *by* reference. Changing the
*contents* of an object doesn't change the value of a variable which
refers to that object.
Agreed. So? I don't seem confused over that.
Yes, you do. You keep claiming to be able to change the value of a
variable you don't have access to, just because you can change the
contents of the object that the variable happens to refer to. They're
not the same thing.
OK, here is what I found "shocking". I took your suggestion and for
one version of this program I used inheritance, like I said above, as
in Form1: Form and Form2: Form1 <--note the inheritance (the other
version, which also works, uses two 'independent' forms Form1: Form
and Form2: Form). Both the inherited and non-inherited versions use
the parametricized constructor to pass classes 1 and 2, but,
crucially, I added a third class, class 0, that was nested. This
class 0 was nested and declared public (twice) within Form1, and thus
could be 'seen' (by Intellisense, and ultimately by the program)
unlike declared Classes 1 and 2 (using "Add" to the Solution), which
had their own modules/translation units, unnested, outside of Form1.
This is part of the problem - instead of trying to isolate one single
piece of how the language behaves, you're coming up with massive
examples with non-descriptive names (Class1, Class2, Class3, Form1,
Form2) and making them *much* more complicated than they need to be.
Why involve designer classes (which you never post), partial classes,
inheritance *and* nested classes all in the same example? Stick to one
at a time, preferably in a simple Console app which doesn't require any
extra code. Your examples would be *much* clearer that way.
Your code is even incomplete in the non-designer classes - you haven't
shown where Form2 is declared.
Specifically, consider 'nested' class 0 as follows, which is properly
seen by base Form 1 and derived Form2. Comments //!! below
namespace MDIForms
{
public partial class Form1 : Form
{
Class1 myClass1; //though these are public, do they now become
'private' since no keyword public? That is the question!
Class2 aNew2Class; // " "
public Class0 myClass0; // !! keyword 'public' required!!
Shocking, no?!!
Required to do what? To see it from Form2? No, it can be private. It
can also be declared anywhere in the class, even after the nested
class, contrary to your later assertion. Here's an example:
using System;
class Test
{
static void Main()
{
Test t = new Test();
t.privateVariable = "private";
new Nested().ShowPrivateVariable(t);
}
class Nested
{
internal void ShowPrivateVariable(Test t)
{
Console.WriteLine(t.privateVariable);
}
}
private string privateVariable;
}
That example is *complete* - you can cut and paste it into a new text
file, then run csc on it and run the resulting executable. I would
greatly appreciate it if you would follow the same model. At the moment
it's like being asked to guess which number you're thinking of.
//note!!! 'FORWARD DECLARATION STEP'
Why are you still using terminology that you're aware is incorrect?
<snip incomplete code>
Perhaps, and I could use your input, the problem 'earlier' in this
thread is that classes 1 and 2, which are not nested, are not
explictly declared prior to the Form1 contructor with the keyword
'public', and, though in their respective modules I declare them as
'public', this makes them 'private' somehow when declared within Form
1 without the keyword 'public' (that is truly shocking if true).
Thanks for your help so far. I look forward to your reply.
If you would post a short but *complete* program which demonstrates
something strange.
Note that there's a big difference between declaring a *variable* as
public and declaring a *class* as public. In the paragraph above you
seem to be conflating the two ideas.
--
Jon Skeet - <skeet@xxxxxxxxx>
Web site:
C# in Depth:
.
- Follow-Ups:
- References:
-
- Prev by Date: Microsoft Report Viewer with SqlConnection
- Next by Date: Re: User control refactoring (WPF)
- Previous by thread: Re: How to pass information, classes between forms in Windows Application mode
- Next by thread: Re: How to pass information, classes between forms in Windows Application mode
- Index(es): | http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2008-07/msg02531.html | crawl-002 | refinedweb | 2,107 | 60.95 |
Sending Emails using WiFi (GPy)
Hi,
Looks like Singapore only allows businesses to use their CAT-M1 and NB-IOT services so I am stuck with WiFi. If I am not wrong, the only way of communicating with other devices is through email. I found a tutorial online on how to send an email using Pycom and here's the code:
def sendEmail(): to = 'recipient@gmail.com' user = 'sender@gmail.com' pwd = 'password' smtpserver = smtplib.SMTP("smtp02.hostnet.nl", 587, tls=False) smtpserver.login(user, pwd) header = 'To:' + to + '\n' + 'From: ' + user + '\n' + 'Subject: Email from the GPy \n' msg = header + '\n Hi, \n this is The GPy emailing ;-) \n\n Cheers, \n The GPy' smtpserver.sendmail(user, to, msg) print("Check Inbox!") smtpserver.close()
However, in the terminal, I am greeted by the following error message:
File "<stdin>", line 72, in sendEmail File "/flash/lib/smtplib.py", line 259, in login SMTPAuthenticationError: (535, b'authorization failed (#5.7.0)')
Line 72 refers to
header = 'To:' + to + '\n' + 'From: ' + user + '\n' + 'Subject: Email from the GPy \n'
My suspicion is that the user and pwd or not meant to be email and the corresponding password but something else.
Is there an alternative way of sending an email or is there a workaround?
Also, is there maybe another way of communicating with devices through wifi instead of emails?
Note, I did use legitimate email addresses and the correct password.
Thanks | https://forum.pycom.io/topic/6194/sending-emails-using-wifi-gpy | CC-MAIN-2022-21 | refinedweb | 239 | 64.41 |
#include <Resume_Handle.h>
List of all members.
Please read the documentation in the bugzilla #575 in the bugzilla database what we mean by handler resumption.
When TAO uses a TP reactor, it takes care of resuming the handler once it makes sure that it has read the whole message out of the socket. During the process of reading the transport object would have to deal with errors in 'read' from the socket, or errors in the messages that has been received. Instead of calling resume_handler () on the reactor at every point in the code, we use this utility class to take care of the resumption.
Ctor.
Dtor.
Allow the users of this class to change the underlying flag.
Assignment operator.
The actual handle that needs resumption..
The flag for indicating whether the handle has been resumed or not. A value of '0' indicates that the handle needs resumption. | http://www.dre.vanderbilt.edu/Doxygen/5.6.2/html/tao/a00329.html | CC-MAIN-2013-20 | refinedweb | 148 | 63.39 |
implements significant performance improvements for
fragmentation handling in the kernel, with a focus on NUMA and SMP
based systems.
Review:
Please review these patches. I have on purpose added comments in the
code with the "//" comments style. These comments are to be removed
before applying. They serve as a questions to, you, the reviewer.
The fragmentation code today:
The fragmentation code "protects" kernel resources, by implementing
some memory resource limitation code. This is centered around a
global readers-writer lock, and (per network namespace) an atomic mem
counter and a LRU (Least-Recently-Used) list. (Although separate
global variables and namespace resources, are kept for IPv4, IPv6
and Netfilter reassembly.)
The code tries to keep the memory usage between a high and low
threshold (see: /proc/sys/net/ipv4/ipfrag_{high,low}_thresh). The
"evictor" code cleans up fragments, when the high threshold is
exceeded, and stops only, when the low threshold is reached.
The scalability problem:
Having a global/central variable for a resource limit is obviously a
scalability issue on SMP systems, and even amplified on a NUMA based
system.
When profiling the code, the scalability problems appeared to be the
readers-writer lock. But, surprise, the primary scalability issue
was caused by the global atomic mem limit counter, which, especially
on NUMA systems, would prolong the time spend inside the
readers-writer lock sections. It is not trivial to remove the
readers-writer lock, but it is possible to reduce the number of
writer lock sections.
Testlab:
My original big-testlab were based on four Intel based 10Gbit/s NICs
on two identical Sandy-Bridge-E NUMA system. The testlab
used/available, while rebasing to net-next, were not as powerful.
Its based on a single Sandy-Bridge-E NUMA system with the same Intel
10G NICs, but the generator machine was an old Core-i7 920 with some
older NICs. This means that I have not been able to generate full 4x
10G wirespeed. I have chosen (mostly) to include 2x 10G test results
due to the generator machine (although the 4x 10G results from the
big system looks more impressive).
The tests are performed with netperf -t UDP_STREAM (which default
send UDP packets with size 65507 bytes, which gets fragmented). The
netserver's get numactl pinned and the CPU sockets get smp_affinity
aligned to the physical NIC connected to its own NUMA node.
Performance results:
For the impressive 4x 10Gbit/s big-testlab results, performance goes
from (a collective) 496 Mbit/s to 38463 Mbit/s (per stream 9615 Mbit/s)
(at packet size 65507 bytes)
For the results to be fair/meaningful, I'll report the used packet
size, as (after the fixes) bigger UDP packets scale better, because
smaller packets will require/create more frag queues to handle.
I'll report packet size 65507 and three fragments 1472*3=4416 bytes.
Disabled Ethernet Flow Control (via ethtool -A). To show the real
effect of the patches, the system needs to be in an "overload"
situation. When Ethernet Flow Control is enabled, the system will
make the generator back-off, and the code path will be less stressed.
Thus, I have disabled Ethernet Flow Control.
No patches:
-------
Results without any patches, and no flow control:
2x10G size(65507) result:(7+50) =57 Mbit/s (gen:9613+9473 Mbit/s)
2x10G size(4416) result:(3619+3772)=7391 Mbit/s (gen:8339+9105 Mbit/s)
The very pure result with large frames is a result of the "evictor"
code, which gets fixed in patch-01.
Patch-01: net: frag evictor, avoid killing warm frag queues
-------
The fragmentation evictor system have a very unfortunate eviction
system for killing fragment, when the system is put under pressure.
The evictor code basically kills "warm" fragments too quickly.
Resulting in a massive, DoS like, performance drop, as seen above
(no-patch) results with large packets.
The solution is to avoid killing "warm" fragments, and rather block
new incoming in case mem limit is exceeded. This is solved by
introducing a creation time-stamp, which set to "jiffies" in
inet_frag_alloc().
2x10G size(65507) result:(3011+2568)=5579 Mbit/s (gen:9613+9553 Mbit/s)
2x10G size(4416) result:(3716+3518)=7234 Mbit/s (gen:9037+8614 Mbit/s)
Patch-02: cache line adjust inet_frag_queue.net (netns)
-------
Avoid possible cache-line bounces in struct inet_frag_queue. By
moving the net pointer (struct netns_frags) because its placed on the
same write-often cache-line as e.g. refcnt and lock.
2x10G size(65507) result:(2960+2613)=5573 Mbit/s (gen:9614+9465 Mbit/s)
2x10G size(4416) result:(3858+3650)=7508 Mbit/s (gen:8076+7633 Mbit/s)
The performance benefit looks small. We can discuss if this patch is
needed or not.
Patch-03: move LRU list maintenance outside of rwlock
-------
Updating the fragmentation queues LRU (Least-Recently-Used) list,
required taking the hash writer lock. However, the LRU list isn't
tied to the hash at all, so we can use a separate lock for it.
This patch looks like a performance loss for big packets, but the LRU
locking changes are needed, by later patches.
2x10G size(65507) result:(2533+2138)=4671 Mbit/s (gen:9612+9461 Mbit/s)
2x10G size(4416) result:(3952+3713)=7665 Mbit/s (gen:9168+8415 Mbit/s)
Patch-04: frag helper functions for mem limit tracking
-------
This patch is only meant as a preparation patch, towards the next
patch. The performance improvement comes from reduce the number
atomic operation, during freeing of a frag queue, by summing the mem
accounting before and doing a single atomic dec.
2x10G size(65507) result:(2475+3101)=5576 Mbit/s (gen:9614+9439 Mbit/s)
2x10G size(4416) result:(3928+4129)=8057 Mbit/s (gen:7259+8131 Mbit/s)
Patch-05: per CPU mem limit and LRU list accounting
-------
The major performance bottleneck on NUMA systems, is the mem limit
counter, which is based on an atomic counter. This patch removes the
cache-bouncing of the atomic counter, by moving this accounting to be
bound to each CPU. The LRU list also need to be done per CPU,
in-order to keep the accounting straight.
2x10G size(65507) result:(9603+9458)=19061 Mbit/s (gen:9614+9458 Mbit/s)
2x10G size(4416) result:(4871+4848)=9719 Mbit/s (gen:9107+8378 Mbit/s)
To compare the benefit of the next patches, its necessary to increase
the stress on the code, but doing 4x 10Gbit/s tests.
4x10G size(65507) result:(8631+9337+7534+6928)=32430 Mbit/s
(gen:8646+9613+7547+6937 =32743 Mbit/s)
4x10G size(4416) result:(2870+2990+2993+3016)=11869 Mbit/s
(gen:4819+7767+6893+5043 =24522 Mbit/s)
Patch-06: nqueues_under_LRU_lock
-------
This patch just moves the nqueues counter under the LRU lock (and
per CPU), instead of the write lock, to prepare for next patch. No
need for performance testing this part.
Patch-07: hash_bucket_locking
-------
This patch implements per hash bucket locking for the frag queue
hash. This removes two write locks, and the only remaining write
lock is for protecting hash rebuild. This essentially reduces the
readers-writer lock to a rebuild lock.
UPDATE: This patch can result in a OOPS during hash rebuilding.
Needs more work before its safe to apply.
2x10G size(65507) result:(9602+9466)=19068 Mbit/s (gen:9613+9472 Mbit/s)
2x10G size(4416) result:(5024+4925)= 9949 Mbit/s (gen:8581+8957 Mbit/s)
To see the real benefit of this patch, we need to crank up the load
and stress on the code, with 4x 10Gbit/s at small packets,
improvement at size(4416): before 11869 Mbit/s now 17155 Mbit/s. Also
note the regression at size(65507) 32430 -> 31021.
4x10G size(65507) result:(7618+8708+7381+7314)=31021 Mbit/s
(gen:7628+9501+8728+7321 =33178 Mbit/s)
4x10G size(4416) result:(4156+4714+4300+3985)=17155 Mbit/s
(gen:6614+5330+7745+5366 =25055 Mbit/s)
At 4x10G size(4416) I have seen 206 frag queues in use, and hash size is 64.
Patch-08: cache_align_hash_bucket
-------
Increase frag queue hash size and assure cache-line alignment to
avoid false sharing. Hash size is set to 256, because I have
observed 206 frag queues in use at 4x10G with packet size 4416 bytes.
2x10G size(65507) result:(9601+9414)=19015 Mbit/s (gen:9614+9434 Mbit/s)
2x10G size(4416) result:(5421+5268)=10689 Mbit/s (gen:8028+7457 Mbit/s)
This does introduce an improvement (although not as big as I
expected), but most importantly the regression seen in patch-07 4x10G
at size(65507) is gone (patch-05:32430 Mbits/s -> 32676 Mbit).
4x10G size(65507) result:(7604+8307+9593+7172)=32676 Mbit/s
(gen:7615+8713+9606+7184 =33118 Mbit/s)
4x10G size(4416) result:(4890+4364+4139+4530)=17923 Mbit/s
(gen:5170+6873+5215+7632 =24890 Mbit/s)
After this patch it looks like the read lock is now the new
contention point.
Patch-09: Hack disable rebuild and remove rw_lock
-------
I've done a quick hack patch, that remove the readers-writer lock, by
disabling/breaking hash rebuilding. Just to see how big the
performance gain would be.
2x10G size(4416) result: 6481+6764 = 13245 Mbit/s (gen: 7652+8077 Mbit/s)
4x10G size(4416) result:(5610+6283+5735+5238)=22866 Mbit/s
(gen: 6530+7860+5967+5238 =25595 Mbit/s)
And the results show, that its a big win. With 4x10G size(4416)
before: 17923 Mbit/s -> now: 22866 Mbit/s increase 4943 Mbit/s.
With 2x10G size(4416) before 10689 Mbit/s -> 13245 Mbit/s
increase 2556 Mbit/s.
I'll work on a real solution for removing the rw_lock while still
supporting hash rebuilding. Suggestions and ideas are welcome.
This patchset is based upon:
Davem's net-next tree:
git://git.kernel.org/pub/scm/linux/kernel/git/davem/net-next.git
On top of:
commit ff33c0e1885cda44dd14c79f70df4706f83582a0
(net: Remove bogus dependencies on INET)
---
Jesper Dangaard Brouer (9):
net: frag remove readers-writer lock (hack)
net: increase frag queue hash size and cache-line
net: frag queue locking per hash bucket
net: frag, move nqueues counter under LRU lock protection
net: frag per CPU mem limit and LRU list accounting
net: frag helper functions for mem limit tracking
net: frag, move LRU list maintenance outside of rwlock
net: frag cache line adjust inet_frag_queue.net
net: frag evictor, avoid killing warm frag queues
include/net/inet_frag.h | 120 +++++++++++++++++++++++--
include/net/ipv6.h | 4 -
net/ipv4/inet_fragment.c | 150 ++++++++++++++++++++++---------
net/ipv4/ip_fragment.c | 43 +++++----
net/ipv6/netfilter/nf_conntrack_reasm.c | 13 +--
net/ipv6/reassembly.c | 16 ++-
6 files changed, 259 insertions(+), 87 deletions(-)
--
Best regards,
Jesper Dangaard Brouer
MSc.CS, Sr. Network Kernel Developer at Red Hat
Author of
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/526963/ | CC-MAIN-2013-20 | refinedweb | 1,799 | 69.62 |
,
Whose (ground) fault
is it anyway if there's electrical leakage?
T5s/Fluorescent Ballasts 9/15/11
<Hello David>
I've got 3 aquariums, 2 of which have the old type T8 light units
(will update to the T5s when they break down), but for the 3rd tank
I'm setting up I didn't have a light unit so I got a T5, I
wasn't informed then what I was told today when I bought it that
you have to have the right unit output size for the length of tube you
want (I've never had a problem with my T8s),
<Two different worlds.>
my 3rd tank is 3ft, I was thinking of getting an 11 to 18 inch tube but
was told that because my unit has an output of 54watts it would be too
much power for tubes that small, it looks like I'd have to get a 46
inch tube (much too big for tank), I phoned the shop where I got the
unit from & he said he doesn't know & can't keep up
with the new information & said I can take it back but I would like
it confirmed if this is true! Do I have to change my unit & get one
with less output?
My new unit takes 2 tubes!
<As long as the ballast is an electronic ballast, it should work for
the 39 watt T5 HO lamps.
Depending on the ballast, you may have to wire the lamps
differently.
There usually is a wiring diagram on the ballast.
The brand and model number of the ballast would have helped
here.>
Thanks for any help that may be forth coming
<You're welcome. James (Salty Dog)>
David.J.Harrison
Low Output Ballasts?/Lighting 8/18/09
Hello everyone,
<Hi Mark>
I recently purchased a VHO ballast and VHO bulbs for a frag tank which
I grow corals in to sell to the LFS to help finance my addiction to the
hobby. The output of the new bulbs didn't appear any different than
the standard 40 watt ones I was using before, so I checked the wattage
with a meter I own. It is one of those that just plugs inline on the
power cord.
It is dead on when I check my metal halides or T-5's on my main
tank. It says the ballast is only putting out around 90 watts total (45
per bulb), far below the 220 advertised. It also tests for amperage and
it is down considerably as well. They are definitely wired correctly as
they were bought as a retro-fit kit from Hello Lights. They are
clueless about what the problem could be and said if they light up
there is nothing wrong with them. I disagree.
<What you are reading on the primary side of the ballast isn't
indicative of the power the ballast is supplying to the lamp
itself.
A magnetic ballast works something like an inductor, a coil of wire in
a circuit which may be wound around a piece of metal (core). When
current flows through the wire, it generates a magnetic field.
Positioning the wire in concentric loops amplifies this field, and the
ballast in tandem with a transformer controls the amount of current
going to the lamps. Newer ballast designs such as ARO's, use
advanced electronics to more precisely regulate the current flowing
through the electrical circuit. Since they use a higher cycle rate, you
don't generally notice a flicker or humming noise coming from an
electronic ballast. Do not compare your current readings to MH and T-5
lighting. Different lamps require specialized ballasts designed to
maintain the specific voltage and current levels needed for a
particular lamp. If the ballast were defective, you would likely see
flickering, or no light at all.>
Is it possible they are selling cheap ballasts not really putting out
what they claim on the packaging?
<ARO is a reputable brand of ballast, the 220 watts/1.82 amps,
strictly refers to the maximum power/current the ballast is capable of
handling.>
I always had decent luck in the past with them so I'm not
criticizing, just wondering if ballast brands could make that much of a
difference.
<Unlikely.>
The brands and specs are as follows: ARO electronic ballasts model
AS-220 and URI T-12 48" VHO bulbs (110 watt each). Have you heard
anything negative about either of these brands?
<No.>
Any advice you can give to what may be the problem would be greatly
appreciated. Your site is a huge benefit to the hobby.
<As above.>
Thanks again.
<You're welcome. James (Salty Dog)>
Mark
PFO ballast convert PC to VHO 12/28/08 Hello,
<Hello Lenny. Minh at your service.> I currently have a 55gal (48
X 17 X 15)reef tank I purchased from a friend who came over and set it
up the way he had it. The pumps that I am using are RIO 17 HF for the
return (he had a Gen-x 4100. I couldn't stand the noise from that
thing so it was changed) and a Gen-x 1000 for the skimmer. The lighting
is a PFO-EL 2-2 ballast running 2 33" 96 watt PC 50/50. This
canopy setup has the PC's 8.5" above the top of the tank. I
would like to change to VHO's which this ballast is capable of. The
main concern for my choice to do this is my tank seems to run on the
warm side around 82 and that is with 2 fans in the canopy and one more
in the sump. I've read and was able to feel myself that the
PC's ran hotter than the VHO's. <This has also been my
experience.> I have searched for the quick connects that are already
wired to the end caps with no luck. I have emailed PFO and was told
basically sorry, we don't have any but good luck. I can find some
3pc T12 end caps through aquacave.com(thanks to your site) but can not
find a wiring diagram for my ballast. <From my research, it appears
that the PFO-EL 2-2 consists of a PFO enclosure and Fulham Workhorse 7
ballasts. You may need to open up the ballast enclosure to verify this
information. The Fulham Workhorse 7 ballast wiring diagram can be found
here:.> Also, not sure how
long the bulbs would need to be if needed to be longer than the current
bulbs. <The Workhorse 7 is capable of running up to 220W. You can
review the specifications on the VHO bulb you are interested in running
for the optimal power/length configuration for this ballast.> Any
ideas or suggestions would be greatly appreciated. <If the above
suggestion does not pan out for you. You can also contact the folks at
DIY Reef () or HelloLights
(), they are both very knowledgeable in
fluorescent lighting.> Lenny <Good luck. Cheers, Minh Huynh.
Re: PFO ballast convert PC to VHO 12/30/08 My
previous email to PFO, finally they sent back an answer that was more
helpful. They replied that my ballast uses the workhorse 5 which I
confirmed once I opened it. After your response I went to the Fulham
website to look for the wiring diagram needed for the type of bulbs
used. They only show for the workhorse 7 or 8. Do I still use this even
though this is not my specific ballast? <After reviewing
Fulham's website, it appears that they only recommend the Workhorse
5 ballast be used with certain bulb combinations. For example, when
using their diagram tool, "T5 Linear HO with a bulb set 2xF24
HO" will give you a Workhorse 5 wiring diagram but not with the
T12 VHO bulb combination. It is best to err on the side of caution and
contact Fulham to get their full recommendation on what you'd like
to achieve with the Workhorse 5 and VHO combination.> Lenny <Good
luck, Minh Huynh.>
PC Ballasts Going Bad 9/12/08 Hello all, long time
no ask :-) Hope the members of the wet web crew are all well. <As
far as I am aware, yes.> I have a 65 gallon reef tank (18" deep
by 36" long by 24" tall). I have a 4x96 power compact
lighting fixture from a well known lighting vendor providing the light
for the tank- I will omit the name. I run 4 different types of bulbs in
my 4x96 - 10,000K daylight, 6700K daylight, 420nm and 460nm actinics. I
try to change them about every nine months (thanks to your advice, I
stagger the change out of bulbs, to not shock the corals). Last year I
lost a bulb, and when I went to change it out, realized after the new
one failed to work, and swapping some bulbs, that I had a bad ballast.
<Dang!> I purchased a new ballast, and installed (not too hard,
just a pain to get to and get all the wires packed back in). About a
week ago, I lost a bulb again (I don't exactly remember, but
I'm fairly certain it's not the same ballast). Turns out I lost
another ballast. My question is, do you feel that this is fairly
common, because it's extremely frustrating? <Definitively not
unheard of, but not an everyday occurrence either.> The light itself
is about 2 years old. I think it's ridiculous that I've lost
two ballasts already. They are not cheap! <Nope.> Not sure if
I'm doing anything wrong. The light sits directly on top of my
glass tank lid. The light came with legs for the light canopy, but the
instructions also stated that the legs were not required and that the
light could sit on top of the tank. The fans in the light housing are
operating. I have my actinics on for about 12hrs per day, and the
daylight lamps on for around 11 hrs. They are on an automatic timer.
Any thoughts? <A few, first you could just chalk this up to plain
old dumb luck. But, two things to look at that may help. First, I would
raise this fixture a bit (just 1' or so) to allow some air
circulation around the entire fixture; maybe even a small fan blowing
on it if you. This will all of course keep things a bit cooler. The
other thing you should look at are any signs of corrosion/moisture
inside (or outside, it is indicative of the moisture getting to it) the
fixture. This can drastically limit the life of a ballast, or even flat
out kill it if the moisture makes it to the wrong places.> Thanks, I
owe my healthy tank and coral success to your website and the amazing
information within. <Awesome!> Chris
<Welcome, Scott V.>
Re: Mounting locations for ballasts in a canopy 7/26/08
Hello again WWM (Scott V), <Welcome!> Thanks for your
prompt reply to my question about ballast mounting locations! One
more quick related question: How far away from the back wall
should the ballasts be situated to safely prevent overheating or
melting of the paint from the wall? I would think at least 6
inches, but that leaves a pretty large space at the back of the
tank. If this proves to be the case, I will probably mount them
remotely at the side of the tank. <Ah, for these ballasts an
inch or two will do. The fact that you will have exhaust fans in
the canopy will keep things at a reasonable temperature. I assume
you will have them blowing in and flowing out the back where the
ballasts will be? Even if you have the fans blowing out of the
canopy, air will still flow over the ballasts.> Thanks,
Leslie
<Welcome, have fun, Scott V.>
Full spectrum fluorescents and electronic ballasts Dear>
VHO Ballast Good>
VHO Ballast Hello,.>: Cheers, Byron
<Have a nice day! -Steven Pro>
Fluorescent Ballast Question Hello --
>
Buffering/lighting Hi Bob, My tap water does not have a lot
of buffering capability. <Do you need, want more? Can be augmented
easily> When I do my regular water changes (7 to 10days), the tank
water has a pH of 7.8. I use Instant Ocean Salt and my replacement
water has a pH around 8.2. I believe that the shift in pH after water
changes is stressing my system. <Good point.> I have
started to use Kent Marine's Super Buffer and now my pH stays at
8.3 and. Alk = 4 mEq/l. Is this method of keeping up Alk/pH up a good
idea or would the two part supplements be a better choice? <Two part
would be better.> I did read the article in FAMA as requested by you
about the Ice Cap ballast running NO fluorescence. I remembered reading
that article years ago and another (same concept) with a plant tank. It
really sounds like they are having tremendous results with NO tubes and
VHO ballast. My main question here is with tube replacement. Ice Cap
says 6x longer life. The recent article in FAMA state that regular
replacement of the tubes have been unnecessary. Also in FAMA with the
other article on the plant tank he state that he has been running the
same tubes for years. Now what puzzles me is that this is exactly
opposite of what most say. Hmmm? <The use of electronic ballasts in
these cases does extend effective lamp life as far as I'm aware,
but don't know about six times, definitely not indefinitely. You
can test for intensity, spectral make-up over time... or just observe
your plant livestock for changes. Bob Br >> | https://www.wetwebmedia.com/fluoballastself.htm | CC-MAIN-2021-31 | refinedweb | 2,309 | 80.01 |
C++ Programming/Code/IO/Streams/string
Contents
The string class[edit].
Basic usage[edit]
Declaring a std string is done by using one of these two methods:
using namespace std; string std_string; or std::string std_string;
Text I/O[edit]);
Getting user input[edit][edit]
We will be using this dummy string for some of our examples.
string str("Hello World!");
This invokes the default constructor with a
const char* argument. Default constructor creates a string which contains nothing, i.e..
Size[edit].
I/O[edit] (i.e. it returns the input stream), you can nest multiple
getline() calls to get multiple strings; however this may significantly reduce readability.
Operators[edit], similar to the C strcmp() function. These return a true/false value.
if(str == "Hello World!") { std::cout << "Strings are equal!"; }
Searching strings[edit].
Inserting/erasing[edit].
Backwards compatibility[edit]).
String Formatting[edit].
Example[edit]
; } | https://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/IO/Streams/string | CC-MAIN-2017-09 | refinedweb | 146 | 50.94 |
RubyConf China: NoSQL, Rails, and Matz on Ruby 2.0
- |
-
-
-
-
-
-
Read later
My Reading List
RubyConf China is an annual conference about the Ruby programming language. The 2nd RubyConf China took place in Shanghai, China, on the 26th of June. Ruby creator "Matz" delivered the keynote, followed by many talks on current Ruby topics, most from speakers from Asia.
This was Matz's second trip to RubyConf China, and his talk was about the Ruby community. Matz thinks it's very lucky for Ruby to have a great community. What's the definition of a "nice" community?
def nice
brave &&
passionate &&
honest &&
respective
end
Matz also mentioned that people can contribute to the Ruby community in many ways: by fixing bugs, publishing gems or even committing code to the Ruby core codebase.
When being asked about Ruby 2.0, Matz said that Ruby 2.0 would be an addition to 1.9 instead of a revolutionary upgrade. Ruby 2.0 will focus on scalability, improve the experience of team collaboration, especially big teams. Besides, in his talk, he mentioned the various implementations of Ruby such as JRuby and Rubinius.
Then, Yottaa's Jared Rosoff shared their experience on MongoDB - how to build a highly scalable system with Ruby and MongoDB. He showed the advantages and disadvantages of different SQL solutions, and explained why they chose MongoDB.
In the afternoon, WenTien Chang (a.k.a. ihower) showed 10 useful tricks. In the talk "Designing Beautiful Ruby APIs", he had many examples showing how to write beautiful APIs. In his opinion, an beautiful API should be:
Readable: easy to understand
Efficient: easy to write
Flexible: easy to extend
Meanwhile, he also introduced the Ruby community in Taiwan and mentioned RubyConf Taiwan 2010 held this April.
In "Ruby, NoSQL and Tokyo Cabinet", SNDA's BiaoWei Zhuang brought their work to RubyConf China - a NoSQL database based on Tokyo Cabinet named TCDatabase and its ActiveRecord adapter tcdb-adapter. By using TCDatabase and tcdb-adapter, developers can migrate their relational database to NoSQL database easily (even seamlessly). Zhuang made a demonstration and provided the roadmap of TCDatabase. It will be opensourced in the near future.
There were some other talks unmentioned above:
- Richard Huang - Ruby Application Based on HTTP
- Quake Wang - Ruby as a Glue Language
- Andy Hu - Build High-Quality Web Application on Rails
- Shunichi Arai - Business Matters in after-Rails World
- Kouichirou Eto - Introducing "Patterns, Wiki and XP"
All the slides and videos will be available on the official site, , soon.
Rate this Article
- Editor Review
- Chief Editor Action | https://www.infoq.com/news/2010/07/rubyconf-china | CC-MAIN-2016-40 | refinedweb | 426 | 55.44 |
Hi,
how can I retrieve global parameters set in a stylesheet?
for example:
I created a windows form where I can set Parameters. these values are later
overgiven with SetParameter (~"parameter_name", "test"). that works fine. But
Id like to parse the stylesheet before and autofill the form with the
parameters set in the stylesheet. Just to make it easier and more comfortable
for the user. I hope its clear what I mean. sry for my bad english.
I found some solutions on that for java. but not for c#. maybe someone has an
idea?
greetings
sry this should be in "help" not in open discussion ...
to make my post clearer. I mean something like this:
XsltTransformer atransformer;
string params = atransformer.GetParameters();
greetings
Michael Kay
2010-04-22
The XsltExecutable in Saxon.Api unfortunately doesn't give you any access to
this information. However you can call Load() to get an XsltTransformer, and
on this you can get the Java net.sf.saxon.Controller as the value of the
Implementation property. Although this is a Java-derived object, you can
manipulate it as any .NET object, though the style may be a little unfamiliar,
e.g. method names beginning lower-case. You will have to add a reference to
the saxon9he.dll (or -pe or -ee) to your application.
From the Controller you can do getExecutable().getCompiledGlobalVariables()
which is a (Java) HashMap from names to variable definitions; for a global
parameter (as distinct from a Variable) the value will be of class
net.sf.saxon.instruct.GlobalParam. Sorry that's a bit circuitous, it's the
best I can come up with at the moment.
its me again.
well, as I said it seems to work fine. but now I have a problem. :-/ when I
have a param like this:
I get this:
DocumentInstr(ValueOf(SimpleContentConstructor(((document($path,
.)/child::element(config, xs:anyType))/child::element(examplXML, xs:anyType)),
" ")))
which is not good. it works great with params written in normal text but when
I write a param with xslt expressions he tries to interpret it I guess.
do you have an idea how to solve this?
Michael Kay
2010-04-27
Don't simply do toString() on the value of the select expression. The user
interface is up to you, but I would say: if the select expression is a an
instance of Literal, display its string value; otherwise display something
like "(computed value)". The original text of the expression from the source
stylesheet is not available in the compiled code.
Michael Kay
2010-04-27
Incidentally, the compiled code would be much less convoluted if you wrote the
xsl:param like this:
Using xsl:value-of in this kind of situation is really bad coding, but
unfortunately very common: it forces saxon to read the document and then make
a copy of it.
I decided to retreive the params on another way. I parse the source xslt file
and write the given values into a string, and put them in a list. and so on.
basically like this:
XmlReader xmlReader = null;
xmlReader = XmlReader.Create(xsltfile);
while (xmlReader.Read())
{
string param, value = "";
if (xmlReader.Name == "xsl:param" && xmlReader.IsStartElement() &&
xmlReader.Depth == 1)
{
bool select = false;
param = xmlReader.GetAttribute("name");
if (xmlReader.MoveToAttribute("select"))
{
value = xmlReader.ReadInnerXml();
select = true;
}
if (xmlReader.MoveToContent() != XmlNodeType.None && select == false)
{
value = xmlReader.ReadInnerXml();
value = Item.value.Trim();
select = false;
}
Program.konfiguration.parameters.Add(Item);
}
}
xmlReader.Close();
works fine. and it seems to run fast.
Michael Kay
2010-04-28
Fine. Be aware that you aren't accessing included/imported stylesheets, and
you're relying on the namespace prefix being "xsl". But as a cheap-and-
cheerful solution, it's fine. | http://sourceforge.net/p/saxon/discussion/94026/thread/12cffdc2/ | CC-MAIN-2014-15 | refinedweb | 614 | 61.53 |
I work with Storm for a while already, but want to get started with development. As suggested, I am using Intellij (up to now, I was using Eclipse and did only write Topologies against Java API).
I was also looking at
This documentation is not complete. I was not able to run anything in Intellij first. I could figure out, that I need to remove the scope of storm-core dependency (in storm-starter pom.xml). (found here: storm-starter with intellij idea,maven project could not find class)
After that I wass able to build the project. I can also run ExclamationTopology with no problems within Intellij. However, WordCountTopology fails.
First I got the following error:
java.lang.RuntimeException: backtype.storm.multilang.NoOutputException: Pipe to subprocess seems to be broken! No output read.
Serializer Exception:
Traceback (most recent call last):
File "splitsentence.py", line 16, in
import storm
ImportError: No module named storm
pyhton-storm
java.lang.RuntimeException: backtype.storm.multilang.NoOutputException: Pipe to subprocess seems to be broken! No output read.
Serializer Exception:
Traceback (most recent call last):
File "splitsentence.py", line 18, in
class SplitSentenceBolt(storm.BasicBolt):
AttributeError: 'module' object has no attribute 'BasicBolt'
dev@storm.apache.org
I think that it was always assumed that topology would always be invoked through storm-command line. Thus working directory would be ${STORM-INSTALLATION}/bin/storm Since storm.py is in the this directory, splitSentence.py would be able to find storm modules. Can you set the working directory to a path, where storm.py is present and then try. If it works, we can add it later to the documentation
WordcountTopology
Unfortunately, AFAIK you can't run multilang feature with LocalCluster without having packaged file.
ShellProcess relies on codeDir of TopologyContext, which is used by supervisor. Workers are serialized to stormcode.ser, but multilang files should extracted to outside of serialized file so that python/ruby/node/etc can load it.
Accomplishing this with distribute mode is easy because there's always user submitted jar, and supervisor can know it is what user submitted.
But accomplishing this with local mode is not easy cause supervisor cannot know user submitted jar, and users can run topology to local mode without packaging.
So, Supervisor in local mode finds resource directory ("resources") from each jars (which ends with "jar") in classpath, and copy first occurrence to codeDir.
storm jar places user topology jar to the first of classpath, so it can be run without issue.
So normally, it's natural for ShellProcess to not find "splitsentence.py". Maybe your working directory or PYTHONPATH did the trick. | https://codedump.io/share/a0tMdcsE5oI2/1/how-to-run-wordcounttopology-from-storm-starter-in-intellij | CC-MAIN-2017-09 | refinedweb | 435 | 51.14 |
Given an integer N as input. The goal is to find the count of integers that are less than N and represented in Binary form. For example if input N is 12 then numbers less than 12 are 1,10,11 that are binary and contain 0s and 1s as digits. The answer would be 3.
For Example
N=100
Count of Binary Digit numbers smaller than N are − 4
The Binary numbers less than 100 are − 1, 10, 11, 100
N=120
Count of Binary Digit numbers smaller than N are: 7
The Binary numbers less than 100 are : 1, 10, 11, 100, 101, 110, 111
Approach used in the below program is as follows −
In this approach we will use an integer vector vec. To this we will first push 1. Now to generate the next binary number we will extract the last number (temp) from vec (Initially 1). Then generate next using: temp*10 and temp*10+1 as binary numbers will always be ( 1,10,11,100,110,111….). Pop numbers from vec and if it is less than N then increment count.
Take an integer N as input.
Function Smaller_N(int N) takes N and returns a count of Binary Digit numbers smaller than N.
Take the initial count as 0.
Take integer vector vec for storing integers that contain 0s and 1s only.
Add 1 to the vector using vec.push_back(1).
Using while loop, traverse vec[ ] and take out last pushed as temp= vec.back(). And remove it from vec.
If temp<=N, then increment count and generate next binary integer as temp*10 and temp*10+1 and add to vec.
At the end of while return count as a result.
#include <bits/stdc++.h> using namespace std; int Smaller_N(int N){ int count = 0; vector<int> vec; vec.push_back(1); while (!vec.empty()){ int temp = vec.back(); vec.pop_back(); if (temp <= N){ count++; int temp_2 = temp * 10; vec.push_back(temp_2); vec.push_back(temp_2 + 1); } } return count; } int main(){ int N = 1000; cout<<"Count of Binary Digit numbers smaller than N are: "<<Smaller_N(N); return 0; }
If we run the above code it will generate the following output −
Count of Binary Digit numbers smaller than N are: 8 | https://www.tutorialspoint.com/count-of-binary-digit-numbers-smaller-than-n-in-cplusplus | CC-MAIN-2021-21 | refinedweb | 376 | 72.66 |
XBee AT/API Reliability
- Login or register to post comments
- by lex lee.
Thus, I'm trying out the API mode with the Xbee library but with no success.
I've tested the Series2_Tx & Series2_Rx examples in the library but I'm getting 2 flash on the led, which translates to:
// local XBee did not provide a timely TX Status Response -- should not happen
Is AT mode sufficient for what I'm attempting? How should I go about with the API mode?
Thanx
Data scrambling
When I was setting my Xbee's up for wireless program uploads I also had some troubles with data scrambling. Something you might want to check on is your computers port settings. Try reducing the latency timer in the advanced options.
You might want to use Serial.available() to check if your buffer is overflowing.
Here you go: Tx:const int
Here you go:
Tx:
const int startByte = 199;
const int endByte = 250;
int data1, data2, data3, data4;
void setup(){
Serial.begin(9600);
}
void loop(){
data1 = analogRead(0);
data2 = analogRead(1);
data3 = analogRead(2);
data4 = analogRead(3);
data1 = map(data1, 0, 1023, 0, 180);
data2 = map(data2, 0, 1023, 0, 180);
data3 = map(data3, 0, 1023, 0, 180);
data4 = map(data4, 0, 1023, 0, 180);
Serial.print(startByte, BYTE); //Initiate
Serial.print(data1, BYTE);
Serial.print(data2, BYTE);
Serial.print(data3, BYTE);
Serial.print(data4, BYTE);
Serial.print(endByte, BYTE); //End
delay(10);
}
Rx:
#include <Servo.h>
Servo servo1, servo2, servo3, servo4;
byte rx, data1, data2, data3, data4;
const int startByte = 199;
const int endByte = 250;
const int error = 255;
void setup(){
Serial.begin(9600);
servo1.attach(5);
servo2.attach(6);
servo3.attach(10);
servo4.attach(11);
}
void loop(){
if (Serial.available()){
rx = Serial.read();
delay(6); //needed for code to work
if (int(rx) == startByte){
data1 = Serial.read();
data2 = Serial.read();
data3 = Serial.read();
data4 = Serial.read();
rx = Serial.read();
if(int(rx) == endByte && (int(data1) != error ||
int(data2) != error ||
int(data3) != error ||
int(data4) != error)){
servo1.write(int(data1));
servo2.write(int(data2));
servo3.write(int(data3));
servo4.write(int(data4));
}
}
}
}
hey, do you have the code
hey,
do you have the code for what you are doing?
I know this is the forum for discussing your problem with the xbee's but i would be very interested in seeing your code
Updates
I've restored the XBees to factory setting & same thing;
w/o XBee, Tx led flashed at constant rate
w XBee, Tx led flashed intermittently
Are you doing anything to be
Are you doing anything to be sure you don't overflow on the Tx end? The baud rate at which you communicate with the xBee module is not the guaranteed baud rate that characters are delivered at. Try starting with overkill, like a delay(50) after you send each character. If that works, reduce the number until it fails again and you can determine the actual aggregate rate you are getting.
And yes, I meant full reset to "party line" mode.
I've tried delay(1000) but
I've tried delay(1000) but with same result.
How do i ensure that the Tx is not overflowing?
A delay of 1000 between each
A delay of 1000 between each character? If you can't send one character per second at close range using factory defaults then one of your xBee units is bad. You should see a a data rate of over 500 characters per second even at medium range.
But just to make sure - your diagnostic has to be at the send end first and needs to have e a timeout.
You're right, one or both of
You're right, one or both of my XBee's is dead.
Borrowed some XBee's from my friend and it works. Now I'm trying to 'revive' my XBees.
One more problem though, I've to put the Coordinator on the Rx & the End Device on the Tx for it to work.
Switching them does not work.
I can't help you with the
I can't help you with the Coordinator and End Device issues. I wanted a more equal peer relationship, so I implemented my own protocol. An observation I can make is that your test indicates that the End Device has the correct address for the Coordinator. Other assumptions are still assumptions...
Meery Xmas! Managed to
Meery Xmas!
Managed to revived one of the XBees, still working on the second one. Any help with de-bricking will be appreciated.
I thot the one of the Xbee must be set to the coordinator; the other an end device?
what kind of protocol are you using? | http://letsmakerobots.com/node/23880 | CC-MAIN-2015-35 | refinedweb | 777 | 66.44 |
Using "using" in C#
Is it better to put the classes you're using with "using" inside or outside your first "namespace"? I have seen both, and I know both will compile, but is there a preference? Thanks (from a C# neophyte).
Andrew Burton
Tuesday, January 13, 2004
ASking what's "better" implies "to whom". What's better for you, is whatever makes you happy. Technically, they're equivalent.
Brad Wilson (dotnetguy.techieswithcats.com)
Tuesday, January 13, 2004
Then let me rephrase my question: Does it make any difference to the compiler where you put it?
Andrew Burton
Tuesday, January 13, 2004
"Technically they're equivalent." Finish ready the post, Andy. *sigh* Thank you.
Recent Topics
Fog Creek Home | https://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=2865&ixReplies=3 | CC-MAIN-2018-26 | refinedweb | 119 | 70.5 |
On Sat, Apr 11, 2009 at 05:48:07AM +0200, Michael Niedermayer wrote: > On Sat, Apr 11, 2009 at 03:42:04AM +0200, Diego Biurrun wrote: > > On Fri, Apr 10, 2009 at 10:48:36PM +0200, Michael Niedermayer wrote: > > > On Fri, Apr 10, 2009 at 09:01:36PM +0200, Diego Biurrun wrote: > > > > On Fri, Apr 10, 2009 at 08:45:41PM +0200, Michael Niedermayer wrote: > > > > > > > > > > Was there a function i deprecated but did not replace where a trivial > > > > > search and replace was sufficient? > > > > > > > > Did any of them require considerable amounts of work? I don't think so. > > > > > > let me repeat my question, what are you talking about? > > > Its very obvious you dont want the issues (if they even exist) fixed > > > because otherwise you would have pointed to them by now > > > >: > > > Michael: > > libavformat/asfdec.c:364: warning: AVPaletteControl is deprecated > > libavformat/avidec.c:491: warning: AVPaletteControl is deprecated > > we first need to decide how to put the palette info into the bitstream, also > fixing these 2 will require all decoders that support palettes from avi/asf > to be fixed at the same time as well. If this has not been decided, why is the function deprecated? There should be a proper replacement first... > > libavutil/random.h:55: warning: av_random_generate_untempered_numbers is deprecated (declared at libavutil/random.h:39) > > libavutil/random.h:73: warning: av_random is deprecated (declared at libavutil/random.h:50) > > libavutil/random.h:55: warning: av_random_generate_untempered_numbers is deprecated (declared at libavutil/random.h:39) > > libavutil/random.h:73: warning: av_random is deprecated (declared at libavutil/random.h:50) > > these have been fixed already, and iam sorry that i did not do more > of these fixes myself, but i dont really remember anyone asking me to > and what you putted under my name was nonsense not fixable, as the whole > file should and was removed once it became unused. > You did not list the actual uses of av_random() that occured all over the > place under my name ... av_random() is now history thanks to my efforts. > > ... Why did you not request the maintainers to fix their code? > a grep INIT_VLC_USE_STATIC will show some of what need to be changed > but there are more init_vlc that just pass 1 instead of INIT_VLC_USE_STATIC > a > grep -A4 init_vlc libavcodec/*.c | grep '1 *)' > might catch some more ... I think Carl Eugen just sent a patch for this. >. Note that I managed to do it for rand() and friends, _t POSIX namespace pollution and a few more things, so it's not like I do not put effort into these issues. Diego | http://ffmpeg.org/pipermail/ffmpeg-devel/2009-April/059346.html | CC-MAIN-2014-52 | refinedweb | 425 | 61.56 |
Wikibooks:Reading room/Proposals
Welcome to the Proposals reading room. On this page, Wikibookians are free to talk about suggestions for improving Wikibooks.
Now under construction: Wikibooks Stacks[edit]
As part of the infrastructure overhaul I've been doing for, at this writing, just over 23 months, and following from the previous discussion here in the ongoing series of threads (link), I'm now developing a replacement for the current subject hierarchy, in the form of a book called Wikibooks Stacks.
I'm not currently asking for help with this, tbh. Somewhat embarrassingly, given the collaborative nature of wikis, just atm I really need to do this carefully, step by step, myself, because there's still new design work involved at each step. But I do want to let everyone know what I'm doing, and perhaps folks here will offer advice (or point out that I'm making a huge mistake somewhere!).
When I'm all done, all our 3000-or-so books will be filed in both the "old" subject hierarchy and the "new" stacks, and I'll be able to do the equivalent of flipping one of those big high-voltage switches and suddenly the categories visible on each book main page will be shelves instead of subjects, and then I can start the process of carefully mothballing the old subject pages, one by one. Then it'll be time to start in earnest on the final(?) stage of this multi-year overhaul of our infrastructure, the introduction of topical categories that list pages as well as books, which will enable us to provide much better targets for incoming links from sister projects, including from Wikipedia.
Grouping all of this machinery in a book is more convenient, organizationally, than the
Subject: namespace, as it happens. The new pages, equivalent to subjects, have name prefix
Shelf: or, at the top level,
Department:, which are not recognized by the wiki platform as namespace prefixes, so these pages are all technically in mainspace, as is the book. Our infrastructure templates such as {{BookCat}} and {{BOOKNAME}} know to associate these name prefixes with book Wikibooks Stacks, which is convenient because most of the pages involved don't have to have the name of the book built into them at all, they can just use markup
{{BOOKNAME|Shelf:}} (which expands to
Wikibooks Stacks). Shelves correspond to subjects that use {{subject page}}, departments to subjects that use {{root subject}}.
There are shelf categories, each with an associated allbooks category, just as there are subject categories with associated allbooks categories. When I set up the machinery of the subject hierarchy, I arranged that when any of the pages involved detected a problem, it would flag it out, and provide buttons to help a human operator implement likely actions to fix it. This time around, I've made some improvements to this semi-automation while I was about it.
I also very much want to arrange for dialog-based assistants to replace the older-style editing buttons (with the older-style buttons reappearing if the dialog tools are not detected — thus, graceful degradation when things aren't working right). This would be very cutting-edge use of the dialog tools, and I very much want to learn as much as I can from the experience, about how to make effective use of the dialog tools. Which is actually part of what's holding me up just atm: I could be marching forward with setting up shelves, but then I'd be missing out on this major opportunity to gain experience with dialog. --Pi zero (discuss • contribs) 19:51, 3 June 2018 (UTC)
- Progress report: All our books have been shelved; they're also all listed in subjects. The shelf categories are hidden, the subject categories are visible; but I'm now in a position to switch that, so the shelf categories are visible and the subject categories hidden. Then I can start shutting down the subjects, which also has to be done manually. Strangely, I've got a discrepancy between the number of shelves and the number of subjects, whose cause should eventually come out during the manual shutdown. I'm not sure what to do about possible incoming links to subject pages that are now going to be either nonexistant or redirects. --Pi zero (discuss • contribs) 02:26, 29 September 2018 (UTC)
- Cheers for all the work you have made already. I noticed two things which I'm not sure whether they are glitches or not: 1) Departments do not list any featured books. 2) Under Wikibooks Stacks/Departments the Wikijunior department correctly lists the Wikijunior shelf, but the Help department does not list the Help shelf. -- Vito F. (discuss) 23:46, 10 October 2018 (UTC)
- On the second point, actually the link provided is to the help shelf, rather than to the help department. I'm unsure whether that should be treated differently, or if instead the wikijunior department should be treated differently. --Pi zero (discuss • contribs) 04:03, 11 October 2018 (UTC)
- Update: My progress on this is currently mired in the various pages associated with quality as assigned by various "WikiProjects". That part of our infrastructure was imported by Adrignola and adapted for Wikibooks —mainly by adding support for Subject pages— back in 2010; it isn't heavily used, but wants updating to support the rearrangement; except that frankly I find its internal design largely indecipherable. How Adrignola figured it out to make changes then, I find hard to imagine, and it's worse now with existing use of the Subject-based version to accommodate. --Pi zero (discuss • contribs) 13:28, 22 January 2019 (UTC)
Export to Pdf, Epub, Odt, LaTeX[edit]
Hi,
I think Wikibooks needs a function to export the the formats Pdf, Epub, Odt and LaTeX.
I suggest to add a new link to the toolbar on the left in the in the section Tools. It shall be labeled Multi format export. I shall link to and fill the form field URL on the page with the current page viewed by the user on the wiki.
You may try this out yourself just now by copying User:Dirk_Hünniger/common.js to common.js in your user namespace.
If this proposal get generally approved I would ask an admin to edit MediaWiki:Common.js accordingly, so that the link will appear for everyone automatically.
I am not sure if the servers on wmflabs will be able to stand the load, if MediaWiki:Common.js get modified, but we will see by then.
Yours --Dirk Hünniger (discuss • contribs) 15:28, 30 November 2019 (UTC)
- Thanks, it's a bit slow but it could be worth it. JackPotte (discuss • contribs) 19:23, 30 November 2019 (UTC)
- @Dirk Hünniger, JackPotte: This is a good thing to list at m:Community Wishlist Survey 2020/Wikibooks. Note that m:Community Wishlist Survey 2020/Wikibooks/EPUB generation exists. —Justin (koavf)❤T☮C☺M☯ 20:32, 30 November 2019 (UTC)
This has been deployed on the German Wikibooks now. See b:de:Hauptseite links "Multi Format Export" in the sidebar on the left. Just let me know, if you are interested in deploying it on the English Wikibooks as well. --Dirk Hünniger (discuss • contribs) 06:12, 21 December 2019 (UTC)
This has also been deployed on the German Wikiversity and Wikisource. --Dirk Hünniger (discuss • contribs) 18:15, 5 January 2020 (UTC)
Comment I've got no particular view on this being added. But I do have a couple of queries about its usage:
- Although I've added the code to my common.js, the addition of the "Multi format export" sidebar link seems very inconsistent. For example, I get the link on this very page (i.e. Wikibooks:Reading room/Proposals). But if I go to e.g.
Algorithms/Print versionor Anatomy and Physiology of Animals/Print version the link fails to materialize. I don't know if this is an issue with my system at all. Addendum: actually I have got it to come up on Algorithms/Print version now through reloading at least sometimes. But if fails on the other book. So its seems a bit inconsistent for some reason. But perhaps my system. --Jules (Mrjulesd) 21:06, 5 January 2020 (UTC)
- I have attempted to use the tool, and I have a continual problem with it: paragraph breaks repeatedly fail to render. I don't know if it is me doing something wrong, but nevertheless it is a repeating problem for me, which is a shame as otherwise the output seems to be of very high quality.
- Any comments on either of these issues? --Jules (Mrjulesd) 20:59, 5 January 2020 (UTC)
I think concening issue 1 you got a browser cache problem. Your browser show an old version of the sidebar from your hard drive. In Firefox you may need to click "reload button" while holding down the SHIFT button on the keyboard (second to left of backwards button). You will need to do this once for every page. On 2) Yes paragraph breaks are omitted. I am not sure if I will implement it since it might have unwanted effects on other parts cause "there is no line here to end" errors in LaTeX. You could possibly work around that by inserting br html tags in the wiki code of the page you wish to render. --Dirk Hünniger (discuss • contribs) 22:04, 6 January 2020 (UTC)
Hi,
I deployed something to resolve issue 2 on the server I tryed with Anatomy and Physiology of Animals/The Skin and could see that in worked look at section "The Dermis"
Yours --Dirk Hünniger (discuss • contribs) 23:01, 6 January 2020 (UTC)
- Hi Dirk Hünniger thanks for your replies.
- Yes that did help to bring it up. What's weird though is that I then reloaded the page again and it failed to materialize! But if I do shift reload each time it comes up, but if I just reload it doesn't. But I expect it might be connected with the MediaWiki installation here, I've noticed a few strange things going on here and there, so I wasn't too surprised. Maybe also my browser.
- Thanks for looking into that, it makes it a far more useful tool if it renders paragraph breaks. I will experiment with it later on and get back to you if I have any further problems.
- Thanks again, --Jules (Mrjulesd) 02:12, 7 January 2020 (UTC)
- I'd like an .epub export facility for sure. I'm not sure about the paragraph break issue but it seems to work well on Wikisource .en / .la for me. JimKillock (discuss • contribs) 22:25, 24 February 2020 (UTC)
- Using Wikisource, they seem to have a working ePub export, can that be applied here? JimKillock (discuss • contribs) 13:16, 29 February 2020 (UTC)
- JimKillock you could use this link: . Remember to fill in the full url of the page (which should be a print version), and change the output format to EPUB. There is more info at Help:Print versions which may be helpful. --Jules (Mrjulesd) 16:46, 29 February 2020 (UTC)
- too late. add export to text file too. it would be tough to handle, say math formulas, but should put less load than a optimized pdf. Retow324 (discuss • contribs) 01:14, 2 April 2020 (UTC)
- Much runtime is spend on finding the proper list of contributors as well as the authors of the images, this would still be needed even if I did a plain text export and did the images as ascii art. But I doubt many users will be happy with that. --Dirk Hünniger (discuss • contribs) 15:04, 4 April 2020 (UTC)
So not much has happend here for a month. Is there any process to come to a decision on this point? --Dirk Hünniger (discuss • contribs) 12:00, 3 May 2020 (UTC)
- I made some suggestions about how this might be handled below. JimKillock (discuss • contribs) 22:09, 3 May 2020 (UTC)
Wikibooks:Maintenance[edit]
I have long felt the usefulness of page Wikibooks:Maintenance is limited by the fact that, although it lists lots of kinds of tasks one might undertake, it doesn't actively tell you which of those sorts of tasks actually has a queue of items waiting to be taken care of; to find that out you'd have to check them all one-at-a-time. A different approach is used at en.wn, where a template called (for partly historical reasons) {{votings/sorted}} lists all the task-queues that are non-empty, and how long each queue is. (Actually it's more sophisticated than that: the queues are sorted into three sets listed on separate lines according to theme (news production, community discussions, admin tasks); most of the empty queues are also listed but moved to the end of the list and greyed out; and some of the queues when nonempty are shaded in various colors to draw attention to them.)
I'm thinking we might enhance the usefulness of Wikibooks:Maintenance by adding some such dynamic list up at/near the top. --Pi zero (discuss • contribs) 15:55, 4 February 2020 (UTC)
- Hi Pi zero well yes that sounds like a definite improvement. I'd be interested to see what you could come up with. --Jules (Mrjulesd) 12:31, 5 February 2020 (UTC)
- I've been thinking about how this might be done. Some queue sizes can be determined using magic word
PAGESINCATEGORY, but others have no associated category. Such as Special:Uncategorizedpages. I was hoping to parse its contents using {{evalx}}, but the wiki platform does not allow these special pages to be transcluded. --Pi zero (discuss • contribs) 13:23, 5 February 2020 (UTC)
What about trying Extension:Translate?[edit]
Hello everybody!
Two years ago I discovered an interesting discussion about the creation of a multilingual version of Wikibooks opened in the 2007 (meta:Requests for new languages/Wikibooks Multilingual). I think that the idea was great, but to be honest I think that they were too in advance with the times and without the needed MediaWiki features, and so I understand how much scaring would be, with the risk of duplicating efforts without too much pratical differentiations between these editions. Anyway there is not enough interest in starting another "multilanguage" version of Wikibooks.
Anyway now we have seen the success stories of sites like the MediaWiki wiki after the adoption of the mw:Extension:Translate.
For those who don't know, the "Mediawiki wiki" hosts a vibrant community of users and developers who aim to provide a well-written documentation about MediaWiki, and MediaWiki-related software, providing this documentation in multiple languages. Without the extension Translate, this purpose would be so much complex. Why? Because MediaWiki is so rich of features and continuously evolving, and its difficult to keep the related documentation in sync with the changes.
Who love software documentation feel the pain of propagating an information in all the languages, without a tool like the Extension:Translate.
"Accessibility" and "internationalization" are somehow not much strictly related to the purpose of "cultural differentiations". I mean: it's great having 120+ Wikibooks editions with their own cultural freedom, but what about having a place where some kind of books can be just written in a language (maybe English?) and then made accessible in 303+ languages (and dialects, who knows?).
Now creating technical books and documentation is difficult and frustrating: Have I to start writing from the en.wikibooks and then translating it manually to it.wikibooks? or vice-versa? and after I will ever end, how to keep them in sync if people improve one or other? or start new translations? Keeping everything in sync is simple with the Extension:Translate, and we can try it here in en.wikibooks for a while.
TD;DR (too long; didn't read):
We have an extension (mw:Extension:Translate) that is activated in some wikis and could be activated here to try to start manuals, documentations, technical references, etc., where every information must be accessible as soon as possible. Try it out in "MediaWiki Wiki" on and see the status of the translations for every page (for example here: mw:Help:Navigation).
Do you have any question? Do you know this extension? Do you want to try this feature here? :) Thank you! --Valerio Bozzolan (discuss • contribs) 07:22, 19 February 2020 (UTC)
- I wouldn't think so, no. This is a mono-lingual project - any translation would go on a sister project. There are so few editors here anyway, there's essentially no chance that translations would be produced particularly as translation of a book is significantly more challenging than translating, say, a site notice on Meta, which is the main use case for the tool. QuiteUnusual (discuss • contribs) 10:17, 19 February 2020 (UTC)
- I'm also confused here. Translate is useful on c:, d:, incubator:, m:, mw:, species:, and s:mul: due to their nature but why would it be here on the English-language Wikibooks? —Justin (koavf)❤T☮C☺M☯ 10:56, 19 February 2020 (UTC)
- @Koavf, QuiteUnusual: You are completely right, and this why in the 2018 I started a discussion in meta:Requests for new languages/Wikibooks Multilingual 2 without success. During the discussion @StevenJ81: suggested to first play with this extension here. --Valerio Bozzolan (discuss • contribs) 09:41, 20 February 2020 (UTC)
- I really don't see any political will to do this or to have a multi-lingual book project, if for no other reason than how small an inactive Wikibooks is generally. —Justin (koavf)❤T☮C☺M☯ 11:23, 20 February 2020 (UTC)
- I don't think book content, by its nature, is especially amenable to translation in general, though there may be a very few individual books that could be. (I'm actually, by coincidence, in the process of reading a dead-tree translated textbook, and despite being well-translated it's got pitfalls to watch out for; it's just not the same as a natively written presentation, and in general the notion of just shunting information back and forth between languages doesn't apply to the subtleties of textbooks.) Wikibooks is, by nature, not so much a single small-ish project as a confederation of thousands of mostly-ultra-tiny micro-projects (individual books) banded together to share a common administrative infrastructure. Almost none of those thousands of micro-projects would be interested in translation; hence, Wikibooks just isn't a likely place for a translation extension to take root. --Pi zero (discuss • contribs) 14:18, 20 February 2020 (UTC)
- I just thought that an activation (even a trial one) of this well-known extension could be useful to someone, even just for one book. But maybe I'm wrong and I was just too enthusiast to have the opportunity to use it for my books. --Valerio Bozzolan (discuss • contribs) 18:31, 24 February 2020 (UTC)
- I'm just having a hard time imagining when in principle a handbook, manual, guide, or textbook would be multilingual. Some source texts certainly are, and they are posted at s:mul: but a textbook in two languages...? That's in addition to the reality of how dead of a project this is. —Justin (koavf)❤T☮C☺M☯ 18:42, 24 February 2020 (UTC)
- Can't honestly agree with the "dead" characterization. --Pi zero (discuss • contribs) 23:41, 24 February 2020 (UTC)
- Side-note: en.Wikibooks get about 10 million page-views a month,; in comparison simple.Wikipedia gets about 20 million, and en.wp gets about 8 billion. So death may have been greatly exaggerated :)--Jules (Mrjulesd) 16:57, 29 February 2020 (UTC)
- Getting .125% as much traffic is actually pretty compelling evidence that this project is "dead" in comparison. I realize that there are still edits here and it's obviously not really a closed or deleted project but by comparison to other WMF projects, Wikibooks is very inactive. And this is only discussing English. —Justin (koavf)❤T☮C☺M☯ 17:02, 29 February 2020 (UTC)
- Still disagreeing, here. --Pi zero (discuss • contribs) 21:42, 29 February 2020 (UTC)
Strong support. It can be tried, if no can appear another project to do it. And thtis is not a good idea. Free translated books in a lot of languages. Seems good. In any case, the "Translate tool" would be activated in the Language links in every page. BoldLuis (discuss • contribs) 11:56, 18 May 2020 (UTC)
Proposal: add features that support ebook writers better[edit]
Hi there, on the general discussion yesterday I mentioned that I would find it useful to have many of the features of Wikisource available here. This would allow creation of books that feel like books, and export well to epub / mobi formats. Specifically we could support:
- optional narrow single column formats;
- optional serif fonts for body text
- Differing styles for headings and so on (not always underlines)
- easy navigation bars (last page, next page)
- optional export links to common ebook formats
Wikisource has developed all of this to support replicating books. Most ebooks have copied this formula more or less as they are produced with print editions. Wikibooks could offer these features as a option for book developers who believe their audience is primarily offline rather than online.
I suspect the work involved is not too great, as the code should already exist. But I can't say for sure, some things like layout options might break some pages and need to be enabled case by case therefore. Similarly many Wikibooks won't export well to epub due to the way tables are not properly supported by many readers.
I think this could open Wikibooks usage to a lot more use cases. I am certainly missing being able to do things along these lines for some book ideas I have, like sample language readers and dual language readers for learners. These don't suit Wikisource as they're incomplete extracts, potentially with editing or simplification, but don't work too well here because the destination format is not currently well supported. JimKillock (discuss • contribs) 07:57, 22 April 2020 (UTC)
- Jim, s:en: has a lot more templates for formatting text. Have you poked around there to see what our sister project has for formatting in a MediaWiki context? —Justin (koavf)❤T☮C☺M☯ 08:25, 22 April 2020 (UTC)
- Yes absolutely, I have been doing a chunk of work there and that is what prompted me to make these suggestions. Is it just a question of me going ahead and copying templates over? or should I suggest which might be brought over and why? (That said I've not investigated the way the page formatting templates work, perhaps these are also imply traditional templates.) JimKillock (discuss • contribs) 17:14, 22 April 2020 (UTC)
- I am active in Persian Wikibooks and there these two issues are on rise, too: Author rights and issuing books. I believe that writers and editors in Wikibooks differ with writers and editors of Wikipedia. In Wikibooks authors are eager to register their names (or usernames as nicknames) on a separate page inside the book, e.g. Wikijunior:The Elements/Authors and Wikijunior:Ancient Civilizations/Authors. Considering practices for issuing knowledge, Wikibooks is different from Wikipedia, too. Print version is a feature more important for Wikibooks than Wikipedia as the content of Wikibooks is supposed to be used by learners (better called readers) who may prefer an offline version of the book. In my opinion, PDF version is good enough as it can be converted to epub just by one click using softwares even available online. --Doostdar (discuss • contribs) 18:11, 22 April 2020 (UTC)
- I don't personally agree that pdf » epub conversion is a great idea (epub is basically html so Wiki to epub is natural where PDF’s basis in postscript does not convert so well back to html); but luckily we don't have to choose; Wikimedia already has the tools. The question then is how to make exports easy for readers who are more likely to want that as you say.
- I really like the way Italian Wikisource have enabled exports for instance, see this example I was recently shown. JimKillock (discuss • contribs) 19:16, 22 April 2020 (UTC)
- We certainly can copy templates: they are all freely licensed. It's usually better to have someone with the appropriate user rights to do this via Special:Import. I brought up Wikisource only because you may be able to identify existing solutions to some of these problems you raise. —Justin (koavf)❤T☮C☺M☯ 19:37, 22 April 2020 (UTC)
- Thank you Justin, that is very helpful. JimKillock (discuss • contribs) 21:42, 22 April 2020 (UTC)
- @JimKillock: There are some differences between the provisions for css on different projects, which probably should be kept in mind when contemplating introducing advanced formatting from another project. This may both complicate things and allow some interesting new techniques. (Alas, I have some awareness of the Wikibooks infrastructure, and more about the Wikinews infrastructure, but no past experience with the Wikisource infrastructure.)
- Different projects may have very different approaches to their customized css. Wikisource appears to have a very small, simple common.css; either there must be some additional css, perhaps induced somewhere by javascript, or perhaps it's all done using javascript instead of css. Wikibooks does a lot more in its common.css, a lot of it arranged modularly in subpages. (For contrast, the Wikinews common.css is all on the one page, which makes it considerably harder to read.)
- Wikibooks has book-specific css pages: our common.js checks for the existence of a subpage for the book, and imports it if found. (Then again, Wikinews has page-specific css pages, also checked for and imported by its common.js.)
- The javascript infrastructures are also different between projects. Wikibooks common.js provides for both book-specific and page-specific javascript pages, and its common.js is largely modular. The page-specific javascript, btw, is key to the dialog tools, and was adapted from Wikinews — changing the naming-convention for the page-specific javascript pages, because the Wikinews convention conflicted with the modularity naming-convention of Wikibooks. (Yes, the Wikinews common.js is all on one page, yes that makes it very hard to read, and yes I have considered modularizing it.)
- --Pi zero (discuss • contribs) 01:31, 23 April 2020 (UTC)
┌─────────────────────────────────┘
Interesting post Pi zero, but some comments on it:
- I believe that the bulk of the Wikisource site-css is at MediaWiki:Gadget-Site.css. For some reason some mediawiki wikis use this file rather than the common.css used by others; see mw:Manual:CSS.
- Custom CSS is now rather easy due to TemplateStyles: see mw:Extension:TemplateStyles. The chief advantage over perbook css is that you don't need admin access to edit, making it easier for most users; also it can be added to any page without the need for it to correspond to a particular book. Despite the name, TemplateStyles can be applied to non-template namespaces, and I have created Template:TemplateStyles/Oberon/styles.css to do so.
- But if custom JS is needed it still needs to be done through perbook JS. --Jules (Mrjulesd) 12:48, 23 April 2020 (UTC)
- I'm interested to hear where the css might be hiding in the Wikisource infrastructure. (Yes, I'm familiar with this sort of use of gadgets.) --Pi zero (discuss • contribs) 18:03, 23 April 2020 (UTC)
- Well it does actually hide in MediaWiki:Gadget-Site.css; despite its name it actually contains the bulk of the site-wide CSS. A similar situation is with the site; if you look at mw:MediaWiki:Common.css its empty, and its site-wide CSS is actually held at mw:MediaWiki:Gadget-site.css. The reason given for this is that "MediaWiki.org controls site CSS with the Gadgets extension, so MediaWiki:Gadget-site.css is used in place of MediaWiki:Common.css. This results in a slightly different load URL." --Jules (Mrjulesd) 18:29, 23 April 2020 (UTC)
- What is the right thing for me to do to move this forward? Should I make a list of templates I would like to have moved over? JimKillock (discuss • contribs) 10:17, 25 April 2020 (UTC)
- That could help to make it all more concrete; we've probably taken the purely abstract discussion of project infrastructures about as far as it can go. --Pi zero (discuss • contribs) 12:09, 25 April 2020 (UTC)
- OK, so here we go, these would be the things I would suggest as a start:
- s:Template:Default_layout » allows differing page layouts to be displayed by default;
- s:Help:Layout » explains the layout system, which I don't understand behind the scenes however
- s:Template:Larger » allows non-underlined headings of varying sizes
- s:Template:Smaller » allows text of smaller sizes than body text
- s:Template:Header » creates title display area with key info, plus navigation back / forward
- s:la:Formula:Titulus » Creates a title area for a front page, also used by ebook exports for front page material AFAICT;
- s:la:Formula:WSExport » Presents a series of export formats for a given book — Preceding unsigned comment added by JimKillock (talk • contribs)
- Yikes. That does look rather... involved. It appears, at first blush, also to have some assumptions built into it about uniformity across the project, that are true for Wikisource but wouldn't be for all of Wikibooks. I hope I'll have a chance to take a closer look sometime in the nearish future... --Pi zero (discuss • contribs) 16:05, 25 April 2020 (UTC)
- Thanks, I guess it is the layout system that looks complex. If there is a simpler way of achieving the goal of a narrow column plus serif fonts, maybe we could consider that?
- The other templates ought to be quite simple (I could be wrong). — Preceding unsigned comment added by JimKillock (talk • contribs) 18:23, 25 April 2020 (UTC)
- @Pi zero: Thought I would flag that it'd be good to think of a simpler way to get the desired result – I don't want to make this stall! If I can help in any way, please let me know. I can bodge around CSS a bit. JimKillock (discuss • contribs) 08:08, 29 April 2020 (UTC)
- @Dirk Hünniger: See the list above, but especially s:la:Formula:Titulus; now in active use, eg s:la:Ólim JimKillock (discuss • contribs) 22:13, 3 May 2020 (UTC)
Proposal to release content on GitHub[edit]
I think if the content on this website was released to GitHub then the books on here would get a lot more traction. It seems to me that you could convert the books to markdown using Pandoc and host them on GitHub. There are many more users on GitHub than there are on this platform and they are generally open-source minded on the platform. Hosting on GitHub will also provide a lot of free infrastructure. You can manage additions to the text however you want by setting up teams with various permissions. Anyone can contribute. 136.33.252.210 (discuss) 01:40, 29 April 2020 (UTC)
- Sounds interesting. Go for it. If you do, please ping me with <nowiki>@Koavf:</ping>. Thanks. —Justin (koavf)❤T☮C☺M☯ 02:53, 29 April 2020 (UTC)
- This may be true and there's permission from a legal POV, but some thought about divergence should be considered – are books being developed on both platforms together, or simply forked? If the latter, the advantages aren't so clear. Also GitHub may well be a better place for books relating to technology and programming, but may not be so helpful for language learners, for instance. Essentially I would apply some care and thought about what is cloned / copied / forked and why. JimKillock (discuss • contribs) 07:29, 29 April 2020 (UTC)
- OP here. My view is that the books may diverge but it shouldn't be too bad to maintain a wiki markup version of the document (converting via pandoc). People that are working on this website can pull from it whenever they want. I reckon pandoc would solve some problems people have been having with converting to formats like epub. This is part of a nonprofit I am working on for test preparation so I am focusing on topics with AP exams or on ACT mathematics. For now the focus is just AP calculus and ACT math. I could imagine extending to all AP exams if we pick up steam. I built some software to help wikibooks crowd source problems as I desired more problems from the calculus book. People can build custom quizzes and share them with their friends. ActuarialAnalyst (discuss • contribs) 12:09, 29 April 2020 (UTC)
- Some links to these examples would help us understand what you're after doing. Exams and maths sound quite good specific things that might work better on GitHub. The food recipe books on Wikibooks, or the children's books, maybe less so, for instance.
- I guess the question feels like: do you have some people who want to do some things on GitHub? If so, great, of course you should go ahead. There is a second point about whether Wikis are the right tool for open learning respources; I am of the opinion that Wikimedia should gradually widen its' available formats over time – as it has with Wikidata and Wikisource – providing more consumer / user focused tolls like easy to set up learning games, course structures etc; (keeping to open licencing all the time). Meanwhile some things will be better done elsewhere, and Github could be a place for some of that. But I don't think moving content will move the authors necessarily. I'm unlikely to use GitHub as I only use it for bug reports and development tasks, I don't submit code and revisions. The majority of people don't use Wikis or repositories, even when they want to create content. Far more find Google docs to be the 'right' default solution – but that doesn't mean we should move all the books to Google Docs either.
- As for epub creation, Wikimedia have good tools for that, (see an example here, they just need implementing here (this is trivial but there is thinking for people to decide how to present links).
- In the end tho Wikimedia Foundation isn't (I imagine) going to start hosting content on other people's platforms, so moving content to GitHub is a decision for you rather than for the community here per se I would suggest.
- NB: you don't need permission for what you want to do, as I am sure you know! JimKillock (discuss • contribs) 16:25, 29 April 2020 (UTC)
- Right, well I suppose I will have to see if I can find help on GitHub. I had hoped somehow I could garner support from administrators on wiki but that is probably too much to hope for. Here is my website to crowd source math problems. I converted the Calculus I and II wiki markup to markdown with pandoc today. Still requires a lot of cleaning. I can't post links in this freaking place ugggh, otherwise I would post my website. edit: I think I'll just not use the wiki content and license the GitHub content under CC0. 136.33.252.210 (discuss) 19:59, 29 April 2020 (UTC)
- For external links, see for instance w:Help:Wikitext#External_links. JimKillock (discuss • contribs) 21:29, 29 April 2020 (UTC)
- JimKillock, it's interesting to me to hear you suggesting the Foundation should branch out to non-wiki-markup formats, because I have a kind of diametriclally opposite view: I think the Foundation has been making a staggeringly huge mistake by trying to deprecate wiki markup pretty much since the Foundation went into full operational mode (what, is it 12 years and change ago, now?) and thereby slow-poisoning the sisterhood that they're supposed to be nurturing, because wiki markup is their greatest asset and should be strengthened and used for everything (rather than marginalized while tasks are offloaded into other languages such as Lua and Javascript, the afaict-entity-relationship database model of Wikidata, whatever). --Pi zero (discuss • contribs) 02:41, 30 April 2020 (UTC)
- I hear what you are saying … I think my concern with the wiki format is that it is just a format; and the goal of the foundation ought to be promotion of collaborative production of open knowledge and learning. When I look at how learning is developing on the net in general, I see many innovations like Duolingo and Memrise, that look like this model but are locking up community-produced content into very specific and potentially short run ventures. I conclude therefore that some quite targeted but evolving tools may be needed that aren't a Wiki model, if we want to leverage free and open for learning. An open competitor to Duolingo / Memrise (like an online Anki) would be possible and a good idea; it would need to have user accounts to track progress at a minimum, and easy ways for people to contribute and build courses. Wiki markup or not I am more agnostic on, but ease of creation and use seems to be the issue. WikiMedia got the idea of working together in the open exactly right; the question to me is why the open learning model is missing so much of the user / creator space at this point. JimKillock (discuss • contribs) 07:51, 30 April 2020 (UTC)
- I think a major long-term obstacle to a flourishing wikimedia sisterhood —it was flourishing when the Foundation kicked into high gear, and has been slowly wilting ever since— has been that the Foundation views the 'educational mission' as their mission, for which they get free labor by the volunteer community, rather than the volunteer community's mission that the Foundation should be catalyzing. I remember this was one of the things I noticed in that Wikimania keynote by Lila Tretikov that, at the time, I mentally summarized as 'the Ministry has decided to interfere at Hogwarts'. (I have never blamed Lila personally, btw; afaict she was set up for it, handpicked and programmed with all the bad ideas that were packed into that keynote; and I don't really think much has changed since then, with the ultimate sources of those bad ideas deeply entrenched.)
In fairness, pursuing wiki markup is a tricky thing; for example, the markup would not be improved by indiscriminately piling on features, which would only give it a worse case of featuritis that it already has. What's needed is some vision on how to add just the right primitives, simple and powerful, to empower and encourage the volunteer community to grow the specific tools needed as part of the wiki, in somewhat the way the volunteer community grows the document-content of the wiki. I've a notion that dialog tools plus {{evalx}} (plus a very few miscellaneous bits like Module:TScope) plus dialog-based semi-automated assistants might do... and it's admittedly a long slog getting there. (A couple of essays I've cobbled together: on Wikibooks, User:Pi zero/essays/Wikiness; on Wikinews, n:User:Pi zero/essays/vision/sisters.) --Pi zero (discuss • contribs) 11:55, 30 April 2020 (UTC)
┌─────────────────────────────────┘
I can't comment on the relationship between WikiMedia foundation and community. I sympathise with the perception that learning Wiki markup is a barrier to entry, but it does open up the composition powers for users of these projects for sure. For me the biggest problem with public interest projects is aligning activity with user needs, as in general their mission has a more abstract purpose, such as codifying knowledge, making it available, etc. This problem is seen through open source models as well as library-like projects; there is a tendency towards completism (all features need to be available) rather than UX (features need to be easy to use and actually used). We have a further problem in the 'open' world, which is that innovation, while permissionless, can sometimes be harder to deliver because of factors like backwards compatibility, lack of investment, or community considerations. I believe in open approaches because they are fairer and spread benefits more widely, but that only works in the open knowledge space if content is used and / or built on. In language learning – my current personal interest, so to speak – much public domain material is used and reused on closed projects; there is little understanding of the benefits of sharing; very few projects take a specifically open approach; there is no sense of a strategy to enable an open learning model to flourish. I am sure this spreads to many other fields, because, after all, why should a strategy exist? So I feel WikiMedia Foundation, Creative Commons and others may want to consider how to build a more strategic approach to specific sectors, and think about what infrastructure, tools, data, ought to be collated, made available, etc, to make the open approach at least as compelling as the closed. That's my broad take on all this. But I've got very off topic! JimKillock (discuss • contribs) 06:56, 1 May 2020 (UTC)
Computing viruses[edit]
It would be interesting a book dedicated only to computing viruses and virus documentation (to documentate the types, names...). From a computer user's point of view (this also include tablets and phones). BoldLuis (discuss • contribs) 11:48, 18 May 2020 (UTC)
Angel Inspiration Cards?[edit]
Hey WIKIBOOKIANS! Although I seem to have lots of energy, I do not, nor do I have a lot of time because I have already started two new projects: Create Vampires and Create Ghost. Hello, I am new to Wikibooks, and I am baffled yet oddly inspired by the work other people have shared. Part of me wants to work on the "bookless" wikibooks called Create Vampires and Create Ghost, although I now see some problems in creating a "text-book" that can be edited by anyone, with unbound pages. Because I am unsure, I thought outside of the box, or rather, about what goes inside the taro box. Although taro / tarot / and motivational cards are NOT considered academic texts, they can be instructional, dependent on the person, or group of people and illustrators, creating the game. Most taro cards are labeled under "U.S GAMES" FOR CLARIFYING REASONS.
The important aspect: a collection of pages that mimic cards, with Art images and useful information, and inspirational quotes. There are dozens of taro cards, they range from dream-analysis linked with introduction to Psychology / Sai-Co-Lo-Gy to cards that introduce STAR TREK crew as "mental functions." I myself prefer inspiration cards, yet I have noticed a lot of motivational material online.
Ideally, a group of interested people would research various taro cards [within reason, exercising precaution because some cards are associated with active cults], then create a resource-book for people to familiarize themselves with the wide range of card decks that are listed, and known generally as taro / tarot cards.
If people like the information, and guidelines, they can then decide to create a category for known taro cards, or design new taro decks. The structure of taro cards maybe what may work for wikibooks, or, this type of taro structure may work for another project, or may work to help develop fictional plot-lines. I share this because I am uncertain of how to structure bookless "books." Maybe Angel inspirational cards could lead to sacred geometry cards / deck, with useful illustrations, sharing helpful math questions, design to get the student to think about problems using their math knowledge, or think about limits because we represent shapes using 2D [sometimes 3d] drawings. Thanks. Peyton09 (discuss • contribs) 00:03, 19 May 2020 (UTC)
3D Slicer[edit]
I suggest a book about 3D Slicer, open and free source, used in medicine.BoldLuis (discuss • contribs) 04:05, 20 May 2020 (UTC) | https://en.wikibooks.org/wiki/Wikibooks:PROPOSALS | CC-MAIN-2020-24 | refinedweb | 7,371 | 58.92 |
import "github.com/go-kit/kit/metrics/statsd"
Package statsd provides a StatsD backend for package metrics. StatsD has no concept of arbitrary key-value tagging, so label values are not supported, and With is a no-op on all metrics.
This package batches observations and emits them on some schedule to the remote server. This is useful even if you connect to your StatsD server over UDP. Emitting one network packet per observation can quickly overwhelm even the fastest internal network.
Counter is a StatsD counter. Observations are forwarded to a Statsd object, and aggregated (summed) per timeseries.
Add implements metrics.Counter.
With is a no-op.
Gauge is a StatsD gauge. Observations are forwarded to a Statsd object, and aggregated (the last observation selected) per timeseries.
Add implements metrics.Gauge.
Set implements metrics.Gauge.
With is a no-op.
Statsd receives metrics observations and forwards them to a StatsD server. Create a Statsd object, use it to create metrics, and pass those metrics as dependencies to the components that will use them.
All metrics are buffered until WriteTo is called. Counters and gauges are aggregated into a single observation per timeseries per write. Timings are buffered but not aggregated.
To regularly report metrics to an io.Writer, use the WriteLoop helper method. To send to a StatsD server, use the SendLoop helper method.
New returns a Statsd object that may be used to create metrics. Prefix is applied to all created metrics. Callers must ensure that regular calls to WriteTo are performed, either manually or with one of the helper methods.
NewCounter returns a counter, sending observations to this Statsd object.
NewGauge returns a gauge, sending observations to this Statsd object.
NewTiming returns a histogram whose observations are interpreted as millisecond durations, and are forwarded to this Statsd object..
WriteLoop is a helper method that invokes WriteTo to the passed writer every time the passed channel fires. This method blocks until the channel is closed, so clients probably want to run it in its own goroutine. For typical usage, create a time.Ticker and pass its C channel to this method.
WriteTo flushes the buffered content of the metrics to the writer, in StatsD format. WriteTo abides best-effort semantics, so observations are lost if there is a problem with the write. Clients should be sure to call WriteTo regularly, ideally through the WriteLoop or SendLoop helper methods.
Timing is a StatsD timing, or metrics.Histogram. Observations are forwarded to a Statsd object, and collected (but not aggregated) per timeseries.
Observe implements metrics.Histogram. Value is interpreted as milliseconds.
With is a no-op.
Package statsd imports 8 packages (graph) and is imported by 30 packages. Updated 2017-07-20. Refresh now. Tools for package owners. | https://godoc.org/github.com/go-kit/kit/metrics/statsd | CC-MAIN-2018-26 | refinedweb | 458 | 60.92 |
This snippet defines a function
printat() which adds line and file information to the normal
print() function output. The intended use is a quick and dirty debugging information for everyday's use. A more complete solution is to use a logging/debugging/tracing framework.
Print with line and file information
Gribouillis 5 Tallied Votes 799 Views Share
#!/usr/bin/env python # -*-coding: utf8-*- # Module: printat (python 2 and 3) # Author: Gribouillis for the python forum at # Date: 2014 June 02 # License: Public Domain # Use this code freely from __future__ import (absolute_import, division, print_function, unicode_literals) __version__ = "0.0.3" import sys def this_line(level = 0): """return a pair (lineno, filename) where this function is called If level > 0, go back up to that level in the calling stack. The filename is the name in python's co_filename member of code objects. """ frame = sys._getframe(level + 1) try: lineno = frame.f_lineno filename = frame.f_code.co_filename return (lineno, filename) finally: del frame def printat(*args, **kwargs): """Print function with additional line number and filename information. Adds a string such as "at line 31 in foo.py" to the printed output, to indicate the position where the printat() function was called. All the calls to print() in a program can be changed to provide additional information by adding print = printat at the top of the program. """ lineno, filename = this_line(1) args += ('at line {n} in {f}'.format(n=lineno, f=filename),) print(*args, **kwargs) if __name__ == '__main__': printat("Hello World!") """ my output --> $ python printat.py Hello World! at line 49 in printat.py """
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge. | https://www.daniweb.com/programming/software-development/code/479747/print-with-line-and-file-information | CC-MAIN-2022-33 | refinedweb | 287 | 57.57 |
Recently I was asked about how to access other TypeScript files from within the file you are working on. The individual had some compiler issues and was trying to figure it out. So here are some tips to maybe help out.
Sometimes it may be necessary to use a
/// <reference path="" /> tag to help the compiler understand what files you are working with. If we had a project that had a folder called
app with a file named
config and we were accessing it from our
main.ts it would look like this:
Reference in
main.ts
/// <reference path="app/config.ts" />
This will help the compiler resolve issues with the type system.
Script Tags
It is possible to use your TypeScript without a fancy module loader and just reference the files you want access to inside your
html. This has the benefit of being quick and easy with smaller projects (read: examples), but lacks the sophistication of a module loading system that allows the modules to self define dependencies.
Given a project that has a
main.ts and
config.ts in root and a
service.ts in a folder
app all files could be referenced on the index page in 3 lines:
index.html
<!DOCTYPE html> <html> <head> </head> <body> </body> </html>
Of course all standard notions of JavaScript script references apply so you can not load a script before a dependency without errors.
For this to work we will also need a complete
main.ts
/// <reference path="config.ts" /> /// <reference path="app/service.ts" /> let config = new Config(); let service = new Service(config.settings.address); let address = service.getAddress(); if(address === config.settings.address){ console.log(`The service returned ${config.settings.address}`) }else{ console.log(`The service did not return ${config.settings.address}`) }
a
config.ts
class Config{ settings = { address :'' } }
and a
service.ts
class Service{ address:string; constructor(address:string){ this.address = address; } getAddress(){ return this.address; } }
Now when our overly simple example loads we should see something like this in the developer console.
This example is just like working with multiple JavaScript files and making calls to other objects that have been added to the global scope from being loaded. The only special markup is if you have to add the
/// <reference path="" /> tags to help identify the proper types.
I’m using Visual Studio 2015 with TypeScript 1.6 and don’t actually need the
referencetags but the handbook says they help.
SystemJS
Another way to work with multiple TypeScript files is to use a module loading system. For this example we will be using (SystemJS)[]. Our files are largely the same but rather than trusting that items will be available on the global scope we will use
import and
require to specify what modules we will be needing as dependencies.
A few changes were necessary:
Updated
index.html
<!DOCTYPE html> <html> <head> </head> <body> System.config({ paths: { '*' :'*.js' } }); System.import('main'); </body> </html>
Using SystemJS we are able to import
system.js file, do any require configuration and tell it the starting module for our ‘app’.
main.ts
import Config = require('app/config'); let config = new Config(); import Service = require('app/services/service'); let service = new Service.Service(config.settings.address); let address = service.getAddress(); if(address === config.settings.address){ console.log(`The service returned ${config.settings.address}`) }else{ console.log(`The service did not return ${config.settings.address}`) }
The main module of our app has a few changes. You may notice that we are using
import and
require keywords to gain access to our other modules. This provides access to the modules that contain the classes we are exporting in the following
.ts files.
app/config.ts
export = class Config{ settings: { address: string }; constructor() { this.settings = { address: '' } } }
and a
service.ts
export = class Service{ address:string; constructor(address:string){ this.address = address; } getAddress(){ return this.address; } }
The primary difference for the
config.ts and
service.ts is we added the
exports before the class declaration so we can allow access to the class in other modules.
Now if we load our
index.html we should see the same results as before in the console.
This was just 2 examples of using
.ts files from different locations within your project. All source code is available at in the
FilesByReference and the
SystemJSModules directories.
If you have more questions feel free to leave a comment and I will get back to you as soon as I can | https://wipdeveloper.com/typescript-accessing-other-ts-files/ | CC-MAIN-2019-39 | refinedweb | 742 | 69.07 |
Each Answer to this Q is separated by one/two green lines.
I’m looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate).
Pybloom is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has an implementation.
Requirements are fast lookup performance and stability. I’m also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there’s a good Java implementation.
Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?
I recently went down this path as well; though it sounds like my application was slightly different. I was interested in approximating set operations on a large number of strings.
You do make the key observation that a fast bit vector is required. Depending on what you want to put in your bloom filter, you may also need to give some thought to the speed of the hashing algorithm(s) used. You might find this library useful. You may also want to tinker with the random number technique used below that only hashes your key a single time.
In terms of non-Java bit array implementations:
- Boost has dynamic_bitset
- Java has the built in BitSet
I built my bloom filter using BitVector. I spent some time profiling and optimizing the library and contributing back my patches to Avi. Go to that BitVector link and scroll down to acknowledgments in v1.5 to see details. In the end, I realized that performance was not a goal of this project and decided against using it.
Here’s some code I had lying around. I may put this up on google code at python-bloom. Suggestions welcome.
from BitVector import BitVector from random import Random # get hashes from from hashes import RSHash, JSHash, PJWHash, ELFHash, DJBHash # # [email protected] / # # copyright (c) 2008, ryan cox # all rights reserved # BSD license: # class BloomFilter(object): def __init__(self, n=None, m=None, k=None, p=None, bits=None ): self.m = m if k > 4 or k < 1: raise Exception('Must specify value of k between 1 and 4') self.k = k if bits: self.bits = bits else: self.bits = BitVector( size=m ) self.rand = Random() self.hashes = [] self.hashes.append(RSHash) self.hashes.append(JSHash) self.hashes.append(PJWHash) self.hashes.append(DJBHash) # switch between hashing techniques self._indexes = self._rand_indexes #self._indexes = self._hash_indexes def __contains__(self, key): for i in self._indexes(key): if not self.bits[i]: return False return True def add(self, key): dupe = True bits = [] for i in self._indexes(key): if dupe and not self.bits[i]: dupe = False self.bits[i] = 1 bits.append(i) return dupe def __and__(self, filter): if (self.k != filter.k) or (self.m != filter.m): raise Exception('Must use bloom filters created with equal k / m paramters for bitwise AND') return BloomFilter(m=self.m,k=self.k,bits=(self.bits & filter.bits)) def __or__(self, filter): if (self.k != filter.k) or (self.m != filter.m): raise Exception('Must use bloom filters created with equal k / m paramters for bitwise OR') return BloomFilter(m=self.m,k=self.k,bits=(self.bits | filter.bits)) def _hash_indexes(self,key): ret = [] for i in range(self.k): ret.append(self.hashes[i](key) % self.m) return ret def _rand_indexes(self,key): self.rand.seed(hash(key)) ret = [] for i in range(self.k): ret.append(self.rand.randint(0,self.m-1)) return ret if __name__ == '__main__': e = BloomFilter(m=100, k=4) e.add('one') e.add('two') e.add('three') e.add('four') e.add('five') f = BloomFilter(m=100, k=4) f.add('three') f.add('four') f.add('five') f.add('six') f.add('seven') f.add('eight') f.add('nine') f.add("ten") # test check for dupe on add assert not f.add('eleven') assert f.add('eleven') # test membership operations assert 'ten' in f assert 'one' in e assert 'ten' not in e assert 'one' not in f # test set based operations union = f | e intersection = f & e assert 'ten' in union assert 'one' in union assert 'three' in intersection assert 'ten' not in intersection assert 'one' not in intersection
Also, in my case I found it useful to have a faster count_bits function for BitVector. Drop this code into BitVector 1.5 and it should give you a more performant bit counting method:
def fast_count_bits( self, v ): bits = ( ) return bits[v & 0xff] + bits[(v >> 8) & 0xff] + bits[(v >> 16) & 0xff] + bits[v >> 24]
In reaction to Parand, saying “common practice seems to be using something like SHA1 and split up the bits to form multiple hashes”, while that may be true in the sense that it’s common practice (PyBloom also uses it), it still doesn’t mean it’s the right thing to do 😉
For a Bloom filter, the only requirement a hash function has is that its output space must be uniformly distributed given the expected input. While a cryptographic hash certainly fulfils this requirement, it’s also a little bit like shooting a fly with a bazooka.
Instead try the FNV Hash which uses just one XOR and one multiplication per input byte, which I estimate is a few hundred times faster than SHA1 🙂
The FNV hash is not cryptographically secure, but you don’t need it to be. It has slightly imperfect avalanche behaviour, but you’re not using it for integrity checking either.
About uniformity, note that the second link only did a Chi-square test for the 32-bit FNV hash. It’s better to use more bits and the FNV-1 variant, which swaps the XOR and the MUL steps for better bit-dispersion. For a Bloom Filter, there’s a few more catches, such as mapping the output uniformly to the index range of the bit-array. If possible, I’d say round up the size of the bit-array to the nearest power of 2 and adjust k accordingly. That way you get better accuracy and you can use simple XOR-folding to map the range.
Additionally, here’s a reference explaining why you don’t want SHA1 (or any cryptographic hash) when you need a general purpose hash.
Look at the array module.
class Bit( object ): def __init__( self, size ): self.bits= array.array('B',[0 for i in range((size+7)//8)] ) def set( self, bit ): b= self.bits[bit//8] self.bits[bit//8] = b | 1 << (bit % 8) def get( self, bit ): b= self.bits[bit//8] return (b >> (bit % 8)) & 1
FWIW, all of the
//8 and
% 8 operations can be replaced with
>>3 and
&0x07. This may lead to slightly better speed at the risk of some obscurity.
Also, changing
'B' and
8 to
'L' and
32 should be faster on most hardware. [Changing to
'H' and 16 might be faster on some hardware, but it’s doubtful.]
It’s almost a decade since the most recent answers on here. And times do change.
Looks like the most popular maintained bloom filter package in late 2019 is now this one:, available on PyPi as pybloom_live:
I’ve put up a python bloom filter implementation at
It’s in pure python, has good hash functions, good automated tests, a selection of backends (disk, array, mmap, more) and more intuitive arguments to the
__init__ method, so you can specify an ideal number of elements and desired maximum error rate, instead of somewhat ethereal, datastructure-specific tunables.
| https://techstalking.com/programming/python/modern-high-performance-bloom-filter-in-python-closed/ | CC-MAIN-2022-40 | refinedweb | 1,282 | 64.41 |
This document contains the following sections:1.0 Introduction
This document provides the release notes for release 10.1 of Allegro Common Lisp and related products. Many sections are divided into non-backward-compatible changes (that produce different behavior in release 10.1 compared to release 10.0) and changes unrelated to backward-compatibility. Note that a bug fix is not considered a backward-incompatible change even if it does result in changed behavior because the previous behavior was erroneous.
You may wish to look at the 10.0 Release Notes, included in this distribution as the file version-100-release-notes.htm.
This document describes the changes, major and minor, from 10.0 to 10.1..1. See sys:update-allegro for information on getting patches and updates.
This section is included in the versions 10.0 and 9.0 updated release notes because some updates are retrofitted to those earlier releases. Each change says whether it applies to releases prior to version 10.1.
(typep x type)into
(funcall predicate x). The new argument, when it is true and when the predicate is a symbol naming a function, causes the transformed form to be
(predicate x), potentially allowing compiler macros for predicate (if such exist) to further inline code. Thie feature is for 10.1 and later only.
acl-socket:*ssl-features*
acl-socket:*ssl-features*is a list of supported SSL features. In 10.1, it contains
:snionly. Also, acl-socket:make-ssl-client-stream accepts a server-name keyword argument. This feature and the variable are 10.1 only. They are not supported (and the variable does not exist) in 9.0 and 10.0.
(require :mplog). There is a patch which exports the symbol
sys::mplog. Without that patch, you need to fully package qualify (as unexported) that symbol. All other functionality is named by exported symbols in the mplog package. See The multiprocessing logging (mplog) facility in miscellaneous.htm.
nilor a non-negative fixnum less than or equal to the length or the prefix argument. With the value
nil(the default) the results are unchanged. Modified by a patch released in April, 2018. The change is for release 10.1 only.
:utf-8sexternal format is described there. This change applies to releases 10.0 and 10.1 but not to release 9.0.
fasl files (compiled Lisp files) created by releases of Allegro CL prior to 10.1 will not load into Allegro CL 10.1..
See Installation sizes and supported Operating System versions in installation.htm for a list of supported platforms and minimal Operating System versions. Allegro CL is tested with new OS versions as they are released (but not pre-release or beta versions). In general, Allegro CL can be assumed to work on newer versions, including those released after Allegro CL 10.1 itself was released.
The :ssl module, when loaded, finds the newest installed version of OpenSSL libraries on your machine and loads them. See Secure Socket Layer (SSL) in socket.htm for information on how OpenSSL libraries are found and loaded.
If you load foreign libraries which themselves use OpenSSL, either in a development image or in a delivery (application) image, those libraries must be compatible with the version of OpenSSL used by the :ssl module. If they are not, the :ssl module cannot be used.
The current supported version of OpenSSL is 1.0.1. We understand there are plans to end support for version 1.0.1 on December 31, 2016. By that time, support for version 1.0.2 will be available.
Allegro CL is now available on the ARM-64 platform under some linux implementations. The ARM-64 is also called the ARM64, the ARMv8, and the Aarch64
The ARM-64 processor (see the Wikipedia description here and the designer website here) is a RISC processor particularly suited to smaller devices.
Only 64-bit Allegro CL runs on the ARM-64, with SMP and non-SMP versions (there is no 32-bit Lisp on the ARM-64). Common Graphics and the IDE (see cgide.htm) are supported in the non-SMP ARM-64 version.
Installation on the ARM-64 is similar to installation on other Linux platforms. See installation.htm. See the Installation sizes and supported Operating System versions in that document for information on minimal operating system versions needed by Allegro CL.
Allegro CL 10.1 is only supported on macOS version 10.11 or later. It is not supported on versions 10.10 or earlier.
Common Graphics and the IDE are now supported on macOS but are not supported on the SMP version on the Mac. See Section 8.5 Common Graphics and the IDE on the Mac for more information. Both the IDE and CLIM require certain tools (X11, GTK, Open Motif) which may have to be installed separately. See Installation on macOS in installation.htm for details.
The Runtime Analyzer (see runtime-analyzer.htm) does not work properly on the 64-bit macOS port (there is no problem on the 32-bit port).
Building
shared libraries on macOS in
foreign-functions.htm describes how to create a
shared library suitable for loading into Allegro CL. We have
determined that the
-flat_namespace to the
ld used to create the shared library is necessary, as shown in
the linked section.
We have had reports that updating macOS may cause X11 to be stop working properly. The symptom is blank rectangles in Common Graphics applications (including Gruff). X11 is necessary for the IDE, CLIM, and Allegro Composer. To fix the problem, install the latest version of XQuartz (available from) after updating the macOS.
When building large new images, it is often useful to specify Lisp heap and ACLmalloc heap start locations. See the discussion of the lisp-heap-start and aclmalloc-heap-start keyword arguments in Arguments to build-lisp-image 2: defaults not inherited from the running image in building-images.htm. Here are the initial locations (called `bases') in Allegro CL 10.1).
Version 10.1 is a maintenance release of Allegro CL. It contains bug fixes and optimizations and other improvements but does not have major new capabilities.
There is now support for the ARM processor. See Section 5.2 The ARM-64 (aka ARMv8 and Aarch64) platform for more information.
The following items were included by patches in Allegro CL 10.0 (and some in earlier releases of Allegro CL) after the release of 10.0 and therefore were not in the original 10.0 documentation. All are part of 10.1 and the 10.1 documentation. Some changes to 10.1 may also be backported to 10.0 and/or 9.0, and thus added to the release notes for those products, but those changes are documented in other sections of this document.
:stack-allocatedby sys:lispval-storage-type. Note that on a non-os-threads Lisp the value may be seen as
:stack-allocatedeven if it is outside of the stack it resides and should have been called
:static.
comp:peephole-optimize-switch, and
comp:save-arglist-switchare no longer used. The variables still exist and can be set (so existing code will not beak) but the values are ignored. Peephole optimizations are now always done during compilation and arguments are always saved. It was determined that any possible savings were too small to be worth doing. This change was made in the initial 9.0 release but was not properly documented.
for-as-in-sequencesubclause which iterates over a list or a simple, general vector. Existing (standard) subclauses include
for-as-in-listand
for-as-across(for vector) and this new subclause combines them, as so allows the sequence operated on to be a list or a simple vector at runtime. See cl:loop and the for-as-in-sequence subclause for looping over sequences in implementation.htm. This new subclause was added in a patch in May, 2014.
:tlsv1+. These modifications were added in a patch released in April, 2014.
*global-gc-behavior*controls when and how often global garbage collections happen. On possible value for this variable is a list of a positive integer (specifying a number of seconds), and a real greater than or equal to 1.0 (and optionally a boolean specifying verbosity). This value is designed to trigger global gc's after a specified amount of idle time. But idle time is ill-defined in an SMP Lisp. The list value for
*global-gc-behavior*uses sys:funcall-after-idle-timeout, which, as the next item notes, should not be used in SMP Lisps.
(replace-re "abc abc bc" "^abc\\s+" "_")would return "__bc" rather than "_abc bc". Also,
(replace-re "abc def " "def$" "_" :end 7)would return "abc _ " rather than "abc def ". This has been fixed and the correct values are now returned. As part of the change, match-re has additional keyword arguments start-unbounded and end-unbounded. The behavior of match-re is unchanged if the new arguments are not specified.
excl,
franz, and
stream. In fact, it is illegal for a package nickname to be the package name (so excl was removed). The other two names (which were added when the symbols in those packages were merged into the excl package) were removed so that they would not appear as qualifiers to excl symbols when
excl:*print-nickname*is true. This is a backward incompatible change. Users who depend on stream or franz as nicknames can add them back using rename-package if desired. This item is repeated below in Section 6.2 Non-backward-compatible changes in the base Lisp.
text-edit-panes and
multi-line-editable-textwidgets. It does not work on file streams. The documentation has been updated to make that clear.
The following changes result in different behavior in Lisp compared to earlier releases.
Listed are other changes to and notes about Allegro CL.
nilis returned when the signal number is unknown. The function strsignal (which is the name of the UNIX library function that does the same thing) is a synonym of nice-signal-name. Both work on all platforms. This function is available with a patch in Allegro CL 10.0.
*script-name*is bound to the name of the script file being run when Allegro CL is being executed by a UNIX script file. See Starting on UNIX using a shell script in startup.htm for more information on running Lisp using a script on Unix.
:command-line-argumentsargument to sys:with-command-line-arguments is unspecified, its value is replaced with the actual command-line arguments used to start Lisp. If, however, its value is specified
nil, it is assumed you want the sys:with-command-line-arguments form to do nothing, and that is what now happens.
*unicode-version*is bound to a string containing the version number for the Unicode Character Database used to build the Allegro CL character name table and collation rules.
#!to be ignored by the compiler, so that Lisp code after those initial lines can be compiled. See compile-file in compiling.htm for more information.
nil, sniff-for-unicode returns a third value with information on BOMs (Byte Order Markers) in the argument stream.
:unicodeexternal-format detects BOMS for UTF-8 UTF-16BE and UTF-16LE. The
:unicode-beexternal-format is like
:unicode, but input is assumed big-endian if no BOM is detected. The
:unicode-leexternal-format is like
:unicode, but output is always little-endian with BOM. See The unicode and fat External-Format Types; the unicode BOM is iacl.htm for more information.
:ignore, the unreadable directory is skipped without notice. The skipping without notice behavior is what was done in earlier releases so the default behavior has not changed. When on-error has any other value, calling programs will see the errors that occur from accessing unreadable directories.
:aclmalloc-heap-sizeand
:lisp-heap-start, etc. #\k and #\m (and their uppercase analogs) have been accepted for some time to mean kilobytes and megabytes. See Table Note 3: specifying starts and sizes for heaps and old and new space in building-images.htm for more information.
:regexpmodule. That has now been replaced with the
:regexp2module. The
:regexp2module is described in regexp.htm.
mp:queue. (This macro was also added as a patch to version 10.0.)
The following are multiprocessing and SMP-related changes.
There are no entries at this time. Information may be placed here in documentation updates after the initial Allegro CL 10.1 release.
The CLIM manual has not been updated (other than minor corrections) for the 10.1 release. There have been no significant changes to CLIM functionality compared to 10.0.
Common Graphics and the IDE are supported on Windows SMP Lisp but are not supported in SMP Lisps on the Mac and Linux. They are supported in the non-SMP Lisps on Windows, Linux, and the Mac.
The first subsection describes changes to Common Graphics and the IDE that are non backward-compatible. Please review this section and make whatever necessary changes to your code to obtain the desired behavior.
The second subsection describes other changes to Common Graphics and the IDE. These should not require code changes (please tell us if any do, because that may indicate a bug).
The section Section 8.4 IDE release notes and its subsections provide information about the IDE.
Most changes to Common Graphics in Allegro CL 10.1 are bug fixes and incremental improvements. There is also the following change which assists in identifying the causes of compiler warnings.
save-source-level-debug-info-switch), you can select an individual warning and then the form inside the function that triggered the warning will be selected in the editor. Also, when a runtime error is signaled for a call in a function whose source code location is known, the restarts dialog will include a restart for showing the calling function in the editor, and it will also select the form for the erroring call if source debug info is present.
Here is an example of the pop-up window followed by a picture of the editor. There are two functions whose compilation signaled warnings, the first because the argument was unused and the other (the third definition) because an unbound, undeclared variable (y) is used.
There are no non-backward compatible changes in release 10.1.
cg.gtk::*use-option-key-for-alt*to
nil, though we hope that that is not needed.
*antialiasing*is true and the window is scrolled.
grid-widgets, keystrokes such as Alt-O to invoke the "OK" default-button still work while editing text in a grid cell.
grid-widgets, hangs could occur when dragging a grid row or column past the end of its section to cause the section to auto-scroll, especially for a larger grid that's drawing lots of stuff.
grid-widgets, when the edit-start-trigger of a grid cell is
:get-focus, the text editing will begin whenever the cell gets the keyboard focus, including when selecting the dialog that the grid-widget is on or alt-tabbing back to the application. Previously it required tabbing to the cell or pressing the Enter key.
*antialiasing*is true then the functions draw-to and draw-to-x-y did not update the current drawing position.
The non-SMP version runs on one hardware processor at a time, and corresponds to earlier versions of Allegro CL.
sys:*all-processes*list. (Patched for 10.0).
Allegro CL 10.0 projects should open without problem in Allegro CL 10.1.
Common Graphics and the IDE and available on the Mac but only on the non-SMP Lisp. You must run X11 (it is in the /Applications directory and comes with recent versions of macOS and is usually installed by default on 10.1, but see Installation on macOS in installation.htm for full details). Usage is like that on Linux. See cgide.htm for details.
These are known problems using CG and the IDE on the Mac:
*show-parenthesis-matches-as-pop-up-window*, which must be set to true, as it is initially on macOS, and also
*parenthesis-match-pop-up-milliseconds*.
This section is repeated from the 10.0 release notes.
Common Graphics and the IDE run on Windows and Linux with GTK. Certain differences between the two operating systems and windowing systems mean that some things do not work the same in Windows as in GTK and vice versa. The functionality listed here tries to handle the differences. Some of the variables/operators/etc. are only available on one of the two platforms.
GTK Only: all-black menu-items and half-black buttons. There is still a mystery on the GTK platform where all button widgets can turn half black along a diagonal line, and all menu-items on some platforms will be totally black. This seems to happen only when opening a project from the Startup Action dialog, though, so a workaround is to not reopen a project from that dialog and instead to use the Recent menu or File | Open Project just afterward. We have tracked the problem down to the use of transparent-pane windows such as the frame-child of a form window, but beyond that it is a total mystery..
The with-message-window window is now a frameless-topmost-p window on the GTK platforms to avoid problems that it had otherwise. This means that deselecting the owner window will close the message window, and so it may be a good idea to display the message in an additional place such as a status bar.
The winapi module contains certain functions, in the windows package, that perform OS-related tasks. See The Windows API and a Windows API program with windows but without CG in cgide.htm for more information. (franz.com), at the location.
No significant changes.
We discuss ANSI conformance in Conformance with the ANSI specification in implementation.htm. Elsewhere in implementation.htm we discuss specifics of our implementation of certain Common Lisp functionality.
Copyright (c) 1998-2017, Franz Inc. Oakland, CA., USA. All rights reserved.
This page has had significant revisions compared to the 10.0 page.
Created 2017.2.15. | https://franz.com/support/documentation/10.1/doc/release-notes.htm | CC-MAIN-2018-43 | refinedweb | 3,047 | 59.09 |
Here is my problem. I create a dashboard with some different options, each option will display a different figure. I want to embed my dashboard link to some text, each text will lead to different option. For example, if user click on text ABC, it will lead to my dashboard with ABC option, or user click on text DEF, it will lead to my dashboard with DEF option. The problem is the url doesn’t change, if user click on my dashboard url, it will lead to default value. I’m thinking of add payload data to my url since i see for each option the url will have different payload data but still don’t sure how to do this. Is there anyone can help me with this problem?
Hi,
Welcome to the community!
Please take a look on the discussions here. I never tried this approach myself, but I don’t see why it wouldn’t work for your particular case. Follow up if it isn’t clear or if you still have questions, I will be happy to help!
I quite confused. Should I wrap link tag outside dropdown tag? if so, how can control which option will add to the path?
Hi @vuthanhdatt
As @jlfsjunior mentioned with the link he provided, it’s possible to do this using query strings.
The easiest way is to use the new
pages/ api to create a multi-page app, then you can pass variables to a page like this:
See the full example here
from dash import dcc, html import dash dash.register_page(__name__, path="/") layout = html.Div( [ html.Div( "This is a demo of how to use query strings to pass variables to other pages of a multi-page app: " ), html.Span( [ "See the bar chart page with tips data for ", dcc.Link("Saturday ", href="/bar-chart?day=Sat"), "or for ", dcc.Link("Sunday ", href="/bar-chart?day=Sun"), ] ), ] )
bar chart page - note that the layout is a function and it receives the
day attribute from the query string and uses it to update the dropdown, which then updates the figure:"), Input("dropdown", "value")) def update_bar_chart(day): mask = df["day"] == day fig = px.bar(df[mask], x="sex", y="total_bill", color="smoker", barmode="group") return fig
Here’s what it looks like:
Nice. This exactly what i looking for. Many thanks
Hi @AnnMarieW ,
Would it also be possible to have the get paramter (“day=…”) update, once you change the value in the drop-down?
I’ve tried adding it in your example bar_chart.py, but it creates an endless loop:"), Output("_pages_plugin_location", "search"), ], Input("dropdown", "value") ) def update_bar_chart(day): mask = df["day"] == day fig = px.bar(df[mask], x="sex", y="total_bill", color="smoker", barmode="group") return [fig, 'day={}'.format(day)]
hmm, it would be nice to update the query string when the dropdown updates, but I’m not sure if there is a way to do that without reloading the page.
To fix the endless loop issue, you might try using the DropdownMenu component from the
dash-bootstrap-components library. However I wouldn’t recommend this because rather than the dropdown just updating the figure, it will refresh the whole page.
hi @AnnMarieW
btw, does it work for multi options?
currently i’m having a chart that update with multi option input like image below
when i go to
first
sma-50option appear
So is there a way can handle it?
@AnnMarieW
So what type of indi param in layout function?. Currently my type is list, like code below
coms = ['AAA','VCB','HPG','FRT','FTS'] indis = ['sma-5','sma-50', 'sma-200'] def layout(com=coms[0], indi = indis): return html.Div([ html.Div([dcc.Dropdown( id = 'com', options = [ {"label": x, "value": x} for x in coms ], value=com, clearable=False, ), dcc.Dropdown( id = 'indicator', options = [ {"label": x, "value": x} for x in indis ], value=indi, clearable=False, multi=True ) ]), dcc.Graph(className='plot', id='chart') ])
When I query
/chart?com=AAA&indi=sma-50&indi=sma-200 on my terminal appear
Calling... {'com': 'AAA', 'indi': 'sma-50'}
Although i use them same key
indi in my query twice but it seem
indi type pass to the layout function still string not list as you mention.
@vuthanhdatt - Yes, you are correct (I was running a different version when I wrote my response, so I’m going to delete that post so it’s not confusing). Currently it ignores multiple values, and I’m looking into relaxing that restriction. I’ll post back here when I have an answer.
Thanks for raising this issue!
update:
I’m doing a PR to fix this. In the next release of dash-labs it will be possible to return multiple values. So in this case, this is what will be returned:
{'com': 'AAA', 'indi': ['sma-50', 'sma-200']} | https://community.plotly.com/t/is-there-anyway-to-use-the-same-link-but-lead-to-different-option/59655/4 | CC-MAIN-2022-21 | refinedweb | 807 | 64.41 |
How to Prototype Beacon Apps with Estimote and Evothings
Bluetooth beacons are an incredibly valuable way to set up location based triggers for apps. Estimote have a range of Bluetooth beacons that are quite easy to set up and experiment with.
One of the tough parts of testing out Bluetooth beacons is that device simulators aren’t able to access Bluetooth devices, so you need to use physical smartphones to test. This is where Evothings comes in really handy! Evothings is a neat simple way to prototype mobile web apps using HTML5 and JavaScript. Within Evothings, you can make changes to your code and have them automatically appear on your smartphone ready with access to your Bluetooth beacons.
In this article, we’ll look at combining the power of Evothings with Estimote Beacons to prototype a beacon enabled mobile app. In particular, we’ll be building an app that turns a LIFX light on and off via IFTTT if you get close to a beacon. Don’t have a LIFX light? Not a problem! You could replace this functionality with any other HTTP requests you’d like to toggle when nearby.
What You’ll Need
- An Estimote Beacon
- Evothings Studio – This will need to be installed and running on your computer. It is available for Windows, Mac OSX and Linux!
- Evothings Viewer app – This will need to be installed on the iPhone or Android device you will be testing on.
- IFTTT and a knowledge of how to use their Maker channel – I’ve got a guide on that here!
- Some basic HTML and JavaScript knowledge.
The Code
All code for this is available on GitHub for you to use as you wish!
Setting Up Your Estimote Beacons
Go to Estimote Cloud and log into your account (or sign up for one if you don’t have any beacons yet!).
From there, your “Beacons” section should already be loaded. If you don’t have any beacons assigned to your account yet, you’ll need to either buy some via the “Buy Beacons” button, transfer them from another account via the “Transfer Beacons” button or activate your dev kit if it came with an activation code:
If you do have beacons, they’ll appear in a list. Choose the one you’d like to use in this demo and click its “Settings” button:
In here, you will want to take note of the beacon’s MAC address as we will be using it later:
That should be all you need in terms of Estimote beacon set up – it is quite easy at a prototyping level.
Getting Evothings Running
To set up your Evothings workflow ready for our coding, head to the Evothings download page and download the Evothings Studio and Evothings Viewer mobile app. This gives us a really easy way to build our app and test the changes on a smartphone instantly.
When you first open Evothings Studio, you’ll be prompted to connect by getting a connect key. Click “Get Key” to generate the key you’ll use to pair up your workbench with your mobile app:
Then open up Evothings on your smartphone, you’ll be greeted with a screen that asks for that connect key. Type it in and click “Connect”:
When you are connected and ready to go, you will see this screen:
You are now ready to get into coding the app.
Our HTML
The HTML for this app is mostly from Evothings templates they’ve publically provided, just with the title and headings changed, along with the addition of a
<div id="in-room"></div> for some basic status messages to appear on screen.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, user-scalable=no initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" /> <title>Magical room light automation</title> <style> @import 'ui/css/evothings-app.css'; @import 'ui/css/patcat.css'; </style> <script> // Redirect console.log to Evothings Workbench. if (window.hyper && window.hyper.log) { console.log = hyper.log } </script> <script src="cordova.js"></script> <script src="libs/jquery/jquery.js"></script> <script src="libs/evothings/evothings.js"></script> <script src="libs/evothings/ui/ui.js"></script> <script src="app.js"></script> </head> <body> <header> <button class="back" onclick="history.back()"> <img src="ui/images/arrow-left.svg" /> </button> <img class="logotype" src="ui/images/logo.svg" alt="Evothings" /> </header> <h1>Magical room light automation</h1> <div id="in-room"></div> </body> </html>
I’ve also put my custom CSS within
ui/css/patcat.css:
html, body, section, main footer { background: #390066; color: #fff; text-align: center; } header { background: #EACFF3; } .in-room, .in-room body, .in-room section, .in-room main footer { background: #F3EC97; color: #333; } .in-room h1 { color: #333; } .in-room header { background: #F3EDE6; } h1 { padding: 0 0 1em; }
Our JavaScript Code
Our
app.js file looks like so:
var app = (function() { var app = {}, roomBeacon, updateTimer = null, inRoom = false; app.initialize = function() { document.addEventListener("deviceready", function() { evothings.scriptsLoaded(onDeviceReady); }, false); }; function onDeviceReady() { startScan(); $("#in-room").html("Out of room!"); updateTimer = setInterval(checkForBeacon, 1000); } function startScan() { function onBeaconsRanged(beaconInfo) { for (var i in beaconInfo.beacons) { var beacon = beaconInfo.beacons[i]; if (beacon.rssi = 2 && inRoom) { console.log("Exited the room"); inRoom = false; $("html").removeClass("in-room"); $("#in-room").html("Out of room!"); turnOffBulb(); setTimeout(turnOnBulb, 1000); } } }"); } function turnOffBulb() { $.getJSON("{YOURKEYHERE}?jsoncallback=?", { format: "json" }, function() { console.log("Left room and told IFTTT about it!"); }) .done(function(data) { console.log("Done"); }) .fail(function(data) { console.log(JSON.stringify(data)); }) .always(function(data) { console.log("Finished"); }); console.log("Turn off bulb"); } return app; })(); app.initialize();
Our JavaScript Code Explained
Let’s simplify it down a bit to step through. Our initial skeleton for the code looks like so:
var app = (function() { var app = {}, roomBeacon, updateTimer = null, inRoom = false; app.initialize = function() { document.addEventListener("deviceready", function() { // What we'll want to do when our app is ready! }, false); }; // Other code will be here! return app; })(); app.initialize();
In the code above we namespace everything within
app. The
roomBeacon variable stores our beacon once we have seen it,
updateTimer will store our regular JavaScript interval to check for beacons and
inRoom will remember whether or not the app believes we are in the room (depending on whether it sees the beacon in range or not).
When our JavaScript runs, we direct it to the
app.initialize() function. However, we don’t run any of the functionality until the
deviceReady event and the
evothings.scriptsLoaded event fires. That way we know the app has loaded and Evothings is ready to watch and reload upon any changes.
function onDeviceReady() { startScan(); $("#in-room").html("Out of room!"); updateTimer = setInterval(checkForBeacon, 1000); }
Within
onDeviceReady(), we start scanning for beacons (we’ll cover the
startScan() function soon). Then we set our
#in-room element in our HTML to say “Out of room!” as our default.
We then run
checkForBeacon() every second, which assesses how far away our beacon is and decides if we are in the room or not.
Our
startScan() function looks like so:
function startScan() { function onBeaconsRanged(beaconInfo) { // Will explain this soon! } function onError(errorMessage) { console.log("Ranging beacons did fail: " + errorMessage); } estimote.beacons.requestAlwaysAuthorization(); estimote.beacons.startRangingBeaconsInRegion( {}, onBeaconsRanged, onError); }
All of the functionality of the
startScan() function start with
estimote.beacons.startRangingBeaconsInRegion(). This starts our app scanning for Estimote beacons. We pass in three things:
- A blank object (
{}) to represent that we want all beacons. We could instead pass in a region we’ve defined in our Estimote beacon options like so:
{identifier:'MyRegion'}.
- Our success function we want to run when we’ve successfully looked for beacons in range (
onBeaconsRanged()).
- Our failure function if something goes wrong (
onError()– a relatively simple function that logs the error).
The inside of our
onBeaconsRanged() function looks like so:
function onBeaconsRanged(beaconInfo) { for (var i in beaconInfo.beacons) { var beacon = beaconInfo.beacons[i]; if (beacon.rssi < 0 && beacon.macAddress == "CE:95:71:43:C9:DD") { console.log("Found room beacon"); roomBeacon = beacon; } } }
This receives an array called
beaconInfo with details of all the beacons that are visible to the device. Our beacons are specifically found within
beaconInfo.beacons, so we iterate through them all and check their RSSI (Recieved Signal Strength Indication) and MAC address. If their RSSI is a negative value, our app has spotted the beacon. We then check to see whether our beacon’s MAC address is the same as the beacon we are looking for. If so, we log the event into our console and set our
roomBeacon variable to this beacon.
For iOS 8, your app is required to ask for permission to use location services (on other platforms, this function will gracefully degrade and do nothing):
estimote.beacons.requestAlwaysAuthorization();
You’ll remember we ran the function
checkForBeacon() every second. That function looks like so:
function checkForBeacon() { if (roomBeacon) { console.log("Checking beacon distance"); if (roomBeacon.distance < 2 && !inRoom) { console.log("Entered the room"); inRoom = true; $("html").addClass("in-room"); $("#in-room").html("In room!"); turnOnBulb(); setTimeout(turnOnBulb, 1000); } else if (roomBeacon.distance >= 2 && inRoom) { console.log("Exited the room"); inRoom = false; $("html").removeClass("in-room"); $("#in-room").html("Out of room!"); turnOffBulb(); setTimeout(turnOnBulb, 1000); } } }
If we have a
roomBeacon, then we run our tests on how far away that beacon is. If you are within two meters of the beacon and we haven’t set
inRoom to true, then we have just entered the room. We set
inRoom to
true, log a message to the console, show the message “In room!” on our app and change the class on our
<html> tag so we can restyle our app depending on if we’re inside the room or not. We also run
turnOnBulb() which will do just that – turn on our LIFX bulb using IFTTT.
If we are further than two meters away from the beacon but the app still thinks we are in the room, we set
inRoom to
false and set everything to be the opposite of the above. We run
turnOffBulb() to turn off the LIFX bulb.
One thing you might be wondering – why do we have a
setTimeout() re-running
turnOnBulb() and
turnoffBulb()? I’ve found sometimes with IFTTT (or possibly the LIFX connectivity in my home), it doesn’t always receive the request the first time. Running it twice seems to fix this nicely!
To actually turn the LIFX bulbs on and off, we make a JSON request to an IFTTT’s action via{YOURKEYHERE}?jsoncallback=?. Turning them off is the same idea, just with
left_room as the trigger name instead of
entered_room. If this all sounds like gibberish to you, have a read of my “Connecting the IoT and Node.js to IFTTT” tutorial first!"); }
Testing On Your Device
To test the app, click the “Projects” tab and drag your
index.html into Evothings Studio to add it to the projects to watch. Then click “Run” to run it:
If you’ve got the Evothings Viewer open on your smartphone, you should have the app appear and run as intended! If you enter the room with the beacon, your light should turn on (and the app should visually show you’ve entered the room) and if you exit the room, the light should turn off (and the app should show you have left).
Conclusion
Prototyping with Estimote beacons and Evothings is just the start, from here you can create a Cordova or Phonegap app, copy over the files from this one and export it into an app you can submit to app stores. You’d just need to add in a way for custom beacons to be added into settings (as you won’t want everyone relying on your beacon unless it is for a public place like a cafe).
If you create a Bluetooth beacon powered prototype with Estimote beacons and Evothings, please share it in the comments or get in touch with me on Twitter (@thatpatrickguy). I’d love to see what you come up with and share it around! | https://www.sitepoint.com/how-to-prototype-beacon-apps-with-estimote-and-evothings/ | CC-MAIN-2018-17 | refinedweb | 2,011 | 65.93 |
*
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Swing / AWT / SWT
Author
Help With a simple GUI
Samuel Weston
Greenhorn
Joined: Oct 24, 2013
Posts: 22
posted
Jun 02, 2014 09:45:23
0
hey, i'm trying to create a program that results in 2 GUI's. the first would be a prompt for the user to input information, and the second would have the inputted information as well as a few sentences-appear on it.
my real goal isn't the result so much as understanding the process of making GUI output based on the user's input as opposed to the programmers.
that being the case, i'm not looking for a package to do my work for me, I'm looking to make the code from (relative) scratch...
to do this, I tried manipulating the code for GUI that I happened to know-to include the Scanner class, that is, to allow for the users input...but its not working.
for all intents and purposes, assume all output (e.g all 'println') are meant to be on the GUI
also, I kept my notes in there, I hope they're more helpful than distracting
(read them as a reflection of my thought process. they in no way dictate the "correct" way of carrying my goals out)
heres the first class
package choices; import java.util.Scanner; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.FlowLayout; public class SequenceOptions extends JFrame{ public static void main(String[]args){ Scanner input = new Scanner(System.in); //declaring a variable to store users inputted values String username; System.out.println("welcome user"); System.out.println("State your name"); Scanner sc = new Scanner(System.in); String name = sc.nextLine(); System.out.println("your name is " + name + "."); //now, i want to put this on a GUI so... //so im going make a simple GUI that just posts the above sentence } //first, ill need to create a variable to store the info... private JLabel item1; //next comes the constructor -we're just plugging in the info //(D.C)just f.y.i the dude didnt realy explain why we're using super or what it does public SequenceOptions(){ super("This is the Title bar"); //for the Layout we'll use a default layout //D.C dont know what we're doing now-flowlayout inside the paranthesis? whats that mean? //but just copying the code that i know works setLayout(new FlowLayout()); //ok so now we want txt in the GUI right? //so for that we'll need the variable we created before with the JLabel attributes //the attributes will let the txt be on the GUI as per the 'rules' of JLabel //D.C again , not fully sure of what im doing, im just copying code that i know works item1 = new JLabel("this is a sentence"); //now we want to put that stuff onto the GUI pane.so we're ging to take the variable //with out info , and put it on the pane like so- add(item1); //now im going to execute the GUI } }
the second class
//this is the execution class for SequenceOptions
package choices; import javax.swing.JFrame; public class SequenceOptions1b { public static void main(String [] args) { //ok! so now we want to print stuff out right? SequenceOptions manly = new SequenceOptions(); manly.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); manly.setSize(275,180); manly.setVisible(true); } }
darn. i want to put the users name onto the GUI but the Scanner code is outside the GUI coding
Im SURE this has been dealt with before. the basic question is
1)how make a GUI that prints Scannernextline or whatever
2)how do i make multiple GUI without having to write the same code over and over?
my aim is to make one pane a prompt for user name
and a second pane that outputs the inputted name (as well as other words)
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 38334
23
posted
Jun 02, 2014 10:07:35
0
I shall move this discussion to our GUIs forum.
Don't attempt to combine logic and display. The GUI classes are for display and there are other classes for the logic. Make sure to keep them separate. You should not therefore use a Scanner or System.out as well as the GUI. You should get the logic working before you try going near the GUI. You can have a class like this
/** * Note written as immutable class */ public final class NameMessage { private final String name; public NameMessage(String name) { this.name = name; } public String getNameAndMessage() { return name + " should have been strangled at birth."; } }
And you call it like this:-
NameMessage nm = new NameMessage("Campbell Ritchie"); System.out.println(nm.getNameAndMessage());
When you have that sort of thing working, then consider a GUI. I suggest you have a controlling class which has a NameMessage object and a GUI as fields. You can enter the name in something like a text field and print the message to a label. You will want a button or menu item or similar to create a new NameMessage object and display its message.
But once you start using a GUI, use that exclusively. And when I said
a
GUI I meant a GUI. You do not want two GUIs in one application. You can have several components in the same frame, or show dialogue windows, but don't attempt to use two frames.
Rico Felix
Ranch Hand
Joined: Mar 08, 2014
Posts: 247
3
I like...
posted
Jun 02, 2014 10:08:12
0
Instead of repeating stuff that has already been explained, I'll point you to the
API Documentation
as well as the
Java Tutorials
If after searching through the content provided you haven't found a solution to your problem, I will try to lead you in a direction if someone else hasn't.
Rico Felix
Ranch Hand
Joined: Mar 08, 2014
Posts: 247
3
I like...
posted
Jun 02, 2014 10:42:26
1
Here is a quick demonstration using some code of what I assume you are trying to achieve:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class InputAndUpdate { public static void main(String[] args) { /* Create a frame */ JFrame frame = new JFrame("Title Goes Here"); /* Create a label to add to frame */ JLabel label = new JLabel("Some Text"); /* Create a button to add to frame */ JButton button = new JButton("Change Text"); /* Set layout properties for the frame */ frame.setLayout(new BorderLayout()); /* Add label to frame */ frame.add(label, BorderLayout.NORTH); /* Add button to frame */ frame.add(button, BorderLayout.SOUTH); /* Set frame size */ frame.setSize(300, 250); /* Set location on screen */ frame.setLocationRelativeTo(null); /* Show frame */ frame.setVisible(true); /* To close frame on exit */ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); /* Add action to the button */ button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { /* Get input from user and update * text in the label */ label.setText( JOptionPane.showInputDialog( frame, "Enter some text:")); } }); } }
The main focus is on the label's
setText(String)
method and the
JOptionPane
's
showInputDialog(Component, Object)
method.
You can use this example along with the references that I've provided and you should be on your way to solving your problem and walking away with new knowledge.
Samuel Weston
Greenhorn
Joined: Oct 24, 2013
Posts: 22
posted
Jun 02, 2014 11:35:42
0
thank you everyone (Campell Ritchie and Rico Felix)
you've given me something to mull over and play around with
thank you very very much
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 38334
23
posted
Jun 02, 2014 13:43:58
0
Nice suggestion, RF. I was thinking of a text field for input, so the two are rather different.
Rico Felix
Ranch Hand
Joined: Mar 08, 2014
Posts: 247
3
I like...
posted
Jun 02, 2014 14:29:00
0
Thank you sheriff!!
The text field I'm sure is what he'd go for and he should... I've only used the
label
and
button
combination to demonstrate a simple and quick application for the functionality that I'm assuming he's looking for... I've also deliberately chosen those two so he can implement the real stuff on his own...
I agree. Here's the link:
subject: Help With a simple GUI
Similar Threads
ItemListener identifying which JCheckBox from array is chosen?
gui problems
Help with assignment and JFileChooser
retrieving variables from another class
Need help on college work
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/634540/GUI/java/simple-GUI | CC-MAIN-2014-35 | refinedweb | 1,445 | 70.94 |
IP2017 - Issues Creating And Testing Applet Server Script Using Workspace
(Doc ID 2304443.1)
Last updated on FEBRUARY 28, 2018
Applies to:Siebel Tools - Version 17.0 [IP2017] and later
Information in this document applies to any platform.
Symptoms
On : 17.0 [IP2017] version, Siebel VB / eScript / COM
Opening a Checkpointed Workspace does not run any script written in that workspace.
STEPS
-----------------------
The issue can be reproduced at will with the following steps:
1. Create a new Workspace in Siebel Tools.
2. Open the Workspace and locate an applet (e.g., LOY Member List Applet)
3. Edit Server Scripts and add any script, e.g.:
function WebApplet_PreInvokeMethod (MethodName)
{
if (Name == "NewQuery")
{
TheApplication().RaiseErrorText("Hit the NewQuery Event");
}
return (ContinueOperation);
}
4. Close the Scripts Window.
5. Launch the Siebel Web Client (e.g., Siebel Loyalty ENU)
6. Access the Workspaces view.
7. Select the Edit-In-Progress Workspace.
8. Click Open
9. Click Inspect
10. Close the Workspaces view
11. Access the view containing the scripted applet. Note the error that appears:
We detected an Error which may have occurred for one or more of the following reasons: No records exist for the current query.(SBL-DAT-00468)
1) Inspecting a Workspace that has an Applet or BC scripted for the first time in that workspace results in the error noted.
2) Inspecting a Workspace with scripted objects previously delivered executes the script normally.
3) Inspecting a Workspace with additional script on the same object only executes the delivered script but does not error.
3) Opening a Checkpointed Workspace does not execute scripts written in that workspace, but does execute script previously delivered to the main branch.
Changes
Cause
In this Document | https://support.oracle.com/knowledge/Siebel/2304443_1.html | CC-MAIN-2018-47 | refinedweb | 281 | 69.89 |
One thing I always wanted to add to the Cognifide PowerShell Console for Sitecore but never had the chance to investigate properly, was GUI and user interaction. For example in a regular PowerShell console when an irreversible action needs to be taken or one that user needs to be notified about – a question is asked:
Unfortunately due to the stateless and non-persistent nature of HTTP connections this is not easily achievable in Sitecore Sheer environment especially since in our case a PowerShell session usually lives in a separate thread within a Sitecore Job.
I knew this had to be achievable as Sitecore allows for rich interaction with user e.g. during a package installation process but I could not find any documentation regarding this subject, and my Sitecore gurus’ posts were pretty discouraging in that regard:
- All About Jobs in the Sitecore ASP.NET CMS by John West
- Using Sitecore Jobs by Brian Pedersen
But heck(!) Somehow the package Installer manages to show those pesky Overwrite/Merge/Skip dialogs, right?
Not discouraged by the early discoveries, I’ve dusted my trusty copy of Reflector and dived inside the installer code. Following are the findings of my investigations and sample solutions for using them with your Jobs.
JobMonitor
The key role in the asynchronous communication between Job and Sheer UI plays the JobMonitor control. For your job to be able to talk with your dialog you need to place this control on your dialog which you can do the following way. Add the namespace JobMonitor lives in to your code:
using Sitecore.Jobs.AsyncUI;
Now add JobMonitor as a field to your Sheer dialog/control:
protected JobMonitor Monitor;
Now we need to instantiate and use the control. For that modify the OnLoad method in your dialog to include the following:
protected override void OnLoad(EventArgs e) { base.OnLoad(e); // your code ... if (Monitor == null) { if (!Context.ClientPage.IsEvent) { Monitor = new JobMonitor {ID = "Monitor"}; Context.ClientPage.Controls.Add(Monitor); } else { Monitor = Context.ClientPage.FindControl("Monitor") as JobMonitor; } } Monitor.JobFinished += MonitorJobFinished; Monitor.JobDisappeared += MonitorJobFinished; // more of your code ... }
Where JobMonitorFinished is a delegate called when the asynchronous task is finished. Now all you need to do in your code to start using the JobMonitor is to run your code in its context:
Monitor.Start("MyJobExecution", "UI", jobRunner.Run);
where jobRunner is an instance of my class that contains any parameters I need for my Job to run. as well as a pointer to your method, but it can as well be containing the code of the job itself. JobMonitor now takes and executes the “Run” method in a new asynchronous Job context. It will also poll the job for any messages and execute them periodically.
Executing UI commands from the Job
Now from the Job context point of view you signal JobMonitor to do stuff for you by sending Messages. You can do some stuff pretty easily like execute the following to show an alert to your user:
JobContext.Alert(Title);
or as for confirmation in the following way:
string response = JobContext.Confirm(“Would you like fries with that?”);
If you want to show do some more elaborate things you might want to either use the following to send a command message and retrieve response:
string response = JobContext.SendMessage(“my:command”);
But if all you want to do is execute a command you can as well use:
string response = JobContext.PostMessage(“my:command”);
to post the message asynchronously and ignore the results.
You can even show dialogs using something like the following (even including parameters to the dialog):
JobContext.ShowModalDialog(parameters, "ConfirmChoice", "800", "300");
and retrieve a response from it. Which finally brings us to the Powershell interactivity that was introduced in the latest console using this technique…
I strongly encourage you to look into the Cognifide PowerShell Console for Sitecore code available on CodePlex. For further investigation on techniques you could employ for some more advanced usages (like sending an item to your dialogs and such. The console available on Sitecore Marketplace now already has this functionality in it and you can use this in multiple ways in commandlets starting with the word Show, like:
- Show-Alert
- Show-Confirm
- Show-Input
- Show-ModalDialog
- Show-YesNoCancel
To find out the latest commandlets in the further versions of console and to find out what parameters each of them can supports execute the following script:
Get-Command Show-* | ft Definition
There, now we have Asynchronous Job-UI communication documented… somewhat. Hope this helps somebody.
This entry (Permalink) was posted
on Thursday, May 16th, 2013 at 12:21 am and is filed under .Net Framework, ASP.NET, Code Samples, PowerShell, Sitecore, Software Development, Solution, Web applications.
You can follow any responses to this entry through the RSS 2.0
feed.
You can leave a response
, or trackback
from your own site. | https://blog.najmanowicz.com/2013/05/16/how-sitecore-powershell-got-gui-support-a-tale-of-jobmonitor-and-sitecore-async-ui-api/ | CC-MAIN-2020-16 | refinedweb | 806 | 54.42 |
Table of contents
- 1 Creating the view and the layout view
- 1.1 Creating the view for the Index action on the Home controller
- 1.2 Creating the layout
- 2 Running the application
- 2.1 Running with IIS or on Mono
- 3 More about actions and views
- 4 Creating the rescue view
- 5 Take a breath
Your first controller and view
For any MonoRail application, the entry point is the Controller. That is the biggest difference from WebForms development where the entry point is the page itself. With MonoRail the controller is executed and decides whether it should render a view and which view. So the controller is the one with control over the application flow, not the pages/views. That reduces the views to their original role: present information, nothing more and nothing less.
It is time to create your first controller. If you have used the wizard to create the project, the controller is already there. Anyway, the controller class should be named HomeController and should exist under the Controllers folder:
Here is the Controller code:
namespace GettingStartedSample.Controllers { using System; using Castle.MonoRail.Framework; [Layout("default"), Rescue("generalerror")] public class HomeController : SmartDispatcherController { public void Index() { } } }
The controller name is, by default, grabbed from the type name. In this case the controller name from MonoRail's point-of-view is simply Home. This controller exposes just one action: Index. Actions are public non-static methods exposed by the controller class.
Although the action code block is empty, there is a behavior implied. When this action is executed, it will render a view named Index. Yes, the action name is used, as convention, to decide the view to render. The action can override this and select a different view using the RenderView method.
Before digging into this, let's create the view.
Creating the view and the layout view
You, as a careful reader that we know you are, have noticed the attributes used on the controller class:
[Layout("default"), Rescue("generalerror")] public class HomeController : SmartDispatcherController
Those defines the following:
- For each view rendered, use the layout named default which lies on the layouts folder
- If any unhandled exception is threw by the action, render the rescue view generalerror which lies on the rescues folder
As stated before, we are using NVelocity view engine. NVelocity is a very simple template engine that supports condition statements, assignments, array creations, and iterate over collections. That is definitely all you need when all you want to do is rendering a view. You can learn more about NVelocity (and how we have improved it) on its page.
Creating the view for the Index action on the Home controller
The views are bound to a controller. In our case we are dealing with the Home controller, so on the Views folder, create a (or use the existing) home folder and create an index.vm file there:
Here is the home.vm contents:
<p> Hello world from my first action. </p>
You can make Visual Studio use the Html editor for .vm files. Use the Open With... option from the context menu.
Fairly simple view. Note that we did not used the html and body tags. We will left that to the layout.
Creating the layout
A layout defines the outter content of a rendered view. You can have multiples layouts on a project, and they should lie on the layouts folder.
Our first layout is very simple, and should be saved as default.vm on the layouts folder.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" ""> <html> <head> <meta http- <title>Layout</title> <link rel="stylesheet" href="$siteRoot/Content/css/base.css" /> </head> <body> $childContent </body> </html>
The $childContent variable defines where the view content should be included on the layout. The $siteRoot variable will represent the root of the application. If the web application is using a virtual dir for example, it will be the virtual dir name. Otherwise it would evaluate to a simple /.
Remember that our controller used the [Layout("default")]? That will make every view rendered from our controller to use this layout.
Running the application
If you created the application with the wizard, just hit Debug\Start or F5. In Visual Studio 2003, Cassini will run. In VS 2005 the internal web server will run. Both allow debug.
On the browser, go to the application url and enter the controller name and the action name plus the extension you have selected. For example:
The browser should render the view content with the layout applied:
Now view the page source code. You should see a well formed xhtml content, as the layout was used.
Running with IIS or on Mono
If you want to run the application using Microsoft Internet Information Services, you must associate the extension you selected (ie rails or castle) with the ASP.Net ISAPI. For more information on this check the Installing document on the User's Guide.
More about actions and views
Views are pretty useless unless you pass parameters and data to it. Each view engine will treat parameters differently. With NVelocity the parameters will turn into variables.
Let's create another action on our HomeController:
[Layout("default"), Rescue("generalerror")] public class HomeController : SmartDispatcherController { public void Index() { } public void DataToTheView() { PropertyBag["name"] = "John Doe"; PropertyBag["today"] = DateTime.Now; RenderView("data"); } }
The DataToTheView action uses the PropertyBag to pass data to the view. It then invokes RenderView to customize the view to render. If we haven't invoked this one, the view name would be datatotheview.
Now lets create the data.vm which should lie on the views\home folder:
<h3> Hello $name! </h3> <h4> Today is $today.ToShortDateString() </h4>
Run the application and go to the home/datatotheview.castle to test your work.
Creating the rescue view
Our controller also uses a rescue. Lets create the rescue view to report errors nicely.
Create a generalerror.vm on the views\rescues folder:
>
Now lets force an exception on a new action just to see the rescue working.
[Layout("default"), Rescue("generalerror")] public class HomeController : SmartDispatcherController { public void Index() { } public void ErroneousAction() { throw new Exception("I'm a bad bad action"); } public void DataToTheView() { PropertyBag["name"] = "John Doe"; PropertyBag["today"] = DateTime.Now; RenderView("data"); } }
Run the application and go to the home/erroneousaction.castle.
Take a breath
That was a crash course on controllers and views. More in-depth information can be found on the reference documentation.
Proceed with Using the SmartDispatcherController. | http://www.castleproject.org/monorail/gettingstarted/firstcontroller.html | crawl-001 | refinedweb | 1,077 | 58.08 |
#include <iostream> #include <cstdio> #include <iomanip> #include <cstdlib> #include <ctime> using namespace std; int main() { int rNumber = 0; int uNumber = 0; const int maxNum = 10; const int minNum = 1; const int range = maxNum - minNum; int counter = 0; //declare random formula srand((unsigned int)time(NULL)); rNumber = 1 + rand() % (range + 1); cout << "Welcome To The Guessing Game!\n"; //goes infinite until the right number is selected or they select -1 do{ while(uNumber != rNumber || uNumber != -1) { cout << "Please Select A Number From 1 Through 10 To See If It Matches The Random Number.\n\n"; cout << "Please Enter -1 To Exit The Program.\n\n"; cout << "Please Enter A Number: \n\n"; cin >> uNumber; counter++; if(rNumber = uNumber){ cout << "You have guessed wisely!\n\n"; cout << "Good Job!\n"; } else{ if(rNumber > uNumber){ cout << "Too High, Try Again!\n\n"; } else{ if(rNumber < uNumber){ cout << "Too Low, Try Again!\n\n";} } } }//End While cout << "You Tried " << counter << " Times\n\n"; cout << "Thank You For Playing The Guessing Game!\n"; } return 0; }
//The Only problem I have with this is that the code runs every time but it tells me that the selection I performed is correct and does not show action that it is creating a random number and i can't fix it, can somebody help me on this? | https://www.daniweb.com/programming/software-development/threads/299085/what-am-i-doing-wrong | CC-MAIN-2017-26 | refinedweb | 219 | 68.6 |
1. I have written an executable script that read a large sample file ("Sample.data") , and uses rbf to create an interpolant function:
- Code: Select all
import numpy as np
from scipy.interpolate import Rbf
x1i,x2i,x3i,x4i,x5i,x6i,x7i,x8i,x9i,x10i,x11i,x12i,x13i,x14i,x15i,di = np.loadtxt('/home/hhamdi/Desktop/RBF_Test/data.txt' , unpack=True)
rbfi=Rbf(x1i,x2i,x3i,x4i,x5i,x6i,x7i,x8i,x9i,x10i,x11i,x12i,x13i,x14i,x15i, di)
2. The vector of values for interpolation i.e. (t1,.. t15) are generated each time with other program in a separate text file (i.e "interpolation.dat"). I read those (t1,..t15) from this file and calculate the corresponding interpolation value Y.
- Code: Select all
Y = rbfi(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15)
However this is very slow, because each time a new vector (t1,...t15) is create, I need to first open the original fixed sample file ("Sample.data"), and again create the fixed interpolant function. Is there any way that I can only create the interpolant function (Rbf) from the Sample.dat file only one time, and to save it somewhre or save it like a native python function, and then only use it for any new value of a vector (t1,...t15). This is very helpful because it save some timed not to open the sample file each time. | http://www.python-forum.org/viewtopic.php?f=6&t=6633&p=8550 | CC-MAIN-2017-13 | refinedweb | 240 | 66.13 |
Recently I learned about GitOps which is a way to manage your Kubernetes clusters and the applications you run on top using Git. The idea is that you can declaratively describe the desired state of your systems in Git and roll out changes as soon as merges occur.
You can immediately see the main benefits of such an approach: Your Git repositories become the single source of truth for both your infrastructure and application code, allowing the teams to increase productivity and stability (you get the Git log to audit changes).
To implement GitOps you can use and configure Flux following some simple steps:
1. Download the helm template
helm fetch ` --repo ` --untar ` --untardir .\.charts ` --version 0.10.2 ` flux
2. Bake the template with your repo (I don’t use Tiller)
helm template flux ` --set git.url="git@github.com:cmendible/kubernetes.samples" ` --set git.path="19.flux" ` --set git.pollInterval="5s" ` --namespace flux ` --output-dir .\.baked .\.charts\fluxcd
As you can see I’m configuring Flux to use my k8s sample repo and the 19.flux folder, which contains a simple deployment file, but of course you can have more resource definitions.
3. Deploy the configuration to your cluster
kubectl apply -f .\.baked\flux\templates\
4. Get the fluxctl CLI
Download the fluxctl CLI
5. Use fluxctl to get the public key
fluxctl identity --k8s-fwd-ns flux
This key is needed to sync your cluster state with the Git repository (GitHub): Copy the key you obtained and use it to create a deploy key with write access on your GitHub repository (Settings > Deploy keys > Add deploy key > check Allow write access > paste the Flux public key > click Add key)
You are all set. If everything runs smooth you’ll find a new deployment in your cluster with the dni-function name.
To learn more about GitOps check: WeaveworksClick here to learn more about Flux
Hope it helps!
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/cmendibl3/gitops-deploying-apps-in-azure-kubernetes-service-aks-with-flux-4ali | CC-MAIN-2022-27 | refinedweb | 322 | 63.19 |
Python attributeError on __del__
I have a python class object and I want to assign the value of one class variable
class Groupclass(Workerclass): """worker class""" count = 0 def __init__(self): """initialize time""" Groupclass.count += 1 self.membercount = 0; self.members = [] def __del__(self): """delte a worker data""" Groupclass.count -= 1 if __name__ == "__main__": group1 = Groupclass()
This execution result is correct, but there's an error message that says:
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound method Groupclass.__del__ of <__main__.Groupclass instance at 0x00BA6710>> ignored
Can someone tell me what me I did wrong?
Answers
Your __del__ method assumes that the class is still present by the time it is called.
This assumption is incorrect. Groupclass has already been cleared when your Python program exits and is now set to None.
Test if the global reference to the class still exists first:
def __del__(self): if Groupclass: Groupclass.count -= 1
or use type() to get the local reference:
def __del__(self): type(self).count -= 1
but do note that this means that the semantics for count change if Groupclass is subclassed (each subclass gets a .count attribute versus only Groupclass having a .count attribute).
Quoting from the __del__ hook documentation:.
If you are using Python 3, two additional notes apply:
CPython 3.3 automatically applies a randomized hash salt to the str keys used in a globals dictionary; this also affects the order in which globals are cleaned up, and it could be that you see the problem on only some of the runs.
CPython 3.4 no longer sets globals to None (in most cases), as per Safe Object Finalization; see PEP 442.
Need Your Help
Linq Filter row differences in historical
NServiceBus 5 without DTC involvement?
nservicebus msdtc nservicebus5I am reading through the documentation and the following confuses me because it states at the top of the document with version 5 we get reliability without using the DTC. | http://unixresources.net/faq/18058730.shtml | CC-MAIN-2019-13 | refinedweb | 324 | 64.3 |
j
query in simple code..i had described all...........
query in simple code..i had described all........... SAME HERE... IS:
abstract class A
{
abstract void callmetoo()
{
System.out.println("anoop");
}
}
ANOTHER FILE IS:
class B extends A
{
void callme()
{
System.out.println
Getting 404 errors - Java Beginners
;
public class login extends HttpServlet {
protected void processRequest... {
/* TODO output your page here
out.println...
I received a 404 errors and I identified that the servlet doesn't appear
need to fix errors please help
modified your code. Check it.
import java.io.*;
class InputName{
static...need to fix errors please help it does have 2 errors what should i fix?
import java.io.*;
class InputName
static InputStreamReader reader = new
Calling hibernate query list() method generates errors
asking your help about this.
I am trying to retrieve a list of jobs from the database, but there seems to be a problem.
In the entity class:
//JobEntity... of the job id from REFRESH to PERSIST, but still the same errors occur.
Does cache
Compiler errors in java
Compiler errors in java Hi,
I used GenerateRDF java file.
Am getting errors when i run this code.
I used command prompt only.
getting errors as no package exist.
i followed your instructions properly.
Please help me out
Servlets errors in same page.
Servlets errors in same page. How do I display errors list in the same page where a form field exists using servlets...........i.e. without using JSP? Please explain with a simple username password program
Java Program Errors
Java Program Errors These are the 2 errors which I am getting when... was not built since its build path is incomplete. Cannot find the class file... ControlPoint cannot be resolved. It is indirectly referenced from required .class
Correct errors - Java Beginners
Correct errors Identify and correct the errors in the following program:
public java Method
{
public static method1(int n, m)
{
n += m... Friend,
Try the following code:
public class Example{
public static void main
Java errors - Java Beginners
uploaded three files to rapidshare.com:
1. the main class:
link:-
http
Java errors when attempting the following.
Java errors when attempting the following. Give the java errors in attempting the following :
1) performing division operation on string value.
2) redefining base class final method in derived class.
3) defining a method...;
<TITLE>Runtime Error in Jsp page</TITLE>
</HEAD>
Robot Class - JSP-Servlet
,
We have modified your code:
function hello
how to include a java class in jsp - JSP-Servlet
.
actually i have a class in which i had written the backend process code and want...how to include a java class in jsp hello sir,
this is my first question, i want know that how to use a java class function's variables
Help please, some strange errors
this errors so i have posted the whole program here. Here i tried to make the monopoly... is causing that run-time errors? Any kind of help will be helpful to me. and let... classes here like Property,Player, main class etc.. I hope i will get some
Display Errors using Message Resources - Struts
Display Errors using Message Resources Hello..
I've a login page where i used applicationresources.properties to display errors for null values and i wrote the condition in formbean.
Now i want to show the errors for invalid
Class files for Jfreechart - JSP-Servlet
Class files for Jfreechart Respected Sir/Madam,
I am... Charting application in JSP.. I have also compiled around 100 files for it.. Though, I found some of the class files are missing.. So, I request you to
bad class file - JSP-Servlet
bad class file (from the JAVA SERVLET PROGRAMMING - O'Reilly) and got a "bad class file...): myservlet.java:9: cannot access HttpServlet bad class file: \HttpServlet.class...bad class file. I'm (desperately) trying to get
I tried to create a dropdown list using struts2.it is not working.can you find the errors in this code?
the errors in this code? /jsp code for creating dropdownlist using...;//submit
</p:form>
</body>
</html>
/java action class for adding... java.sql.SQLException;
import java.util.ArrayList;
public class EmpAdd extends
Coding errors for printing function, please help
Coding errors for printing function, please help Hello,
We, my... it is not actually printing the persons class schedule, we have currently coded the print button for class schedule to bring up the printer menu. I can email the program too
Using a user defined non-packaged servlet class in jsp. - JSP-Servlet
Using a user defined non-packaged servlet class in jsp. i want know... example.
actually i have a class in which i had written the backend process code and want to use those variables in my jsp for further process
verify the code and give me the code with out errors
;
import java.util.Date;
public class add
{
String msg;
JFrame f;
JPanel p... clear the errors and give me correct tutorial for my knowledge improving.pls anyone
JSP - JSP-Servlet
had mentioned what the error says & where, your question can be answered more...JSP Thanks for your reply....regarding dbase connection using beans.
i am using tomcat 5.0. I want to know where i have to place this class file
<errors><error><domain>yt:quota</domain><code>too_many_recent_calls</code></error></errors>
?
Thanks
Hi,
If your application is receiving such error, then stop your application and wait for 10-15 minutes. Then start the application, after... if your limit exceeds the quota.
You will get the error in following xml format
Handling Errors While Parsing an XML File
Handling Errors While Parsing an XML File
This Example shows you how to Handle Errors While... below for Handling Errors:-SAXParserFactory saxpf = SAXParserFactory.newInstance
Any specific log4j statements for Hibernate Envers for showing the Envers related errors
project.
If there is any specific errors related to hibernate envers those are not coming in console.
We had the following statements in log4j
Doubt in using combination of JSP page and Java class. - JSP-Servlet
Doubt in using combination of JSP page and Java class.
I've got... be disabled from clicking.
How to go about doing this in a "JSP Page using a Pure Java class"?
The Database table looks like this:
SeatCode
check for errors
check for errors How can I check for errors
Generated java file - JSP-Servlet
to compile class for JSP:
An error occurred at line: 7 in the generated java file...Generated java file Hello friends,
At run time JSP files....
logout.jsp--includes- logersout.jsp as final code.
As soon as a member had
Importing Your Own Package
Importing Your Own Package I would like to know if it is possible to create a class with your own methods so that you can import them when writing programs
jsp runtime error - JSP-Servlet
-jsp\readingWriting_0005fexcel$jsp.java:5: Class...jsp runtime error sir, when i am running ur prog...
from this website....
i did the same
jsp
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 7 in the jsp file: /jsp/insertdate.jsp
month cannot be resolved
4...jsp when i compile the dateOfBirth.html i got the following errors
What is the errors?
What is the errors? ) while ( c <= 5 )
{
product *= c;
++c;
if ( gender == 1 )
cout << "Woman" << endl;
else;
cout << "Man" << endl;
Post the whole code
Controlling your program
Controlling your program
... is and that too without
making any errors. Until now we have learnt how to use... is the code of the program :
public class Continue
when you forgot your password and want to recover the password. The
forgot password action requires user name and passwords same as you had entered
during...=strPasswordEmail[2];
String subject="Your username & password ";
String message
jsp
= "java.io.*" errorPage = "" %>
<jsp:useBean id = "formHandler" class...;p>%>
<jsp:useBean id="formHandler" class="testing.Beanform" scope...;/p>
<pre class="prettyprint">errors= new Hashtable();
}
public String
java errors
Exception Handling
;
Exception,
that means exceptional errors. Actually exceptions are used for handling
errors in programs that occurs during the program execution. During the program
execution if any error occurs and you want to print your own
types of errors in php
types of errors in php What are the different types of errors in php
jsp error - JSP-Servlet
jsp error HTTP Status 404 - /jsp...
message /jsp/
description The requested resource (/jsp/) is not available... and did not reveal the reason why. 404 errors should not be confused
Get Noticed with Your Resume
Get Noticed with Your Resume
... the importance of your resume- they tell you that your resume can make or break your chances... opportunities than it had a couple of decades back- the IT boom has created many
jsp and ajax - JSP-Servlet
jsp and ajax i had some problem
i want to display the current... this link to find the solution about your problem.
Thanks
Example of ActionSupport class
Example of ActionSupport class
Struts ActionSupport class provides the default... the errors().
clearMessages() - It clears all the messages().
ActionSupport class also provides some fields LOG, textProvider,
validationAware
An
Why System class not in jsp - JSP-Servlet
Why System class not in jsp Hi Friends, why system.out.println("") not working in jsp . But out.println is working I want the reason pz . Thanks Prakash
The import Attribute of page Directive In JSP
package or
the class in your jsp application. Here a Java code has also been provided which
class has been imported in the following JSP code like <%@page...
The import Attribute of page Directive In JSP
Java error class
Java error class
... able class. This mean the
application does not able to catch the error occurred... class and its subclass
define the object to be thrown and the message to be appear
Static database class - JSP-Servlet
Static database class I want to create a static database class and i want to use that class in all servlets ? How can i achive
selectoptions errors in java script
selectoptions errors in java script hi,
in my web page when I select the color of the image it displays that particular color but when i again opt the select option it displays errors message. How do I rectify this problem
WEBSERVICE USING APACHE AXIS - TUTORIAL-2 AXIS FOR EJB-WEBSERVICE (part-5)
;
In DeveloperIQ ( March-2004) ,
we had seen parts 1 to 4 of this tutorial...;
"It
is entirely possible to package your business logic into Java Beans and
not worryabout the EJB API.However,as your business logic becomes more
jdbc-jsp
jdbc-jsp <html>
<head>
<title>your info mail<...;<font color=#1f2e3c>your info mail</font></u></center>... into database but the field names should be different while giving. You had used same name
The errors tag
In this section, you will learn about the errors tag of the Spring form tag library
Convert String to Class - JSP-Servlet
. Reading job name, class name, day & time using xml file only.
Problem is while reading class name, retrieve as a string format but Quartz required in "Class" format
Java class in JSP
Java class in JSP
To use a Java class method in jsp first we need...
the jsp page we now need to create an object of the class by using the new
operator
Simple Java class program - Java Beginners
your code and handle any errors that may arise.
Thank you
Alexander ...Simple Java class program Hi sir,
Please help me Write a simple class that iterates through all the arguments passed in on the command
Scanner class
Scanner class import java.util.*;
class Dd
{
public static void...; Here your code works fine..Which java version you are using?
Actually Scanner class was introduced in java 5
robot class
in the programming.
where exactly robot class is useful.
why is it necessary... provide the class Robot. It gives the java program much power. It can perform all the function that you can do with your mouse and keyboard.The program has even
Spring MVC, request object in val;idator class
variable in the commandClass there is a binding on jsp, which populates the variable.
Now there may be some elements on your view which are not bound to any... question - How will you get these parameters in the validator class and validate
JSP Training
in JSP Pages
What is Custom Tag?
Building Your first custom JSP Tag
Types... and Databases
JSP Errors
Debugging JSP Errors
Custom error page
Looking towards...
JSP Training
Java Server Pages
srvlet compilation error - JSP-Servlet
class not found errors & many such class not are generated. Hi Friend... the servlet-api.jar into the lib folder of your apache tomcat folder.Then set the classpath and restart the compiler to compile the class.
Thanks
how to set the class path variable in tomcat ?
;jsp:useBean
<jsp:setProperty name...;The error lies in your jsp code. Check the syntax properly of using Bean. Anyways...how to set the class path variable in tomcat ? description
Commenting out your code - Java Tutorials
errors
But the given below code compile :
public class Sample2... class Sample{
Character a= new Character('\u000d');
}
When... will comment it so that at least it will get compile :
public class Sample
jsp - JSP-Servlet
jsp The value for the useBean class attribute SQLBean.DbBean is invalid.
This is JSP page...
package SQLBean;
import java.sql.*;
import java.io.*;
public class DbBean
Actionerror and Actionmessage Tags (Non-Form UI Tags) Example
action
errors (in the jsp pages.) if they exists while the actionmessage tag...;/action>
<action name="login" class... an action class that uses methods
addActionMessage(String)
and addActionError
STRUTS2.0 Validation Errors
the previous field errors persist in the page.
For eg:if i am not entering both
I need your help - Java Beginners
I need your help What is the purpose of garbage collection in Java, and when is it used? Hi check out this url :
what are the jar files should i add to resolve the Exception(Class org.apache.jsp.index_jsp Not Found) ?
cannot find servlet class org.apache.jsp.index_jsp or a class it depends...what are the jar files should i add to resolve the Exception(Class org.apache.jsp.index_jsp Not Found) ? what are the jar files should i add
WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP?
WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP? WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP
Tips for Increasing Money Making Abilities of Your Articles
idea for checking your errors. Checking our own article can be tough...
Tips for Increasing Money Making Abilities of Your Articles... your online business is an extremely cost effective and powerful method
jsp - JSP-Servlet
:\apache-tomcat-6.0.18;
2)CLASS_PATH= C:\apache-tomcat-6.0.16;
Create application folder inside C:\apache-tomcat-6.0.18\webapps and put your jsp file...jsp how can i do program in jsp ???
Hi Friend
PHP Displaying the date and time in your timezone Tutorial
PHP Date Time Zone
In PHP Date Time Zone class displays the time of different time zone, along
with time it is also capable of displaying the longitude, latitude and comment
Struts2.2.1 fielderror Tag Example
field errors if they exists.
The following Example will shows how to implement the fielderror tag in the
Struts2.2.1 --
First we create a JSP file named...;action
name="FieldErrorTag"
class="
php display errors
compilation errors - Swing AWT
JSP - JSP-Servlet
JSP Thank you very much for your fast reply.. Now it is working...
In my project I have to insert the data from different JSP pages. I know one... that "use only one class file. In that class file write all the connections to dbase
Struts2.2.1 handle multiple Submits in your application
Struts2.2.1 handle multiple Submits in your application
... --
Directory structure of the Example-
First we create a JSP file named...;h3>Please
enter your order details</h3>
<s:form
Java Exception Class Hierarchy Diagram
class.
The class Exception and its subclasses are defined in such a way that an application may generate a condition which might be caught. The Exception class extends the Throwable class. All errors and exception classes are the subclasses
JSP-EL - JSP-Servlet
JSP-EL Dear Sir,
I know that this below code run on your... Application server weblogic 8.1. In weblogic 8.1 allthough execute the JSP... is:
Home.html
A simple JSP application
EL Uisng In JSP
Name
The ActionForm Class
the error on the jsp page <html:errors/>
tag is used. The <html:errors... The ActionForm Class
... validation
of data, the data will be sent to model (the action class
JSP-EL - JSP-Servlet
JSP-EL Dear Sir,
You gave me that code:
Home.html
A simple JSP application
EL Uisng In JSP
Name... of Expression Language in jsp
Hello ${vij.name
servlet - JSP-Servlet
*;
^
Avanthi.java:7: cannot find symbol
symbol: class HttpServlet
public class Avanthi extends... symbol
symbol : class ServletException
location: class Avanthi
public...{
^
Avanthi.java:39: cannot find symbol
symbol : class ServletRequest
location: class
Ask Programming Questions and Discuss your Problems
Ask Programming Questions and Discuss your Problems
Dear Users, Analyzing your plenty of problems and your love for Java and Java and Java related fields, Roseindia Technologies | http://www.roseindia.net/tutorialhelp/comment/84546 | CC-MAIN-2014-35 | refinedweb | 2,885 | 67.25 |
The following test for a difference between the centre of a sample of data and a given reference point. The one sample t-test assumes normally distributed data, whereas the Wilcoxon signed rank test can be used with any data.
One sample t-test
import numpy as np import scipy.stats as stats # generate the data normDist = stats.norm(loc=7.5, scale=3) data = normDist.rvs(100) # Define a value to check against checkVal = 6.5 # T-test # --- >>> START stats <<< --- t, tProb = stats.ttest_1samp(data, checkVal) # --- >>> STOP stats <<< --- print ('P value:') print (tProb) OUT: P value: 0.007269398564245046
Wilcoxon signed rank test
Note the test value is subtracted from all data (test is then effectively against zero).
rank, pVal = stats.wilcoxon(data-checkVal) print ('P value:') print (pVal) OUT: P value: 0.006010251964988403
One thought on “48. Statistics: One sample t-test and Wilcoxon signed rank test” | https://pythonhealthcare.org/2018/04/12/48-statistics-one-sample-t-test-and-wilcoxon-signed-rank-test/ | CC-MAIN-2020-29 | refinedweb | 148 | 69.99 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
avoiding loading screen? Multi threading in openerp?
Hi all,
Here i creating a database within openerp custom module. ERP is loading while creating database (i know it takes background process for db creation).
but i want creating database in background while clicking "create database" button. i don't want affect user interface by loading screen. How can i achieve this please help me...
and i running openerp under gunicorn mode...
is possible in python threading?
Here is my code
def create_template(self, cr, uid, ids, context=None):
obj = self.browse(cr, uid, ids[0])
openerp.service.db.exp_create_database(obj.database, False, 'en_US')
return self.write(cr, uid, obj.id, {'state': 'confirmed'})
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/avoiding-loading-screen-multi-threading-in-openerp-73864 | CC-MAIN-2018-05 | refinedweb | 166 | 62.75 |
[meta] URL: schemes should be named correctly ("wyciwyg", "keyword", etc
.)
RESOLVED WONTFIX
Status
()
People
(Reporter: benc, Unassigned)
Tracking
({meta})
Firefox Tracking Flags
(Not tracked)
Details
There are RFC's that describe the naming of URL schemes and their syntax. On many occassions, we have demonstrated a disregard for these rules, and I've had my fill of it. Here's a couple examples: 1- Not using "X-" for schemes that are not accepted by IANA. Things like "engine:" and "keyword:" are wrong. If you can't prove that the scheme is registered and you are using it correctly, implement it with the "X-" so everyone knows you are making something up. 2- Not using vendor strings (both Netscape and Mozilla do this wrong). For example, really cryptic, barely making sense and unspecified URL schemes like: "wyciwyg". If you really meant to make it so this is used in your products, and you could not credibly conceive that anyone one else would (and that you would share your intentions with an RFC), then register for the vendor namespace and put your creations in your namespace, rather than cluttering up the root level. 3- Incorrectly formated usage of RFC URLs: Internally, news: URLs include a hostname|IP + port number. This is not how it is describedin RFC 1738. Take the advice given above in point #1 and #2. People have already started to cut and paste these URLs into web pages, which might not make sense to other browsers.
Speaking of #3, mozilla assumes that the @ in the path component of a news URL should always be replaced with %40 yet there is no RFC that requires that.
if we switched back to a grandfathered protocol could we keep the short name?
timeless: I'm not sure what you mean.
Ben: I find it refreshing that there are folks within AOL who care about this. I've brought this up in the past, but the issue was dimissed. I'm not sure how much help I can be, but I'll do what I can. I'm afraid this will be an uphill battle, though. It seems to me that the issues with "news" are separate from naming and thus warrant a separate bug report.
Good point, maybe this should really be a meta bug...
Maybe it should be; but I really think we should wait until there are bugs for a meta bug to track. Before filing those bugs, I think we should take this space (or space on a newsgroup) to test the water and see if fixing this bug is really tractable. There are political and legacy issues. timeless: IMO, they should go away. The Problem is that Mozilla is invading a governed public namespace. Just adding synonymous schemes doesn't fix the problem; the offending identifiers need to be eliminated. I have filed the news scheme issues in bug 133792 and bug 133793, and I modified this bug's summary to remove "news".
QA futuring of various bugs to focus on remaning bugs. If you think your bug needs immediate attention for Mozilla 1.0, set the milestone to "--". I will review these bugs (again) later.
Target Milestone: --- → Future
mozilla does not escape the @ in a path component, if that happens mozilla must take the segment as something else, the hostname perhaps. This is of course possible because mozilla can't handle news:something urls. It will make something the host. There are already a lot of bugs about this. Oh yes, the news versus nntp thing ... we say news when mean nntp. The problem also lies deeply burried with the structure of the mailnews component. In necko we know nsStandardURLs (hierachical) and nsSimpleURLs (flat, only scheme:something). nntp is hierachical, news is simple. Mailnews defines its own mailnewsurl which descents from nsStandardURL. The news url is based on nsMailNewsURL which makes it hierachical ... as long as mailnews does not start to use the necko URIs directly (or also havve a simple mailnewsurl) and make news a simple uri there is no way this can be fixed. But of course this will break the current usage of news urls which means we need a preparser that looks at the structure of the url and then changes the scheme accordingly before giving it to the real parser.
Regarding point 3. The news URLs Mozilla implements are include extentions from draft-gilman-news-url-00. It's unfortunate they never became official, because news: is relatively useless without them. Since I don't ever install MailNews, I wrote a little perl script that groks RFC 1738 + draft-gilman news: URLs. It's ugly and unfinished, but it's worked like a champ for me for months. I'll throw it up on my site in a few minutes... it'll be: I believe Netscape 4.x did news: URLs the same way. > Oh yes, the news versus nntp thing ... we say news when mean nntp. No, we don't. nntp: has a different syntax. They're compared in the help output of my script above (conveniently at the top of the source).
Jeremy: Good enough for me. I've marked bug 133792 INVALID. Bug 133793 is still an issue, though. In URL-encoding the '@', Mozilla isn't representing RFC 1738 or Gilman news: URLs correctly; and it's not correctly processing said URLs that *are* represented correctly.
Why does this bug depend on bug 953 and bug 15372? Neither of those bugs has to do with correcting the URI schemes.
They are examples of schemes that are not named correctly. They should all have an X- in front of them...
So? The bugs aren't about correcting the scheme names. And resolving those bugs has brought this meta bug no closer to resolution. Or are you suggesting that bug 953 and bug 15372 need to be reopened?
This is a tracking bug. We use the fields we got, I could say this bug "blocks" them instead, but tha would make even less sense.
The dependency relationship is exactly what you want for a tracking bug. When all the dependencies are resolved, the tracking bug goes away. Thus, resolving a tracking bug's dependencies *does* bring the tracking bug closer to resolution. That's clearly not happening here. If you think it's appropriate to have a bug for each bogus URI scheme and have those bugs block this one, that would make sense. But what this bug is being used for now makes no sense at all. Either those bugs should be filed, or this should not be a tracking bug.
Is this bug actually being used or usefull to anyone anymore, or can i kill it?
What do you mean by "useful"? Are you asserting that Mozilla should continue to violate IETF guidelines for proprietary URI schemes? If not, do you have an alternative proposal for addressing the problem (or at least noting it, which is all this bug does)?
Travis: I don't know about other reporters, but I'd like to think all my bugs are useful:) Do you have an objection to the bug report itself? If not, please don't go into bugs proposing they get closed, esp. if you are not carrying a lot of cred for the area.
Status: NEW → RESOLVED
Closed: 4 years ago
Resolution: --- → WONTFIX | https://bugzilla.mozilla.org/show_bug.cgi?id=130089 | CC-MAIN-2019-26 | refinedweb | 1,224 | 74.59 |
The class hold dynamic table statistics for a table. More...
#include <table_stats.h>
The class hold dynamic table statistics for a table.
This cache is used by internal UDF's defined for the purpose of INFORMATION_SCHEMA queries which retrieve dynamic table statistics. The class caches statistics for just one table.
Overall aim of introducing this cache is to avoid making multiple calls to same SE API to retrieve the statistics.
Store the statistics form the given handler.
Store the statistics.
Check if we have seen a error.
Build a key representing the table for which stats are cached.
Get checksum.
Return statistics of the a given type.
Check if open table in progress.
Check if the stats are cached for given db.table_name.
Read dynamic table/index statistics from SE by opening the user table provided OR by reading cached statistics from SELECT_LEX.
Read dynamic table/index statistics by opening the table OR by reading cached statistics from SELECT_LEX.
Read dynamic table/index statistics from SE API's OR by reading cached statistics from SELECT_LEX.
Set checksum.
Set open table in progress.
Mark the cache as valid for a given table.
This creates a key for the cache element. We store just a single table statistics in this cache.
Set error string for the given key.
The combination of (db, table and partition name) forms the key. | https://dev.mysql.com/doc/dev/mysql-server/latest/classdd_1_1info__schema_1_1Table__statistics.html | CC-MAIN-2019-26 | refinedweb | 227 | 69.28 |
Is there a method to save a numpy memmap array into a
.npy
.npy
data = numpy.load("input.npy", mmap_mode='r')
.npy
.npy
numpy.save(output.filename, output.copy())
is there a way to infer the shape of the stored array?
No. As far as
np.memmap is concerned the file is just a buffer - it stores the contents of the array, but not the dimensions, dtype etc. There's no way to infer that information unless it's somehow contained within the array itself. If you've already created an
np.memmap backed by a simple binary file then you would need to write its contents to a new
.npy file on disk.
You could avoid generating a copy in memory by opening the new
.npy file as another memory-mapped array using
numpy.lib.format.open_memmap:
import numpy as np from numpy.lib.format import open_memmap # a 10GB memory-mapped array x = np.memmap('/tmp/x.mm', mode='w+', dtype=np.ubyte, shape=(int(1E10),)) # create a memory-mapped .npy file with the same dimensions and dtype y = open_memmap('/tmp/y.npy', mode='w+', dtype=x.dtype, shape=x.shape) # copy the array contents y[:] = x[:] | https://codedump.io/share/zpZt67lZsDVW/1/flushing-numpy-memmap-to-npy-file | CC-MAIN-2017-13 | refinedweb | 198 | 70.9 |
.
And the decompiled code is ... very strange.
Look below.
Width is int, but setter casts it to nint.
namespace Accelerate
struct vImageBuffer:
...
private nint HeightIntPtr;
private nint WidthIntPtr;
private nint RowBytesCountIntPtr;
...
public int Width
{
get
{
return (int) this.WidthIntPtr;
}
set
{
this.WidthIntPtr = (nint) value;
}
}
...
This is by design; it is highly doubtful you'll ever need Height/Width/BytesPerRow > int32.MaxValue, so we've bound it using the 32-bit data types.
Well,
why didn't Apple thought of this then ?
You are creating a potential limitation to Apple's version because you decided to.
If tomorrow Apple's decide to put specific information in the unused high bits of the 64 bit value, what will happen ? Your customers will be stuck until you fix it.
This is not a good direction to follow. | https://xamarin.github.io/bugzilla-archives/26/26749/bug.html | CC-MAIN-2019-43 | refinedweb | 134 | 71 |
Reminder.url - what does it do?
- jaredchurch
I see in latest release a new attribute of Reminder called url. I expected that this would allow me to add a url to a reminder so that it appears attached to the reminder.
However, I set the attribute and save the reminder, but I cannot see the value in the reminders app, or when an alarm comes on the reminder. The only place I seem to be able to see the reminder is in Pythonista itself.
Have I misunderstood the functionality, is this just an attribute available in pythonista and cannot use it anywhere else? I cannot see to find any more information than on here:
My script to create the reminder is very simple:
import reminders
r=reminders.Reminder()
r.title='Reminder with URL'
r.url=''
r.save()
exit()
I am using iOS version 12.4.5
its not very obvious is docs but this should represent a url or address to access reminders and the said reminder.
webbrowser.open('x-apple-reminder://')
chevk out appex and shortcuts modules
@jaredchurch iOS 13 only, see example here
- jaredchurch
13 only, see example
thanks...
:( a little disappointing for me - I realised afterwards a description I should have added, was that I was hoping it worked like when you create a reminder from safari using share-sheet.
One more reason I need to upgrade my phone :) | https://forum.omz-software.com/topic/6262/reminder-url-what-does-it-do | CC-MAIN-2020-29 | refinedweb | 232 | 71.34 |
As one of the lead PMs for SAP Cloud Platform Mobile Services, I often have the privilege to hear about customers describe the business problems they are trying to solve with mobility, or increasingly with the business opportunities they would like to create with mobility. I’m constantly impressed with the ideas that people come up with!
In several scenarios I see multiple mobile technologies combined in order to achieve a higher purpose. Indeed this concept is productized in the mobile card kit feature of SAP Cloud Platform Mobile Services, where a card can easily be linked to places to get more information, whether it be a web site, another mobile app, or even the Fiori Client. This synergy allows the user to benefit from one technology (in this case SAP Mobile Cards) as an innovation layer while at the same time providing a connection to pre-existing content. I decided to focus on how multiple technologies can be used together in a new way.
That’s what we’re going to build today.
In order to minimize the steps required in this blog, it assumes that you have built a wizard based Android app, using SAML authentication, and that you have configured SAP Mobile Cards to connect to the same Mobile Services account. To build your Android app – follow the steps in the Android tutorial found here, with one exception. When it says to configure your Mobile Services application definition to use Basic auth, use SAML instead. To install and connect SAP Mobile Cards (on iOS, Android or both), follow the steps in the Mobile Interactive Tutorial guide that describes the process.
There are basically 3 steps to enabling your Android app to send a card:
- Create / import a card to send.
- Add a mechanism in your mobile app to let the user indicate that he wants to save information for a specific product.
- Add the code to interact with the Mobile Services REST API to send the card.
That’s it! Okay, let’s get to the details!
NOTE: This is not a tutorial. I’m assuming here that you know your way around Mobile Services. You’re going to need to know your way around Android Studio too. But I hope that even with a basic understanding of Mobile Services and Android Studio you can complete the steps – but feel free to post anything I missed in the comments!
You can do this! And for those of us who jump to the last page of the book and read the ending first, here’s what the results will look like:
Create/Import a card
Add this destination to SAP Mobile Cards under Mobile Applications > SAP Mobile Cards > Connectivity.
Import the mobile card from here. This card that I created is basically a modification of the sample Product card included in Template manager with a few updates for formatting. To import a mobile card, follow the steps to add a new card and select the zip file you downloaded as the “Resource Package”. Give the card a name and Save.
NOTE: If the newly created card does NOT point to the newly created destination, change it in the dropdown to do so.
Add a mechanism to let the user trigger card delivery
This part of the exercise requires the most knowledge of Android Studio, but the steps are relatively simple. We’ll add a menu item in the Item Detail activity to let the user send a card. While we could get smarter on how to do this, in our example the user will see the menu item for every entity type. We’ll add some code to only send a card if the detail item is a product.
Open /res/menu/itemlist_view_options.xml. (it may be located under /res/menu/itemlist_view_options (2)/itemlist_view_options.xml).
Add a new <item> entry above the other two existing items:
<item android:
Add the code to send the card
In this last couple steps we’ll add the code that interacts with the Mobile Services REST API to trigger the card delivery.
Open /java/[yourprojectnamespace]/mdui/ItemDetailFragment.java. This is the class that is associated with the menu we just edited. The screenshot below shows the location in my project, where my namespace is com.company.mobilecardssend;
Add code to the onOptionsItemSelected(MenuItem item) method to handle when the icon is tapped:
case R.id.sendcard: if (entityValueUiConnector.getConnectedObject() instanceof Product) { String productID = entityValueUiConnector.getPropertiesWithValues().get("ProductId"); new CardManager().execute(productID); } else { Toast.makeText(getActivity().getBaseContext(), "Sorry, Product cards only!", Toast.LENGTH_LONG).show(); } return true;
directly above the following line:
case R.id.delete_item:
This added code determines if you’re on the Product Item detail page, obtains the Product ID for the current record, and triggers card delivery on a separate thread.
Last we need to add the code to send the card. To do this, we’ll create an inner class called CardManager to do the work. CardManager extends Android’s AsyncTask class, a class often used to perform network operations. The following code should be place just above the last “}” for ItemDetailFragment.java:
public class CardManager extends AsyncTask<String, Void, Integer> { @Override protected Integer doInBackground(String... strings) { SAPWizardApplication wizardApp = (SAPWizardApplication)getActivity().getApplication(); ConfigurationData configData = wizardApp.getConfigurationData(); final String connID = "SAPCPMobileServices"; final String templateID = "YOUR_TEMPLATE_ID"; OkHttpClient client = ClientProvider.get(); String serviceURL = configData.getServiceUrl(); String templateURL = serviceURL + connID + "/mobileservices/origin/hcpms/CARDS/v1/cardTypes/" + templateID + "/cardInstances"; try { JSONObject jsonBody = new JSONObject(); JSONArray jsonArray = new JSONArray(); JSONObject uri = new JSONObject(); uri.put("uri", "/Products('" + strings[0] + "')?$expand=SupplierDetails"); JSONArray imageArray = new JSONArray(); imageArray.put(entityValueUiConnector.getPropertiesWithValues().get("PictureUrl")); uri.put("imagePaths", imageArray); jsonArray.put(uri); jsonBody.put("resourceIdentifiers", jsonArray); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, jsonBody.toString()); Request request = new Request.Builder() .url(templateURL) .post(body) .build(); Response response = client.newCall(request).execute(); return new Integer(response.code()); } catch (Exception e) { Log.d("MOBILECARD", e.getMessage()); } return new Integer(0); } @Override protected void onPostExecute(Integer httpCode) { super.onPostExecute(httpCode); if (httpCode == 201) { Toast.makeText(getActivity().getApplicationContext(), "Card Successfully Added", Toast.LENGTH_SHORT).show(); } else if (httpCode == 409) { Toast.makeText(getActivity().getApplicationContext(), "Card has already been Added", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity().getApplicationContext(), "Error Will Robinson!", Toast.LENGTH_SHORT).show(); } } }
This will trigger a message box that prompts you to import several new classes. Make sure you do so or the code won’t compile.
As you can see, you need to supply the Template ID of the card that you are sending. To do this, open the card you created earlier and copy the “ID” field.
At this point, you’ve done everything you need on the client side, but there is still one more step. If you miss this step, you’ll have done all this work but the result of the call to send a card will be a 403 error.
In the client side code, you can notice that we are calling a URL that includes a reference to the connID variable:
String templateURL = serviceURL + connID + "/mobileservices/origin/hcpms/CARDS/v1/cardTypes/" + templateID + "/cardInstances";
Basically the client is requesting that Mobile Services connect to the named Destination on its behalf. In this scenario the destination name is SAPCPMobileServices. All the stuff that is added on the end is actually the Mobile Services REST API to send the card. But if you’ve created the app with the wizard, that destination won’t be available – we have to add it. To do so, open the Mobile Services application definition for your newly created Android app and add the SAPCPMobileServices destination to the Connectivity feature:
Nov 16 2018 Update: This step must be completed AFTER the SDK wizard has been used to create the mobile app. If you try to add the SAPCPMobileServices destination before you run the wizard, the project generation will not complete successfully.
And with that, this blog is all wrapped up! Run your app and navigate to a particular product page. Click on the icon in the menu that allows you to save a card. You should see a Toast message that says “Card Successfully Added” and more importantly, you should receive the card in SAP Mobile Cards. Edit the Product record in your native app then swipe to refresh SAP Mobile Cards and that content will quickly get reflected there as well. Or you can do nothing with SAP Mobile Cards and wait to see that the content gets updated automatically. If you try to add the card again, you’ll receive a 409 status code which means the card’s already been added to the mobile. If things didn’t go exactly as planned, “Error Will Robinson” will appear and it’s time to do a little bit more debugging.
I hope you find this sample useful, happy coding! | https://blogs.sap.com/2018/10/31/sending-a-mobile-card-from-an-sap-cloud-platform-sdk-for-android-app/ | CC-MAIN-2021-21 | refinedweb | 1,472 | 56.15 |
User Name:
Published: 18 Jan 2008
By: Tanzim Saqib
Download Sample Code
This article illustrates how to create a Volta control around Flickr, the popular image hosting service.. In this article, you will end up creating a Flickr widget like the one shown in figure 1.
Currently Volta is at its first CTP release, which was made publicly available on December 5 last year. Volta requirements and the installer can be found at Since it's just the first CTP, there are still a lot of limitations. I hope they will get over those in the next CTP or so.
The widget will have the following features:
Flickr is a very popular photo hosting and sharing service. It is considered to be one of the leading examples of Web 2.0 applications. Users of Flickr can host hundreds of photos and share them with others. Flickr allows users to tag their photos, which make them easy to find. It has some of the best photo management features, which let users control access to photos pretty efficiently. A few of the interesting features of Flickr are the possibility of marking photos as favourites, grouping photo pool and Flickr Interestingness. Flickr also offers users the ability to release images under certain common usage licenses.
Flickr has an open API besides RSS and Atom feeds. The Flickr API offers numerous methods. It supports different popular request and response formats that should be familiar to the third party developers:
We choose REST because it is the simplest among others, and it is performed by simple HTTP GET or POST actions.
The Flickr API exposes 115 methods so far. The methods are categorized in Authentication, Photos, User Activity, Photo Pool, Photo Upload and many more. Few of them are named as follows:
A full listing can be found at:.
The general format of a Flickr request is:
__API_KEY__ is replaced by the API key
The response of a REST query can be rendered by the browser. Simply copy the URL above and paste it into the browser's address bar; then hit enter. You will see a response text somewhat like the following:
As you see the response is pretty straightforward. It simply has a bunch of photo tags and each of the tags has information about that particular photo. A photo tag has the unique identifier of the photo, owner identifier, server information and also a title. In our widget, we need to parse such XML and display the photos.
photo
Note the rsp tag with a stat attribute that has ok as value. It means the API call was completely errorless and successful. Let us make some mistakes intentionally to see how Flickr reacts. Hit the browser using the previous URL with a wrong API Key. You will receive an XML as response like the following:
rsp
stat
ok
Here the stat attribute has fail as value, which means some kind of problem has occurred during the API call and the Flickr API notifies it so that the code can decide whether it should crawl any further or not.
fail
User NSID is an alphanumeric string which uniquely identifies a user. It is often useful, especially in our case where our widget will display the photos of a particular user. In order to retrieve the NSID for a user, Flickr offers a method named flickr.people.findByUsername which takes the Flickr screen name of the user and returns an XML like the following:
flickr.people.findByUsername
First of all, create a new Volta Application and name it VoltaFlickrWidgetDemo. Then, add a new Volta Control application named VoltaFlickrWidget to the solution. Add a class to the Volta control project named FlickrHelper.cs. This class contains very useful methods that fetch Flickr photo data and make them easily accessible by the control. Now include the VoltaFlickrWidget project in the References of the VoltaFlickrWidgetDemo project. The resulting solution structure will be like the one shown in the following figure.
VoltaFlickrWidgetDemo
VoltaFlickrWidget
The Flickr Volta control we are going to develop should be easy to add to the Volta page considering that there is a div element with an id of divWidgetContainer present in the Volta page:
divWidgetContainer
Here VoltaControl1 is the Flickr control we are going to build. Sorry for the naming, but Volta is still immature and can't rename the underlying HTML file of the Volta Control which we will discuss later. Thus, instead of making it confusing, we are keeping it called VoltaControl1. In the above code snippet, VoltaControl1 is initialized with the screen name, API key, control's title, height and width properties. The AddToDiv method of the control adds itself to the div passed as a parameter and then the DownloadPhotos method starts downloading the photos. As soon as AddToDiv is called, the control's HTML file content is injected into the DOM, and HTML elements become accessible like so:
VoltaControl1
AddToDiv
DownloadPhotos
The FlickrHelper class basically performs two operations. One of them is retrieving the NSID of the user against the screen name; and the other is fetching the photo collection of the specified user. The following GetNSID method performs an Asynchronous REST call to the Flickr API and receives the NSID back:
GetNSID
Both the IHttpRequest interface and the HttpRequestFactory class can be found in the Microsoft.LiveLabs.Volta.MultiTier namespace. The AsyncSend method performs the asynchronous call and then calls back the delegate, inside of which the OnNsidLoaded event is fired to notify the user of the FlickrHelper class that the NSID data has just arrived. An instance of the NsidLoadedEventArgs is passed to the subscriber of that event to make the NSID available after parsing the necessary XML:
IHttpRequest
HttpRequestFactory
Microsoft.LiveLabs.Volta.MultiTier
AsyncSend
OnNsidLoaded
NsidLoadedEventArgs
Similarly, an asynchronous call is made for fetching photo feed:
In the above code snippet, an instance of PhotoLoadedEventArgs is passed to the subscriber. In this case the photo URL collection is sent back using a Dictionary object:
PhotoLoadedEventArgs
Dictionary
The contents of VoltaControl1.cs file is basically HTML manipulation, so most of it is self-explanatory and doesn't need further discussion. Yet there are few points to ponder. The most important part is the DownloadPhotos method:
It registers the NsidLoaded event of FlickrHelper, which is handled by flickrHelper_NsidLoaded. Then, the GetNSID method is called. Therefore, as soon as the NSID data is available, it will call the flickrHelper_NsidLoaded method to handle the data:
NsidLoaded
flickrHelper_NsidLoaded
Unlike the NSID, the DownloadPhotos method of FlickrHelper returns a Dictionary of photos URLs and the LoadPhotos method iterates through the photos and displays them in a 3x3 grid using a typical logic for pagination.
LoadPhotos
The construction of the Volta page is simple. The default page would do, but for our project we need an extra div with an id of divWidgetContainer. Moreover, we will add some other HTML code to beautify it. As for the Volta control, we are keeping the Volta page called VoltaPage1. We will use some CSS classes, and add a CSS file named Style.css in the root of the Volta application. In the current release of Volta, CSS files are not automatically discovered even if you add it in the page's HTML as links. To make the Style.css file usable by the Volta page, perform the following steps:
VoltaPage1
namespace
As stated before, the control is very convenient to use:
This is pretty much it. When you download and run this project, you will see Flickr REST calls and photo navigation all performed within an AJAX application created without writing any JavaScript code. Volta generated the necessary client code for us to run the application in multiple browsers.
You have learned how to create a Volta control around the Flickr API. The code was purely written in .NET, yet we achieved complete AJAX functionality without writing a single line of JavaScript code introducing typical ContentProxy kind of things..
--
Mehfuz Hossain
Reply
|
Permanent
link
-----
Tanzim Saqib
B:
W:
[MVP since 2005] [MCAD]
Webmaster of DotNetSlackers
Question or Suggestion?
Feel free to ask my any .NET question
Our Posting FAQ
Long Live .NET
Kazi Manzur Rashid (Amit)
_________________________
Granville | http://dotnetslackers.com/articles/aspnet/BuildingAVoltaControlAFlickrWidget.aspx | crawl-002 | refinedweb | 1,363 | 61.56 |
Eric Ma's Blogurn:uuid:a7611166-dd1f-3792-b62b-0c03a42833502022-07-25T00:00:00ZPython Builtins and their Modern and Convenient Replacements2022-07-25T00:00:00ZEric J. Maurn:uuid:4c4ead57-cabc-34f9-95f3-f2757c4afec3<p.</p> <h2 id="summary-table">Summary Table</h2><p>If this blog post is too long for you, then here's the tl;dr:</p> <table> <thead><tr> <th style="text-align:center">Built-in</th> <th style="text-align:center">Replacement</th> </tr> </thead> <tbody> <tr> <td style="text-align:center"><a href=""><code>csv</code></a></td> <td style="text-align:center"><a href=""><code>pandas</code></a></td> </tr> <tr> <td style="text-align:center"><a href=""><code>logging</code></a></td> <td style="text-align:center"><a href=""><code>loguru</code></a></td> </tr> <tr> <td style="text-align:center">Disable <a href=""><code>warnings</code></a></td> <td style="text-align:center"><a href=""><code>shutup</code></a></td> </tr> <tr> <td style="text-align:center"><a href=""><code>argparse</code></a></td> <td style="text-align:center"><a href=""><code>typer</code></a></td> </tr> </tbody> </table> <p>(You can click on the package/module names to check them out!)</p> <h2 id="handling-tabular-data">Handling tabular data</h2><p>Before <code>pandas</code> came along and became the <em>de facto</em> library for handling tabular data in Python, the built-in <code>csv</code> module was the <em>de facto</em> library before it. The kind of code that we'd have to write before looked like this:</p> <div class="hll"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">"data.csv"</span><span class="p">,</span> <span class="s2">"r+"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span> <span class="n">data_reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">delimiter</span><span class="o">=</span><span class="s2">","</span><span class="p">)</span> <span class="c1"># We would need more code to parse each row...</span> </pre></div> <p>Of course, with <code>pandas</code>, we know that we can now write the following compact code instead:</p> <div class="hll"><pre><span></span><span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span> <span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span><span class="s2">"data.csv"</span><span class="p">)</span> </pre></div> <p><code>pandas</code> did a great job by giving us an intuitive API for reading CSV files and other tabular data formats, such as Excel spreadsheets and Matlab data files. In addition, it also gave us an interface to <em>compact</em> binary representations of data files, such as the <code>.feather</code> or <code>.parquet</code> formats, which, in some cases, can result in 3-20X disk space reductions.</p> <h2 id="logging-information">Logging information</h2><p>If you use logging, you might know that Python has a <a href="">built-in logging module</a>. Logging has advantages over printing, the most significant two that I've experienced being (1) knowing (in the logs) <em>exactly</em> which module a logging line came from, and (2) the ability to redirect the logs to a plain text file that we can search later. As it turns out, <a href=""><code>loguru</code></a> makes logging in your Python code as easy as printing without too much overhead.</p> <p>Here's the code that you might write using the built-in logging facilities in Python:</p> <div class="hll"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="n">name</span><span class="p">)<>And here is the code that, frankly, feels just a <em>tad</em> easier to write, because we eliminate one line of boilerplate:</p> <div class="hll"><pre><span></span><span class="kn">from</span> <span class="nn">loguru</span> <span class="kn">import</span> <span class="n">logger<>The output looks beautiful in the terminal because of its colours!</p> <h2 id="disabling-warnings">Disabling <code>warnings</code></h2><p>I can't remember how many times I've forgotten how to disable all warnings in a Jupyter notebook. Usually, a quick online search would lead me to <a href="">this StackOverflow post</a>, but there are many options for doing so listed on that post that I invariably give up and live with warnings piling up in my notebooks. That is, until, I saw <code>shutup</code>.</p> <p>Before <code>shutup</code>, we would write:</p> <div class="hll"><pre><span></span><span class="kn">import</span> <span class="nn">warnings</span> <span class="n">warnings</span><span class="o">.</span><span class="n">filterwarnings</span><span class="p">(</span><span class="s2">"ignore"</span><span class="p">)</span> </pre></div> <p>But with <code>shutup</code> we would write the following code that is just a <em>tad</em> easier to remember than the builtin:</p> <div class="hll"><pre><span></span><span class="kn">import</span> <span class="nn">shutup</span> <span class="n">shutup</span><span class="o">.</span><span class="n">please</span><span class="p">()</span> </pre></div> <p>The package is so Canadian and polite too!</p> <h2 id="making-command-line-interfaces">Making command line interfaces</h2><p>If you've built command line interface (CLI) tools using Python's built-in <code>argparser</code> module, you'll know that it's incredibly convenient to turn Python scripts into CLIs. Yet, at the same time, it's also really verbose. You might end up writing code that looks like this:</p> <div class="hll"><pre><span></span><span class="c1"># Hello {name} program!</span> <span class="kn">import</span> <span class="nn">argparse</span> <span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span> <span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s2">"My App"</span><span class="p">)</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">"name"</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">str</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">"Name to say hello."</span><span class="p">)</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">"times"</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">"Number of times to say hello."</span><span class="p">)</span> <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">times</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"Hello </span><span class="si">{</span><span class="n">args</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span> </pre></div> <p>Looking at that code, I can imagine building CLIs composed of multiple commands will be challenging to maintain and develop.</p> <p>Typer makes building CLIs much more accessible by helping you easily organize your CLI code into sub-commands.</p> <div class="hll"><pre><span></span><span class="kn">import</span> <span class="nn">typer</span> <span class="n">app</span> <span class="o">=</span> <span class="n">typer</span><span class="o">.</span><span class="n">Typer</span><span class="p">()</span> <span class="nd">@app</span><span class="o">.</span><span class="n">command</span><span class="p">()</span> <span class="k">def</span> <span class="nf">hello<">"Hello </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s2">!"</span><span class="p">)</span> <span class="nd">@app</span><span class="o">.</span><span class="n">command</span><span class="p">()</span> <span class="k">def</span> <span class="nf">goodbye<">"Goodbye </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s2">!"</span><span class="p">)</span> <span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span> <span class="n">app</span><span class="p">()</span> </pre></div> <p>As you probably can tell, it is much easier to compose command line interface programs with Typer than with `argparse; this is thanks to type hints in modern Python. Typer takes advantage of this to make building CLIs a breeze!</p> <h2 id="summary">Summary</h2><p>As the Python ecosystem matures and grows, as a community, we will uncover and find new sane patterns that lubricate our code development work. That will, in turn, lead to more development of what I call "convenience packages"; in the marketplace of ideas, good ones will usually (though not always) rise to the top and become well-known. I'd encourage you to try out these modern replacements for built-in Python modules and see if they stick!</p> PyScript: Python in the Web Browser2022-05-01T00:00:00ZEric J. Maurn:uuid:318f4d6e-0dd5-3767-8ce2-f64875e94f90<script defer</script><p>At yesterday's PyCon 2022 keynote, Anaconda CEO <a href="">Peter Wang</a> did a big reveal on <a href="">PyScript</a>, which lets us use Python in the browser just like we would use JavaScript. Having heard the Keynote and having sat in on the Open Space led by <a href="">Fabio Pliger</a>, one of the lead software developers on the project, I immediately went off and tested the thing that afternoon.</p> <p>My initial reactions can be described using the following phrases, in exact order:</p> <ul> <li>No way this is happening!</li> <li>Wow!</li> <li>Oh wow!</li> <li>Daaaaaaang!</li> <li>I can write Python just like JavaScript??????</li> <li>Oh man, I see so many possibilities.</li> <li>Yes, yes, this is for the masses.</li> </ul> <p>So I decided to give it a shot. That afternoon, I put in a <a href="">pull request</a> to the <code>pyscript</code> examples gallery. It was one describing how to do message passing on graphs, a point that left many of my <a href="">Network Analysis Made Simple tutorial</a> participants mindblown. I'm replicating the example below, with a few prose enhancements.</p> <h2 id="message-passing-and-linear-algebra-a-demo">Message Passing and Linear Algebra: A Demo</h2><div> <py-env> - networkx - numpy </py-env> </div><p>Imagine we have a chain graph that looks like this:</p> <div class="hll"><pre><span></span>O --> <span class="m">1</span> --> <span class="m">2</span> --> <span class="m">3</span> </pre></div> <p>In NetworkX, we could construct a graph object that represents the graph. That graph would have the following edges:</p> <div> <py-script import networkx as nx G = nx.DiGraph() nodes = list(range(4)) G.add_edges_from(zip(nodes[0:-1], nodes[1:])) print(G.edges()) </py-script> </div><div><pre id="edges"></pre></div><p>It would also look like this:</p> <div> <py-script import matplotlib.pyplot as plt fig = plt.figure() nx.draw(G, ax=plt.gca(), with_labels=True) fig </py-script> </div> <div id="mpl"></div><p>Now, as it turns out, this graph has a linear algebra representation in the form of an adjacency matrix that looks like this:</p> <div> <py-script import numpy as np A = np.eye(4, k=1) print("A:") print(A) </py-script> </div><div><pre id="adj-mat"></pre></div><p>And imagine that we have a message that lives on the graph. It is given by an indicator vector <code>M</code>, where <code>1</code> indicates that the message lives on a node and <code>0</code> indicates that the message is absent from the node.</p> <pre><py-script> M = np.array([1.0, 0.0, 0.0, 0.0]) print("M:") print(M) </py-script></pre><p>Now, if you did a dot product beetween the message and the adjacency matrix, you would pass the message along the chain. Try it out for yourself by copying and pasting in any one of the following lines into the embedded PyScript REPL below:</p> <pre><code>M @ A M @ A @ A M @ A @ A @ A </code></pre> <p>(Execute the REPL by hitting <code>Ctrl+Enter</code> or <code>Shift+Enter</code>.)</p> <p><div><py-replM @ A</py-repl></div></p> <pre id="repl-out"></pre><h2 id="reflections">Reflections</h2><p>I'm not sure that 2022 is going to be the year of the Linux desktop, but I'm very sure that 2022 is already the year of Python <em>embedded</em> in the browser. I wrote this blog post entirely in Markdown, with only a few <code><div></div></code>, <code><pre></pre></code> and <code><py-script></py-script></code> tags sprinkled throughout the post to make this happen. As someone who has programmed in Python for my entire professional life, there's a glaring inability for me to embed Python in HTML documents. As such, Python has a strong server-to-client vibe baked into the ecosystem.</p> <p>PyScript changes that paradigm: everything you saw above was rendered client-side only. My website is a static site, and yet you were able to run an embedded Python REPL here! The possibility of using Python just like JavaScript is pretty amazing. I can see many possibilities going forward, both at work, in education, and more. Kudos, Peter, Fabio, and the rest of the Anaconda team that put this out. I can't wait to see how PyScript evolves!</p> Matrices and their connection to graphs2022-04-02T00:00:00ZEric J. Maurn:uuid:a014a7be-f074-3dd1-a275-7e8d17f53685<p>Graphs, also known as networks, are ubiquitous in our world. But did you know that graphs are also related to matrices and linear algebra?</p> <p>Graphs, at their core, are comprised of two sets:</p> <ul> <li>A node set</li> <li>An edge set</li> </ul> <p>Nodes are entities in a graph, and edges are their relationships. One anchoring example you can use throughout this blog post is a social network - people are nodes, and their connections are edges. In "Network Analysis Made Simple", we go much deeper into <a href="">particular examples</a> and <a href="">the specific NetworkX implementation</a>.</p> <p>As it turns out, you can represent graphs as matrices! Let's construct a minimal complex example to illustrate the point. If you had a social network of 4 people (A through D), such that they had the following connectivity pattern:</p> <pre><code> D | A - B - C └-------┘ </code></pre> <p>We can actually represent the graph as an <em>adjacency matrix</em>, which highlights which nodes are connected to which other nodes:</p> <pre><code> A B C D ┌------------┐ A | 0 1 1 0 | B | 1 0 1 1 | C | 1 1 0 0 | D | 0 1 0 0 | └------------┘ </code></pre> <p>Here, a value of <code>1</code> in the matrix indicates a connection between the two nodes, while a value of <code>0</code> indicates no relationship.</p> <p>Using NetworkX, it's straightforward to create the graph and convert it to matrix form:</p> <div class="hll"><pre><span></span><span class="kn">import</span> <span class="nn">networkx</span> <span class="k">as</span> <span class="nn">nx</span> <span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span> <span class="n">G</span> <span class="o">=</span> <span class="n">nx</span><span class="o">.</span><span class="n">Graph</span><span class="p">()</span> <span class="n">G</span><span class="o">.</span><span class="n">add_nodes_from</span><span class="p">(</span> <span class="p">[(</span><span class="s2">"A"</span><span class="p">,</span> <span class="s2">"B"</span><span class="p">),</span> <span class="p">(</span><span class="s2">"B"</span><span class="p">,</span> <span class="s2">"C"</span><span class="p">),</span> <span class="p">(</span><span class="s2">"A"</span><span class="p">,</span> <span class="s2">"C"</span><span class="p">),</span> <span class="p">(</span><span class="s2">"B"</span><span class="p">,</span> <span class="s2">"D"</span><span class="p">)]</span> <span class="p">)</span> <span class="n">adj_mat</span> <span class="o">=</span> <span class="n">nx</span><span class="o">.</span><span class="n">to_adjacency_matrix</span><span class="p">(</span><span class="n">G</span><span class="p">)</span> <span class="c1"># This is what adj_mat looks like</span> <span class="n">adj_mat</span> <span class="c1"># output:</span> <span class="n">array</span><span class="p">([[</span><span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">],</span> <span class="p">[</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">],</span> <span class="p">[</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">],</span> <span class="p">[</span><span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">]])</span> </pre></div> <p>From the adjacency matrix, it's already easy to infer some basic information about the graph.</p> <p>Firstly, we can test whether the matrix is symmetric around the diagonal or not to infer whether or not the graph can be represented as an undirected graph. We do this by checking whether the lower triangle of the adjacency matrix is equal to the upper triangle of the adjacency matrix when either one of them is transposed:</p> <div class="hll"><pre><span></span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">triu</span><span class="p">(</span><span class="n">adj_mat</span><span class="p">)</span> <span class="o">==</span> <span class="n">np</span><span class="o">.</span><span class="n">tril</span><span class="p">(</span><span class="n">adj_mat</span><span class="p">)</span><span class="o">.</span><span class="n">T</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="c1"># evaluates to `True`</span> </pre></div> <p>If the graph is undirected, we can count the number of edges in the graph by summing up either the upper or lower triangle of the matrix. If the graph is directed, then summing the matrix tells us the total number of edges:</p> <div class="hll"><pre><span></span><span class="n">np</span><span class="o">.</span><span class="n">triu</span><span class="p">(</span><span class="n">adj_mat</span><span class="p">)</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span> <span class="c1"># evalutes to 4.0</span> </pre></div> <p>Additionally, taking the <code>k</code>-th matrix powers of the adjacency matrix tells us the number of ways to reach another node by taking <code>k</code> hops on the graph. Let's see the example of <code>k = 2</code>:</p> <div class="hll"><pre><span><">1.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">],</span> <span class="p">[</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">3.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">],</span> <span class="p">[</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">2.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">],</span> <span class="p">[</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">]])</span> </pre></div> <p>As we can see, there are two ways to go from A and back to A (value = 2), by going <code>A -> B -> A</code> and <code>A -> C -> A</code>. There are no ways to go from B to D using 2 hops. Hence the value is 0.</p> <p>And if you've been astute enough to pick it up, the diagonal also happens to tell us the <em>degree</em> of each node, that is, the number of neighbours that each node has:</p> <div class="hll"><pre><span></span><span class="n">np</span><span class="o">.</span><span class="n">diagonal</span><span class="p">(<">3.</span><span class="p">,</span> <span class="mf">2.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">])</span> </pre></div> <p>Knowing how to convert between object and matrix representations of graphs is a really useful skill, because being able to do so gives you access to the necessary programming language APIs that can make your life a lot easier. I <a href="">know this from personal experience</a>!</p> <p>I will be at ODSC East 2022 teaching <a href="">Network Analysis Made Simple</a>. There, we will learn more cool stuff about graphs, their key underlying concepts, and awesome connections to other topics through this tutorial. Hope to see you there!</p> Functional over object-oriented style for pipeline-esque code2022-04-01T00:00:00ZEric J. Maurn:uuid:945bd75f-35fe-319f-8a5f-a07d5a7f35f8<p>Where possible, in my data science projects, I usually go for a functional programming style over an object-oriented style. I'd like to explain why this could be advantageous from the standpoint of a mental model, which is an idea that my friend Jesse Johnson has elaborated on <a href="">in the context of in biotech organizations</a>.</p> <h2 id="types-standards-and-pipelines">Types, standards, and pipelines</h2><p>It all starts with types -- basically, what objects are floating around in a program. When writing data science code, data type transformations are commonplace. Reasoning about the data types is hard enough without introducing another object -- and, therefore, another type. Introducing another type into the program <a href="">is like introducing another standard</a> -- suddenly, you have one more thing to worry about.</p> <p>Here's an example. We read in a CSV file and spit out a <code>pandas</code> DataFrame. That <code>pandas</code> <code>DataFrame</code> goes into another function that constructs a PyMC model and returns the model. Next, the model goes into another function that calls on a PyMC sampler and returns an <code>InferenceData</code> object. The <code>InferenceData</code> object then gets parsed back into another <code>DataFrame</code> for multiple uses -- to generate plots, get checked into a database, and more.</p> <p>If we were to introduce a new object, say, a <code>DataModeller</code> object, we might encapsulate all of those steps in the following way:</p> <div class="hll"><pre><span></span><span class="k">class</span> <span class="nc">DataModeller</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="o">...</span><span class="p">):</span> <span class="o">...</span> <span class="k">def</span> <span class="nf">make_model</span><span class="p">(</span><span class="o">...</span><span class="p">):</span> <span class="o">...</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="n">model</span> <span class="k">def</span> <span class="nf">sample</span><span class="p">(</span><span class="o">...</span><span class="p">):</span> <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">idata</span> <span class="o">=</span> <span class="n">pm</span><span class="o">.</span><span class="n">sample</span><span class="p">()</span> <span class="k">def</span> <span class="nf">process_posterior</span><span class="p">(</span><span class="o">...</span><span class="p">):</span> <span class="o">...</span> </pre></div> <p>Now, the critical trouble I usually run into with classes-for-data-pipelining is not merely about needing to create new objects and hence, new "types" in the project. It's also that the class methods can, in theory, be called without any enforcement of order - and errors will result. It's challenging to reason clearly about the correct order of operations when reading just the code. The atomic class methods are attached to the class at the same level of abstraction as the higher-level class methods, and the object's internal state can be created on-the-fly -- and is implicit, not explicit.</p> <p>By adopting a functional style, we can make keeping atomic functions and higher-order functions mentally separate easier. We can keep the atomic functions inside a submodule and higher-order functions higher up in the source code hierarchy. And by calling on the higher-order functions, we can easily read off the correct order of operations that need to happen, i.e. the pipeline. Riffing off the above example:</p> <div class="hll"><pre><span></span><span class="c1"># This is where the atomic functions might live, e.g. `src/models/stuff.py`</span> <span class="k">def</span> <span class="nf">make_model">make_model">sample</span><span class="p">(</span><span class="n">model</span><span class="p">:</span> <span class="n">pm</span><span class="o">.</span><span class="n">Model</span><span class="p">)</span> <span class="o">-></span> <span class="n">az</span><span class="o">.</span><span class="n">InferenceData</span><span class="p">:</span> <span class="sd">"""Convenience wrapper around `pm.sample` with defaults for our problem."""</span> <span class="o">...</span> <span class="k">return</span> <span class="n">idata</span> <span class="k">def</span> <span class="nf">process_posterior</span><span class="p">(</span><span class="n">idata</span><span class="p">:</span> <span class="n">az</span><span class="o">.</span><span class="n">InferenceData</span><span class="p">)</span> <span class="o">-></span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">:</span> <span class="o">...</span> <span class="k">return</span> <span class="n">posterior_df</span> </pre></div> <p>And now the functions are easily composable to make higher-order functions:</p> <div class="hll"><pre><span></span><span class="c1"># This is where the higher-order functions live, e.g. in `src/__init__.py`</span> <span class="kn">from</span> <span class="nn">src.models.stuff</span> <span class="kn">import</span> <span class="n">make_model_1</span><span class="p">,</span> <span class="n">make_model_2</span><span class="p">,</span> <span class="n">sample</span><span class="p">,</span> <span class="n">process_posterior</span> <span class="n">model_name_mapping</span> <span class="o">=</span> <span class="p">{</span> <span class="s2">"model1"</span><span class="p">:</span> <span class="n">make_model_1</span><span class="p">,</span> <span class="s2">"model2"</span><span class="p">:</span> <span class="n">make_model_2</span><span class="p">,</span> <span class="p">}</span> <span class="k">def</span> <span class="nf">model</span><span class="p">(</span><span class="n">df</span><span class="p">:</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">,</span> <span class="n">model_name</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">:</span> <span class="sd">"""Some docstring here."""</span> <span class="n">model_func</span><span class="p">:</span> <span class="n">Callable</span> <span class="o">=</span> <span class="n">model_name_mapping</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">model_name</span><span class="p">)</span> <span class="n">model</span><span class="p">:</span> <span class="n">pm</span><span class="o">.</span><span class="n">Model</span> <span class="o">=</span> <span class="n">model_func</span><span class="p">(</span><span class="n">df</span><span class="p">)</span> <span class="n">idata</span><span class="p">:</span> <span class="n">az</span><span class="o">.</span><span class="n">InferenceData</span> <span class="o">=</span> <span class="n">sample</span><span class="p">(</span><span class="n">model</span><span class="p">)</span> <span class="n">posterior_df</span><span class="p">:</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span> <span class="o">=</span> <span class="n">process_posterior</span><span class="p">(</span><span class="n">idata</span><span class="p">)</span> <span class="k">return</span> <span class="n">posterior_df</span> </pre></div> <p>A natural hierarchy appears here! We import lower-level functions from deeper within the library; with higher-level functions, we go closer to the top-level imports.</p> <p>(In the example above, I also took the liberty of annotating types in-line. They are another form of in-line documentation. They also help with reasoning about the workflow much more efficiently, especially if someone is just getting used to, say, the <code>df -> model -> idata -> posterior_df</code> workflow.)</p> <p>As you probably can see here, too, using functions enables us to easily see the idiomatic workflow. Our mental model is more easily read off by the next person in the pipelines-as-functions paradigm rather than pipelines-as-objects paradigm.</p> <p>And as a side benefit, if we think carefully about the data types we pass around, consume, and generate, then we end up with easily reusable functions. That's another awesome side effect!</p> <h2 id="objects-are-fine-just-not-everywhere">Objects are fine, just not <em>everywhere</em></h2><p>Now, just to be clear, I'm not advocating an abdication of objects altogether. Clearly, a PyMC Model, InferenceData and DataFrames are all objects themselves. <em>For someone who works with data, when do objects make sense?</em></p> <p>I think in the context of data pipelines, objects make the most sense as a data container. One clear example is configuration objects (which I usually implement as a dataclass with very-few-to-zero class methods). Another clear example is when 3-4 related dataframes need to be kept together. Also, we may need convenient class methods to dump them to disk at once. Here a dataclass with 3-4 corresponding attributes and a single class method would make a ton of sense.</p> <p>Pipelines are best thought of as functions and are therefore best implemented as functions. Data (and data containers) are best thought of as objects and are therefore best implemented as objects. Objects as data pipelines, though? In my opinion, doing so only adds confusion. Once again, it's my conviction, having written more than 9 years of Python data science code, that pipelines-as-functions express the developer's mental model of the pipeline more cleanly than pipelines-as-objects.</p> <h2 id="the-twist">The twist</h2><p>Aaaaaand I know there's going to be someone who says, "But you can make objects callable too, right?" Yeah, I know that's doable :). On this point, the flexibility of Python allows for things to be implemented in multiple ways. However, in line with the Zen of Python, it's probably best to adopt one clear way of implementing things. Pipelines as functions, data as objects. This is a much saner way of establishing simple idioms that, subjectively, allows for cleaner reasoning about our code.</p> Everything gets a package? Yes, everything gets a package.2022-03-31T00:00:00ZEric J. Maurn:uuid:be71bac2-773c-3410-94ac-02234558c3b9<p>I recently read <a href="">Ethan Rosenthal's Python Data Science</a> setup, and I loved every line of it. His blog post encapsulates some of the best of the ideas that I wrote about in my <a href="">Data Science Bootstrap knowledge base</a>. In this blog post, I'd like to share my own data science setup and some new tooling that I've been working on to make it <em>easy</em> to achieve the same goals as I have.</p> <h2 id="but-why-all-the-trouble">But why all the trouble?</h2><p>Isn't there a <em>ton</em> of overhead that comes from doing software work? You now suddenly have to manage dependencies, start documenting your functions, add tests... you suddenly can't just store data with code in the repo... I can't just commit the notebook and be done with it?</p> <p>Let me explain. Data science is no longer solo work, but teamwork. The corollary is this: <em>discipline enables better collaborative work</em>.</p> <p>Have you encountered the following issues?</p> <ul> <li>A notebook that works on your colleague's computer trips up on imports?</li> <li>A notebook that ran on your colleague's machine errors out because you were missing a data file?</li> <li>Your PyMC model definition doesn't agree with your colleagues', because you two were independently editing two notebooks that now each contains drifted model code?</li> </ul> <p>These are problems that are solved by thinking more like a software developer and less like a one-off script writer. Let me explain what to optimize for when adopting this mindset.</p> <h2 id="optimize-for-portability">Optimize for portability</h2><p>My grad school days taught me the pains of dependency management and dependency isolation, so as soon as I borked my MacBook Air's native Py27 environment, I bought into using <code>conda</code> for environment management. (That's a long, long story I can tell at some other time.) I also had to run code locally and on an HPC machine, and maintaining two separate computation environments means that from the get-go, I had to learn how to maintain <em>portable</em> environments that could work anywhere.</p> <p>By buying into the <code>conda</code> package manager and the associated <code>environment.yml</code> file early on, it meant I could recreate any project's software environment with a single command <code>conda env update -f environment.yml</code>. (Nowadays I use <code>mamba</code> instead of <code>conda</code> because <code>mamba</code> is faster, but the command is essentially the same.)</p> <p>Why <code>conda</code>? On one hand, the ability to install <code>conda</code> <em>with ease</em> from <code>conda</code> - this holds especially true for cheminformatics projects that I have worked on.</p> <h2 id="optimize-for-standardized-structure">Optimize for standardized structure</h2><p><a href="">Cookiecutter Data Science by DrivenData</a> was the OG inspiration for this idea. Basically, I ensure that every project I work on starts with a standardized project directory structure that looks, at the minimum, something like this:</p> <div class="hll"><pre><span></span>andorra_geospatial/ <span class="c1"># the project name</span> <span class="p">|</span>- docs/ <span class="p">|</span>- notebooks/ <span class="p">|</span>- andorra_geospatial/ <span class="c1"># custom source code, usually named after the project name.</span> <span class="p">|</span>- tests/ <span class="p">|</span>- .gitignore <span class="p">|</span>- .pre-commit-config.yaml <span class="p">|</span>- environment.yml <span class="p">|</span>- pyproject.toml <span class="p">|</span>- setup.cfg <span class="p">|</span>- setup.py </pre></div> <p>If you squint hard, you'll notice that the project structure essentially looks like a Python software package, except that there is also a <code>notebooks/</code> directory added into the mix. This is intentional! Structuring every project in this fashion ensures that when future me, or someone else comes to view the project repository, they know exactly where to go for code artifacts.</p> <p>Need an analysis? Look it up in <code>notebooks/</code>. Need to find where that function was defined? Look it up in <code>andorra_geospatial</code> submodules. Need to add a package? Update the <code>environment.yml</code> definition and get <code>conda</code> or <code>mamba</code> to update your environment. Imposing this structure ensures your code is organized, and as the CCDS website states:</p> <blockquote><p>Well organized code tends to be self-documenting in that the organization itself provides context for your code without much overhead.</p> </blockquote> <p>But what about a <code>data/</code> directory? That's a good question - lots of people store CSV files in a <code>data/</code> <a href="">official Dropbox Python API</a>).</p> <h2 id="optimize-for-effective-processes-and-habits">Optimize for effective processes and habits</h2><p>Any data scientist has enough knowledge to carry in their heads: domain expertise, programming skills, modelling skill, and more. With that amount of knowledge overhead that we already have to carry, adding more minutiae only adds to more cognitive stress. Therefore, <em>any kind of <strong>standardized</strong> workflow that helps us ship our work into our colleagues' hands</em> will, in the words of <a href="">Katie Bauer</a>:</p> <blockquote><p>ensure (original: ensuring) folks can contribute without having to hold a bunch of background knowledge in their head, and reduce (original: reducing) unproductive variance in operations.</p> </blockquote> <p>In the spirit of that, here are some of the processes that I use in my personal and work projects.</p> <h3 id="follow-the-1-to-1-to-1-to-1-rule">Follow the 1-to-1-to-1-to-1... rule</h3><p>No matter how big or small, every project gets a <code>git</code> repository on some hosted service, whether GitHub (my favourite) or Bitbucket. Doing so ensures that my code can always be pulled into a new machine from a <em>single source of truth.</em>. <a href="">I detail more in my Data Science Bootstrap Notes page on the rule of one-to-one</a>.</p> <h3 id="commit-code-often">Commit code often</h3><p>By committing code often, I get the benefit of history in the git log! I can think about the number of times I accidentally deleted a chunk of notebook code that I needed later, and how the git history helped me recover that code chunk.</p> <p.</p> <h3 id="ensure-code-adheres-to-minimum-quality-standards">Ensure code adheres to minimum quality standards</h3><p>All code that I write (that gets placed in the custom source code directory) should, at the minimum, have a docstring attached to it. I try to go one step further and ensure that they have type hints (which are <em>incredibly</em> useful!) and an example-based test associated with it. Even better is if the docstring contains a minimum working example of how to use the chunk of code!</p> <h3 id="refactor-by-using-source-py-files">Refactor by using source <code>.py</code> files</h3><p>Like any other user of Jupyter notebooks as prototyping environments, functions I write in the notebook may end up relying on the internal state of the notebook. <strong>The cleanest way to ensure that a block of code operates independently of the internal state of the notebook is to cut and paste it out into a <code>.py</code> file, and then re-import the function back into the notebook.</strong> This is refactoring, data science-style. By cutting and pasting functions out, I'm forced to account for every variable inside the function.</p> <h3 id="pre-define-with-colleagues-what-a-unit-of-work-will-look-like">Pre-define with colleagues what a unit of work will look like</h3><p>When doing team data science, communication and coordination are key. Usually, there are <em>independent units of work</em> that need to be completed by individuals, and at times these units of work can run in parallel. Some examples of these include:</p> <ol> <li>Software-oriented pieces of work, such as contributing new functions to the custom library,</li> <li>Analyses using the same code but on different datasets,</li> </ol> <p.</p> <h2 id="optimize-for-automation">Optimize for automation</h2><p>Once your processes are well-defined, automation becomes a cinch! The value of automation is obvious - you save time and effort! <em>But the value of automation can only be realized when your processes are also stabilized.</em> Without a stable process, you'll never have to execute the same commands over and over and over, and hence you'll never have the need to automate. That's because <em>by definition, we can only automate stable processes and habits</em>..</p> <p>There are a lot of tools that I use to automate my workflow. They range from tools that create a new project in a standardized fashion to tools that save keystrokes at the terminal. Below are some of my own notes taken over time.</p> <ul> <li><a href=""><code>pyds-cli</code></a> is a tool I developed, based on my experiences at work, to automate routine chains of shell commands. It automates conda environment management tasks, standardizes the creation of new projects, and many more. Still in development, so there may be rough edges.</li> <li>I also wrote <a href="">a blog post detailing some <code>conda</code> hacks that I use</a>.</li> <li>To save typing at the terminal, I wrote about <a href="">how to use shell aliases to cut down on typing</a>.</li> <li>To avoid arguing with your colleagues about minimum code quality standards, get a bot to enforce them. In this case, that machine is pre-commit hooks. <a href="">I wrote about how to get set up on my DS Bootstrap Notes.</a></li> </ul> <h2 id="summary">Summary</h2><p>This kind of working mode is <em>other-centric</em> rather than <em>self-centered</em>. <em>collaborative</em> software development practices in our data science work, we're adopting highly productive team workflows that will benefit our team productivity and robustness in the long-run!</p> <h2 id="faq">FAQ</h2><p><em>Why not Docker?</em></p> <p, <a href="">as Uwe Korn details in his blog post</a>). <code>docker-slim</code> is a project that makes a good attempt at slimming down containers, but I haven't yet had the bandwidth to try it out.</p> <p><em>Why not just pip/poetry/pipx?</em></p> <p>In my line of work, I end up using a lot of conda-only packages, such as RDKit, so defaulting to <code>conda</code> packages first tends to make things easier. Also <code>mamba</code> is amazing 🙂!</p> <p><em>What about the problem Ethan detailed - reproducible builds when packages come from different channels?</em></p> <p>It's important to set the channel priorities in <code>environment.yml</code>. Packages by default are pulled from the first priority channel, then the second if not found in the first, and so on and so forth. If we reason clearly about channel priorities and pair them with <code>conda env export</code> and its associated fixed package versions, then we've got a good story for reproducible conda environments.</p> <p><em>Can I ask you more questions?</em></p> <p>Of course! Send me a message through <a href="">Shortwhale</a>. If enough people ask questions about the same thing, I'll just update the FAQ here.</p> Better conda environments on GitHub actions2021-12-30T00:00:00ZEric J. Maurn:uuid:ce7d9a6e-9a90-33bc-adbe-47f1d35368d3<p>I recently figured out two tips to make GitHub actions play nicely with conda installations. Here they are.</p> <h2 id="ensure-bash-is-in-login-mode">Ensure bash is in login mode</h2><p>The first is to use the following block:</p> <div class="hll"><pre><span></span><span class="w"> </span><span class="c1">#</span><span class="w"></span> <span class="w"> </span><span class="nt">defaults</span><span class="p">:</span><span class="w"></span> <span class="w"> </span><span class="nt">run</span><span class="p">:</span><span class="w"></span> <span class="w"> </span><span class="nt">shell</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">bash -l {0}</span><span class="w"></span> </pre></div> <p>What this does is ensure that every shell command is run in login mode. As detailed in <a href="">this StackOverflow answer</a>:</p> <blockquote><ul> <li><code>-l</code> to insure (sic) a login bash, where the environment is correctly set;</li> <li><code>{0}</code>, a template placeholder, replaced at pipeline execution time by the actual script command to execute.</li> </ul> </blockquote> <p>Counterfactually, I would have had to use the deprecated <code>source activate <env_name></code>, which always made me a bit nervous. Now, I can instead switch over to using <code>conda activate <env_name></code> before executing environment-specific commands, thereby providing longevity for the build.</p> <h2 id="use-mambaforge">Use mambaforge</h2><p>The other tip is to use the mambaforge installer to get a conda installation onto GitHub actions. The block I recently used for my <a href="">causality repo</a> is as follows:</p> <div class="hll"><pre><span></span><span class="w"> </span><span class="c1"># See:</span><span class="w"></span> <span class="w"> </span><span class="p p-Indicator">-</span><span class="w"> </span><span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">Setup miniconda</span><span class="w"></span> <span class="w"> </span><span class="nt">uses</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">conda-incubator/setup-miniconda@v2</span><span class="w"></span> <span class="w"> </span><span class="nt">with</span><span class="p">:</span><span class="w"></span> <span class="w"> </span><span class="nt">auto-update-conda</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">true</span><span class="w"></span> <span class="w"> </span><span class="nt">miniforge-variant</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">Mambaforge</span><span class="w"></span> <span class="w"> </span><span class="nt">channels</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">conda-forge</span><span class="w"></span> <span class="w"> </span><span class="nt">python-version</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">3.9</span><span class="w"></span> <span class="w"> </span><span class="nt">activate-environment</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">causality</span><span class="w"></span> <span class="w"> </span><span class="nt">environment-file</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">environment.yml</span><span class="w"></span> <span class="w"> </span><span class="nt">use-mamba</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">true</span><span class="w"></span> </pre></div> <p>This configuration guarantees the use of <code>mamba</code> to solve the environment, which means we will have blazingly fast builds. Previously, I used to use a different GitHub action (<code>s-weigand/setup-conda@v1</code>), original <code>conda</code> (rather than <code>mamba</code>), and a convoluted build that involved environment caching. You can take a look at an example that I copied over from my <code>nxviz</code> project repository by expanding the details below.</p> <details> <pre><code class="yaml"> name: Build documentation on: push: branches: - master jobs: build-environment: runs-on: ubuntu-18.04 name: Build conda environment steps: - uses: actions/checkout@v2 name: Checkout repository # See: - name: Setup anaconda uses: s-weigand/setup-conda@v1 with: conda-channels: "conda-forge" # Build cache of environment - name: Cache conda environment id: cache-environment uses: actions/cache@v2 with: path: nxviz.tar.gz # Note: Remember that whatever files the environment build depends on # should be hashed and added to the key. key: ${{ runner.os }}-env.${{ hashFiles('environment.yml') }} - name: Build environment if: steps.cache-environment.outputs.cache-hit != 'true' run: | conda env create -f environment.yml python -m pip install . - name: Install conda-pack if: steps.cache-environment.outputs.cache-hit != 'true' run: conda install -c conda-forge conda-pack - name: Run conda-pack if: steps.cache-environment.outputs.cache-hit != 'true' run: conda pack -n nxviz -o nxviz.tar.gz # See: - name: Upload environment uses: actions/upload-artifact@v2 with: name: nxviz-tarball path: nxviz.tar.gz docs: name: Build static site docs runs-on: ubuntu-latest needs: build-environment steps: - name: Checkout repository uses: actions/checkout@v2 # - name: Download environment tarball uses: actions/download-artifact@v2 with: name: nxviz-tarball - name: Unpack environment and activate it run: | bash scripts/ci/unpack_environment.sh - name: Build docs run: | source /tmp/nxviz/bin/activate python -m ipykernel install --user --name nxviz><p>By contrast, the new build is much smaller and easier to maintain:</p> <details> <pre><code class="yaml"> name: Build documentation on: push: branches: - master jobs: build-docs: runs-on: ubuntu-latest name: Build conda environment # defaults: run: shell: bash -l {0} steps: - uses: actions/checkout@v2 name: Checkout repository # See: - name: Setup miniconda uses: conda-incubator/setup-miniconda@v2 with: auto-update-conda: true miniforge-variant: Mambaforge channels: conda-forge python-version: 3.9 activate-environment: nxviz environment-file: environment.yml use-mamba: true - name: Build environment run: | conda activate nxviz python -m ipykernel install --user --name nxviz python -m pip install .>What candidates can and cannot control in their job hunt2021-11-28T00:00:00ZEric J. Maurn:uuid:635a32ff-9b3e-3b85-ba57-d469d9066660<p>Having been involved in quite a few rounds of hiring data scientists in a biomedical research context, I'd like to share some perspectives that may help candidates who desire a move into a data science role in biomedical research. I'll start off with the usual disclaimer that these are personal observations and thoughts; they may not apply uniformly to all biomedical data science teams, and may reflect personal biases. With that disclaimer out of the way, here are my observations.</p> <h2 id="60-70-of-the-hiring-process-is-out-of-a-candidate-s-control">60-70% of the hiring process is out of a candidate's control</h2><p>As a candidate, you probably want to focus on just the things that are <em>in</em> your realm of control while not fretting over the things that are <em>out</em> of your control.</p> <p>Here are a few examples of what I mean by things you <em>cannot</em> control:</p> <ol> <li>Whether the role is opened up specifically for another person or not.</li> <li>The underlying "story" that the hiring manager is telling themself regarding the role, such as the relative emphases and weight that the hiring manager places on different skillsets.</li> <li>The personality, personal history, and angles of inquiry that the interviewing team brings to the process.</li> <li>Whether or not the hiring manager can or cannot hire you because of other legal constraints.</li> </ol> <p>A candidate can't know <em>any</em> of these constraints unless you have contacts inside the company that can help you find these out. Because these pointers are inherently dependent on what I call the "local" hiring context, you're therefore also unable to directly control how those factors will affect your chances of being hired.</p> <p>For one's own sanity and peace of mind, I would strongly advise not fretting about these matters and instead, focus on the 30-40% of things you can control.</p> <h2 id="30-40-of-the-hiring-process-is-within-a-candidate-s-control">30-40% of the hiring process <em>is</em> within a candidate's control</h2><p>Here is a sampling of what I know is within the realm of control of a candidate.</p> <ol> <li>If a candidate comes out of a research project, how cutting-edge their choice of methods is is highly likely to be within their realm of control.</li> <li>The professionalism of their searchable <a href="">digital footprint</a>.</li> <li>The development of their creative imagination to imagine the problem space of the firm they are applying to.</li> <li>Mock practice sessions that a candidate gets before interviewing.</li> </ol> <p>I think these examples adequately highlight the kinds of things within a candidate's realm of agency as they embark on the job hunt. Once in a while, I see junior candidates (fresh grads) complain about the state of data science hiring. While I can empathize with the underlying emotion, I also think it is more productive to direct that energy towards things they can control - including better curating that <em>digital footprint</em> which is being affected by those publicly aired complaints.</p> <h2 id="what-i-looked-for-when-i-was-involved-in-hiring">What I looked for when I was involved in hiring</h2><p>When I was involved in hiring, I was laser-focused on technical excellence. I chose this aspect out of the many factors because of my personal interest. I wanted to see what new things I could learn from candidates. I also wanted to continue raising the bar on technical excellence in my team because I know this is fundamental to a data science team's collective ability to deliver on projects. Having worked with individuals who possess the seeds of technical excellence that also match my own mental model of excellence, I had a blueprint for MSc-level and PhD-level from prior experience that I could benchmark candidates against.</p> <p>Here are the criteria by which I have evaluated technical excellence.</p> <h3 id="special-sauce-modelling-skills">"Special sauce" modelling skills</h3><p>Firstly, I looked for <em>evidence</em> of special sauce modelling skills. "Special sauce" skills refer to something uncommon, rare, and technically challenging. I looked for probabilistic modelling, causal inference, graph algorithms, and graph neural networks. Having taken a class can only be considered <em>weak evidence</em>; <em>strong evidence</em> implied actual projects that they had to dedicate a significant amount of time towards solving, usually for half a year or longer. This may be in a Masters or Ph.D. research thesis, or it may be in an internship.</p> <p>Candidates may or may not be able to go in-depth into specific business-related project details. However, they should usually be able to go in-depth into technical details. To tease out these details, I would question and probe very deeply. I would also ask counterfactual questions, say, on their choice of modelling strategy. In questioning, I would place equal weight on technical correctness and interpersonal response; a candidate that gets defensive or starts name-dropping terms without justification would usually end up getting low ratings from me.</p> <p>Special sauce skills, in my opinion, signal intellectual agility and relentlessness to go technically deep. Hence the premium I placed on this skillset.</p> <h3 id="strong-software-development-skills">Strong software development skills</h3><p>Secondly, I looked for evidence of solid software development skills.</p> <p>My preferred way of evaluating this skill is not by programming puzzles; in my opinion, these are artificial tests that are mostly divorced from the day-to-day reality of data science programming. Instead, I looked for evidence of a candidate being able to structure their code in a way that enables others to use it. When it comes to data science projects, I hold a firm conviction that it is <em>primarily</em> by structuring the project like an idiomatically-built software package with notebooks, can we: (1) smoothen out the path from prototype to production, and (2) enable team ownership of the project. Hence, I looked out for evidence of solid software development skillsets.</p> <p>To assess these skillsets, I would ask a candidate to walk through the source code they were most proud of. This served as an excellent simulator for code review sessions where we bring others up to speed on the status of a project. While they introduced the code to me, I put on the persona that I would have in an actual code review question. I would ask questions about the structure of the code, counterfactual questions about alternative code architecture, and how they would improve the code. It was okay if their only <em>best</em> public work was from a few years ago and less-than-polished; using that code as a base, it is still possible to probe deeply with questions to tease out the candidates' thought processes.</p> <h3 id="does-such-a-candidate-exist">Does such a candidate exist?</h3><p>As an example, there was one candidate I interviewed before (left anonymized to protect privacy) whose main thesis work I read via a preprint and whose project code I read via GitHub. That candidate's work had excellence written throughout their project. The preprint contained clear and structured writing that made it easy to understand the premise of the project. Furthermore, the candidate's codebase was already <code>pip</code>-installable via PyPI! In addition, when I spoke with the candidate in a pre-interview setting, the candidate graciously handled a very pointed technical question about setting priors on one of their model's hyperparameters to induce regularization.</p> <h2 id="intellectual-work-products-are-the-evidence-that-you-can-provide">Intellectual work products are the evidence that you can provide</h2><p>When hiring, a candidate needs to remember: evidence is everything! If a hiring manager is comparing two candidates, the only way to be fair to both candidates is to use the <em>evidence</em> presented by both candidates to assess their merits. We cannot use <em>intent</em> to learn something as a justification to hire someone. Companies hire people who are equipped to do a job; companies do not hire people who intend to be equipped to do a job. We can help provide the environment for our colleagues to expand their skillsets after they accumulate enough credibility points.</p> <p>Evidence of software development skills can be assessed by publicly available code, and barring that, through a code walkthrough on code that has been approved for public viewing. Evidence of technical depth can be assessed by looking at work products such as blog posts, papers (and preprints), and code. Evidence of mental agility can be assessed by deep, probing questions.</p> <p>Because evidence matters so much, for this reason, the digital footprint can be such a powerful tool to leverage if you are in a position to do so. (Unfortunately, I am not sure how to advise those whose work doesn't permit them to have a digital footprint.) By <em>investing</em> time curating your digital footprint, you invest in a public profile that will yield career dividends for many years. Your digital footprint, and more generally, your production of intellectual work products, serve as <em>evidence</em> of your capabilities.</p> <h2 id="summary">Summary</h2><p>To summarize my points here:</p> <ol> <li>Many parts of the hiring process are out of a candidate's realm of control.</li> <li>Intellectual work products are 100% within a candidate's realm of control.</li> <li>Intellectual work products are evidence of your skillsets.</li> <li>Candidates are hired on the evidence of their skillsets, amongst other factors.</li> <li>To stand out, one probably wants to have some "special sauce" skillset.</li> </ol> Career FAQ2021-09-30T00:00:00ZEric J. Maurn:uuid:0fd78a63-ad48-3679-ab6e-ae799acf7756<p><strong>Q: How was my transition from the academic world to the industry?</strong></p> <p>I found the transition relatively easy because, I think, of the environment that I first joined. The Novartis Institutes for BioMedical Research, NIBR, was famed for leaning towards the academic side back in 2017. Thus, over the 3.5 years that I was there, I was given free rein to decide what to work on. The operational freedom was quite important to me as I had experienced a similar environment in graduate school.</p> <p>That lesson on the environment turned out to be more critical than I appreciated early on. We might live in an individualistic society, yet we're more affected by our community and environment than we might expect. (One might even make the case that a phase change might happen when a community collectively turns individualistic... that's an irony to explore in another setting.) During my time there, I found NIBR's environment to be pretty forgiving, thanks to its slower pace than other companies. Generally, my colleagues were kind and intelligent (in that order). Colleagues at the same level were idealists who strived to do good science. Having that community of similarly skilled and motivated colleagues was essential to me early in my career.</p> <p><strong>Q: What essential steps/skills that I gained allowed me to advance in the field?</strong></p> <p>First off, we should get one point out of the way - I don't consider promotions my primary indicator of advancement. For me, it is a side-effect of doing good work. What profoundly satisfies me the most at work is that the projects I work on accelerate science to the speed of thought. I hold the conviction that if I'm advancing the field of science that way, I'll eventually share in the team's success.</p> <p>That perhaps is the most critical lesson that others way more experienced than me have given to me: to stay mission-focused and to not think much about promotions, salary, and more, for they come, eventually. To transcend the material and not think <em>much</em> of credit gives us the freedom to pursue high-value work in the service of others. The irony here is that when you do high-value work in the service of others, you'll then have the credibility points to ask for a high-value, market-rate compensation for that work.</p> <p>So the most important thing I see is finding, buying into, or creating a transcendent, high-value, service-oriented mission for yourself. Then, use your powers of logic to deduce the high-value actions you need to take to serve others. All of business, science, and life, in general, should be about deep service to others. If we start focusing inwards on our own desires, we'll end up deeply unsatisfied. But, on the other hand, I firmly believe that if we keep service to others squarely in our sights, we'll always find unique and fun work to do.</p> <p>Now, everything I said above does not exclude looking around and benchmarking whether I'm being treated fairly or not. Still, it's important to note the order of priorities: I am first concerned with the transcendental mission and then worried about making sure I'm being treated fairly. With that order of importance, I can be free to do my best work first. Doing so lets me accumulate credibility points to advocate for fair treatment of myself and others around me. Flip that order of priority, and I am sure I will be treated as a pariah with no credibility. So our credibility points must be earned first.</p> <p>As for the tangibles, such as salary and title, some of my following observations could be of help:</p> <ol> <li>Salary raises and title promotions jump most <em>substantially</em> when one switches roles. But I would not encourage switching roles just to get salary and title jumps.</li> <li>Internal promotions can sometimes be biased because of the human factor involved. Therefore, you should always be aware of your internal context.</li> </ol> <p>Okay, so beyond the overarching "how do you advance" point, I'd like to address "how to do good work." I'm trusting that you probably know a lot of these points anyway. So I'm expecting that these points should serve merely as reminders rather than advice. I'll explain this in the context of my idealized project lifecycle.</p> <p>Firstly, when you embark on a project, I would encourage you to sit down and carefully write out a two-page (~1000 word) document for yourself. This document should provide an overview of the motivation, needs, and possible solutions for a problem your colleague brings to you or that you have identified. This document is akin to a project charter. It's very tempting to dive head-first into programming as that <em>feels</em> like our currency of data science work. But the <em>actual</em> currency of data science work is our insights; code is merely our medium to get there. Writing a document that accurately, concisely, and clearly communicates an overview of the project can help you design the solution; sometimes, it also kickstarts the flow of creative ideas. In other settings, it might illuminate the most straightforward method that solves the problem. Clarity and empathy, accurately communicated, are what you need to bring to the table for your insights to be accepted. Without that, your colleagues will give you "the eye" and wonder what you're talking about.</p> <p>Secondly, once you've spent the time wrestling with the problem, it's time to design and execute the solution. This is the project phase where we will end up doing programming work. In choosing our strategy, the standard advice circulating around is to "pick the simplest solution." However, I think that is only partially useful as an answer. A more helpful response, in my opinion, is to <em>pick the principled solution that solves the problem at its core</em>. Looking beyond the fluff of most issues, you can probably identify a core problem that needs to be solved. This is the problem you need to tackle first. The complexity involved in a problem usually comes from edge cases, h uman-made exceptions introduced to other human-made reasons (e.g. legal or ethical). Those can be composed later but should not affect your solution core at the beginning.</p> <p>Thirdly, iterate with regular communications with colleagues. Junior data scientists may find it very tempting to dive into a hole and not surface for a good month or so, with the positive intent of delightfully surprising your colleagues at the end of your adventure. The reality is quite different, though:</p> <ol> <li>Your colleagues are humans and will value regular communication. Doing so will help you build trust with them.</li> <li>Your original interpretation of your colleagues' problems might not match their interpretation of their problems. Therefore, regular communication allows you to refine your interpretation while sharpening their understanding at the same time.</li> <li>By ensuring regular communication intervals, you also give yourself the outlet to celebrate the intermediate efforts behind the results.</li> </ol> <p>As I've learned, it's often non-trivial to arrive at a simple solution that offers you high leverage over a problem. Regularly communicating the challenge to your colleagues can help them better appreciate your work.</p> <p><em>And in case you mistakenly think I communicate perfectly, I don't. That paragraph above is as much a reminder for myself as it is advice to share, too.</em></p> <p>Finally, you'll want to think about how to round out a project. One useful outlet is a final presentation - a debrief for your main stakeholder(s). Try to schedule something, even if its only purpose is to ceremonially mark the end of a project. The goal, at the minimum, is to bring closure to a project. Whether or not the stated purposes of a project were accomplished, celebrate everything learned through the process. Having a clear boundary at the end of a project brings a lot of clarity to everyone at the table. You can also leverage the final presentation to shape collective memory of what was accomplished and done - which can mean credibility points for you to spend on other projects. Being able to schedule a "final" presentation means that you'll also be less likely to be bogged down by a constant trickle of follow-up requests. Heed the words of one who has experienced it before!</p> <p><strong>Q: What tips do you have for conveying technical points to a non-technical audience?</strong></p> <p>For this, I have taken a lot of inspiration from quotes by Richard Feynman, particularly w.r.t. learning new things. He has this quote along the lines of being able to explain things to a five-year-old. The broader point is explaining a technical idea at multiple levels of detail and adapting to what your audience is looking for.</p> <p>Conveying technical points to a non-technical audience always takes time and lots of preparation. Therefore, doing a project well will necessarily mean also communicating it well. For this reason, I found that if I want to do my projects well, I need to stop willy-nilly accepting new requests to do projects. Rather, I need to focus on delivering well on one or two of them.</p> <p><strong>Q: What tips do you have for contributing to the community, like writing blog posts and such?</strong></p> <p>Share what you learn, and that's good enough. Treat the blog post as your learning log, don't worry about impressing others. I found that when I worry about impressing others, I end up not writing. That ironically hurts my ability to learn. So forget about impressing others and simply focus on recording what you've learned.</p> Machine-Directed Evolution2021-09-12T00:00:00ZEric J. Maurn:uuid:e57e7d7a-e7ad-30de-880b-8f6a1c6a27f6<h2 id="the-backdrop">The backdrop</h2><p>In 2019, while I was still at the Novartis Institutes for BioMedical Research (NIBR), I joined an internal startup team doing enzyme evolution in NIBR's chemistry department. This project was part of an internal innovation program, Genesis Labs, where teams are given the space and time to pursue a project idea. Our team wanted to compare and contrast how traditional directed evolution fared against machine learning-powered directed evolution (which we call machine-directed evolution in the paper).</p> <h2 id="the-scientific-story">The scientific story</h2><p>Our enzyme of choice is IRED, which is an industrially relevant enzyme for chemistry applications. We had a choice of IREDs that catalyzed our desired reactions, some of which were good already and others that were somewhat middling and not ideal. Our goal wasn't <em>solely</em> to get a good IRED, however. We <em>also</em> wanted to compare machine-directed evolution against traditional directed evolution techniques. Therefore, we picked the "kinda middling" IRED-88 enzyme as our starter enzyme. That way, we could explore how quickly machine-directed evolution could help us climb the dynamic range of enzyme goodness vs. traditional directed evolution.</p> <p>But what do we <em>exactly</em> mean by enzyme <em>goodness</em>? We meant to measure enzyme goodness on two axes: (1) substrate conversion into product and (2) chiral selectivity. Conversion measures how much substrate gets converted into the desired product; for us, higher conversion is better. Chiral selectivity, if you remember organic chemistry from 2nd-year science curricula, is all about getting the correct <em>chiral form</em> of the molecule; chirality results from having a tetrahedral geometry around carbon atoms. If you're curious to learn more, <a href="">Wikipedia has a great article on this</a>. When the enzyme catalyzes our reaction, we get a mixture of R- and S-chiral molecules; we were interested in maximizing the yield of R-chiral product while minimizing the production of S-chiral product.</p> <h3 id="deep-mutational-scan">Deep mutational scan</h3><p>To start, we generated a deep mutational scan (DMS) dataset. DMS requires the generation of a site-saturation mutagenesis library, where we generate all possible single-mutant variants of wild-type IRED-88. Doing so gave us a great starter dataset for machine learning purposes by covering a large proportion of single-mutant sequence space. Out of the roughly 6000+ mutants that we could have possibly generated, we cloned about 81% of them successfully. Then, we measured their activity; we also measured their chiral selectivity for a subset of them. In the subsequent paragraphs, I won't talk much about chiral selectivity. Still, you know that we always measured selectivity for a subset of highest activity mutants -- a subset, because chirality is harder to measure at scale.</p> <p><img src="dms.png" alt=""></p> <p><em>Fig. 2(a) from our paper, deep mutational scan measurements. X-axis: position on linear amino acid sequence of IRED-88. Y-axis: amino acid substitution. Heatmap shows activity measurements for ~81% of all 6000+ possible single point mutations.</em></p> <p><img src="activity-dist.png" alt=""></p> <p><em>Fig. 2(b) from our paper, activity distributions. X-axis: Bayesian estimated activity of IRED-88 mutants. Y-axis, top panels: Activity cumulative distribution of our mutants. Y-axis, bottom panels: Enantioselectivity of our mutants.</em></p> <p>Even without machine learning, that DMS dataset was highly informative! We happened to have a crystal structure of IRED-88 on hand. When we mapped what positions in the linear sequence were present in the crystal structure, we noticed that part of the N- and C-termini (head and tail of the sequence, respectively) were actually not present -- they probably were too floppy to be included as part of the solved structure. Yet, because we had measurements from the N- and C-termini mutants of IRED, we found that mutations in the C-termini were beneficial for enzyme activity. I think this means that a DMS dataset can help uncover potentially good mutants that we would never have guessed to take a look at, simply because they were missing in a crystal structure of the same protein.</p> <h3 id="traditional-directed-evolution">Traditional directed evolution</h3><p>At the same time, we did three rounds of traditional directed evolution. These are EPPCR1-3 in Fig. 2(b) shown above. One round was based directly on the wild-type, generating roughly 4000+ mutants (with replicates, so go ahead and imagine how many colonies we had to pick). Out of those enzymes, the winner turned out to be an okay-ish enzyme. However, in the interest of obtaining a good enzyme, we decided to take a winner from the deep mutational scan as our basis for a 2nd round and subsequent round of directed evolution. The winners of those next rounds all turned out to be pretty good. However, the number of things we had to screen was close to 10,000 mutants (with replicates). So, again, keep that number in mind: it's $10^4$ mutants measured, amounting to about $10^5$ activity measurements taken.</p> <h3 id="machine-directed-evolution">Machine-directed evolution</h3><p>So now we moved on to machine-directed evolution. Here, our strategy was to train a machine learning model to learn the relationship between sequence and activity/chirality and then use that model to score in-silico proposed mutants. It's the most basic form of machine-directed evolution one can use. Nowadays, there's lots of hype around generative models of sequences and the likes. Still, back in 2019, we wanted to compare directed evolution against a known and robust baseline strategy before going to fancier approaches. The strategy we chose was a guess-and-check approach; we're not biasing the generation of molecules in any way whatsoever.</p> <p><strong>Note:</strong> For machine learning practitioners out there, by the way, this example follows my opinion on how one <em>should</em> go about building ML systems. Start with strong baselines first because you never know how long you'll need to debug the fancier systems when they go wrong.</p> <p>What exactly was the model we used, and how did we take protein sequences and convert them into a numerical representation? Well, around 2019 was when the UniRep authors first put on the UniRep paper Biorxiv. My colleague Arkadij (intern at the time) quickly dug into it, replicating some of the results in the paper and extending it in other useful ways. Together, we <a href="">reimplemented the entire model in JAX directly</a>. That, plus user-friendly improvements to the model API, made it an easy-to-use tool for us to obtain a numerical descriptor set for our proteins. We then threw a Random Forest model on top of those numerical descriptors and trained it against our activity data.</p> <p>That model turned out to be a great prioritizer but a horrible scorer. Using the prioritization strategy described in the paper, we could pick out high-performing mutants from the $10^5$ in-silico proposed mutants pool. Still, our predictions of their activity were off. That's okay, though, because ultimately, we were able to measure just $10^2$ proposed mutants to get an activity distribution that was significantly right-shifted compared to the $10^4$ mutants measured over three rounds of directed evolution. (So that you don't have to scroll back up to see the result, I've resurfaced the figure below - see the "ML" panel.) In this way, with a good-enough model, machine-directed evolution can be pretty sample-efficient.</p> <p><img src="activity-dist.png" alt=""></p> <h3 id="structure-informed-machine-directed-evolution">Structure-informed machine-directed evolution</h3><p>This experiment was one that I helped design, and I was suuuuuuuper happy that we got to do it. One question I've had since grad school was this: "When does combining mutations result in linear additivity of our property of interest?" We'll have a <em>superb invariant handle</em> over enzyme evolution if we know the answer to this question. So, to answer this question, we took a hard look at the structure, identified positions that were either <em>at</em> the active site (AS), <em>neighboring</em> the active site (N), or <em>distal</em> to the active site (D). You can get a visual feel for these positions in the figure below.</p> <p><img src="sgm-positions.png" alt=""></p> <p><em>Fig. 3(a) from our paper. Here, we highlight the active site, neighboring, and distal positions on IRED-88 that we mutated.</em></p> <p>Then we took our best single mutants from each category, and generated double and triple combinations of those mutant categories. So, for example, we might combine two active site mutations or two distal mutations with one neighbouring. At its core, the idea was to test whether combinations of these categories of mutations resulted in <em>linear</em> additivity in activity.</p> <p>The result? If you don't touch the active site, then you have a pretty good chance of being able to predict combination activity by simply adding up their individual activity values.</p> <p><img src="linear-additivity.png" alt=""></p> <p><em>Fig. 3(b) from our paper. The results shown here are from our experiments probing linear additivity of mutations. We show that combining mutations in positions distal to the active site result in linearly additive mutations.</em></p> <p>For me, this result was <em>huge</em>! At the time, "big billion parameter BERT models" were all the rage -- and for me, this trend represented intellectual laziness on the part of modellers. Was not the goal of modelling to get a quantitative handle over the invariants of a problem? Bucking the large model trend, with this experiment, we had confirmed that a tremendously more straightforward principle (adding mutations) for engineering enzymes was effective, and we uncovered the conditions under which that principle worked predictably.</p> <p>On this point, when we received our reviewer's comments, one of them wrote:</p> <blockquote><p>the finding that linear combinations of mutations afford predictable activity increases is important</p> </blockquote> <p>I remember being soooooooooo happy when I read that comment. Finally, someone recognized the importance of this point!</p> <p>As for how the activity distribution looked? Just like the machine-directed round - right-shifted and with only $10^2$ samples measured. See Fig. 2(b)'s "SGM panel" (resurfaced below for convenience).</p> <p><img src="activity-dist.png" alt=""></p> <h3 id="low-n-engineering">Low N Engineering</h3><p>We also wanted to test-drive Low N engineering, a strategy that first popped up in the original UniRep paper. Low N engineering is similar in spirit to machine-directed evolution, except that in our case, we had to pretend that we didn't have access to the DMS dataset. Training a model on just 24 data points feels weird for a machine learner. Still, bolstered by the idea of linear additivity of mutations, we were confident that Low N would work out just fine. We took a random set of 24 mutants from the DMS dataset and trained a model on their activity. We then prioritized another 24 to order and test. Likewise, we found a shift in activity distribution, though not as dramatic as the machine-directed and structure-guided rounds. (This is the "LowN" panel in Fig. 2(b).)</p> <h2 id="what-did-we-learn">What did we learn?</h2><p>Firstly, we showed that machine-directed evolution is a <em>sample-efficient strategy for evolving enzymes</em>! Rather than measure tens of thousands of mutants, we only had to measure hundreds to shift the enzyme activity distribution curve dramatically. I think of it as giving ourselves much better shots on goal.</p> <p>Secondly, we uncovered the conditions under which simply combining mutations can result in predictable, additive increases in activity. Fancy models are not required for those circumstances! If you know roughly what a protein's structure is, you can find (what I think of as) the "linear basis functions" for enzyme engineering. Thus, linearly adding mutations should <em>absolutely</em> be a baseline for protein engineers and machine learners that one tries to leverage for engineering - or beat if trying to build fancier models.</p> <h2 id="what-did-i-learn">What did I learn?</h2><p>That second point was, for me, the most satisfying piece of this work. If we can categorize sequence positions as being part of the (1) active site, (2) neighbours to the active site, or (3) distal to the active site, then I am pretty sure that simply adding two distal mutations together would provide the kind of additive effect that we desire. I also now have this hypothesis that a large reason for why machine learning in enzyme engineering works is because of linear additivity of mutational effects.</p> <p>More importantly, I also learned a lot about the pace at which science moves. Data science in the biomedical research space is rate-limited by our ability to generate fit-for-purpose datasets. The rate at which we can generate fit-for-purpose datasets is, in turn, determined by people and equipment. High throughput measurements enabled us to generate the data we needed; if we didn't have that equipment, we'd be unable to do such a large-scale study. People are the other variable to factor in: I had to win the trust of my colleagues by really empathizing with how they made decisions. In this respect, my prior background at the bench and the empathy that comes with experience for the particular difficulties in executing experiments helped me win their trust. That trust, in turn, afforded me the credibility points to participate in experiment design.</p> <p>I am now also of the belief that there's only so much we can do by leveraging public datasets; empirically, I have found myself reaching for public datasets only as a testbed to prototype a model, but have rarely used that public dataset as part of the final solution to our scientific problems. For example, in this project, we used public datasets to validate the model building piece. Still, ultimately our decisions could <em>only be logically taken</em> based on a model trained on fit-for-purpose data. A model trained on data for one assay cannot logically be used to predict results for another assay; things don't work that way. I learned, thus, that in research data science, we data scientists want to partner with colleagues who are willing to generate fit-for-purpose data for the problem at hand.</p> Hiring data scientists at Moderna! (2021)2021-08-26T00:00:00ZEric J. Maurn:uuid:584e9d0c-3fa0-30ac-aad9-e564462f57ff<p>The team I'm on is hiring! We are looking for three bold, curious, relentless, and collaborative data scientists to join Moderna's DSAI group. There are three specializations, one for public health/medical affairs, one for chemistry, and one for biological sequence modelling. Here are the LinkedIn links at which you can apply and learn more about the roles:</p> <ul> <li><a href="">Commercial & medical affairs role</a></li> <li><a href="">Chemistry role</a></li> <li><a href="">Biology role</a></li> </ul> <p>We are looking for strong model-building skills, prior experience handling relevant data, and the compassion & competence to communicate with non-technical stakeholders.</p> <p>Historically, we are a Python + PyTorch shop. Bonus points for special technical skills (network science, Bayesian modelling) on top of a technical track record of building fit-for-purpose machine learning models.</p> <hr> <p>And now for an FAQ that disambiguates some questions that you might have. The answers, views, and observations listed below are my own; they don't represent Moderna's official hiring policies, which I'm striving to adhere to. In no order of importance, and basically in order of what I could think of to include in an FAQ, here they are.</p> <p><strong>Q: Is relocation necessary?</strong> Because of the collaborative nature with colleagues who can't work remotely, we expect relocation to Cambridge, MA, with an eventual return to campus. COVID times dictated a temporary change in practice, but in-person lubricates difficult technical discussions. We do have some colleagues in other states/cities, but they plan to move to Cambridge eventually.</p> <p><strong>Q: Who will the roles be reporting to?</strong> For the chem & bio roles, yours truly. For commercial and medical affairs, my wonderful colleague Adrianna Loback.</p> <p><strong>Q: Who leads the broader team?</strong> Andrew Giessel, data scientist #1 at Moderna. (I am only #6!)</p> <p><strong>Q: Is a Ph.D. required?</strong> The expectation is yes, because of the research-y nature of the role and because of the level of scientific depth required. However, excellent MSc candidates <em>might</em> be considered if a publishing track record or <em>relevant</em> industry experience is present.</p> <p><strong>Q: How urgent is the hiring?</strong> For the bio and chem DS roles, I'm still at the point where I'm willing to wait. We want to consider a diverse slate of candidates before making a decision. For the Commercial & Medical Affairs role, I would defer to Adrianna for her thoughts, but I also want to respect her time - she is slammed with many projects.</p> <p><strong>Q: What are the core skills we need to demonstrate?</strong></p> <p>For the BioDS role: solving scientific problems that rely on biological sequences as input to machine learning models. We have professional bioinformaticians, so traditional bioinformatics skillsets are not really what we're looking for.</p> <p>For the ChemDS role: solving scientific problems that rely on QSAR modelling and the extended suite of modelling tools. We have computational chemists, so traditional comp chem skillsets are not really what we're looking for either.</p> <p>For both roles: showing me that you can build custom differentiable or likelihood-based models and not just grab something off-the-shelf. Or, if you did grab something off-the-shelf, show me that you really have dissected the internals to the point that you can recreate it in a different framework. I only trust modellers who know the ins and outs of the models they build.</p> <p><strong>Q: If I work at Novartis, will I be considered?</strong> Unfortunately, no. I have a non-solicit clause that bars me from recruiting anyone from Novartis within a year of my last day of work, which was 30 July 2021. That means my colleagues cannot include me in any interview panel that involves a candidate currently working at Novartis.</p> <p><strong>Q: Is there an algorithm filtering me out?</strong> No. Real humans are at work. Trust me. I've once thought that way too. But, now that I'm on the other side, I know what it looks like. Our friendly talent acquisition partner in HR is helping us with the process, and he handles wayyyyyyy more than we see. So... yes, we're overwhelmed with the response and have been working through your resumes. But we definitely want to pick well.</p> <p><strong>Q: Is a GitHub repository required?</strong> Not really, but we do want to see your best work at some point, including how you code. All of us, including myself, have work that came from our early days of data science that we're not proud of, but don't worry about those - I'm only interested in knowing how what your best work looks like. A GitHub repo can help as a data point. If you do choose to highlight one, make sure it's done well - a README that explains why your repo exists and how to get started is an absolute necessity!</p> <p><strong>Q: What is the impact of the role to Moderna and the world?</strong> I can't reveal internal workings, but the roles I'm in charge of will involve the core platforms of mRNA, lipid nanoparticle delivery, and protein engineering. There are <em>so, so</em> many open scientific problems that we can solve building models. My friend Jon Bloom at Cellarity characterized it on Twitter this way, "If you’d like your sequence-to-function optimization to impact a billion people... this is the team to join."</p> <p><strong>Q: Will we get feedback?</strong> I did provide feedback for final round intern candidates during my time at NIBR. Unfortunately, I won't have the bandwidth for everyone who applies but will strive to do so for final-round candidates as a courtesy for your time. (Not a promise, though!)</p> <p><strong>Q: What can I do to improve my chances during resume screening?</strong></p> <p>I don't mind revealing how I read your resumes.</p> <p>I skip your education and skills and go straight to projects because I really don't care if you're from the so-called top-tier schools or not. I skip skills because they're so easy to include bullet points on. I'd rather have evidence of skills than a listing of them.</p> <p>I have a mental filter for "used method X to solve problem Y in language Z using packages ABC, with impact K." Miss out on that phrasing, and I'll probably skip over something important in your resume.</p> <p>I don't read your hobbies section either; historically, I have found them irrelevant for my ability to see whether you can fulfill the role requirements.</p> <p><strong>Q: What will your phone screen be like?</strong> I will be on the lookout for clarity in communication, depth, and breadth of knowledge, and I'm going to probe until I see the boundaries of your knowledge or I reach the boundaries of my own. Just so you are aware, I don't follow a standard script, as I prefer to follow the trajectory of your stories. That also means you don't have to prep for the question, "Tell me about yourself." I don't particularly appreciate hearing that question or answering it, and I wouldn't want to hypocritically subject you to that question too. Adrianna might handle things differently.</p> <p><strong>Q: What will the on-site look like?</strong></p> <p>A job talk based on your prior work or a data challenge (your choice). I will work with our recruiting team to ensure the prompt reflects that; if you make it to a virtual on-site and saw this FAQ, please hold me accountable!</p> <p>Following that will be a committee of colleagues, likely collaborators with whom you'll be interacting. I'm going to try to organize things so that each of us covers one to two aspects of the role, such as technical, interpersonal, drive to learn, etc. I will take the collaborators' viewpoints seriously; they sacrifice time to help with hiring, which is my way of respecting their time.</p> <p><strong>Q: Do you look at our online profiles while screening?</strong></p> <p>I do, but only for those whose resumes, I have been intrigued by. It is quite time-consuming, and we have other work to deliver on that pushes our scientific tech platforms further.</p> <p>If your digital footprint is well-curated and presented in a polished fashion, though, it is a good data point and might inspire me to dig further. I sometimes engage in nerdy things like viewing the source of your website to see whether you hand-crafted your theme or not because I'm a nerd like that.</p> <p><strong>Q: What proportion of resumes have you been impressed by?</strong> This is not a question I'm willing to answer, as it could have negative second-order effects on the hiring process. Probably best not to ask me other statistics about the hiring process at this point.</p> <p><strong>Q: What is the expected salary range?</strong> No idea, you would talk with HR about that question.</p> <p><strong>Q: What about the expected title?</strong> Quite likely that for these roles, it will be "Data Scientist" for fresh grads/post-docs with a shorter technical track record, and "Senior Data Scientist" for candidates with a stronger technical track record.</p> <p><strong>Q: Will Moderna survive the next 10 years?</strong> I made a bet on MTX and started on July 19. So my answer is going to be as good as yours.</p> <p><strong>Q: Is deep learning a necessity?</strong> If you look at the JD, it's highly preferred to have more than just feed-forward neural network experience. (I am also strongly considering probing for an experience beyond just <em>transfer learning</em> as well - I find transfer learning intellectually boring, as much as it might be practically useful.) I take this as an indicator of a relentless drive to learn. With interns at NIBR, my best ones were similarly relentless in learning, sometimes mastering something to the point that I would reference their work. So I'm looking for candidates with <em>evidence</em> of that trait.</p> <p><strong>Q: Can you elaborate a bit on model-building skill?</strong> Yes, definitely. I have a strong admiration for individuals whose track record of work reflects their ability to <em>design</em> models in which each component of the model is purposefully and intentionally included. From my perspective, this strongly implies thinking carefully through the data-generating process and translating it into equations. There are some pieces of work where you can <em>just tell</em> that the authors were trying some fancy neural network model for no substantial reason, good as their reasons might be -- they were not injecting any inductive biases into their models. And then there are some pieces of work that combine deep probabilistic modeling in such a creative way that you can <em>just tell</em> that it was well thought through. I'm interested in the trait of <em>carefully thinking through about the model that you're building</em>.</p> <p><strong>Q: Will there be a take-home data challenge?</strong> I am still in flux on this question. We have to ensure that the hiring process is standardized so that no candidate is unfairly assessed. At the same time, we would like to have sufficient information to make an informed decision. I'll probably offer it as one option for you if it could help me assess your software skills and your relentlessness to learn. I want to avoid doing so, though, as it is extra work and is a big disadvantage for candidates who can't take the time out to do one.</p> <p><strong>Q: If I do the take-home data challenge, can I use the work I produce as part of my data science portfolio?</strong> Absolutely. Please show it off - curating a portfolio did many wonders for my career, and I believe the same will be true for you. (This is my way of compensating for your time spent - by investing in a foundational tangible output for your career development.)</p> <p><strong>Q: What is the stack that you all use?</strong> AWS + Docker. We have excellent in-house tooling developed on top of AWS that really simplifies a <em>lot</em> of infra work for data scientists. Two weeks in, I already helped deploy OSS tooling for colleagues. If you join, you'll like what you see.</p> <p><strong>Q: How important are software skills?</strong> Quite important, but you don't have to be a seasoned engineer. I will be looking for <em>evidence</em> of the ability to structure a project's source repository in a way that is reasonably organized, that's all. Most of us are very well-organized; as a reminder, a badly organized GH repo won't do you any favours.</p> <p><strong>Q: Will you review my resume before I submit my application?</strong> Unfortunately I won't have the time to do so. However, if you've read the FAQ, you'll know how best to structure your resume, and you'll have a good idea of whether you'll fit the role or not.</p> <p><strong>Q: Should I apply to all three roles or just one?</strong> I'd advise just one because Adrianna and I are looking out for candidates that might be suitable for each others' roles, and we'd like to reduce the load for our Talent Acquisition partner. So effectively, you'll still be entering a combined pool of candidates, but you'll also be indicating your preference by applying to just one.</p> <p><strong>Q: Can I connect with you on LinkedIn regarding the role?</strong> As a general rule of thumb, I only connect with individuals I have met in person or worked with. I also am notorious for not responding to LinkedIn invites until they pile up. Even if you include your reasons, I might still ignore the request if you send a connection request.</p> My experience switching to GitHub codespaces2021-08-23T00:00:00ZEric J. Maurn:uuid:4e3ddd0d-f8b3-32f3-9600-69f392194232<p>I recently started experimenting with GitHub codespaces and I wanted to share a bit about my experience.</p> <h2 id="what-is-github-s-codespaces">What is GitHub's Codespaces?</h2><p>GitHub Codespaces is a way for anyone who develops in code to work on a repository without going through the hassle of initial setup. At its core, Codespaces is based on container technology; essentially, code is cloned into a volume and mounted into a container that is defined by a single source of truth <code>Dockerfile</code>. This is known as a "development container", which VSCode supports excellently. GitHub Codespaces takes this one step further and runs the container on a cloud VM, thereby eliminating any local setup overhead: with one click, you get set up in a development environment inside the browser, connected to a VM that is potentially more powerful than your own.</p> <h2 id="what-benefits-do-we-get-by-using-codespaces">What benefits do we get by using Codespaces?</h2><p>To illustrate the benefits of Codespaces, and development containers more generally, I need to recount the 2019 <code>pyjanitor</code> sprints at SciPy 2019 and PyCon 2019.</p> <p>These were the days before I knew anything about development containers. As such, the best environment isolation tool I knew of at the time was Conda environments. As such, I had instructions for Conda environment development setup. It was, to say the least, quite a bit of work getting that documentation up and running. However, not everyone uses Conda; some Python developers either have a preference for <code>pip</code>-oriented virtual environment tooling or are already invested in it and have a shell configuration built around it. Other users were using Windows; this made things particularly challenging for me when debugging because I hadn't used a Windows machine in over 13 years. (I had switched to a Mac in 2006 and never looked back.) As you can see, the main challenge I had to deal with as a maintainer and sprint lead was the myriad and variety of possible environment setups; each contributor also had to work through their own system's quirks to get up and running. Though some found it satisfying, others found it frustrating; if left alone to wrangle environment set up, first-time open source contributors would most likely be scared off.</p> <p>Codespaces, and development containers more generally, solves <em>that</em> exact problem of development environment setup by taking responsibility for it out of the hands of the contributor and putting that responsibility in the hands of the project maintainer. The project maintainer sets up a working container definition via a <code>Dockerfile</code> and a <code>devcontainer.json</code> file that is sufficient for all of the tasks necessary to work on a project. Those tasks might include running tests, building docs and previewing them on a web server, or building an app and previewing it on a web server. For education materials that I develop as a hobby, I can get new contributors set up and running on Codespaces or dev containers running Jupyter Lab in the background automagically, no setup is required on their side. I even started developing my personal website, yes, this exact site that you're viewing right now, on Codespaces.</p> <p>The hardware that Codespaces VMs run on can be quite hefty and impressive. For software development that involves heavy computation, having access to a 32-core, 64GB RAM machine can be quite liberating when our local machine is only an 8-core, 16GB RAM machine. Impressively, when I checked the specs of the VM, I saw that I was running on a 4-CPU, 8GB RAM box. That was more than generous for what I needed to develop this website.</p> <p>Even better, the entire Codespaces setup <em>feels</em> local, even though it is running in the cloud; if there are temporary web services that we need to run, such as the Lektor web server that I used to write this blog post in, we are given a temporary URL for that Codespaces session that lets us access the web service easily, as if we were accessing something on <code>:<port>/</code>. And as a bonus, that URL can be provided to fellow developers if they need a live preview of the site to provide feedback, eliminating delays in feedback that may arise from using a CI system to preview the docs. (As they say, "right tool for the job" - CI previews are good for asynchronous development but potentially frustrating to wait for in synchronous, pair programming settings.)</p> <p>Another benefit, which might feel a bit niche but is highly relevant, is that with Codespaces, we need not worry about multiple SSH keys existing on a system and which SSH key we use. (I for one, prefer to have just one key for one computer, which simplifies things greatly.) Some users configure their system to use multiple SSH keys. Sometimes the reason is intentional, but at other times the reason is something specific and peculiar in history that we forgot why later on... and yet the system state remains encrusted. The confusing part comes when a relatively inexperienced <code>git</code> user tries to clone a repository onto their system using SSH keys but forgets which SSH key they are supposed to use for accessing their remotes. Using Codespaces we completely eliminate this stumbling block, because access to the remote is granted automagically.</p> <h2 id="can-you-do-data-science-work-in-codespaces">Can you do data science work in Codespaces?</h2><p>The short answer is yes!</p> <p>The longer answer depends on what your preferred configuration is.</p> <p>If you're used to running code in Jupyter notebooks, then you should ensure that Jupyter is included in your environment definition. You should also ensure that the appropriate port, which by default is usually <code>8888</code>, is exposed in <code>devcontainer.json</code>. Once your Codespace is launched, you should be able to run a Jupyter session from inside there.</p> <p>On the other hand, you can also run Jupyter notebooks directly from inside VSCode! To enable this, you'll have to install the Jupyter extension for VSCode. That's basically it!</p> <h2 id="what-are-some-limitations-of-codespaces">What are some limitations of Codespaces?</h2><p>Right now, I can use Codespaces for free because it is in beta until September 10. However, as with any good product, GitHub will charge for the infrastructure that backs Codespaces. As someone who chooses to invest in good <em>local</em> compute hardware, I'd say paying for more compute on the cloud when I have more than sufficient compute locally is a bit of a hard sell.</p> <p>To get around that, though, if one's project is small enough and doesn't require that much compute, one can use development containers locally too, thereby taking advantage of isolated environments while also making full use of our local system.</p> <p>With all of that said, for large projects with many developers involved and/or those projects that might involve large compute, I can see the use of Codespaces being a productivity saver.</p> <h2 id="what-do-i-hope-to-see-for-codespaces">What do I hope to see for Codespaces?</h2><p>One thing that would blow my mind away is if GitHub offered a free tier for Codespaces, tied to a user's account, that gave a high time limit on the smallest unit of compute available, something like 3000 minutes per month on a 2-core/4GB VM. 3000 minutes equates to about 2.5 hrs of software development time on a daily basis 5 days/week, which is more than generous for the vast majority of open-source projects. (Explicitly not asking for unlimited! That may open the system to abuse.) Such a move would be a huge enabler for open-source projects by lowering the barrier to contribution.</p> Beautiful Graph Visualization with `nxviz`2021-08-16T00:00:00ZEric J. Maurn:uuid:3e975ade-c647-379a-92bc-206bd73b7875<p <code>nxviz</code> project.</p> <p><code>nxviz</code> is a library that I originally built during my graduate school training days. My goals were simple: to produce two kinds of beautiful and rational graph visualizations: Circos plots and Hive plots, both built by one of my graph visualization heroes, <a href="">Martin Krzywinski</a> of the BC Cancer Research Center in Vancouver, BC. Back then, an easy API for making graph visualizations did not exist in the Python world. So I decided to scratch my builder's itch and created that API.</p> <p>Fast forward 5 years later, <code>nxviz</code> has become a part-time research hobby into graph visualization while also being a generally useful tool for Pythonistas who wish to visualize graphs. The goals are simple: to provide a declarative API for producing beautiful and <em>rational</em> graph visualizations from NetworkX graph objects. In this post, I would like to introduce you to the basic, high-level plotting API so that you can get started with it easily.</p> <h2 id="what-plots-can-you-make-with-nxviz">What plots can you make with <code>nxviz</code>?</h2><p><code>nxviz</code> provides a family of plots: Circos, Arc, Matrix, Hive, and Parallel plots. They are unified by this idea that <em>rational</em> plotting starts with prioritizing the placement of nodes.</p> <p>Assuming you have a NetworkX graph called <code>G</code> that you have been working with in-memory, making a Circos plot that has colour annotations for the nodes and edge transparencies is as simple as:</p> <div class="hll"><pre><span></span><span class="c1"># We assume you have a graph G that is a NetworkX graph object.</span> <span class="c1"># In this example, all nodes possess the "group" and "value" node attributes</span> <span class="c1"># where "group" is categorical and "value" is continuous,</span> <span class="c1"># and all edges have the "edge_value" node attribute as well.</span> <span class="kn">import</span> <span class="nn">nxviz</span> <span class="k">as</span> <span class="nn">nv</span> <span class="n">ax</span> <span class="o">=</span> <span class="n">nv</span><span class="o">.</span><span class="n">circos</span><span class="p">(</span> <span class="n">G</span><span class="p">,</span> <span class="n">group_by</span><span class="o">=</span><span class="s2">"group"</span><span class="p">,</span> <span class="n">sort_by</span><span class="o">=</span><span class="s2">"value"</span><span class="p">,</span> <span class="n">node_color_by</span><span class="o">=</span><span class="s2">"group"</span><span class="p">,</span> <span class="n">edge_alpha_by</span><span class="o">=</span><span class="s2">"edge_value"</span> <span class="p">)</span> <span class="n">nv</span><span class="o">.</span><span class="n">annotate</span><span class="o">.</span><span class="n">circos_group</span><span class="p">(</span><span class="n">G</span><span class="p">,</span> <span class="n">group_by</span><span class="o">=</span><span class="s2">"group"</span><span class="p">)</span> </pre></div> <p><img style="width:250px" src="./circos.png"></p> <p><code>nxviz</code> assumes that node attribute fields, i.e. the keys in the Python dictionary that constitutes the node attribute dictionary, are consistent across every node. (There are special cases where we can break this assumption, but we won't go into that here.) The same is said for edge attribute data. With that information, we can declare that we would like nodes to be coloured by some attribute and edges to have their transparency controlled by some other attribute.</p> <p>Apart from Circos plots, other plots are available: Hive plots, Arc plots, and Matrix plots, as you can see below.</p> <p><img src="nxviz-gallery.png" alt=""></p> <h2 id="what-is-the-underlying-philosophy-of-nxviz">What is the underlying philosophy of <code>nxviz</code>?</h2><p>When analyzing a graph, <em>structure</em> is what we primarily pursue. Thus, when visualizing a graph, we should highlight its structure. To additionally make the graph <em>beautiful</em>, one needs to impose additional constraints. As such, the <em>rational</em> approach to visualization is to prioritize the placement of nodes. Doing so helps us avoid the construction of messy hairballs, which, though illustrative of the complexity of networks, don't actually give us much in the way of visual insights.</p> <p><code>nxviz</code> works by first deciding where overall to place nodes. This is known as the "graph layout" step of network visualization. For example, in a Circos plot, we first constrain all nodes to be placed on the circumference of a circle. Next, we need to decide how to place nodes <em>relative to one another</em> by leveraging node metadata attributes. For example, if we plot the social network of students on the Circos plot and want to visualize how height co-varies with connectivity, we might order the students' nodes along the circumference from shortest to tallest. If students were also assigned Houses, as in Harry Potter, we might group the students by their House. Once that basic layout is done, we can add node styling, edge drawing, and edge styling into the mix.</p> <h2 id="what-else-can-you-do-with-nxviz">What else can you do with <code>nxviz</code>?</h2><p>Apart from making beautiful plots, <code>nxviz</code> does more! For example, you can also annotate the plots using our annotation API and highlight certain nodes using the highlighting API. And because <code>nxviz</code> plots are built entirely on <code>matplotlib</code> axes, you can drop down to the <code>matplotlib</code> API easily to make fine-tuned customizations of your own.</p> <h2 id="where-can-i-learn-more-about-nxviz">Where can I learn more about <code>nxviz</code>?</h2><p>Please head over to the <a href="">official <code>nxviz</code> documentation page</a>. I'd love to hear how you use it and where it can be improved - and even better, if you'd like to work together to implement something, then let's hash it out on <a href="">the issue tracker</a>!</p> <p>Finally, I will be teaching <a href="">a tutorial on Network Analysis</a> on the <a href="">ODSC AI+ platform</a> - learn more about NetworkX, applied network science, and graph visualization up there!!</p> Ancestors and descendants apply to undirected and directed graphs2021-08-15T00:00:00ZEric J. Maurn:uuid:41b9a53f-f0fa-32e9-accf-00ec1de63c4d<p>Today I learned a new thing! It is inspired by <a href="">PR #5017</a> from a GSoC student that I have been co-mentoring with Ross Barnowski (in the NetworkX dev team). The PR really forced me to think about the concepts described here.</p> <p>There are two functions in the NetworkX library called <code>ancestors(G, n)</code> and <code>descendants(G, n)</code>. Respectively, they return:</p> <ul> <li><code>ancestors</code>: All nodes that have a path into a node in graph G.</li> <li><code>descendants</code>: All nodes that have a path from a node in graph G.</li> </ul> <p>Do you think it applies to directed graphs only or both directed and undirected graphs when you think of this definition?</p> <p>Intuitively, we might think that ancestors and descendants apply only to directed graphs, particularly directed acyclic graphs (like trees). However, as it turns out, based on the definition provided, they must apply to both directed and undirected graphs.</p> <p>Here's why.</p> <p>We can think of undirected graphs as being <em>equivalent</em> to directed graphs that have bidirectional edges between nodes. When viewed this way, an undirected graph is a specific case of the more general directed graph.</p> <p>When we trace all ancestors of a node, we are recursively collecting nodes along the path into that node. If we continue recursively collecting nodes in the bidirectional representation of an undirected graph, then we will end up collecting all of the nodes in the <em>connected component</em> of the graph that are connected to the node we are asking for ancestors. The same argument applies to descendants.</p> One killer way to burst to the cloud from your laptop2021-07-12T00:00:00ZEric J. Maurn:uuid:c5e82b78-d7b2-36bb-9e53-a410d42da0d0<p>Today I finally had a chance to test-drive <a href="">Coiled Computing's</a> product. Oh boy, am I impressed!</p> <p>The first time I first tasted parallel computation on the MIT GridEngine compute cluster in 2014. Ever since then, one thing I've been <em>dreaming</em> of is the ability to burst my computation into remote machines <em>from my little laptop</em>.</p> <p>The computing model I'm thinking of isn't <em>exactly</em> an SSH tunnel, as this model presumes a few things:</p> <ol> <li>We have permanent access to a remote beefy machine or a cluster.</li> <li>We have the ability to SSH directly into it to manipulate it.</li> <li>Our compute environment lives <em>entirely</em> on the cluster and not on our local machine.</li> </ol> <p>The computing model I'm thinking of is as follows:</p> <ol> <li>We only want convenient and ephemeral access to the practically infinite cloud computing resources available.</li> <li>We merely need to declare what our environment <em>ought</em> to look like using configuration files.</li> <li>Our compute environment lives <em>primarily</em> on my portable machine and can be replicated in the cloud.</li> </ol> <p>You can think of this as akin to having <a href="">12 Factor App</a>-like computing environments.</p> <p>Coiled Computing's product provides <em>exactly</em> <code>environment.yml</code>.</p> <p>Once we've done that, if you've got code written against Dask that runs on your little laptop, then <em>literally nothing else needs to change</em>! Execute the rest of your code, whether in a Jupyter notebook or in a Python script.</p> <p>From my perspective, this is the ideal situation for parallel computation.</p> <p.</p> <p>Additionally, easy-to-follow documentation is readily available, making it easy for me to create very ephemeral Dask clusters in the cloud that also shut down as soon as my computation is done.</p> <p>By contrast, at work, I had tried Databricks. It was helpful for some things that my colleagues needed, but it was also highly inflexible: back in 2018, my <code>conda</code> environment was not recognized, I couldn't develop and use custom software packages in support of a project, and I most certainly couldn't have the convenience of a local computation environment. So I quickly ditched it because of the lack of flexibility.</p> <p.</p> <p>By contrast, Coiled has me smiling to my ears. I'm very impressed with what I see here! <a href="">Clarke's third law</a> <em>feels</em> like magic. That was the exact feeling I had when I first test-drove their demo code successfully on my laptop.</p> <p><img src="coiled-preview.png" alt=""> <img src="coiled-preview-2.png" alt=""></p> <p>Kudos to Matt and Hugo, the two whom I know most closely, and the rest of the team, who have really built a fantastic product! I am excited to try things out on my projects at home :).</p> How to enable custom source package installation in Binder2021-07-10T00:00:00ZEric J. Maurn:uuid:19d4a01e-9b99-36e7-9aef-7f0b765b9600<p>When I make tutorial material, I often choose to write a custom library in support of the tutorial. For example, for this JAX-centric tutorial repository that I made (<code>dl-workshop</code>),.</p> <p>When building a Binder container using a configuration file, it's sometimes difficult to include the custom source library in the Binder build. I could, in theory, use the <code>pip</code> section of an <code>environment.yml</code> file to install the custom source as follows:</p> <div class="hll"><pre><span></span><span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">my_project</span><span class="w"></span> <span class="nt">channels</span><span class="p">:</span><span class="w"></span> <span class="p p-Indicator">-</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">conda-forge</span><span class="w"></span> <span class="nt">dependencies</span><span class="p">:</span><span class="w"></span> <span class="p p-Indicator">-</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">python=3.9</span><span class="w"></span> <span class="p p-Indicator">-</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">...</span><span class="w"></span> <span class="p p-Indicator">-</span><span class="w"> </span><span class="nt">pip</span><span class="p">:</span><span class="w"></span> <span class="w"> </span><span class="p p-Indicator">-</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">...</span><span class="w"></span> <span class="w"> </span><span class="p p-Indicator">-</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">-e src/.</span><span class="w"></span> </pre></div> <p>However, there are cases where we might not necessarily want the current version of the custom library. In those cases, we may instead prefer a canonical version that we can reference (like the one that lives on the <code>master</code>/<code>main</code> branch). Sticking the <code>-e src/.</code> in <code>environment.yml</code> thus restricts the flexibility that we might otherwise need.</p> <p>Suppose this level of flexibility is needed. In that case, we need to match the flexibility with the appropriate composition of tooling. Writing a <code>Dockerfile</code> could be the way out. Thankfully the Binder team made a fit-for-purpose abstraction called the <a href=""><code>postBuild</code> script</a>. Essentially <code>postBuild</code> is nothing more than a shell script that gets executed right after the Docker container is built. We can use it to install our custom source library for use with Binder:</p> <ol> <li>Include a file named <code>postBuild</code> in the root of our repository. It shouldn't have any file extensions, such as <code>.sh</code> or <code>.zsh</code>.</li> <li>In there, add in the following commands, assuming our source code library is in the directory <code>src/</code>:</li> </ol> <div class="hll"><pre><span></span><span class="ch">#!/bin/bash</span> <span class="nb">set</span> -e <span class="c1"># don't allow errors to fail silently</span> <span class="nb">echo</span> <span class="sb">`</span>which pip<span class="sb">`</span> <span class="c1"># in case the wrong `pip` is used, this will let us debug</span> pip install -e src/ <span class="c1"># install the custom library</span> </pre></div> <p>As a side note, Binder also provides <a href=""><code>start</code></a>..</p> <p>I really do have to give it to the Binder team. They've done a fantastic job here in architecting the package to satisfy <em>workflow</em> needs. Kudos!</p> How I do conference talks in 20212021-06-04T00:00:00ZEric J. Maurn:uuid:ff82ca35-b854-35ff-a31c-e281d07d7f82<p>This year I participated in PyCon US 2021. It's my 7th PyCon running, and I'm thankful to have been able to attend one every year since 2017.</p> <p>For the past year and a half, we've been on lock-down, though. This means we have had to do conferences online instead.</p> <p>In this blog post, I wanted to simply document what my setup and process for doing these recordings was like, in addition to writing down why I made particular choices.</p> <p>My recording setup can be broken down into the hardware and software setup.</p> <h2 id="the-hardware">The hardware</h2><p>Let's first talk about the hardware setup.</p> <h3 id="video-recording">Video recording</h3><p>To record videos, I used a 1080p webcam that I bought off Amazon. Back then, because supplies were low, I paid a premium of around USD80 to get one of the lesser-known brands; brand-name Logitech would have cost close to USD200. Nowadays, though, these webcams are available at a much lower price, about USD40 instead.</p> <h3 id="audio-recording">Audio recording</h3><p>For audio, I splurged and bought myself a RODE podcaster USB mic. Every condenser microphone that I had tried recorded way too much background noise. With the red line rolling in the background from time to time, it'd be too distracting in the recorded videos. Hence, I opted for a dynamic microphone. Of them, the RODE Podcaster USB mic seemed to be at the sweet spot for being relatively affordable at about USD200+. This included the boom arm and shock mount while still having a good enough quality for recordings. As we all know, the most crucial element in videos is actually the audio, and I wanted to make sure this was done right.</p> <h3 id="hardware-for-maintaining-a-standing-posture">Hardware for maintaining a standing posture</h3><p>When doing presentations, I have a preference for standing over sitting. This is because I was trained to give presentations while standing, so I'm used to it, and standing gives me this sense of formality that keeps me grounded when I'm doing these talks.</p> <p>So in support of standing while presenting, I have three pieces of hardware that help.</p> <p>The first is the monitor desk arms by North Bayou. They keep my monitor and laptop in an elevated position and are at about the right height. The second is the folding laptop desk. It <em>just so happens</em> to be of the correct height such that when I stand, my hands land comfortably on the keyboard and mouse. I also have a microphone boom arm, which allows me to keep the microphone at a comfortable height. With a pop filter, plosives become minimized. I tried it out at a PyMC Labs weekly meeting, and everyone could hear the difference.</p> <h3 id="usb-dock">USB Dock</h3><p>Connecting the entire hardware setup is the Tobenone USB 13-port docking station. It provides power to the laptop, HDMI connectivity to the floating monitor, and USB-A connectivity for the webcam and microphone. Both my keyboards are Bluetooth (the big one is Logitech's K480, which allows simultaneous connectivity to three devices).</p> <h3 id="pics-or-it-never-happened">Pics or it never happened</h3><p>Here's a photo of the setup!</p> <p><img src="desk-setup-2021.jpeg" alt=""></p> <h2 id="the-software">The software</h2><h3 id="open-broadcaster-software">Open Broadcaster Software</h3><p>When recording, I set up the <a href="">Open Broadcaster Software</a> (OBS) with a scene that has:</p> <ol> <li>A video capture channel</li> <li>A screen capture channel</li> <li>An audio capture channel</li> </ol> <p>The video capture takes in video from my webcam; the screen capture is recording the main presentation window; the audio capture records audio from the RODE microphone.</p> <h3 id="presentation-slides">Presentation slides</h3><p>I've taken a particular liking to web technologies. Hence, I typically make my slides using a combination of hand-crafted, raw HTML backed by <code>reveal.js</code>. I like HTML slides because I can then host the slides on GitHub Pages without manually compiling them from another source, such as Keynote. Additionally, I can have complete control over the presentation.</p> <p>Now, one may suggest that writing Markdown followed by calling on any one of the available markdown-to-reveal converters would make authoring the slides a bit easier. I agree, especially when all I need is to quickly bang out a set of slides! That said, I sometimes also want to have fine-grained control over particular transitions. Sometimes wish to embed custom JavaScript inside the slides. And at other times, I'd like to do highly custom HTML layouts, such as two cards on the left-to-right. Of course, to do this, I'd end up writing HTML and JavaScript anyway, so I figure I might as well write the entire slide deck in hand-crafted HTML anyways.</p> <p>Committing the slides to GitHub also gives me GitHub pages. That means I can distribute a URL to my audience. They can flip through on their own terms if they choose to go on their own pace; no need to be constrained by my own pace.</p> <h3 id="scripting-and-teleprompting">Scripting and teleprompting</h3><p>I use Ulysses (and, nowadays, Obsidian if I happen to be working there) to draft my script. The ability to focus on just the text and nothing else helps a lot.</p> <p>Because I have a two-monitor setup (laptop native and the external monitor), my OBS setup will capture the window on the laptop. My external monitor, where I have my webcam mounted, is also where I set up a makeshift. There, I use Ulysses (or Obsidian) with a window size just wide enough to manually scroll through the text as I click down the slides. It took me a bit of finessing around to get the arrangement right. Still, the general idea is to have the window focus on the presentation but mouse cursor on my script. That is my poor man's teleprompting setup.</p> <h3 id="video-editing">Video editing</h3><p>Much as I love open source software, my most recent training was on LumaFusion on the iPad, and as such, I have stuck with it on my Mac as well.</p> <h2 id="thoughts-on-recording">Thoughts on recording</h2><p>Like Ramon, I also sometimes stumble on my words while recording. I also sometimes veer off course and improvise. And just like Ramon's experience, I have learned to accept that some stumbling and pausing make for a much more humanizing and natural video recording.</p> <p>Getting to this point did take a bit of time and practice. It was vital for me to have a few conferences to get into the groove of recording things. Nowadays, recording a video feels much more natural and less awkward. I think I might start doing it a bit more often and not just for conferences.</p> Ward: A new Python package for software testing2021-05-29T00:00:00ZEric J. Maurn:uuid:29c91a15-9b72-361b-a3c2-36d7029ac69b<p>Today I learned about a new package called <a href="">Ward</a>. It claims to be an alternative to pytest <em>with a focus on productivity and readability</em>.</p> <p>Looking at the examples on <a href="">the docs</a>, I see a few cool things that are in there:</p> <div class="hll"><pre><span></span><span class="nd">@fixture</span> <span class="k">def</span> <span class="nf">three</span><span class="p">():</span> <span class="k">yield</span> <span class="mi">3</span> <span class="nd">@test</span><span class="p">(</span><span class="s2">"</span><span class="si">{a}</span><span class="s2"> + </span><span class="si">{b}</span><span class="s2"> == </span><span class="si">{result}</span><span class="s2">"</span><span class="p">)</span> <span class="k">def</span> <span class="nf">_</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">result</span><span class="o">=</span><span class="n">three</span><span class="p">):</span> <span class="k">assert</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">==</span> <span class="n">result</span> <span class="nd">@test</span><span class="p">(</span><span class="s2">"simple addition"</span><span class="p">,</span> <span class="n">tags</span><span class="o">=</span><span class="p">[</span><span class="s2">"unit"</span><span class="p">,</span> <span class="s2">"regression"</span><span class="p">])</span> <span class="k">def</span> <span class="nf">_</span><span class="p">():</span> <span class="k">assert</span> <span class="mi">1</span> <span class="o">+</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">3</span> </pre></div> <p>Firstly, how the <code>@test</code> decorator is used to provide a descriptive name, thus allowing us to completely bypass trying to think up descriptive test function names and instead simply describe the test in plain English. I can see how this makes documenting the test a little bit easier.</p> <p>Secondly, how tags (which in <code>pytest</code> land would be <code>marks</code>) are simply added as part of the <code>@test</code> decorator.</p> <p>The syntax is definitely attractive. That said, while I like the syntax, one thing that might prevent me from using <code>ward</code> at this moment in time is the lack of clarity with how it interfaces with <code>hypothesis</code>, which I use to do testing of machine learning model implementations. I might do some digging in the near future. For now, just leaving this note here for future reference.</p> Help MathJax render correctly by wrapping latex in span tags2021-05-28T00:00:00ZEric J. Maurn:uuid:f4435f7e-173a-3c27-b95e-98a46b84cc5f<p>Today I learned that we can help MathJax <em>guarantee</em> correct rendering of LaTeX in HTML and HTML-converted Markdown documents by simply wrapping the latex inside a <code><span></code> tag.</p> <p>For example, if the following equation gives you trouble because the underscore gets parsed by a Markdown parser incorrectly:</p> <pre><code>$y_{alpha} = 3x^2 + 5$ </code></pre> <p>If it is rendered correctly, you'll see: $y_{alpha} = 3x^2 + 5$</p> <p>However, if the rendering is butchered somehow, then we can simply add <code><span></code> tags around it to guarantee correct parsing:</p> <pre><code><span> $y_{alpha} = 3x^2 + 5$ </span> </code></pre> <p>With the span tags, it'll look like: <span>$y_{alpha} = 3x^2 + 5$</span>. (Inspect the website source to see how I did it.)</p> <p>This tip should apply anywhere we use LaTeX inside Markdown and wish to have it render correctly in HTML using MathJax. Some examples of documents where this might be useful is in:</p> <ol> <li>Jupyter Notebooks</li> <li>vanilla Markdown files,</li> <li>Markdown blocks in YAML files that get parsed.</li> </ol> Grammarly is surprisingly useful2021-05-19T00:00:00ZEric J. Maurn:uuid:3155f228-fbec-3313-9ba1-952bd7e83d69<p>Grammarly is surprisingly helpful.</p> <p>As a native speaker of English and who once nearly chose to do English Literature as part of my A-Level coursework, I pride myself on having a good command of English grammar, vocabulary, and literary devices to communicate effectively. That said, language habits that form over time become hard to change. Over-used passive voice, wrong placement of commas, over-use of a single word, and many more bad habits can conspire to muffle my message.</p> <p>In using Grammarly, I find that it helps me be much more aware of myself when writing. I'm not kidding when I say that my experience writing is just like the advertisements portray it: write something and use the immediate feedback to iterate quickly. Frequently I find that my writing <em>after</em> Grammarly edits is much more concise and to-the-point. It's something I would recommend trying out. The premium version might be worth it for individuals whose main day-to-day work relies heavily on writing; otherwise, the free version is a great preview of what it's like!</p> Set environment variables inside a Jupyter notebook2021-05-14T00:00:00ZEric J. Maurn:uuid:0028a19a-340a-3ae2-acec-931583785e70<p>Today, I learned that one can set an environment variable from within a Jupyter notebook session.</p> <p>Let's say you needed an environment variable set for your Jupyter notebook, but you:</p> <ol> <li>Don't want it set globally or project-wide, or</li> <li>Forgot to set it before you launched Jupyter.</li> </ol> <p>To do so, add the following line(s) to the very, very first cell of the notebook:</p> <pre><code>%env MY_ENV_VAR=value </code></pre> <p>Within the same code cell, you can clone that as many times as you want to set environment variables of any kind.</p> <p>To verify that the environment variable has been set correctly, you can use the following code block to view the value of the environment variable that you set:</p> <div class="hll"><pre><span></span><span class="kn">import</span> <span class="nn">os</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">"MY_ENV_VAR"</span><span class="p">]</span> </pre></div> <p>Now, one thing has to be stated - according to 12 Factor App development principles, you might need to set environment variables for sensitive information. You should <strong>never, ever, ever</strong> set those environment variables at the top of your notebook because they will be exposed!</p> Desktop Python applications with Flask2021-05-12T00:00:00ZEric J. Maurn:uuid:70f3f3bf-3425-3106-9042-03e8abbdbd74<p>Today, I learned that it's possible to create a desktop app that uses Flask as the webserver, Python for application logic, and HTML/CSS/JS for the front-end.</p> <p>The logic basically that we split the desktop app code into the front-end and back-end, and we let the front-end and back-end communicate data using JSON. The backend code does whatever complex logic is needed, while the front-end code simply does the rendering. It's basically a very familiar pattern for server-based applications.</p> <p>One tool that helps with this is <a href=""><code>flaskwebgui</code></a>, by GitHub user <code>@ClimenteA</code>. I found out about this tool by reading a <a href="">dev.to article on using FastAPI to create a desktop application</a>.</p> <p>I also saw <a href="">another article on using Svelte.js + Flask to create a Python app</a>. That one also looks like a simple pattern to follow, with the advantage that Svelte.js makes reactivity very simple.</p> <p>Of course, if you're looking to stay in a single language without this separation of concerns, it's feasible to stay with a single framework, like Streamlit, ipywidgets, Panel, and more. Indeed, for some projects, it may be more pragmatic to stick with a single language depending on the language skillset of those working on that project.</p> Canada exports education2021-05-06T00:00:00ZEric J. Maurn:uuid:f8109887-ba8f-3771-a7c3-2992fb47fef7<p>Today, I learned that one of Canada's exports is actually <em>education</em>.</p> <p>It sounds weird, but I learned this from Economics Explained, and I think I can follow the logic.</p> <p>A foreign student who studies in Canada brings money into the country. Four years later (or longer), Canada sends that student back to their home country. Canada's economy gets money up-front, while the foreign country gets a smarter student later on.</p> <p>Economists have a very different way of looking at the world.</p> <p><a href="">Here is the relevant video.</a></p> Probability Simplex2021-05-05T00:00:00ZEric J. Maurn:uuid:4d06bbad-66a2-3909-81ab-9598750c61d8<p>Doing another TIL (<a href="">as inspired by Simon Willison</a>), this time being the definition of a probability simplex.</p> <p>I gleaned a pretty good definition of the probability simplex from <a href="">this article</a>. From a computational perspective, it is represented as:</p> <ol> <li>a vector of $K$ numbers ($K$ being the dimension of the simplex) that lie between 0 and 1, such that</li> <li>their sum is equal to 1.0 (it is a probability vector, after all), and</li> <li>each vector slot represents a choice mutually exclusive with others.</li> </ol> <p>Here are a few examples.</p> <ul> <li>A probability simplex where $K = 2$ might be the vector $(0.15, 0.85)$.</li> <li>A probability simplex where $K = 3$ might be the fector $(0.10, 0.50, 0.40)$.</li> </ul> <p.</p> Nudge for your flu shot2021-05-03T00:00:00ZEric J. Maurn:uuid:e5a6665b-4e24-388d-8cc9-07666647ffd5<p>I'm a fan of nudges that help us make better decisions for society. In <a href="">this recent study published in PNAS</a>, researchers found that text nudges could boost vaccination rates by up to 5 percentage points. The text nudge was one that, in my opinion, removed complexity for the individual. Consider the following selection of nudges (lifted from the paper):</p> <ul> <li>Flu shot reserved for you</li> <li>Share a joke about the flu</li> <li>Improve the flu shot rate in your region</li> </ul> <p>If you were to rank-order the three options, which would you find to be the most effective?</p> <p>Looking at the results of the paper, it was the "Flu shot reserved for you" text, out of the 19 interventions tested (including the three above) that worked the best. This result immediately prompted thoughts: why?</p> <p>I can't claim to fathom what goes on in people's minds, but on doing some post-reading self-reflection, I arrived at the following answers for myself. If I were given the first text message over the third, I would:</p> <ol> <li>Perceive myself as being treated with care by the healthcare system. ("We reserved something good for you.")</li> <li>Find the decision much easier to take ("yes" vs "no").</li> <li>Find the interaction much more lightweight (flash binary decision vs. having to think through possibilities).</li> <li>No additional action was needed, the flu shot is given as a byproduct of doing a routine clinical visit.</li> </ol> <p>In thinking through these options, I can see why such nudges would be the most effective of them all.</p> Preview built static sites on Netlify2021-04-28T00:00:00ZEric J. Maurn:uuid:9eca8699-380d-3845-93dd-7b3001ee5639<p>Twitter is an amazing universe. I asked a question, and friends came to help.</p> <p>I use Netlify to host my site previews. That said, I use GitHub actions to build the site, as site-building on Netlify has a limit of 300 minutes, while for my open source projects, I have unlimited minutes. I was curious about how to enable static site previews on Netlify <em>with an automatic comment on the PR housing the URL</em>. <a href="">Peter Bull kindly replied</a>, and that's when I learned that <a href="">GitHub user @nwtgck</a> created <a href="">a GitHub Action</a> that makes this easy.</p> <p>Inside one of our GitHub actions configuration YAML files, we add this step:</p> <div class="hll"><pre><span></span><span class="w"> </span><span class="c1"># Taken from:</span><span class="w"></span> <span class="w"> </span><span class="p p-Indicator">-</span><span class="w"> </span><span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">Deploy site preview to Netlify</span><span class="w"></span> <span class="w"> </span><span class="nt">uses</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">nwtgck/actions-netlify@v1.1</span><span class="w"></span> <span class="w"> </span><span class="nt">with</span><span class="p">:</span><span class="w"></span> <span class="w"> </span><span class="nt">publish-dir</span><span class="p">:</span><span class="w"> </span><span class="s">"./site"</span><span class="w"></span> <span class="w"> </span><span class="nt">production-deploy</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">false</span><span class="w"></span> <span class="w"> </span><span class="nt">github-token</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">${{ secrets.GHPAGES_TOKEN }}</span><span class="w"></span> <span class="w"> </span><span class="nt">deploy-message</span><span class="p">:</span><span class="w"> </span><span class="s">"Deploy</span><span class="nv"> </span><span class="s">from</span><span class="nv"> </span><span class="s">GitHub</span><span class="nv"> </span><span class="s">Actions"</span><span class="w"></span> <span class="w"> </span><span class="nt">enable-pull-request-comment</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">true</span><span class="w"> </span><span class="c1"># this is crucial!</span><span class="w"></span> <span class="w"> </span><span class="nt">enable-commit-comment</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">false</span><span class="w"></span> <span class="w"> </span><span class="nt">overwrites-pull-request-comment</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">true</span><span class="w"></span> <span class="w"> </span><span class="nt">alias</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">deploy-preview-${{ github.event.number }}</span><span class="w"></span> <span class="w"> </span><span class="nt">env</span><span class="p">:</span><span class="w"></span> <span class="w"> </span><span class="nt">NETLIFY_AUTH_TOKEN</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">${{ secrets.NETLIFY_AUTH_TOKEN }}</span><span class="w"></span> <span class="w"> </span><span class="nt">NETLIFY_SITE_ID</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">${{ secrets.NETLIFY_SITE_ID }}</span><span class="w"></span> <span class="w"> </span><span class="nt">timeout-minutes</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">1</span><span class="w"></span> </pre></div> <p>The result looks something like this:</p> <p><img src="netlify-action.png" alt=""></p> <p>Now, it's much easier for me and collaborators to find the preview URL rather than dig through a bunch of logs to find it.</p> <p>When one can query the collective intellect of the whole wide world, that's an amazing feeling.</p> Publishing data with Datasette2021-04-26T00:00:00ZEric J. Maurn:uuid:d83ba4e4-e605-3666-a0a1-d1ff45ead834<p>I think the Datasette ecosystem of tools is amazing. Built basically single-handedly by Simon Willison, it provides a way to turn collections of CSV files into read-only collections of SQLite databases that one can serve on the web. Here are a few use cases of Datasette as described by Simon on the official website:</p> <ol> <li>Journalists and academics can publish the data that they use or generate onto the web.</li> <li>Web developers can stand quickly stand up a mock database for developing applications, complete with web APIs, without needing to go to more expensive solutions.</li> </ol> <p>I also remember having the pleasure of meeting Simon at PyCon 2019 while in line for food! In some sense, while I enjoy remote work, I do miss being at an in-person conference. The balance where we do remote work but getting together once in a while to do in-person events seems like the right balance for me.</p> <p><img src="meeting-simon.jpeg" alt=""></p> <h3 id="combine-multiple-data-files-into-a-single-database">Combine multiple data files into a single database</h3><p>I recently wanted to share some data from a publication that I had co-authored with colleagues. Primarily, there were two CSV files - one that was about 100MB in size and the other was 10MB in size. The flat CSVs were a tad overloaded in information, so I did a "data refactor" (a.k.a. data normalization in database terms) and pulled out some of the columns into independent CSV files as needed. (I used pandas and a Jupyter notebook to do that processing.)</p> <p>Then, I put them back into a single SQLite database using Datasette. This is where Datasette's suite of tools really shines. One CLI tool, which is called <code>csvs-to-sqlite</code>, has a wonderful command-line interface for handling this task:</p> <div class="hll"><pre><span></span>csvs-to-sqlite file1.csv file2.csv bundled_database.db </pre></div> <p>Essentially, <code>csvs-to-sqlite</code> takes as many CSV files as you want and stashes them into a single SQLite database. Doing so allows you to convert logical collections of CSV files into a single database file that is now queryable using SQL syntax. Compared to sharing a collection of CSV files that might be up to hundreds of files long, sharing a single SQLite database as a logical collection is much easier. This ability to quickly get a logical collection of data into a single data container (the SQLite database) is handy! (It's no wonder Datasette is labelled as a multi-tool, like a Swiss Army knife.</p> <h3 id="publishing">Publishing</h3><p>Publishing data is the second piece that Datasette excels in. Built-in to Datasette is a web server for browsing the contents of a SQLite database. To launch the server, you use the following command on your local machine:</p> <div class="hll"><pre><span></span>datasette serve bundled_database.db </pre></div> <p>Now, you can go to your local host on a port that <code>datasette</code> specifies for you and view it. For example, I might get port 8001, so I would go to <code></code> on my browser to view the contents of the database.</p> <p>This allows you to serve files on a local network. But what if you wanted to publish the database across the <em>whole wide world</em>?</p> <p>That's where <a href="">Datasette's dataset publishing</a> capabilities really start to shine. Datasette comes with several publishing plugins that let you deploy a Docker container housing the SQLite database onto PaaS providers such as Vercel, Heroku, and Fly. (I think AWS is also supported, but I also remember Simon ranting on Twitter about how hard some parts of AWS were.) To use the <code>datasette publish</code>, you will need to have <code>datasette</code> installed in your environment alongside one of the hosting plugins that Simon has generously built. In my case, I used the Fly plugin <code>datasette-publish-fly</code>, which one installs into the same environment as <code>datasette</code> itself. After logging into Fly's command-line interface, we then execute the following command:</p> <div class="hll"><pre><span></span>datasette publish fly bundled_database.db --app<span class="o">=</span><span class="s2">"some-nice-name"</span> </pre></div> <p>After a short while, the data will be viewable at <code>some-nice-name.fly.dev</code>!</p> <p>Now, what happens behind the scenes? Basically, <code>datasette publish</code> automates the construction of a Docker container. The first build will usually take a while, but once the build is done and the container deployed, you'll get a URL returned to you in the Terminal at which you can view the Datasette instance with your data served up. For example, check out the <a href="">Drosha data that I deployed on Fly</a>.</p> <h2 id="some-comments-on-using-datasette">Some comments on using datasette</h2><p>In using Datasette, knowing some key concepts about databases is highly recommended. These include primary keys, foreign keys, data types, and more. For example, if you have a column in your CSV files that basically acts as an indexer across multiple tables, you might want to consider extracting it to a separate lookup table using <code>csvs-to-sqlite</code>'s <code>-c/--extract-column</code> flag.</p> <p>Here's one practical consequence of doing this. Suppose you have a categorical column with repeated values. In a CSV file, that column's values are stored as a raw string over and over; multiply it by tens of thousands of rows, and you might end up with that value occupying megabytes of data. Instead of recording the raw string repeatedly, one can store an integer-to-string mapping in a separate table while recording the integer value in the original table, thus saving on storage. (Indeed, I was able to shave off about 25% of the size of the original files put together using this trick.) It goes without saying that knowing something about the relationships in your data will help a ton too.</p> Learning CSS by Styling a Resume2021-04-24T00:00:00ZEric J. Maurn:uuid:dbf2f3d1-fa49-3fd3-be73-928a04a0560c<p>Once in a while, I make it a practice to hack my <a href="">resume</a>. The goal isn't explicitly to keep it relevant, though. Instead, I use it as an excuse to practice CSS. (But then again, since I have it open anyways, I update the content along the way.)</p> <p>Since I've been on leave for a while, I decided that it was a good idea to update my resume design. The previous iteration was based on Nord, but my design choice felt a bit dark and bland simultaneously. This time around, I decided to spruce things up a bit. The result is something I'm pretty pleased with.</p> <h2 id="design-process">Design process</h2><p>To gather inspiration, I browsed several designs that were freely available online. Amongst those that I personally found aesthetically pleasing and informative, I noticed that:</p> <ol> <li>There were a lot of whitespaces. By contrast, my old resume site was visually dense.</li> <li>Prose was deployed effectively for <em>clarity</em>. By comparison, my previous resume site was a tad brief in my skills section.</li> <li>The colour scheme was well-defined with tasteful colour accents. By contrast, my old resume site was a bit overwhelmingly dark.</li> <li>Resumes that were <em>relatable</em> had a headshot of the person. For some reason, seeing a face is quite important.</li> </ol> <p>One of the designs that I saw used a left-right layout for each item in education and experience. For example, with work experience, the left third of a Bootstrap card would contain the role title, with a short description placed on that card's right side. One example I saw also included an aesthetically pleasing pine green background colour on the left third. That became one of the biggest design inspirations that I used.</p> <p>Additionally, I revisited the <a href="#">Nord theme</a> colours. I rediscovered <code>nord7</code> through to <code>nord15</code>, the non-blue/gray colours that are part of the standard palette. They were gorgeous colours! Since my resume already had sections, I decided that the colours could help visually identify each section.</p> <p>I saw two CSS features in other resumes and decided to incorporate them. They were (1) drop shadows for the cards and (2) hover scaling to give the resume a bit of additional "pop." Those turned out to be easy-to-implement yet beautiful interaction elements that I could include. Along the way, I learned about CSS transitions and scaling too.</p> <p>Finally, in all the examples that I reviewed, the ones that were the <em>cleanest</em> had no icons on the headers. Icons next to headings were something I used to have because I thought it looked cool. I was also using it to getting familiar with FontAwesome's icon sets. However, my personal aesthetic has changed now. I now think the resume looks less cluttered and much cleaner without the icons.</p> <p>Now, far from setting requirements and sprinting one-shot towards the final product, I actually iterated over a few ideas and refined them towards the final design that I settled on. Everything I wrote above is a crystallized summary of the process, which in reality, was much messier!</p> <h2 id="some-code-snippets">Some code snippets</h2><p>I wanted to highlight two technical pieces here: (1) implementing the scale transition on hover and (2) implementing cards with headers on the left and content on the right. Both of these assume some degree of familiarity with Bootstrap CSS and its card system for laying out content.</p> <h3 id="scale-transitions-in-css">Scale transitions in CSS</h3><p>The effect I was going here is to make a particular card increase in size when the user's mouse cursor hovers on top of the Bootstrap card. To do so, I wrote two CSS classes, one to control transitioning and the other to control hover on cards:</p> <div class="hll"><pre><span></span><span class="p">.</span><span class="nc">transition</span><span class="w"> </span><span class="p">{</span><span class="w"></span> <span class="w"> </span><span class="k">transition</span><span class="p">:</span><span class="w"> </span><span class="kc">all</span><span class="w"> </span><span class="mi">500</span><span class="kt">ms</span><span class="p">;</span><span class="w"></span> <span class="p">}</span><span class="w"></span> <span class="p">.</span><span class="nc">card-hover</span><span class="p">:</span><span class="nd">hover</span><span class="w"> </span><span class="p">{</span><span class="w"></span> <span class="w"> </span><span class="k">transform</span><span class="p">:</span><span class="w"> </span><span class="nb">scale</span><span class="p">(</span><span class="mf">1.05</span><span class="p">);</span><span class="w"></span> <span class="p">}</span><span class="w"></span> </pre></div> <p>I then applied the <code>.transition</code> and <code>.card-hover</code> CSS classes to every card that I wished to have hovering enabled for:</p> <div class="hll"><pre><span></span><span class="p"><</span><span class="nt">div</span> <span class="na">class</span><span class="o">=</span><span class="s">"card card-hover transition"</span><span class="p">></span> ... content goes here ... <span class="p"></</span><span class="nt">div</span><span class="p">></span> </pre></div> <p>Now, anytime someone mouses over a card with those two CSS classes applied to them, the card and all of its child elements will increase in scale to 1.05x in size.</p> <h3 id="left-right-organization-on-card-contents">Left-right organization on card contents</h3><p>To implement left-right organization on card contents, we actually nest a zero-gutter (<code>g-0</code>) row inside the card, and then use the <code>col-md-4</code> and <code>col-md-8</code> (the numbers should add to 12, ideally) classes on two divs to split the card horizontally:</p> <div class="hll"><pre><span></span><span class="p"><</span><span class="nt">div</span> <span class="na">class</span><span class="o">=</span><span class="s">"card"</span> <span class="na">id</span><span class="o">=</span><span class="s">"main-card-content"</span><span class="p">></span> <span class="p"><</span><span class="nt">div</span> <span class="na">class</span><span class="o">=</span><span class="s">"row g-0"</span> <span class="na">id</span><span class="o">=</span><span class="s">"row-placeholder"</span><span class="p">></span> <span class="p"><</span><span class="nt">div</span> <span class="na">class</span><span class="o">=</span><span class="s">"card-body col-md-4 bg-blue"</span> <span class="na">id</span><span class="o">=</span><span class="s">"left-side"</span><span class="p">></span> <span class="p"><</span><span class="nt">h2</span><span class="p">></span>Header text<span class="p"></</span><span class="nt">h2</span><span class="p">></span> <span class="p"><</span><span class="nt">small</span><span class="p">></span>Sub-text to header<span class="p"></</span><span class="nt">small</span><span class="p">></span> <span class="p"></</span><span class="nt">div</span><span class="p">></span> <span class="p"><</span><span class="nt">div</span> <span class="na">class</span><span class="o">=</span><span class="s">"card-body col-md-8"</span> <span class="na">id</span><span class="o">=</span><span class="s">"right-side"</span><span class="p">></span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>Some elaboration text goes here.<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="p"></</span><span class="nt">div</span><span class="p">></span> <span class="p"></</span><span class="nt">div</span><span class="p">></span> <span class="p"></</span><span class="nt">div</span><span class="p">></span> </pre></div> <p>To implement colours, I used the Nord CSS variables in my custom CSS class definitions. For example, you'll notice the <code>.bg-blue</code> class definition used in the left side of the card:</p> <div class="hll"><pre><span></span><span class="p">@</span><span class="k">import</span><span class="w"> </span><span class="s2">"nord.css"</span><span class="p">;</span><span class="w"></span> <span class="p">.</span><span class="nc">bg-blue</span><span class="w"> </span><span class="p">{</span><span class="w"></span> <span class="w"> </span><span class="k">background-color</span><span class="p">:</span><span class="w"> </span><span class="nf">var</span><span class="p">(</span><span class="nv">--nord8</span><span class="p">);</span><span class="w"></span> <span class="p">}</span><span class="w"></span> </pre></div> <p>Now, the left side of the card will have a blue background.</p> <h2 id="screenshot">Screenshot</h2><p>Having described the design process and outcomes, here's <a href="">a link to the final product</a>.</p> <p>And here's a full screenshot of the page in case you're feeling lazy :).</p> <p><img src="resume.png" alt=""></p> <h2 id="lessons-learned">Lessons Learned</h2><p>This was a fantastic exercise, crafting a personal resume to my liking. In particular, I enjoyed discovering new things about CSS that I didn't know before. I also enjoyed bringing some pop and colour into my resume.</p> <p>Having previously structured my resume in a pretty sane YAML format made it much easier for me to change what I thought needed reworking. Since a resume is primarily composed of data, this reinforced for me that storing data in a sane data structure is supremely important. Counterfactually, if my resume were entangled with the HTML by being written directly in HTML, I'd lose the flexibility to rework isolated parts of the system.</p> <p>Finally, this exercise reinforced for me that <em>art is a beautiful medium for learning tech</em>. Styling a resume is nothing critical. But treating the act of styling the resume as an art project means there is a creative outlet for anything technical to learn. The resume, I think, is a particularly excellent win-win outlet. Because it's highly <em>personalized</em>, you can flex your design and creativity muscles. Simultaneously, because it is highly <em>useful</em>, you'll effectively be investing in your career development anyways.</p> Grammatically composing network visualizations2021-04-02T00:00:00ZEric J. Maurn:uuid:6f7bed9e-d95a-3ff4-a2aa-ad6ec70e7995<p>This past month, I've been revamping the <code>nxviz</code> package, a package I created in graduate school to build network visualizations on top of NetworkX and Matplotlib. (You can see the work being done in <a href="">this PR branch</a>!)</p> <p>It's been a bit neglected! The biggest reason, I think, is the lack of a <em>grammar</em> for composing network visualizations, which then leads to hairball being created. Sometimes the hairballs are beautiful; most of the time they are uninformative. Flowing from a lack of grammar means the architecture of the codebase is also a bit messy, with one example being annotations being too tightly coupled to a particular plot object.</p> <h2 id="network-visualization-workflow">Network visualization workflow</h2><p>To revamp the <code>nxviz</code> API, I started by structuring the API around the following workflow for constructing graph visualizations. As such, I decided to refactor the API, structuring it around what I know about the grammar of graphics.</p> <p>Firstly, because the core idea of <code>nxviz</code> is <em>rational graph visualizations</em> that prioritize node placements, the refactor started there, with node layout algorithms that group and sort nodes according to their properties.</p> <p>Once we have node <em>placement</em> figured out, we can now proceed to node <em>styling</em>. Mapping data to aesthetic properties of glyphs is a core activity in data visualization; in <code>nxviz</code>, the styling that can be controlled by data are the node size (radius), color, and transparency.</p> <p>Following that, we need algorithms for drawing edges. Do we simply draw lines? Or do we draw Bezier curves instead? If we draw curves, what are the anchor points that we need? Sane defaults are provided for each of the plot families in <code>nxviz</code>.</p> <p>As with nodes, we then add in aesthetic styling that are mapped to a given edge's metadata. In <code>nxviz</code>, the edge styling that can be controlled by data are their line width, color, and transparency.</p> <p>We then add in annotations onto the graph. Are there <em>groups</em> of nodes? If so, for each node layout type, we can add in group annotations in sane locations. Are colors mapped to a quantitative or qualitative variable? Legends or color bars can be annotated easily.</p> <p>Finally, in some cases, it may be helpful to highlight a node, a particular edge, or edges attached to a node; we might use such highlights in a presentation, for example. The final part of the refactor was to add in functions for adding in each of these highlights in an easy fashion.</p> <p>Summarized, the flow looks something like this:</p> <ol> <li>Layout nodes.</li> <li>Style nodes according to node properties.</li> <li>Connect nodes by drawing in edges.</li> <li>Style edges according to edge properties.</li> <li>Annotate visualization with auxiliary information.</li> <li>Add highlights.</li> </ol> <h2 id="handling-node-layouts-with-cloned-node-axes">Handling node layouts with cloned node axes</h2><p>Some node layouts involve <em>cloning</em> the axis on which the nodes live. Examples of this include the matrix plot, in which we lay out the nodes on the x-axis, and then clone them onto the y-axis, canonically in the exact same order (though not always). These were much easier to write once the components underneath were laid out in a sane fashion.</p> <h2 id="supporting-data-structures">Supporting data structures</h2><p>Some data structures were immensely important in the API redesign, and turned out to be foundational for almost everything.</p> <p>Every graph's node set can be represented as a data table. In the node table, nodes are the index, while the metadata are the columns. In the edge table, two special columns, <code>source</code> and <code>target</code>, indicate the nodes between which an edge exists, and the rest of the columns are the metadata.</p> <p>A node position dictionary that maps node ID to (x, y) coordinates was also something extremely important. This is calculated by the node layout algorithm and used by the edge drawing algorithms and elsewhere in the library. Worrying about the positions of nodes is a page taken out of NetworkX's drawing functionality directly, and I have to give the developers much of the credit for that.</p> <p>The global stateful nature of Matplotlib turned out to be a blessing in disguise. Rather than having a user pass around an axes object all of the time, in <code>nxviz</code> we simply assume that there is a globally available axes object.</p> <h2 id="optimizing-for-composability-and-workflow">Optimizing for composability and workflow</h2><p>In redesigning the <code>nxviz</code> API, I wanted to make sure that the <em>workflow</em> of creating a network visualization, done in a <em>principled fashion</em>, was something that the API would support properly. As such, the API is organized basically around the workflow described above. A lesson I learn over and over in writing software is that once the workflow is clear, the API that's needed to support it also becomes quite clear. And when does the workflow become clear? Usually, that clarity comes when the important logical steps that are composable with one another are well-defined, and the core data structures that support that workflow are present.</p> <h2 id="bringing-a-grammar-to-network-visualization">Bringing a grammar to network visualization</h2><p>The Grammar of Graphics, <code>ggplot</code>, Seaborn, Altair, and Holoviews were all inspirations for nxviz's functional and declarative API. Network visualization appears to be an under-developed area of the data visualization ecosystem, and I'm hoping that this grammar of network visualization helps bring clarity!</p> <h2 id="with-thanks">With thanks</h2><p>I wanted to give a heartfelt shoutout to my Patreon and GitHub supporters, Hector, Carol, Brian, Fazal, Eddie, Rafael, and Mridul, who all have had an early preview of how the new <code>nxviz</code> API.</p> Phony targets in Makefiles2021-03-04T00:00:00ZEric J. Maurn:uuid:e14ecbd9-96f2-3451-88ef-8c72ea2fe3a5<p>Makefiles can be used to create a lightweight CLI entry point for your project. By writing a <code>Makefile</code>, you can automate repetitive shell commands, such as building a Dockerfile (which might require you to remember certain incantations):</p> <div class="hll"><pre><span></span><span class="nf">.PHONY</span><span class="o">:</span> <span class="n">container</span> <span class="nf">container</span><span class="o">:</span> docker build -t mycontainer -f Dockerfile . </pre></div> <p>Doing so allows us to build a Docker container using the command <code>make container</code> when at the command line.</p> <p>Now, you'll probably notice the <code>.PHONY</code> line at the top. What's that all about?</p> <p>By convention, the command <code>container</code> would have referred to a file target on disk. (This is how Makefiles were originally designed.) However, if we want the command to be independent of any files on disk, we declare it to be a <em>phony</em> target that doesn't actually exist on disk.</p> Machine learning system design2021-03-01T00:00:00ZEric J. Maurn:uuid:a19b2005-e778-3dbc-88cd-0a8454778204<p>I think we're past the age of building fancy models. After about a decade or so of seeing where models could make an impact on decisions being made, I think we're entering a phase where operationalizing these models is more important than building bigger and more powerful models. The field of data science is evolving yet again, this time with a big offshoot branch with the name "Machine Learning Engineering".</p> <p>The key problem here is that most data scientists don't possess the software <em>and</em> engineering skills to build and operationalize machine learning systems for colleagues. There's a big opportunity here to make machine learning systems work. The key here is to design machine learning systems the way software engineers design software systems: modular, with clean contracts, minimizing entanglement, etc. etc.</p> <p>There are very few resources that I know of that can help us learn what needs to be done, but here are a few that I have encountered.</p> <ol> <li><a href="">Machine Learning Systems Design</a> by Chip Huyen.</li> <li><a href="">Machine Learning Engineering</a> by Andriy Burkov</li> <li><a href="">MLOps</a> by @visenger</li> </ol> Configure tmux and zsh to play nicely2021-02-28T00:00:00ZEric J. Maurn:uuid:67493255-07f2-3df5-9026-178e86020325<p>I have been encountering this problem where <code>tmux</code> reloads my PATH environment variable incorrectly. As it turns out, the fix is documented in <a href="">a StackOverflow post</a>.</p> <p>The crux of the problem is as follows: When <code>tmux</code> loads, my <code>.zshrc</code> is re-evaluated. By setting the following line in my <code>.tmux.conf</code> configuration file:</p> <pre><code>set -g default-command /bin/zsh </code></pre> <p>I can now prevent <code>zsh</code> from being instantiated as a login shell.</p> <p>(If you're now wondering what in the world is a "login shell", fret not, I had to search online too. Here's the best answer I found, this time on <a href="">StackExchange</a>.)</p> Experience with M1 MacBook Air2021-01-27T00:00:00ZEric J. Maurn:uuid:c01248b2-ee1f-3660-9f24-3ef142eb332f<p>Though I've been a Mac user for close to 15 years now, it's the first time that I've had to experience an architecture change. Having upgraded from an old 12" MacBook to a new 13" MacBook Air, I wanted to quickly document some of my early experiences with the M1 MacBook Air.</p> <h2 id="initial-ordering">Initial Ordering</h2><p>The online shopping experience is something that I have to mention and give full credit to Apple. They've enabled customers to order a MacBook Air at noon and get it by 2:30 pm, at least in the Boston area. I think this was possible because the model I ordered, a 16GB RAM + 1TB SSD MacBook Air, was available and in-stock in their South Shore store. Good move, Apple; I was pleasantly delighted at being able to make this purchase. (Hopefully, I get a good four years of use out of it, as I did for my little MacBook!)</p> <h2 id="installing-tooling">Installing tooling</h2><p>My tools primarily involve the following:</p> <ol> <li>Homebrew for system-wide packages.</li> <li>Anaconda for the Python data science stack.</li> <li>VSCode for software development.</li> <li>Jupyter for notebook experimentation.</li> </ol> <p>I started by installing as much as I could of my stack under native (ARM) mode rather than emulated (x86) mode. Here's my report on what worked and what didn't.</p> <h3 id="homebrew">Homebrew</h3><p>As of 26 Jan 2021, Homebrew has partial support for the M1 ARM processors. Installing Homebrew was not difficult. Open up the <em>native</em> Terminal, type in the official Homebrew installation commands, and see it go to work. No problems encountered.</p> <p>As an experiment, I removed the ARM-compatible Homebrew installation and re-installed it in emulation mode. To do this, I opened up the Hyper terminal, which was not ported over to M1 yet, and ran the official Homebrew installation commands. Likewise, I encountered no problems. As I have been a bit lazy, I did not revert to ARM Homebrew.</p> <p>ARM Homebrew and x86 Homebrew get installed into two different directories. The ARM <code>brew</code> goes into <code>/opt/homebrew/bin</code>, while the x86 version goes into the usual <code>/usr/local/bin</code>. Just keep this point in mind; you might find it handy in the future.</p> <h3 id="anaconda">Anaconda</h3><p>Following the <a href="">best practices I outline in my knowledge base</a>, I install Miniconda on my machine. After reading some blog posts online, I discovered that there's <a href="">miniforge</a>, a Miniconda distribution that comes with native ARM compatibility. As such, I started by installing that first.</p> <p>Soon, however, I found that there were some environments that I couldn't build. These included <a href="">the one for this website</a>, and anything involving JAX. Initially, I considered living with the situation and using a remote development machine, but I soon felt that nagging feeling that I was leaving a lot of awesome compute on the table by doing that. As such, I uninstalled Miniforge and installed Miniconda in emulation mode. As with Homebrew, I got Miniconda going by running the installer inside Hyper. After the installation was complete, I could build all of my conda environments with ease.</p> <p>Having installed Miniconda, I went to work benchmarking a test suite for <a href=""><code>jax-unirep</code></a>, an RNN model that my intern Arkadij and I accelerated together. One of my projects uses JAX, which I could not install in native ARM mode. The exciting thing for me is that I saw the test suite run with no issues! Also, I noticed that the slow tests ran at approximately twice as fast on my computer than on GitHub Actions. This anecdotal benchmark is enough for me to gain confidence in using JAX on this laptop. If you want numbers, though:</p> <ul> <li>GitHub Actions for jax-unirep tests:<ul> <li>45 seconds for fast test</li> <li>3m 35 seconds for slow tests</li> </ul> </li> <li>M1 MacBook air (while running on battery power in emulation mode)<ul> <li>43 seconds for fast test</li> <li>1m 25 seconds for slow tests</li> </ul> </li> </ul> <h3 id="docker">Docker</h3><p>Docker has a technical preview for the M1 Mac, and it has only crashed once thus far. (I didn't have enough time to dig deep and figure out why.) Other than that, I was able to install the tech preview with no hassle and even use it to build a development container in VSCode for <code>pyjanitor</code>, in which I made a few pull requests into the library.</p> <h3 id="vscode">VSCode</h3><p>To get VSCode, I had to install and use the <a href="">Insiders build for ARM64</a>. No big hiccups here, everything installed without issues. As I mentioned above, building development containers involved zero hiccups.</p> <h3 id="jupyter">Jupyter</h3><p>The Jupyter notebook server ran in x86 emulation mode with no issues as well. I installed the latest jupyter lab 3.0.5, which ran with no hiccups, was snappy in the browser, everything behaving in line with what I was accustomed to.</p> <h3 id="julia-language">Julia Language</h3><p>I also went ahead and installed Julia both from conda-forge (it is a bit dated, at v1.1.1) and from the official Julia language website. Installation went smooth; running had no hiccups.</p> <h2 id="overall-two-day-impressions">Overall two-day impressions</h2><p>As someone who's used a Mac exclusively since 2006, <em>nothing substantial</em> has changed on the surface. That's something worth mentioning: Apple does it again, making a technically complicated technological transition without letting an end-user know as much. Doing this is insanely remarkable! I've done calls, written emails, this blog post, done software development and ML model fitting with gradient descent, all on a lightweight but powerful machine that sips very little power. I'm wholly impressed here.</p> <p>The conda-forge community of volunteers has done just as much too. I'm wholly impressed by the speed at which the team could get their bots to town, cross-compiling the ecosystem's packages.</p> <p>I know I'm leaving some performance on the table by sticking with x86 emulation at the moment. Nonetheless, I still can't help but remark that the performance is insanely great! I was quite pleasantly surprised at how smoothly everything runs. Compared to the Intel m5 processor in my old 12" MacBook, the M1 chip runs fast, <em>even in emulation mode</em>.</p> <h2 id="tips-for-data-science-usage">Tips for data science usage</h2><p>These tips are valid as of 26 Jan 2021. Here are some things that I suggest you might want to do if you want stuff to "just work":</p> <ol> <li>Don't bother with emulation mode for the Python DS/software/web development stack. Install Miniconda in emulation mode and be done with it.</li> <li>Same goes for Homebrew.</li> <li>Install VSCode Insiders for ARM64; you'll enjoy the speed at which everything runs.</li> <li>Install Docker's technical preview for M1 if you need to use Docker.</li> </ol> <p>If you do the above, keep your eyes peeled for community movement on ARM64 compatibility, and don't hesitate to re-install things.</p> <h2 id="limitations-encountered">Limitations encountered</h2><p>From my perspective, these are the current limitations I see:</p> <ol> <li>JAX, being built on top of XLA, is not yet natively compatible with the M1 Mac's GPU. Some movement is probably necessary from the XLA team to make it happen. <a href="">There is an issue tracker I filed with the JAX team</a>, in which Metal bindings are necessary. Targeting compilation to the Neural Engine will be difficult because there are no public APIs for that, as far as I can tell.</li> </ol> <h2 id="references">References</h2><p>I used the following references in getting set up:</p> <ol> <li><a href="">A comment by Chris Fonnesbeck on PyMC3's issue tracker</a>.</li> <li><a href="">A question on Stack Overflow</a>.</li> <li><a href="">A slightly dated Medium post on How to run Jupyter notebooks on your Mac</a>.</li> </ol> Dispatch rather than check types2021-01-24T00:00:00ZEric J. Maurn:uuid:605fc2e1-3426-32da-867a-9ae833b9ec88<p>I finally grokked an old thing!</p> <p>The thing I've been trying to understand properly is "how and when to do single/multiple dispatching". It's an idea that is heavily baked into the Julia programming language, and one for which I rarely see the pattern being used in Python. But after reading <a href="">Michael Chow's blog post on single dispatching</a>, I finally realized how dispatching gets used. Let me explain with an example.</p> <p>Let's say you have a function that can process one column or multiple columns of the a dataframe. As a first pass, you might write it as follows:</p> <div class="hll"><pre><span></span><span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span> <span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Union</span><span class="p">,</span> <span class="n">List</span><span class="p">,</span> <span class="n">Tuple</span> <span class="k">def</span> <span class="nf">my_func</span><span class="p">(</span><span class="n">df</span><span class="p">:</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">,</span> <span class="n">column_names</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">List</span><span class="p">,</span> <span class="n">Tuple</span><span class="p">,</span> <span class="nb">str</span><span class="p">]):</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">column_names</span><span class="p">,</span> <span class="p">(</span><span class="nb">list</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">)):</span> <span class="k">for</span> <span class="n">column</span> <span class="ow">in</span> <span class="n">column_names</span><span class="p">:</span> <span class="c1"># something happens.</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">column_names</span><span class="p">,</span> <span class="nb">str</span><span class="p">):</span> <span class="c1"># something happens.</span> <span class="k">return</span> <span class="n">df</span> </pre></div> <p>Here are the problems I see:</p> <ol> <li>Notice how nested that function <code>my_func</code> is. It definitely goes against the Zen of Python's recommendation that "flat is better than nested".</li> <li>At the same time, the function silently fails for data types that are not explicitly supported -- also an anti-pattern that should not be encouraged.</li> </ol> <p>Here's the same function written instead as two functions that share the same name, leveraging the <a href="">multipledispatch package by Matt Rocklin</a>:</p> <div class="hll"><pre><span></span><span class="kn">from</span> <span class="nn">multipledispatch</span> <span class="kn">import</span> <span class="n">dispatch</span> <span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span> <span class="nd">@dispatch</span><span class="p">(</span><span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span> <span class="k">def</span> <span class="nf">my_func</span><span class="p">(</span><span class="n">df</span><span class="p">,</span> <span class="n">column_names</span><span class="p">):</span> <span class="c1"># do str-specific behaviour</span> <span class="k">return</span> <span class="n">df</span> <span class="nd">@dispatch</span><span class="p">(</span><span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">,</span> <span class="p">(</span><span class="n">List</span><span class="p">,</span> <span class="n">Tuple</span><span class="p">))</span> <span class="k">def</span> <span class="nf">my_func</span><span class="p">(</span><span class="n">df</span><span class="p">,</span> <span class="n">column_names</span><span class="p">):</span> <span class="k">for</span> <span class="n">column</span> <span class="ow">in</span> <span class="n">column_names</span><span class="p">:</span> <span class="c1"># do stuff</span> <span class="k">return</span> <span class="n">df</span> </pre></div> <p>Notice how now each function is:</p> <ol> <li>Flatter</li> <li>Self-documented because of the type annotations used as part of the <code>dispatch</code> call.</li> <li>Easier to see when the function will fail.</li> </ol> <p>The only downside I can think of to the "dispatch" programming pattern is that one must know the concept of "dispatching" before one can understand the <code>@dispatch</code> syntax. The one who is unfamiliar with this concept might also be thrown off by declaring the same function twice. That said, I think the benefits here are immense though!</p> Libro.fm: DRM-free Audiobooks2020-12-27T00:00:00ZEric J. Maurn:uuid:b1d22181-f7b9-3501-94a6-f75249e4ec38<p>As COVID-19 raged on, I decided it was time to pick up the habit of listening to Audiobooks. There were convergent factors that helped me make this decision.</p> <p>Firstly, many hours of holding a child get boring if the child is sleeping. Audiobooks help do the job of alleviating boredom, as it means I can learn hands-free.</p> <p>Secondly, the company I work for has a benefit that let me test-drive audiobooks via Audible.com. I went crazy and downloaded 5 audiobooks into my Audible catalogue (that was the limit per month, I think, but I'm not quite sure). The book "How will you measure your life", by Harvard Business School professor Clayton Christensen, was such a wonderful audiobook to listen to that I was hooked.</p> <p>Thirdly, I have known for a long time that my first exposure to ideas is best done audibly, with hands-on experience and text <em>reinforcing</em> what I have heard. If I were to start engaging with ideas in text form first, then I would end up getting lost pretty quickly.</p> <p>Since audiobooks get the job of "entertaining and teaching while hands-free" done, I decided to take the plunge.</p> <h2 id="deciding-on-libro-fm-over-audible">Deciding on Libro.fm over Audible</h2><p>I started out with Audible because it is part of the benefits package that my company, Novartis, offers to its employees. However, I very quickly became dissatisfied with the offering. In particular, I was acutely aware of the lock-in I was buying into by going with Audible. And being an open-source developer and data scientist, I have this heightened "lock-in" radar (much as some individuals I know have heightened "BS" radar) that I actively try to avoid. Audible reeked of lock-in, so I went on the search for a different audiobook provider.</p> <p>That is where Libro.fm comes in. It has a comparably large library of audiobooks, and the authors whose works I was most interested in hearing were all available up there. The parts of their service that caught my eye the most though were two-fold:</p> <ol> <li>All of their audiobooks are DRM-free. This means I can download the MP3 version for myself and keep it for as long as I remember it's there.</li> <li>They support local bookstores through their sales. (I chose a bookstore in Porter Square, in Cambridge.)</li> </ol> <p>So rather than line the pockets of executives at Amazon, I decided to support local bookstores through my purchases. It felt like the right thing to do overall.</p> <p>Other than that, their app is well-designed and easy to use. I'm a tad miffed that the two books I have chapters named "Track 1", "Track 2" etc. instead of the chapter names, but that's a minor thing that I will be giving them feedback on.</p> Moving my CI pipelines to GitHub Actions2020-12-24T00:00:00ZEric J. Maurn:uuid:56d787e6-d8a9-3c3a-8490-ff9eaaabe372<p>Today, I began the long-awaited migration of my CI pipelines off from Travis CI and on to GitHub Actions. I started with my <a href="">Network Analysis Made Simple tutorial repository</a> as my test-bed, for the following reasons:</p> <ol> <li>It has a sufficiently complex workflow for which parts can be parallelized.</li> <li>It is something I have been actively curating and developing, so I am familiar with what I need in this CI pipeline.</li> <li>I strive actively to apply "good software practices" to that repository, and it has a good starting point.</li> </ol> <p>In this blog post, I'm going to document what I did and why, as well as lessons learned from migrating a CI pipeline off one provider onto another.</p> <h2 id="engineering-the-pipeline-for-modularity">Engineering the pipeline for modularity</h2><p>The biggest architectural change I did here was to split up my build pipelines into logical "jobs". I defined three logical stages:</p> <ol> <li>Building the environment</li> <li>Building the website (which requires the built environment)</li> <li>Building the LeanPub book (which also requires the built environment)</li> </ol> <p>Building the environment takes approximately 3-6 minutes (depending on the performance of the machine that runs the install steps).</p> <p>Building the website requires executing all of the notebooks from top to bottom. In authoring the notebooks, I try my best to ensure that they can be executed without errors <em>in under 15 seconds</em>, though 1 minute is the upper-bound acceptable. MkDocs is the site building engine, while <code>mknotebooks</code> gives me the ability to execute the notebooks as part of the build. (A little interjection here: I also put in a PR to <code>mknotebooks</code> to enable insertion of a Binder link at the top of a notebook, so that readers can directly open a Binder session with the notebook!) The site that gets built is then force-pushed into the <code>gh-pages</code> branch of the repository. In total, this step takes about 5-7 minutes.</p> <p <code>leanpub</code> branch of the repository, and I do a curl call to the LeanPub API to trigger a new build of the book. In total, this step takes about 5-7 minutes as well.</p> <h2 id="experimenting-with-parallel-builds">Experimenting with parallel builds</h2><p>Building the website and LeanPub book can run in parallel as soon as the environment is built. Hence, I took advantage of this fact on GitHub Actions, which:</p> <ol> <li>Allows me to specify which jobs depend on each other, and</li> <li>Automatically runs builds in parallel.</li> </ol> <p>I could write the pipeline such that it would build the environment once, package it up as an artifact, and re-use the environment in both of the downstream steps, thus allowing me to parallelize the two steps.</p> <h2 id="engineering-the-pipeline-to-be-modular">Engineering the pipeline to be modular</h2><p.</p> <p>To start, I made the build steps into individual bash scripts that are stored in the <code>scripts/ci/</code> directory. The scripts stored here are, in order of operation:</p> <ol> <li><code>build_environment.sh</code>: used to build the <code>conda</code> environment for the tutorial, and package it up using <code>conda-pack</code>.</li> <li><code>build_leanpub.sh</code>: used to build the source files that power the LeanPub book.</li> <li><code>build_website.sh</code>: used to build the files that are hosted on GitHub Pages.</li> </ol> <p>In terms of workflow, the order of operations is:</p> <pre><code>build_environment.sh -> build_leanpub.sh -> build_website.sh </code></pre> <p>In GitHub Actions, I structured the pipelines as different "jobs". Because user <code>@s-weigand</code> has a <a href=""><code>setup-conda@v1</code> action available</a>, I can skip over the <code>install_anaconda.sh</code> step, and leverage what he has instead. After building the environment with <code>build_environment.sh</code>, which includes a <code>conda-pack</code> step to build a tarball with the environment packaged up, I used the <a href=""><code>actions/upload-artifact@v2</code> action</a> to take the built tarball and upload it as an artifact of the build. This allowed me to share the built environment between the job that builds the environment and the jobs that builds+deploys the website and book.</p> <p>The two deployment steps were quite similar, with the only difference being the build script that is called. Otherwise, before the build script, I would use the <a href=""><code>actions/download-artifact@v2</code> action</a> to download the built artifact from the previous job, and execute their respectively configured <a href=""><code>peaceiris/actions-gh-pages@v3</code> actions</a> to deploy the websites. On the LeanPub push, I would also execute a <code>curl</code> command to a web API (available only to Pro users, which I gladly paid for) to trigger the publishing of a new version.</p> <p>Finally, I wanted to make sure that my code adhered to <code>black</code> code standards. As such, I made an extra job that runs independently, in which I install a lightweight Python environment which I use to run code checks against the codebase.</p> <p.</p> <h2 id="leveraging-bash-hacks-to-help-with-conda-environment-activation">Leveraging bash hacks to help with conda environment activation</h2><p>Because conda activation can behave a bit non-uniformly, I had to resort to a little bash hack that allowed me to execute the environment activation uniformly. The specific line I used was:</p> <div class="hll"><pre><span></span><span class="nb">source</span> nams_env/bin/activate <span class="o">||</span> conda activate nams <span class="o">||</span> <span class="nb">source</span> activate nams </pre></div> <p>These are three ways to activate an environment. The first activates a <code>conda-pack</code>ed environment; the second way is the modern way, while the third way is the legacy way. I layered them this order just in case one of them failed.</p> <h2 id="leveraging-caches-to-speed-up-build-times">Leveraging caches to speed up build times</h2><p.</p> <p>For building the environment, if none of <code>environment.yml</code> and <code>build_environment.sh</code> changed, then the CI system would use the cached version of the gzipped environment.</p> <p.</p> <h2 id="view-the-source-files-for-my-pipelines">View the source files for my pipelines</h2><p>If you're interested in studying my pipelines, you can find them on <a href="">the GitHub repository</a>. In particular, you'll want to view:</p> <ul> <li><a href="">the GitHub actions config file</a></li> <li><a href="">the collection of shell scripts</a></li> </ul> <h2 id="building-ci-pipelines-still-takes-skill-and-time">Building CI pipelines still takes skill and time</h2><p: <em>the ability to construct an accurate mental picture of the current state of the filesystem and runtime environment variables that are active and available</em>. If you can do this, you can build CI pipelines and debug them faster than others can.</p> :</p> <ol> <li>differ from provider to provider,</li> <li>we need to be absolutely clear about,</li> <li>require browsing documentation to figure out.</li> </ol> <p>For those reasons, building pipelines still takes about a day or so of time investment, maybe less if you're seasoned and know the idioms well enough. Yes, at its core, pipeline building is really nothing more than shuffling files around and executing them, but knowing <em>how</em> they get shuffled around and <em>why</em>.</p> <h2 id="what-are-your-thoughts-on-github-actions">What are your thoughts on GitHub Actions?</h2><p>Firstly, I think GitHub Actions is really awesome because of its unlimited <em>parallel</em> builds for open source projects. With this, I can keep the continuous integration systems running on my OSS projects in a time-effective (and definitely cost-effective) fashion.</p> <p...)</p> <p>Finally, nothing really beats the graph view! Take a look at it below.</p> <p><img src="github-actions-graph-view.png" alt=""></p> <p>It's gorgeous and helps me visually see the status of the pipeline.</p> <p!</p> Graphs, language, and categories2020-12-18T00:00:00ZEric J. Maurn:uuid:f88b3528-66aa-3d78-9de9-7b6826925380<p>Just as I began vacation, my brain started going into overdrive. (This is a quirk of my head.) One of the epiphanies I arrived at involved graphs, programming languages, and categories.</p> <h2 id="let-s-talk-about-multiple-dispatch">Let's talk about multiple dispatch</h2><p>Multiple dispatch is a programming construct. It essentially allows us to write functions that:</p> <ol> <li>Share the same name, but</li> <li>Exhibit different behaviour based on the <em>types</em> of the arguments passed in.</li> </ol> <p>This idea is baked into the Julia programming language and is part of what makes Julia so composable. Python programmers don't have this luxury, partially because multiple dispatch isn't part of the language design and partially because of namespaces. That said, Matt Rocklin and a few others maintain the <a href=""><code>multipledispatch</code></a> Python package, which implements multiple dispatch in a pretty sane fashion. To borrow the example from the package, we might design a function called <code>add</code>, but need it to operate differently depending on whether we put in integers or Python objects:</p> <div class="hll"><pre><span></span><span class="nd">@dispatch</span><span class="p">(</span><span class="nb">int</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span> <span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span> <span class="sd">"""Adds two numbers together."""</span> <span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="nd">@dispatch</span><span class="p">(</span><span class="nb">object</span><span class="p">,</span> <span class="nb">object</span><span class="p">)</span> <span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span> <span class="sd">"""Performs a concatenation between two strings."""</span> <span class="k">return</span> <span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="n">a</span><span class="si">}{</span><span class="n">b</span><span class="si">}</span><span class="s2">"</span> </pre></div> <p>Is this a good idea? I used to wonder when I'd know enough to answer the question. I think I do now. But first, we have to take a detour to graphs.</p> <h2 id="let-s-talk-about-graphs">Let's talk about graphs</h2><p>Graphs are a data structure that allows us to model entities and their relationships. Entities are nodes, while relationships are edges. I usually teach a tutorial at PyCon, SciPy and ODSC titled "<a href="">Network Analysis Made Simple</a>", in which we use <a href="">NetworkX</a> as a tool to learn applied graph theory. It's been running since 2014, and I've learned a lot, made a lot of friends, and had new opportunities spring up through teaching it.</p> <p>As a data model, graphs are handy for reasoning because for our logic to make sense, we must be extremely clear on our definitions. What exactly constitutes a node? What exactly constitutes a relationship? What connections are allowed to exist between nodes (or, surprise! <em>categories</em> of nodes)? These answers must be precise.</p> <p>This then brings us to categories.</p> <h2 id="let-s-talk-about-categories">Let's talk about categories</h2><p>I think it was from <a href="">Eric Schles</a> that I learned that there was this entire field of mathematics called "category theory". (This was likely ODSC 2017, while both of us were chatting in the speaker's lounge.) Also, I started reading the blog of <a href="">Tai Danae-Bradley</a>, who trained as a category theorist at NYU and even has a book on it. From <a href="">one of her excellent blog posts</a>, I learned the core of category theory is about: "...collections of objects that can relate to each other via morphisms..."</p> <p>Sounds familiar... it sounds like a graph!</p> <h2 id="so-what-about-multiple-dispatch">So... what about multiple dispatch?</h2><p>If you stepped back one moment and looked carefully at the <code>add</code> example, you'll notice that we have a microcosm of category theory being brought to life in a programming language.</p> <p>There's a category of objects called <em>objects</em>, and there's a (sub-)category of objects called <em>integers</em>. There are relations between integers called <em>add</em>, and a similar relation between objects, also called <em>add</em>. Both have a relationship named <em>add</em>, but each <em>add</em> differs because the "integers" case is a particular case that needs to be handled differently from the "objects" case.</p> <p>You could construct a graph to represent it all, one that looks like this:</p> <div class="hll"><pre><span></span><span class="p">(</span><span class="nb">int</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span> <span class="o">--</span><span class="n">add</span><span class="o">--></span> <span class="nb">int</span> <span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">obj</span><span class="p">)</span> <span class="o">--</span><span class="n">add</span><span class="o">--></span> <span class="nb">str</span> </pre></div> <p>If we think about it carefully, because integers are a sub-category of objects, the second case <code>(obj, obj)</code> covers the child cross-type cases.</p> <p>So what gives, what's the epiphany?</p> <p><em>Multiple dispatch works because linguistically, we might need to reuse the same category of relations, as indicated by their shared name, for different object categories, for no other reason than doing so is the semantically correct thing to do for our problem.</em> And doing so allows us to leverage composition to write cleaner and interoperable programs.</p> Building a personal knowledge graph on Obsidian2020-12-15T00:00:00ZEric J. Maurn:uuid:b7737054-653e-3252-8aa1-50c381409f39<p>Amidst COVID-19, I decided to take a break from work. I was definitely in need of a bit of personal rejuvenation after hitting hard on the accelerator at work, mostly to get things wrapped up before our first baby girl was born. During this personal rejuvenation time, I stumbled upon <a href="">Andy Matuschak's notes</a>, which are famous amongst the "personal knowledge management" community.</p> <p>At the same time, I also saw the rise of <a href="">Roam Research</a> and <a href="">Obsidian</a>, and I was looking with envious eyes at those who had early access to Roam. I was a bit turned off by the subscription and lock-in that characterized Roam and was much more attracted to the Freemium + "respect your data rights" model embraced by Obsidian, so I dipped my toes in. The result is this learning journey building my own "personal knowledge management" system from which I've never turned back.</p> <p>Let me explain.</p> <p>For a long time, I've known that the way that I think is in a "linked" fashion. I rarely entertain a thought on its own in isolation. Instead, I will jump and hop from one idea to another in my brain. Sometimes, I joke with others that my mind is effectively a random graph: nodes are ideas, and edges are relationships between them. The unfortunate thing is that I don't have the right tools for externalizing the relationships that I uncover. As a practicing data scientist, as I continuously learn and discover new model classes that may be useful in my projects, I also see connections between models, their components, and their applications.</p> <p>My previous notetaking tool, Evernote, is better described as an archival tool. In there, I would dump and collect everything and anything that I thought might be of marginal value. After all, Evernote's mantra is to help us store everything and make it searchable to us. It's a great tool, and I still use it in that fashion. However, using it as a tool for developing and understanding ideas is a bit like treating a flea market as a museum. Yes, it's a collection of items, but a flea market has everything and anything in there, while a museum is intentionally curated. Intentional curation is the key to internalizing insights from the external knowledge we gain.</p> <p>All of those points above brings us to the problem of tooling. Evernote is a tool for collection, not curation and linking. Tools that help us actively curate a concrete representation of an idea -- a note -- and help us link them together will also help us intentionally curate these ideas together. Obsidian gives us the necessary tooling to be such a curator.</p> <h2 id="how-obsidian-helps">How Obsidian Helps</h2><p>There are at least three features of Obsidian that help with this.</p> <h3 id="markdown-files">Markdown files</h3><p>Firstly, Obsidian treats individual notes, implemented as Markdown files, as the unit on which linking happens. When you want to create a wiki-style link to another page, you use a double square bracket (<code>[[...]]</code>) and start typing the name of the note that you want to link. A pop-up display will show the note titles, which can help you if you have a fuzzy or approximate notion of the idea you're trying to link. If you use "imperative tone" ideas to name your note files, then linking becomes <em>even more</em> natural.</p> <h3 id="graph-view">Graph view</h3><p>Secondly, Obsidian has a graph view. This graph view is nothing more than a node-link diagram, likely implemented using <code>d3.js</code>, with note titles overlaid. Yes, it is fascinating to explore our ideas' connected structure, but the more significant value proposition is quickly identifying every note file that exists as an unlinked singleton. Why? Because one of the goals of linked notetaking is to search for linkable ideas and then explicitly connect them. The visual graph view also helps me surf through concepts; each time I trace a path between the thoughts I've recorded down, I reinforce the link in my unreliable internal store.</p> <h3 id="random-notes">Random notes</h3><p>Thirdly, Obsidian has a "show me a random note" feature. This feature helps me <em>ruminate</em> through ideas. It's the digital equivalent of me jumping through concepts in my head, except now I have a <em>reliable</em> external store for ideas (Obsidian) rather than an <em>unreliable</em> internal store (my brain). Surfacing up random notes is an extremely excellent way of hopping through my knowledge graph to surface up ideas in a spaced repetition fashion, allowing my mind to uncover and create connections between ideas that I might not have made otherwise.</p> <h3 id="plain-text">Plain text</h3><p>Apart from those three key features, one other notable feature, pun intended, makes me <em>trust</em> Obsidian over other notetaking services. That feature is Obsidian's choice to rely on simple Markdown files as the unit on which linking happens. This choice stands in contrast to Evernote's expanded XML syntax, which, though open, is not <em>plain</em> enough to have a low barrier to parsing. The choice also stands in contrast to Roam's and Notion's choice to link individual blocks of text, which requires additional tech that, almost by definition, requires specialized data structures - again, being not low enough of a barrier. Effectively, with Obsidian, I own my data, stored using the lowest common denominator of computing: text files.</p> <h2 id="tips-for-using-obsidian">Tips for using Obsidian</h2><p>I've now decided to change up my notetaking systems and go the "whole hog" with Obsidian. For the rest of this post, I'd like to share some of the tips that I picked up that made the system click for me.</p> <h3 id="each-markdown-file-as-a-single-unit-of-thought">Each Markdown file as a single unit of thought</h3><p>The first tip I picked up was to treat each Markdown file as a coherent and atomic unit of thought. This tip is something I picked up directly from Andy Matuschak's notes, and I believe this is the most crucial tip to making a system like this work. In doing so, we are nudging ourselves to compose a coherent and atomic unit of thought, to which we can establish relationships to other similarly-constructed ideas. Writing them down takes effort, so this mode of notetaking not for the "collector" type; instead, it is for intentional curators.</p> <h3 id="actively-connect-ideas">Actively connect ideas</h3><p>The second tip I picked up was to intentionally try to establish as many connections between ideas as possible. Andy Matuschak calls this "linking densely," and this action is essential: it is how we construct our knowledge graph! A way to make these links is to think of ideas as <em>imperative statements</em> that we make; inside the note, we elaborate on the concept with, say, supporting evidence. As an example, this paragraph would be given the title <code>Notes should be linked densely</code>. I would then link to it inside a list on an overview page or as part of textual prose.</p> <h3 id="tend-to-the-knowledge-garden-regularly">Tend to the knowledge garden regularly</h3><p>A third tip that I uncovered through experience is to treat the knowledge graph as a garden that requires regular tending. For me, tending implies:</p> <ol> <li>Leveraging the random note feature to find old ideas buried beneath the more recent things I have been thinking about,</li> <li>Browsing through Obsidian's graph view to locate singleton notes and trace paths through them, and</li> <li>Ruminating over the notes at a later date using the random notes feature.</li> </ol> <h2 id="my-notes-made-public">My notes made public</h2><p>I've written a lot about how I've used Obsidian to help me organize my knowledge. However, you might be wondering, can I see an example? In line with the principle of working in the open, of course! <a href="">I put my notes online</a>, available for others to see, and so that I can reference them when I interact with others. In case you want to see the note(s) that backed this blog post, look around for my "blog drafts" on the index page, and follow the knowledge graph from there. :)</p> Disable sleep on Ubuntu2020-10-18T00:00:00ZEric J. Maurn:uuid:6c77e921-c931-3cad-b730-7cd6e8941f95<p>I have a running Linux tower at home that contains a GPU. It runs headless, i.e. without keyboard, mouse, and monitor. However, the box sometimes goes to sleep, which means I'm unable to SSH (or <a href=""><code>mosh</code></a>) into the tower on our home network, or access a perpetually running Jupyter session that I have. Short of keeping a keyboard next to it, I thought there had to be a better way to keep the tower alive.</p> <p>Turns out, it's a simple command.</p> <p>Based on <a href="">this StackOverflow</a> post, to disable sleeping/suspending, we execute the following command at the terminal (after logging in):</p> <div class="hll"><pre><span></span>sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target </pre></div> <p>You'll get the following output:</p> <div class="hll"><pre><span></span. </pre></div> <p>Now, let's say we wanted to re-enable sleep/suspend. In that case, we have the inverse command available:</p> <div class="hll"><pre><span></span>sudo systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target </pre></div> <p>You'll get the following output:</p> <div class="hll"><pre><span></span>Removed /etc/systemd/system/sleep.target. Removed /etc/systemd/system/suspend.target. Removed /etc/systemd/system/hibernate.target. Removed /etc/systemd/system/hybrid-sleep.target. </pre></div> <p>The <code>mask</code>/<code>unmask</code> combo is what does the magic. Specifically, when masking, the command creates a symbolic link in <code>/etc/systemd/system</code> for each of sleep, suspend, hybernate and hybrid-sleep, and points it to <code>/dev/null</code>. Pointing to <code>/dev/null</code> is a great way to redirect commands to oblivion, thus disabling sleep.</p> Fermi estimation and Bayesian priors2020-10-15T00:00:00ZEric J. Maurn:uuid:6313a275-b268-3d74-9606-6662a4888a2a<p>Fermi estimation is named after the renown physicist Enrico Fermi for his ability to give accurate order-of-magnitude estimates for certain quantities. From Wikipedia, Fermi estimation is described as such:</p> <blockquote><p.</p> </blockquote> <p.</p> <p>Let me illustrate.</p> <p.</p> <p.</p> <p.</p> <p.</p> Why giving talks is important for writing2020-10-06T00:00:00ZEric J. Maurn:uuid:9b9a3643-4830-33c1-bbbc-6d97b5651e1d<p>I recently arrived at an epiphany. Delivering talks on a topic is an important way to prepare for writing a paper.</p> <p.</p> <p.</p> <p.</p> <p>So why did talking help with the writing? Turns out, when delivering a talk, we are forced to <strong>linearize the spaghetti mess of a project that we've worked on</strong>, which exactly parallels what <em>must</em>.</p> <p.</p> <p.</p> Moving Data Securely and Quickly with `croc`2020-10-01T00:00:00ZEric J. Maurn:uuid:78ffa845-a69d-3256-8f7e-10b6c1066647<p>I recently had to move a large file from a computer in one site at work to another computer in another site at work, to obtain a dataset for machine learning purposes. To do this, I usually would have used <code>scp</code>, but for whatever reason (didn't debug, no time), it was borked on my user account. We apparently pay for an Aspera license, but it was installed on a very old system that I was struggling/wrestling with. Thus, I looked back on my GitHub stars, knowing that someone must have made something that we could use - and indeed, I found <a href=""><code>croc</code></a>.</p> <p>What's <code>croc</code>? It's a file transfer system that sends files securely using end-to-end encryption, via a file transfer relay. What's a "file transfer relay"? Essentially, it's a go-between computer that is set up to relay connections to and from computers -- it does this one and only one job -- but cannot read the contents of anything that is passed through it.</p> <p>Using a relay in between two computers sounds kind of roundabout. Why would we want this in contrast to directly <code>scp</code>-ing, or standing up an HTTP server and using an HTTP URL to send the data?</p> <p>To understand more, I read <code>croc</code>'s creator's <a href="">blog post describing the design advantages of <code>croc</code></a>. The key advantages are <strong>speed</strong>, <strong>security</strong>, and <strong>simplicity</strong>, all-in-one. Speed because the relay doubles the number of computers sending/receiving data. Security because of the use of Password-Authenticated Key Exchange between the two computers, and the ephemeral nature of the connection. And simplicity, because of the user-interface.</p> <p>Now, baked into <code>croc</code>'s configuration is the use of a public relay server that <code>croc</code>'s creator has set up, but one can set up their own relay server, and configure <code>croc</code> to use that relay server at runtime. To do this requires a one-time setup on a third computer or in a docker container. I did the former at work, setting up a temporary relay server on a Linux workstation, because I couldn't access the public relay server on our VPN (which is exactly what is supposed to happen, for security!). The 6GB file was transferred at a rate of about 50 MB/sec, which, for me, was fast enough and heartening to get on with life!</p> <p>To do this, we access the relay computer, which should be a computer visible on the intranet, download <code>croc</code>, and run <code>croc</code> as a relay process:</p> <div class="hll"><pre><span></span>croc relay </pre></div> <p>Then, we point croc away from the default public relay when sending a file:</p> <div class="hll"><pre><span></span>croc --relay <span class="s2">"my-url.my-host.com:9009"</span> send some_file.extension </pre></div> <p>Then on the receiving end:</p> <div class="hll"><pre><span></span>croc --relay <span class="s2">"my-url.my-host.com:9009"</span> some-secret-code </pre></div> <p>Being written in the Go programming language, it's fast and easily distributed on multiple platforms. Coupled with its ease-of-use, count me a fan!</p> Tools to help you write consistent Python code2020-09-30T00:00:00ZEric J. Maurn:uuid:c08d0d95-8be0-3ee2-9278-7491ab06a60d<p>As a data scientist, you might be feeling the need to level-up your code-writing skills. After all, if your hacked together script becomes the basis of production systems, imagine the headache :). Moreover, as time goes by, it seems to me that for data scientists to uncover the high risk, but nonetheless potentially high value and high impact outlets, nothing beats having software skills to flexibly express the custom logic that's needed. Hadley Wickham's sentiment that <a href="">one can't do data science in a GUI</a> seems to ring true, though I'd probably refine it by saying that one can't do <em>highest value</em> data science without programming skills!</p> <p>Mostly because of the community of <a href=""><code>pyjanitor</code></a> developers, who encounter a smattering of tooling that I might not have, I have had the privilege of learning from them a collection of tooling that I think can really help with code style. Especially if you transition your code from a Jupyter notebook to a <code>.py</code> source file! Equipped with the right tools, you can write consistent code without needing to memorize all of the rules. And that idea of externalizing the rules to a program is what these tools are all about!</p> <h2 id="tl-dr-what-tools-are-there">tl;dr: What tools are there?</h2><p>For the impatient, here's the summary:</p> <h3 id="code-formatters">Code formatters</h3><p>i.e. those that explicitly change your code:</p> <ul> <li>Black</li> <li>isort</li> </ul> <h3 id="code-linters">Code linters</h3><p>i.e. those that <em>don’t</em> change your code, but flag errors:</p> <ul> <li>Flake8</li> <li>Interrogate</li> <li>Darglint</li> <li>pylint</li> <li>mypy</li> </ul> <p>Some of these come with <code>pre-commit hooks</code>, which I strongly suggest you use!</p> <h3 id="vscode-tooling">VSCode tooling</h3><p>VSCode tooling for those who are used to VSCode as your development environment:</p> <ul> <li>Python extension</li> <li>pylance: this is superbly fast. hats off, Microsoft.</li> </ul> <h3 id="external-ci-services">External CI services</h3><p>Tools that run as an external service for your continuous integration pipeline:</p> <ul> <li>deepsource</li> </ul> <h2 id="thats-a-lot-of-tools-how-do-i-interact-them">That’s a lot of tools; how do I interact them?</h2><p>A full-fledged tutorial is probably not the realm of this tiny blog post, but I will begin by giving you the overview of how you interact with them in general. That should give you enough patterns to work with when you look at their docs.</p> <h3 id="at-the-cli">At the CLI</h3><p>The code formatters and linters are runnable at the CLI. You can consider this to be the lowest-level/primitive way of using them. For example, with <code>black</code>, you would call on it at the command line at the root of your project repository:</p> <div class="hll"><pre><span></span>black . </pre></div> <p>What pops out is Black telling you what files it formatted, or error messages telling you which files it couldn’t format.</p> <p>Likewise for <code>flake8</code>:</p> <div class="hll"><pre><span></span>flake8 . </pre></div> <p>What pops out is an entire collection of “error codes”, which specify one and only one error that it caught. The error messages will tell you what’s <em>wrong</em>, so correcting the error is a matter of doing the opposite. For example, <code>flake8</code> might tell me that a line is too long at 89 characters, which is greater than the 79 that it is configured for, and so I would have to split up that line, or if it’s a string then remove unnecessary words, to correct the error.</p> <h3 id="configuration">Configuration</h3><p>Sometimes, two tools might come with defaults that conflict with one another. <code>flake8</code> and <code>black</code> are two; <code>black</code>, being opinionated, will format lines to fit in 88 characters, but <code>flake8</code> will by default look for 79 characters. (I’m in favour of 79, because it allows me to look at my code in its entirety side-by-side on a 15” MacBook Pro.)</p> <p>Each tool comes with its own configuration documentation page. The Python community has started gravitating towards a config file called <a href=""><code>pyproject.toml</code></a>, which is intended for Python language tools. If <code>pyproject.toml</code> is supported by a tool, then you should be able to find a page in the documentation. A well-written docs page will give you a copy/paste-able config file with extensive comments that you can read to know what’s going on. (Black itself leads the charge: its <a href="">page on the <code>pyproject.toml</code> file</a> is very well-documented!)</p> <p>I think that the community-wide standardization is a great thing! The way this has happened is a bit slow, but at least the tool authors don’t make it <em>onerous</em> to migrate from existing config files. Fits all of the right patterns: make doing the right thing easy!</p> <h3 id="inside-vscode">Inside VSCode</h3><p>If you use VSCode as your day-to-day integrated development environment (or IDE), there are two extensions that are indispensable for Python developers: <a href="">the official Python extension</a> and <a href="">Pylance</a>. The official Python extension adds support for:</p> <blockquote><p>IntelliSense, linting, debugging, code navigation, code formatting, Jupyter notebook support, refactoring, variable explorer, test explorer, snippets, and more!</p> </blockquote> <p>Pylance, on the other hand, is:</p> <blockquote><p>powered by Pyright, Microsoft's static type checking tool. Using Pyright, Pylance has the ability to supercharge your Python IntelliSense experience with rich type information, helping you write better code faster.</p> </blockquote> <p>With code linting enabled in VSCode, you get the benefits of errors showing up as you type. An example from the <code>pyjanitor</code> library, which contains some holdover code style issues from before the time I was proficient in these tools, can be seen in the screenshot below.</p> <p><img src="pylance-screenshot.png" alt=""></p> <p>Underneath the hood, for code style checking, both extensions call out to <code>flake8</code>, <code>black</code>, <code>mypy</code> and other tools to perform code checking, and this is configurable in VSCode itself.</p> <h3 id="inside-your-ci-system">Inside your CI system</h3><p>If you build a project and have a continuous integration system for it, you can continuously check your code using the CLI tools. Concpetually, the steps you'd follow are:</p> <ol> <li>Install the tools inside the CI environment at build time.</li> <li>Place in the right configuration files in your project root.</li> <li>Execute the tools in the testing section of your CI build.</li> </ol> <p>The <a href=""><code>pyjanitor</code> Azure pipelines CI</a> has a great example of this in action. I'd recommend putting these early on, as waiting for test to pass before catching these <em>slightly</em> more trivial problems can make for a <em>slightly</em> irritated developer 😅.</p> <p>Because we're talking about CI systems, we might as well also talk about the external CI service highlighted here, DeepSource. It's a commercial service that is free for open source projects, and in there I've gotten a few reminders on certain anti-patterns. I like what they're doing; the team does have to make a living, so I'm not opposed to the commercialization of their tool, and in fact I'm quite appreciative of the fact that they've made it freely accessible for OSS projects.</p> <h3 id="what-about-inside-jupyter-notebooks">What about inside Jupyter notebooks?</h3><p>Most of us who are data scientists spend a majority of our time inside Jupyter notebooks. Are there tools available for us to help us write good code inside notebooks?</p> <p>Turns out, there's quite a few projects that try to do this! Given the breadth of people who know how to use Python to do things, it never seems far-fetched to think that someone else who has a need to scratch has already figured this out.</p> <p>Through digging around on the internet, I found at least the following tools that could be promising:</p> <ul> <li><a href=""><code>black-nb</code></a></li> <li><a href=""><code>nb_black</code></a></li> <li><a href=""><code>jupyter-black</code></a></li> </ul> <p>That said, I usually adhere to the following principle with notebooks: that they are intended to be both read <em>and</em> executed, meaning if you have long walls of code inside your notebook, they should be refactored out into a custom package to keep the storytelling logic of your notebook flowing nicely. That is when using an IDE can help you. If your intent with <code>black</code>-ifying notebooks is to avoid refactoring your code, then you'll be disappointed - <code>black</code> has a tendency to add lines to code, such as hard-coded lists that are unavoidably long. <code>black</code>-ifying your notebook code may thus have unintended consequences for readability!</p> <p>Instead, do the right thing: <a href="">Refactor your code!</a>! To learn how to break out custom code, <a href="">check out this very well-written blog post</a>!</p> <h2 id="help-me-take-action-what-should-i-do-next">Help me take action! What should I do next?</h2><p>Here's the next thing you can do: add these tools into your <code>environment.yml</code> (conda users) or <code>requirements.txt</code> (venv/pip-only users) files! Then, update your virtual environment. Voilà! You now have these tools in your environment, and can start checking your code style!</p> <p>(Not using environments? I won't judge you 😅, but I would <em>strongly encourage</em> that you do so! <a href="">Here's some tips to help</a>.)</p> <h2 id="conclusions">Conclusions</h2><p>Hopefully this short essay has helped you get familiar with some of the tooling to help you write consistently-styled code that is also readable by a large swathe of the Python-writing universe of programmers. Writing code in a consistent style is important. That style usually involves rules; having tools to externalize that style, such you don't have to worry about remembering it, helps us conform to that style more easily. Have fun writing clean code!</p> Add a direct Binder link for built HTML notebooks2020-09-12T00:00:00ZEric J. Maurn:uuid:612c5024-bf34-3ece-824b-5b47f4aedecf<p>I recently learned a thing! If you write tutorial material in Jupyter notebooks, it's possible to include a Binder link directly to a notebook, such that Binder opens up <em>directly</em> inside that notebook (rather than in the file browser).</p> <p>The "vanilla" link one usually gets from <a href="">mybinder.org</a> looks like this (using Network Analysis Made Simple as an example):</p> <div class="hll"><pre><span></span><span class="p">[</span><span class="err">!</span><span class="p">[</span><span class="n">Binder</span><span class="p">](</span><span class="n">https</span><span class="p">:</span><span class="o">//</span><span class="n">mybinder</span><span class="o">.</span><span class="n">org</span><span class="o">/</span><span class="n">badge_logo</span><span class="o">.</span><span class="n">svg</span><span class="p">)](<="p">)</span> </pre></div> <p>More generally speaking, the anatomy of the URL> </pre></div> <p>Now, if you want to point directly to a file to be opened on Binder launch, you would instead do something?</span><span class="n">filepath</span><span class="o">=</span><span class="n">docs</span><span class="o">%</span><span class="mi">2</span><span class="n">F01</span><span class="o">-</span><span class="n">introduction</span><span class="o">%</span><span class="mi">2</span><span class="n">F02</span><span class="o">-</span><span class="n">networkx</span><span class="o">-</span><span class="n">intro</span><span class="o">.</span><span class="n">ipynb</span> </pre></div> <p>The general form of the URL looks now like the following:<><span class="err">?</span><span class="n">filepath</span><span class="o">=<</span><span class="n">FILE_PATH</span><span class="o">></span> </pre></div> <p>Here, the <code><FILE_PATH></code> is a POSIX-style string relative to the repository root. A thing to note: all of the <code>/</code> characters in the <code><FILE_PATH></code> probably have to be replaced with <code>%2F</code>, otherwise the URL might not work correctly!</p> <p>Using this pattern, I was able to insert a Launch Binder icon for all of my Jupyter notebooks in the Network Analysis Made Simple repository!</p> <p>That said, manually inserting that many Launch Binder icons by hand is not an easy-to-maintain thing. Is there a better way? You bet!</p> <p>Leveraging the Jupyter notebook Python API (the <a href=""><code>nbformat</code> package</a>) as well as the <code>mkdocs</code> navigation section, I was able to write a few custom functions that inserted a correct Binder URL with the badge into the top of each notebook before building the HTML pages with <code>mkdocs</code>. The code roughly looked like this:</p> <div class="hll"><pre><span></span><span class="n">badge_url</span> <span class="o">=</span> <span class="sa">f</span><span class="s2">"[](</span><span class="si">{</span><span class="n">nb_relpath</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s2">%2F</span><span class="si">{</span><span class="n">nb_relpath</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s2">)"</span> <span class="n">nb_path</span> <span class="o">=</span> <span class="n">docroot</span> <span class="o">/</span> <span class="n">nb_relpath</span> <span class="n">nb</span><span class="p">[</span><span class="s2">"cells"</span><span class="p">]</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">nbformat</span><span class="o">.</span><span class="n">v4</span><span class="o">.</span><span class="n">new_markdown_cell</span><span class="p">(</span><span class="n">source</span><span class="o">=</span><span class="n">badge_url</span><span class="p">))</span> </pre></div> <p>The full build script is located <a href="">here</a>.</p> <p>I thought this might be a useful addition to <code>mknotebooks</code>, which handles Jupyter notebook preprocessing for <code>mkdocs</code>, so I also raised <a href="">an issue</a> up there to see if the maintainer of <code>mknotebooks</code> is interested in it!</p> Faster iteration over dataframes2020-09-07T00:00:00ZEric J. Maurn:uuid:ebccf211-7675-3fd0-bb6a-be914ab4c9ee<p>I can't claim credit for this one, as I found it <a href="">here on LinkedIn</a>. That said, in case it's helpful for you, here's the tip:</p> <p>We are usually taught to loop through a dataframe using <code>df.iterrows()</code>:</p> <div class="hll"><pre><span></span><span class="k">for</span> <span class="n">r</span><span class="p">,</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">df</span><span class="o">.</span><span class="n">iterrows</span><span class="p">():</span> <span class="nb">print</span><span class="p">(</span><span class="n">d</span><span class="p">[</span><span class="s2">"column_name"</span><span class="p">])</span> </pre></div> <p>Turns out, the faster way to loop over rows in a dataframe is:</p> <div class="hll"><pre><span></span><span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">df</span><span class="o">.</span><span class="n">itertuples</span><span class="p">():</span> <span class="nb">print</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">column_name</span><span class="p">)</span> </pre></div> <p>According to the post, this is about on the order of 1000X faster.</p> <p>The main reason for the speedup is because the use of <a href=""><code>.itertuples()</code></a> leads to the construction of <a href=""><code>namedtuples</code></a>. By contrast, the use of <a href=""><code>.iterrows()</code></a> returns <code>d</code> as a pandas Series, which is slower to construct on each loop iteration.</p> <p>Of course, one would usually try to vectorize as much as possible, but in the event that looping is unavoidable, this might be a good tip to keep in your back pocket!</p> Pandera, Data Validation, and Statistics2020-08-30T00:00:00ZEric J. Maurn:uuid:60641a47-c634-3484-b085-4120550f0d59<p>I have test-driven the <a href="pandera.readthedocs.io/"><code>pandera</code></a> package over the past few days, and I'm extremely happy that this package exists!</p> <p>Let me tell you why.</p> <h2 id="data-testing">Data testing</h2><p>"Data testing" is the colloquial term that I have used in place of the more formal term, "schema validation", or "data validation". Ever since I was burned once by CSV files with invalid column names, I put together a <a href="">data testing tutorial</a> to kickstart the idea, and have been keeping an eye on the space ever since.</p> <p>But let’s step back a bit.</p> <p>What do we mean by schema/data validation? It’s merely a fancy way of checking, “are my data as I expect them to be?”</p> .</p> <p:</p> <div class="hll"><pre><span></span><span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span> <span class="p">{</span> <span class="s2">"non_negative"</span><span class="p">:</span> <span class="p">[</span><span class="mf">1.1</span><span class="p">,</span> <span class="mf">0.34</span><span class="p">,</span> <span class="mf">2.5</span><span class="p">],</span> <span class="s2">"two_values"</span><span class="p">:</span> <span class="p">[</span><span class="s2">"val1"</span><span class="p">,</span> <span class="s2">"val2"</span><span class="p">,</span> <span class="s2">"val2"</span><span class="p">],</span> <span class="p">}</span> <span class="p">)</span> </pre></div> <p>If I were implementing these checks in a test suite in vanilla Python, I would write them as follows:</p> <div class="hll"><pre><span></span><span class="kn">from</span> <span class="nn">project_source.data</span> <span class="kn">import</span> <span class="n">load_data</span> <span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span> <span class="k">def</span> <span class="nf">test_load_data</span><span class="p">():</span> <span class="n">data</span> <span class="o">=</span> <span class="n">load_data</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="k">assert</span> <span class="n">np</span><span class="o">.</span><span class="n">all</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="s2">"non_negative"</span><span class="p">]</span> <span class="o">></span> <span class="mi">0</span><span class="p">)</span> <span class="k">assert</span> <span class="nb">set</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="s2">"two_values"</span><span class="p">]</span><span class="o">.</span><span class="n">unique</span><span class="p">())</span> <span class="o">==</span> <span class="nb">set</span><span class="p">([</span><span class="s2">"val1"</span><span class="p">,</span> <span class="s2">"val2"</span><span class="p">])</span> </pre></div> <p>Having the checks in the test suite is nice, as it means if the checks are run as part of a CI pipeline, they’ll continually be checked. However, they cannot be checked whenever I call on <code>load_data()</code>, <code>load_data()</code> function. And we know that duplication of code increases risk of stale code.</p> <p>Enter <code>pandera</code>. Instead of writing the checks in two separate places, I can start by writing the following declarative schema in a Python module, that serves as a defined source of truth:</p> <div class="hll"><pre><span></span><span class="c1"># project_source/schemas.py</span> <span class="kn">from</span> <span class="nn">pandera</span> <span class="kn">import</span> <span class="n">Column</span><span class="p">,</span> <span class="n">DataFrameSchema</span><span class="p">,</span> <span class="n">Check</span> <span class="kn">import</span> <span class="nn">pandera</span> <span class="k">as</span> <span class="nn">pa</span> <span class="n">schema</span> <span class="o">=</span> <span class="n">DataFrameSchema</span><span class="p">(</span> <span class="n">columns</span><span class="o">=</span><span class="p">{</span> <span class="s2">"non_zero_column"</span><span class="p">:</span> <span class="n">Column</span><span class="p">(</span><span class="n">pa</span><span class="o">.</span><span class="n">Float</span><span class="p">,</span> <span class="n">Check</span><span class="o">.</span><span class="n">greater_than</span><span class="p">(</span><span class="mi">0</span><span class="p">)),</span> <span class="s2">"categorical_column"</span><span class="p">:</span> <span class="n">Column</span><span class="p">(</span><span class="n">pa</span><span class="o">.</span><span class="n">String</span><span class="p">,</span> <span class="n">Check</span><span class="o">.</span><span class="n">isin</span><span class="p">([</span><span class="s2">"value_1"</span><span class="p">,</span> <span class="s2">"value_2"</span><span class="p">])),</span> <span class="p">}</span> <span class="p">)</span> </pre></div> <p>Now, the flexibility with which this schema gets used is simply <em>superb</em>! Because I've declared it as a Python object in code, I can import it <em>anywhere</em> I want validation to happen.</p> <p>For example, I can validate the inputs to a function at runtime:</p> <div class="hll"><pre><span></span><span class="c1"># project_source/data.py</span> <span class="kn">from</span> <span class="nn">pandera</span> <span class="kn">import</span> <span class="n">check_input</span><span class="p">,</span> <span class="n">check_output</span> <span class="kn">from</span> <span class="nn">.schemas</span> <span class="kn">import</span> <span class="n">dataframe_schema</span><span class="p">,</span> <span class="n">cleaned_df_schema</span> <span class="nd">@check_input</span><span class="p">(</span><span class="n">dataframe_schema</span><span class="p">)</span> <span class="nd">@check_output</span><span class="p">(</span><span class="n">cleaned_df_schema</span><span class="p">)</span> <span class="k">def</span> <span class="nf">clean</span><span class="p">(</span><span class="n">dataframe</span><span class="p">):</span> <span class="c1"># stuff happens</span> <span class="k">return</span> <span class="n">cleaned_df</span> </pre></div> <p>And because the validation happens as soon as the function is executed, I can also validate the schema as part of an automatically-executed test suite that continuously runs and checks data alongside code.</p> <div class="hll"><pre><span></span><span class="kn">from</span> <span class="nn">project_src.data</span> <span class="kn">import</span> <span class="n">load_some_data</span> <span class="k">def</span> <span class="nf">test_load_some_data</span><span class="p">():</span> <span class="n">data</span> <span class="o">=</span> <span class="n">load_some_data</span><span class="p">()</span> </pre></div> <p>The data test suite becomes simpler to maintain, as it gets reduced to a simple execution test. Validating data at every step that it could go wrong is pretty important!</p> <p>Additionally, if there is a new data file that needs to be processed in the same way, when we pass in the dataframe version into the <code>clean_data</code> function, it is automatically validated by <code>pandera</code>’s <code>check_input</code>. If a dataframe that fails <code>check_input</code>, then <code>pandera</code> will give us an error message straight away!</p> <p>These are just the basics. Pandera comes with even more:</p> <ul> <li>Validating the <code>Index</code>/<code>MultiIndex</code>.</li> <li>Automatically inferring a draft schema that you can use as a base.</li> </ul> <p>I'm excited to see how this goes. Congratulations to the package author Niels Bantilan, it's a package that has all of the <em>right< <code>pandas</code> DataFrames, an idiomatic data structure in the Python data science world, which is always a plus. Having incorporated <code>pandera</code> into a project just recently, I'm excited to see where its future is headed!</p> <h2 id="data-validation-as-statistical-evaluation">Data Validation as Statistical Evaluation</h2><p>I can see that data validation <em>actually</em> has its roots in statistical evaluation of data.</p> <p>Humour me for a moment.</p> <p>Say we have a column that can only take two values, such as “yes” and “no”.</p> <p>From a statistical viewpoint, that data are generated from Bernoulli distribution, with “yes”/1 and “no”/0 being the outcomes.</p> <p>If you get a “maybe” in that column, that value is outside of the <em>support</em> of the distribution. It’s like trying to evaluate the likelihood of observing a 2 from a Bernoulli. It won’t compute.</p> <p>So every time we run a <code>pandera</code> check, we are effectively expressing a <em>statistical</em> check of some kind. The byline of the package, “Statistical Data Validation for Pandas”, is <em>even more apt</em> once we consider this viewpoint!</p> <h2 id="conclusions">Conclusions</h2><p>I hope this post encourages you to give <code>pandera</code> a test-drive! Its implementation of "runtime data validation" is very handy, allowing me to declare the assumptions I have about my data up-front, and catch any violations of those assumptions as early as possible.</p> Software Engineering as a Research Practice2020-08-21T00:00:00ZEric J. Maurn:uuid:7d641c13-80de-3410-868d-cc989efa303f<p>At this year's SciPy 2020, a talk and proceedings paper caught my eye: "Software Engineering as Research Method". (Here are links to <a href="">the paper</a> and <a href="">the talk</a>.) In it, the authors, Mridul Seth and Sebastian Benthall, detailed the benefits that software skills bring to the academic and industrial research communities, both from the perspective of making scientific progress and from the perspective of pedagogy.</p> <p>I've been doing some reflection of my own on how software skills have helped me tremendously, as a data scientist. Here's my thoughts on them, using the example of random number generators and probability distributions.</p> <h2 id="generating-random-numbers">Generating Random Numbers</h2><p>In building scientific software, we are recognizing pragmatically useful categories around us, and formalizing them in a language. Let's look at a really simple example of drawing <code>1</code>s and <code>0</code>s from a Bernoulli distribution.</p> <h3 id="oppa-imperative-style">Oppa <em>Imperative</em> Style</h3><p>If we were to write a Bernoulli draws generator in Python code, we might implement it as follows:</p> <div class="hll"><pre><span></span><span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">random</span> <span class="n">p</span> <span class="o">=</span> <span class="mf">0.5<> </pre></div> <p>This is purely imperative style programming. Without going too deep (pun intended) into definitions, by using mostly built-in primitives of the Python language, we are operating at a fairly low-level paradigm.</p> <p>Now, let's imagine a world where the Bernoulli distribution object does not exist. I have a collaborator who wants to build on top of Bernoulli distributions to make other things. They would have to copy/paste this <em>imperative</em> block of code into their programs.</p> <h3 id="oppa-functional-style">Oppa <em>Functional</em> Style</h3><p>What can we do to alleviate this, then?</p> <p>One thing we can try is to encapsulate it in a function! The implementation might look like"">p</span> </pre></div> <p>But wait, what are the semantics of <code>p</code>? Is it the probability of obtaining class 1, or class 0? The behaviour isn't documented in the class, so let's add some of"""</span> <span class="sd"> Return a sequence of Bernoulli draws.</span> <span class="sd"> :param p: The probability of obtaining class 0.</span> <span class="sd"> :num_draws: The number of Bernoulli draws to make.</span> <span class="sd"> Should be greater than zero.</span> <span class="sd"> :returns: A list of 1s and 0s.</span> <span class="sd"> """<, we can do a few things with this implementation. Firstly, we can write a test for it. For example, we can assert that numbers drawn from the Bernoulli are within the correct support:</p> <div class="hll"><pre><span></span><span class="k">def</span> <span class="nf">test_bernoulli</span><span class="p">():</span> <span class="n">draws</span> <span class="o">=</span> <span class="n">bernoulli</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mf">0.3</span><span class="p">)</span> <span class="k">assert</span> <span class="nb">set</span><span class="p">(</span><span class="n">draws</span><span class="p">)</span><span class="o">.</span><span class="n">issubset</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">])</span> </pre></div> <p>Secondly, we can compose it in bigger programs, such as a Binomial generator:</p> <div class="hll"><pre><span></span><span class="k">def</span> <span class="nf">binomial</span><span class="p">(</span><span class="n">num_draws</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">n<">num_ones</span> <span class="o">=</span> <span class="n">n</span> <span class="o">-</span> <span class="nb">sum</span><span class="p">(</span><span class="n">bernoulli</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">p</span><span class="p">))</span> <span class="n">draws</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">num_ones</span><span class="p">)</span> <span class="k">return</span> <span class="n">draws</span> </pre></div> <p>Please excuse my lack of docstrings for a moment!</p> <h3 id="oppa-classy-style">Oppa <em>Classy</em> Style</h3><p.</p> <p>The probability density function is unique property of a probability distribution; it's also an invariant property. As such, it is something we can instantiate once and forget about later. Perhaps using an object-oriented paradigm might be good here. Let's see this in action:</p> <div class="hll"><pre><span></span><span class="k">class</span> <span class="nc">Bernoulli</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">p</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">p</span> <span class="o">=</span> <span class="n">p</span> <span class="k">def</span> <span class="nf">pdf</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">:</span> <span class="nb">int</span><span class="p">):</span> <span class="k">if</span> <span class="n">data</span> <span class="ow">not</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">]:</span> <span class="k">raise</span> <span class="n">ValueErrror</span><span class="p">(</span><span class="s2">"`data` must be either 0 or 1!"</span><span class="p">)</span> <span class="k">if</span> <span class="n">data</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="k">return</span> <span class="n">p</span> <span class="k">return</span> <span class="mi">1</span> <span class="o">-</span> <span class="n">p</span> <span class="k">def</span> <span class="nf">rvs</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">n<, with this object, we've made using the category of Bernoulli distributions much easier!</p> <div class="hll"><pre><span></span><span class="n">b</span> <span class="o">=</span> <span class="n">Bernoulli</span><span class="p">(</span><span class="mf">0.5</span><span class="p">)</span> <span class="n">draws</span> <span class="o">=</span> <span class="n">b</span><span class="o">.</span><span class="n">rvs</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># draw 10 numbers</span> <span class="n">pdfs</span> <span class="o">=</span> <span class="p">[</span><span class="n">b</span><span class="o">.</span><span class="n">pdf</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">draws</span><span class="p">]</span> <span class="c1"># calculate pdf of data</span> </pre></div> <p>An object-oriented paradigm here also works well, because the way <code>.rvs()</code> and <code>.pdf()</code> have to be implemented for each probability distribution is different, but the inputs to those functions are similar across the entire category of things called "probability distributions".</p> <h3 id="a-reflection">A reflection</h3><p <em>useful</em> and <em>verifiable</em> models of the world is a core activity of the quantitative sciences.</p> <p>By exploring and structuring probability distributions in a logical fashion, my pedagogical exploration of probability distributions as a modelling tool is reinforced with the following main ideas:</p> <ol> <li>Probability distributions generate random numbers according to a set of rules,</li> <li>Probability distributions can evaluate data against its PDF</li> </ol> <p>And by structuring a probability distribution as an object with class methods, our mental model of the world of probability distributions is made much clearer.</p> <h2 id="research-discipline-you-say">"Research discipline", you say?</h2><p>Yes, research discipline, and in both ways. Here’s what I mean.</p> <p>Discipline (<em>a la</em> "rigour") in thought means thinking <em>clearly</em> about how the thing we are working with fits <em>most naturally</em> in relation to other things. Nudging ourselves to make better software makes us better thinkers about a problem class. Bringing this level of discipline gives us an opportunity to organize the little subject matter discipline that we inhabit.</p> <p>As a discipline (i.e. "way of thought"), well-written software also enables us to build on top of others' thoughtfully laid out tooling. As such we are</p> <h3 id="stability-in-underlying-primitives-matter">Stability in underlying “primitives” matter</h3><p>Contrary to a generation of us that might think that "choice in everything is the ultimate", a stable base is what a field <em>really</em>.</p> <p!</p> <p>As such, shared stability in the base gives us confidence to build on top of it.</p> <h3 id="building-and-reinforcing-mental-models">Building and reinforcing mental models</h3> <em>building</em> software.</p> <p>The act of organizing the world around us into categories with properties and relationships is made <em>concrete</em> when we build software. By organizing the conceptual world into layers of abstractions and sequences of actions, we bring a clarity of thought to the flow of work. I would argue that this can <em>only help</em> with the construction of a consistent and productive view of a field.</p> <h3 id="incidental-benefits">Incidental benefits</h3><p.</p> <h2 id="application-of-software-skills-a-case-study">Application of software skills: A case study</h2><p>Some of the work I engage in at NIBR involves fairly non-standard models. These are the models for which a <code>scikit-learn</code>).</p> <p <code>scikit-learn</code>'s API for model construction, and leveraging <code>jax</code> for speed and expressiveness.</p> <h3 id="implementing-the-core">Implementing the core</h3><p.</p> <h3 id="testing">Testing</h3><p <em>more generally</em> correct.</p> <h3 id="documentation">Documentation</h3><p>We invest time up-front working on documentation. By documentation, I mean at least the following:</p> <ul> <li>Docstrings for every function, and</li> <li>Usage examples to cover workflows.</li> </ul> <p>Investing time up-front for documentation is actually a great thing to do. By putting in workflow examples, we actually leave for ourselves copy/paste-able workflows that can greatly speed up the ramp-up phase of a new project that leverages what we have built.</p> <h3 id="view-towards-open-sourcing">View towards open sourcing</h3><p!</p> <h2 id="conclusion">Conclusion</h2><p>Whenever I go to my tribe of data scientists at work and advocate for better software skills, I often get a myriad of responses. A small sliver agree with me <em>and</em> actively put it into practice. A much larger slice agree, other factors stop them from getting started; these might be lack of knowledge, or too much external pressure to deliver results, and as such no action is taken.</p> <p.</p> <p.</p> <p.</p> <h2 id="resources-for-learning">Resources for learning</h2><ul> <li><a href="">Software Carpentry's Lessons</a></li> <li><a href="">Software Engineering for Data Scientists by Itamar Turner-Trauring</a></li> <li><a href="">Software engineering fundamentals for Data Scientists</a></li> <li><a href="">Software Engineering for Data Scientists by Matt Hoffman</a></li> <li><a href="">University of Washington's Software Engineering for Data Scientists</a></li> </ul> Data/Software Challenges as Tools for Hiring2020-07-26T00:00:00ZEric J. Maurn:uuid:2c9866da-ea09-3422-9e91-cb9f09c0604c<p.</p> <h2 id="what-are-data/software-challenges">What are data/software challenges?</h2><p>Data/software challenges are take-home interview assignments that are given a specific time frame to be completed.</p> <p>In the case of the three interns that I helped with hiring, two were for data science roles, and one was for a software engineering role. In all three cases, we gave them a one week time frame to complete the assigned challenge.</p> <p.</p> <p.</p> <p.)</p> <h2 id="what-were-you-looking-for">What were you looking for?</h2><p>I can speak more for the data challenge, as I designed it.</p> <p>To start, my data challenge borrowed ideas from the legend of <a href="">Van Halen’s Brown M&Ms</a>!</p> <p>Apart from that, I was looking for a candidate’s ability to write “good” code (refactored and documented at least), take care to make sure their notebooks are “readable”, and be able to “defend” in their prose their choice of problem <em>and</em>.</p> <h2 id="what-qualities-in-a-candidate-were-you-trying-to-infer-from-the-aforementioned-things-you-were-looking-out-for">What qualities in a candidate were you trying to infer from the aforementioned things you were looking out for?</h2><p>Primarily, this list:</p> <ul> <li>Meticulousness</li> <li>Empathy</li> <li>Logical rigor</li> <li>Creativity</li> </ul> <p>Meticulousness is most evident from their ability to pass the “Van Halen details” test.</p> <p>Creativity would show in their problem choice and choice of methods.</p> <p>Logical rigor would show up in how they defended their choices.</p> <p>Empathy shows up in the way they communicate, both written and oral.</p> <p>I am confident that these are non-controversial qualities to desire in colleagues.</p> <p>This next statement will possibly be controversial, but I hold it to be true: taken <em>holistically</em>, one can tell from <em>a presented pattern of good/bad behaviours</em>.</p> <h2 id="werent-the-expectations-a-bit-high-for-interns">Weren’t the expectations a bit high for interns?</h2><p.</p> <h2 id="were-the-data-challenges-effective">Were the data challenges effective?</h2><p>Subjectively, I would claim yes, but because I ended up working with these interns, I might clearly be biased.</p> <p.</p> <p>In one case, the intern we hired was the only plausible candidate available; the other candidate didn’t do the challenge.</p> <p.</p> <p>In all cases, I made sure to take the time to provide feedback to the candidates that we interviewed on-site. I remember <em>not</em>.</p> <h2 id="would-you-use-this-for-hiring-regular-colleagues">Would you use this for hiring regular colleagues?</h2><p>Possibly, though not always.</p> <p <em>absolute requirement</em>.</p> <p.)</p> <p.</p> <h2 id="how-should-a-hiring-team-approach-using-a-data-challenge">How should a hiring team approach using a data challenge?</h2><p?</p> <p.</p> <p>For a data scientist, I sense that "basic good software skills" are increasingly going to be important. That said, a data challenge is <em>not</em>.</p> <p.</p> <h2 id="how-should-a-candidate-approach-a-data-challenge">How should a candidate approach a data challenge?</h2><p:</p> <ul> <li>Programming skills</li> <li>Communication ability</li> <li>Visualization taste</li> </ul> <p>Be careful to see if there are Van Halen tests inside the data challenge. If there are, you may be unnecessarily disqualifying yourself.</p> <p.</p> <h2 id="conclusions">Conclusions</h2> <em>only</em> or <em>primary</em> tool relied on. When hiring, I we should be on the lookout for people with whom we holistically can work with and who also complement the local environment of the team. An ecosystem of hiring tools are needed.</p> Jupyter notebooks as scripts2020-07-11T00:00:00ZEric J. Maurn:uuid:c9dcdb8b-f48b-32f9-b151-12f6d1dcc3c4<p>If you're one of the types of programmers for whom a notebook interface helps with prototyping and scripting, it is possibly handy to treat notebooks as a script and execute them programmatically. There's multiple ways to do accomplish this.</p> <h2 id="nbconvert-to-python-script"><code>nbconvert</code> to Python script</h2><p>One way is to use <code>nbconvert</code> to convert your script into a Python script on the fly, and then execute the Python script itself:</p> <div class="hll"><pre><span></span>jupyter nbconvert --to python my_notebook.ipynb python my_notebook.py </pre></div> <h2 id="direct-programmatic-execution-of-a-jupyter-notebook">Direct programmatic execution of a Jupyter notebook</h2><p>This other way also uses <code>nbconvert</code>, but slightly differently in that we take advantage of <code>nbconvert</code>'s execution capabilities:</p> <div class="hll"><pre><span></span>jupyter nbconvert --to notebook --execute my_notebook.ipynb </pre></div> <p>By default, there is a timeout of 30 seconds, so if you need to specify a longer timeout than the default, you can do so:</p> <div class="hll"><pre><span></span>jupyter nbconvert --ExecutePreprocessor.timeout<span class="o">=</span><span class="m">1200</span> --to notebook --execute mynotebook.ipynb </pre></div> <p><code>1200</code> is in seconds, so that will give you a 20 minute execution timeout. With that said, you should ideally be ensuring that anything programmatically executed should execute quickly.</p> <h2 id="use-papermill">Use <code>papermill</code></h2><p>Papermill takes the notebook execution paradigm one level up, in that it allows you parameterize your notebooks. I haven't used it myself, so I won't provide a code sample, but I'll <a href="">link it here nonetheless</a>.</p> <h2 id="how-do-i-choose">How do I choose?</h2><p>There's really not much of a difference between the first two methods, so I'd encourage you to test-drive both and see which one you're more comfortable with.</p> <p>Personally, I would choose the first option. Even though it "feels" a bit more roundabout, it helps me because I don't have to remember the <code>ExecutePreprocessor</code> syntax (which can feel a bit clunky typing at the command line). That said, if you wrap everything inside a nice <code>Makefile</code>, this minor practical difference goes away.</p> <p>As for <code>papermill</code>, I see its utility for teams who don't necessarily yet have the software chops to make well-structured Python packages and scripts. It's a good hack <em>en route</em> to good practices, but at the end of the day, I'd choose "principled workflow over hacks" whenever practically possible. In the long-run, it makes a ton of sense for data science teams to equip themselves with software skills!</p> <h2 id="do-you-have-an-example">Do you have an example?</h2><p>Yes, indeed! For the <a href="">Network Analysis Made Simple</a> tutorial series that my co-author Mridul and I teach, I recently spent a bit of time figuring out how to convert our collection of Jupyter notebooks and markdown files, which get rendered in our <a href="">official tutorial website</a> as a <a href=""><code>mkdocs</code></a> site with a beautiful and functional <a href=""><code>mkdocs-material</code></a> theme, into leanpub-flavoured markdown that we then <a href="">publish as a book for offline viewing</a>. In doing so, we could preserve a single source of truth for the content, and automatically publish to two locations simultaneously.</p> <p>I needed the interactivity of a Jupyter notebook to prototype what I wanted to get done. I also wanted to use the notebook as the "gold standard" source of truth, rather than a Python script, as this would facilitate modifying and debugging later (i.e. I could execute up to a certain point and go deep). Thus, in the Travis CI script, we first convert the notebook to a Python script, then execute it, and also build the website:</p> <div class="hll"><pre><span></span><span class="nt">script</span><span class="p">:</span><span class="w"></span> <span class="w"> </span><span class="c1"># Build LeanPub files</span><span class="w"></span> <span class="w"> </span><span class="p p-Indicator">-</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">jupyter nbconvert --to python scripts/bookbuilder/markua.ipynb</span><span class="w"></span> <span class="w"> </span><span class="p p-Indicator">-</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">python scripts/bookbuilder/markua.py</span><span class="w"></span> <span class="w"> </span><span class="c1"># Build official website</span><span class="w"></span> <span class="w"> </span><span class="p p-Indicator">-</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">mkdocs build</span><span class="w"></span> </pre></div> <p>Finally, we get Travis to publish everything to the <code>leanpub</code> branch, which we never edit.</p> <div class="hll"><pre><span></span><span class="w"> </span><span class="c1"># Publish the LeanPub files</span><span class="w"></span> <span class="w"> </span><span class="p p-Indicator">-</span><span class="w"> </span><span class="nt">provider</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">pages</span><span class="w"></span> <span class="w"> </span><span class="nt">skip_cleanup</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">true</span><span class="w"></span> <span class="w"> </span><span class="nt">github_token</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">$GITHUB_TOKEN</span><span class="w"> </span><span class="c1"># Set in the settings page of your repository, as a secure variable</span><span class="w"></span> <span class="w"> </span><span class="nt">keep_history</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">false</span><span class="w"></span> <span class="w"> </span><span class="nt">on</span><span class="p">:</span><span class="w"></span> <span class="w"> </span><span class="nt">branch</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">master</span><span class="w"></span> <span class="w"> </span><span class="nt">target_branch</span><span class="p">:</span><span class="w"> </span><span class="l l-Scalar l-Scalar-Plain">leanpub</span><span class="w"></span> </pre></div> How I feel about Hey2020-06-29T00:00:00ZEric J. Maurn:uuid:1af5c112-deff-3ab6-bbb2-e142f47208b4<p><a href="hey.com">Hey</a> is a new email service by Basecamp. If you’re a techie type, you’ve probably heard of it via the Twitter world.</p> <p>I saw the demo by their CEO Jason Fried, and I was sold enough to write an email to their invite request address (<a href="mailto:iwant@hey.com">iwant@hey.com</a>).</p> <h2 id="my-likes">My likes</h2><p>Now that I’ve been trying it out for about a week, I wanted to share about my favourite features about Hey email that makes me ready to pay up for it.</p> <h3 id="batched-replies">Batched replies</h3><p>Hey gives us an interface that lets us set aside emails into a bucket that one can “Reply Later”. With any email open, we can mark it as an email to “Reply Later”, and assign it to the “Reply Later” stack.</p> <p>At a later time in the day, we can go into that stack, and hit the “Focus & Reply” button, which gives us another interface to go down the stack and respond to emails one by one.</p> <p>This makes so much more sense, because:</p> <ol> <li>It’s easier to give each email the attention that it needs,</li> <li>Without having to pass through the “Inbox” and being distracted by something else we “feel” we need to respond to (but don’t actually have to).</li> </ol> <h3 id="the-screener">The Screener</h3><p>The Screener is pretty rad. I can quickly screen emails into the appropriate buckets: The Imbox, The Feed, and The Papertrail. This helps reduce the amount of clutter that hits my eyes.</p> <p>The screening procedure is quite deterministic. There’s no fancy machine learning that goes on that attempts to stochastically move emails unexpectedly. Emails from important people, or important newsletters, get sent to the Imbox. (I get to decide what is important!) Other emails are sent out of sight, out of mind, until I feel ready to look at them as a collection.</p> <h3 id="functional-piles">Functional piles</h3><p>“Functional piles” is, by far, the biggest thing I’ve come to like about Hey. I’ve alluded to this above, but I thought I’d detail this a bit more.</p> <p>Hey gives us a functionally broad definition of “piles” of email:</p> <ul> <li>The Screening</li> <li>The Imbox</li> <li>The Papertrail</li> <li>The Feed</li> <li>The Set Aside Pile</li> <li>The Reply Later Pile</li> </ul> <p>What’s really cool about this functional definition is that:</p> <ol> <li>The definition is “functional”, in that it determines <em>what I do</em> with the email in a sane workflow.</li> <li>The definition is broad enough that I don’t have to think <em>too</em> hard about which pile it goes into.</li> </ol> <p>For example, “The Screening” pile is for all of the first-time emails in my Inbox, and all I have to decide is whether I might want to see that email later or not.</p> <p>As another example, the “Reply Later” pile lets me batch together emails that I might want to focus and reply to at one shot.</p> <p>The workflow feels <em>very</em> functional, and the user interaction design is definitely geared towards making sane the way we handle email.</p> <p>By contrast, in Gmail, I was paying for SaneBox to help me automatically triage my email for me, but even then, I couldn’t leisurely scroll through them because it was a separate service with a separate interface that made it difficult to work with.</p> <p>Also, Gmail never gave us the ability to screen out emails, neither did it give us the ability to set aside special piles to “reply to” later.</p> <p>I know I could have used Gmail tags to handle this, but dragging and dropping an email to a generic tag qualitatively <em>feels</em> different compared to hitting a button to send it to a pile that is still visible but not in my face.</p> <p>Finally, whenever an email is read, it gets moved from the top of the Imbox into the “read” pile. This is another one of those subtle designs that makes usage such a joy. There’s a feed of email below that I’ve seen once, but only the <em>truly</em> unread ones are still above. Having ingrained email habits for over 20 years, this takes a bit of getting used to, but once one is used to Hey’s design, one realizes how helpful it is for triaging and batching (i.e. “pretty good” email workflow).</p> <h3 id="forwarding-in">Forwarding in</h3><p>Any email service can do this, but yes, email forwarding is the way that we get emails ported over from our old addresses. Forwarding is the most straightforward (ahem!) way to get started with the service without needing to resort to emailing a ton of people.</p> <p>I still keep my old Gmail account around because I use it for the calendar scheduling story, and for Google Drive. It’s hard to part with an address I’ve had for a long time, but I’ve done migration off digital services before, and I know it just takes a bit of patience to finish.</p> <h2 id="concluding-thoughts">Concluding thoughts</h2><p>Perhaps my situation has become typical of the kind of user that Hey is trying to help: lots of emails, a small fraction being important, the others I might need to know.</p> <p>Yet again, good design is shown to matter - Hey makes “great workflow” front-and-center, whereas most email services don’t. This seemingly little workflow detail has a disproportionate impact on the quality of the service. Good design matters, and I’m happy to pay for it!</p> Statistical tests are just canned model comparisons2020-06-28T00:00:00ZEric J. Maurn:uuid:2351d28b-660a-3ade-84f7-399edc5a175e<p>I reached another statistics epiphany today.</p> <p>Statistical tests? They are nothing more than a comparison between statistical models that has been made canned.</p> <p>What do I mean?</p> <p>Let's say we have data for Korean men from both the North and the South. We could write a generative model for men's height that looks something like the following:</p> <p>$$h^n \sim N(\mu^{n}, \sigma^{n})$$</p> <p>$$h^s \sim N(\mu^{s}, \sigma^{s})$$</p> <p>(The superscripts don't refer to powers, but "north" and "south"; I was just having difficulty getting Markdown + LaTeX subscripts parsed correctly.)</p> <p>In effect, we have one data generating model per country.</p> <p>Think back to how you might analyze Korean male height data using canned statistical procedures. You might choose the t-test. In performing the t-test, we make some assumptions:</p> <ul> <li>The two populations have equal variance, and</li> <li>We are only interested in comparing the means.</li> </ul> <p>Yes, there are variations on the t-test, such as t-test with unequal variance and the likes, but I wonder how many of us would <em>really</em> think deep about the assumptions underlying the procedure when faced with data and a "canned protocol"? Instead, we'd simply ask, "is there a difference in the means?" And then calculate some convoluted p-value.</p> <p>How could we go beyond canned procedures and tell if the two populations have a difference? Well, we could compare their means, but we could also add another comparison of the variance too. All of this comes very naturally from thinking about the data generating story. Let's see this in action.</p> <p>In performing Bayesian inference, we would obtain posterior distributions for both the $\mu$ and $\sigma$ parameters of both models. We could then compare the $\mu$ and the $\sigma$ parameters, and they would both be informative.</p> <p>For example, if $\mu$s turned out to be different and their posteriors do not overlap, we would claim that the two populations differ in their average height, and explain it as being due to the nutritional difference arising from economic mismanagement.</p> <p>On the other hand, if the $\sigma$ turned out to be different and their posterios didn't overlap, we would claim that the two populations differ in their <em>variation in height</em>. How would we explain this? For example, if the distribution of North Korean heights was tighter giving rise to a smaller $\sigma$ value, we might explain this as being due to rationing and genetic homogeneity.</p> <p>In both comparisons, by thinking more precisely about the data generating process, we had access to a broader set of hypotheses. If we had defaulted to the t-test as a "canned statistical procedure", and not thought carefully about setting up a data generating model, we would be missing out on a rich world of inquiry into our data.</p> | https://ericmjl.github.io/blog.xml | CC-MAIN-2022-33 | refinedweb | 47,297 | 53.81 |
reduce_mean¶
- paddle.fluid.layers.nn. reduce_mean ( input, dim=None, keep_dim=False, name=None ) [source]
Warning: API “paddle.fluid.layers.nn.reduce_mean” is deprecated since 2.0.0, and will be removed in future versions. Please use “paddle.mean” instead.
Computes the mean of the input tensor’s elements along the given dimension.
- Args:
- input (Variable): The input variable which is a Tensor, the data type is float32,
float64, int32, int64.
- dim (list|int, optional): The dimension along which the mean is computed. If
None, compute the mean over all elements of
inputand return a variable with a single element, otherwise it must be in the range \([-rank(input), rank(input))\). If \(dim[i] < 0\), the dimension to reduce is \(rank(input) + dim[i]\).
- keep_dim (bool, optional): Whether to reserve the reduced dimension in the
output Tensor. The result tensor will have one fewer dimension than the
inputunless
keep_dimis true, default value is False.
- name(str, optional): The default value is None. Normally there is no need for
user to set this property. For more information, please refer to Name
- Returns:
Variable: Tensor, results of average on the specified dim of input tensor, it’s data type is the same as input’s Tensor.
- Raises:
TypeError, if out data type is different with the input data type.
- Examples:
import paddle.fluid as fluid # x is a Tensor variable with following elements: # [[0.2, 0.3, 0.5, 0.9] # [0.1, 0.2, 0.6, 0.7]] # Each example is followed by the corresponding output tensor. x = fluid.data(name='x', shape=[2, 4], dtype='float32') fluid.layers.reduce_mean(x) # [0.4375] fluid.layers.reduce_mean(x, dim=0) # [0.15, 0.25, 0.55, 0.8] fluid.layers.reduce_mean(x, dim=-1) # [0.475, 0.4] fluid.layers.reduce_mean(x, dim=1, keep_dim=True) # [[0.475], [0.4]] # y is a Tensor variable with shape [2, 2, 2] and elements as below: # [[[1.0, 2.0], [3.0, 4.0]], # [[5.0, 6.0], [7.0, 8.0]]] # Each example is followed by the corresponding output tensor. y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') fluid.layers.reduce_mean(y, dim=[1, 2]) # [2.5, 6.5] fluid.layers.reduce_mean(y, dim=[0, 1]) # [4.0, 5.0] | https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/fluid/layers/nn/reduce_mean_en.html | CC-MAIN-2021-31 | refinedweb | 379 | 52.05 |
Install Snowplow On The Google Cloud Platform
Last updated 18 Jan 2019: Added details about the free tier limitations, and showed how to avoid the Dataflow jobs auto-scaling out of control.
I’m (still) a huge fan of Snowplow Analytics. Their open-source, modular approach to DIY analytics pipelines has inspired me two write articles about them, and to host a meetup in Helsinki. In my previous Snowplow with Amazon Web Services guide, I walked you through setting up a Snowplow pipeline using Amazon Web Services. This time around, I’m looking at the wondrous Google Cloud Platform, for which Snowplow introduced support in an early 2018 release.
I won’t be offering a comprehensive comparison between GCP and AWS, nor will I walk you through every single possible customization you could do when firing up the instances and building the pipeline. Those are left for you to discover by yourself, or to consult a data engineer who can help you with scale.
In fact, the setup I’ll walk you through will be suboptimal in many places. It won’t be the most robust setup for a large flow of data through the pipeline, but what it will provide you is the comprehensive list of steps you need to make to get things running.
Note that Snowplow also offers their own Snowplow Insights service for setting up and managing the pipeline so that you can jump straight into data collection and analysis. I really recommend this service especially if you are unsure about how to set up the pipeline in an economical and scalable way. You might accrue a lot of extra costs if you don’t know how to scale the required resources to suit what you actually need for efficient analysis.
You can also follow the official Snowplow wiki, if you wish. The steps are similar to what I go through in this guide, though I do think this guide will be better suited for you in case you are unfamiliar with how GCP works.
Table of Contents
My Powerpoint visualization skills just get better and better each passing year!X
The Simmer Newsletter
Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox!
Word of warning
This probably won’t come as a surprise to you, but working with a cloud platform is not free of charge. If you’re a first-time user, you should be eligible for the free trial of $300 to be spent during the first 12 months. This is more than enough to build a pipeline and test it out over a number of days, but it won’t get you far.
UPDATE 18 Jan 2019: The free tier only gives you 8 CPUs total across your entire project. That means that you must keep count of all the instances you’ll be using for the collector and for the ETL machine. Start with a low number, e.g. 1 or 2 CPUs per instance to see how Snowplow works. Once you have the budget, you can shoot for more ambitious setups.
You’ll need to keep a close eye on the billing dashboard of your project. It helps you get an idea of how much cost you have factually accumulated to this day, and what the projected cost for the whole month will be.
What you’ll need
To follow this guide, you will need:
A Google account - something to log into Google services with, such as your Google Mail ID.
A credit card - you’ll need to enable billing in your Google Cloud account to fire up some of the services we need.
A custom domain name - this is optional, but it’s necessary if you want to set up the tracker as a secure HTTPS endpoint. Without a custom domain name, you’re forced to use HTTP only. You can get a cheap domain name from Google Domains. You might be able to set something up for free using Cloud Endpoints, but this guide will not cover this.
Good luck! Let me know in the comments if some part of this guide was particularly unclear.
First steps
Here we’ll setup the GCP project, make sure you have the necessary resources enabled, and we’ll also install the Google Cloud SDK so that you can interact with your project via your local terminal, too.
Step 1: Set up a new project
The first thing you’ll need to do is set up a new Google Cloud project.
(1) Browse to. Remember to login with the Google ID which you’ll use to manage this project. Click CREATE PROJECT.
If this is the first time you use GCP with this account, you might see an offer for free credit. Take it!
(2) Give the project a name.
For convenience, it might be good to change the Project ID to something more legible and easy to understand.
If you have Organizations and Locations (such as folders) set up for your Google Cloud account, choose the appropriate ones from the menu.
Also, if you already have a Billing Account set up, choose that as well from the respective drop-down menu.
Choose CREATE when you’re done.
After clicking the button, GCP will do some loading and spinning for a while, after which you should see your new project dashboard. If you don’t, make sure to select it from the project selector menu.
Congratulations! You’ve created the project.
Step 2: Enable Billing
You’ll need to create a billing account so that GCP can invoice you if necessary (sucks, I know).
(1) Browse to.
(2) Click Add billing account.
Here, follow the steps to add your credit card, or, if you’re eligible for the free trial, to activate your free trial.
Make sure you follow the prompts to link your Snowpow project to the Billing account you just created.
Step 3: Enable the required services
Next, you need to enable the services and APIs we’ll need to get started. These steps let you set up the collector. When you move to the enrich and BigQuery load steps, you’ll need to enable additional services.
(1) Browse to.
You should see a search bar, so start by searching for Compute Engine API and click the relevant result. We’ll need the Compute Engine to fire up our virtual machines on which the Snowplow collector will reside.
Upon entering the Compute Engine API page, simply click the blue ENABLE button at the top.
Once it’s done, you should see something like this where the Enable button used to be:
Now, follow these exact same steps for the Cloud Pub/Sub API. Pub/Sub (for Publisher/Subscriber) is a real-time message queue we’ll use to process the data fed into the Snowplow pipeline.
Once you’re done enabling these services, you’re ready to move onto the next step!
Step 4: Install the Google Cloud SDK
The next thing you’ll want to do is to install the Google Cloud SDK locally in your machine. It’s very convenient because it lets you access your GCP project from the command line, and it lets you test some of the services from your local machine rather than having to find the appropriate paths through the often confusing UI.
To install the SDK, follow the steps for your platform, starting from here.
Once you’ve installed the SDK, you should be able to run these commands in your terminal / shell:
$ gcloud auth login $ gcloud config set project PROJECT_ID
The first command logs you in with Google Cloud using the Google Account you choose in the web prompt. The second command points the current
gcloud setup to the project ID you’ll give (replace
PROJECT_ID with the ID you configured when you created the project). The end result should be something like this:
Step 5: Setup a service account
The final initialization step is to setup a service account. A service account is basically a Google Cloud account which has full access to your GCP services and resources. It’s a necessary step if you want to run services on GCP programmatically rather than with your own, personal Google account.
Note that when you enable Compute Engine API for your project, a Compute Engine default service account is created for you automatically. the steps below really only apply if you wanted to create a different service account for your pipeline.
(1) Browse to.
(2) Make sure you have the correct project selected in the project selector menu.
(3) Click the blue Create credentials selector, and choose Service account key from the menu.
Since you’ve enabled the Compute Engine API, you should be able to choose the default GCE service account from the drop-down.
Keep the JSON option selected, and choose Create.
The browser should automatically download the JSON file, so make sure you find it in your local files and store it securely.
At this point, it would be a good idea to create a local folder for this entire Snowplow experiment. In that local folder, you can store this service account key and any temporary configuration files you’ll work on, and other stuff such as executables and binaries you’ll eventually upload to the GCP, if necessary.
Once you’ve created the service account you are ready to move on. All the initial steps have now been completed, congratulations!
Setting up the Pub/Sub topics
Snowplow uses a collector as the endpoint of your tracker requests. This collector resides in a Compute Engine instance (a virtual machine, basically), and it processes the requests you send to the endpoint.
These requests are then published into Pub/Sub topics, from where they are then passed on further down the pipeline for enrichment and parsing. Pub/Sub is essentially a real-time messaging pipeline, which collects messages in topics, which are then available for subscriptions to access.
Make sure you check out Snowplow’s official wiki for more information on this part of the pipeline.
Step 1: Create the Pub/Sub topics
The first thing you’ll need to do is create topics in the Pub/Sub you’ve enabled for your project.
(1) Browse to.
(2) Make sure you have the correct project selected in the project selector.
(3) Click the blue Create a topic button.
(4) Type
good after the project path as in the screenshot below, and click CREATE.
(5) Click CREATE TOPIC and type
bad as the name of the new topic, and then click CREATE.
Snowplow uses these two topics to filter out hits and requests that validate (
good stream) and those that have issues and errors (
bad stream).
Step 2: Create a subscription (optional)
Next, you can create a subscription with which you can test the stream. This is optional, but might be a good idea if you want to see how the pipeline is working.
(6) Click the
good topic to enter its configuration page.
(7) Choose CREATE SUBSCRIPTION from the top navigation.
(8) Give the subscription a name (
test-good).
(9) Leave the other settings as they are, and click CREATE.
Now that you’ve created the Pub/Sub topics, it’s time to step into one of the more complicated steps of this guide: setting up the collector itself.
Create an HTTP endpoint with the Scala Stream Collector
Snowplow uses a collector written in Scala for processing the requests sent from your website. These records are parsed by the Scala Stream Collector and then distributed into the Pub/Sub topics you created in the previous chapter.
We’ll start with a simple HTTP endpoint using the default IP address assigned to the Compute Engine instance you’ll spin up. This is only to test that the whole pipeline works. You’ll want to configure your own custom domain name with an HTTPS endpoint for the actual tracker!
Step 1: Create the config file
In the local directory where you’re storing all your project files (such as the service account credentials you created earlier), create a new file named
application.config, and copy-paste the contents of this sample config within.
At this time, the only line you need to edit is the one with
googleProjectId = your-project-id. Change
your-project-id to your actual Google Cloud project ID.
Keep this file at hand, because you’ll need to make some changes to it soon.
Step 2: Fire up a GCE instance
You are now ready to start a Compute Engine instance.
NOTE! Because this is just a test - remember to shut down the instance as soon as you’re done so that you don’t accumulate extra costs.
(1) Browse to and make sure your project is selected in the project selector.
(2) Click Create.
Next, you’ll be transported to the configuration screen.
(3) Give the instance a name.
(4) Choose a region (somewhere close by, preferably) - you can use the default zone.
(5) Make sure the service account you’ve created (or the default Compute Engine service account) is selected in the relevant list.
(6) Choose Set access for each API from the scope selector.
(7) Scroll down the list of APIs, and choose Enabled for the Cloud Pub/Sub API.
(8) Scroll down to Firewall and check Allow HTTP traffic. Next, click the Management, security, disks, networking, sole tenancy link.
(9) Select the Networking tab, and type
collector into the Network tags field.
Once you’ve done these changes, click Create to fire up the instance!
Step 3: Create a firewall rule
You’ll need to create a firewall rule which accepts incoming connections from your website.
(1) Browse to and make sure the correct project is selected.
(2) Click CREATE FIREWALL RULE.
(3) In the configuration that opens, give the rule some name, e.g.
snowplow-firewall-rule.
(4) Scroll down to Target tags and type in the tag name you gave in the end of the previous step (
collector if you used my example).
(5) Make sure IP ranges is selected in the Source filter menu, and type
0.0.0.0/0 into the Source IP ranges field.
(6) Under Protocols and ports, check tcp and type
8080 as the port value.
When ready, click Create to finalize the firewall setup.
Step 4: Create a storage bucket for your configuration file
Next thing you’ll need to do is upload the configuration file for the collector into a Cloud Storage bucket. This is because the file needs to be available for your instance to use, and it’s extremely convenient to have the file available in Google Cloud, because the service account can simply pull the file directly from the bucket.
(1) Browse to, and, as always, make sure you have the right project selected before clicking Create bucket.
(2) Give the bucket a descriptive (and unique) name, such as
snowplow-yourname-collector-bucket.
(3) You can leave the rest of the settings with their default values, then click Create.
(4) In the view that opens up, click Upload files, find the
application.config file you downloaded earlier, and upload it to the bucket.
Good job! You are now ready to connect your GCE instance and fire up the collector!
Step 5: SSH into the Compute Engine instance
Now that you have the virtual machine running in the cloud, and you have the configuration file uploaded to a Cloud Storage bucket, the next step is to connect to the virtual machine, download all the remaining files, and start the collector.
It’s very simple and trivial to do the following steps using the Google Cloud SDK on your local machine, too. If you want to try it out, follow the relevant steps in Snowplow’s wiki.
(1) Browse to.
(2) Click the SSH option next to your instance.
(3) Visit and find the file that starts with
snowplow_scala_stream_collector_google_pubsub_ and check what the latest version number is that doesn’t have the
rcl suffix. Make note of this version number (e.g.
0.14.0), no need to download the file.
(4) Next, in the SSH window, run the following commands in order, pressing enter after each command.
$ sudo apt-get update $ sudo apt-get -y install default-jre $ sudo apt-get -y install unzip $ wget<VERSION>.zip $ gsutil cp gs://<YOUR-BUCKET-NAME>/application.conf . $ unzip snowplow_scala_stream_collector_google_pubsub_<VERSION>.zip $ java -jar snowplow-stream-collector-google-pubsub-<VERSION>.jar --config application.conf
Replace all instances of
<VERSION> with the latest version of the collector ZIP file which you checked in (3).
Replace
<YOUR-BUCKET-NAME> with the name you gave the cloud storage bucket in the previous step (e.g.
snowplow-yourname-collector-bucket).
After running the last command, if all has been configured correctly, you should see the following output in the instance shell:
You are now ready to send a test request to the endpoint, after which you can check your Pub/Sub subscription if it received the message!
Step 6: Send a test request and verify it was published into Pub/Sub
To send the request, you’ll first need to check what the external IP of your Cloud instance is.
(1) Browse to and click the Snowplow instance name.
(2) Copy the IP address from the External IP field.
The next step requires you to send an HTTP POST request with a specific payload to this IP endpoint. There are many ways to do it - you could use the JavaScript console of the web browser, for example.
My preference for testing HTTP endpoints quickly is to use curl, which is a command-line tool available in almost any terminal. If you’re using an operating system that doesn’t come equipped with curl, I recommend downloading and installing it from here.
(3) Open the terminal on your local machine, and copy-paste the following command, switching
<EXTERNAL_IP> with the actual external IP you copied from the GCE instance settings.
$ curl -d "&e=pv&page=curl-test&url=http%3A%2F%2Fjust-testing.com&aid=snowplow-test" -X POST http://<EXTERNAL_IP>:8080/com.snowplowanalytics.iglu/v1
The payload is very simple - it basically has only four parameters:
The endpoint is suffixed with
/com.snowplowanalytics.iglu/v1 to denote the schema you’ll be using for processing and validating the incoming data. Since we’re working with the most out-of-the-box solution available for testing purposes, you can use this default schema for now.
Later, we’ll use the Google Analytics plugin to simplify things and to send a more complete payload, but for the purposes of testing this will do.
(4) If everything worked, you should see a status code OK as a response.
Now you can test if your record was published in the
good Pub/Sub topic. To test this, you need to pull the recent records from the topic by using the subscription you created earlier. The easiest way to do this is by using the Google Cloud SDK that you should now have installed and configured on your local machine.
(5) The command you’ll need to use is:
$ gcloud pubsub subscriptions pull --auto-ack test-good
Where
test-good is the name you gave to the subscription when you created it. If it worked, you should see the following output:
Don’t worry about the fact that it looks all garbled. This is the request stored in binary Thrift format. You should see all sorts of interesting bits and pieces such as your local machine IP address, the User-Agent string (just
curl for now), and the data payload itself. If you see all this in the
good Pub/Sub topic, it means everything is working!
You have now successfully created a collector behind an HTTP endpoint. You could proceed to the enrichment stage, but I urge you to first stop the GCE instance so you don’t accumulate extra costs for having it running.
I also recommend you continue with the next chapter, where you’ll learn how to use your own custom domain as an HTTPS-secured endpoint for the collector. Using HTTP is crippling, and you can’t really create a production-ready endpoint with a single GCE instance behind the HTTP protocol.
Create an HTTPS endpoint with a custom domain name
This step replaces the previous chapter, effectively. Instead of using an ephemeral, external IP behind the HTTP protocol, we’ll assign a static IP address to our virtual machine instance. On top of that, we’ll configure a custom domain name to point to this static IP, and we’ll have everything work behind the HTTPS protocol.
You’ll still want to read the previous chapter, though. We’ll be doing a lot of similar things here.
IMPORTANT! If you want to skip reading the previous chapter, then please note that you must do steps (1) and (4) from the previous chapter before moving on with the HTTPS endpoint.
This is, basically, what the final collector product should look like. You’re using a load balancing system to automatically scale the instances with incoming traffic, AND you’ll be able to avoid pesky cross-protocol errors due to using HTTPS as the sole endpoint. There’s the added security, too.
Step 1: Create an instance template
Instead of working with a single GCE instance, we’ll use a cluster of instances that will be scaled up and down automatically with traffic. This will, naturally, reflect on the cost structure of your monthly GCP invoices, so keep an eye on the estimated charges in your dashboard.
(1) If you followed the previous chapter, you can go ahead and delete the GCE instance and the Firewall Rule. You’ll start from scratch here.
(2) You can keep the
application.conf file as it is in the storage bucket. The same settings you used in the previous chapter apply here.
(3) Go to and click Create instance template.
The instance template is what each new virtual machine will use as its “template”, meaning it will inherit the settings from this template as well as the startup script that will fire up the collector itself.
The steps for the instance template are almost the same as for a single GCE instance from the previous chapter, but let’s go over them anyway.
(4) Give a descriptive name for the instance.
(5) Make sure the default Compute Engine service account is selected.
(6) Choose Set access for each API in the Access Scopes list.
(7) Scroll down the list to Cloud Pub/Sub and choose Enable.
(8) Under Firewall, select Allow HTTP traffic.
(9) Expand the Management, security, disks, networking, sole tenancy accordion.
(10) Scroll down to Startup script, and copy-paste the following code within:
#! /bin/bash sudo apt-get update sudo apt-get -y install default-jre sudo apt-get -y install unzip archive=snowplow_scala_stream_collector_google_pubsub_<VERSION>.zip wget gsutil cp gs://<YOUR-BUCKET-NAME>/application.conf . unzip $archive java -jar snowplow-stream-collector-google-pubsub-<VERSION>.jar --config application.conf &
(11) Edit the two instances of
<VERSION> with the latest version number you can find for the
snowplow_scala_stream_collector_google_pubsub_ prefix here (don’t use the version with the
_rcl prefix). At the time of writing, the latest version was
0.14.0.
(12) Replace
<YOUR-BUCKET-NAME> with the name of the Cloud Storage bucket that stores the
application.conf file.
This startup script is run whenever a new instance is built with this template. It loads all the dependencies and the runs the collector Java file.
(13) Click open the Networking tab, scroll to Network tags, and add
collector as a tag.
(14) Click Create when done.
Step 2: Create a firewall rule
You’ll need to create a Firewall rule to allow external connections to your GCE instances.
(1) Browse to, and click CREATE FIREWALL RULE.
(2) Give the rule a name.
(3) Scroll down to Target tags, and type
collector in the field.
(4) In Source IP ranges, type
0.0.0.0/0.
(5) Check the box next to TCP in the Protocols and ports selection (with Specified protocols and ports selected), and type in
8080.
(6) Click Create when ready.
Step 2: Create an instance group
Next, we’ll need to create an instance group, which is used by the load balancer as the backend service.
(1) Scroll to, and click Create instance group.
(2) Give the group a descriptive name.
(3) Feel free to set the Location closer to home, if you wish.
(4) Select the instance template you created in the previous step from the Instance template selector.
UPDATE 18 Jan 2019: You can also set Autoscaling
Off. This means that the instance will not generate new machines automatically. You can start off with this, and then move to an autoscaling setup if you find the Collector lagging behind a lot.
(5) Scroll down to Health check, click the menu, and select Create a health check.
(6) Set the following options:
- Name: a descriptive name
- Protocol: HTTP
- Port: 8080
- Request path: /health
- Check interval: 10 seconds
- Unhealthy threshold: 3 consecutive failures
You can leave the rest of the settings to their default values.
(7) Click Save and continue once finished with the health check settings.
(8) Click Create to finish creating the instance group.
Once you create the group, you should see it loading for a while, after which you will see that the group has been created and a new instance has already been fired up!
At this point, you can quickly test if the instance is working.
(9) Browse to, and copy the IP address from the External IP field next to the instance created from your instance group.
(10) Open your terminal software and run the following command:
$ curl http://<EXTERNAL_IP_HERE>:8080/health
Replace
<EXTERNAL_IP_HERE> with the IP address you copied.
You should see a
OK message as the response.
Next, try:
$ curl http://<EXTERNAL_IP_HERE>:8080/i
You should see a garbled GIF response (something like
GIF89a????!?,D;).
If you see those two, your instance is working, and you’ve successfully created an HTTP endpoint.
Huh? That’s exactly what you did in the previous chapter!
But by using Instance groups you are now ready for the biggest step here: creating a load balancer.
Step 3: Create a load balancer
The purpose of the load balancer is to automatically scale your system up and down, depending on things like traffic spikes and CPU usage. It works by establishing a single IP address in the public-facing internet, which then tunnels/proxies the traffic to all the necessary internal IP addresses (your GCE instances, basically), without the outside world knowing this.
The other benefit of the load balancer is that we can use it to assign a static IP address to the balancer, and with a static IP we can apply our custom domain name so that a Google-managed SSL certificate can be applied to the endpoint.
So, there’s a lot of stuff in this step, pay attention!
(1) Browse to, and click Create load balancer.
(2) Click Start configuration in the HTTP(S) Load Balancing panel.
(3) Give the load balancer a name, click Backend configuration, then Create or select backend services & backend buckets, then choose Backend services -> Create a backend service.
(4) Give the backend service a name.
(5) Leave all the other settings to their default values, but choose the Instance group you created earlier from the respective menu. Set
8080 in the Port numbers field, and select the Health check you’ve also created earlier in the Health check menu.
(6) Click Create when ready.
(7) Click open Host and path rules, and make sure the backend service you created is visible in the rule.
(8) Next, click Frontend configuration.
(9) Give the frontend service a name.
(10) Choose HTTPS as the Protocol.
(11) Select the IP Address list, and click create IP address.
(12) Choose a name for the IP address and click RESERVE.
(13) Make sure the new IP address is selected in the frontend configuration, and copy the IP address to a text editor or something. You’ll need it when configuring the DNS of your custom domain name!
(14) Make sure
443 is set as the Port.
(15) In the Certificates menu, choose Create a new certificate.
(16) Give the new certificate a name.
(17) Choose Create Google-managed certificate.
(18) Type the name of the domain you will set to point to your collector in the Domains field.
(19) When ready, click Create.
(20) When finished with the frontend configuration, click Done.
(21) Click Review and finalize to see all the changes. You’ll probably see that your certificate is still in the
PROVISIONING status, because you haven’t updated your domain DNS yet.
(22) When satisfied, click Create to create the load balancer.
Step 4: Configure your DNS
At this point, you need to go to your DNS settings for the custom domain name you want to point to your load balancing collector.
You need to create an
A record for the domain name, which points to the static IP address you created for the load balancer frontend above. You can set the
TTL to something like 600 seconds to see the change quicker.
This is what it would look like in GoDaddy.
Once you’ve configured the DNS, it will take a while for the new name to resolve. You can check what the status is by running this in your terminal:
$ host tracker.gtmtools.com
Replace
tracker.gtmtools.com with the domain name you configured in the DNS. If it works, you should see a response with the IP address you configured.
Step 5: Testing everything
Once you’ve configured the domain name and it resolves to the correct IP, you might still need to wait a while for the SSL certificate to be provisioned for the domain name. This might take anywhere from a couple of minutes to some hours, so be patient.
You can check the status of your system by browsing to the load balancer list and clicking the load balancer you created.
The frontend should show a green checkmark next to your certificate name to indicate that the certificate has been assigned.
In the backend service, you should see one healthy instance created.
If all is fine, the next step is to test the endpoint itself. Open the terminal and run the following command:
$ curl -d "&e=pv&page=https-test&url=https%3A%2F%2Fjust-testing.com&aid=snowplow-test" -X POST https://<CUSTOM_DOMAIN>/com.snowplowanalytics.iglu/v1
Replace
<CUSTOM_DOMAIN> with the domain name you’ve configured to point to the load balancer.
If it worked, you should see an
OK response.
Next, you can try and retrieve the payload from the Pub/Sub topic with:
$ gcloud pubsub subscriptions pull --auto-ack test-good
You should see something like this as the response:
If you see that, then congratulations, you now have an HTTPS endpoint for your collector!
If something’s wrong, then you’ll need to start narrowing down where the problem is. Check your Google Compute Engine pages, make sure there’s a healthy GCE instance running. You can even SSH into the instance, browse to the
/var/log/ directory, and open the
daemon.log file for editing to see if there was a problem with the startup script.
Other than that, it’s very difficult to say what the likely source of the problem is. Personally, I made many mistakes initially with port configurations and setting up the individual components. But if you follow this guide to the letter, you should be fine.
Sometimes the problem is that you just need to wait for the DNS to resolve and the certificate to be assigned to the new domain name. This might take a while.
Next up, enrichment and loading the data into BigQuery!
Note! If you’re going to take a break now, remember to STOP your GCE instance. You can always restart it when ready to go on. You don’t want to accumulate any unwanted costs from having the instance running for no purpose!
Set up the Google Analytics tracker
Before we go on to enrichment, now is a good time to set up the tracker. For this purpose, we’ll be using the Snowplow Google Analytics plugin, because it’s an easy way to leverage existing tracking on your site. If you want, feel free to use the regular Snowplow JavaScript tracker.
To begin with, head on over to my customTask Builder Tool.
(1) Click the option labelled
Copy Hits to Snowplow Collector Endpoint.
(2) Click Copy to clipboard.
(3) Next, in Google Tag Manager, create a new Custom JavaScript variable, and paste the contents of the clipboard there.
(4) In the beginning of the code block, remove
var _customTask = , so that the first characters of the block are
function() {.
(5) In the end of the block, remove the semicolon that is the very last character of the block.
(6) Edit the line starting with
var snowplowEndpoint = '...'; so that the string contains the URL to your collector endpoint.
(7) Save the variable with some name, e.g.
JS - Snowplow duplicator.
(8) Next, open your Page View tag, check Enable overriding settings in this tag, scroll down to More Settings > Fields to set, and add a new field:
Field name: customTask
Value: {{JS - Snowplow duplicator}}
That’s it for the tracker. The way it works now is that whenever your Page View tag fires, it will copy the payload to the Snowplow collector endpoint.
If you want, you can publish your container now, after which every visitor to your website will start sending those Page Views to your collector. However, I recommend you use Preview mode for now, so that only your Page Views are sent to the collector.
Once the pipeline is up and running, you can start collecting more comprehensive data from your visitors.
Prepare the ETL step
Before moving forward to the extract, transform, and load (ETL) of your collector data, we’ll need to do some preparations.
Step 1: Enable the Dataflow API
The enrichment process and the BigQuery loader require a new service to be enabled.
(1) Browse to the API library.
(2) Search for
dataflow, and click the Dataflow API selector.
Cloud Dataflow lets you enrich a data stream with minimal latency. This is exactly what we need. We need the enricher to pull in events for the Pub/Sub topic to which the collector writes them, enrich and shred them to proper format, and write them back into a Pub/Sub topic for BigQuery loading.
(3) Click the ENABLE button in the API page to enable this service.
Step 2: Create the necessary Pub/Sub topics and subscriptions
By now, you should have two Pub/Sub topics,
good and
bad for hits processed by your collector.
We’ll need to create a bunch of additional topics and subscriptions for the remaining steps of the pipeline.
(1) Browse to.
(2) Click open the
good topic, and click Create Subscription. Give the subscription the name
good-sub.
(3) Next, create the following topics:
bq-bad-rows
bq-failed-inserts
bq-types
enriched-bad
enriched-good
(4) Then, click open
bq-types and create a new subscription for it named
bq-types-sub.
(5) Finally, click open
enriched-good and create a new subscription for it named
enriched-good-sub.
This is what the topic list should look like:
This is what the subscription list should look like:
You can, of course, create additional subscriptions for testing and debugging, but these are what the following steps of the pipeline specifically need.
Step 3: Create a new storage bucket for temporary files
You’ll need to create a new storage bucket for temporary files created by the enrichment process. But this is a good place to also store some files required by the enrich and load stages.
(1) Browse to.
(2) Click CREATE BUCKET and create a new bucket with the name
snowplow-yourname-temp like so:
(3) Click into that bucket and click Create folder, and name the new folder
temp-files:
Step 4: Create the iglu_resolver.json configuration
Snowplow uses something called resolvers to automatically identify the parameters of each incoming hit. This is necessary for many reasons, the main being hit validation (to identify valid requests from invalid ones), for enriching and shredding the hits to the proper data format, and for mutating and loading the data into BigQuery tables.
(1) Download the
iglu_resolver.json file from here and open it for editing.
(2) Change the two
vendorPrefixes parameters to also include the Google Analytics namespace (Note! You don’t have to do this if you’re using the vanilla Snowplow JavaScript tracker).
(3) Save the file locally.
(4) Browse to, click open the temporary file bucket you just created, and upload the modified
iglu_resolver.json to the root of that bucket (so not in the
temp-files folder).
With this resolver configuration, you’re instructing the enricher and loader that hits using the Google Analytics namespace might be coming in.
Step 5: Create a new BigQuery dataset
Before moving on, you’ll need to create a new dataset in BigQuery that will hold the table where your data will end up.
(1) Browse to, and choose your project from the selector to the left. Click CREATE DATASET.
(2) Give the dataset an ID, such as
snowplow_yourname_dataset, and click Create dataset.
NOTE! At this point you might want to just create a new table manually and partition that table on the
derived_tstamp column. This way the BigQuery table is automatically partitioned by date of the hit, making it easier to manage and query by date.
This guide proceeds without creating a partitioned table just so that you can see how the mutator works.
Step 6: Create the BigQuery configuration file
(1) Open a new file for editing in a plain text editor.
(2) Copy-paste the following within:
{ "schema": "iglu:com.snowplowanalytics.snowplow.storage/bigquery_config/jsonschema/1-0-0", "data": { "name": "Snowplow Page View Data", "id": "<Random UUID>", "projectId": "<Your GCP project name>", "datasetId": "<The BigQuery dataset ID>", "tableId": "pageviews", "input": "enriched-good-sub", "typesTopic": "bq-types", "typesSubscription": "bq-types-sub", "badRows": "bq-bad-rows", "failedInserts": "bq-failed-inserts", "load": { "mode": "STREAMING_INSERTS", "retry": false }, "purpose": "ENRICHED_EVENTS" } }
(3) Change the value of
"id" to a random UUID which you can generate here. A valid value would be e.g.
"3a27d47f-aeaf-4034-84b6-b1e82ca711d6".
(4) Change the value of
"projectId" to your GCP project ID (e.g.
"snowplow-production-simoahava").
(5) Change the value of
"datasetId" to the ID you just gave your BigQuery dataset, e.g.
"snowplow_simoahava_dataset".
(6) Make sure the Pub/Sub topic and subscription names correspond with those you created earlier in this chapter.
(7) Save the file locally as
bigquery_config.json.
(8) Upload it to the temporary file bucket, where you already uploaded
iglu_resolver.json to:
PHEW! That’s all the prep work done. Now you’ll need to just get the enricher and the BQ loader up and running in a new virtual instance group!
Finalize the ETL process
For ETL (extraction, transformation, and loading of your collector data), we’ll create a new instance template for an auto-scaling instance group.
You could use the same instance group as your collector, but this is not a sustainable way to run the pipeline, because the data streams from your site to the collector, from your collector to the enricher, and from the enriched stream to the BigQuery loader are vastly asymmetrical.
It will lead to a lot of redundancy and overhead if you have all your eggs in one basket.
Optimally, you’d run the enrichment and the BQ loader in their own groups, too, but for the sake of this exercise I’ll bunch them together for now.
Step 1: Create the instance template
Since you’ve done all the preparations in the previous chapter, this final step of the ETL is actually pretty simple. All you’ll need to do is create the instance template and fire an instance group off of it.
Well, it’s simple to you. It took me hours and hours and hours to get the thing working, so you’re welcome!
(1) Browse to, and click CREATE INSTANCE TEMPLATE.
(2) Give the template a name, e.g.
snowplow-etl-template.
(3) Make sure the Compute Engine default service account is selected, and choose Set access for each API in the Access scopes list.
(4) Change the following API scopes:
- BigQuery: Enabled
- Cloud Pub/Sub: Enabled
- Compute Engine: Read Write
- Storage: Read Write
Leave the other options with their default values.
(5) Scroll down and click the Management, security, disks, networking, sole tenancy accordion heading.
(6) Under Automation, copy-paste the following code into Startup script:
#! /bin/bash enrich_version="0.1.0" bq_version="0.1.0" bucket_name="<cloud storage bucket name>" project_id="<gcp project id>" region="<region where to run the dataflow instances>" sudo apt-get update sudo apt-get -y install default-jre sudo apt-get -y install unzip wget unzip snowplow_beam_enrich_$enrich_version.zip wget unzip snowplow_bigquery_loader_$bq_version.zip wget unzip snowplow_bigquery_mutator_$bq_version.zip gsutil cp gs://$bucket_name/iglu_resolver.json . gsutil cp gs://$bucket_name/bigquery_config.json . ./beam-enrich-$enrich_version/bin/beam-enrich --runner=DataFlowRunner --project=$project_id --streaming=true --region=$region --gcpTempLocation=gs://$bucket_name/temp-files --job-name=beam-enrich --raw=projects/$project_id/subscriptions/good-sub --enriched=projects/$project_id/topics/enriched-good --bad=projects/$project_id/topics/enriched-bad --resolver=iglu_resolver.json ./snowplow-bigquery-mutator-$bq_version/bin/snowplow-bigquery-mutator create --config $(cat bigquery_config.json | base64 -w 0) --resolver $(cat iglu_resolver.json | base64 -w 0) ./snowplow-bigquery-mutator-$bq_version/bin/snowplow-bigquery-mutator listen --config $(cat bigquery_config.json | base64 -w 0) --resolver $(cat iglu_resolver.json | base64 -w 0) & ./snowplow-bigquery-loader-$bq_version/bin/snowplow-bigquery-loader --config=$(cat bigquery_config.json | base64 -w 0) --resolver=$(cat iglu_resolver.json | base64 -w 0) --runner=DataFlowRunner --project=$project_id --region=$region --gcpTempLocation=gs://$bucket_name/temp-files
UPDATE 18 Jan 2019.
It might be wise to start off by capping the auto-scaling of the Dataflow jobs. Otherwise, since you’re working with streaming inserts, you might end up with lots and lots of virtual machines being started to support the hit stream.
To prevent the
loader from auto-scaling out of control, you can cap the number of available workers at e.g. 3 (so max. 3 CPUs are used by the job), or you can turn off auto-scaling altogether by capping the worker number at
1.
To set the maximum of 3 workers to the loader, add this to the end of the
snowplow-bigquery-loader command:
--maxNumWorkers=3
Setting the maximum to 1 will lead to a single-worker, non-autoscaling setup. To have more than one worker but no autoscaling, you’ll also need to add the option
--autoscalingAlgorithm=NONE to the loader.
You’ll need to populate the five variables in the beginning of the code block before saving the instance template.
enrich_version: Get the latest Beam Enrich version number from here.
bq_version: Get the latest BigQuery Loader version number from here.
bucket_name: Type the name of the storage bucket for temporary files you created earlier.
project_id: Type your GCE project ID.
region: Choose a region for the Dataflow instances to run in (you need to choose from this list).
Once you’ve made the changes to the startup script, click Create.
Step 2: Start up a new instance group
Now that you have the template created, it’s time to create and start an auto-scaling instance group using this template. The idea is that when requests start flooding in, you’ll want to fire up new instances for your enrichment and loading steps so that your data collection won’t be impacted too severely by latency.
UPDATE 18 Jan 2019: Instead of creating an auto-scaling instance group, it’s more than enough to just use a single machine in the group to handle the Dataflow! This part of the guide was originally based on some misinformation. You can still go ahead with the instance template, but once we reach the section about the instance group, please read the steps carefully.
(1) While still in the instance template list, click open the template you just created.
(2) In the top of the page, click CREATE INSTANCE GROUP.
(3) Give the new group a descriptive name, such as
snowplow-etl-group.
(4) Choose a region, e.g.
europe-west1.
(5) Make sure the instance template you just created is selected in the Instance template menu.
UPDATE 18 Jan 2019: You can set Autoscaling
Off. The machine starting the Dataflow jobs does not need to autoscale. The Dataflow jobs are the ones that will require more power depending on the throughput rate, but you can start this machine with one static instance, scaling up manually if necessary.
(6) You can keep the rest of the options with their default values, but if you like, you can set the health check to what you use for the collector instance, too.
When ready, click Create.
Test everything
When you create the instance group, it runs the startup script from beginning to end. These are the steps it takes, in order:
Beam Enrich is started as a new Dataflow job, using
iglu_resolver.jsonfor configuration. The Dataflow job essentially starts a new GCE instance group for the job.
The BigQuery Mutator is run with the
createcommand, and this creates the
pageviewstable with a simple atomic structure in your BigQuery dataset.
The Mutator is next run in its own thread with the
listencommand. This is basically a Java program which listens for incoming, enriched requests being populated in the
enriched-goodPub/Sub topic. Each request is parsed for values and data types, and if the
pageviewstable in BigQuery doesn’t have a corresponding column for some value in the request (validated against a schema resolved by the Iglu Resolver), a new column is created.
Finally, the BigQuery Loader starts up as its own Dataflow GCE instance, and this will load your enriched data into the corresponding columns and rows in your BigQuery table.
Before starting the debugging, make sure you’re sending some hits from your site to the collector. So browse around, visit different pages, and check the network requests to make sure the requests to your collector are completing successfully.
Step 1: Check that Beam Enrich is running
To check if Beam Enrich is running, go to the Dataflow job list. You should see
beam-enrich in the list with the status Running.
Step 2: Check that the mutator created the table
To check if the mutator’s
create command worked, go to your BigQuery dataset, and expand it. You should see a table named
pageviews under it, and the table should be populated with a number of columns, such as
app_id,
etl_tstamp, etc. These columns are the “default” atomic data columns Snowplow uses.
Step 3: Check that the mutator creates additional columns where necessary
Since you are collecting data with the Google Analytics tracker, you should shortly see a bunch of new columns added to the table description.
Step 4: Check that the BigQuery loader Dataflow job started
Visit the Dataflow job list again. You should see something like
main-root-XXXXX-YYYYY in the list with the status Running.
Step 5: Check that data is flowing into your BigQuery table
Visit your BigQuery dataset/table again, and select the
pageviews table.
In the Query editor, type the following query and press Run query:
SELECT * FROM `your_dataset_name.pageviews`
Where
your_dataset_name should be replaced with the name of your dataset. You should see a bunch of results returned after the query is complete.
Troubleshooting
You can visit the VM instances list and SSH directly into the ETL instance.
There, you can visit
/var/log/, and open the file
daemon.log for editing with e.g.
$ pico /var/log/daemon.log
It’s a full log of the the instance’s processes. You’ll need to run through the log and see where the error is.
There are many things that might have gone wrong, but the most common (in my own experience) are:
Incorrect access scopes in the instance template - double-check here.
Typo in
iglu_resolver.jsonor
bigquery_config.json, or forgot to add them to the correct cloud storage bucket - double-check resolver here and BigQuery config here.
Typo in the startup script - double-check here.
Collector not running - double-check here.
Impatience - wait 10-15 minutes before trying all the steps above again. It’s possible you’re just too hasty and the virtual machine instance hasn’t started up properly yet.
Final thoughts
It’s a long guide, but I still worry if it’s detailed enough. I’m a bit ashamed at not being able to tell you exactly how you should scale and group your instances, or how you should optimize your load balancing system. But these are things you need to experiment with by yourself, or with the help of a seasoned data engineer. Remember that you can also utilize the Snowplow Insights service to help you set things up and manage the pipeline!
I very much prefer the GCP user interface over AWS - there’s a flow to things, and related resources are grouped and linked together in a logical way. It makes moving from one service to another much smoother.
Setting up the pipeline is fun (if you’re into that kind of thing), but it does result in a huge data table full of columns and rows of often undecipherable data. One thing I tend to forget is that the real work begins after the pipeline is created. Making sense of the data requires, at the very least, visualization in a tool such as Data Studio, but you might want to look at what Snowplow has to say about data modelling, too.
I think Snowplow’s done an impressive job of making it possible create your own analytics pipeline with a fairly manageable cost. There are things that could have been done far more smoothly, such as utilizing Docker containers offered by Snowplow.
There are many moving parts in the pipeline. For me, personally, the race between different services enriching, shredding, mutating, and loading each incoming request is still a bit of a mystery. Snowplow has services (such as the BigQuery forwarder) that handle these problems, but setting it up was beyond the scope of this guide.
There’s also the whole world of enrichments that I deliberately skipped. It’s painful to see the columns for e.g. geographical data showing
null, but I’ll leave those for another guide.
One thing to note is that you should keep a keen eye on projected and actualized costs. Once you’ve managed to build the pipeline itself, your next job as a data engineer is to look for optimization opportunities. With a scalable cloud infrastructure, it’s important to understand the often strenuous relationship between latency, scale, and cost.
I hope this guide has been useful. I also hope it doesn’t become outdated too soon.
Huge thanks to Snowplow for providing me with help and resources throughout writing this guide. I’m especially grateful to Yali Sassoon and Joao Luis for their support. | https://www.simoahava.com/analytics/install-snowplow-on-the-google-cloud-platform/ | CC-MAIN-2022-05 | refinedweb | 8,595 | 63.39 |
hi im using OpenCL on a GPU (data para.) the kernel that i run has a very long for loop (i <= 99999999) All kernels will eventually find the answer and return (exit) from the loop but one kernel will always find the answer sooner than the others. So I want a way to have one kernel signal the other kernels to stop (break from the loop) and return. I currently do this using a global variable that all kernels check from within the loop. so the first kernel that finds the answer sets the global flag to true and all other kernels read the flag, break from the loop, and returns. This gave me a BIG speed increase. However, I would simply like a way to have one kernel signal all other kernels that something has happened so i can use it to have all the other kernels break and return. Is there a way that one kernel can signal all other kernels?
Thanks | https://community.khronos.org/t/how-to-have-one-kernel-signal-all-other-kernels-to-return/2318 | CC-MAIN-2022-40 | refinedweb | 164 | 76.05 |
(8)
Rahul Bansal)
Rizwan Ali(2)
Arunava Bhattacharjee(2)
Pankaj Lohani(2)
Kailash Chandra Behera)bbiajeev Ranjan(1)
Manish Kumar Choudhary)
Mohit Sharma)
Mahesh Alle(1)
Vinod Kumar(1)
Amalendu Dey(1)
Arpit Jain(1)
Pawan Pandey(1)
Burak Seyhan(1)
Resources
No resource.
Dynamic Query Using LINQ
Sep 28, 2014.
This article explains how to create a dynamic query in LINQ...
Regular Expression in PHP
Sep 30, 2013.
Regular expression is very useful for validation or pattern matching.
C# Corner Delhi Chapter Meet, 21 September, 2013: Official Recap
Sep 23, 2013.
The C# Corner Delhi Chapter organized its monthly event at MCN Solutions Pvt. Ltd. It was another very successful session.
Finding Directories With Regular Expressions
Aug 26, 2013.
This article provides an example of using a regular expression to search a directory and determine a file type.
Python Basics: Understanding The Functions
Aug 23, 2013.
In this article we will learn about functions in Python, how to create and call functions and how to create a program that uses functions.
Validating User Input With Regular Expressions
Aug 17, 2013.
This article explains how to use Regular expressions (the Regx class of the System.Text.RegularExpressions namespace).).
About expression-web4
NA
File APIs for .NET
Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more! | http://www.c-sharpcorner.com/tags/expression-web4 | CC-MAIN-2017-39 | refinedweb | 232 | 50.02 |
The topic of coding conventions (or coding standards) comes up a lot. You can always find it as a recent topic in the microsoft.public.dotnet.languages.vb newsgroup. A search on Google for “Coding Conventions” returns 170,000 hits. Why such interest? I think people simply want to know the way to format code.
With that said, there is no single way of authoring Microsoft Visual Basic code that is universally agreed upon. Microsoft defines a set of coding conventions that are adopted to a large or small degree by many development teams, but it’s very common for different sets of developers to follow, at least slightly, different rules.
You might wonder why we have conventions at all if nobody can agree on them. The reason, in a word, is consistency. At a minimum, code should be consistent with itself. This means that if you have multiple developers working on a given application, they should all be following the same rules. This can happen only if the rules are documented and agreed upon.
Ideally, all the code in an organization is consistent—although in practical terms, this virtually never happens. If the code that’s currently being written is consistent with code that’s developed in other departments, developers are more portable within the organization.
Coding conventions also affect code maintenance. Over the lifetime of a given application, more resources will be used to enhance and maintain the application than were originally used to develop the application. Also, applications are not typically maintained exclusively by the original authors. If the application uses consistent coding conventions, it’s easier to decipher and modify. For these reasons alone, coding conventions have value.
The true value of coding conventions is that they convey additional information not by what is written, but by how it’s written. Based on a given set of coding conventions, you can tell certain things by looking at the following statements:
What could you tell about this code? Based on the conventions that will be outlined in this chapter, you would know that currentUser is a private or protected variable and not a public property. You would know that IsValid, on the other hand, is a public property that returns a Boolean value. You would also know that txtUserIsValid is a user-interface element, and more specifically, a TextBox. Compare this case with the following code:
CurrentUser=NextUser() IfCurrentUser.CheckValidThen UserIsValid.Text= "Yes" EndIf
In this case, you can’t make any assumptions. There’s no way to tell whether CurrentUser is a public property or an internal variable. You know that UserIsValid is some kind of object, but is it a user-interface object? There’s no way to be certain, as any class could expose a Text method. If you do assume that it’s a user-interface element, you don’t know whether it’s a Label, a TextBox, or something else. Left to maintain this code, you would have a certain amount of spelunking to do just to figure out what you’re looking at.
I want to repeat that coding conventions described in this book are not the only ones that work. You could have standards where _currentUser, currentUser, current_user, sCurrentUser, and CURRENT_USER would all denote completely different things. The point is simply to have standards because doing so will enhance the readability and maintainability of your code.
Once you’ve decided that you’re going to institute coding conventions, you can either define a few guidelines or attempt to define a rule for nearly every conceivable coding scenario. If you want a truly minimalist approach, just remember, “It’s more important to be consistent than to be right.” This philosophy has a number of ramifications. It means that if you’re maintaining existing code, you simply follow the coding conventions used by the original author. Also remember that it’s never a good idea to fix the coding conventions of an entire application, unless the application is already being rewritten for some other reason.
If you want something a little more structured, I’ll offer what I consider to be the most important conventions for Microsoft Visual Basic .NET.
Option Strict On
Option Strict On was used for all the samples in this book simply because it results in safer, more reliable, often better performing, and more explicit code. Almost all production code should be authored with Option Strict On. There is one exception: if you’re specifically trying to leverage the late-binding feature of Visual Basic .NET, it’s OK to use Option Strict Off. However, this code should be contained within its own file, and the majority of the application should still use Option Strict On.
Camel Casing
Camel casing means the first letter is a lowercase letter and then the beginning of each subsequent word is an uppercase letter. For example: currentUser, firstCustomer, and myDocumentsFolder. You should use camel casing for parameters passed to methods, for local variables, and for private or protected class variables. Using this convention makes it easy to see that something is an internal variable and not externally accessible.
Pascal Casing
Pascal casing means that you capitalize the first letter of every word. For example: GetCustomer, SaveChanges, and FirstName. Pascal casing should be used for all classes, enumerations, methods, properties, public fields, namespaces, etc. In other words, Pascal casing is used for everything except the few cases where you use camel casing.
This use of Pascal and camel casing is consistent with all the classes you’ll find in the base class library of the .NET Framework.
You should comment every procedure. This commenting should include at a minimum the purpose of the method, a description of the arguments, and the meaning of the value returned. You should also comment all variables and properties, and all logical blocks of code. The most important rule of commenting is that the comments should describe the code, not repeat the code. Consider the following two sections of code:
'openatextfile DimsrAsNewStreamReader("c:somefile.txt") 'declareaninteger DimiAsInteger 'looponreadingeachline Whilesr.ReadLine() 'incrementi i+=1 EndWhile 'Countthelinesinafile DimsrAsNewStreamReader("c:somefile.txt") DimiAsInteger Whilesr.ReadLine() i+=1 EndWhile
Which is more informative? The first example comments every line. However, the comments don’t tell you anything you don’t already know. They’re just repeating the code. Sometimes, less is more. In the second example, the comment explains what the code does, not how it does it. This is the purpose of comments. If you feel you have to comment how the code is doing something, perhaps because a certain code block is extremely complex, consider rewriting the code to simplify it. Remember, comments are designed to give additional information to a programmer who already has the ability to read code.
Do Things the Visual Basic Way
When dimensioning a variable, it’s better to say Dim cn As New SqlConnection() than to say Dim cn As SqlConnection = New SqlConnection(). This approach also means it’s preferable to use Len instead of String.Length, MsgBox instead of MessageBox.Show, and Declare instead of DllImport. It’s also worth noting that conversion functions such as CInt and CBool are not really functions; they are language keywords and are actually faster than CType(x, Integer).
There is a great misunderstanding about the intrinsic Visual Basic methods. People have the impression that if you use Len, you’re not writing “pure” .NET code. This is completely untrue. Len is simply a method in the Microsoft.VisualBasic namespace. This namespace is part of the core Framework. By using these methods, you aren’t burdening your application with carrying around something equivalent to the Visual Basic 6 runtime. The exception to this is the Microsoft.VisualBasic.Compatability namespace. This exists only for migrating Visual Basic 6 code to Visual Basic .NET, and it should never be used for new development.
Use Meaningful and Consistent Names
You should pick names that are readable and mean something. You should use variables such as i, j, and k only for trivial loops. If you have a property or variable that stores a Boolean value, its name should contain Is to denote a True or False value or yes/no—for example, IsValid or IsAuthorized.
Constants and Enumerations
Your code should never contain magic numbers or strings. You should use constants and enumerations instead. For example:
'Bad DimbufferSize(1024*1024)AsByte 'Good ConstK_BYTEAsInteger=1024 ConstMEG_BYTEAsInteger=1024*K_BYTE DimbufferSize(MEG_BYTE)AsByte
In the first example, who knows what the code means? In the second example, it’s obvious that the code is creating a 1-megabyte buffer. The only raw numbers that should appear in your code are 0 and 1. Anything else should be defined as a constant or enumeration. It is also a matter of convention to declare constants in all capital letters with an underscore separating each word.
Enumerations can also make your code more readable and maintainable. Compare the following:
PublicEnumPriority Low Medium High EndEnum 'Bad Mail.Priority=1 'Good Mail.Priority=Priority.Medium
Using the enumeration obviously makes the code more readable. Enumerations in .NET have the added advantage of allowing you to easily convert them to strings. For example: lblPriority.Text = Mail.Priority.ToString().
Hungarian Notation
When you use Hungarian notation, you prefix each variable declaration with mnemonics that denote the type. For example, m_sUserName indicates a private or protected member variable of the String data type. In Visual Basic 6, this type of Hungarian notation was sometimes used. What was almost universal, however, was to prefix all user-interface elements with a three-character prefix: txt for TextBox, lbl for Label, and so on.
In Visual Basic.NET, m_ should be used only for private or protected members that are accessed through a public property procedure. Other protected member variables should simply be given a camel-case name. Primitive data types should not be prefixed, so you should simply use customerName, and not sCustomerName or strCustomerName.
Microsoft originally recommended against using any form of Hungarian notation; however, the prefixes for user-interface elements are so ingrained and useful that they’re now accepted. If you’re building an application that has a user name label, text box, and member variable, you can run out of creative names quickly. However, with prefixes for the user interface elements, it’s obvious what lblUserName, txtUserName, and userName are in your code.
Table 15-1 shows the recommended prefixes for user-interface elements:
Because data objects are so common, they’re also sometimes prefixed. If you decide to prefix data objects, you should use the conventions listed in Table 15-2.
Use Good Object-Oriented (OO) Practices
Visual Basic 6 is an event-driven programming language. If you have a structured programming background, you know that in Visual Basic 6 you simply had to think differently to solve the same problems.
In addition to being event driven, Visual Basic .NET is fully object oriented. Guess what? This means thinking differently to solve the same problems. The purpose of this book isn’t to teach the concepts of object-oriented (OO) languages. Many great titles exist that cover the concepts quite adequately. The point I want to make is that you no longer have a choice about doing or not doing OO. All Visual Basic .NET code is OO by nature. When you create a Web page or a form, it shows up in your code as a class. The Framework itself makes extensive use of inheritance, polymorphism, and other OO concepts. In addition, the Framework was specifically designed to assume that you would inherit portions of it and implement interfaces as the way to build solutions.
Visual Basic 6 was not OO, and you might not be used to thinking this way. I strongly recommend learning object-oriented analysis and design practices and using them in your applications.
Some Things Were Bad, Are Bad, and Always Will Be Bad
Goto, Option Explicit Off, and On Error Resume Next have generally never been good ideas. They still aren’t. But, the list of “bad things” has actually grown with Visual Basic .NET. You should now avoid the On Error construct completely. Instead, you should use structured error handling in your code:
Try DimxAsInteger x=x/0 CatchexAsException MsgBox(ex.Message) Finally 'Thiscodealwaysruns EndTry
When handling errors this way, you wrap the code that might fail in a Try block. If an exception occurs, execution will jump to the Catch block, where the error can be dealt with appropriately. Code in the Finally block will always run, whether an exception occurs or not. For a detailed description of structured exception handling, see the related sample. It suffices to say that structured exception handling should be used in place of On Error, in every case.
You should also avoid type characters when declaring variables. So instead of using
Dims$
you should use
DimsasString
One exception to the “has always been bad” rule is variable declaration. You used to pay a performance penalty if you dimensioned variables using As New:
DimcnnAsNewSqlConnection()
This is now the recommended mechanism for instantiating objects.
User Interface
You can do some simple things to make your application more accessible. The easiest thing to do is to add accelerators for all menus, labels, buttons, and so forth. Each application should also contain an About form on the Help menu that at a minimum explains where the user can get support.
When naming user-interface elements, it’s not a crime to have Label1 and Panel1, unless those objects will be accessed by code. Any object that is accessed by code—either to access properties or methods, or handle events— should have a meaningful name.
Coding conventions are all about making code that’s more readable and ultimately more maintainable. You can almost think of conventions as metadata for your code, as they convey additional information beyond the code itself. While this section has outlined many common and agreed-upon coding conventions for Visual Basic .NET, you might need additional or different conventions within your organization. That’s fine. What is critical is that within your organization you adopt conventions that everyone agrees to. Conventions are simply a mechanism for consistency. | http://flylib.com/books/en/2.31.1/coding_conventions.html | CC-MAIN-2018-05 | refinedweb | 2,372 | 56.45 |
Main class for Stellarium core processing. More...
#include <StelCore.hpp>
Main class for Stellarium core processing.
This class provides services like management of sky projections, tone conversion, or reference frame conversion. It is used by the various StelModules to update and display themself. There is currently only one StelCore instance in Stellarium, but in the future they may be more, allowing for example to display several independent views of the sky at the same time.
Supported reference frame types.
Available projection types. A value of 1000 indicate the default projection.
Get the state of the horizontal flip.
Get the state of the vertical flip.
Get a new instance of projector using the current display parameters from Navigation, StelMovementMgr, etc...
If not specified the projection type is the default one set in the core. This is a smart pointer, you don't need to delete it.
Get an instance of projector using the current display parameters from Navigation, StelMovementMgr and using the given modelview matrix.
If not specified default the projection type is the default one set in the core.
Get a new instance of a simple 2d projection.
This projection cannot be used to project or unproject but only for 2d painting
Set the flag with decides whether to arrage labels so that they are aligned with the bottom of a 2d screen, or a 3d dome.
Set the horizontal flip status.
Set the vertical flip status.
Update all the objects with respect to the time. | http://stellarium.org/doc/0.10.6/classStelCore.html | CC-MAIN-2016-50 | refinedweb | 246 | 59.09 |
with faster code written in C or C++. All we need to do is let Node know where to find this code and how to interface with it.
There are a few ways to solve this problem depending on what level of abstraction you want. We'll start with the lowest abstraction, which is the Node Addon.
Addons
An addon works by providing the glue between Node and C/C++ libraries. For the typical Node developer this may be a bit complicated as you'll have to get in to actually writing C/C++ code to set up the interface. However, between this article and the Node documentation, you should be able to get some simple interfaces working.
There are a few things we need to go over before we can jump in to creating addons. First of all, we need to know how to compile (something Node developers happily forget about) the native code. This is done using node-gyp. Then, we'll briefly talk about nan, which helps with handling different Node API versions.
node-gyp
There are a lot of different kinds of processors out there (x86, ARM, PowerPC, etc), and even more operating systems to deal with when compiling your code. Luckily,
node-gyp handles all of this for you. As described by their Github page,
node-gyp is a "cross-platform command-line tool written in Node.js for compiling native addon modules for Node.js". Essentially,
node-gyp is just a wrapper around gyp, which is made by the Chromium team.
The project's README has some great instructions on how to install and use the package, so you should read that for more detail. In short, to use
node-gyp you need to do the following.
Go to your project's directory:
$ cd my_node_addon
Generate the appropriate build files using the
configure command, which will create either a
Makefile (on Unix), or
vcxproj (on Windows):
$ node-gyp configure
And finally, build the project:
$ node-gyp build
This will generate a
/build directory containing, among other things, the compiled binary.
Even when using higher abstractions like the
ffi package, it's still good to understand what is happening under the hood, so I'd recommend you take the time to learn the ins and outs of
node-gyp.
nan
nan (Native Abstractions for Node) is an easily overlooked module, but it'll save you hours of frustration. Between Node versions
v0.8,
v0.10, and
v0.12, the V8 versions used went through some big changes (in addition to changes within Node itself), so
nan helps hide these changes from you and provides a nice, consistent interface.
This native abstraction works by providing C/C++ objects/functions in the
#include <nan.h> header file.
To use it, install the
nan package:
$ npm install --save nan
Add these lines to your binding.gyp file:
"include_dirs" : [ "<!(node -e \"require('nan')\")" ]
And you're ready to use the methods/functions from
nan.h within your hooks instead of the original
#include <node.h> code. I'd highly recommend you use
nan. There isn't much point in re-inventing the wheel in this case.
Creating the Addon
Before starting on your addon, make sure you take some time to familiarize yourself with the following libraries:
- The V8 JavaScript C++ library, which is used for actually interfacing with JavaScript (like creating functions, calling objects, etc).
- NOTE:
node.his the default file suggested, but really
nan.hshould be used instead
- libuv, a cross-platform asynchronous I/O library written in C. This library is useful for when performing any type of I/O (opening a file, writing to the network, setting a timer, etc) in your native libraries and you need to make it asynchronous.
- Internal Node libraries. One of the more important objects to understand is
node::ObjectWrap, which most objects derive from.
Throughout the rest of this section, I'll walk you through an actual example. In this case, we'll be creating a hook to the C++
<cmath> library's
pow function. Since you should almost always be using
nan, that's what I'll be using throughout the examples.
For this example, in your addon project you should have at least these files present:
pow.cpp
binding.gyp
package.json
The C++ file doesn't need to be named
pow.cpp, but the name typically reflects either that it is an addon, or its specific function.
// pow.cpp #include <cmath> #include <nan.h> void Pow(const Nan::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) { Nan::ThrowTypeError("Wrong number of arguments"); return; } if (!info[0]->IsNumber() || !info[1]->IsNumber()) { Nan::ThrowTypeError("Both arguments should be numbers"); return; } double arg0 = info[0]->NumberValue(); double arg1 = info[1]->NumberValue(); v8::Local<v8::Number> num = Nan::New(pow(arg0, arg1)); info.GetReturnValue().Set(num); } void Init(v8::Local<v8::Object> exports) { exports->Set(Nan::New("pow").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(Pow)->GetFunction()); } NODE_MODULE(pow, Init)
Note there is not semicolon (
;) at the end of
NODE_MODULE. This is done intentionally since
NODE_MODULE is not actually a function - it's a macro.
The above code may seem a bit daunting at first for those that haven't written any C++ in a while (or ever), but it really isn't too hard to understand. The
Pow function is the meat of the code where we check the number of arguments passed, the types of the arguments, call the native
pow function, and return the result to the Node application. The
info object contains everything about the call that we need to know, including the arguments (and their types) and a place to return the result.
The
Init function mostly just associates the
Pow function with the
"pow" name, and the
NODE_MODULE macro actually handles registering the addon with Node.
The
package.json file is not much different from a normal Node module. Although it doesn't seem to be required, most Addon modules have
"gypfile": true set within them, but the build process seems to still work fine without it. Here is what I used for this example:
{ "name": "addon-hook", "version": "0.0.0", "description": "Node.js Addon Example", "main": "index.js", "dependencies": { "nan": "^2.0.0" }, "scripts": { "test": "node index.js" } }
Next, this code needs to be built into a 'pow.node' file, which is the binary of the Addon. To do this, you'll need to tell
node-gyp what files it needs to compile and the binary's resulting filename. While there are many other options/configurations you can use with
node-gyp, for this example we don't need a whole lot. The
binding.gyp file can be as simple as:
{ "targets": [ { "target_name": "pow", "sources": [ "pow.cpp" ], "include_dirs": [ "<!(node -e \"require('nan')\")" ] } ] }
Now, using
node-gyp, generate the appropriate project build files for the given platform:
$ node-gyp configure
And finally, build the project:
$ node-gyp build
This should result in a
pow.node file being created, which will reside in the
build/Release/ directory. To use this hook in your application code, just
require in the
pow.node file (sans the '.node' extension):
var addon = require('./build/Release/pow'); console.log(addon.pow(4, 2)); // Prints '16'
Node Foreign Function Interface
Note: The
ffi package is formerly known as
node-ffi. Be sure to add the newer
ffi name to your dependencies to avoid a lot of confusion during
npm install :)
While the Addon functionality provided by Node gives you all the flexibility you need, not all developers/projects will need it. In many cases an abstraction like
ffi will do just fine, and typically require very little to no C/C++ programming.
ffi only loads dynamic libraries, which can be limiting for some, but it also makes the hooks much easier to set up.
var ffi = require('ffi'); var libm = ffi.Library('libm', { 'pow': [ 'double', [ 'double', 'double' ] ] }); console.log(libm.pow(4, 2)); // 16
The above code works by specifying the library to load (libm), and specifically which methods to load from that library (pow). The
[ 'double', [ 'double', 'double' ] ] line tells
ffi what the return type and parameters of the method is, which in this case is two
double parameters and a
double returned.
Conclusion
While it may seem intimidating at first, creating an Addon really isn't too bad after you've had the chance to work through a small example like this on your own. When possible, I'd suggest hooking in to a dynamic library to make creating the interface and loading the code much easier, although for many projects this may not be possible or the best choice.
Are there any examples of libraries you'd like to see bindings for? Let us know in the comments! | https://stackabuse.com/how-to-create-c-cpp-addons-in-node/ | CC-MAIN-2018-51 | refinedweb | 1,459 | 64.1 |
C# Compiler
I've been promising myself an extended vacation for a long time now, but working at Microsoft has been so much fun I've kept postponing it. Well, this is it - my last day at Microsoft.
Feel free to email me at 'hotweird' at hotmail.
I.
A {
return this.myInstance.GetSingleton(
delegate() {
return this.CreateSingleton(OrderContext, "third");
}
);
}
}
I’m sharing my comments on the code, as it demonstrates some important design principles. Here’s the original code:
public class DoubleCheckedLock<T> where T : class
{
private volatile T myInstance;
private static readonly object lockObject = new object();
public T GetSingleton(CreateObject c) {
if (this.myInstance == null) {
lock (lockObject) {
if (this.myInstance == null) {
this.myInstance = c();
}
}
Debug.Assert(this.myInstance != null);
return this.myInstance;
public delegate T CreateObject();
public abstract class DoubleCheckedLock2<T> where T : class
protected abstract T CreateObject();
private DoubleCheckedLock<T> myInstance = new DoubleCheckedLock<T>();
public T Instance {
get {
return this.myInstance.GetSingleton(this.CreateObject);
And here are my comments:
Now the client code looks like this:
sealed class Client {
private readonly Singleton<ExpensiveResource> expensiveValue;
Client() {
this.expensiveValue =
new Singleton<ExpensiveResource>(
delegate()
{
return new ExpensiveResource();
}
);
public ExpensiveResource ExpensiveValue {
get { return this.expensiveValue.Value; }
Which is pretty damn sexy, if I don't say so myself.
Here's the implementation:
public delegate T Creator<T>();
public class Singleton<T> where T : class {
private readonly Creator<T> creator;
public Singleton(Creator<T> creator) {
Debug.Assert(creator != null);
this.creator = creator;
public T Value {
if (this.myInstance == null) {
lock (lockObject) {
if (this.myInstance == null) {
this.myInstance = this.creator();
this.creator = null; // allow creator object to be GC-ed as soon as possible
Debug.Assert(this.myInstance != null);
return this.myInstance;
Happy coding,
Peter
Don Syme and the F# team have just released a new version of F#. Check it out here:
The,
Hey Folks,
Charlie Calvert video taped our discussion on some of the new C# 3.0 features. Find it here:.
Cheers,
What do professional programmers really do with their time anyway?
Design Code
Write New Code
Understand Existing Code
Modify Existing Code
Verify Existing Code Still Works
New Code: 2%
Modifying Existing Code: 20%
Understanding Code: 78%
New Code: 5%
Modifying Existing Code: 25%
Understanding Code: 70%
Hey folks,
First off, I want to appologize for not having any activity on my blog for a while. I just got back from a wonderful 3 week vacation in Spain. Now that I'm back, rested and limber, here's a twisted peice of C# code which is gauranteed to turn your brain inside out.
Why does the compiler (correctly) give an error message on the override in the following code?
abstract class A<T>{ public abstract T getT(); class B : A<B> { public override B getT() { throw new System.Exception("The method or operation is not implemented."); } }}
I got this code from a coworker, and I must confess that the first time I saw it I was convinced that the behaviour was a compiler bug. It turns out that the compiler correctly diagnoses the problem, though even after seeing the error message it took me a while to figure out what's going on. I'll post a discussion in a couple of days.
Any Takers?
PeterC# Guy
C# Guy.
Just a quick one this week:
Why is it that you cannot use enum constants in a switch statement's cases without first casting them to type int?
Often you will want to use Enum constants as case labels in switch statements. Sometimes, the compiler will complain and require a cast to int on each case label. This will look something like this:
enum Color { Red, Green, Blue };
int i = ...;
switch (i)
{
// cast required! Aarg!
case (int)Color.Red: break;
case (int)Color.Green: break;
case (int)Color.Blue: break;
The confusion stems from a subtle difference between C++ and C#. In C++, values of enum type are implicitly convertible to int. In C#, conversions between an enum type and its underlying type are explicit and require a cast. To maintain consistency, the requirement for the cast carries over into the use of enums in switch statements.
However, you can use expressions of enum type as case labels without a cast, but only in a type safe way. The rule is that the type of the expression being switched on, the ‘governing type’ of the switch statement in C# language spec terminology, must match the type of the expressions in the case labels.
For example:
Color c = ...;
switch (c) // Governing type is ‘Color’ not ‘int’ so ...
// ... no cast required
case Color.Red: break;
case Color.Green: break;
case Color.Blue: break;
One of the design goals for enums in C# was to treat them as first class types that were truly distinct from their underlying type. This is one of the subtle ways that this decision manifests itself in the language.[]
I’m back from my course on Software Design. Now that we are starting to think about the version of C# after VS 2005 we are shining a bright light on all the ways the current compiler codebase could be better. This is the fun part of the product cycle where you get to really dig in and reorganize your code. Fun stuff!
I hope everyone had a good weekend. I spent the weekend out in the San Juan Islands. A bunch of us went out to celebrate Tim’s bachelor party. I’m mostly recovered from the hangover – so I hope I can keep it together for this week’s question:
In C# only objects derived from System.Exception can be thrown, so why allow general catch clauses? Isn’t that just the same as catch (System.Exception)?
C# allows specifying two kinds of catch clauses – specific catch clauses, and general catch clauses. Specific catch clauses specify the type of exception to be caught. Exceptions which are not of the specified type are ignored by the specific catch clause.
try
using (StreamReader reader = new StreamReader(fileName))
char[] text = reader.ReadToEnd().ToCharArray();
...
catch (IOException e)
Console.WriteLine("Error reading from file '{0}' : '{1}'",
fileName, e.Message);
This example demonstrates a good guideline when catching exceptions – only catch exceptions that you expect, and in general catch the most specific set of exceptions possible. In this case the System.IO.IOException is an expected result of attempting to read a file, so catching it is reasonable.
In contrast, general catch clauses don’t name a type. They catch all thrown objects. The general catch clause is useful in the (hopefully rare) occasions when you need to catch everything. However, a specific catch clause which catches System.Exception is guaranteed to catch everything that can be thrown by C# code. So why add the general form of the catch clause?
The subtle difference is that although catch System.Exception will catch everything that C# code can throw, it doesn’t catch everything that the CLR can throw. In the CLR, any object can be thrown – even objects not derived from System.Exception. That’s right, in IL or C++ you can throw the string “hello”, or the integer 5 just as easily as you can throw a new System.Exception()!
The general catch clause was added to C# so that code which interoperates with non-C# code can catch anything that can be thrown in the CLR. One of the benefits of C# running on the CLR is that it allows C# code to interoperate easily with other CLR languages, however this example shows that this feature has some drawbacks as well. Needless to say, the fact that a string can be thrown is a subtlety that most C# programmers are not aware of, and it’s exactly those kinds of subtleties that can lead to unexpected bugs.
Well, this was all a warm up to talk about a new feature that was added to the CLR and C# in VS2005 to help address the mismatch. Unfortunately its getting late and I need to grab some dinner. I’ll have to save that for my next post …
I.
Well. | http://blogs.msdn.com/peterhal/default.aspx | crawl-002 | refinedweb | 1,346 | 65.62 |
#include <hallo.h> Steve Langasek wrote on Mon Jun 17, 2002 um 01:52:48PM: > > tetex-src? > > mindterm (an edge case; the binary package includes full source for > > legal reasons..) > > pine (only source package avilable; pine-tracker; etc) cfdisk-utf8 (includes util-linux source) cloop-src (includes zlib source) ash-knoppix (soon, includes ash and modutils source) They all would benefit from having a method to specifying a source dependency, so the source would be loaded as part of dependencies _and_ build-dependencies, and used from a system-wide accessible directory. Gruss/Regards, Eduard. -- <schneckal> hat einer von euch schon bind9 installiert? <eis> das neue root kit? :-> -- #debian.de
Attachment:
pgpJwKy0_8IEm.pgp
Description: PGP signature | https://lists.debian.org/debian-devel/2002/06/msg01489.html | CC-MAIN-2015-32 | refinedweb | 115 | 56.86 |
Nosayaba Omo-Ogbebor2,071 Points
Challenge Task 1 of 1 the functions and the class,
Challenge Task 1 of 1
Function and class white space
def first_function(arg1): return 'arg1 is {}'.format(arg1) def second_function(arg1): return 'arg1 is {}'.format(arg1) class MyClass: args = [1, 2, 3] def class_func(self): return self.args
3 Answers
Chris FreemanTreehouse Moderator 63,984 Points
You are very close. The error I get with your code is Bummer! Your file has 1 error(s) on line(s) 11: blank line contains whitespace.
Remove the spaces on line 11 and it should pass.
Post back if you need more help. Good luck!!!
Nosayaba Omo-Ogbebor2,071 Points
Thanks Chris, I removed the spaces but still won't pass.
Nosayaba Omo-Ogbebor2,071 Points
Thank you Chris, The spaces were the indention. I removed them and it passed. Thanks a lot.
Chris FreemanTreehouse Moderator 63,984 Points
Chris FreemanTreehouse Moderator 63,984 Points
What error message do you get back? | https://teamtreehouse.com/community/challenge-task-1-of-1-the-functions-and-the-class | CC-MAIN-2021-21 | refinedweb | 164 | 77.03 |
delete vs delete[] vs free in C++
Get FREE domain for 1st year and build your brand new site
In this article, we will explore the difference between delete, delete[], free keywords of C++ which are often confused with each other and sometimes wrongly used leading to the errors in one's program.
In short, all the three keywords (delete, delete[] and free)are used to deallocate or free a block of memory which had been allocated dynamically. We need to deallocate a block of memory to prevent memory leakage and crashing of the program in future.
Before we go into the differences between them, let us first get the basic understanding of the three keywords separately.
The free keyword
free is a pre-defined function, defined in 'cstdlib' header file of C++, which is used to deallocate a block of memory that was previously dynamically allocated using
malloc,
calloc, or
realloc in case of reallocation of memory. This is done to make the memory available for future allocations.
The syntax of the free function is as follows:
void free(void *memory_block);
In the above code, memory_block is the previously allocated memory which needs to be freed. As we can see, the return type of the free() function is 'void' which means that the free function does not return any value and only frees up the allocated memory.
The number of bytes that are freed is equal to the number of bytes that were requested when the block was allocated (or reallocated, in the case of realloc). If memory_block is NULL(i.e. it does not point anywhere), then the pointer is ignored and free immediately returns.
If we try to free a pointer to a memory block that was not allocated by calloc, malloc, or realloc, it may affect subsequent allocation requests and cause errors in our program or might destroy the memory management making a system to crash.
The free() function does not change the value of the pointer, hence it still points to the same(now invalid) memory location.
Example of free() function using malloc and realloc:
#include <iostream> #include <cstdlib> #include <cstring> using namespace std; int main() { char *ptr; ptr = (char*) malloc(10*sizeof(char)); strcpy(ptr,"Hello C++"); cout << "Before reallocating: " << ptr << endl; ptr = (char*) realloc(ptr,20); strcpy(ptr,"Hello, Welcome to C++"); cout << "After reallocating: " <<ptr << endl; free(ptr); cout << endl << "Garbage Value: " << ptr; return 0; }
The output of the above code is:
Before reallocating: Hello C++
After reallocating: Hello, Welcome to C++
Garbage Value:
The delete or delete[] keyword
delete is a memory management operator in C++, which is used to deallocate memory that was previously dynamically allocated to a new object or a bunch of objects using the memory management operator-
new. This is done to prevent memory leakage which may lead to crashing of the program.
Depending on the number of objects needed to be deallocated, we have two sytax of the delete operator:
1. Deallocation of a single object.
The syntax for deleting a single object is:
delete ptr-variable;
In the above syntax, the ptr-variable points to the memory address of an object whose allocated memory space has to be freed.
For example,
#include<iostream> using namespace std; int main() { int *d = new int(10); cout<< "The value at the address pointed by the pointer variable : " << *d << "\n"; cout<< "The memory address allocated to the pointer variable : " << d << "\n"; delete d; cout<< "The value at the address pointed by pointer variable : " << *d << "\n"; cout<< "The memory address allocated to the pointer variable : " << d; }
The output of the above code is:
The value at the address pointed by the pointer variable : 10
The memory address allocated to the pointer variable : 0x68ae30
The value at the address pointed by pointer variable : 0
The memory address allocated to the pointer variable : 0x68ae30
2. Deallocation of multiple objects.
The syntax for deleting multiple objects is:
delete [] ptr-variable;
In the above syntax, the ptr-variable points to the memory address of the (array of) objects whose allocated memory space has to be freed.
For example,
#include<iostream> using namespace std; int main() { int *d = new int[100]; delete [] d; }
The above code deallocates the 100 blocks of integer type memory(array) which was allocated with the help of new operator.
We can see that the delete operator does not destroy the pointer that is pointing to the object but it destroys the value or memory block pointed by the pointer.
We cannot use delete operator on a pointer to an object which has not been allocated with the new operator since it will give us unpredictable results. However, we can use delete on a pointer with the value 0. This means that, when new returns 0 on the failure of allocating the required memory, deleting the result of a failed new operation is harmless.
When the delete operator is called, it deallocates memory and calls the destructor for a single object created with new whereas when the delete [] operator is called, it deallocates memory and calls destructors for an array of objects created with new [].Using delete on a pointer returned by new [] or delete [] on a pointer returned by new results in undefined behavior.
The delete operator has a result type of void and therefore does not return a value.
Now that we have understood the basics of all the three keywords, let us compare them.
- free is a library function whereas delete and delete[] are both operator.
- free does not call any destructor while delete calls a destructor, if present whereas delete[] calls all the destructors that are present, according to the array size.
- free deallocates any block of memory created using malloc, calloc or realloc while delete deallocates a non-array object that has been created with new.whereas delete[] deallocates an array that has been created with new[].
- Freeing or deleting a null pointer with free, delete or delete[] causes no harm.
- free() uses C run time heap while delete and delete[] may be overloaded on class basis to use private heap.
We cannot allocate an object with malloc() and free it using delete().
With this article at OpenGenus, you must have complete idea of the differences of delete, delete[] and free in C++. | https://iq.opengenus.org/delete-vs-free-in-cpp/ | CC-MAIN-2021-43 | refinedweb | 1,047 | 52.73 |
Diego, On Sat, Oct 2, 2010 at 8:32 AM, Diego Biurrun <diego at biurrun.de> wrote: > On Thu, Sep 30, 2010 at 03:55:11PM -0700, Pascal Massimino wrote: > > On Thu, Sep 30, 2010 at 3:53 PM, Pascal Massimino < > > pascal.massimino at gmail.com>: > > >> > > >> > > >> > > > what about > > > > > attached, too. That's easier > > > > --- libavformat/Makefile (revision 25217) > > +++ libavformat/Makefile (working copy) > > @@ -277,6 +277,7 @@ > > +OBJS-$(CONFIG_WEBP_MUXER) += webp.o > > Since this is compiled conditionally... > > > --- libavformat/webp.c (revision 0) > > +++ libavformat/webp.c (revision 0) > > @@ -0,0 +1,217 @@ > > + > > +#include "avformat.h" > > +#include "riff.h" > > + > > +#ifdef CONFIG_WEBP_MUXER > > ...this #ifdef is unnecessary. > > > + if (s->nb_streams != 1) > > if (...) { > > same below, more nits for you to notice on your own ;) > > > +#endif /* CONFIG_WEBP_MUXER */ > > + > > +#if CONFIG_WEBP_DEMUXER > > Hmm, it seems that the Makefile entry is incomplete.. > should be fixed in attached patch... skal -------------- next part -------------- A non-text attachment was scrubbed... Name: patch_webp_ffmpeg.diff Type: application/octet-stream Size: 7528 bytes Desc: not available URL: <> | http://ffmpeg.org/pipermail/ffmpeg-devel/2010-October/099060.html | CC-MAIN-2014-41 | refinedweb | 158 | 62.64 |
Opened 8 years ago
Closed 8 years ago
#3586 closed Bugs (fixed)
Use of Greedy quantifiers in Quoted Expressions locks up at regex compile
Description
The following will not compile: \Q.*\E and causes the program to lockup at the compile step. I have attempted other usages: '\Qh*\E', '\Q.+\E', '\Q+\E', '\Q*\E' etc. and they all lock-up on compile. Note that escaping the quantifier will allow it to compile (but it is a different expression): '\Q.\*\E' -- compiles but will only match '.\*' not '.*'
#include <iostream> #include <boost/xpressive/xpressive.hpp> using namespace boost::xpressive; int main() { std::string hello( "hello .* world!" ); std::cout << "compile regex" << std::endl; sregex rex = sregex::compile( "\\Q.*\\E" ); smatch what; std::cout << "Get Iterator" << std::endl; sregex_iterator cur( hello.begin(), hello.end(), rex ); sregex_iterator end; std::cout << "begin search" << std::endl; while( cur != end ) { smatch const &what = *cur; std::cout << "found: " << what[0] << '\n'; cur++; } return 0; }
Attachments (0)
Change History (1)
comment:1 Changed 8 years ago by
Note: See TracTickets for help on using tickets.
(In [57346]) fix infinite loop with some uses of \Q...\E quotemeta, fixes #3586 | https://svn.boost.org/trac10/ticket/3586 | CC-MAIN-2017-43 | refinedweb | 190 | 68.87 |
SYNOPSIS
#include <Xm/Xm.h>
XmString XmStringNConcat(
XmString s1,
XmString s2,
int num_bytes);
DESCRIPTION
This function is obsolete and exists for compatibility with previous releases. It is replaced by XmStringConcat. XmStringNConcat appends a specified number of bytes from s2 to the end of s1,.
- num_bytes
- Specifies the number of bytes of s2 to append to s1. If this value is less than the length of s2, as many bytes as possible, but possibly fewer than this value, will be appended to s1 such that the resulting string is still a valid compound string.
RETURN
Returns a new compound string.
RELATED
XmStringCreate(3) and XmStringFree(3). | http://manpages.org/xmstringnconcat/3 | CC-MAIN-2021-49 | refinedweb | 105 | 58.69 |
Is XMPP the 'Next Big Thing' 162
Open Standard Lover writes "XMPP (eXtensible Messaging and Presence Protocol) has been getting a lot of attention during the last month and it seems that the protocol is finally taking off as a general purpose glue to build distributed web applications. It has been covered that AOL was experimenting with an XMPP gateway for its instant messaging platform. XMPP has been designed since the beginning as an open technology for generalized XML routing. However, the idea of an XMPP application server is taking shape and getting supporters. A recent example shows that ejabberd XMPP server can be used to develop a distributed Twitter-like system."
buzzwords are my favorite (Score:5, Funny)
Minus two points for not managing to cram the phrases "AJAX" or "Web 2.0" into this writeup.
Re:buzzwords are my favorite (Score:4, Insightful)
Re:buzzwords are my favorite (Score:5, Funny)
Re:buzzwords are my favorite (Score:5, Interesting)
Re: (Score:2)
Re: (Score:2)
AJAX is an ugly hack...[instead], the server can push XML fragments to the client whenever it wants and some client-side JavaScript could then process them into the DOM
Umm... Isn't that just a different ugly hack?
Browsers force polling. (Score:2)
Google's actually come up with a neat hack to deal with this -- leave the connection open for 30 seconds, and if nothing new comes down it, close that connection and open a new one. Technically "polling", but practically just as fast as XMPP.
Re: (Score:2)
Re: (Score:3, Insightful)
Re: (Score:2, Interesting)
Remember, YMMV.
Re: (Score:3, Insightful)
Re: (Score:3, Funny)
A twitter-like system could be built on top of xmpp. In much the same way that a gmail-like system can be built on top of SMTP/POP. That doesn't mean that SMTP/POP are web-based.
I don't know if a twitter-like [slashdot.org] system would be a wise course of action for an instant messenger system let alone an instant messenger system using XMPP. Do you know what problems could arise from this? Text such as M$, Windoze, Micro$oft, or anything dealing with anti-Microsoft topics would pop-up in your message. This change could occur when you type in MS, Microsoft, Windows, or anything dealing with Microsoft; or just occur spontaneously.
;)
Re: (Score:3, Funny)
Re:buzzwords are my favorite (Score:4, Informative)
Huh?
Field test of XMPP based system (Score:4, Informative)
Just what we (didn't) need !! (Score:2, Insightful)
Is there NOTHING sacred that some lemon won't wrap in XML ???
Oh, no, wait
Brilliant !!
Re: (Score:2)
Re:Just what we (didn't) need !! (Score:4, Informative)
Yeah, I know, this is Slashdot, where people like to spew completely uninformed pseudo-opinions, but this one is just too obvious. Well, happy IMing on unencrypted, stone-age, propertiary networks that force-feed you with ads and censor your messages, if that's what you want.
Re: (Score:3, Insightful)
Well, happy IMing on unencrypted, stone-age, propertiary networks that force-feed you with ads and censor your messages, if that's what you want.
XML doesn't solve any of these problems (and they're not all problems.) There's no technical reason that any given messaging service couldn't use SSL, and XMPP is extensible, and an implementation of it can be made proprietary enough to require a client that will force-feed you ads. Any network can censor messages, assuming they can read them.
Your post is overrated.
Yeah, I know, this is Slashdot, where people like to spew completely uninformed pseudo-opinions, but this one is just too obvious.
Oh, sorry, I guess you covered all of that.
Re: (Score:2)
XMPP is OK but would be better if JSON (Score:2)
It is pretty silly that in a a 4-5 word IM message, 75% of the data transferred in an XMPP client is just protocol overhead, and the message is just 25%.
If they had used a more lightweight container like JSON for the protocol it would have much less overhead.
Frankly, IMO, almost all data transfer protocols would be better suited to the JSON container than XM
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
XMLJPG (Score:2)
Re: (Score:2)
My first impression based on the tools actually using it (like ejabberd) is more like "IRC wrapped in an XML overcoat where everyone is a lousy sexchat bot".
Re: (Score:2)
I am a great sexchat bot.
Re: (Score:2)
Yes, because RFC 822 header fields are the pinnacle of parser research. Have you ever tried to write your own mail client? Have you ever tried to write your own mail server? By comparison, I'm pretty sure I could knock out a minimal compliant XMPP server in an afternoon, and it would support Unicode for free.
But anyway, the biggest thing the "X" buys you is a lot of extensions [xmpp.org]. I'd say it's actually delivering on what it promises.
Am I too late... (Score:5, Interesting)
'Zemp' would be a nice easy way of saying this.
Re:Am I too late... (Score:5, Funny)
Re: (Score:2)
Re: (Score:2)
Re:Am I too late... (Score:5, Informative)
A lot of people pronounce it "Jabber". The name "XMPP" arose when they were moving it through the IETF standardisation process.
Re: (Score:2)
Re:Am I too late... (Score:5, Informative)
Re:Am I too late... (Score:5, Insightful)
Re: (Score:2)
Why is this modded as funny? As a Pidgin user, I'd LOVE to see someone fix the crapstorm that is their poor excuse for a Jabber client. If you've got the ability, do it...it would make a lot of people happy.
After all, isn't this what the Open Source ethic is all about?
Re:Am I too late... (Score:4, Interesting)
If the guy can write an XMPP client, and knows exactly what is wrong with Pidgin's implementation in order to "fix" his client to support it, then he should be more than capable of providing a fix to Pidgin's code, so that he doesn't have to keep fixing his code, and the all of us Pidgin users can benefit as well.
Re: (Score:3)
What exactly is the problem with Pidgin's XMPP/Jabber support? I use Pidgin for my MSN, AIM, and GTalk accounts.. and all three of them seem to work identically and without issue O_o
In case it didn't come across clearly, I actually am interested in knowing what it does so poorly with Jabber, since as an end-user I really can't say that I see what the issue is =(
Aikon-
Re: (Score:2)
I haven't seen the Pidgin code or dealt with the community, so this may very well be off base: perhaps it's darn nigh unfixable, or the authors don't readily accept patches?
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
Hell, I'm just happy that I don't have to track license counts any more (like I did with e/pop Professional).
Re: (Score:2)
For a GUI client, I like Psi. Right now I am using the xmpp extension for irssi.
Re: (Score:2)
Re: (Score:2)
Care to elaborate? (Score:2)
Re: (Score:2)
XMPP as a silver bullet? (Score:5, Interesting)
Re:XMPP as a silver bullet? (Score:5, Informative)
Re: (Score:2)
If I encrypt everything in a proprietary method (or with a proprietary key) and layer that into XMPP, you can still be locked in.
It's kind of like saying because it's stored in XML it's open...
<document>
h5847uhlib43o8fvacgos8
5rw4978hefw9348fqw34fg
f438gqwoluiaf4687wgoasd
</document>
There's my open document, so you can read it. (No, I didn't include a DTD, but just
Re: (Score:2, Funny)
Aha! So the gov't *is* hiding UFO's in secret hangers. And do something about that stuttering problem of yours.
Re: (Score:2)
However it's true on the intersite scale. All the services use Bantu, which is XMPP. They actually advertise themselves as the IM used by US govt. [bantu.com]
Performance (Score:3, Interesting)
Re: (Score:3, Informative)
Re: (Score:2, Insightful)
A brief explanation (Score:4, Informative)
If someone connected to a gmail jabber server sends a message to andrewducker@livejournal.com then google chat automatically connects to the livejournal jabber server and passes the message over.
You can see how this could be extended to allow federations of application servers to communicate. Heck, you could reimplement email over this without massive difficulty.
Re:A brief explanation (Score:4, Interesting)
Heck, you could reimplement email over this without massive difficulty.
In reality I think it was one of the first things they implemented in Jabber. A lot of clients, especially the hardcore jabber clients, have different messaging modes: one mode composes a single message, another mode opens up a little chatbox. If you examine the former, you'll find that it's exactly like e-mail, although really it's just a jabber message. Everybody ends up using the chatbox because that's what jabber is for, and many popular clients (eg Pidgin) have only that.
In terms of server and protocol, in my opinion Jabber is fully able to do e-mail. In fact, I'm sure Jabber servers already have e-mail gateways. You just need a client that operates in a manner that implements e-mail as we are used to; for example, most clients just pop up offline messages as soon as you connect, or mark them on your roster instead of presenting you with a stored list of messages that you can manipulate mailbox style.
Re: (Score:3, Interesting)
only thing about using xmpp as a mail "replacement", can it do attachments?
no, im not talking about file transfers, im talking about attaching the file to the xmpp message and have it be stored on the server if the recipient is offline at the moment.
thats the one strong suit of mail vs sms or im right now, that you can fire and forget a file rather then having to watch for a person being available to accept it.
still, xmpp will
Re: (Score:2, Informative)
Actually... Yes you can. There's this newfangled thing called the <data> element. But, it got pushed into a XEP like two months ago, so client support is rather limited, and it's only good for 8k for now...
:(
If people starts using this much however, I can't see why the XMPP server wouldn't be able to store the file temporarily and then push it once the user is online. But, I think this is better for an xmpp/http hybrid.
Re: (Score:2)
now to see thunderbird and the rest adopt it as a "mail" protocol of sorts
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
In fact, the only reason I can see for a company to move to XMPP (or to include an XMPP g
Re: (Score:2)
Client-side IM services achieved "commodity" status some time ago; monetizing them shouldn't be on the agenda, for the most part. However, server technologies & protocol extensions haven't reached that stage. IMHO any company focusing on client lock-in is shooting their own foot.
A more reasonable alternative is to monetize server development. Find a niche or market segment that would b
WTF? (Score:2, Interesting)
What the hell does that mean?
I don't know whether to apply the "alphabetsoup" tag or the "stopturningnounsintoverbs" tag.
New Here (Score:4, Funny)
Could an ejabbered XMMP server really be said to be Twitter-like?
I don't think that Twitter-like systems are the way to go here.
That's really cool, we could really use a Twitter-like enjabered XMMP server here. It will revolutionise computing!
Re: (Score:2)
Re: (Score:2)
"that ejabberd XMPP server can be used to develop a distributed Twitter-like system."
What the hell does that mean?
I don't know whether to apply the "alphabetsoup" tag or the "stopturningnounsintoverbs" tag.
Where do you see a verb that used to be a noun?
ejabberd is an XMPP-server (that apache HTTP server -> that ejabberd XMPP server)
"can be used to develop" should be obvious
"a distributed": in this case this means that the network does not have a central server; the administration is distributed among the different XMPP-servers
"Twitter-like system": a system like twitter (twitter.com afaik).
Reading comprehension isn't your strong point, n'est-ce pas?
Re: (Score:2)
I'll be curious to see if XMPP makes it into the world of intra-application messa
Re: (Score:2)
"that ejabberd XMPP server can be used to develop a distributed Twitter-like system."
You mix twat,tit and throw in some dimwit and you get a twit. Do a while (42) {} on it and here is your twitter.
On a more serious note the more obscure parts of the XMPP spec can be read in so many ways that there is always a way to create non-interoperable clients. For example - the thread support which is even in the original RFC is still not implemented in any of the clients (I did a patch for pidgin a while back, it is still sitting in the queue). Same for whiteboarding and many other things. Classi
Re: (Score:2)
"XMPP has been designed since the beginning as an open technology for generalized XML routing."
The best reasoning I have is the use of "has been designed since"
Re: (Score:2)
So XMPP was designed from the beginning as an open technology for generalized XML routing."
Better?
Distributed computing and "the cloud" (Score:2)
I'm interested in how this protocol can help glue together applications for better/easier/simpler distributed computing
With all the cheap servers with multi-cores we have, it seems like we all have the ability today to do distributed computing on our own grid.
This site (and corresponding book) Enterprise Integration Patterns [enterprise...tterns.com] was very enlightening to me as I thought more about messaging and less about imperative programming.
New technologies like Terracotta [terracotta.org] (for Java) make distribution simple, too. Eve
Thanks Google (Score:5, Insightful)
Re: (Score:2, Interesting)
PFTLOGCWCUWMUA (Score:3, Funny)
Ugh!
XMPP is a PITA (Score:4, Interesting)
XMPP also requires you to keep a fair amount of state information. Stuff I seemingly would think should be kept by the server. I suppose by making the server really dumb (basically a router) you really put the eXtensible in XMPP but at the cost of a more complex client.
On its surface XMPP looks great: an open-source IM protocol!! Once you, the newb, get into it it gets really ugly.
Then again, maybe I made a poor choice in a python package or I just happened to not find that key page with google that basically explains my problem away (and that's all it is is acclimation, it's not terribly difficult once you "get it"). Not even the wikipedia page [wikipedia.org] explains inner-working details of XMPP. And FWIW, I was *trying* to do what this story was saying XMPP is going to be so great for: server glue for a distributed web-based application. Where I sit now with what [little] I know: I completely disagree until someone wraps it all up into a super-easy library (which shouldn't be too hard).
Re:XMPP is a PITA (Score:5, Informative)
Re: (Score:3, Informative)
The best way, I'm afraid, is to read the RFCs [xmpp.org] (mostly 3920 and 3921. There are updated, clearer drafts, 3920bis and 3921bis, a link away from that page) and XEPs [xmpp.org] (XMPP Extension Proposal). There's also a book [oreilly.com], but I heard that it's a bit outd
Re: (Score:2)
What the hell? [jajcus.net]
How do you get javascript from that?!?!?!
As for this part:
I don't need the library to hold my hand and explain XML, the concept of "online" vs. "away", etc. I want a page that says you have to: connect, authenticate, pull down a roster, send presence notifications, and then send messa
Re: (Score:2)
PyXMPP -- Python Jabber/XMPP implementation
How do you get javascript from that?!?!?!
Woops, you're right. I misread
/.'s domain shortcut, jajcus, for JSJaC [in-berlin.de].
Regarding doc, I'm didn't mean that you needed to read all the basics down to XML Namespaces or whatever, but I was surprised by your frustration with interacting with XMPP, and interpreted it as a lack of doc for semi-advanced topics. I couldn't believe that PyXMPP wouldn't provide even a basic tutorial on getting online and sending a message. Indeed, I haven't found anything after some quick googling.
As I said, there's a host of libra
Re: (Score:3, Informative)
If you are enough of a programmer to deal with Jabber, which means being comfortable with XML, this is by far the easiest bit of working with Jabber. All the tricky bits like connecting and stuff are the harder bits worth writing a library for.
Look for a library that handles:
Re: (Score:2)
The little bits that I found were either sparse, incomplete, not authorative, outdated or wrong. Often it was *all* of that at the same time.
Even most of the sample implementations and libraries were outright broken.
XMPP sounds like a great idea in theory and the existence of fairly mature implementations (in erlang FWIW) suggest that *someone* must know how to put t
Re: (Score:2)
Learning to use the libraries, then, requires reading the protocol specificat
Re: (Score:2)
As far as implementations, there are 3 major Open Source servers: ejabberd (Erlang), OpenFire (aka WildFire, written in Java) and jabberd2 (C), not to mention djabberd, LiveJournal's Perl-based jabber server framework.
Re: (Score:3, Informative)
We use jabber.py [sourceforge.net]. It hasn't changed in years, but our needs are pretty simple and it meets all of them easily. For example
Honestly, I don't know how you could make that a whole lot simpler.
Re: (Score:3, Interesting)
Yeah, that's brilliantly simple. Except when you have no clue what you're doing.
Look at the documentation provided by jabberpy. It's computer-generated pydoc with pseudo code on making a simple client. Did they have time to write an entire jabber library but couldn't taken the 45 seconds you did to write actual code instead of pseudo code?
Now when you take your bare example and try to receive messages then your simplicity isn't there any
Re: (Score:2)
What I was addressing was that the fault is in the library (or libraries) you've tried, not that writing a client is inherently difficult.
XMPP isn't a big deal, except on a phone (Score:2)
Re: (Score:2)
Re: (Score:2)
I actually have a smartphone with a Jabber client, and since I primarily use IRC, I wrote some scripts to glue messaging between xmpp-irssi and irc (mostly a gateway between the two so that I could bridge my IRC session to my phone.) The dr
The 'X' means Extensible (Score:2)
One
XMPP decentralized online social networking ?! (Score:2)
[1] [xmpp.org]
Anything can be the next big thing (Score:2)
1) can overcome real difficulties (Something which overcomes the design principle that everything should be "downwards compatible" to be transported over web servers/proxies/http or funny extensions/hacks of these, overcomes a real problem).
2) Is supported by google
has chances to be a big thing.
Let's hope not (Score:2, Interesting)
For one thing, it is an example of how NOT to use namespaces in XML. Many elements are needlessly separated out, causing a lot of confusion and problems for simple xml parsers. Namespaces do not solve the problem of name conflicts, as the xmpp site still has a registry of namespace names. Separating out extensions - maybe, but the whole point of namespaces is to avoid conflicts when two _disjoint_ e
Re: (Score:2)
Re: (Score:2) | https://developers.slashdot.org/story/08/02/04/1320210/is-xmpp-the-next-big-thing | CC-MAIN-2017-43 | refinedweb | 3,406 | 70.63 |
table of contents
- stretch 4.10-2
- testing 4.16-2
- stretch-backports 4.16-1~bpo9+1
- unstable 4.16-2
NAME¶mbind - set memory policy for a memory range
SYNOPSIS¶
#include <numaif.h> long mbind(void *addr, unsigned long len, int mode, const unsigned long *nodemask, unsigned long maxnode, unsigned flags); Link with -lnuma.
DESCRIPTION¶mbind() thread must be privileged (CAP_SYS_NICE) to use this flag. If MPOL_MF_STRICT is also specified, then the call will fail with the error EIO if some pages could not be moved.
RETURN VALUE¶.¶The mbind() system call was added to the Linux kernel in version 2.6.7.
CONFORMING TO¶This system call is Linux-specific.
NOTES¶For. | https://manpages.debian.org/stretch/manpages-dev/mbind.2.en.html | CC-MAIN-2019-47 | refinedweb | 115 | 61.93 |
Pygame - Quick Tips
20 December 2013
Placement
Greetings. If you're starting up a new game and you want to get some assets quickly placed to see what it looks like, you can block out parts of a mock screen and then add code to listen for the arrow keys and move that asset by incrementing correctly. Finally, add a key (I used return) to report its x,y position. From there, you'll know your boundaries.
import pygame from pygame.locals import * def game_on(): pygame.init() screen = pygame.display.set_mode((296, 289)) background = pygame.image.load('background_296x289.png') playground = pygame.image.load('dummy_blocks.png') in_game = True x = 20 y = 15 while in_game: for event in pygame.event.get(): if event.type == QUIT: return if event.type == KEYDOWN: if event.key == K_DOWN: y += 1 if event.key == K_UP: y -= 1 if event.key == K_RETURN: print 'x=%d,y=%d' % (x,y) screen.blit(background, (0,0)) screen.blit(playground, (x,y)) pygame.display.flip() if __name__ == '__main__': game_on()
One thing you want to be careful about is your blit order. Remember -- the further away something is, the earlier it's blitted to screen.
Mousing
If you have a play area in your game that you would prefer not showing the mouse in, you can use pygame.mouse.set_visible() to toggle its visibility. A good game that this would be used for would be a breakout clone for instance.
To do it, just have a rect assigned to your play area and in your update loop, check if the mouse passes a collidepoint check.
# game loop while True: if playground.rect.collidepoint(pyg.mouse.get_pos()): pyg.mouse.set_visible(False) else: pyg.mouse.set_visible(True)
Now the mouse will show except when you're in the play area.
Trackbacks for this entry [ Trackback URL ]
My Blog Links
Recent Entries
See You Code Cowboy
on Apr 01 2014 12:42 PM
April Project: Tic Tac Toe
on Mar 31 2014 05:56 PM
Bulls and Cows
on Mar 26 2014 05:13 AM
Interesting Behavior
on Mar 26 2014 02:53 AM
Patterns in Python -- Second Thoughts
on Mar 24 2014 01:14 AM
Recent Comments
- andrewsw
on Mar 28 2014 05:35 PM
Interesting Behavior
- MentalFloss
on Mar 18 2014 04:40 PM
Leibniz Formula
- andrewsw
on Mar 18 2014 04:21 PM
Leibniz Formula
- MentalFloss
on Mar 18 2014 03:53 PM
Leibniz Formula
- andrewsw
on Mar 18 2014 03:30 PM
Leibniz Formula
Search My Blog
0 user(s) viewing
0 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s) | http://www.dreamincode.net/forums/blog/2274/entry-4638-pygame-quick-tips/ | CC-MAIN-2016-07 | refinedweb | 436 | 74.9 |
Adding a smart set via script doesn't work
I'm trying to add a smart set and always get an error ... what am I doing wrong?
from mojo.UI import SmartSet, addSmartSet s = SmartSet() s.name = "Test" s.query = u"Contours > 0" addSmartSet(s)
The error is:
Traceback (most recent call last): File "", line 6, in File "mojo/UI.pyc", line 360, in addSmartSet File "mojo/UI.pyc", line 390, in setSmartSets RoboFontError: Smart Set needs a query
ah, your aren't doing anything wrong
bug in setting smart sets.
setSmartSet seems not to be working nicely with groups....
will be fixed in the next update, thanks
Thanks! | https://forum.robofont.com/topic/233/adding-a-smart-set-via-script-doesn-t-work | CC-MAIN-2020-16 | refinedweb | 109 | 77.43 |
timeout_set, timeout_add, timeout_del, timeout_pending,
timeout_initialized - execute a function after a specified
period of time
#include <sys/types.h>
#include <sys/timeout.h>
void
timeout_set(struct timeout *to, void (*fn)(void *), void
*arg);
void
timeout_add(struct timeout *to, int ticks);
void
timeout_del(struct timeout *to);
int
timeout_pending(struct timeout *to);
int
timeout_initialized(struct timeout *to);
int
timeout_triggered(struct timeout *to);
The timeout API provides a mechanism to execute a function
at a given
time. The granularity of the time is limited by the granularity of the
hardclock(9) timer which executes hz(9) times a second. The
function
will be called at softclock interrupt level.
It is the responsibility of the caller to provide these
functions with
pre-allocated timeout structures. All functions in this API
may be used
in interrupt context below splclock().
This API replaces the historic functions timeout() and
untimeout().
The function timeout_set() prepares the timeout structure to
to be used
in future calls to timeout_add() and timeout_del(). The
timeout will be
prepared to call the function specified by the fn argument
with a void *
argument given in the arg argument. Once initialized, the
to structure
can be used repeatedly in timeout_add() and timeout_del()
and does not
need to be reinitialized unless the function called and/or
its argument
must change.
The function timeout_add() schedules the execution of the to
timeout in
at least ticks/hz seconds. Negative values of ticks are illegal. If the
value is `0' it will, in the current implementation, be
treated as `1',
but in the future it might cause an immediate timeout. The
timeout in
the to argument must be already initialized by timeout_set()
and may not
be used in calls to timeout_set() until it has timed out or
been removed
with timeout_del(). If the timeout in the to argument is
already scheduled,
the old execution time will be replaced by the new
one.
The function timeout_del() will cancel the timeout in the
argument to.
If the timeout has already executed or has never been added
the call will
have no effect.
The timeout_pending() macro can be used to check if a timeout is scheduled
to run.
The timeout_initialized() macro can be used to check if a
timeout has
been initialized.
The timeout_triggered() macro can be used to check if a
timeout is running
or has been run. The timeout_add() and timeout_del()
functions
clear the triggered state for that timeout.
These functions are implemented in the file
sys/kern/kern_timeout.c.
hz(9), hzto(9), sleep(9), splclock(9), tvtohz(9)
OpenBSD 3.6 June 23, 1996 | http://nixdoc.net/man-pages/OpenBSD/man9/timeout_add.9.html | CC-MAIN-2013-20 | refinedweb | 425 | 63.7 |
Last Updated on August 28, 2020.
Running the example creates the dataset and summarizes the shape of the input and output elements.
We can see that, as expected, there are 1,000 samples, each with 10 input features and three output features.
Next, let’s look at how we can develop neural network models for multiple-output regression tasks.
Neural Networks for Multi-Outputs
Many machine learning algorithms support multi-output regression natively.
Popular examples are decision trees and ensembles of decision trees. A limitation of decision trees for multi-output regression is that the relationships between inputs and outputs can be blocky or highly structured based on the training data.
Neural network models also support multi-output regression and have the benefit of learning a continuous function that can model a more graceful relationship between changes in input and output.
Multi-output regression can be supported directly by neural networks simply by specifying the number of target variables there are in the problem as the number of nodes in the output layer. For example, a task that has three output variables will require a neural network output layer with three nodes in the output layer, each with the linear (default) activation function.
We can demonstrate this using the Keras deep learning library.
We will define a multilayer perceptron (MLP) model for the multi-output regression task defined in the previous section.
Each sample has 10 inputs and three outputs, therefore, the network requires an input layer that expects 10 inputs specified via the “input_dim” argument in the first hidden layer and three nodes in the output layer.
We will use the popular ReLU activation function in the hidden layer. The hidden layer has 20 nodes, which were chosen after some trial and error. We will fit the model using mean absolute error (MAE) loss and the Adam version of stochastic gradient descent.
The definition of the network for the multi-output regression task is listed below.
You may want to adapt this model for your own multi-output regression task, therefore, we can create a function to define and return the model where the number of input and number of output variables are provided as arguments.
Now that we are familiar with how to define an MLP for multi-output regression, let’s explore how this model can be evaluated.
Neural Network for Multi-Output Regression
If the dataset is small, it is good practice to evaluate neural network models repeatedly on the same dataset and report the mean performance across the repeats.
This is because of the stochastic nature of the learning algorithm.
Additionally, it is good practice to use k-fold cross-validation instead of train/test splits of a dataset to get an unbiased estimate of model performance when making predictions on new data. Again, only if there is not too much data and the process can be completed in a reasonable time.
Taking this into account, we will evaluate the MLP model on the multi-output regression task using repeated k-fold cross-validation with 10 folds and three repeats.
Each fold the model is defined, fit, and evaluated. The scores are collected and can be summarized by reporting the mean and standard deviation.
The evaluate_model() function below takes the dataset, evaluates the model, and returns a list of evaluation scores, in this case, MAE scores.
We can then load our dataset and evaluate the model and report the mean performance.
Tying this together, the complete example is listed below.
Running the example reports the MAE for each fold and each repeat, to give an idea of the evaluation progress.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.
At the end, the mean and standard deviation MAE is reported. In this case, the model is shown to achieve a MAE of about 8.184.
You can use this code as a template for evaluating MLP models on your own multi-output regression tasks. The number of nodes and layers in the model can easily be adapted and tailored to the complexity of your dataset.
Once a model configuration is chosen, we can use it to fit a final model on all available data and make a prediction for new data.
The example below demonstrates this by first fitting the MLP model on the entire multi-output regression dataset, then calling the predict() function on the saved model in order to make a prediction for a new row of data.
Running the example fits the model and makes a prediction for a new row.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.
As expected, the prediction contains three output variables required for the multi-output regression task.
Further Reading
This section provides more resources on the topic if you are looking to go deeper.
Summary
In this tutorial, you discovered how to develop deep learning models for multi-output regression.
Specifically, you learned:
- Multi-output regression is a predictive modeling task that involves two or more numerical output variables.
- Neural network models can be configured for multi-output regression tasks.
- How to evaluate a neural network for multi-output regression and make a prediction for new data.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Lors de l’exécution est générée l’erreur suivante:
File “C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py”, line 703, in is_tensor
return isinstance(x, tf_ops._TensorLike) or tf_ops.is_dense_tensor_like(x)
AttributeError: module ‘tensorflow.python.framework.ops’ has no attribute ‘_TensorLike’
Comment résoudre?
Sorry to hear that, perhaps confirm that your version of Keras and TensorFlow are up to date:
The tips here may also help:
Hy
Running this example I get the following error:
AttributeError: module ‘tensorflow.python.framework.ops’ has no attribute ‘_TensorLike’
A solution?
What version of Keras and TensorFlow are you using?
You must use the follow versions or higher:
Hi Jason,
could you tell me why a model is compiled for each cross validation fold?
Each model requires training a new model from scratch in order to establish an unbiased estimate of model performance when making predictions on out of sample instances.
If you are new to k-fold cross-validation, you can get started here:
I thought a model had to be instantiated once and then was passed to the cross validation loop. I missed something I guess…
In the example below taken from one of your excellent article ( Add Binary Flags for Missing Values ) I understand that the model is instantiated and that this instance of the model is evaluated on each cross validation training folds :
[ step 1 ] model = RandomForest()
[ step 2 ] cv = RepeatedStratifiedKFold( n_splits = 10 , n_repeats = 3 )
[ step3 ] scores = cross_val_score( model , X , y , scoring = ‘accuracy’ , cv = cv , n_jobs = -1 )
Here it seems to me that for each training fold a model is instanciated and then evaluated on the corresponding testing folds.
Both logic seems different… or I missed something.
I tested passing the model to the evaluation function :
def evaluate_model( model , X , y ) :
results = list()
n_inputs = X.shape[ 1 ]
n_outputs = y.shape[ 1 ]
cv = RepeatedKFold( n_splits = 10 , n_repeats = 1 , random_state = 999 )
for train_ix, test_ix in cv.split( X ) :
X_train, X_test = X[train_ix], X[test_ix]
y_train, y_test = y[train_ix], y[test_ix]
model.fit( X_train , y_train , verbose = 0 , epochs = 100 )
mae = model.evaluate( X_test , y_test , verbose = 0 )
results.append( mae )
print( f’mae : {mae:.3f}’ )
return results
mae keeps decreasing… I do not understand why…
It is invalid as you continue to train the same model each loop.
The model must be re-defined and re-fit each cross-validation loop otherwise the evaluation is optimistic.
It does the same thing.
In that case, the model is created and fit a new for each cross-validation fold. You just don’t see it as it happens internally to the function.
OK. I thought the model was created once and then fitted on each cross validation fold.
I have been doing a little experiment.
cv = RepeatedStratifiedKFold( n_splits = 10 , n_repeats = 1 , random_state = 777 )
and then [ A ] :
> scores_A = []
>_A.append( score )
After that [ B ] :
> scores_B = []
> model = AdaBoostClassifier()
>_B.append( score )
The difference between [ A ] and [ B ] is that with [ B ] the model is instantiated outside the loop once whereas with [ A ] it is created anew for each fold.
scores_A and _B are the same ( even when I change the random state parameter for RepeatedStratifiedKFold and/or the model used : RandomForest…).
This experiment makes me think the model has to be created once and be fitted on each cross validation fold.
For me, the sole difference between model_A = AdaBoostClassifier() an model_B = AdaBoostClassifier() is there memory location this is why I do not understand why the get_model function is called in the evaluate_model function…
PS :
I was not able to replicate the scores given by
> cross_val_score( model , X , y , scoring = ‘roc_auc’ , cv = cv , n_jobs = -1 )
The cross-validation procedure requires the model be re-fit each evaluation.
Internally cross_val_score will clone the model and refit from scratch each iteration. This is functionality equilivient to re-defining and re-fitting each iteration.
HI Jason,
Just out of curiosity, why would you build a multi-output model instead of multiple models of single outputs? When would it be better/worse?
Try both and see what works best for your specific dataset.
Hi Jason. How can I apply those codes into specific datasets? Since you were using random values.
This will help you to load your dataset:
Hi Jason,
First of all, congratulations on your website and for your detailed explanations and examples. I really appreciate it!
I have a question for you, as I’ve already spent a considerable amount of time searching online, without significant success. How can we handle a situation where we have partial ground truth for our targets? (e.g. output vectors with some NaN values)
So far, I understand that if you provide a y_train with NaNs, then the loss function won’t behave properly. If we provided a loss function for each output variable (I think keras allows that with loss=[‘mse’, ‘mse’, …]), then in theory, we could dismiss a group of NaNs within a batch of an output variable, by filtering them out (practically making both y_true and y_pred = 0).
The problem is that if we create a custom loss function and try to replace NaNs with 0s in both vectors, then keras throws an error (I think it relates to the use of non-tensorflow functions to filter nans, thus making keras unable to compute the derivative of the loss function)
Could you think of an elegant solution on this problem? Or maybe a completely different approach? (i assume that this way is sensible from the optimization perspective)
Thanks in advance for your time!
Thanks!
It is common to replace missing inputs with an imputed value using statistics or a model.
For some models, you can mark missing values with a special value and allow the model to treat missing as just another value.
Also, you can mark missing values for some models and configure them to ignore them, e.g. a masking layer in neural nets.
I hope that gives you some ideas.
Hi Jason,
Thanks for your reply.
In this case, it’s not missing inputs, and I can’t really use any statistics to learn the missing targets.
Regarding the special values, I haven’t seen anything related in Keras. Are you aware of such symbol?
Also, I checked the masking layers, but that’s again only for the inputs. This wouldn’t affect the y_true in the loss function.
In general, it seems like a trivial problem which doesn’t seem to have a trivial solution…
Maybe I need to check how people handle missing labels on multi-label classification.
Hopefully I’ll figure it out soon!
You can use zero padding in the putput (yhat) then manually ignore zero padded values when using the output or evaluating predoctions.
This is very common in seq2seq problems in NLP.
This is a great nn-model for regression. I tried using mean sq log error for the loss, so I can interpret the reslt a bit better.
Now, when you evaluate or use the evaluation, is there a difference if you setup the repeat times as desired? Or just keep calling the evaluation function with just 2 or 3 repeats?
Just wandering with this algorithm as I never use tried RepeatedKFolds before.
Thanks for sharing J.
Perhaps you can keep the loss as mse, and use sq log error as a metric?
Repeated k-fold cross-validation is a good practice for stochastic models, if they are not too expensive to fit. 3 repeats is conservative, 10 or 30 is better.
More here:
can you please explain how the mean absolute error in Keras loss function is calculated on multi-output vectors? Is it the average of corresponding values in vectors averaged over dimensions of the output and samples?
I believe it is error averaged across variables and samples.
Hello
I have a question
My data is not time dependent
Not image and video
Which Deep Learning model is more suitable for predicting my data?
Thanks for guiding me
An MLP.
Also, this will help:
Hi Jason,
Can you be my teacher
I’m happy to answer questions about machine learning.
Hi, thanks for the tutorial.
If the goal is simply prediction, what are the benefits of fitting a multi-output NN instead of multiple single-output NN? What are the gains in this case? Is there a paper or reference you can recommend?
The problem will require a single or multiple outputs. You must use the model that achieves the goals of the project.
Hi, thank you for this article!
I didn’t get once you go through the Cross validation step how you choose one configuration with respect to the others in order to make prediction on new data. I mean, once all the loop is finished what has to be done?
See this:
Ok I think I’ve understood.
Based on what you have written in this article, I evaluate the model using k-fold-cross validation and based on what the score is I change the Layers and their parameters in my model accordingly. Then I make my network learning on all the data already used during validation and finally I make the predictions.
To conclude, Validation is used just to measure the performance of the model I have built, is that right?
The train set is used to fit the model.
The test set is used to evaluate the model.
The validation set can be used to tune the model or stop training the model at the right time.
More here:
Wondering about this: With “model.compile(loss=’mae’, optimizer=’adam’)”, I basically instruct keras to minimize the combined loss of both output values together. This averages out the two errors stemming from the two separate target values, which could lead to a large positive error on target 1 which is compensated by a large negative error on target 2.
I imagine to avoid this, I would have to create 2 separate submodels that optimize each loss individually – probably using the functional API?
Yes.
Another approach, a model with two output and two losses (so-called multi-output model):
Hi, I really appreciate your content!
I am starting with deep learning models and I have a project on mind.
What I want to do, giving certain input values (for example: 10 features), I want to predict a curve. I mean, I want to obtain a 2D curve (where Y axis will be force and X axis will be time). Can “Multi-output regression” be a solution? I will predict time steps (t0=5, t1=16, t2=26…).
What other solution can I use for this case?
thanks in advance
If you want a curve, then perhaps use curve fitting directly:
I tested this on my data set and found that it worked if iloc was used. ex:
X_train, X_test = X.iloc[train_ix], X.iloc[test_ix]
y_train, y_test = y.iloc[train_ix], y.iloc[test_ix]
Nice work!
Can I do this to forecast t+1, t+2 and so on?
Yes.
Hi Jason, how would it be for multi-output binary classification?
For example, forecast if t+1 is 0 or 1 and t+2 is 0 or 1 and t+3 is 0 or 1.
1. Output layer: model.add(Dense(n_outputs, activation=’sigmoid’))?
2. Loss function: ‘binary_crossentropy’?
Thanks in advance.
Great tutorial!!!
Yes, I believe so. Try it and see.
Hi Jason, first of all, thanks for your great content! I am also using MLP for doing some multi-output regression, but I found that when I tested the model, the output would always be the same regardless of the input (this also happened at training stage). I have normalized my input data and the dimension of my input and output are 450 and 120, respectively, also I used tanh activation function to bound my output within range [-1,1]. Do you have any suggestions on this? Thanks in advance 🙂
It may suggestion your model require further tuning for your dataset.
The suggestions here will help:
Hey Jason, I really love your works here. I’m working on a dataset_1 where the output classes of this dataset_1 has some other features dataset, say dataset_2, that the model could also learn from. The challenge I’m facing is that dataset_1 and dataset_2 are totally different, so there’s no way I could merge them on some common features.
I’d like to know if there’s a way to train a model that would be able to learn on dataset_1 then subsequently learn on dataset_2?
I am considering using dimensionality reduction to reduce the features of the dataset_2 to a single value and then use this single value as an output to dataset_1 in a multi-output model. Do you think this is a good approach?
Thanks!
Try it and compare to other approaches.
Perhaps try to ensemble their predictions?
Thanks a lot for this amazing article. I love your works. I actually need some advice on a multioutput regression problem. In the problem, the outputs are percentage. and all the outputs need to sum up to 1.
For example, i have to predict 3 outputs A, B, C. each of them can be any value between 0 and 1. let’s say,
A = 0.6,B = 0.3,C = 0.1 or A = 1.0, B = 0.0, C = 0.0
so, A+B+C is 1. how do i approach this problem.
Thanks in advance.
Thanks!
Use a softmax activation:
Hi
I appreciate your post. I have a question, how to determine the number of hidden layers and their dense? Is there any relation between them and the shape of input/output?
Thanks.
Good question, I answer it here:
Hey Jason,
Absolutely enjoy reading these concise tutorials. What are the available metrics for multi-output regression models when using grid search? When compiling the model, any other metric besides [“Accuracy”] raises an error. Is accuracy the MAE or R^2 value in this case?
Thanks.
You can use the same old regression metrics either for overall error or per output variable error.
Accuracy is inappropriate for regression, you can use MSE, RMSE or MAE as common error metrics.
Hi
If I want to build deep model , as output will be vector of 20 elements and each element will take a value from on two possible values …..what kind of system i can use??,, any hep ..to solve this problem
I recommend testing a suite of different models in order to discover what works well or best for your dataset.
Perhaps start with a simple MLP.
thanks for reply
if any link to MLP example to fellow??
Yes, the above tutorial is exactly this, an MLP (multilayer perceptron) for multi-output regression.
Hi there, first of all thank you for the tutorial! This website has been immensely helpful for me in recent months as I’ve started to incorporate machine learning into my research. My main question for this post is why you chose he_uniform for your kernel initialization on the output layer. I know that it’s the best choice for relu activations, but I can’t find anything anywhere saying that it should also be used for linear activation. Maybe you have a good source/reason for this choice here? To be honest, I can’t find much about what is the best canned initializer for linear activation so I’m really curious to hear your thoughts.
You’re welcome!
It probably should not be used for linear activation. Probably won’t make a difference though.
Hi
If there is example based on dividing data set into training and testing Multi-Output Regression
It would be the same for single output regression:
Unless, you have a time series, then this will help:
Hi,
you mentioned that if the data set is small , can use k folds for evaluation …what about if the data set is large?? , for example ..instead of 1000 , maybe 5000 or 10000
Those are still small datasets, and k-fold cross validation.
Nevertheless, for very large data (millions/billions of samples) or for data where small samples are stable/stationary, you can use a train/test split.
okay..Thanks alots Jason
Hi ,
May I know how to import x y data which i have as excel instead of auto generated x y data as per above code.
I want to predict multiple outputs and above concept is nice to start with, but since i am new to coding would like to get help on how to import my excel data of multiple xs and multiple ys
Thank you
Your help will be much appreciated
Save your excel to CVS, then load your CSV as a numpy array:
which deep learning will be used for prediction of crop production ,humidity ,temperature and pH and also rain fall ?
Hi, just wondering, how can this neural network use multiple inputs and outputs if it is using Keras’s sequential API? Everything I’ve read online says that a Functional API is required for multiple inputs and outputs? thanks!
Yes, the functional API is required if you want to use separate input models or output models.
To have a vector input or vector output the sequential model can be used directly.
Thank you for your reply, I really appreciate it. Would it be possible to explain the difference between using “seperate input models” and simply using “vector input or vector output” if it wouldn’t be too much trouble? For example, I have data with 5 numerical inputs and 9 numerical outputs. The inputs represent the performance characteristics of a op-amp, e.g gain and slew rate, the outputs are the widths of transistors which give those performance characteristics. Would these be vector inputs and outputs or separate models? Sorry if this is a foolish question, this is all quite new to me. Thanks again for your help and this fantastic article.
Separate input models would be multiple disjoint vectors as input to the model for example.
You can see models with separate input models here:
Yes, you’re describing a single model that takes a vector in and predicts a vector out. You could also model it with a separate “model” for output of each element in the output vector if you want – this might make sense if the elements were unrelated/uncorrelated.
Hi Jason,
I have a question about activation functions in multi-output regression neural networks. I notice you choose the default linear function for the output and ReLU for the hidden layer.
In my case, my outputs can be very small numbers, and often the predictions return negative values which are physically meaningless. How can I restrict the outputs to be positive only? Is a linear output required for regression models, or can I change the output transfer function to tansig, logsig, etc.?
Thanks!
Perhaps you can use a sigmoid activation then scale the output to the desired range.
Hi! Nice work
Please help me here:
yhat = model.predict(newX)
model is not defined. Rest works fine I think
Why this error
Perhaps you have skipped some lines of code in the example, this will help:
Hi Jason,
Great!! thank you so much for your nice tutorial. However, can I know how to develop an explainer for developing an interpretable model such as Permutation Feature Importance in a multi-output regression?
Thank you
Sorry, I cannot help you with model interpretation – I don’t have tutorials on this topic.
Hi Jason,
Would you please help me that how I can develop multi output classification neural network?
Thanks
See this example:
Hi Jason,
Thanks for this tutorial, helped me on a real project.
I have a related question please.
I have a set of image matrix data set (lets say red, green, blue, white etc.) and the output colour is decided by a set of three input (x, y, z) (numerical values). Therefore the data looks like this (everything numerical, nothing categorical):
Input
X1,Y1,Z1 –> Blue Matrix (flattened 1-D arrays)
X2,Y2,Z2 –> Red Matrix
‘
‘
Xn,Yn,Zn –> White Matrix
Now I want build a NN regression model, like you showed here, where if [X,Y,Z] are input, it predicts the entire colour matrix (/ flattened 1-D array)
now, I understand this output layer will have a shape = shape(1-D colour matrix) (similar to 2 in your example). I also understand that the output layer’s shape is >> input layer’s size.
Can you please give some comments ? is this possible (technically I dont see why not)? Which algorithm you suggest is ideal.
thanks
Perhaps the model can predict a class label and you can write code to then create the matrix – if it is the same for each class label.
Hi,
First of all, thank you for this amazing explanation, it was really helpful.
My question is, can we use RNN or LSTM to predict many output variables because I’ve been searching and found LSTM may be the best option but didn’t found any implementation to start with.
Thank you.
You’re welcome.
Yes, see this:
Hello
I want to know how MAE for multi regression output is calculated numerically , if you can mention the mathematical equation for better understanding?
Thanks in advance
Mean of the absolute differences, more here:
Dear Jason,
Thank you for this nice tutorial.
I have a complex multi-output regression task, in which, the input elements and output elements are not independent. I have designed a network with multi-layers of 1D convolutions by trial and error. I was wondering if you could recommend a well-known network architecture for multi-output regression problems.
I guess it makes more sense to optimize the hyperparameters of a well-known model to my problem rather than designing it from the scratch.
Thank you in advance,
Samaneh
We cannot know what architecture will work well or best for a dataset, I recommend testing a suite of models and model configurations in order to discover what works best for your specific dataset.
Hi,
I run this code: I have two features(inputs) and 13 output, but I have this error:
—————————————————————————
TypeError Traceback (most recent call last)
in
16 mae = model.evaluate(x_test, y_test, verbose=0)
17 # store result
—> 18 print(‘>%.3f’ % mae)
19 results.append(mae)
20 return results
TypeError: must be real number, not list
######################################
def evaluate_model(x, y):
results = list()
n_inputs, n_outputs = x.shape[1], y.shape[1]
# define evaluation procedure
cv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)
# enumerate folds
for train_ix, test_ix in cv.split(x):
# prepare data
x_train, x_test = x[train_ix], x[test_ix]
y_train, y_test = y[train_ix], y[test_ix]
# define model
model = build_regression(n_inputs, n_outputs)
# fit model
model.fit(x_train, y_train, verbose=0, epochs=100)
# evaluate model on test set
mae = model.evaluate(x_test, y_test, verbose=0)
# store result
print(‘>%.3f’ % mae)
results.append(mae)
return results
Sorry to hear that, these tips may help:
Hi Jason Brownlee,
Thank you for this pedagogically explained model.
I would like to know how I can save this code in a file. Do you have a code to save it?
You’re welcome.
This will help you to save the code:
Thanks Jason Brownlee, but sorry that was a stupid question.
No problem.
Hi Jason, Just I want to Train a model with a set of inputs in numbers and set of outputs in numbers without knowing relationship between them(input and output).
Yes, that is the definition of regression problems.
Hi, first of all, thank you for the tutorial! my question is: I have students’ id as a sample and I want to predict 3 grades in the future to evaluate their performance but the problem is that the student id is repeated because they have many homework and many quizzes and so on. how can I predict the grades for each student separately? Then I want to save these predicted grades in a new file with a unique student-id to decide the student performance. Note: the repeated for student-id are different from student to other. any suggestion? Thanks in advance
Student id is a nominal data. This should not be input to the model. I would suggest you to create a vector for each student id, holding the grades of homework and quiz, and predict the final grade. No student id should be in this vector.
Hi, I’ve bought some of your books and they are great. BTW, for multi outputs regression, are there different weights and bias for each output? Or all outputs share the same w and b? In that case, how are the performance of multi outputs regression compared to separate single output regression?
Likely different because there is nothing in the model to enforce that they should be the same (but you can construct a model that way if you insist). For performance comparison, I doubt if that is possible because it sounds like you are comparing apples to oranges.
Hi, there is a shared metrics between the classification and regression? I want to compare the performance of regression NN with classification NN?
You’re comparing apples to oranges. Note, regression is about predicting continuous values that the numbers have its literal meaning. Classification, however, are predicting nominal values that the numbers at the output are just names. This vast difference causes one metric can make no sense in the wrong problem.
First of all, congratulations on your website and for your detailed explanations and examples. I really enjoy it!
Multiple output regression involves predicting two or more numerical variables.
In the end (# evaluate a model using repeated k-fold cross-validation), on the part of loading dataset, this error apears
ValueError: too many values to unpack (expected 2)
Can you tell me what can be?
Appreciated.
Can’t tell what exactly it is but this is how to trigger this error:
In python you can do multiple assignments in one line using tuple notation as above. But if the number of elements on either side of the assignment do not match, you have this “too many values to unpack” error. | https://machinelearningmastery.com/deep-learning-models-for-multi-output-regression/ | CC-MAIN-2022-05 | refinedweb | 5,280 | 63.49 |
I am trying to write this code, but I am having problem with using floating point in the while. The code works, but when I input the number, I get some strange result. What's wrong?
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int hourWorked; double hourlyRate; double total; total = 0; double salary; printf( "Enter hour Worked: "); scanf("%d", &hourWorked); while (hourWorked != -1) { total = total + hourWorked; printf( "hourly Rate: " ); scanf("%d", &hourlyRate); // Initialize gallon. printf( "Enter hour Worked: "); scanf("%d", &hourWorked); salary = total * hourlyRate; printf( "Miles gallons was %d\n\n", salary ); } system( "PAUSE"); return 0; } | https://www.daniweb.com/programming/software-development/threads/412258/problem-with-using-double-data-type-in-while-loop | CC-MAIN-2019-04 | refinedweb | 101 | 81.33 |
We can refer to each individual element of the array using an element's index enclosed in brackets.
The index for the first element is 0, the second element 1, the third element 2, and so on.
This is called zero-based indexing. The index for the last element of an array is the length of the array minus 1.
If we have an array of length 5, the indexes of the array elements would be 0, 1, 2, 3, and 4.
It is a runtime error to refer to a non-existing element of an array.
For example, using myID[5] in the code will throw an exception, because myID has a length of 5 and myID[5] refers to the sixth element, which is non-existent.
We can assign values to elements of an array as follows:
myID[0] = 10; // Assign 10 to the first element of myID myID[1] = 20; // Assign 20 to the second element of myID myID[2] = 30; // Assign 30 to the third element of myID myID[3] = 40; // Assign 40 to the fourth element of myID myID[4] = 50; // Assign 50 to the fifth element of myID
The following statement assigns the value of the third element of the myID array to an int variable temp:
int temp = myID[2]; // Assigns 30 to temp
An array object has a public final instance variable named length, which contains the number of elements in the array.
int[] myID = new int[5]; // Create an array of length 5 int len = myID.length; // 5 will be assigned to len
length is the property of the array object.
Until we create the array object, we cannot use its length property.
Typically, elements of arrays are accessed using loops.
for (int i = 0 ; i < myID.length; i++) { myID[i] = (i + 1) * 10; }
Array elements are always initialized.
Array elements of primitive data type are initialized to the default value for their data types.
For example, the numeric array elements are initialized to zero, boolean elements to false, and the reference type elements to null.
The following code illustrates the array initialization:
intArray[0], intArray[1] and intArray[2] are initialized to zero by default.
int[] intArray = new int[3];
bArray[0] and bArray[1] are initialized to false.
boolean[] bArray = new boolean[2];
An example of a reference type array. strArray[0] and strArray[1] are initialized to null.
String[] strArray = new String[2]
All 100 elements of the person array are initialized to null.
Person[] person = new Person[100];
The following illustrates the array initialization for an instance variable and some local variables.
public class Main { private boolean[] bArray = new boolean[3]; // An instance variable /* www .j a v a 2 s . c o m*/ public Main() { for (int i = 0; i < bArray.length; i++) { System.out.println("bArray[" + i + "]:" + bArray[i]); } } public static void main(String[] args) { int[] myID = new int[3]; // A local array variable for (int i = 0; i < myID.length; i++) { System.out.println("myID[" + i + "]:" + myID[i]); } String[] name = new String[3]; // A local array variable for (int i = 0; i < name.length; i++) { System.out.println("name[" + i + "]:" + name[i]); } } }
The code above generates the following result. | http://www.java2s.com/Tutorials/Java/Java_Data_Type/0310__Java_Array_Element.htm | CC-MAIN-2018-34 | refinedweb | 535 | 63.9 |
I'm really confused about how this code works.
Suppose the Inputs for the list are [ C, B, A, exit].
On the first "for" statement, it will swap around the list positions 0 and 1, which are C and B.
This would lead to a new list with [B, C, A]
However, why is it that on the second set of "for" statements, it would swap around A and B instead of C and A? This can be seen in the photo where the output says that it will swap B and A. I'm so confused as to why it would do that when it should be using positions 1 and 2 of the list instead.
I have tried hand-tracing the code and I always get that C and A should have swapped instead. Can someone help explain it to me? Thank you very much in advance
def bubble(alist):
count = 0
count2 = 0
for length in range(len(list)):
for i in range(len(list) - 1):
if list[i] > list[i + 1]:
print("Swapping", list[i + 1], list[length])
tmp = list[length]
list[length] = list[i+1]
list[i + 1] = tmp
list = []
while True:
val = input()
if val == "exit":
break
list.append(val)
counts = bubble(list)
print(list)
Your comparison
if list[i] > list[i + 1]:
does not match your swap code
tmp = list[length] list[length] = list[i+1] list[i + 1] = tmp
Either change you comparison to
if list[i + 1] > list[length]
or change your swap code to
tmp = list[i + 1] list[i + 1] = list[i] list[i] = tmp
Also, you should really never use
list as a variable name as it is a built-in type. | https://codedump.io/share/9P03IHwmqiPC/1/understanding-bubble-sort-in-python | CC-MAIN-2017-13 | refinedweb | 284 | 80.14 |
Error building Qt 5.9.1 from source
- drmhkelley last edited by
Not certain whether or not this is the correct topic for this question - let me know if it should go somewhere else
I want to build Qt 5.9.1 from source, using recent version of MinGW (G++ 6.2.0) and followed the on-line instructions (for using built-in opengl, not ANGLE). The build failed while compiling component qwindowswindow.cpp (path doesn't matter) with error
In file included from qwindowsintegration.cpp:75:0:
........\include\QtEventDispatcherSupport\5.9.1/QtEventDispatcherSupport/private/qwindowsguieventdispatcher_p.h:1:94:
fatal error:
../../../../../src/platformsupport/eventdispatchers/qwindowsguieventdispatcher_p.h:
No such file or directory
#include "../../../../../src/platformsupport/eventdispatchers/qwindowsguieventdispatcher_p.h"
The problem is one too many "../" in that include statement. Manually fixed it in "............../private/qwindowsguieventdispatcher_p.h" and now things are on track.
Is there an "official" way to pass notice for this apparent Qt source bug?
- SGaist Lifetime Qt Champion last edited by
Hi,
In what path did you install Qt ?
In what path are you building Qt ?
What parameters did you pass to configure ?
- drmhkelley last edited by
I could provide that, but doubt it's relevant. Everything cranked along find until I found that anomaly. And after that, everything went fine until I bumped into some error making the qtlocation package. I just re-configured to skip that step. Won't know whether it all works or not til it either does or I hit some other glitch. | https://forum.qt.io/topic/83648/error-building-qt-5-9-1-from-source/3 | CC-MAIN-2022-21 | refinedweb | 248 | 52.76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.