Mike Clark
This workbook is Copyright © 2010 The Pragmatic Studio. Please don’t use it to create training courses or books without permission.
Sample code is provided for educational purposes only, and comes with absolutely no warranty.
This is your workbook—follow along now, or work through it later.
Generate a basic scaffold app:
$ rails saveup $ cd saveup $ rails g scaffold goal name:string amount:decimal
Run it:
$ rake db:migrate $ rails s
And create a goal or two…
ActiveRecord models can serialize themselves as XML or JSON:
$ rails c >> print Goal.first.to_xml >> print Goal.first.to_json >> print Goal.all.to_xml >> print Goal.all.to_json
And resources can be serialized as XML over HTTP:
$ curl http://localhost:3000/goals.xml $ curl http://localhost:3000/goals/1.xml
Add JSON handling to the respond_to
blocks in the actions of the GoalsController
:
def index @goals = Goal.all respond_to do |format| format.html format.xml { render :xml => @goals } format.json { render :json => @goals } end end
Copy in code/staged/goals_controller.rb
for full JSON support
Request the resource with a json
format:
$ curl http://localhost:3000/goals.json $ curl http://localhost:3000/goals/1.json
Response should be a JSON record, or an array of records:
{ "id":1, "name":"Tropical Vacation", "amount":2000.0, "created_at":"2010-05-13T18:20:49Z", "updated_at":"2010-05-13T18:38:55Z" }
RootViewController
to GoalsViewController
⇧ ⌘ J
)How many sections in the table?
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
How many rows per section?
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
What’s the table cell for a given section/row pair?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
Add a goals
instance variable and property to the .h
file:
@interface GoalsViewController : UITableViewController { NSMutableArray *goals; } @property (nonatomic, retain) NSArray *goals; @end
Synthesize and dealloc it in the .m
file:
@synthesize goals; - (void)dealloc { [goals release]; [super dealloc]; }
Change the viewDidLoad
method to initialize the goals
array:
- (void)viewDidLoad { [super viewDidLoad]; self.title = @"Goals"; self.navigationItem.leftBarButtonItem = self.editButtonItem; NSMutableArray *data = [[NSMutableArray alloc] initWithObjects:@"iPad", @"Vacation", @"Donation", nil]; self.goals = data; [data release]; }
Use the size of the goals
array as the number of rows:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [goals count]; }
Configure a row’s cell to contain the name of the goal at the given row:
NSString *goal = [goals objectAtIndex:indexPath.row]; cell.textLabel.text = goal;
Remove the deleted goal from the goals
array:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { [tableView beginUpdates]; if (editingStyle == UITableViewCellEditingStyleDelete) { [goals removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } [tableView endUpdates]; }
code/1-bootstrap
Goal
objectsNSURL *url = [NSURL URLWithString:@"http://localhost:3000/goals.json"]; NSError *error = nil; NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
Synchronously reads data from the URL and creates a string, interpreted using the encoding.
#import "SBJSON.h" NSError *error = nil; SBJSON *json = [[SBJSON alloc] init]; NSArray *results = [json objectWithString:aJsonString error:&error]; [json release];
NSDictionary
if the JSON string has one recordNSArray
of NSDictionary
objects if the JSON string has multiple recordscode/staged/json-framework
directoryGoal
is a client-side representation of the Goal
resource on the server:
@interface Goal : NSObject { NSString *name; NSString *amount; NSString *goalId; NSDate *createdAt; NSDate *updatedAt; } @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *amount; @property (nonatomic, copy) NSString *goalId; @property (nonatomic, retain) NSDate *createdAt; @property (nonatomic, retain) NSDate *updatedAt; - (id)initWithDictionary:(NSDictionary *)dictionary; + (NSArray *)findAllRemote; @end
Don’t forget to synthesize and dealloc the properties:
#import "Goal.h" #import "SBJSON.h" @implementation Goal @synthesize name; @synthesize amount; @synthesize goalId; @synthesize createdAt; @synthesize updatedAt; - (void)dealloc { [name release]; [amount release]; [goalId release]; [createdAt release]; [updatedAt release]; [super dealloc]; } @end
We need to be able to create a Goal
from a dictionary:
- (id)initWithDictionary:(NSDictionary *)dictionary { if (self = [super init]) { self.name = [dictionary valueForKey:@"name"]; self.amount = [NSString stringWithFormat:@"%@", [dictionary valueForKey:@"amount"]]; self.goalId = [dictionary valueForKey:@"id"]; self.createdAt = [dictionary valueForKey:@"created_at"]; self.updatedAt = [dictionary valueForKey:@"updated_at"]; } return self; }
Send a GET request, parse the JSON response, and create Goal
objects:
+ (NSArray *)findAllRemote { NSURL *url = [NSURL URLWithString:@"http://localhost:3000/goals.json"]; NSError *error = nil; NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error]; NSMutableArray *goals = [NSMutableArray array]; if (jsonString) { SBJSON *json = [[SBJSON alloc] init]; NSArray *results = [json objectWithString:jsonString error:&error]; [json release]; for (NSDictionary *dictionary in results) { Goal *goal = [[Goal alloc] initWithDictionary:dictionary]; [goals addObject:goal]; [goal release]; } } return goals; }
Add a refresh
action that fetches the goals and reloads the table:
- (IBAction)refresh { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; self.goals = [Goal findAllRemote]; [self.tableView reloadData]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; }
Call refresh
when the view is loaded:
- (void)viewDidLoad { [super viewDidLoad]; self.title = @"Goals"; self.navigationItem.leftBarButtonItem = self.editButtonItem; [self refresh]; }
Change each row to contain the respective goal’s name and amount:
Goal *goal = [goals objectAtIndex:indexPath.row]; cell.textLabel.text = goal.name; cell.detailTextLabel.text = goal.amount;
The refresh button messages our refresh
action:
- (void)viewDidLoad { [super viewDidLoad]; self.title = @"Goals"; self.navigationItem.leftBarButtonItem = self.editButtonItem; UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)]; self.navigationItem.rightBarButtonItem = refreshButton; [refreshButton release]; [self refresh]; }
code/2-json
code/3-scaffold
directoryGoal
to include CRUD methods that delegate to the libraryGoalsViewController
to delete a remote goalGoalAddViewController
to create or update a remote goal1. Create a request from a URL:
NSURL *url = [NSURL URLWithString:@"http://localhost:3000/goals.json"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [request setHTTPMethod:@"GET"];
2. Send the request synchronously:
NSURLResponse *response = nil; NSError *error = nil; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
3. Handle the returned data:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
To support CRUD, we need four standard verbs:
#import <Foundation/Foundation.h> @interface Resource : NSObject { } + (NSString *)get:(NSString *)url; + (NSString *)post:(NSString *)body to:(NSString *)url; + (NSString *)put:(NSString *)body to:(NSString *)url; + (NSString *)delete:(NSString *)url; @end
Implementation can be generalized:
+ (NSString *)get:(NSString *)url { return [self sendBy:@"GET" to:url withBody:nil]; } + (NSString *)post:(NSString *)body to:(NSString *)url { return [self sendBy:@"POST" to:url withBody:body]; } + (NSString *)put:(NSString *)body to:(NSString *)url { return [self sendBy:@"PUT" to:url withBody:body]; } + (NSString *)delete:(NSString *)url { return [self sendBy:@"DELETE" to:url withBody:nil]; }
+ (NSString *)sendBy:(NSString *)method to:(NSString *)url withBody:(NSString *)body { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]]; [request setHTTPMethod:method]; if (body) { [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; } return [self sendRequest:request]; } + (NSString *)sendRequest:(NSMutableURLRequest *)request { NSHTTPURLResponse *response; NSError *error; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; [responseString autorelease]; return responseString; }
Define new CRUD methods:
@interface Goal : NSObject { NSString *name; NSString *amount; NSString *goalId; NSDate *createdAt; NSDate *updatedAt; } @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *amount; @property (nonatomic, copy) NSString *goalId; @property (nonatomic, retain) NSDate *createdAt; @property (nonatomic, retain) NSDate *updatedAt; - (id)initWithDictionary:(NSDictionary *)dictionary; + (NSArray *)findAllRemote; - (void)createRemote; - (void)updateRemote; - (void)saveRemote; - (void)destroyRemote; @end
Implement CRUD methods to delegate to our custom Resource
class:
- (void)createRemote { NSString *url = [NSString stringWithFormat<EMAIL_ADDRESS>siteURL]; [Resource post:[self params] to:url]; } - (void)updateRemote { NSString *url = [NSString stringWithFormat:@"%<EMAIL_ADDRESS>siteURL, self.goalId]; [Resource put:[self params] to:url]; } - (void)saveRemote { if (self.goalId == nil) { [self createRemote]; } else { [self updateRemote]; } } - (void)destroyRemote { NSString *url = [NSString stringWithFormat:@"%<EMAIL_ADDRESS>siteURL, self.goalId]; [Resource delete:url]; }
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { [tableView beginUpdates]; if (editingStyle == UITableViewCellEditingStyleDelete) { Goal *goal = [goals objectAtIndex:indexPath.row]; // TODO: destroy remote goal [goals removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } [tableView endUpdates]; }
-(IBAction)save { goal.name = nameField.text; goal.amount = amountField.text; // TODO: create or update remote goal [self.delegate didChangeGoal:goal]; [self.navigationController popViewControllerAnimated:YES]; }
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { [tableView beginUpdates]; if (editingStyle == UITableViewCellEditingStyleDelete) { Goal *goal = [goals objectAtIndex:indexPath.row]; [goal destroyRemote]; [goals removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } [tableView endUpdates]; }
-(IBAction)save { goal.name = nameField.text; goal.amount = amountField.text; [goal saveRemote]; [self.delegate didChangeGoal:goal]; [self.navigationController popViewControllerAnimated:YES]; }
⇧ ⌘ R
)code/4-crud
1. Create a request from a URL:
NSURL *url = [NSURL URLWithString:@"http://localhost:3000/goals.json"]; NSURLRequest *request = [NSURLRequest requestWithURL:url];
2. Send the request synchronously:
NSURLResponse *response = nil; NSError *error = nil; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
3. Handle the returned data:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
1. Create a request from a URL:
NSURL *url = [NSURL URLWithString:@"http://localhost:3000/goals.json"]; NSURLRequest *request = [NSURLRequest requestWithURL:url];
2. Send the request asynchronously, with a delegate:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
3. Handle the returned data in a delegate method:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { if (receivedData == nil) { receivedData = [[NSMutableData alloc] init]; } [receivedData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // do something with receivedData } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // handle error }
NSURLConnection
can run a network request asynchronously1. Write a method you want to run asynchronously:
- (void)doWork:(NSObject *)anArgument { // do some work }
2. Wrap the method in an NSInvocationOperation
:
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doWork:) object:anArgument];
3. Add it to an NSOperationQueue
:
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperation:operation]; [operation release];
- (void)doWork:(NSObject *)anArgument { [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; [self.navigationController performSelectorOnMainThread:@selector(popViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:NO]; [self performSelectorOnMainThread:@selector(deleteRowsAtIndexPaths:) withObject:[NSArray arrayWithObject:indexPath] waitUntilDone:NO]; }
Same UI, but with
Base URL where your resources live:
[HRRestModel setBaseURL:[NSURL URLWithString:@"http://your-server"]];
Delegate object that handles responses:
[HRRestModel setDelegate:anObject];
Optional bits:
[HRRestModel setFormat:HRDataFormatXML]; // JSON by default [HRRestModel setBasicAuthWithUsername:@"mike" password:@"secret"];
[HRRestModel getPath:@"/goals" withOptions:nil object:nil];
NSDictionary *params = [NSDictionary dictionaryWithObject: [newGoal JSONRepresentation] forKey:@"body"]; [HRRestModel postPath:@"/goals" withOptions:params object:nil];
NSDictionary *params = [NSDictionary dictionaryWithObject: [updatedGoal JSONRepresentation] forKey:@"body"]; [HRRestModel putPath:@"/goals/3" withOptions:params object:nil];
[HRRestModel deletePath:@"/goals/3" withOptions:nil object:nil];
Results delivered in a callback method implemented by the delegate:
- (void)restConnection:(NSURLConnection *)connection didReturnResource:(id)resource object:(id)object { // resource is an array or dictionary for (id item in resource) { Goal *goal = [[Goal alloc] initWithDictionary:item]; } } - (void)restConnection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response object:(id)object { // If you're interested in handling response codes }
Delegate object should implement these methods, too:
- (void)restConnection:(NSURLConnection *)connection didFailWithError:(NSError *)error object:(id)object { // Handle connection errors: failure to connect to server, etc. } - (void)restConnection:(NSURLConnection *)connection didReceiveError:(NSError *)error response:(NSHTTPURLResponse *)response object:(id)object { // Handle invalid responses: 404, 500, etc. } - (void)restConnection:(NSURLConnection *)connection didReceiveParseError:(NSError *)error responseBody:(NSString *)string { // Request was successful, but couldn't parse the // data returned by the server }
code/5-httpriot
directoryHRRestModel
to see how it worksSet a breakpoint in the refresh
action of GoalsViewController.m
:
- (IBAction)refresh { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; [HRRestModel setDelegate:self]; [HRRestModel getPath:@"/goals" withOptions:nil object:nil]; }
Set another breakpoint in the delegate method:
- (void)restConnection:(NSURLConnection *)connection didReturnResource:(id)resource object:(id)object { NSMutableArray *remoteGoals = [[NSMutableArray alloc] init]; for (NSDictionary *dictionary in resource) { Goal *remoteGoal = [[Goal alloc] initWithDictionary:dictionary]; [remoteGoals addObject:remoteGoal]; [remoteGoal release]; } self.goals = remoteGoals; [remoteGoals release]; [self.tableView reloadData]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; }
refresh
method running in?restConnection:didReturnResource:object:
method running in?Set a breakpoint in the save
action of GoalAddViewController.m
:
-(IBAction)save { goal.name = nameField.text; goal.amount = amountField.text; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; NSDictionary *options = [NSDictionary dictionaryWithObject:[goal JSONRepresentation] forKey:@"body"]; if (goal.goalId == nil) { [HRRestModel postPath:@"goals" withOptions:options object:nil]; } else { [HRRestModel putPath:[NSString stringWithFormat:@"goals/%@", goal.goalId] withOptions:options object:nil]; } }
Set another breakpoint in the delegate method:
- (void)restConnection:(NSURLConnection *)connection didReturnResource:(id)resource object:(id)object { Goal *remoteGoal = [[Goal alloc] initWithDictionary:resource]; [self.delegate didChangeGoal:remoteGoal]; [remoteGoal release]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; [self.navigationController popViewControllerAnimated:YES]; }
Run it, and use the debugger to fully understand how it works.
1. Download, build, and install it:
$ git clone http://github.com/Caged/httpriot.git $ cd httpriot $ mkdir pkg $ gem install versionomy $ rake sdk:dist $ rake sdk:install
2. Set the Additional SDKs build setting to:
~/Library/SDKs/httpriot-0.6.10/$(PLATFORM_NAME)$(IPHONEOS_DEPLOYMENT_TARGET).sdk
3. Set the Other Linker Flags build setting to:
-lhttpriot -lxml2 -ObjC -all_load
4. Set the Header Search Paths build setting to:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.2.sdk/usr/include/libxml2
- (void)get { NSURL *url = [NSURL URLWithString:@"http://your-server.com/goals.json"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDelegate:self]; [request startAsynchronous]; } - (void)post:(NSString *postDataString) { NSURL *url = [NSURL URLWithString:@"http://your-server.com/goals.json"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setRequestMethod:@"POST"]; [request appendPostData:[postDataString dataUsingEncoding:NSUTF8StringEncoding]]; [request setDelegate:self]; [request startAsynchronous]; } - (void)requestFinished:(ASIHTTPRequest *)request { NSString *response = [request responseString]; } - (void)requestFailed:(ASIHTTPRequest *)request { NSError *error = [request error]; }
Remote methods added to NSObject
:
#import "ObjectiveResource.h" @interface Goal : NSObject { NSString *name; NSString *amount; NSString *goalId; NSDate *createdAt; NSDate *updatedAt; } @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *amount; @property (nonatomic, copy) NSString *goalId; @property (nonatomic, retain) NSDate *createdAt; @property (nonatomic, retain) NSDate *updatedAt; @end
Nothing special here:
#import "Goal.h" @implementation Goal @synthesize name; @synthesize amount; @synthesize goalId; @synthesize createdAt; @synthesize updatedAt; - (void)dealloc { [name release]; [amount release]; [goalId release]; [createdAt release]; [updatedAt release]; [super dealloc]; } @end
#import "ObjectiveResource.h" [ObjectiveResourceConfig setSite:@"http://your-server/"]; [ObjectiveResourceConfig setResponseType:JSONResponse];
NSArray *goals = [Goal findAllRemote];
Goal *goal = [[Goal alloc] init]; goal.name = @"Tropical Vacation"; [goal createRemote];
Goal *goal = [Goal findRemote:@"3"]; goal.name = @"Donation"; [goal updateRemote];
[goal destroyRemote];
code/4-crud
directory
Resource
classcode/staged/objectiveresource
directoryjson-framework
directoryGoal.h
:#import "ObjectiveResource.h"
Goal
Resource
classIn SaveUpAppDelegate.m
, add an import:
#import "ObjectiveResourceConfig.h"
And configure ObjectiveResource in application:didFinishLaunchingWithOptions:
:
[ObjectiveResourceConfig setSite:@"http://localhost:3000/"]; [ObjectiveResourceConfig setResponseType:JSONResponse];
Add an initializer that includes:
ActiveRecord::Base.include_root_in_json = true
ObjectiveResource expects JSON responses to include the resource name
code/6-objectiveresource
ConnectionManager
singleton- (void)runJob:(SEL)selector onTarget:(id)target withArgument:(id)argument { NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:target selector:selector object:argument]; [operationQueue addOperation:operation]; [operation release]; }
For example, change refresh
from:
- (IBAction)refresh { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; self.goals = [Goal findAllRemote]; [self.tableView reloadData]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; }
To run a background job instead:
- (IBAction)refresh { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; [[ConnectionManager sharedInstance] runJob:@selector(fetchRemoteGoals) onTarget:self]; }
Write the method that runs on a separate thread:
- (void)fetchRemoteGoals { self.goals = [Goal findAllRemote]; [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; }
code/rails_app
directory
Goal
and Credit
resources (nested)code/iphone_app
directory
The Rails app has a nested Credit
resource:
Saveup::Application.routes.draw do |map| resources :goals do resources :credits end end
Credits are always accessed via a goal:
class CreditsController < ApplicationController before_filter :find_goal def show @credit = @goal.credits.find(params[:id]) respond_to do |format| format.html format.xml { render :xml => @credit } format.json { render :json => @credit } end end protected def find_goal @goal = current_user.goals.find(params[:goal_id]) rescue ActiveRecord::RecordNotFound flash[:error] = "Invalid goal." redirect_to @goal end end
Credit
holds its respective Goal
id:
#import "ObjectiveResource.h" @interface Credit : NSObject { NSString *creditId; NSString *goalId; NSString *name; NSString *amount; NSDate *updatedAt; NSDate *createdAt; } @property (nonatomic, copy) NSString *creditId; @property (nonatomic, copy) NSString *goalId; @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *amount; @property (nonatomic, retain) NSDate *updatedAt; @property (nonatomic, retain) NSDate *createdAt; @end
Credit
must override some methods to be nested:
@implementation Credit @synthesize creditId; @synthesize goalId; + (NSString *)getRemoteCollectionName { return @"goals"; } - (NSString *)nestedPath { NSString *path = [NSString stringWithFormat:@"%@/credits", goalId]; if (creditId) { path = [path stringByAppendingFormat:@"/%@", creditId]; } return path; } - (BOOL)createRemoteWithResponse:(NSError **)aError { return [self createRemoteAtPath:[[self class] getRemoteElementPath:[self nestedPath]] withResponse:aError]; } - (BOOL)updateRemoteWithResponse:(NSError **)aError { return [self updateRemoteAtPath:[[self class] getRemoteElementPath:[self nestedPath]] withResponse:aError]; } - (BOOL)destroyRemoteWithResponse:(NSError **)aError { return [self destroyRemoteAtPath:[[self class] getRemoteElementPath:[self nestedPath]] withResponse:aError]; } @end
On the iPhone side, Goal
can find its remote credits:
@implementation Goal - (NSArray *)findAllRemoteCredits { return [Credit findRemote:[NSString stringWithFormat:@"%@/%@", goalId, @"credits"]]; } @end
Controller needs to scope goals to the current user:
class GoalsController < ApplicationController before_filter :login_required def index @goals = current_user.goals.all respond_to do |format| format.html format.xml { render :xml => @goals } format.json { render :json => @goals } end end end
Filter challenges with HTTP basic authentication:
def login_required return if logged_in? respond_to do |format| format.html do save_location redirect_to login_url end format.any(:json, :xml) do unless login_from_basic_auth request_http_basic_authentication end end end end
ObjectiveResource will automatically respond to authentication challenges:
[ObjectiveResourceConfig setSite:@"http://your-server/"]; [ObjectiveResourceConfig setResponseType:JSONResponse]; [ObjectiveResourceConfig setUser:@"mike"]; [ObjectiveResourceConfig setPassword:@"secret"];
Always store credentials in the iPhone keychain:
- (void)saveCredentialsToKeychain { NSURLCredential *credentials = [NSURLCredential credentialWithUser:self.login password:self.password persistence:NSURLCredentialPersistencePermanent]; [[NSURLCredentialStorage sharedCredentialStorage] setCredential:credentials forProtectionSpace:[self protectionSpace]]; }
Try to create a remote Session
(it’s a resource):
- (BOOL)authenticate:(NSError **)error { if (![self hasCredentials]) { return NO; } Session *session = [[[Session alloc] init] autorelease]; session.login = self.login; session.password = self.password; return [session createRemoteWithResponse:error]; }
When the app launches, authenticate or show the login view:
- (void)login { if ([self.user hasCredentials]) { NSError *error = nil; BOOL authenticated = [self.user authenticate:&error]; if (authenticated == NO) { [AppHelpers handleRemoteError:error]; [self showAuthentication:self.user]; } } else { [self showAuthentication:self.user]; } }
Be careful what you serialize by default from Rails:
class User < ActiveRecord::Base def to_xml(options={}) default_serialization_options(options) super(options) end def to_json(options={}) default_serialization_options(options) super(options) end def default_serialization_options(options={}) options[:only] = [:username, :user_id, :updated_at, :created_at] end end
Cache expiration is notoriously challenging
If you have a network connection:
If you don’t have a network connection:
Keep local and remote objects in sync:


new generation unit test framework for C
First, download a release tarball.
Novaprova is intended to be built in the usual way that any open source C software is built. However at the moment it doesn't even use autotools, so there's no configure script. To build you need to have g++ and gcc installed. You will also need to have the valgrind.h header file installed, which is typically in a package named something like valgrind-dev .
# download the release tarball from http://sourceforge.net/projects/novaprova/files/ tar -xvf novaprova-1.1.tar.bz2 cd novaprova-1.1 make make install
For advanced users only. Novaprova needs several more tools to build from a Git checkout than from a release tarball, mainly for the documentation. You will need to have Python Markdown, Pygments, and Doxygen installed. On an Ubuntu system these are in packages python-markdown, python-pygments, and doxygen respectively.
git clone git://github.com/gnb/novaprova.git
cd novaprova
make
make install
Because you're testing C code, the first step is to build a test runner executable. This executable will contain all your tests, the Code Under Test and a small main routine, and will be linked against the NovaProva library and whatever other libraries your Code Under Test needs. Typically, this is done using the check: make target to both build and run the tests.
# Makefile check: testrunner ./testrunner TEST_SOURCE= mytest.c TEST_OBJS= $(TEST_SOURCE:.c=.o) testrunner: testrunner.o $(TEST_OBJS) libmycode.a $(LINK.c) -o $@ testrunner.o $(TEST_OBJS) libmycode.a $(NOVAPROVA_LIBS)
NovaProva uses the GNOME pkgconfig system to make it easy to find the right set of compile and link flags.
NOVAPROVA_CFLAGS= $(shell pkg-config --cflags novaprova) NOVAPROVA_LIBS= $(shell pkg-config --libs novaprova) CFLAGS= ... -g $(NOVAPROVA_CFLAGS) ...
Note that you only need to compile the test code mytest.c and the test runner code testrunner.c with NOVAPROVA_CFLAGS. NovaProva does not use any magical compile options or do any pre-processing of test code.
However, you should make sure that at least the test code is built with the -g option to include debugging information. NovaProva uses that information to discover tests at runtime.
Your main routine in testrunner.c will initialise the NovaProva library by calling np_init and then call np_run_tests to do all the heavy lifting. Here's a minimal main.
/* testrunner.c */ #include <stdlib.h> #include <unistd.h> #include <np.h> /* NovaProva library */ int main(int argc, char **argv) { int ec = 0; np_runner_t *runner; /* Initialise the NovaProva library */ runner = np_init(); /* Run all the discovered tests */ ec = np_run_tests(runner, NULL); /* Shut down the NovaProva library */ np_done(runner); exit(ec); }
The last piece of the puzzle is writing some tests. Each test is a single C function which takes no parameters and returns void. Unlike other unit test frameworks, there's no API to call or magical macro to use to register tests with the library. Instead you just name the function test_something, and NovaProva will automatically create a test called something which calls the function.
For example, let's create a test called simple which tests the function myatoi which has the same signature and semantics as the well-known atoi function in the standard C library.
/* mytest.c */ #include <np.h> /* NovaProva library */ #include "mycode.h" /* declares the Code Under Test */ static void test_simple(void) { int r; r = myatoi("42"); NP_ASSERT_EQUAL(r, 42); }
The macro NP_ASSERT_EQUAL checks that it's two integer arguments are equal, and if not fails the test. Note that if the assert fails, the test function terminates immediately. If the test function gets to it's end and returns naturally, the test is considered to have passed.
If we build run this test we get output something like this.
% make check
./testrunner
np: starting valgrind
np: running
np: running: "simple"
PASS simple
np: 1 run 0 failed
As expected, the test passed. Now let's add another test. The myatoi function is supposed to convert the initial numeric part of the argument string, i.e. to stop when it sees a non-numeric character. Let's feed it a string which will exercise this behaviour and see what happens.
static void test_initial(void) { int r; r = myatoi("4=2"); NP_ASSERT_EQUAL(r, 4); }
Running the tests we see:
% make check ./testrunner np: starting valgrind np: running np: running: "mytest.simple" PASS mytest.simple np: running: "mytest.initial" EVENT ASSERT NP_ASSERT_EQUAL(r=532, 4=4) at 0x80529F2: np::spiegel::describe_stacktrace (np/spiegel/spiegel.cxx) by 0x804C0FC: np::event_t::with_stack (np/event.cxx) by 0x804B2D2: __np_assert_failed (uasserts.c) by 0x804AC27: test_initial (mytest.c) by 0x80522D0: np::spiegel::function_t::invoke (np/spiegel/spiegel.cxx) by 0x804C731: np::runner_t::run_function (np/runner.cxx) by 0x804D5C4: np::runner_t::run_test_code (np/runner.cxx) by 0x804D831: np::runner_t::begin_job (np/runner.cxx) by 0x804E0D4: np::runner_t::run_tests (np/runner.cxx) by 0x804E22C: np_run_tests (np/runner.cxx) by 0x804AB12: main (testrunner.c) FAIL mytest.initial np: 2 run 1 failed make: *** [check] Error 1
The first thing we see is that the name of the old test has changed from simple to mytest.simple. NovaProva organises tests into a tree whose node names are derived from the test source directory, test source filename, and test function name. This tree is pruned down to the smallest possible size at which the root of the tree is unique. So when we added a second test in the same source file, the full name of both tests now includes a component mytest derived from the name of the source file mytest.c.
Note also that the new test failed. Immediately after the "np: running:" message we see that the NP_ASSERT_EQUAL macro has failed, and printed both its arguments as well as a stack trace. We expected the variable r to equal to 4 but its actual value at runtime was 532; clearly the myatoi function did not behave correctly. We found a bug!


Advanced Vector Extensions 512 - VL
Intel® AVX512VL is a 512 bit instruction set extension including 128-bit and 256-bit versions of instructions that use the EVEX encoding.


The paper [1] is proposing a social bookmarking system called Social Semantic Collaborative Filtering (SSCF). It presents how digital libraries can be combined with social semantic information sources and it exemplifies how these techniques can improve e-Learning. The goal of the SSCF is to enhance individual bookmarks with shared knowledge of the community. The Fig. 1 shows the dificulty (or time-consumptions) of bookmarking all the interested links and then share all of them in a blog for other users.
Source: [1]
In order to solve this problem, they [1] proposed a SSCF bookmarking system, which is based on JeremeDL. This platform joins 3 separated applications: blog, Digital Library, and bookmarking application (Fig. 3), to solve the problems above-mentioned.
Source: [1]
JeromeDL can be use to reduce the time of login in 3 different applications as show in the Fig. 5
Source: [1]
The process that includes SOIC ontology support and alignment is the following:
- Users can bookmark blog post, forums, or URL site.
- Extract metadata from the bookmarked site using SOIC browser (http://sparql.captsolo.net/browser/browser.py?url=URL).
- All relevant information is saved to the SSCF RDF repository.
- SSCF module generates bookmark trees and also displays SIOC information.
- Ontology alignment: creating some content using SIOC metadata and delivery mediation mechanism for other SSCF/JeromeDL content.
I like the idea of organizing and categorizing URL sites using existing ontologies and web semantics. This allow to group similar content together and enhance navigability of the information. It’s also interesting the way they join multiple applications (library, bookmarks and blog) in other to reduce the time as shown in the Fig. 5. However, it’s not clear to me how if the SSCF is an addon to the JeremeDL system or if is a fork of this project.
Mentions:
- Semantic Web, http://en.wikipedia.org/wiki/Semantic_Web,
- Ping Semantic Web, http://pingthesemanticweb.com/, repository for RDF documents
- SIOC (Semantically-Interlinked Online Communities), http://sioc-project.org/, aims to enable the integration of online community information
- Connotea, http://www.connotea.org/, Free online reference management for all researchers, clinicians and scientists.
- Open directory, dmoz.org, uses a hierarchical ontology scheme for organizing site listings.
- RDF (Resource Description Framework),http://en.wikipedia.org/wiki/Resource_Description_Framework, description or modeling of information that is implemented in web resources
- JeromeDL, http://www.jeromedl.org/, Social Semantic Digital Library. As a digital library, it allows institutions to easily publish documents on the Web. It supports a variety of document formats and allows to store and query a rich bibliographic description of each document
Ideas:
- Uses a hierarchical ontology scheme for organizing site listings and also uses web semantics to categorize information.
- Join multiple applications to reduce time user’s time performing common tasks.
Reference:
[1] Sebastian Ryszard Kruk, Adam Gzella, Jaros law Dobrzanski,Bill McDaniel, and Tomasz Woroniecki; “E-Learning on the Social Semantic Information Sources”; EC-TEL 2007, LNCS 4753, pp. 172–186, 2007. Springer-Verlag Berlin Heidelberg 2007.


SOFTWARE INFO
-
Software version:[BUILD_VERSION]
-
Build date:[BUILD_DATE]
PROJECT LINKS
-
Repository:
-
Documentation:
-
Editor:
TESTING TOOLS
-
JSON/Python converter:


Street Food
We don't play with food
When I was a small boy, my father told me never to recommend a church or a woman to anyone. And I have found it wise never to recommend a restaurant either. Something always goes wrong with the cheese soufflé
Eat together
There is something profoundly satisfying about sharing a meal. Eating together, breaking bread together, is one ofthe oldest and most fundamental unifying of human experiences.
Explore Menu
- Burger Name
- Burger Name
- Burger Name
- Burger Name
- Burger Name
- Burger Name
There is something profoundly satisfying about sharing a meal
There is something profoundly satisfying about sharing a meal
There is something profoundly satisfying about sharing a meal
There is something profoundly satisfying about sharing a meal
There is something profoundly satisfying about sharing a meal
There is something profoundly satisfying about sharing a meal
Hot Deals
SPECIAL COMBO PACK
Burger Pizz
Fries & Drinks
There is something profoundly satisfying about sharinga meal. Eating together, breaking bread together, is one of the oldest and most fundamentally unifying of human experiences.
Contact Us
There is something profoundly satisfying about sharing a meal. Eating together, breaking bread together, is one of the oldest and most fundamentally unifying of human experiences.


YARN has multiple features to enforce container memory limits. There are three types of controls in YARN that can be used. 1. The polling feature monitors periodically measures container memory usage and kills the containers that exceed their limits. This is a legacy feature with some issues notably a delay that may lead to node shutdown. 2. Strict memory control kills each container that has exceeded its limits. It is using the OOM killer capability of the cgroups Linux kernel feature. 3. Elastic memory control is also based on cgroups. It allows bursting and starts killing containers only, if the overall system memory usage reaches a limit.
If you use 2. or 3. feature 1. is disabled.
cgroups can be used to preempt containers in case of out-of-memory events. This feature leverages cgroups to clean up containers with the kernel when this happens. If your container exited with exit code 137, then ou can verify the cause in /var/log/messages.
The cgroups kernel feature has the ability to notify the node manager, if the parent cgroup of all containers specified by yarn.nodemanager.linux-container-executor.cgroups.hierarchy goes over a memory limit. The YARN feature that uses this ability is called elastic memory control. The benefits are that containers can burst using more memory than they are reserved to. This is allowed as long as we do not exceed the overall memory limit. When the limit is reached the kernel freezes all the containers and notifies the node manager. The node manager chooses a container and preempts it. It continues this step until the node is resumed from the OOM condition.
The limit is the amount of memory allocated to all the containers on the node. The limit is specified by yarn.nodemanager.resource.memory-mb and yarn.nodemanager.vmem-pmem-ratio. If these are not set, the limit is set based on the available resources. See yarn.nodemanager.resource.detect-hardware-capabilities for details.
The preemption logic specifies which container to preempt in a node wide out-of-memory situation. The default logic is the DefaultOOMHandler. It picks the latest container that exceeded its memory limit. In the unlikely case that no such container is found, it preempts the container that was launched most recently. This continues until the OOM condition is resolved. This logic supports bursting, when containers use more memory than they reserved as long as we have memory available. This helps to improve the overall cluster utilization. The logic ensures that as long as a container is within its limit, it won’t get preempted. If the container bursts it can be preempted. There is a case that all containers are within their limits but we are out of memory. This can also happen in case of oversubscription. We prefer preemting the latest containers to minimize the cost and value lost. Once preempted, the data in the container is lost.
The default out-of-memory handler can be updated using yarn.nodemanager.elastic-memory-control.oom-handler. The class named in this configuration entry has to implement java.lang.Runnable. The run() function will be called in a node level out-of-memory situation. The constructor should accept an NmContext object.
In case of Elastic Memory Control, the limit applies to the physical or virtual (rss+swap in cgroups) memory depending on whether yarn.nodemanager.pmem-check-enabled or yarn.nodemanager.vmem-check-enabled is set.
There is no reason to set them both. If the system runs with swap disabled, both will have the same number. If swap is enabled the virtual memory counter will account for pages in physical memory and on the disk. This is what the application allocated and it has control over. The limit should be applied to the virtual memory in this case. When swapping is enabled, the physical memory is no more than the virtual memory and it is adjusted by the kernel not just by the container. There is no point preempting a container when it exceeds a physical memory limit with swapping. The system will just swap out some memory, when needed.
There is a difference between the virtual memory reported by the container monitor and the virtual memory limit specified in the elastic memory control feature. The container monitor uses ProcfsBasedProcessTree by default for measurements that returns values from the proc file system. The virtual memory returned is the size of the address space of all the processes in each container. This includes anonymous pages, pages swapped out to disk, mapped files and reserved pages among others. Reserved pages are not backed by either physical or swapped memory. They can be a large part of the virtual memory usage. The reservabe address space was limited on 32 bit processors but it is very large on 64-bit ones making this metric less useful. Some Java Virtual Machines reserve large amounts of pages but they do not actually use it. This will result in gigabytes of virtual memory usage shown. However, this does not mean that anything is wrong with the container.
Because of this you can now use CGroupsResourceCalculator. This shows only the sum of the physical memory usage and swapped pages as virtual memory usage excluding the reserved address space. This reflects much better what the application and the container allocated.
In order to enable cgroups based resource calculation set yarn.nodemanager.resource-calculator.class to org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.CGroupsResourceCalculator.
The following levels of memory enforcement are available and supported:
| Level | Configuration type | Options |
|---|---|---|
| 0 | No memory control | All settings below are false |
| 1 | Strict Container Memory enforcement through polling | P or V |
| 2 | Strict Container Memory enforcement through cgroups | CG, C and (P or V) |
| 3 | Elastic Memory Control through cgroups | CG, E and (P or V) |
The symbols above mean that the respective configuration entries are true:
P: yarn.nodemanager.pmem-check-enabled
V: yarn.nodemanager.vmem-check-enabled
C: yarn.nodemanager.resource.memory.enforced
E: yarn.nodemanager.elastic-memory-control.enabled
CG: C and E require the following prerequisites: 1. yarn.nodemanager.container-executor.class should be org.apache.hadoop.yarn.server.nodemanager.LinuxContainerExecutor. 2. yarn.nodemanager.runtime.linux.allowed-runtimes should at least be default. 3. yarn.nodemanager.resource.memory.enabled should be true
yarn.nodemanager.pmem-check-enabled and yarn.nodemanager.vmem-check-enabled should be false.
yarn.nodemanager.resource.memory.enforced should be false.
yarn.nodemanager.elastic-memory-control.enabled should be false.
yarn.nodemanager.pmem-check-enabled or yarn.nodemanager.vmem-check-enabled should be true.
yarn.nodemanager.resource.memory.enforced should be false.
yarn.nodemanager.elastic-memory-control.enabled should be false.
Strict memory control preempts containers right away using the OOM killer feature of the kernel, when they reach their physical or virtual memory limits. You need to set the following options on top of the prerequisites above to use strict memory control.
Configure the cgroups prerequisites mentioned above.
yarn.nodemanager.pmem-check-enabled or yarn.nodemanager.vmem-check-enabled should be true. You can set them both. Currently this is ignored by the code, only physical limits can be selected.
yarn.nodemanager.resource.memory.enforced should be true
The cgroups based elastic memory control preempts containers only if the overall system memory usage reaches its limit allowing bursting. This feature requires setting the following options on top of the prerequisites.
Configure the cgroups prerequisites mentioned above.
yarn.nodemanager.elastic-memory-control.enabled should be true.
yarn.nodemanager.resource.memory.enforced should be false
yarn.nodemanager.pmem-check-enabled or yarn.nodemanager.vmem-check-enabled should be true. If swapping is turned off the former should be set, the latter should be set otherwise.


Unit Convert
From:
To:
Select a unit
Meter
Kilometer
Centimeter
Millimiter
Micrometer
Nanometer
Mile
Yard
Foot
Inch
Light Year
Select a unit
Meter
Kilometer
Centimeter
Millimiter
Micrometer
Nanometer
Mile
Yard
Foot
Inch
Light Year


About Us
Our Privacy Policy!
Introduction Grid systems are used for creating page layouts through a series of rows and columns that house your content. Here's how the Bootstrap grid system works: Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding. Use rows to create horizontal groups of columns. Content should be placed within columns, and only columns may be immediate children of rows. Predefined grid classes like .row and .col-xs-4 are available for quickly making grid layouts. Less mixins can also be used for more semantic layouts. Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and last column via negative margin on .rows. The negative margin is why the examples below are outdented. It's so that content within grid columns is lined up with non-grid content. Grid columns are created by specifying the number of twelve available columns you wish to span. For example, three equal columns would use three .col-xs-4. If more than 12 columns are placed within a single row, each group of extra columns will, as one unit, wrap onto a new line. Grid classes apply to devices with screen widths greater than or equal to the breakpoint sizes, and override grid classes targeted at smaller devices. Therefore, e.g. applying any .col-md-* class to an element will not only affect its styling on medium devices but also on large devices if a .col-lg-* class is not present. Look to the examples for applying these principles to your code.


| Home | Trees | Indices | Help |
|
|---|
|
|
defines all "built-in" classes that implement declarations compare functionality according to some criteria
| Classes | |
|
matcher_base_t matcher_base_t class defines interface for classes that will implement compare functionality according to some criteria. |
|
|
and_matcher_t Combine several other matchers with "&". |
|
|
or_matcher_t Combine several other matchers with "|". |
|
|
not_matcher_t Return the inverse result of matcher, using "~" |
|
|
declaration_matcher_t Instance of this class will match declarations by next criteria: |
|
|
variable_matcher_t Instance of this class will match variables by next criteria: |
|
|
namespace_matcher_t Instance of this class will match namespaces by name. |
|
|
calldef_matcher_t Instance of this class will match callable by next criteria: |
|
|
operator_matcher_t Instance of this class will match operators by next criteria: |
|
|
regex_matcher_t Instance of this class will match declaration using regular expression. |
|
|
access_type_matcher_t Instance of this class will match declaration by its access type: public, private or protected. |
|
|
virtuality_type_matcher_t Instance of this class will match declaration by its virtuality type: not virtual, virtual or pure virtual. |
|
|
custom_matcher_t Instance of this class will match declaration by user custom criteria. |
| Home | Trees | Indices | Help |
|
|---|
| Generated by Epydoc 3.0.1 on Mon Oct 20 09:00:17 2008 | http://epydoc.sourceforge.net |


This is the phone that's changing the shape of the future. Discover the cutting-edge hinge
technology that allows it to fold like a book, stand on its own, and break the rules of what you
thought a smartphone should do.
{% for product in products %}
{% if product.compName == "Samsung" %}
{{product.mobName}}
₹ {{product.price}}
{% endif %}
{% endfor %}
{% for product in products %}
{% if product.compName == "Apple" %}


--- layout: post title: "Journal - Week 3 of FUSRP" subtitle: "" date: 2020-07-26 18:04:00 -0400 background: '/img/posts/02.jpg' ---
This week was a busy week. Prof.Hilfinger clarifies our research goals again. It is definitely more clear when things are written down as physically-seen words. I finally understand that we are trying to find a procedure to characterize individual, a fingerprint given one’s glucose data in the hope to provide personalized medicine service. To achieve this goal, we need to analyze the given data (box plots, autocorrelation, big drop & rise), while finding a control and regulation rule that explains how glucose data interacts in one’s body. We also have our midterm presentation soon. I found a template and tried to make slides look visually attractive. My teammates will be responsible for the intellectually attractive part :D
We have tried new ways to measure the interpolation error and the device error. Another week that I got carried by my research partner...
I found myself lack motivation while working remotely at home; really miss the days where we can go to library to study/work with friends. Lots of readings to do for lecture notes... The hardest part is to start doing it. Otherwise, I can procrastinate the whole day with no efforts :(


Toggle navigation
Home
General
Summary
Emails
Names
DNS
Config
Maps
Records
Registered Domains
Domain
Hosts
Squatting
Subdomains
Whois Domain
Whois IP
Files
Excel
PDF
PowerPoint
Text
Word
Reports
Active Recon
Passive Recon
Active
Certificates
Traceroute
Web App FW
WhatWeb
Zone Transfer
Active
WhatWeb


Purple Martians
Technical Code Descriptions
Project Organization
Software and Libraries
Allegro
MinGW-w64
Code::Blocks
Source files
Class Naming Conventions
Main
Game Objects
Software and Libraries
Purple Martians is written in C++ and is complied with gcc, the gnu C compiler.
It uses the Allegro game library for display creation, drawing, input, sound, etc...
Because Allegro is a cross platform library, I use the exact same source code to generate the windows and linux versions.
On windows, I use MinGW-w64 port of gcc.
I use Code::Blocks as my IDE, it has windows and linux versions, and the same project file works for both.
All software used is free and open source.
Allegro
Allegro - A Game Programming Library
Allegro is a cross-platform library mainly aimed at video game and multimedia programming. It handles common, low-level tasks such as creating windows, accepting user input, loading data, drawing images, playing sounds, etc. and generally abstracting away the underlying platform. However, Allegro is not a game engine: you are free to design and structure your program as you like.
MinGW-w64
MinGW-w64 - A complete runtime environment for GCC & LLVM for 32 and 64 bit Windows
Mingw-w64 is an advancement of the original mingw.org project, created to support the GCC compiler on Windows systems. It has forked it in 2007 in order to provide support for 64 bits and new APIs. It has since then gained widespread use and distribution.
Code::Blocks
Code::Blocks - The free C/C++ and Fortran IDE.
Code::Blocks is a free C/C++ and Fortran IDE built to meet the most demanding needs of its users. It is designed to be very extensible and fully configurable.
Source files
All the source and header files are in the 'src' directory and all compile and link to a single executable.
'pm.exe' for windows
'pm' for linux
Class Naming Conventions
Classes are declared and defined in a pair of .cpp and .h files with the same name as the class.
Then an instance is defined and externally declared.
For example, class name: 'mwFont'
Declared in 'mwFont.h'
// mwFont.h
class mwFont
{
public:
void load_fonts(void);
ALLEGRO_FONT *pixl;
};
extern mwFont mFont;
Implemented in 'mwFont.cpp'
// mwFont.cpp
#include "mwFont.h"
mwFont mFont;
void mwFont::load_fonts(void)
{
al_destroy_font(pixl);
pixl = al_load_ttf_font("bitmaps/PixelGosub.otf", 7, ALLEGRO_TTF_MONOCHROME | ALLEGRO_TTF_NO_KERNING);
if (!pixl) mInput.m_err("Failed to load font from bitmaps/PixelGosub.otf");
.....
}
An instance 'mFont' is defined in 'mwFont.cpp' and externally declared in 'mwFont.h'
Then any source file that uses mwFont just needs to include:
#include "mwFont.h"
And then it refers to the object members like:
mFont.load_fonts()
mFont.pixl
Main
The function 'main' is found in the file: 'main.cpp'.
int main(int argument_count, char **argument_array)
{
mMain.pm_main(argument_count, argument_array);
}
It just directly calls 'mMain.pm_main'
int mwMain::pm_main(int argument_count, char **argument_array)
{
proc_command_line_args1(argument_count, argument_array); // these args get processed before initial setup is called
if (initial_setup())
{
proc_command_line_args2(argument_count, argument_array); // these args get processed after initial setup is called
if (mLoop.state[0] == 0) // nothing set by command line args
{
mLoop.state[1] = mLoop.state[0] = 1; // set up for menu
}
mLoop.main_loop();
}
if (mLog.autosave_log_on_program_exit) mLog.save_log_file();
mConfig.save();
final_wrapup();
exit(0);
}
Game Objects
There are 5 categories of game objects:
Players
class: mwPlayer
instance: mPlayer
files:
mwPlayer.h
mwPlayer.cpp
There are data structures for 8 players.
The class contains two arrays of structures for each player. One local and one synced in netgame.
struct psyn syn[NUM_PLAYERS];
struct ploc loc[NUM_PLAYERS];
Enemies
class: mwEnemy
instance: mEnemy
files:
mwEnemy.h
mwEnemy.cpp
mwEnemyArchwagon.cpp
mwEnemyCannon.cpp
mwEnemyCloner.cpp
mwEnemyEditorFnx.cpp
mwEnemyFlapper.cpp
mwEnemyFnx.cpp
mwEnemyJumpworm.cpp
mwEnemyTrakbot.cpp
mwEnemyVinePod.cpp
There are data structures for 100 enemies.
Each enemy has an array of 32 integers and 16 floats
int Ei[100][32]; // enemy ints
float Ef[100][16]; // enemy floats
Items
class: mwItem
instance: mItem
files:
mwItem.h
mwItemBombRocket.cpp
mwItemDoor.cpp
mwItemEditorFnx.cpp
mwItemKeySwitch.cpp
mwItemMessage.cpp
mwItemStartExitGate.cpp
mwItemTrigger.cpp
There are data structures for 500 items.
Each item has an array of 16 integers and 4 floats
int item[500][16]; // item ints
float itemf[500][4]; // item floats
Shots
class: mwShot
instance: mShot
files:
mwShot.h
mwShot.cpp
There are data structures for 50 player shots and 50 enemy shots
struct eshot e[50];
struct pshot p[50];
Lifts
class: mwLift
instance: mLift
files:
mwLift.h
mwLift.cpp
There are data structures for 40 lifts, each containing 40 lift steps
struct lift cur[NUM_LIFTS];
struct lift_step stp[NUM_LIFTS][40];


--- layout: post status: publish published: true title: '"Dat LaStella Doh" - Podcast Episode 6.45' author: display_name: Corey Fineran login: Corey email<EMAIL_ADDRESS>url: '' author_login: Corey author_email<EMAIL_ADDRESS>wordpress_id: 10480 wordpress_url: http://ivyenvy.com/?p=10480 date: '2014-11-16 23:04:02 +0000' date_gmt: '2014-11-17 05:04:02 +0000' categories: - Podcast tags: - Arodys Vizcaino - Russell Martin - Tommy LaStella comments: - id: 15378 author: SteveHoffman author_email<EMAIL_ADDRESS>author_url: '' date: '2014-11-21 16:23:54 +0000' date_gmt: '2014-11-21 22:23:54 +0000' content: "…folks!!" - id: 20280 author: http://www.fodig.de/plugins.php?fussballbekleidung/textilien/sweatshirts/hummel-sweatshirts/hummel-sweatshirt-roots-kids-rot-f3062.html,http://www.fodig.de/plugins.php?fussballbekleidung/textilien/sweatshirts/hummel-sweatshirts/hummel-sweatshirt-roots-kid author_email: '' author_url: http://www.fodig.de/plugins.php?fussballbekleidung/textilien/sweatshirts/hummel-sweatshirts/hummel-sweatshirt-roots-kids-rot-f3062.html,http://www.fodig.de/plugins.php?fussballbekleidung/textilien/swe date: '2015-09-08 08:11:48 +0000' date_gmt: '2015-09-08 13:11:48 +0000' content: |- http://www.fodig.de/plugins.php?fussballbekleidung/textilien/sweatshirts/hummel-sweatshirts/hummel-sweatshirt-roots-kids-rot-f3062.html,http://www.fodig.de/plugins.php?fussballbekleidung/textilien/sweatshirts/hummel-sweatshirts/hummel-sweatshirt-root… Four players scored double figures for Class 2 A No. 2 Wesprefer only one type, boxers or boxer briefs. On the other hand, designer house Paul Smith is comingdbags' for years she now has about 40 but as prices climb towards 1,000, she knows she will n… ---
A few hours before we recorded this episode, the Cubs traded Arodys Vizcaino back to the Braves for 2nd baseman, Tommy LaStella. We discuss why the Cubs may have made this trade and what it may (or may not) signal as far as bigger deals the Cubs are setting up.
Baseball Prospectus released their Top 10 Cubs prospects list this week. We were a little surprised that Addison Russell was ranked #1 over Kris Bryant and talk about why Russell earned the top spot. In this discussion, I mentioned an episode of Effectively Wild. You can find that episode here.
We talk about the general hype that the Cubs have started to get and talk about how that may expand in the future. This conversation comes up because the Cubs/Cardinals Opening Day game has been moved to primetime, the night before.


Predict¶
At the heart of convergent cross mapping is the k-nearest neighbors algorithm. In fact, the package uses scikit-learn’s nearest neighbor implementation for efficient calculation of distances and to retrieve the indices of the nearest neighbors. It is a good idea to understand the k-nearest neighbor algorithm before interpreting what this package implements.
Training and Testing¶
Before making predictions, split the embedded time series into a testing set and a training set. This protects against highly autocorrelated time series. For example, random walk time series can seem like they are coupled if they are not split into a training set and testing set.
The code for this is done with a function in skccm.utilities
.
from skccm.utilities import train_test_split
#split the embedded time series
x1tr, x1te, x2tr, x2te = train_test_split(X1,X2, percent=.75)
The code above uses the first 75% as the training set (to rebuild the shadow manifolds) and uses the last 25% as the testing set.
Distance Calculation¶
At this point, you will have these four embedded time series:
- X1tr
- X1te
- X2tr
- X2te
The distance is calculated from every sample in X1te
to every sample in X1tr
. The same is then done for X2tr
and X2te
. The distances are then sorted and the closest \(k\) indices are kept to make a prediction in the next step. \(k\) is the embedding dimension plus 1. So if your embedding dimension was three, then the amount of near neighbors used to make a prediction will be four.
Weighted Average¶
The next step is to use the near neighbor indices and weights to make a prediction about the other time series. The indices that were found by calculating the distance from every sample in X1te to every sample in X1tr, are used on X2tr to make a prediction about X2te. This seems a little counterintuitive, but it is expected that if one time series influences the other, the system being forced should be in a similar state when the system doing the forcing is in a certain configuration.
Notice the distances and indices have the same number of samples as the testing set, but an extra dimension. This is because you need \(K+1\) near neighbors in order to surround a point.
Library Length¶
A prediction is made for multiple library lengths. As the library length is increased, the prediction skill should converge. By increasing the library length, the density of the rebuilt attractor is increasing. As that attractor becomes more and more populated, better predictions should be able to be made.


Let Sn be the regular n-sided polygon – or shape – whose vertices vk (k = 1,2,…,n) have coordinates:
| xk = cos( 2k-1/n180° ) | |
| yk = sin( 2k-1/n180° ) |
Each Sn is to be interpreted as a filled shape consisting of all points on the perimeter and in the interior.
The Minkowski sum, S+T, of two shapes S and T is the result of adding every point in S to every point in T, where point addition is performed coordinate-wise: (u, v) + (x, y) = (u+x, v+y).
For example, the sum of S3 and S4 is the six-sided shape shown in pink below:
How many sides does S1864 + S1865 + … + S1909 have?


Adult Mom accuses record label Tiny Engines of breach of contract
"The business model of Tiny Engines appears to be this: Use the money that the more successful bands make on funding small releases and signings. Never pay the successful band for as long as humanly possible"
Adult Mom has accused their record label Tiny Engines of breach of contract, citing various alleged late royalty payments as well as “unprofessional” conduct in subsequent discussions about returning the musician’s masters.
In a series of tweets yesterday (November 9), the lo-fi indie artist – whose real name is Stevie Knipe – took to Twitter with an initial 18-part thread detailing their recent wrangles with the label. They claim that Tiny Engines sent “0 [zero] statements or royalty payments” between signing for them in 2015 and May 2018, and have been “sporadic and irresponsible” in doing so since then. See the key tweets below.
Since posting the thread, Tiny Engines alumni Mannequin Pussy, now signed to Epitaph Records, retweeted with a comment that appeared to suggest they had experienced similar problems while signed to the label. Knipe also tweeted to claim they are aware of “at LEAST 10 other bands on this label who have experienced this or something similar”.
Several other bands and musicians have since commented in support of Knipe, including Diet Cig, Titus Andronicus and Speedy Ortiz singer Sadie Dupuis.
The artist has remained active on social media throughout the weeekend, posting messages of thanks for the support offered to her by fans and artists, a list of ways fans can financially support them without contributing to Tiny Engines, and a reminder that there will still be a new Adult Mom record next year.
Adult Mom has released two albums to date: 2015’s Momentary Lapse of Happily and 2017’s Soft Spots, both via Tiny Engines. Watch the video for ‘Drive Me Home’ below.
On the Tiny Engines website, Adult Mom is presently listed under ‘Alumni’ rather than ‘Current Artists’. There has been no official response to Knipe’s accusations from Tiny Engines at the time of writing. NME has reached out for comment.


Appointlet
Grow your sales, not your inbox. Turn more prospects into customers by letting them book you right away, without the costly back-and-forth. When prospects can book you at the peak of their interest, you'll see up to a 300% increase in conversion rates and closed sales. Appointlet allows you to turn more prospects into customers by letting them connect with you straight from your landing pages, emails & sales funnels. Bookings are then seamlessly added to your Google or Office 365 calendar so you can focus on selling.
- Customize your appointment schedule and booking page.
- Share your personal booking page with your customers & prospects. You can integrate your scheduling page into your website, emails and landing pages.
- Your customers & prospects book an available time with you. It's automatically added to your calendar and theirs without the tedious back and forth.
Up to 80% time saved from eliminating back-and-forth, manual reminders & appointment administration tasks means you'll close sales faster. Your customers & prospects will love the convenience and simplicity of online booking. Boost their confidence in you and stand out from the crowd.


3 references to Members
System.Management.Automation (3)
engine\MshMemberInfo.cs (3)
4023
Members
[newMember.Name] = newMember;
4044
var members =
Members
;
4081
var members =
Members
;


By:
666 66
Add to favourites
2
China
Breakfast
50 min
4
Main ingredient
Ingredients
Vegetarian/vegan info
Description
Trivia
Return to recipes


Whitefoot the Woodmouse
by Thornton W. Burgess
"Mr. and Mrs. Whitefoot"
Additional Information
- Year Published: 1922
- Language: English
- Country of Origin: United States of America
- Source: Burgess T. W. (1922). Whitefoot the Woodmouse Boston: Little, Brown & Co..
-
Readability:
- Flesch–Kincaid Level: 4.5
- Word Count: 663
- Genre: Fantasy
- Keywords: 20th century literature, american literature, life lessons, nature
- ✎ Cite This
Downloads
When all is said and all is done
‘Tis only love of two makes one.
—Whitefoot.
Little Miss Dainty, the most beautiful and wonderful Woodmouse in all the Great World, according to Whitefoot, was very shy and very timid. It took Whitefoot a long time to make her believe that he really couldn’t live without her. At least, she pretended not to believe it. If the truth were known, little Miss Dainty felt just the same way about Whitefoot. But Whitefoot didn’t know this, and I am afraid she teased him a great deal before she told him that she loved him just as he loved her.
But at last little Miss Dainty shyly admitted that she loved Whitefoot just as much as he loved her and was willing to become Mrs. Whitefoot. Secretly she thought Whitefoot the most wonderful Woodmouse in the Great World, but she didn’t tell him so. The truth is, she made him feel as if she were doing him a great favor.
As for Whitefoot, he was so happy that he actually tried to sing. Yes, sir, Whitefoot tried to sing, and he really did very well for a Mouse. He was ready and eager to do anything that Mrs. Whitefoot wanted to do.  Whitefoot forgot that he had ever been sad and lonely. He raced about and did all sorts of funny things from pure joy, but he never once forgot to watch out for danger. In fact he was more watchful than ever, for now he was watching for Mrs. Whitefoot as well as for himself.
At last Whitefoot rather timidly suggested that they should go see his fine home in a certain hollow stub. Mrs. Whitefoot insisted that they should go to her home. Whitefoot agreed on condition that she would afterwards visit his home. So together they went back to Mrs. Whitefoot’s home. Whitefoot pretended that he liked it very much, but in his heart he thought his own home was very much better, and he felt quite sure that Mrs. Whitefoot would agree with him once she had seen it.
But Mrs. Whitefoot was very well satisfied with her old home and not at all anxious to leave it. It was in an old hollow stump close to the ground. It was just such a place as Shadow the Weasel would be sure to visit should he happen along that way. It didn’t seem at all safe to Whitefoot. In fact it worried him. Then, too, it was not in such a pleasant place as was his own home. Of course he didn’t say this, but pretended to admire everything.
Two days and nights they spent there. Then Whitefoot suggested that they should visit his home. “Of course, my dear, we will not have to live there unless you want to, but I want you to see it,” said he.
Mrs. Whitefoot didn’t appear at all anxious to go. She began to make excuses for staying right where they were. You see, she had a great love for that old home. They were sitting just outside the doorway talking about the matter when Whitefoot caught a glimpse of a swiftly moving form not far off. It was Shadow the Weasel. Neither of them breathed. Shadow passed without looking in their direction. When he was out of sight, Mrs. Whitefoot shivered.
“Let’s go over to your home right away,” she whispered. “I’ve never seen Shadow about here before, but now that he has been here once, he may come again.”
“We’ll start at once,” replied Whitefoot, and for once he was glad that Shadow the Weasel was about.


Forest Jam
beta
Forest Jam
beta
Start a party!
Join the Party!
Or use
URL address
Tweet
Created by
Yonatan
,
Krista
and Alvaro with the power of node.js and WebSockets.


{% block meta_description %} {% endblock %} {% set stats = h.get_site_statistics() %}
Tiers of government refer to distinct levels of government set up for a particular country. In India, there are three tiers of government: Union, State and Local, the latter being either urban or rural.
The portal includes twelve broad sectors as organised below. These sectors represent Union and State Budget expenditure on both Economic Services and Social Services.


Mystery Bowl
Yeah, I don't really know where this came from. Speculation tells me the bowl is some sort of experiment used to examine interference patterns of light on itself, plus a random DI water squirter.
Carbonation
A shot through a mango Italian soda.
Honolulu
Taken from my condo in Oahu, HI.
Moon Shot (missing name)
iPhone through a telescope capturing a special feature of a rarely seen rille.


Trains
Train Info
Train Name
Destination
Frequency
Next Arrival
Minutes Away
Add Trains
Train Name:
Destination:
First Train Time (military time)
Frequency (mins)
Submit


Game Info
Each running game will need to track which board it's using, and the current state of all players.
I anticipate that we'll have a node app running the server, which will also serve up the client HTML5 app as static content.
Communication will likely be done via websockets. I would establish a channel for the game browser, and a separate channel for each game.
Boards
- Multiple boards must be available
- Each board should provide images for rendering
- The board should have a record of all spaces
- Each space should reference the other spaces accessible from that space.
- accessible space references should be referred to as in, forward, and out. This will be used to ensure that available moves comply with lane traversal rules.
- Corner spaces will be flagged so that it can be determined whether a player finished a turn in a corner
- Pit stop spaces will also be specially marked so the system can determine if repairs should be made
- The board will also have a record of each corner, which will include the shortest and longest path counts for the corner and the number of stops required in that corner.
Players
- Each player will choose a unique car
- Each player record will track the current gear and damage
- Advanced games will track damage per vehicle component
- if any damage category reaches maximum, the player loses.
Vehicles
- Vehicles will provide images for display
- Each vehicle will allow 20 combined damage points for basic play
- For advanced play, vehicles may distribute 40 damage points as the player chooses across the following categories:
- Engine (default: 6 DP)
- Transmission (default: 6 DP)
- Tires (default: 10 DP)
- Brakes (default: 6 DP)
- Suspension (default: 6 DP)
- Body (default: 6 DP)
Taking damage
This is a summary of the cases where damage may be taken, for each component of the vehicle.
When playing with basic rules, all damage is applied to the overall vehicle damage points
- Engine
- ALL players in 5th or 6th gear have a 20% chance of damage (determined individually) if ANY PLAYER rolls 20 spaces in 5th gear or 30 spaces in 6th gear.
- The space where damage is taken becomes dangerous.
- Losing all DP results in elimination
- Transmission
- N-1 damage is taken for down shifting by N gears.
- Tires
- Up to 3 damage for braking
- 1 DP for each space on overshooting a corner
- Brakes
- Up to 3 damage for braking
- Suspension
- 5% chance of damage on passing over or landing on a dangerous space.
- Losing all suspension DP results in elimination
- Body
- Players have a 20% chance of damage when immediately adjacent to another vehicle at the end of movement for either vehicle.
This damage will be applied prior to the slipstream rule, if applicable. This rule should be applied for each adjacent vehicle.
- The space where damage is taken becomes dangerous.
- Losing all body DP results in elimination
Gameplay
- Players will take turns moving their vehicles
- The vehicle in the lead will move first, while the vehicle trailing will move last.
- Inside track spaces will be considered ahead of spaces farther out.
- For each turn, the player must select the gear they wish to use
- Players may shift up by one gear.
- Players may shift down by one gear without taking damage
- If a player down shifts by N gears, they will take N-1 damage points.
- In advanced play, damage is applied to the transmission.
- If a player has no damage points available, they cannot shift down by more than one gear
- After selecting a gear, the system will randomly select the number of movement points for the player on this turn. The distribution of the random numbers will depend
on the random implementation used, and is not guaranteed.
- 1st gear: 1-2 movement points
- 2nd gear: 2-4 movement points
- 3rd gear: 4-8 movement points
- 4th gear: 7-12 movement points
- 5th gear: 11-20 movement points
- 6th gear: 19-30 movement points
- Once the number of movement points has been determined, the player will be presented with a choice of which space to move to.
- Players may elect to use up to 6 damage points to reduce the distance traveled
- Decrease spaces to move (not necessarily movement points, see Hills below) by 1 for each DP taken.
- For advanced play: the first three DP apply to brakes, the second three DP apply to tires.
- Braking by 7+ spaces will destroy the vehicle, regardless of available DP
- If insufficient DP are available, the car is destroyed.
- Players cannot drive through other vehicles. They must drive around them or brake to avoid hitting them.
- If the road is blocked by other vehicles, players must brake.
- When driving through a straight, players may only traverse lanes in one direction.
- Weaving back and forth is not permitted.
- Players may move over one lane, then immediately back to pass another vehicle.
- Two-way lane traversal in corners is permitted as long as the movement follows the allowed movements for the corner space.
- This will require that we track what lanes a car has been in (except when passing) for each straight
- Each corner has a number indicating how many times a player must finish moving while in that corner.
- Overshooting the corner on the final stop results in damage to tires.
- Overshooting the corner prior to the final stop destroys the car.
- If a vehicle loses all tire DP from overshooting, the car spins out - place it backwards on the space.
- On the next turn, return the car to the forward direction, and start driving in 1st gear.
- If all tire DP are gone, overshooting by 1 causes the car to spin out. (see above)
- Overshooting by more than the available tire DP destroys the car.
- Any time a car is destroyed, the space where the movement ended is marked as dangerous.
- For advanced play, if a player ends a move immediately behind another vehicle, and both vehicles are in 4th gear or higher, the player in the rear
is in the slipstream of player in front, and may optionally move three additional spaces.
- Players may use braking to reduce the number of spaces moved.
- Normal movement rules apply.
- If the movement from slipstream rules results in ending immediately behind another player in 4th gear or higher, the slipstream rule is applied again.
Hills
higher gears require more movement points to traverse (1 pt for 1st and 2nd, 2pt for 3rd and 4th, 3pt for 5th and 6th)
Pit Stops
- Players must have movement points equal to or higher than the distance to the pit to make use of a pit stop.
- Excess movement points are discarded with no penalty
- All tire damage is repaired.
- On the turn after the pit stop: 50/50 chance of a quick stop or a slow stop.
- For a quick pit stop
- Leave the pit in 4th gear
-
- Even chances of moving between 1 and 5 spaces when exiting (replaces normal movement)
- For a slow pit stop
- Skip one turn
- Leave the pit in 4th gear or lower (normal movement applies)


View Highscores
Code Quiz
There are 9 questions in total. Each worth 10 points. There are 60 seconds total. Quiz ends when all questions are answered, or timer reaches 0.
Start


Contents
Short Descriptions
|
is an utility used to set adapter properties. |
|
|
is a tray applet used to manage bluetooth. |
|
|
is an application used for configuring and pairing bluetooth devices. |
|
|
is used to start obex browser for specified device. |
|
|
is the bluetooth device manager. |
|
|
is an application used for sending files to bluetooth devices. |
|
|
is a graphical dialog used for configuring local bluetooth services. |


Regex cheatsheet
Many programs use regular expression to find & replace text. However, they tend to come with their own different flavor.
You can probably expect most modern software and programming languages to be using some variation of the Perl flavor, "PCRE"; however command-line tools (grep, less, ...) will often use the POSIX flavor (sometimes with an extended variant, e.g. egrep
or sed -r
). ViM also comes with its own syntax (a superset of what Vi accepts).
This cheatsheet lists the respective syntax of each flavor, and the software that uses it.
If you spot errors or missing data, or just want to make this prettier/more accurate, don't hesitate to open an issue or a pull request.
Syntax
| What | Perl/PCRE | Python's re | POSIX (BRE) | POSIX extended (ERE) | ViM |
|---|---|---|---|---|---|
| Basics | |||||
| Custom character class | [...] | [...] | [...] | [...] | [...] |
| Negated custom character class | [^...] | [^...] | [^...] | [^...] | [^...] |
| \ special in class? | yes | yes | no, ] escaped if comes first | ||
| Ranges | [a-z] , - escaped if comes last | [a-z] , - escaped if first or last | [a-z] , - escaped if comes last | [a-z] | |
| Alternation | | | | | \| | | | \| \& (low precedence) |
| Escaped character | \033 \x1B \x{1234} \N{name} \N{U+263D} | \x12 | \%d123 \%x2A \%u1234 \%U1234ABCD | ||
| Character classes | |||||
| Any character (except newline) | . | . | . | . | . |
| Any character (including newline) | \_. | ||||
Match a "word" character (alphanumeric plus _ ) | \w [[:word:]] | \w | \w | \w | \w |
| Case | [[:upper:]] / [[:lower:]] | [[:upper:]] / [[:lower:]] | [[:upper:]] / [[:lower:]] | \u [[:upper:]] / \l [[:lower:]] | |
| Match a non-"word" character | \W | \W | \W | ||
| Match a whitespace character (except newline) | \s [[:space:]] | \s [[:space:]] | \s [[:space:]] | ||
| Whitespace including newline | \s [[:space:]] | \s | \_s | ||
| Match a non-whitespace character | \S | \S | [^[:space:]] | [^[:space:]] | \S [^[:space:]] |
| Match a digit character | \d [[:digit:]] | \d | [[:digit:]] | [[:digit:]] | \d [[:digit:]] |
| Match a non-digit character | \D | \D | [^[:digit:]] | [^[:digit:]] | \D [^[:digit:]] |
| Any hexadecimal digit | [[:xdigit:]] | [[:xdigit:]] | [[:xdigit:]] | \x [[:xdigit:]] | |
| Any octal digit | \o | ||||
| Any graphical character excluding "word" characters | [[:punct:]] | [[:punct:]] | [[:punct:]] | [[:punct:]] | |
| Any alphabetical character | [[:alpha:]] | [[:alpha:]] | [[:alpha:]] | \a [[:alpha:]] | |
| Non-alphabetical character | [^[:alpha:]] | [^[:alpha:]] | \A [^[:alpha:]] | ||
| Any alphanumerical character | [[:alnum:]] | [[:alnum:]] | [[:alnum:]] | [[:alnum:]] | |
| ASCII | [[:ascii:]] | ||||
| Character equivalents (e = é = è) (as per locale) | [[=e=]] | [[=e=]] | [[=e=]] | ||
| Zero-width assertions | |||||
| Word boundary | \b | \b | \b | \b | \< / \> |
| Anywhere but word boundary | \B | \B | \B | \B | |
| Beginning of line/string | ^ / \A | ^ / \A | ^ | ^ | ^ (beginning of pattern ) \_^ |
| End of line/string | $ / \Z | $ / \Z | $ | $ | $ (end of pattern) \_$ |
| Captures and groups | |||||
| Capturing group | (...) (?<name>...) | (...) (?P<name>...) | \(...\) | (...) | \(...\) |
| Non-capturing group | (?:...) | (?:...) | \%(...\) | ||
| Backreference to a specific group. | \1 \g1 \g{-1} | \1 | \1 | \1 non-official | \1 |
| Named backreference | \g{name} \k<name> | (?P=name) | |||
| Look-around | |||||
| Positive look-ahead | (?=...) | (?=...) | \(...\)\@= | ||
| Negative look-ahead | (?!...) | (?!...) | \(...\)\@! | ||
| Positive look-behind | (?<=...) | (?<=...) | \(...\)\@<= | ||
| Negative look-behind | (?<!...) | (?<!...) | \(...\)\@<! | ||
| Multiplicity | |||||
| 0 or 1 | ? | ? | \? | ? | \? |
| 0 or more | * | * | * | * | * |
| 1 or more | + | + | \+ | + | \+ |
| Specific number | {n} {n,m} {n,} | {n} {n,m} {n,} | \{n\} \{n,m\} \{n,\} | {n} {n,m} {n,} | \{n} \{n,m} \{n,} |
| 0 or 1, non-greedy | ?+ | ?? | |||
| 0 or more, non-greedy | *+ | *? | \{-} | ||
| 1 or more, non-greedy | ++ | +? | |||
| Specific number, non-greedy | {n,m}+ {n,}+ | {n,m}? {n,}? | \{-n,m} \{-n,} | ||
| 0 or 1, don't give back on backtrack | ?+ | ||||
| 0 or more, don't give back on backtrack | *+ | ||||
| 1 or more, don't give back on backtrack | ++ | ||||
| Specific number, don't give back on backtrack | {n,m}+ {n,}? | ||||
| Other | |||||
| Independent non-backtracking pattern | (?>...) | \(...\)\@> | |||
| Make case-sensitive/insensitive | (?i) / (?-i) | (?i) / (?-i) | \c / \C |
Programs
| What | Syntax | Comments/gotchas |
|---|---|---|
| Programming languages | ||
| Perl | PCRE | PCRE is actually a separate implementation from Perl's, with slight differences |
Python's re standard lib | Python's own syntax (Perl-inspired) | |
| Ruby | Ruby's own syntax (Perl-inspired) | |
| Java's java.util.regex | Almost PCRE | |
| Boost.Regex | PCRE | |
| Text editors | ||
| Eclipse | PCRE | |
| Emacs | ? | |
| Netbeans | PCRE | |
| Notepad++ | PCRE (Boost.Regex) | |
| PyCharm | PCRE | Perl-inspired |
| Sublime Text | ? | |
| UltraEdit | PCRE | |
| ViM | ViM | |
| Command-line tools | ||
| awk | ERE | might depend on the implementation |
| grep | BRE, egrep for ERE, grep -P for PCRE (optional) | |
| less | ERE | usually; man page says "regular expression library supplied by your system" |
| screen | plain text | |
| sed | BRE, -E switches to ERE |


Computational utility functions.
This module defines a number of low-level, numerical, high-performance
utility functions like rmsd for example.
|
(n,3) numpy.array
|
|
|
tuple
|
bfit(X,
Y,
n_iter=10,
distribution=' student ' ,
em=False,
full_output=False)
Robust superposition of two coordinate arrays. |
source code
|
|
|
(d,) numpy.array
|
|
|
numpy array
|
deg(x)
Convert an array of torsion angles in radians to torsion degrees
ranging from -180 to 180. |
source code
|
|
|
(m,) numpy.array
|
|
|
numpy array
|
|
|
(m,) numpy.array
|
|
|
iterable
|
|
|
tuple
|
fit(X,
Y)
Return the translation vector and the rotation matrix minimizing the
RMSD between two sets of d-dimensional vectors, i.e. |
source code
|
|
|
(n,3) numpy.array
|
|
|
tuple
|
fit_wellordered(X,
Y,
n_iter=None,
n_stdv=2,
tol_rmsd=0.5,
tol_stdv=0.05,
full_output=False)
Match two arrays onto each other by iteratively throwing out highly
deviating entries. |
source code
|
|
|
(d,d) numpy.array
|
|
|
bool
|
|
|
tuple
|
|
|
numpy array
|
rad(x)
Convert an array of torsion angles in torsion degrees to radians. |
source code
|
|
|
(d,) numpy.array
|
|
|
float
|
rmsd(X,
Y)
Calculate the root mean squared deviation (RMSD) using Kabsch'
formula. |
source code
|
|
|
float
|
rmsd_cur(X,
Y)
Calculate the RMSD of two conformations as they are (no fitting is
done). |
source code
|
|
|
tuple
|
scale_and_fit(X,
Y,
check_mirror_image=False)
Return the translation vector, the rotation matrix and a global
scaling factor minimizing the RMSD between two sets of d-dimensional
vectors, i.e. |
source code
|
|
|
(d,d) numpy.array
|
|
|
float
|
tm_score(x,
y,
L=None,
d0=None)
Evaluate the TM-score of two conformations as they are (no fitting is
done). |
source code
|
|
|
tuple
|
tm_superimpose(x,
y,
fit_method=<function fit at 0x7fe0c56e4c08>,
L=None,
d0=None,
L_ini_min=4,
iL_step=1)
Compute the TM-score of two protein coordinate vector sets. |
source code
|
|
|
float
|
|
|
numpy.array
|
|
|
tuple
|
wfit(X,
Y,
w)
Return the translation vector and the rotation matrix minimizing the
weighted RMSD between two sets of d-dimensional vectors, i.e. |
source code
|
|
|
float
|
wrmsd(X,
Y,
w)
Calculate the weighted root mean squared deviation (wRMSD) using
Kabsch' formula. |
source code
|
|
|
tuple
|
xfit(X,
Y,
n_iter=10,
seed=False,
full_output=False)
Maximum likelihood superposition of two coordinate arrays. |
source code
|
|


My Movies
Pick a Movie
Last Ship
Nikita
Game of Thrones
Titanic
Power
Arrow
American Soldier
Jungle Book
Movies
Second Run
Frist Run
Movie Times
11am
noon
1pm
2pm
3pm
4pm
5pm
6pm
7pm
8pm
Select your age
Under 18
Youth
Adult 40+
Ticket price:
Ksh.


@(message: String) @main("ScalaUserGroup.org") {
Our first meeting is scheduled for Saturday, December 13, 9:00 AM to 10:30 AM on Google Hangouts. The point of this meeting is to get to know one another, discuss our interest in Scala and what we hope to gain out of the group.
Here are some things we might discuss. Please feel free to add more either using our mailing list or by forking this page and sending a pull request. Meantime if nothing on this list appeals to you, remember this list is just my first attempt at an agenda and we can certainly discuss other ideas when we meet.


Does your child have five or more flat light brown birthmarks (each more than three quarters of an inch or 1.5 centimeters in diameter)? If so, they should be examined by an expert to exclude neurofibromatosis, an inheritable condition that may be associated with learning disabilities, epilepsy, and a high risk of malignant tumors.
Neurofibromatosis is an inherited condition that occurs in 1 child per 2,500. It is very variable in its manifestations. A child who has one or more of the following should be assessed by an expert:
- Five or more “café au lait” spots (light brown, flat moles) on the skin (each measuring over 1.5 centimeters or three quarters of an inch in diameter). They are most commonly found on the trunk of the body, and are usually not present at birth but appear in the first two decades of life.
- Freckling in the armpits and/or groin
- Plexiform neurofibroma, a lumpy overgrowth of parts of peripheral nerves, most common on the jaw and eyelids
- Fibromas, or small, pink, non-painful lumpy growths on the skin that do not occur until puberty
- Speckling on the iris of the eyes
- Scoliosis or bowing of the legs
Adults may have neurofibromatosis but be unaware of it. Affected children may experience neurological problems during infancy, such as epilepsy, attention deficit disorder, and mental retardation. Those affected are at a high risk of developing tumors of the optic nerve (the nerve to the eye), the main nerve to the ear, and the brain. A precise diagnosis is especially important, since the family should seek genetic consulting.


Basic example
Here is a basic example of a JSON Schema:
{ "title": "Example Schema", "type": "object", "properties": { "firstName": { "type": "string" }, "lastName": { "type": "string" }, "age": { "description": "Age in years", "type": "integer", "minimum": 0 } }, "required": ["firstName", "lastName"] }
Walkthroughs
The two examples below are step-by-step guides into building a schema:
- a simple example which covers a classical product catalog description.
- a more advanced example, using JSON Schema to describe filesystem entries in a Unix-like /etc/fstab file.
The Space Telescope Science Institute has also published an guide aimed at schema authors.


@import models.Address @(address : Address, blockId : String) @address.line1<EMAIL_ADDRESS>{item =><EMAIL_ADDRESS>{item =><EMAIL_ADDRESS>{item =><EMAIL_ADDRESS>{item =>, @item}


---
layout: post
title: Battleships!
alias: /battleships
published: true
---
Hi Everybody,
Thanks to all who came a long and participated last night, it was a great night and we had some really good battles!
Overall, Matthew Robinson was the victor! Matthew Bennett came in second and I finished third. All the entries are on Github, and hopefully will be pulled into the main repository:
https://github.com/MrJaba/battleshipThanks again to everyone for making it such a fun evening.


Module: Qo::Helpers
- Included in:
- Qo
- Defined in:
- lib/qo/helpers.rb
Instance Method Summary collapse
-
#count_by(targets, &fn) ⇒ Hash[Any, Integer]
Counts by a function.
-
#dig(path_map, expected_value) ⇒ Proc
A curried variant of Hash#dig meant to be passed as a matcher util.
Instance Method Details
#count_by(targets, &fn) ⇒ Hash[Any, Integer]
Counts by a function. This is entirely because I hackney this everywhere in pry anyways, so I want a function to do it for me already.
29 30 31 32 33 34 35 |
# File 'lib/qo/helpers.rb', line 29 def count_by(targets, &fn) fn ||= -> v { v } targets.each_with_object(Hash.new(0)) { |target, counts| counts[fn[target]] += 1 } end |
#dig(path_map, expected_value) ⇒ Proc
Note:
This method will attempt to coerce path segments to Symbols if unsuccessful in first dig.
A curried variant of Hash#dig meant to be passed as a matcher util.
13 14 15 16 17 18 19 20 |
# File 'lib/qo/helpers.rb', line 13 def dig(path_map, expected_value) Proc.new { |hash| segments = path_map.split('.') expected_value === hash.dig(*segments) || expected_value === hash.dig(*segments.map(&:to_sym)) } end |


--- layout: post title: I'm a knittin' me a hat, in Summer? date: 2011-01-02 02:33:17.000000000 -05:00 categories: - Books - Knitting tags: - Boutique Knits - Hat - Knitting status: publish type: post published: true meta: aktt_notify_twitter: 'no' _edit_last: '1' _wp_old_slug: '' dsq_thread_id: '1188031717' author: login: cint email<EMAIL_ADDRESS>display_name: Jacinta first_name: Jacinta last_name: '' ---
Well this week started out quite cool. In fact we lit the fire twice. Nothing like a fire to add to the ambiance of the festive season. I decided to get my knitting out, because wood fires provoke that in me, and re-cast a hat that I had frogged a while back. It isn't a complicated pattern, it's just I, in all my wisdom, took it (the first version) along to a craft night held with a group of friends. That was a big mistake, as I got talking and stuffed up my knitting. I am quite the multi tasker, but not when it comes to knitting. Now I should know this, but every now and again, my ego gets the better of me and I feel the need to knit in company. Perhaps, if I did make New Year resolutions, at the top of my list would be:
Don't try and talk while knitting, or knit while talking, hmm, we'll see how long it takes me to try that out again (probably not all that long).
Anyway, the hat. It is called Sideways Grande Hat. I am using Moda Vera Mousse yarn which is 70% wool, 30% soya. It's lovely and soft. The colour I would describe as petrol or perhaps peacock blue. The pattern is from a book called Boutique Knits by Laura Irwin. I love this book (a gift from a dear friend) and can see myself knitting quite a few of the patterns. I'm lovin' the hat on the front cover (Side Slip Cloche). It will be the next thing to cast on after I have finished the Sideways Grande.
Please feel free to link your latest knitting project. I always love to see what other people are knitting.


HTML: The Specifics
Jump to there
This h1 heading is going to be the same size as h2
Semantic Elements
Semantic tags define structure and express the meaning of content. Semantic elements include header, footer, article, nav, etc. Non-semantic tags are tags that don't particularly describe its role in its document. Such tags include div or span.
Headings
In HTML, there are 6 levels of heading tags to display titles with varying weights. They look like the following
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
Head vs Header vs Heading
This is a common html interview question that gets asked often. Know the difference between the three!
Block vs Inline elements
Block elements, such as
div
, takes up 100% width of its parent element
Where as, inline elements such as span, only takes up as much space as the content needs.
This is also a common qc/interview question
Styling with HTML
While not recommended, there are certain amount of stylings you can accomplish with html tags
b tags make things bold and i tags italicize the content
You can also make the text small
s tags strikes through content and u tags underline
Note: Not only are these not the best practices, if you use these tags, you are at the mercy of each browser engine to determine how these tags look. You really don't want that. Just think Internet Explorer.
Lists
There are two types of lists: Ordered List and Unordered List
- Ordered Lists (ol) have enumerators
- Inside Each List Element
- There exists list items, li for short
- This is Unordered List (ul)
- It doesn't have numbers
- You can also change their bullets through css
- Or remove them entirely!
Anchor tags
They are the backbone of interwebs
Highly useful tags that you can link internal or external webpages
Use href attribute to define their destination
And target attributes to avoid the most annoying phenomenon of hyperlinks (opening in the same browser tab)
This link opens Google in a new tab, like a civilized person
You can even use the id attribute to create anchor tags that jumps to different parts of a document.
Go To Top
Table
| Name |
Species |
Favorite Activity |
| Auryn |
Cat |
Eating |
Napping |
Sun bathing |
| Snow |
Napping |
Petting |


West Lothian Dyslexia Support Group delighted to welcome acclaimed author
Elizabeth Wein will speak at the group's next meeting in Linlithgow
by Debbie Hall, https://www.dailyrecord.co.uk/authors/debbie-hall/The West Lothian branch of Dyslexia Scotland are delighted to welcome acclaimed author Elizabeth Wein to their next meeting.
Elizabeth will speak to the branch at Linlithgow Burgh Halls on Wednesday, November 20 from 6.30pm to 8pm.
Elizabeth has written many novels for children and young people, including two dyslexia-friendly books published by Barrington Stoke.
As well as being an author, Elizabeth is a keen pilot and flying often features in her writing.
This free event is aimed at young people aged between 10 and 14 but everyone is welcome to come along. There will also be a prize draw to give away some dyslexia friendly books.
A spokesperson for the group said: “Dyslexia Scotland aims to empower people with dyslexia to reach their full potential. Dyslexia Scotland West Lothian is your local branch, run entirely by volunteers.
“This event is part of Book Week Scotland celebrations and is funded by the Scottish Book Trust – the national charity changing lives through reading and writing.
“Working with a wide range of partners, the trust will deliver events and activities across the country during Book Week Scotland 2019, which runs from November 18 to 24 November, linked to this year’s theme of conversation.
“Now in its eighth year, Book Week Scotland was initiated by the Scottish Government and is funded annually by Creative Scotland. Hundreds of free events happen during Book Week Scotland across every region, including every Scottish Library service with the support of Scottish Library and Information Council (SLIC).”
You can book a ticket at dswestlothian@gmail.com.


Travel Log
Place (location)
Time of Year
Landmarks
Add Landmark
Add Place
Locality:
Time Period:
Landmark(s):


1 Nupur Goenka
Co-Founder
2 Nupur Goenka
Co-Founder
3 Nupur Goenka
Co-Founder
4 Nupur Goenka
Co-Founder
5 Nupur Goenka
Co-Founder
6 Nupur Goenka
Co-Founder


I'm a student at Instituto Tecnológico de Costa Rica and actually I'm also a Freelancer in my free time. Currently I live in Aguas Zarcas, San Carlos. I really love Web Development and my favorite Framework is Angular. One of my favorites hobbies is exercising and watching Tv Shows on Netflix.
I've already worked in important projects like
Sistema de Gestión de Averías del Acueducto de la Municipalidad de San Carlos
wich was developed in Android from June 2017 to June 2018.
I've taught Web Development Courses in Angular and HTML5 to Instituto Tecnológico de Costa Rica students. In addition I've made serveral conferences to students and people in San Carlos. If you want to know more about me, please checkout out my TimeLine.
{{t.name}}


Code listing for: ZRA12_02TOP
Description: Include ZRA12_02TOP
*&---------------------------------------------------------------------*
*& Include ZRA12_02TOP - Report ZRA12_02
*&---------------------------------------------------------------------*
REPORT zra12_02 MESSAGE-ID k5. " MESSAGE-ID : ### ### ## ##
**********************************************************************
* Tables
**********************************************************************
TABLES : scarr, sflight, scustom.
**********************************************************************
* Internal tables and Work area
**********************************************************************
DATA : BEGIN OF gs_sflight,
seatsocc TYPE sflight-seatsocc,
carrid TYPE sflight-carrid,
connid TYPE spfli-connid,
price TYPE sflight-price,
seatsmax TYPE sflight-seatsmax,
planetype TYPE sflight-planetype,
fldate TYPE sflight-fldate,
END OF gs_sflight.
DATA : gt_scarr TYPE TABLE OF scarr,
gt_sflight LIKE TABLE OF gs_sflight.
* Practice 1
DATA : BEGIN OF gty_s_flightocc,
connid TYPE sflight-connid,
seatsocc TYPE sflight-seatsocc,
fldate TYPE sflight-fldate,
END OF gty_s_flightocc.
DATA gt_flightocc LIKE TABLE OF gty_s_flightocc.
DATA : BEGIN OF gty_s_flight,
carrid TYPE sflight-carrid,
connid TYPE sflight-connid,
END OF gty_s_flight.
DATA gt_flight LIKE TABLE OF gty_s_flight.
* Inclass Practice
DATA : BEGIN OF gs_custom,
region TYPE scustom-region,
telephone TYPE scustom-telephone,
postcode TYPE scustom-postcode,
END OF gs_custom.
DATA gt_custom LIKE TABLE OF gs_custom.
DATA : BEGIN OF gs_conn,
carrid TYPE scarr-carrid,
connid TYPE spfli-connid,
carrname TYPE scarr-carrname,
cityfrom TYPE spfli-cityfrom,
cityto TYPE spfli-cityto,
url TYPE scarr-url,
END OF gs_conn.
* Assignment 10-22
DATA : BEGIN OF gs_booking,
carrid TYPE sflight-carrid,
connid TYPE sflight-connid,
fldate TYPE sflight-fldate,
bookid TYPE sbook-bookid,
* price TYPE sflight-price,
* seatsmax TYPE sflight-seatsmax,
* seatocc TYPE sflight-seatsocc,
smoker TYPE sbook-smoker,
class TYPE sbook-class,
END OF gs_booking.
DATA : gt_booking LIKE TABLE OF gs_booking,
gt_conn LIKE TABLE OF gs_conn.
Extracted by Direct Download Enterprise version 1.3.1 - E.G.Mellodew. 1998-2005 UK. Sap Release 751


Help
Confused? Problems? Try this.
- Help with Ox
If you are not familiar with Ox syntax and the Ox help and documentation pages, then you will struggle with using niqlow.
- Help with Dynamic Programming
- Help with Optimization
- Help with MPI and Parallel Execution
- Finding help with niqlow
- Templates and Examples
- The Hierarchy Tree
- In the upper right hand corner of documentation pages is the hierarchy link. This shows all the classes defined in that part of niqlow (DDP, FiveO, etc).
So if you wonder if a kind of state variable or method or optimization algorithm has already been defined look in the hierarchy.
- The Templates Directory has some files that can be used to get started
- Try making a copy of the
.h
and .ox
files for one of the Examples and modify it to try to do other things
- Ask the author!