This chapter describes how to access Java from a script interpreted by the Nashorn engine.
The sections in this chapter contain examples of script statements interpreted by the Nashorn engine in interactive language shell mode. This interactive shell is started by running the jjs
command without any scripts passed to it. This is useful for trying things out, but the main purpose of the Nashorn Java API is to write Java applications as scripts that can be interpreted by the Nashorn engine.
There are two approaches to access packages and classes using Nashorn: the traditional approach is to use the Packages
global object, and the recommended approach is to use the Java
global object. This section describes both approaches.
The predefined top-level Packages
object enables you to access Java packages and classes using their fully qualified names, as if they are properties of the Packages
object. The following example shows how you can access the MyPackage
package and its MyClass
class if MyPackage.jar
is in your class path:
jjs> Packages.MyPackage [JavaPackage MyPackage] jjs> Packages.MyPackage.MyClass [JavaClass MyPackage.MyClass]
Accessing standard Java packages and classes is more straightforward than accessing custom packages and classes. For your convenience, there are global objects defined for each of the standard Java packages: com
, edu
, java
, javafx
, javax
, and org
. They have aliases that correspond to properties of the Packages
object. The following example shows how you can access the java.lang
package and the java.lang.System
class:
jjs> java.lang [JavaPackage java.lang] jjs> typeof java.lang object jjs> java.lang.System [JavaClass java.lang.System] jjs> typeof java.lang.System function
As you can see from the previous example, Nashorn interprets Java packages as JavaPackage
objects, and Java classes as JavaClass
function objects, which can be used as constructors for the classes. For more information about instantiating a class, see Creating Java Objects.
The traditional approach for accessing Java packages and classes is intuitive and straightforward, but at the same time, it can be inefficient, limited, and error-prone for the following reasons:
Each property access has a cost, so accessing a package or class in a deep hierarchy can be slow.
There is no special syntax for creating Java arrays. You must use the java.lang.reflect.Array
class as a workaround.
If you misspell a class name, Nashorn assumes that you provided a package name, and interprets it as a JavaPackage
object instead of a JavaClass
function object. You might not be aware of this until an error is thrown when you attempt to use it as a class. To avoid this, use the typeof
operator to conditionally test that the construct you are trying to access is interpreted as a function object. The following example shows how this conditional check works:
jjs> typeof java.lang.System == "function" true jjs> typeof java.lang.Zyztem == "function" false
To avoid the disadvantages of the approach previously described, Nashorn defines the Java
global object that has several functions for working with Java classes. The Java.type()
function takes a string with the fully qualified Java class name, and returns the corresponding JavaClass
function object. The following example shows how you can access the java.lang.System
class:
jjs> Java.type("java.lang.System") [JavaClass java.lang.System]
Similar to importing classes in Java, it is a good practice to declare variables of JavaClass
type at the beginning of a script. The following example shows how you can declare the System
variable and give it a value of the java.lang.System
class:
jjs> var System = Java.type("java.lang.System") jjs> System [JavaClass java.lang.System]
To instantiate a class, pass the JavaClass
function object to the new
operator. Nashorn invokes the corresponding constructor based on the arguments passed to the function. The following example shows how you can instantiate the java.util.HashMap
class with the default initial capacity and with the initial capacity set to 100:
jjs> var HashMap = Java.type("java.util.HashMap") jjs> var mapDef = new HashMap() jjs> var map100 = new HashMap(100)
You can use the standard dot notation to access static fields, methods, and inner classes as follows:
jjs> Java.type("java.lang.Math").PI 3.141592653589793 jjs> Java.type("java.lang.System").currentTimeMillis()<PHONE_NUMBER>330 jjs> Java.type("java.util.Map").Entry [JavaClass java.util.Map$Entry]
An inner class can also be accessed using internal representation with the dollar sign ($
) as the separator, or a dot, which is consistent with Java:
jjs> Java.type("java.util.Map$Entry") [JavaClass java.util.Map$Entry] jjs> Java.type("java.util.Map.Entry") [JavaClass java.util.Map$Entry]
To invoke an instance method or access an instance field of an object, use the dot operator, similar to how it is done in Java. The following example shows how you can call the toUpperCase()
method on a String
object:
jjs> var String = Java.type("java.lang.String") jjs> var str = new String("Hello") jjs> str Hello jjs> var upper = str.toUpperCase() jjs> upper HELLO
Nashorn also supports member access using the bracket notation, where you specify the name of the member as a string between brackets ([]
) that immediately follow the class (in case of a static member) or object (in case of an instance member). This method is defined by the ECMAScript as an alternative to the dot notation, and is not intuitive for Java developers. However, it can be used to resolve method overload ambiguity. By default, Nashorn uses the overloaded method that best matches the arguments, and this is not always what you expect. For example, if you want to print a double
value, you must use the java.lang.System.out.println(double)
method overload, as shown in the following example:
jjs> Java.type("java.lang.System").out.println(10) 10 jjs> Java.type("java.lang.System").out["println(double)"](10) 10.0
Nashorn enables you to treat accessor and mutator methods in JavaBeans as equivalent JavaScript properties. The name of the property is the name of the JavaBean method without the get
or set
suffix, and starts with a lowecase letter. For example you can call the getYear()
and setYear()
methods in a java.util.Date
object using the year
property as follows:
jjs> var Date = Java.type("java.util.Date") jjs> var date = new Date() jjs> date.year + 1900 2013 jjs> date.year = 2014 - 1900 114 jjs> date.year + 1900 2014
To access a Java array class, pass to the Java.type()
function the type of objects that comprise the array followed by a pair of brackets (similar to Java syntax). The following example shows how you can access a Java array of integers and a Java array of String
objects:
jjs> Java.type("int[]") [JavaClass [I] jjs> Java.type("java.lang.String[]") [JavaClass [Ljava.lang.String;]
After you have the array type object, you can use it to instantiate an array as you do any other class. You can access array entries by their indexes, and use the dot or bracket notation to access members (similar to Java syntax), as shown in the following example:
jjs> var IntArrayType = Java.type("int[]") jjs> var arr = new IntArrayType(10) jjs> arr[1] = 123 123 jjs> arr[2] = 321 321 jjs> arr[1] + arr[2] 444 jjs> arr[10] java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 10 jjs> arr.length 10
If you have an existing JavaScript array, you can convert it to a Java array using the Java.to()
function. The following example shows how you can convert a JavaScript array of strings "a"
, "b"
, and "c"
, to a java.lang.String[]
array with the same values:
jjs> var jsArr = ["a","b","c"] jjs> var strArrType = Java.type("java.lang.String[]") jjs> var javaArr = Java.to(jsArr, strArrType) jjs> javaArr.class class [Ljava.lang.String; jjs> javaArr[0] a
You can iterate through a Java array's indexes and values using the for
and for each
statements as follows:
jjs> for (var i in javaArr) print(i) 0 1 2 jjs> for each (var i in javaArr) print(i) a b c
Strings are interpreted by Nashorn as java.lang.String
objects. However, if you concatenate two strings you get an instance of the jdk.nashorn.internal.runtime.ConsString
class. This is not a problem for most scripts, because both classes implement the java.lang.CharSequence
interface, but in some cases, Nashorn passes the ConsString
object when a method expects a java.lang.Object
argument. To avoid this, use the String()
function to ensure that the string is a Java String
object, as shown in the following example:
jjs> var a = "abc" jjs> a.class class java.lang.String jjs> var b = a + "def" jjs> b.class class jdk.nashorn.internal.runtime.ConsString jjs> var c = String(b) jjs> c.class class java.lang.String
Nashorn interprets numbers as java.lang.Double
, java.lang.Long
, or java.lang.Integer
objects, depending on the computation performed. You can use the Number()
function to force a number to be a Double
object, as shown in the following example:
jjs> var intNum = 10 jjs> intNum.class class java.lang.Integer jjs> var dblNum = Number(intNum) jjs> dblNum.class class java.lang.Double
Nashorn interprets Java collections as arrays. You can access collection elements using the index in brackets ([]
) and iterate over the values of a collection using the for each
statement, as shown in the following example:
jjs> var ArrayList = Java.type("java.util.ArrayList") jjs> var alist = new ArrayList() jjs> alist.add("a") true jjs> alist.add("b") true jjs> alist.add("c") true jjs> alist[1] b jjs> for each (var i in alist) print(i) a b c
Unlike other collections, to iterate over keys and values in a map, you must use the keySet()
and values()
methods. The following example shows how you can create a HashMap
object and iterate over its keys and values:
jjs> var HashMap = Java.type("java.util.HashMap") jjs> var hm = new HashMap() jjs> hm.put("name", "Bob") jjs> hm.put("age", 40) jjs> hm.put("weight", 180) jjs> for each (var i in hm.keySet()) print(i) weight age name jjs> for each (var i in hm.values()) print(i) 180 40 Bob
You can extend a class using the Java.extend()
function that takes a Java type as the first argument and method implementations (in the form of JavaScript functions) as the other arguments. Example 2-1 shows a script that extends the java.lang.Runnable
interface and uses it to construct a new java.lang.Thread
object.
Example 2-1 Extending a Java Class
var Run = Java.type("java.lang.Runnable"); var MyRun = Java.extend(Run, { run: function() { print("Run in separate thread"); } }); var Thread = Java.type("java.lang.Thread"); var th = new Thread(new MyRun());
Nashorn can automatically extend single abstract method (SAM) classes if you provide the function for implementing the method as the argument to the constructor. Example 2-2 shows a script that extends the java.lang.Runnable
interface and uses it to construct a new java.lang.Thread
object, but it uses fewer lines of code than in Example 2-1, because the Java.extend()
function is called automatically for a SAM class.
Example 2-2 Extending a Java SAM Class
var Thread = Java.type("java.lang.Thread") var th = new Thread(function() print("Run in a separate thread"))
For more information about the capabilities of the Java.extend()
function, see Java Scripting Programmer's Guide at http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/index.html
The jdk.nashorn.api.scripting.ClassFilter
interface, https://docs.oracle.com/javase/8/docs/jdk/api/nashorn/jdk/api/scripting/ClassFilter.html
, enables you to restrict access to specified Java classes from scripts run by a Nashorn script engine. Applications that embed Nashorn, in particular, server-side JavaScript frameworks, often have to run scripts from untrusted sources and therefore must limit access to Java APIs. These applications can implement the ClassFilter
interface to restrict Java class access to a subset of Java classes. To do so, client applications must use Nashorn APIs to instantiate the Nashorn script engine.
To use a class filter, implement the ClassFilter
interface and define the method boolean exposeToScripts(String)
. The String
argument is the name of the Java class or package that the Nashorn script engine encounters when it runs a script. Define the method exposeToScripts
such that it returns false
for those classes and packages you want to prevent scripts from accessing. Then, create a Nashron script engine with with your class filter with the method NashornScriptEngineFactory.getScriptEngine(ClassFilter)
or NashornScriptEngineFactory.getScriptEngine(String[], ClassLoader, ClassFilter)
.
If you are using a security manager, then Nashorn allows a script to use the Java Reflection APIs (for example, the java.lang.reflect
and java.lang.invoke
packages) only if the script has the nashorn.javaReflection
run time permission. If you are using a class filter, then Nashorn prevents access to Java Reflection APIs even when a security manager is not present. Note that you do not need to use a class filter if the Java Reflection APIs are available because a script can use the Class.forName(String)
to circumvent the class filter.
The following example demonstrates the ClassFilter
interface:
Example 2-3 MyClassFilterTest.java
import javax.script.ScriptEngine; import jdk.nashorn.api.scripting.ClassFilter; import jdk.nashorn.api.scripting.NashornScriptEngineFactory; public class MyClassFilterTest { class MyCF implements ClassFilter { @Override public boolean exposeToScripts(String s) { if (s.compareTo("java.io.File") == 0) return false; return true; } } public void testClassFilter() { final String script = "print(java.lang.System.getProperty(\"java.home\"));" + "print(\"Create file variable\");" + "var File = Java.type(\"java.io.File\");"; NashornScriptEngineFactory factory = new NashornScriptEngineFactory(); ScriptEngine engine = factory.getScriptEngine( new MyClassFilterTest.MyCF()); try { engine.eval(script); } catch (Exception e) { System.out.println("Exception caught: " + e.toString()); } } public static void main(String[] args) { MyClassFilterTest myApp = new MyClassFilterTest(); myApp.testClassFilter(); } }
This example prints the following:
C:\Java\jre8 Create file variable Exception caught: java.lang.RuntimeException: java.lang.ClassNotFoundException: java.io.File
The MyClassFilterTest.java
example does the following:
Implements the ClassFilter
with the inner class MyCF
by defining the method exposeToScripts
. In this example, the method exposeToScripts
returns false if its String
argument is java.io.File
; otherwise it returns true
.
Creates a Nashorn script engine, engine
, with the method NashornScriptEngineFactory.getScriptEngine(ClassFilter)
. The example invokes getScriptEgnine
with an instance of MyCF
.
Runs the following script with the Nashorn script engine engine
:
print(java.lang.System.getProperty(\"java.home\")); print(\"Create file variable\"); var File = Java.type(\"java.io.File\");
The class filter in engine
checks each Java package and class in the script. When the class filter encounters the class java.io.File
, the class filter returns false
, and the Java.type
function throws a ClassNotFoundException
.


Dr Wan Azizah: Corruption eradication is a non-stop effort
KUALA LUMPUR, Nov 19 — Deputy Prime Minister Datuk Seri Dr Wan Azizah Wan Ismail said efforts to eradicate corruption are being pursued indefinitely to ensure prosperity in the country.
She said corruption was like cancer destroying a body of any government and could spread rapidly if the disease was not contained.
“Extensive efforts are being made to eradicate corruption that has taken root in all walks of life,” she said when addressing the launch of the Hikayat Raja Pasai book at the International Institute of Islamic Thought and Civilisation (ISTAC) here today
She said all quarters could learn from the Hikayat Raja Pasai which emphasised on the morals of ‘sang penguasa’ (the ruler) as determinants of a government’s wellbeing, in line with the teaching of Islam.
Dr Wan Azizah said just like what was revealed in the book, the Malaysian government of the day strongly upheld the principles of Islamic teachings that emphasize human morality in developing the country.
“In the Hikayat Raja Pasai narrative, the writer tried to show that due to the cruelty and greed of its king, Pasai has been conquered by Majapahit,” she said.
She said the book also showed at how Samudera-Pasai turned into a prosper nation through its diversity of its people, a criteria shared by Malaysia.
Dr Wan Azizah said the Federal Constitution of Malaysia stated that Islam is the religion of the Federation, but the constitution also provided protection to other religions.
“The constitution of this country rejects all forms of extremism from any quarters in practising religion,” she added.
Hikayat Raja Pasai is one of the Malay masterpieces which was edited by Prof Emeritus Datuk Dr Ahmat Adam. — Bernama


Thank you for registering at {BOARD_NAME}
Your account is activated and ready to go!
To login, visit {BOARD_NAME} and use the following credentials:


Caret
.js
Textarea
Type something here for fun!!
ContentEditable
Hello, some
bold
and
italic
and
bold
text
iframe body


OPPO debuts Realm X2 Pro, Realme 5S in India
by Rei PadlaOPPO is launching two new smartphones: the Realme X2 Pro and the Realme 5S. The new Realme phone follows the Realme 5 and Realme 5 Pro introduced last August with powerful quad cameras. The Realme X2 Pro was already introduced last month, making an impression with the 64MP Quad camera setup and 20x Hybrid Zoom. The new Realme 5s is only a mid-ranger but already comes with decent specs. Both of these units have arrived in India so we can expect the OPPO brand will further expand in the country.
Realme X2 Pro
The Realme X2 Pro has been unveiled in Europe and China as a flagship offering last month. In India, it costs INR 29,999 which is about $420 and still cheaper than its price in Europe.
The smartphone will also have a Master Edition version. It comes equipped with a 6.5-inch Super AMOLED screen with 90Hz fluid display (refresh rate), 1080 x 2400 pixel resolution, Qualcomm Snapdragon 855+ processor, quad rear camera setup (64MP + 13MP + 8MP + 2MP), 20x hybrid zoom, 16MP selfie camera, 6GB/12GB RAM, 256GB onboard storage, and a 4000mAh battery with 50W SuperVOOC Flash Charging. The battery can be fully charged within 35 minutes. It runs on Android 9 Pie OS topped by ColorOS 6.1 but we’re assuming it will get ColorOS 7 soon.
Realme 5S
The Realme 5S is a follow-up to the Realme 5 and Realme 5 Pro. Price starts at ₹9,999 which is around $139. The mid-range phone already boasts a 48MP Samsung GM1 camera, 8MP 119° ultra-wide, 2MP macro, and 2MP depth sensor. You can say the camera setup is similar to the Realme 5 Pro.
Other features include 4GB of RAM, 64GB or 128GB onboard storage, a 6.5-inch screen, 720p+ resolution, Qualcomm Snapdragon 665 processor, and a large 5000mAh battery. The features are impressive already for a sub $150 phone. OPPO Realme 5S will be available on Realme.com and Flipkart beginning on November 29.


You'll be the first to have exclusive access to the best curated collection
of activewear, athleisure and accessories from Kokuré.
Help us spread the word!
© 2017 Kokuré Fit
Privacy Policy | Terms of Service


Cambridgeshire minibus crash: 'Seriously injured' among 20 casualties
Twenty people are being treated in hospital after a minibus overturned in rural Cambridgeshire.
The two-vehicle collision happened on the B1040 Somersham Road near the villages of Woodhurst and Bluntisham, at 16:51 GMT.
"Multiple people are involved and some are seriously injured," police said.
More than 20 firefighters are at the scene, the fire service said. A police cordon is also in place.
Casualties are being taken to Addenbrooke's and Hinchingbrooke hospitals in Cambridge, a spokeswoman for the East of England Ambulance Service said.
A spokesman from Cambridgeshire Constabulary said they had "varying levels of injury".
Roads in both directions near Wheatsheaf Road are closed and diversions are in place through Pidley.
The East Anglian Air Ambulance and a hazard response team are also at the scene.


--- layout: chapter title: Alignments and Reading Data output: html_document: toc: true toc_float: true pdf: true ---
In our fist class we learnt about how to set up our c++ environment and we wrote our first, very simple program. Importantly, you should know by now how to compile a c++ software. In this chapter we will start with our BabyBayes implementation. The first part of this implementation is to implement an alignment class and a simple alignment reader, i.e., another class that reads in alignments from a file.
Here we will start with one of the most basic alignment formats: the phylip file format. You can read up about this on Joe Felsenstein’s website. Here is an example of the primates.phy alignment file.
12 898
Tarsius_sy AAGTTTCATT GGAGCCACCA CTCTTATAAT TGCCCATGGC CTCACCTCCT CCCTATTATT
Lemur_catt AAGCTTCATA GGAGCAACCA TTCTAATAAT CGCACATGGC CTTACATCAT CCATATTATT
Homo_sapie AAGCTTCACC GGCGCAGTCA TTCTCATAAT CGCCCACGGG CTTACATCCT CATTACTATT
Pan AAGCTTCACC GGCGCAATTA TCCTCATAAT CGCCCACGGA CTTACATCCT CATTATTATT
Gorilla AAGCTTCACC GGCGCAGTTG TTCTTATAAT TGCCCACGGA CTTACATCAT CATTATTATT
Pongo AAGCTTCACC GGCGCAACCA CCCTCATGAT TGCCCATGGA CTCACATCCT CCCTACTGTT
Hylobates AAGCTTTACA GGTGCAACCG TCCTCATAAT CGCCCACGGA CTAACCTCTT CCCTGCTATT
Macaca_fus AAGCTTTTCC GGCGCAACCA TCCTTATGAT CGCTCACGGA CTCACCTCTT CCATATATTT
M_mulatta AAGCTTTTCT GGCGCAACCA TCCTCATGAT TGCTCACGGA CTCACCTCTT CCATATATTT
M_fascicul AAGCTTCTCC GGCGCAACCA CCCTTATAAT CGCCCACGGG CTCACCTCTT CCATGTATTT
M_sylvanus AAGCTTCTCC GGTGCAACTA TCCTTATAGT TGCCCATGGA CTCACCTCTT CCATATACTT
Saimiri_sc AAGCTTCACC GGCGCAATGA TCCTAATAAT CGCTCACGGG TTTACTTCGT CTATGCTATT
TTGCCTAGCA AATACAAACT ACGAACGAGT CCACAGTCGA ACAATAGCAC TAGCCCGTGG
CTGTCTAGCC AACTCTAACT ACGAACGAAT CCATAGCCGT ACAATACTAC TAGCACGAGG
CTGCCTAGCA AACTCAAACT ACGAACGCAC TCACAGTCGC ATCATAATCC TCTCTCAAGG
CTGCCTAGCA AACTCAAATT ATGAACGCAC CCACAGTCGC ATCATAATTC TCTCCCAAGG
CTGCCTAGCA AACTCAAACT ACGAACGAAC CCACAGCCGC ATCATAATTC TCTCTCAAGG
CTGCCTAGCA AACTCAAACT ACGAACGAAC CCACAGCCGC ATCATAATCC TCTCTCAAGG
CTGCCTTGCA AACTCAAACT ACGAACGAAC TCACAGCCGC ATCATAATCC TATCTCGAGG
CTGCCTAGCC AATTCAAACT ATGAACGCAC TCACAACCGT ACCATACTAC TGTCCCGAGG
CTGCCTAGCC AATTCAAACT ATGAACGCAC TCACAACCGT ACCATACTAC TGTCCCGGGG
CTGCTTGGCC AATTCAAACT ATGAGCGCAC TCATAACCGT ACCATACTAC TATCCCGAGG
CTGCTTGGCC AACTCAAACT ACGAACGCAC CCACAGCCGC ATCATACTAC TATCCCGAGG
CTGCCTAGCA AACTCAAATT ACGAACGAAT TCACAGCCGA ACAATAACAT TTACTCGAGG
...
A phylip formatted alignment file always starts with a line containing two numbers: the number of taxa and the number of characters. The two numbers are separated by any number of whitespace characters (e.g., spaces or tabs). Then, we have the sequence data in each row. The row starts with the name of the taxon which can be at most 10 characters long.
Each class start with the header file to define the class with its methods and variables. Write a new files called Alignment.h with the following content.
#ifndef Alignment_h
#define Alignment_h
#include <stdio.h>
#include <string>
#include <vector>
/**
* \class Alignment
*
* \brief Represents the multiple sequence alignment class holding the data matrix.
*
* This class represent the multiple sequence alignment.
* It's main purpose is to hold and manage the character data matrix.
*
*
* \author Sebastian Höhna
*
*/
class Alignment {
public:
Alignment(size_t nt, size_t ns);
~Alignment(void);
char getNucleotide(size_t i, size_t j) const;
size_t getNumberOfSites(void) const;
size_t getNumberOfTaxa(void) const;
const std::vector<std::string>& getTaxonNames(void) const;
std::vector<int> getPossibleNucleotides (char nuc) const;
void print(std::ostream & o) const;
void setMatrix(const std::vector<std::vector<char> > &m);
void setNucleotide(char x, size_t i, size_t j);
void setTaxonNames(const std::vector<std::string> &n);
private:
size_t num_taxa;
size_t num_sites;
std::vector<std::string> taxon_names;
std::vector<std::vector<char> > data_matrix;
};
#endif /* Alignment_h */
This class has all the definition that we need.
Then, we write a new file called Alignment.cpp. We start implementing each function that we defined in Alignment.h now. First, we load the libraries and other header files needed,
Then, we continue with the constructor function. The constructor has always the same name as the class. Here the constructor will create an empty data matrix.
/**
* Constructor of the alignment class.
* We will construct an empty data matrix of size nt rows and nc columns.
*
* @param nt number of taxa/rows in the alignment
* @param ns number of sites/characters/columns in the alignment
*/
Alignment::Alignment( size_t nt, size_t ns ) :
num_taxa( nt ),
num_sites( ns )
{
// create an empty data matrix of num_taxa rows and num_sites columns.
// By default we set every entry to '?', the missing character
data_matrix = std::vector<std::vector<char> >(num_taxa, std::vector<char>(num_sites, '?'));
}
It is a good style to also always add a destructor. The destructor is always called when the object is destroyed and should free all the memory from an object. So we will do this here that you will learn how to add one.
/**
* Desctructor of the alignment class.
*
* Since we don't have any allocated memory we don't need to free any.
*/
Alignment::~Alignment( void )
{
// nothing to do in here.
}
Now, our first actual method is the getNucleotide method. This is a faily simple method that exactly does what the name suggests; it returns a nucleotide from the data matrix.
/**
* Get the character for the i-th taxon/row and j-th site/column.
*
*
* @param i the i-th taxa in the alignment
* @param j the j-th site in the alignment
*
* @return the character.
*/
char Alignment::getNucleotide(size_t i, size_t j) const
{
// simply return
return data_matrix[i][j];
}
For future use, we might also provide more helper methods that return, for example, the number of sites.
/**
* Get the number of sites/characters/columns for this alignment.
*
* @return the number of sites.
*/
size_t Alignment::getNumberOfSites( void ) const
{
// return our private variable for the number of sites
return num_sites;
}
Similary, we implement a method for the number of taxa.
/**
* Get the number of taxa/rows for this alignment.
*
* @return the number of taxa.
*/
size_t Alignment::getNumberOfTaxa( void ) const
{
// return our private variable for the number of taxa
return num_taxa;
}
And we also implement a method to retrieve the taxon names.
/**
* Get the taxa names.
*
* @return a vector of strings with the names of the taxa.
*/
const std::vector<std::string>& Alignment::getTaxonNames(void) const
{
// return our private variable for the taxon names
return taxon_names;
}
Most Importantly, we want to see what we actually stored in the data matrix. So for our own purpose, we print the data matrix.
/**
* Print the alignment to the given stream.
* For simplicity, we will assume that the number of character
*
*/
void Alignment::print(std::ostream & o) const
{
// first, we print some information about the alignment
// print the number of sites
o << "Number of sites = " << num_sites << '\n';
o << " ";
// then print the index for each taxon
for (int i=0; i<num_taxa; i++)
o << std::setw(3) << i << " ";
o << '\n';
// we nicely separate these by '-'
o << "------------------------";
for (int i=0; i<num_taxa; i++)
o << "---";
o << '\n';
// now we print on each line the column/site
for (int j=0; j<num_sites; j++)
{
o << std::setw(10) << j+1 << " -- ";
// so we iterate over all taxa to print the actual data matrix
for (int i=0; i<num_taxa; i++)
{
o << std::setw(3) << data_matrix[i][j] << " ";
}
o << '\n';
}
// make sure to flush the stream so that it is printed.
o.flush();
}
As before with the get methods, we provide a set of set methods. In general, it is a good programming style to have your variables to be private. This means, no one can change them from the outside. Only through getters and setters can the variables be used.
First, we add a set method for a specific character.
/**
* Set the nucleotide for taxon i at site j.
*
* @param x The new nucleotide.
* @param i The index of the taxon.
* @param j The index of the site.
*/
void Alignment::setNucleotide(char x, size_t i, size_t j)
{
// set the character of our internal data matrix
data_matrix[i][j] = x;
}
Then, we also add a set function for the entire matrix, just for convenience.
/**
* Set the data matrix.
*
* @param m The new data matrix.
*/
void Alignment::setMatrix(const std::vector<std::vector<char> > &m)
{
// set the internal variable
data_matrix = m;
}
And another set function for the taxon names.
/**
* Set the taxon names.
*
* @param n A vector of strings with the new taxon names.
*/
void Alignment::setTaxonNames(const std::vector<std::string> &n)
{
taxon_names = n;
}
This was it for our alignment class. If you finished with this, you can take a coffee break :)
In this next section we write a reader class to read in alignments in phylip format.
#ifndef AlignmentReader_h
#define AlignmentReader_h
#include <string>
/**
* \class AlignmentReader
*
* \brief A reader for alignments from files in different formats.
*
* This class provides the functionality of a reader for alignments.
* The alignments will be read from file. Currently, we support only
* the Phylip data format.
*
*
* \author Sebastian Höhna
*
*/
class AlignmentReader {
public:
AlignmentReader(void);
~AlignmentReader(void);
Alignment readPhylip(const std::string &fn);
};
#endif /* Alignment_h */
This concludes the definition of our AlignmentReader in the file AlignmentReader.h.
#include <iostream> // for std::cerr
#include <sstream> // for splitting strings
#include <fstream> // for reading from a file
#include <iterator> // std::istream_iterator
#include <string>
#include <vector>
#include "Alignment.h"
#include "AlignmentReader.h"
/**
* A default constructor that does nothing besides creating an object of this class.
*/
AlignmentReader::AlignmentReader( void )
{
// nothing to initialize
}
/**
* A default destructor that does nothing because we don't have any allocated variables.
*/
AlignmentReader::~AlignmentReader( void )
{
// nothing to delete here
}
Alignment AlignmentReader::readPhylip(const std::string& fn)
{
// first, we open the file stream
// this uses a ifstream object and needs the filesname
std::ifstream in_stream(fn);
// let's see if the stream was opened
if (!in_stream)
{
// it was not opened, so the file did not exist
// we need to tell the user and terminate
std::cerr << "Cannot open file \"" + fn + "\"" << std::endl;
exit(1);
}
// now we can initialize some helper variables
// we a string for the current line of the file
std::string linestring = "";
// we also need the current taxon number
size_t taxon_num = 0;
// the number of taxa
size_t num_taxa = 0;
// the number of sites
size_t num_sites = 0;
// and if all the taxon names have been read in
bool taxon_names_read = false;
// finally we also need a vector of strings for the taxon names
std::vector<std::string> taxon_names;
// first, we need to read the number of taxa and sites
// this should be the first line, so we load the first line into the linestring variable
getline(in_stream, linestring);
// now we split the line into tokens separated by a white space
// this assumme that the number of taxa and sites are provided in this line with only whitespaces separating them
// we create stringstream for this
std::istringstream word_iss(linestring);
// and then separate the line by whitespaces
std::vector<std::string> words((std::istream_iterator<std::string>(word_iss)),
std::istream_iterator<std::string>());
// now we store the number of taxa and sites into our variables
num_taxa = std::stoi( words[0] );
num_sites = std::stoi( words[1] );
// with these two, we can now create our alignment
Alignment this_alignment = Alignment(num_taxa, num_sites);
// for the actual data, and for convenience, we create a data matrix that has num_taxa rows but no columns yet
std::vector<std::vector<char> > matrix = std::vector<std::vector<char> >( num_taxa, std::vector<char>() );
// then we start to loop over the entire file
// we do this with an endless loop which we will stop when the end of file has been reached.
while ( true )
{
// first, check if there are more lines to be read
bool more_lines_in_file = getline(in_stream, linestring).good();
// then, we skip forward over any empty line
while ( more_lines_in_file && linestring == "" )
{
// check again if we reached the end of file
more_lines_in_file = getline(in_stream, linestring).good();
}
// if we reached the end of the file, then we should break out of endless loop
if ( more_lines_in_file == false )
{
// this break command stops the endless loop
break;
}
// now we split the line by whitespaces using again a stringstream
std::istringstream iss(linestring);
std::vector<std::string> tokens((std::istream_iterator<std::string>(iss)),
std::istream_iterator<std::string>());
// we then iterate over all the tokens/words that we received.
for ( int i=0; i<tokens.size(); i++ )
{
// the first word should be the taxon name
// this should only be done if we haven't read all taxon names in interleaved file format
if ( i == 0 && taxon_names_read == false )
{
// so we push the first word to the end of the names of the taxa
taxon_names.push_back(tokens[i]);
}
else
{
// otherwise, we have an actual sequence
const std::string &the_sequence = tokens[i];
// so we add the sequence to the end of the sequence for this taxon
// thus, we append our data matrix using the insert function
matrix[taxon_num].insert(matrix[taxon_num].end(), the_sequence.begin(), the_sequence.end());
}
}
// since we finished we this line, we need to move on to the next taxon.
taxon_num++;
// if we have finished with all taxa, then we start with the first one again (for interleaved files)
if ( taxon_num == num_taxa )
{
// hence, set the taxon index to 0 (we start counting with 0)
taxon_num = 0;
// and remember that we read all taxon names
taxon_names_read = true;
}
} // the end of our while ( true ) loop
// always remember to close the file
in_stream.close();
// now we propagate the taxon names and data matrix into our alignment
this_alignment.setTaxonNames( taxon_names );
this_alignment.setMatrix( matrix );
// and finally return this new alignment
return this_alignment;
}
Finally, so that you can test your program, you need to add your new classes to the main function. Change your main class to something like this.
#include <iostream> // for std::cout
#include "Alignment.h"
#include "AlignmentReader.h"
int main (int argc, char* argv[]) {
// print header
std::cout << "BabyBayes v1.0\n";
std::cout << "Sebastian Höhna\n";
std::cout << "Ludwig-Maximilians-Universität München\n";
std::cout << "\n\n";
// read the data
AlignmentReader reader;
Alignment my_alignment = reader.readPhylip( "primates.phy" );
my_alignment.print(std::cout);
return 0;
}
Make sure that your Makefile has the correct source and object files:
SRC = Alignment.cpp AlignmentReader.cpp main.cpp
OBJECTS = Alignment.o AlignmentReader.o main.o
Then you can compile BabyBayes using your Makefile and run it. See what it does!


HONGDAE
HONGDAE's chicken its taste lingers on your taste buds
To any chicken enthusiast, no words can possibly describe the sensation of biting into a crispy layer of fried goodness following a juicy chunk of meat that burst in flavors. Just the thought of it summons your saliva right beneath your tongue. Moments like these are what The COOP offers with our highly recognized chicken series. Along with the best of traditional Korean flavors and refined art of cooking, The COOP has invested in extensive research in the past two years to come up with a formula that enhance the taste of our chicken. Our taste lab in California has concocted some of the most delicious sauces that our top grade chicken can relish in.
Here at The COOP we also support a healthy style of eating, which means we use the cleanest and the most organic source of ingredients. Our chicken is from a local farm nearby, they are raised in a free range environment for the least amount of stress, restricted from hormones that promote abnormal growth, and is not contaminated with antibiotics like most corporate farms do. Bottom line, we just want you to have the best!
Grilled Chicken :: Craving some char-grilled flavor? Our famous grilled chicken can hit the spot!  Served with Chef J's special oranges sweet and sour sauce the grilled chicken is one of our staple items here at The COOP.
Fried Wings :: Embellished with your choice of our soy garlic or spicy sauce, our fried wings are crispy and succulent all at the same time. Using a thin layer of batter, our chicken is light and juicy when bitten into. When it's time for wings, you can say we are the experts.
Whole Fried Chicken :: Want something more than just wings? Why don't you try our whole fried chicken? Prepared for excellency, our whole fried chicken is cut up to pieces, battered and deep fried to perfection!


Preparation time
less than 30 mins
Cooking time
1 to 2 hours
Serves
Serves 2
Venison is very lean and cooking it in a salt crust keeps it beautifully moist. Perfect for a romantic dinner á deux.
For the venison sauce, heat a little olive oil in a large saucepan and fry the venison trimmings until brown all over. Add the carrots and onion and fry gently for two minutes, or until the onions are soft and translucent. Add the garlic, thyme, juniper berries, black pepper, red wine and port. Simmer for five minutes then add the beef stock.
Simmer for 45 minutes. Pass through a sieve into a clean saucepan and simmer again until the volume of liquid has reduced to a rich sauce.
For the venison in a spiced salt crust, preheat the oven to 225C/425F/Gas mark 7.
To make the salt crust, combine all the spices in a large bowl. Put a few pinches of the spices to one side. Add the salt, egg white and 100ml/3½fl oz water to the bowl. Slowly add the flour and knead until you have a smooth dough. Cover with cling film and set aside to rest for an hour.
In a very hot pan, heat a little oil and brown the venison loin for a minute. Remove the venison and sprinkle it with the reserved spices.
On a lightly floured work surface, roll out the salt crust dough to a rectangle 1cm/½in thick. Place the venison in the middle of the dough ready to encase it. Trim off any excess where the corners will overlap to form a rough cross shape. Fold the ends over the venison, then wrap the long edges over so the meat is completely enclosed. Turn it over to hide the seams and make a small hole in the top. Bake for 12-14 minutes.
To check the venison is cooked, insert a metal skewer into the hole and leave for 10 seconds. Place the skewer on the back of your hand, if the meat is cooked it should feel warm. Remove from the oven and set aside to rest for 12 minutes.
For the caramelized chicory, melt the butter in a frying pan. Add the chicory and season to taste with salt and pepper. Sprinkle over the sugar and cook for two minutes. Pour in the orange and lemon juices and the chicken stock. Simmer for five minutes before finishing with chopped mint.
To serve, place the chicory on serving plates. Crack open the salt crust, wipe the venison with kitchen paper and carve. Place a few slices next to the chicory and spoon over the sauce.


--- layout: post title: "Function isomorphisms" description: "Instance methods are isomorphic to functions." date: 2018-01-22 14:37 UTC tags: [Software Design] image: "/content/binary/function-isomorphism.png" image_alt: "Diagram showing isomorphism between instance method and function." --- {% include JB/setup %}
{{ page.description }}
This article is part of a series of articles about software design isomorphisms.
While I have already, in an earlier article, quoted the following parable about Anton, Qc Na, objects, and closures, it's too good a fit to the current topic to pass up, so please pardon the duplication.
The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor man's closures."
Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress.
On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn?  At that moment, Anton became enlightened.
The point is that objects and closures are two ways of looking at a thing. In a nutshell, objects are data with behaviour, whereas closures are behaviour with data. I've already shown an elaborate C# example of this, so in this article, you'll get a slightly more formal treatment of the subject.
In object-oriented design, you often bundle operations as methods that belong to objects. These are isomorphic to static methods, because a lossless translation exists. We can call such static methods functions, although they aren't guaranteed to be pure.
In the spirit of Refactoring, we can describe each translation as a refactoring, because that's what it is. I don't think the book contains a specific refactoring that describes how to translate from an instance method to a static method, but we could call it Replace Object with Argument.
Going the other way is, on the other hand, already described, so we can use Refactoring's Move Method.
While the concept of refactoring ought to be neutral across paradigms, the original book is about object-oriented programming. In object-oriented programming, objects are the design ideal, so it didn't make much sense to include, in the book, a refactoring that turns an instance method into a static method.
Nevertheless, it's straightforward:
this
and base
to the new argument.Baz
method:
public class Foo { public Bar Baz(Qux qux, Corge corge) { // Do stuff, return bar } // Other members... }
You'll first introduce a new Foo foo
argument to Baz
, change the method body to use foo
instead of this
, and then make the method static. The result is this:
public class Foo { public static Bar Baz(Foo foo, Qux qux, Corge corge) { // Do stuff, return bar } // Other members... }
Once you have a static method, you can always move it to another class, if you'd like. This can, however, cause some problems with accessibility. In C#, for example, you'd no longer be able to access private
or protected
members from a method outside the class. You can choose to leave the static method reside on the original class, or you can make the member in question available to more clients (make it internal
or public
).
The book Refactoring doesn't contain a recipe like the above, because the goal of that book is better object-oriented design. It would consider a static method, like the second variation of Baz
above, a code smell named Feature Envy. You have this code smell when it looks as if a method is more interested in one of its arguments than in its host object. In that case, the book suggests using the Move Method refactoring.
The book already describes this refactoring, so I'm not going to repeat it here. Also, there's no sense in showing you the code example, because it's literally the same two code examples as above, only in the opposite order. You start with the static method and end with the instance method.
C# developers are most likely already aware of this relationship between static methods and objects, because you can use the this
keyword in a static method to make it look like an instance method:
public static Bar Baz(this Foo foo, Qux qux, Corge corge)
The addition of this
in front of the Foo foo
argument enables the C# compiler to treat the Baz
method as though it's an instance method on a Foo
object:
var bar = foo.Baz(qux, corge);
This is only syntactic sugar. The method is still compiled as a static method, and if you, as a client developer, wish to use it as a static method, that's still possible.
A static method like public static Bar Baz(Foo foo, Qux qux, Corge corge)
looks a lot like a function. If refactored from object-oriented design, that function is likely to be impure, but its shape is function-like.
In C#, for example, you could model it as a variable of a delegate type:
Func<Foo, Qux, Corge, Bar> baz = (foo, qux, corge) => { // Do stuff, return bar };
Here, baz
is a function with the same signature as the above static Baz
method.
Have you ever noticed something odd about the various Func
delegates in C#?
They take the return type as the last type argument, which is contrary to C# syntax, where you have to declare the return type before the method name and argument list. Since C# is the dominant .NET language, that's surprising, and even counter-intuitive.
It does, however, nicely align with an ML language like F#. As we'll see in a future article, the above baz
function translates to an F# function with the type Foo * Qux * Corge -> Bar
, and to Haskell as a function with the type (Foo, Qux, Corge) -> Bar
. Notice that the return type comes last, just like in the C# Func
.
...but, you may say, what about data with behaviour? One of the advantages, after all, of objects is that you can associate a particular collection of data with some behaviour. The above Foo
class could have data members, and you may sometimes have a need for passing both data and behaviour around as a single... well... object.
That seems to be much harder with a static Baz
method.
Don't worry, write a closure:
var foo = new Foo { /* initialize members here */ }; Func<Qux, Corge, Bar> baz = (qux, corge) => { // Do stuff with foo, qux, and corge; return bar };
In this variation, baz
closes over foo
. Inside the function body, you can use foo
like you can use qux
and corge
. As I've already covered in an earlier article, the C# compiler compiles this to an IL class, making it even more obvious that objects and closures are two sides of the same coin.
Object-oriented instance methods are isomorphic to both static methods and function values. The translations that transforms your code from one to the other are refactorings. Since you can move in both directions without loss of information, these refactorings constitute an isomorphism.
This is another important result about the relationship between object-oriented design and functional programming, because this enables us to reduce any method to a canonical form, in the shape of a function. From a language like Haskell, we know a lot about the relationship between category theory and functional programming. With isomorphisms like the present, we can begin to extend that knowledge to object-oriented design.
Next: Argument list isomorphisms.


Hello, world!
This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.
Alerts
This is a primary alert—check it out!
This is a secondary alert—check it out!
This is a success alert—check it out!
This is a danger alert—check it out!
This is a warning alert—check it out!
This is a info alert—check it out!
This is a light alert—check it out!
This is a dark alert—check it out!


The number of milliseconds to use for RPC socket read or write timeouts. If set to zero, timeouts are disabled.


Your browser does not support HTML5. Please update your browser; we recommend the latest
Firefox
release.


This server has encountered an error and don't know what to do with it!
Besides, it didn't found a way to display its internal errors.


Avtar Ganju has a PhD in Pharma, an executive management degree in marketing and is a Certified Financial Planner (C.F.P), Chartered Life Underwriter (CLU) and a Chartered Financial Consultant (Ch.FC).
Avtar has been in the financial industry for over 35 years. He used to host a very popular TV show “Money Matters” on Indian Television in early 90's. Avtar Ganju was a member of the Top 50 Club at MONY, the life insurance company. Avtar held the sales manager positions both at MONY and MetLife. He was a Managing Director at MONY and MetLife. He has trained 100's of life agents.
Currently, Avtar specializes in Retirement Planning and Wealth Transfer with a focus on Legacy & Charitable Planning. Avtar has 600 plus endorsements on his LinkedIn Profile.
Outside of his career, Avtar is committed to various community organizations. He is the founding member of US Chapter of Salam Bombay Children’s Foundation - one of the most respected Charitable Organizations in India. He is the Treasurer and a member of the Board Of Directors. Avtar is an adviser to OPTIMIST - an Organization devoted for the betterment of poor children in Bangladesh.


--- layout: post title: 'Phys Ed: Do Certain Types of Sneakers Prevent Injuries?' date: 2010-07-22 08:01:12.000000000 +01:00 tags: - research - quickie - link type: post published: true ---
In a word: Nope. The US Military has just finished a large study only to conclude: wearing the “right” shoes for their particular foot shape had increased trainees’ chances of being hurt. From the article, it looks like quite a few studies on the effects of shoes on injury prevention and cause are starting to come to light.


{% extends "_template.html" %} {% block title %}Nextzen Developers - Your API Keys{% endblock %} {% block scripts %} {{ super() }} {% endblock %} {% block container %} {{ super() }}
{{ key.api_key }}
⚠ Your account has been locked by an administrator, so you cannot create more API keys. Please contact us if you have questions.
{% else %} {% endif %} {% endblock %}


Open Government Licence – Alberta
You are encouraged to use the Information that is available under this licence with only a few conditions.
Using Information under this licence
- Use of any Information indicates your acceptance of the terms below.
- The Information Provider grants you a worldwide, royalty-free, perpetual, non-exclusive licence to use the
Information, including for commercial purposes, subject to the terms below.
You are free to:
- Copy, modify, publish, translate, adapt, distribute or otherwise use the Information in any medium,
mode or format for any lawful purpose.
You must, where you do any of the above:
- Acknowledge the source of the Information by including any attribution statement specified by the
Information Provider(s) and, where possible, provide a link to this licence.
If the Information Provider does not provide a specific attribution statement, or if you are using Information from
several Information Providers and multiple attributions are not practical for your product or application, you must
use the following attribution statement:
Contains information licensed under the Open Government Licence – Alberta.
- The terms of this licence are important, and if you fail to comply with any of them, the rights
granted to you under this licence, or any similar licence granted by the Information Provider, will end
automatically.
Exemptions
- This licence does not grant you any right to use:
- Personal Information;
- Information or Records that are not accessible under applicable laws;
- third party rights the Information Provider is not authorized to license;
- the names, crests, logos, or other official symbols of the Information Provider; and
- Information subject to other intellectual property rights, including patents, trade-marks and official
marks.
Non-endorsement
- This licence does not grant you any right to use the Information in a way that suggests any official
status or that the Information Provider endorses you or your use of the Information.
No warranty
- The Information is licensed “as is”, and the Information Provider excludes all representations,
warranties, obligations, and liabilities, whether express or implied, to the maximum extent permitted by law.
- The Information Provider is not liable for any errors or omissions in the Information, and will not
under any circumstances be liable for any direct, indirect, special, incidental, consequential, or other loss,
injury or damage caused by its use or otherwise arising in connection with this licence or the Information, even
if specifically advised of the possibility of such loss, injury or damage.
Governing Law
- This licence is governed by the laws of the province of Alberta and the applicable laws of Canada.
- Legal proceedings related to this licence may only be brought in the courts of Alberta.
Definitions
- In this licence, the terms below have the following meanings:
"Information"
means information resources or Records protected by copyright or other
information or Records that are offered for use under the terms of this licence.
"Information Provider"
means Her Majesty the Queen in right of Alberta.
“Personal Information”
has the meaning set out in section
1(n) of the Freedom of Information and Protection of Privacy Act (Alberta)
“Records”
has the meaning set out in section
1(q) of the Freedom of Information and Protection of Privacy Act (Alberta)
"You"
means the natural or legal person, or body of persons corporate or incorporate,
acquiring rights under this licence.
Versioning
- This is version 2.0 of the Open Government Licence – Alberta. The Information Provider may make
changes to the terms of this licence from time to time and issue a new version of the licence. Your use of the
Information will be governed by the terms of the licence in force as of the date you accessed the information.


|
|
bool | DoS (int nDoSIn, bool fIn) const |
| |
|
| IMPLEMENT_SERIALIZE (READWRITE(this->nVersion);nVersion=this->nVersion;READWRITE(hashPrevBlock);READWRITE(hashMerkleRoot);READWRITE(nTime);READWRITE(nBits);READWRITE(nNonce);if(!(nType &(SER_GETHASH|SER_BLOCKHEADERONLY))) { READWRITE(vtx);READWRITE(vchBlockSig);} else if(fRead) { const_cast< CBlock * >(this) ->vtx.clear();const_cast< CBlock * >(this) ->vchBlockSig.clear();}) void SetNull() |
| |
|
bool | IsNull () const |
| |
|
uint256 | GetHash () const |
| |
|
int64_t | GetBlockTime () const |
| |
|
void | UpdateTime (const CBlockIndex *pindexPrev) |
| |
|
unsigned int | GetStakeEntropyBit () const |
| |
|
bool | IsProofOfStake () const |
| |
|
bool | IsProofOfWork () const |
| |
|
std::pair< COutPoint, unsigned int > | GetProofOfStake () const |
| |
|
int64_t | GetMaxTransactionTime () const |
| |
|
uint256 | BuildMerkleTree () const |
| |
|
std::vector< uint256 > | GetMerkleBranch (int nIndex) const |
| |
|
bool | WriteToDisk (unsigned int &nFileRet, unsigned int &nBlockPosRet) |
| |
|
bool | ReadFromDisk (unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true) |
| |
|
void | print () const |
| |
|
bool | DisconnectBlock (CTxDB &txdb, CBlockIndex *pindex) |
| |
|
bool | ConnectBlock (CTxDB &txdb, CBlockIndex *pindex, bool fJustCheck=false) |
| |
|
bool | ReadFromDisk (const CBlockIndex *pindex, bool fReadTransactions=true) |
| |
|
bool | SetBestChain (CTxDB &txdb, CBlockIndex *pindexNew) |
| |
|
bool | AddToBlockIndex (unsigned int nFile, unsigned int nBlockPos, const uint256 &hashProofOfStake) |
| |
|
bool | CheckBlock (bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const |
| |
|
bool | AcceptBlock () |
| |
|
bool | GetCoinAge (uint64_t &nCoinAge) const |
| |
|
bool | SignBlock (CWallet &keystore, int64_t nFees) |
| |
|
bool | CheckBlockSignature () const |
| |
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce values to make the block's hash satisfy proof-of-work requirements. When they solve the proof-of-work, they broadcast the block to everyone and the block is added to the block chain. The first transaction in the block is a special one that creates a new coin owned by the creator of the block.
Blocks are appended to blk0001.dat files on disk. Their location on disk is indexed by CBlockIndex objects in memory.


Group Of Children In Vietnam Used A Dead Snake As A Skipping Rope
"This is some gangster sh*t right here."
by Tamara JayneCover image via Crafoo TV YouTube
A video recently went viral showing a couple of children in Vietnam casually jumping "rope"... but it wasn't rope
Upon closer inspection, the group was seen playing and giggling while skipping over a large dead snake.
The video was viewed over 80,000 times since it went online on 13 November, according to Daily Mail.
Vietnam Heritage revealed that the country is home to 206 snake species, including at least 30 venomous terrestrial snakes. It is unclear whether this particular snake was venomous or not.


{% extends "layout.html" %} {% from "govuk/components/button/macro.njk" import govukButton %} {% block content %}
You can now sign in to your account


The index is prolonging the leg lower from last week and is trading in fresh multi-day lows in sub-98.00 levels.
The resumption of the upside bias should initially target the key 55-day SMA, today at 98.27 ahead of last week’s tops in the mid-98.00s.
If the selling impetus gathers traction, the next support is located at the 21-day SMA at 97.81 ahead of the critical 200-day SMA at 97.55. As long as this area holds, the constructive view on the buck is expected to remain unchanged.


This includes a necessary fix for payments CC provided by blackjok3r. Without this, certain paymentsrelease transactions would not pass validation. This also includes something I missed in the initial ac_cbmaturity PR. Without this change, ac_cbmaturity would not affect the magic value of the chain unless another parameter in this if statement was used.


Export ONNX into Python#
Through OnnxInference#
The Python Runtime can be optimized by generating
custom python code and dynamically compile it.
OnnxInference
computes predictions based on an ONNX graph with a
python runtime or onnxruntime.
Method to_python
goes further by converting the ONNX graph into a standalone
python code. All operators may not be implemented.
External tools#
Another tool is implemented in onnx2py.py and converts an ONNX graph into a python code which produces this graph.
Export functions#
The following function converts an ONNX graph into Python code.
onnx API#
The python code creates the same exported onnx graph with onnx API.
mlprodict.onnx_tools.onnx_export.export2onnx
(model_onnx, opset = None, verbose = True, name = None, rename = False, autopep_options = None)
Exports an ONNX model to the onnx syntax.
to numpy#
The python code creates a python function using numpy to produce the same results as the ONNX graph.
mlprodict.onnx_tools.onnx_export.export2numpy
(model_onnx, opset = None, verbose = True, name = None, rename = False, autopep_options = None)
Exports an ONNX model to the numpy syntax. The exports does not work with all operators.
tf2onnx#
This function was used to write a converter for a function from tensorflow (RFFT). To speed up the development, the first step consisted into writing a numpy function equivalent to the tensorflow version. Then this function was converted into ONNX using the numpy API for ONNX. Finally, the ONNX graph was exported into a python code following tf2onnx API.
mlprodict.onnx_tools.onnx_export.export2tf2onnx
(model_onnx, opset = None, verbose = True, name = None, rename = False, autopep_options = None)
Exports an ONNX model to the tensorflow-onnx syntax.


Connect to EAST ASIA LANGUAGES & CIVILIZATIONS-LPS in the Course Register.
EAST ASIA LANGUAGES & CIVILIZATIONS
EALC-038 RELIGION, STATE, SOCIETY 1 CU 601 SEM W 6-9PM WILL 215 TAVOR O CROSS LISTED: RELS-270 MAX W/CROSS LIST: 20 EALC-069 JAPANESE POPULAR CULTURE 1 CU CROSS CULTURAL ANALYSIS 601 LEC T 6-9PM BENN 201 HARRINGTON L MAX: 30
Return to Course & Room Roster
Comments to:
Office of the University Registrar
University of Pennsylvania
Room 221 Franklin Building
3451 Walnut Street
Philadelphia, PA 19104-6291
Phone:<PHONE_NUMBER> Fax:<PHONE_NUMBER>
<EMAIL_ADDRESS>Updated: Sat Jan 17 08:30:02 2015


Navigation
Overview
Navigation allows to switch view depending on the current viewModel.
Neutronium supports:
- Javascript-side navigation (or routing navigation) where view changes are made by javscript routing
- C# navigation where view changes are provided by altering the Html displayed
It is strongly recommended to use javascript-side navigation as it integrates better with javascript framework and is more powerful.
C# navigation exists mainly for historical reason and no new features will be provided.
Routing or javascript-side navigation
Overview
The solution is composed of:
- A C# implementation is provided as part of Neutronium Building Blodk
- A Vue implementation using vue-router is provided by vue-cli plugin
In this architecture:
- Navigation convention is created on the c# side
- Javascript as the responsibility of changing page displayed using vue-router.
- Navigation can be triggered both on javascript or C# side.
A full example integrating these two components is provided in the Neutronium.SPA template.
Creating navigation
Router
that implements IRouterBuilder
is meant to build the application routing by associating a viewModel type to a specific HTML file. HTMLWindow exposes the public property INavigationBuilder NavigationBuilder.
If the same ViewModel type can be displayed using different View you can use the Id string to discriminate the Views.
public interface IRouterBuilder
{
IRouterBuilder Register(Type type, string routerName, bool defaultType = true);
IRouterBuilder Register<T>(string routerName, bool defaultType = true);
}
Example for javascript routing navigation:
routerBuilder.Register<Vm1>("vm1");
routerBuilder.Register<Vm2>("vm2");
routerBuilder.Register<Vm2>("vm3", "alternative");
Once the routing is done, you can navigate from ViewModel to ViewModel using the INavigator
interface:
public interface INavigator
{
event EventHandler<RoutingEventArgs> OnNavigating;
event EventHandler<RoutedEventArgs> OnNavigated;
Task Navigate(object viewModel, string routeName = null);
Task Navigate(string routeName);
Task Navigate<T>(NavigationContext<T> context = null);
Task Navigate(Type type, NavigationContext context = null);
}
Or on the javascript side, using the route name as registered with the router builder.
Convention Navigation
Since Core version 0.5.0, Neutronium has navigation helper that provides short-cut for navigation based on convention. For example:
public static void Register(IRouterBuilder builder)
{
// Create a convention for the corresponding builder
// Every type will be registered using the template
// "View\{vm}\dist\index.HTML" where VM will be the class
// name without postfix "ViewModel" if nay
var convention = builder.GetTemplateConvention(@"View\{vm}\dist\index.HTML");
// Use fluent helper to register class from same assembly as RoutingConfiguration
// in "NeutoniumDemo.ViewModel" namespace excluding ApplicationMenuViewModel
typeof(RoutingConfiguration).GetTypesFromSameAssembly()
.InNamespace("NeutoniumDemo.ViewModel")
.Except(typeof(ApplicationMenuViewModel))
.Register(convention);
}
C# side navigation
Please consider using routing navigation instead.
C# navigation exists mainly for historical reason and no new features will be provided.
Creating navigation
To use navigation, you have to use HTMLWindow UserControl instead of HTMLViewControl.
The main difference between the two is that HTMLWindow exposes an INavigationBuilder interface and implements INavigationSolver.
public interface INavigationSolver : IDisposable
{
bool UseINavigable { get; set; }
Task NavigateAsync(object viewModel, string Id = null, JavascriptBindingMode mode = JavascriptBindingMode.TwoWay);
event EventHandler<NavigationEvent> OnNavigate;
}
The NavigateAsync method will find the HTLM page associated with the viewModel using the INavigationBuilder resolution and apply a binding between the View and the ViewModel using the corresponding iMode.
Ex:
//Navigate to View\index.html
await myHTMLWindow.NavigateAsync(vm);
//Navigate to View\index2.html
await myHTMLWindow.NavigateAsync(vm2);
//Navigate to View\index3.html
await myHTMLWindow.NavigateAsync(vm2, "alternative");
OnNavigate event is called every time the ViewModel changes. If UseINavigable is set to true and the ViewModel implements the INavigable interface the Navigation setter is called during navigation allowing that a ViewModel knows the INavigationSolver and use it to navigate to another ViewModel.
public interface INavigable
{
INavigationSolver Navigation { get; set; }
}
Convention Navigation
Since Core version 0.5.0, Neutronium has navigation helper that provides short-cut for navigation based on convention. For example:
public static void Register(INavigationBuilder builder)
{
// Create a convention for the corresponding builder
// Every type will be registered using the template
// "View\{vm}\dist\index.HTML" where VM will be the class
// name without postfix "ViewModel" if nay
var convention = builder.GetTemplateConvention(@"View\{vm}\dist\index.HTML");
// Use fluent helper to register class from same assembly as RoutingConfiguration
// in "NeutoniumDemo.ViewModel" namespace excluding ApplicationMenuViewModel
typeof(RoutingConfiguration).GetTypesFromSameAssembly()
.InNamespace("NeutoniumDemo.ViewModel")
.Except(typeof(ApplicationMenuViewModel))
.Register(convention);
}
See BuilderExtension.cs, TypesProviderExtension.cs and ITypesProvider.cs for detailed API description.
Transition
HTMLWindow UserControl embeds two WebBrowser used to ensure smooth transition between view: one is used to display the current view, the other is used when NavigateAsync is called: the next view is then loaded in the second WebControl, the ViewModel is then bound and finally this WebControl becomes visible.
During this process, it is possible to display javascript animation when one view is closing and when one View is first displayed.
This possible due to custom hook implemented by both Vue and knockout binding
For knockout
You can use custom bindings onopened and onclose. Ex:

where:
- OnEnter is a function receiving one unique argument which is the element that owns the binding. It is called when the HTLM View is displayed.
- OnClose is a function receiving as a first argument a callback to be called when the animation is over and as second argument the element that owns the binding. It is very important to always call the callback as the new View will only be displayed after the callback is called.
Ex:
function OnEnter(element){
$(element).addClass("boxanimated");
}
function OnClose(callback, element){
$(element).removeClass("boxanimated");
setTimeout(callback, 2000);
}
Full example can be found in the projects:


Motivation
Motivation behind the Monitor & LogTracker.
Why we built Monitor & LogTracker.
Under Construction | To - Be - Continued.
Motivation behind the Monitor & LogTracker.
Why we built Monitor & LogTracker.
Under Construction | To - Be - Continued.


We reduce risk through consulting, services, and security product expertise. We are a trusted advisor for all cyber security initiatives.
Using the latest technology and industry experience, our full-stack mobile developers develop the Versatile, Creative Mobile App you need.
We have an experienced Web Application Development team, which is dedicated to delivering engaging mobile sites and apps with a user-friendly experience.
Scalable solutions for cloud computing are managed by our company and we provide users with access to computing services such as analytics.
Get your first Web Application exclusively for FREE
Contact UsI'm fortunate to be part of a team that's excited about solving tough engineering problems and reasoning every solution to its core. Each of us really gets ownership over an area, too. I love the work culture and enjoy working at GrowMore.
I am glad to work at GrowMore. Company allows you to wear multiple hats, empowers you with freedom to make decisions and has a good mix of young and old workforce to team up with. I have spent 5 plus years with the organization.
I started out as an intern at GrowMore during my last semester of college and immediately felt welcomed throughout the entire office. Upon graduating, I found myself in my first full-time opportunity working with an amazing company.


--- layout: post title: World Cup notes date: 2010-06-27 05:31:41.000000000 +05:30 categories: - random tags: [] status: publish type: post published: true meta: _edit_last: '1' _wp_old_slug: '' author: login: admin email<EMAIL_ADDRESS>display_name: admin first_name: '' last_name: '' ---
[caption id="" align="alignright" width="338" caption="Messi at WC 2010"][/caption]
Not being a particular fan of football or the FIFA world cup, I'm now a convert. My reasons are voiced lucidly by tbray's take on it:
..The sense of occasion, and the widespread joy it brings to so many around the world. Something that causes this much intense shared feeling just can’t be a bad thing. On balance, I’d say the World Cup is one of the good things about being a member of Homo sapiens.
Wavin' Flag
I love the song. It is uplifting, and the choice of the song is courageous. These times are well known for political correctness, so the choice of a song on "Freedom" at the world stage is good.
However, the spirits came down a bit when I looked in the history of the song. Wavin' Flag was originally released in March '09. The song is powerful, and the lyrics hard hitting. Excerpts :
Born to a throne, stronger than Rome
But Violent prone, poor people zone
But it’s my home, all I have known
Where I got grown, streets we would roamSo we struggling, fighting to eat and
We wondering when we’ll be free
Read it in it's entirety here. I was saddened to learn Coca-Cola, who selected the song as the WC anthem got rid of the "darker lyrics". The PR blurb is :
It's about the one time that we all get together and the world forgets its conflict and its problems and we focus on this unity and celebration. That moment is connected now to 'Wavin' Flag.
I thought Coca-Cola missed the mark here. Selecting the original song for all of it's power would've been a better choice. Acknowledging, rather than setting aside, these "dark" issues would've been the bolder thing to do. Hear the actual song, and compare it with the "Celebration Mix".
Of course Fifa and K'Naan are all happy with this. Who am I to complain!? I do wonder what N.Korea, China, etc think of the song.
The Games
Other Notes
India?
Which brings me to the end of the post. When will this country with 1/6th the population of the world produce a dozen good footballers?! I like all the hype behind football right now. It gets pages of newsprint, compared to cricket's quarter page. I hope this is not a passing fancy with the game, but rather reflects the birth of interest in a non-cricket game. We sorely need it.


Basket Continue Shopping Empty Basket Delivery Ship To Adress $3.99 Post Office $2.99 1 Day Delivery $10.99 Total Sum $ 0


Made from fresh fruit
Made freshly from fruit and from crushed fruitwith yogurt or ice cream added
Made with fruit and syrup
Bottled juice drinks for the event, serve up to 1000 people.


Objective builder provides a step-by-step process for the creation of measurable learning objectives in the cognitive, affective, or psychomotor domains.
Learning objectives are created in the CABD format, which stands for Condition, Audience, Behavior, and Degree.
The following theoretical frameworks are used:
This is an example of an objective created by objective builder. Each part of the objective is color coded.
Condition
Given a blank map of the United States
Audience
the student
Behavior
will identify all 50 states and capitals
Degree
with 90 percent accuracy
"Given a blank map of the United States the student will identify all 50 states and capitals with 90 percent accuracy."
Please state as specifically as possible what will be provided to the audience. Example: a thesis statement, the quadratic equation, a map.
Typically, the generic word "student" is used, however be specific if writing your objective for a narrow population.
Click anywhere to outside the box to close
Definition:
Example:
Each domain is broken into different levels. Each level represents an increase in difficulty of mastery. The levels are listed simple (top) to complex (bottom)
Please give a brief description of the product your audience will interact with. Refer to the example for details.
State the level of accuracy that you deem "proficient". Example: 80%,in 500 words or less, on the first attempt, within 15 minutes.
Your learning objective is now complete
New Objective
View All
Copy your objectives and click anywhere outside the box to close.
Given , will .


--- layout: default title: Community ---
The Google group is a public mailing list that anyone can join to ask questions about / discuss Jsonnet. We also use the list for release announcements and other relevant communications to Jsonnet users.
The #jsonnet channel on Kubernetes Slack is for discussion around the use of Jsonnet with Kubernetes.
There is also an IRC channel: #jsonnet on the freenode network (chat.freenode.net).
There is a Jsonnet tag on Stack Overflow.
All Jsonnet implementations are licensed under the Apache 2.0 license.
You're welcome to contribute to Jsonnet via Github and do share your plans with us even if you're at an early stage. If it's your first time submitting a pull request, a bot will ask you to sign either the Google individual or corporate contributor license agreement (CLA). CLAs are a common requirement when patching open source software projects owned by large companies.