├── .gitignore ├── MANIFEST.in ├── pyrustlearn ├── rustlearn-bindings │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ └── lib.rs └── __init__.py ├── circle.yml ├── examples └── mnist.py ├── tests └── test_init.py ├── setup.py ├── readme.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.*~ 2 | *.pyc 3 | *egg* 4 | *#* 5 | *~ -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include .so 2 | recursive-include rustlearn-bindings *.so -------------------------------------------------------------------------------- /pyrustlearn/rustlearn-bindings/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /pyrustlearn/rustlearn-bindings/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustlearn-bindings" 3 | version = "0.1.0" 4 | authors = ["maciej "] 5 | 6 | [dependencies] 7 | rustlearn = "0.3.0" 8 | 9 | [lib] 10 | name = "rustlearn" 11 | crate-type = ["dylib"] 12 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | dependencies: 2 | pre: 3 | - pip install numpy 4 | - pip install scipy 5 | - pip install scikit-learn 6 | - rm ~/.gitconfig 7 | - touch ~/.gitconfig 8 | - git config --global user.email maciej.kula@gmail.com 9 | - git config --global user.name "Maciej Kula" 10 | - curl -sf -L https://static.rust-lang.org/rustup.sh | sh /dev/stdin --yes 11 | - sudo apt-get install libffi-dev 12 | -------------------------------------------------------------------------------- /examples/mnist.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from sklearn.cross_validation import KFold 4 | from sklearn.datasets import load_digits 5 | from sklearn.metrics import accuracy_score 6 | 7 | from pyrustlearn import SGDClassifier 8 | 9 | 10 | def _get_data(): 11 | 12 | data = load_digits() 13 | 14 | X = data.data.astype(np.float32) 15 | y = data.target.astype(np.float32) 16 | 17 | return (X, y) 18 | 19 | 20 | def run_example(): 21 | 22 | data, target = _get_data() 23 | 24 | n_folds = 5 25 | accuracy = 0.0 26 | 27 | for (train_idx, test_idx) in KFold(n=len(data), n_folds=n_folds, shuffle=True): 28 | 29 | train_X = data[train_idx] 30 | train_y = target[train_idx] 31 | 32 | test_X = data[test_idx] 33 | test_y = target[test_idx] 34 | 35 | model = SGDClassifier() 36 | model.fit(train_X, train_y) 37 | 38 | predictions = model.predict(test_X) 39 | 40 | accuracy += accuracy_score(predictions, test_y) 41 | 42 | return accuracy / n_folds 43 | 44 | 45 | accuracy = run_example() 46 | 47 | 48 | print('Accuracy %s' % accuracy) 49 | -------------------------------------------------------------------------------- /tests/test_init.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from sklearn.cross_validation import KFold 4 | from sklearn.datasets import load_digits 5 | from sklearn.metrics import accuracy_score 6 | 7 | from pyrustlearn import SGDClassifier 8 | 9 | 10 | def _get_data(): 11 | 12 | data = load_digits() 13 | 14 | X = data.data.astype(np.float32) 15 | y = data.target.astype(np.float32) 16 | 17 | return (X, y) 18 | 19 | 20 | def run_example(): 21 | 22 | data, target = _get_data() 23 | 24 | n_folds = 5 25 | accuracy = 0.0 26 | 27 | for (train_idx, test_idx) in KFold(n=len(data), n_folds=n_folds, shuffle=True): 28 | 29 | train_X = data[train_idx] 30 | train_y = target[train_idx] 31 | 32 | test_X = data[test_idx] 33 | test_y = target[test_idx] 34 | 35 | model = SGDClassifier() 36 | model.fit(train_X, train_y) 37 | 38 | predictions = model.predict(test_X) 39 | 40 | accuracy += accuracy_score(predictions, test_y) 41 | 42 | return accuracy / n_folds 43 | 44 | 45 | def test_mnist(): 46 | 47 | accuracy = run_example() 48 | 49 | assert accuracy > 0.9 50 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import subprocess 4 | 5 | from setuptools import setup 6 | from setuptools.command.test import test as TestCommand 7 | 8 | def build_extensions(): 9 | 10 | cwd = os.path.join(os.path.dirname(__file__), 11 | 'pyrustlearn/rustlearn-bindings') 12 | 13 | # Compile the Rust library 14 | subprocess.check_call(['cargo', 'build', '--release'], 15 | cwd=cwd) 16 | 17 | build_extensions() 18 | 19 | 20 | class PyTest(TestCommand): 21 | user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] 22 | 23 | def initialize_options(self): 24 | TestCommand.initialize_options(self) 25 | self.pytest_args = ['tests/'] 26 | 27 | def finalize_options(self): 28 | TestCommand.finalize_options(self) 29 | self.test_args = [] 30 | self.test_suite = True 31 | 32 | def run_tests(self): 33 | # import here, cause outside the eggs aren't loaded 34 | import pytest 35 | errno = pytest.main(self.pytest_args) 36 | sys.exit(errno) 37 | 38 | 39 | setup( 40 | name='pyrustlearn', 41 | version='0.1.0', 42 | packages=['pyrustlearn'], 43 | cmdclass={'test': PyTest}, 44 | install_requires=['cffi', 'numpy', 'scipy', 'scikit-learn'], 45 | tests_require=['pytest'], 46 | package_data={'pyrustlearn': ['rustlearn-bindings/target/release/librustlearn.so']}, 47 | author='Maciej Kula', 48 | license='Apache 2.0', 49 | ) 50 | -------------------------------------------------------------------------------- /pyrustlearn/rustlearn-bindings/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | extern crate rustlearn; 3 | 4 | use std::mem; 5 | 6 | use rustlearn::prelude::*; 7 | use rustlearn::multiclass; 8 | use rustlearn::linear_models::sgdclassifier; 9 | 10 | 11 | fn construct_array(input: *mut f32, rows: usize, cols: usize) -> Array { 12 | 13 | let len = rows * cols; 14 | 15 | let mut data = unsafe { 16 | Array::from(Vec::from_raw_parts(input, len, len)) 17 | }; 18 | 19 | data.reshape(rows, cols); 20 | 21 | data 22 | } 23 | 24 | 25 | #[no_mangle] 26 | pub extern fn fit_sgdclassifier(X_ptr: *mut f32, X_rows: usize, X_cols: usize, 27 | y_ptr: *mut f32, y_rows: usize, y_cols: usize) 28 | -> *const multiclass::OneVsRestWrapper 29 | { 30 | 31 | let X = construct_array(X_ptr, X_rows, X_cols); 32 | let y = construct_array(y_ptr, y_rows, y_cols); 33 | 34 | let mut model = sgdclassifier::Hyperparameters::new(X.cols()) 35 | .learning_rate(0.05) 36 | .l2_penalty(0.000001) 37 | .l1_penalty(0.000001) 38 | .one_vs_rest(); 39 | 40 | for _ in 0..5 { 41 | model.fit(&X, &y).unwrap(); 42 | } 43 | 44 | let boxed_model = Box::new(model); 45 | 46 | // We don't want to free the numpy arrays 47 | mem::forget(X); 48 | mem::forget(y); 49 | 50 | Box::into_raw(boxed_model) 51 | } 52 | 53 | 54 | #[no_mangle] 55 | pub extern fn predict_sgdclassifier(X_ptr: *mut f32, X_rows: usize, X_cols: usize, 56 | model_ptr: * mut multiclass::OneVsRestWrapper) 57 | -> *const f32 58 | { 59 | let model = unsafe { 60 | Box::from_raw(model_ptr) 61 | }; 62 | 63 | let X = construct_array(X_ptr, X_rows, X_cols); 64 | 65 | let predictions = model.predict(&X).unwrap(); 66 | let predictions_ptr = predictions.data()[..].as_ptr(); 67 | 68 | // We don't want to free the numpy arrays... 69 | mem::forget(X); 70 | // or the memory we allocated for predictions... 71 | mem::forget(predictions); 72 | // or the model, we might need it later 73 | mem::forget(model); 74 | 75 | predictions_ptr 76 | } 77 | 78 | 79 | #[no_mangle] 80 | pub extern fn free_sgdclassifier(model_ptr: * mut multiclass::OneVsRestWrapper) { 81 | let _ = unsafe { 82 | Box::from_raw(model_ptr) 83 | }; 84 | } 85 | 86 | #[test] 87 | fn it_works() { 88 | } 89 | -------------------------------------------------------------------------------- /pyrustlearn/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import cffi 4 | 5 | import numpy as np 6 | 7 | 8 | def _build_bindings(): 9 | 10 | ffi = cffi.FFI() 11 | ffi.cdef(""" 12 | struct SGDModel; 13 | struct SGDModel *fit_sgdclassifier(float *X_ptr, unsigned long X_rows, unsigned long X_cols, 14 | float *y_ptr, unsigned long y_rows, unsigned long y_cols); 15 | float* predict_sgdclassifier(float *X_ptr, unsigned long X_rows, unsigned long X_cols, 16 | struct SGDModel *model); 17 | void free_sgdclassifier(struct SGDModel *model); 18 | """) 19 | 20 | path = os.path.join(os.path.dirname(__file__), 21 | 'rustlearn-bindings/target/release/librustlearn.so') 22 | lib = ffi.dlopen(path) 23 | 24 | return ffi, lib 25 | 26 | 27 | ffi, lib = _build_bindings() 28 | 29 | 30 | def _as_float(array): 31 | """ 32 | Cast a np.float32 array to a float*. 33 | """ 34 | 35 | return ffi.cast('float*', array.ctypes.data) 36 | 37 | 38 | def _as_usize(num): 39 | """ 40 | Cast num to something like a rust usize. 41 | """ 42 | 43 | return ffi.cast('unsigned long', num) 44 | 45 | 46 | def _as_float_ndarray(ptr, size): 47 | """ 48 | Turn a float* to a numpy array. 49 | """ 50 | 51 | return np.core.multiarray.int_asbuffer(ptr, size * np.float32.itemsize) 52 | 53 | 54 | class SGDClassifier(object): 55 | 56 | def __init__(self): 57 | self.model = None 58 | 59 | def fit(self, X, y): 60 | 61 | self.model = lib.fit_sgdclassifier(_as_float(X), 62 | _as_usize(X.shape[0]), 63 | _as_usize(X.shape[1]), 64 | _as_float(y), 65 | _as_usize(len(y)), 66 | _as_usize(1)) 67 | 68 | def predict(self, X): 69 | 70 | if self.model is None: 71 | raise Exception('Call fit before calling predict') 72 | 73 | predictions_ptr = lib.predict_sgdclassifier( 74 | _as_float(X), _as_usize(X.shape[0]), _as_usize(X.shape[1]), 75 | ffi.cast('struct SGDModel*', self.model) 76 | ) 77 | 78 | predictions = np.frombuffer(ffi.buffer(predictions_ptr, len(X) 79 | * ffi.sizeof('float')), 80 | dtype=np.float32) 81 | 82 | return predictions 83 | 84 | def __del__(self): 85 | 86 | if self.model is not None: 87 | lib.free_sgdclassifier(self.model) 88 | self.model = None 89 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # python-rustlearn 2 | 3 | [![Circle CI](https://circleci.com/gh/maciejkula/python-rustlearn.svg?style=svg)](https://circleci.com/gh/maciejkula/python-rustlearn) 4 | 5 | A simple example of using a Rust library (in this case, [rustlearn](https://github.com/maciejkula/rustlearn)) from Python. 6 | 7 | We'll we rustlearn to estimate a simple logistic regression model on the MNIST digits dataset --- but we'll do the data processing and model evaluation in Python. 8 | 9 | ## Installation 10 | This example is set up as a Python package. You should be able to run it by: 11 | 12 | 1. Installing the Rust compiler: https://www.rust-lang.org/downloads.html 13 | 2. Installing `libcffi-dev` (on Ubuntu, `sudo apt-get install libcffi-dev`) 14 | 3. Cloning this repository, and 15 | 4. Running `pip install .` in the resulting directory. 16 | 17 | You can verify that everything works by running `python setup.py test`. 18 | 19 | ## Setting up a C API in Rust 20 | 21 | First, we need to create a new crate using `cargo new` and set it to compile to a shared object via `Cargo.toml`: 22 | 23 | ``` 24 | [dependencies] 25 | rustlearn = "0.3.0" 26 | 27 | [lib] 28 | name = "rustlearn" 29 | crate-type = ["dylib"] 30 | ``` 31 | 32 | Because we're only writing a simple wrapper, we can start adding code directly in [`lib.rs`](/pyrustlearn/rustlearn-bindings/src/lib.rs). 33 | 34 | The first thing we construct is a helper function which can create a rustlearn `Array` from a raw C pointer: 35 | 36 | ```rust 37 | fn construct_array(input: *mut f32, rows: usize, cols: usize) -> Array { 38 | 39 | let len = rows * cols; 40 | 41 | let mut data = unsafe { 42 | Array::from(Vec::from_raw_parts(input, len, len)) 43 | }; 44 | 45 | data.reshape(rows, cols); 46 | 47 | data 48 | } 49 | ``` 50 | 51 | This allows us to share numpy arrays with Rust without making any copies. The small `unsafe` section turns a raw pointer into a Rust vector. 52 | 53 | With the use of this helper we can write a public function to fit the model. We use the `#[no_mangle]` directive to enable us to call it by name. 54 | 55 | ```rust 56 | #[no_mangle] 57 | pub extern fn fit_sgdclassifier(X_ptr: *mut f32, X_rows: usize, X_cols: usize, 58 | y_ptr: *mut f32, y_rows: usize, y_cols: usize) 59 | -> *const multiclass::OneVsRestWrapper 60 | { 61 | 62 | let X = construct_array(X_ptr, X_rows, X_cols); 63 | let y = construct_array(y_ptr, y_rows, y_cols); 64 | 65 | let mut model = sgdclassifier::Hyperparameters::new(X.cols()) 66 | .learning_rate(0.05) 67 | .l2_penalty(0.000001) 68 | .l1_penalty(0.000001) 69 | .one_vs_rest(); 70 | 71 | for _ in 0..5 { 72 | model.fit(&X, &y).unwrap(); 73 | } 74 | 75 | let boxed_model = Box::new(model); 76 | 77 | // We don't want to free the numpy arrays 78 | mem::forget(X); 79 | mem::forget(y); 80 | 81 | Box::into_raw(boxed_model) 82 | } 83 | ``` 84 | 85 | The function takes pointers for the data and label arrays and returns a pointer for a model object. Because our Python code will only interact with the model object via API calls, we don't really need to worry about what this is on the Python side. 86 | 87 | Having obtained the input data, we set up a logistic regression model and run 5 epochs of training, in a way that is very similar to what we would do in Python. 88 | 89 | Once this is done we need to take care of a couple of tricky things. 90 | 91 | 1. We wrap the model object into a `Box`. That's because Rust allocates things on the stack by default: `model` is on the stack, and will be destroyed once it goes out of scope. But we want to keep it around and use it later --- to make that possible, we move it to the heap by boxing it. 92 | 2. We tell Rust we don't want it to call destructors on the input arrays. If it did, the data would get freed on the Python side as well and break our Python code. We do this by calling `mem::forget`. 93 | 3. Finally, we turn the box containing the model into a raw pointer. This does two things: allows us to return a straightforward pointer _and_ tells Rust not to call the destructor on the boxed value when it goes out of scope. 94 | 95 | The drill is similar for getting predictions. We get the input data and the model pointer, transform it to a boxede model (which is unsafe because the pointer could be invalid), and compute the predictions. We then tell Rust to forget about freeing the data we want to keep around, and return a pointer to the predictions data. 96 | 97 | ```rust 98 | #[no_mangle] 99 | pub extern fn predict_sgdclassifier(X_ptr: *mut f32, X_rows: usize, X_cols: usize, 100 | model_ptr: * mut multiclass::OneVsRestWrapper) 101 | -> *const f32 102 | { 103 | let model = unsafe { 104 | Box::from_raw(model_ptr) 105 | }; 106 | 107 | let X = construct_array(X_ptr, X_rows, X_cols); 108 | 109 | let predictions = model.predict(&X).unwrap(); 110 | let predictions_ptr = predictions.data()[..].as_ptr(); 111 | 112 | // We don't want to free the numpy arrays... 113 | mem::forget(X); 114 | // or the memory we allocated for predictions... 115 | mem::forget(predictions); 116 | // or the model, we might need it later 117 | mem::forget(model); 118 | 119 | predictions_ptr 120 | } 121 | ``` 122 | 123 | Finally, we need a way of freeing the model object. This is very simple: we turn the model pointer into a box and let Rust free it in the normal way: 124 | 125 | ```rust 126 | #[no_mangle] 127 | pub extern fn free_sgdclassifier(model_ptr: * mut multiclass::OneVsRestWrapper) { 128 | let _ = unsafe { 129 | Box::from_raw(model_ptr) 130 | }; 131 | } 132 | ``` 133 | 134 | Once this is done, we can simply call `cargo build` to build the shared object we need. 135 | 136 | ## Using the API from Python 137 | To write the Python bindings I'm going to use [`cffi`](https://cffi.readthedocs.org/en/latest/). 138 | 139 | The first thing we need to do is to describe the C interface and open the `.so` file: 140 | 141 | ```python 142 | def _build_bindings(): 143 | 144 | ffi = cffi.FFI() 145 | ffi.cdef(""" 146 | struct SGDModel; 147 | struct SGDModel *fit_sgdclassifier(float *X_ptr, unsigned long X_rows, unsigned long X_cols, 148 | float *y_ptr, unsigned long y_rows, unsigned long y_cols); 149 | float* predict_sgdclassifier(float *X_ptr, unsigned long X_rows, unsigned long X_cols, 150 | struct SGDModel *model); 151 | void free_sgdclassifier(struct SGDModel *model); 152 | """) 153 | 154 | path = os.path.join(os.path.dirname(__file__), 155 | 'rustlearn-bindings/target/release/librustlearn.so') 156 | lib = ffi.dlopen(path) 157 | 158 | return ffi, lib 159 | ``` 160 | 161 | The function definitions are the key part. We specify an opaque struct `SGDModel`, and the three functions we've exposed from the Rust code via the `#[no_mangle]` attribute. `cffi` parses and checks their syntax. 162 | 163 | We can then open the library by calling `ffi.dlopen(...)`. 164 | 165 | To make using the interface easier, we can define a couple of helper functions: 166 | 167 | ```python 168 | def _as_float(array): 169 | """ 170 | Cast a np.float32 array to a float*. 171 | """ 172 | 173 | return ffi.cast('float*', array.ctypes.data) 174 | 175 | 176 | def _as_usize(num): 177 | """ 178 | Cast num to something like a rust usize. 179 | """ 180 | 181 | return ffi.cast('unsigned long', num) 182 | 183 | 184 | def _as_float_ndarray(ptr, size): 185 | """ 186 | Turn a float* to a numpy array. 187 | """ 188 | 189 | return np.core.multiarray.int_asbuffer(ptr, size * np.float32.itemsize) 190 | ``` 191 | 192 | For numpy arrays, `array.ctypes.data` is the memory address of the data buffer: to pass it as `float*`, we simply cast it. (Note that this only works for C-contiguous arrays.) 193 | 194 | We can then define an sklearn-like class for our model: 195 | 196 | ```python 197 | class SGDClassifier(object): 198 | 199 | def __init__(self): 200 | self.model = None 201 | 202 | def fit(self, X, y): 203 | 204 | self.model = lib.fit_sgdclassifier(_as_float(X), 205 | _as_usize(X.shape[0]), 206 | _as_usize(X.shape[1]), 207 | _as_float(y), 208 | _as_usize(len(y)), 209 | _as_usize(1)) 210 | 211 | def predict(self, X): 212 | 213 | if self.model is None: 214 | raise Exception('Call fit before calling predict') 215 | 216 | predictions_ptr = lib.predict_sgdclassifier( 217 | _as_float(X), _as_usize(X.shape[0]), _as_usize(X.shape[1]), 218 | ffi.cast('struct SGDModel*', self.model) 219 | ) 220 | 221 | predictions = np.frombuffer(ffi.buffer(predictions_ptr, len(X) 222 | * ffi.sizeof('float')), 223 | dtype=np.float32) 224 | 225 | return predictions 226 | 227 | def __del__(self): 228 | 229 | if self.model is not None: 230 | lib.free_sgdclassifier(self.model) 231 | self.model = None 232 | ``` 233 | 234 | In the `fit` function, we convert the inputs into pointers, call the Rust API, and get a model pointer back. To predict, we use the predict API function with the new input data and the model pointer. We get back a data pointer which we turn into a numpy array via a cffi buffer. Finally, we add a custom destructor to make sure we clean up the model data when we are finished. 235 | 236 | You can see the whole file [here](/pyrustlearn/__init__.py). 237 | 238 | ## Putting it all together 239 | To make sure that everything works, we'll [test it](/examples/mnist.py) on the MNIST digits dataset. 240 | 241 | Let's define a couple of helper functions: 242 | 243 | ```python 244 | import numpy as np 245 | 246 | from sklearn.cross_validation import KFold 247 | from sklearn.datasets import load_digits 248 | from sklearn.metrics import accuracy_score 249 | 250 | from pyrustlearn import SGDClassifier 251 | 252 | 253 | def _get_data(): 254 | 255 | data = load_digits() 256 | 257 | X = data.data.astype(np.float32) 258 | y = data.target.astype(np.float32) 259 | 260 | return (X, y) 261 | ``` 262 | 263 | and the main model evaluation loop: 264 | 265 | ```python 266 | def run_example(): 267 | 268 | data, target = _get_data() 269 | 270 | n_folds = 5 271 | accuracy = 0.0 272 | 273 | for (train_idx, test_idx) in KFold(n=len(data), n_folds=n_folds, shuffle=True): 274 | 275 | train_X = data[train_idx] 276 | train_y = target[train_idx] 277 | 278 | test_X = data[test_idx] 279 | test_y = target[test_idx] 280 | 281 | model = SGDClassifier() 282 | model.fit(train_X, train_y) 283 | 284 | predictions = model.predict(test_X) 285 | 286 | accuracy += accuracy_score(predictions, test_y) 287 | 288 | return accuracy / n_folds 289 | ``` 290 | 291 | Running this should succeed, resulting in an accuracy of about 0.92. 292 | 293 | ## Conclusions 294 | 295 | The Python scientific ecosystem is amazing, and I wouldn't advise rewriting any of it in Rust. 296 | 297 | When writing new extension modules, however, I think Rust presents a very compelling alternative to C, C++, and Cython. It is very expressive and safe, and integrating it with Python is no more difficult than C or C++. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Maciej Kula 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. --------------------------------------------------------------------------------