text:
'use strict';

/* Controllers */

angular.module('coreBOSJSTickets.controllers', [])
.controller('navigationCtrl',function($scope, $rootScope, Setup, $i18next, $window, $location,coreBOSWSAPI) {
	$scope.appname = Setup.app;
	$scope.messageurl = "http://corebos.org";
	$scope.messagetxt = "Data provided by coreBOS. © 2014";
	$(window).bind('resize', function() {
		if ($window.innerWidth < 768 || $location.path() == '/login') {
			$scope.menuShow = false;
			$rootScope.menuShow = false;
		} else {
			$scope.menuShow = true;
			$rootScope.menuShow = true;
		}
		$scope.$apply();
	});
        coreBOSWSAPI.doListTypes().then(function(response) {
		$scope.listtypes = response.data.result;
		var ltypes = coreBOSWSAPI.processListTypes(response.data.result.information, false, true);
		$scope.selecttypes = ltypes;
                //$scope.selecttypes.push({name:'Accounts',label:'Aziende'});
	});

//        var option = {
//                  ns: 'translation',
//                  resGetPath: 'locales/it/translation.json?lng=en&ns=translation',
//                  //resGetPath: '/CID/webservice.php?module=Campaigns&operation=getlanguagefile&sessionName='+coreBOSAPIStatus.getSessionInfo()._sessionid+'&lng=en&ns=translation',
//                  dynamicLoad: true
//                };
//        i18n.init(option);

	if($location.path() == '/login')
		$scope.menuShow = false;
	else
		$scope.menuShow = true;
//        coreBOSWSAPI.doQuery('select * from PHBManager' ).then(function(response) {
//			$scope.result = response.data.result[0];
//                        less.modifyVars({
//                              '@color': $scope.result.menu_color
//        });
//		});
	$scope.toggleMenu = function() {
		$scope.menuShow = !$scope.menuShow;
		$rootScope.menuShow = !$rootScope.menuShow;
	};
	$rootScope.$watch("menuShow", function(newval, oldval){
		$scope.menuShow = $rootScope.menuShow;
	});

	$scope.isActive = function (viewLocation) {
		var active = (viewLocation === $location.path());
		return active;
	};
})
.controller('navtop',function($scope, $rootScope, Setup, $i18next, $window, $location,coreBOSWSAPI) {
	 coreBOSWSAPI.userInfo().then(function(response) {
                $scope.url=Setup.corebosapi;
		$scope.user_data = response.data.result;
		$scope.user_firstname = $scope.user_data.first_name;
                $scope.user_lastname = $scope.user_data.last_name;
                $scope.user_image = $scope.user_data.imagename;
	});

    })
.controller('logoutCtrl',function($scope, $location, coreBOSAPIStatus) {
	// delete cookies or storage variables here
	coreBOSAPIStatus.setInvalidKeys(true);
	coreBOSAPIStatus.setSessionInfo({});
	$location.path('/login');
})
.controller('termscCtrl',function($scope) {
})
.controller('loginCtrl',function($scope, $rootScope, $i18next, $filter, Setup, coreBOSWSAPI, coreBOSAPIStatus,$location) {
//	$scope.username='paziente';
//        $scope.password='juKaW2jesSfBhgHM';
        if (!coreBOSAPIStatus.hasInvalidKeys()) {
		$location.path('/currentorder');
	}
	else
	{
		$rootScope.menuShow = false;
		$scope.langs = [ {
			name : i18n.t('English'),
			code : 'en'
		}, {
			name : i18n.t('Spanish'),
			code : 'es'
		}];
		$scope.changeLanguage = function (lng) {
			i18n.setLng('en', function(t) {
				$scope.langs = [ {
					name : t('English'),
					code : 'en'
				}, {
					name : t('Spanish'),
					code : 'es'
				}];
				$i18next.options.lng='en';
			});
		};
		var found = $filter('getArrayElementById')($scope.langs, $i18next.options.lng, 'code');
		if (found!=null) {
			$scope.currentLang = found;
		} else {
			$scope.currentLang = $scope.langs[0];
		}
		coreBOSWSAPI.setURL(Setup.corebosapi,false);
		$scope.$watch("username", function(newval, oldval){
			coreBOSWSAPI.setcoreBOSUser(newval,false);
		});
		$scope.$watch("password", function(newval, oldval){
			coreBOSWSAPI.setcoreBOSKey(newval,false);
		});
		$scope.login = function(){

			coreBOSWSAPI.doLoginPortal($scope.username,$scope.password).then(function(response) {

					coreBOSWSAPI.setConfigured();
					$rootScope.contactinfo = [{
						contactid : '',
						firstname : '',
						lastname  : '',
						accountid : '',
						email     : '',
					}];
					$location.path('/cid_module/Patients/Pazienti');
				},function(){

                                        coreBOSWSAPI.doLogin($scope.username,$scope.password).then(function() {
                                            coreBOSWSAPI.setConfigured();
                                            $location.path('/cid_module/Patients/Pazienti');
                                },function(){
                                                $scope.ErrorUserNotValid = true;
                                        });
			});
		};

		$scope.cbAPIConfigured = coreBOSWSAPI;
		$scope.cbAPIKeys = coreBOSAPIStatus;
	}
})
.controller('neworderCtrl',function($scope, $i18next, $filter, coreBOSWSAPI) {
	$scope.so = {};
	var dmin = new Date();
	dmin.setHours(6);
	dmin.setMinutes(0);
	var dmax = new Date();
	dmax.setHours(18);
	dmax.setMinutes(30);
	$scope.cities = [
	 "Fort Collins", "Loveland", "Greeley", "Windsor", "Ault", "Bellvue", "Berthoud", "Eaton",
	 "Evans", "Johnstown", "Laporte", "La Salle", "Loveland", "Longmont", "Milliken",
	 "Severence", "Timnath", "Wellington", "OTHER"
	];
	$scope.apartments = ["Apartment", "Condo", "Duplex", "SingleFamily", "Commercial"];
	$scope.yesno = ["Yes","No"];
	$scope.sqfeetoptions = ["250 - 500","500 - 1000","1000 - 1500","1500 - 2000","2000 - 2500","2500 - 3000","3000 - 3500","3500+"];
	$scope.condoptions = ["Unknown","Average","Heavily Soiled","Trashed"];
	$scope.petoptions = ["None","Unknown","Urine Smell","Other Foul Smell"];
	$scope.minDate = new Date();
	var mdate = new Date();
	mdate.setFullYear($scope.minDate.getFullYear()+1,$scope.minDate.getMonth(),$scope.minDate.getDate());
	$scope.maxDate = mdate;
	$scope.openworkdate = function($event) {
		$event.preventDefault();
		$event.stopPropagation();
		$scope.openedworkdate = true;
	};
	$scope.openduedate = function($event) {
		$event.preventDefault();
		$event.stopPropagation();
		$scope.openedduedate = true;
	};
	var ddefault = new Date();
	ddefault.setHours(8);
	ddefault.setMinutes(30);
	$scope.so.atime = ddefault;
	$scope.setMaxMinTime = function () {
		if ($scope.so.atime>dmax) {
			$scope.so.atime=dmax;
		}
		if ($scope.so.atime<dmin) {
			$scope.so.atime=dmin;
		}
	};
	$scope.ordersent = false;
	$scope.errorsending = false;
	$scope.doSendNewOrder = function() {
		$scope.so.account_id = '3x32528'; // FIXME
		$scope.so.cf_837 = $scope.so.account_id; // FIXME:: accountname
		$scope.so.sostatus = 'Pending';
		$scope.so.invoicestatus = 'Pending';
		$scope.so.ship_state = 'CO';
		$scope.so.bill_street = '*';
		$scope.so.purchaseorder = '0';
		$scope.so.cf_541 = $filter('date')($scope.so.atime,'HH:mm');
		$scope.so.duedate = $filter('date')($scope.so.ddate,'yyyy/MM/dd');
		$scope.so.cf_555 = $filter('date')($scope.so.cdate,'yyyy/MM/dd');
		// líneas de producto
		$scope.so.pdoInformation = [
			{productid:135,
			 comment:'',
			 qty:1,
			 listprice:0,
			 discount:0,  // 0 no discount, 1 discount
			 discount_type: 0,  //  amount/percentage
			 discount_percentage:0,  // not needed nor used if type is amount
			 discount_amount:0  // not needed nor used if type is percentage
		}];
		coreBOSWSAPI.doCreate('SalesOrder',$scope.so).then(function(response) {
			$scope.ordersent = true;
			$scope.comment = 'Your order for ' + $scope.so.address + ' has been submitted. Check the Open Orders list to watch for confirmation.';
		},function(response) {
			$scope.errorsending = true;
			$scope.errormsg = 'Your order for ' + $scope.so.address + ' could not be submitted correctly. Please try again and inform your contact in Smart Carpet Care for assistance.';
		});
	};
})
.controller('emailusCtrl',function($scope, $i18next, coreBOSWSAPI) {
	$scope.emailustext = '';
	$scope.emailsent = false;
	$scope.doSendEmail = function() {
		coreBOSWSAPI.doInvoke('scSendQuestion',{
			'question': $scope.emailustext,
			'entityid': ''  // FIXME
			},'POST').then(function(response) {
			$scope.emailsent = true;
		});
	};
})
.controller('referralCtrl',function($scope, $i18next, coreBOSWSAPI) {
	$scope.emailustext = '';
	$scope.emailsent = false;
	$scope.doSendReferralEmail = function() {
		var $message;
		$message = "The following referral has been submitted by TEST USER\n\n"; // FIXME: change TEST USER
		$message+= "Name: " + $scope.name + "\n";
		$message+= "Company: " + $scope.company + "\n";
		$message+= "Phone: " + $scope.phone + "\n\n";
		$message+= "Email: " + $scope.email + "\n";
		coreBOSWSAPI.doInvoke('scSendReferral',{
			'referral': $message,
			'entityid': ''  // FIXME
			},'POST').then(function(response) {
			$scope.emailsent = true;
			$scope.comment = i18n.t('okReferralComment', {refname: $scope.name});
		});
	};
})
.controller('currentorderCtrl',function($scope, $i18next, coreBOSWSAPI) {
	$scope.currentLang = $i18next.options.lng;
	$scope.ordersItemsCount = 0;
	$scope.ordersTotalCount = 0;
	$scope.ordersList = [];
	var so_account_id = '3x32528'; // FIXME
	var sqlr = "select id,cf_555,ship_street,duedate,sostatus from SalesOrder ";
	var sqlw = " where sostatus in ('Created','Scheduled','Pending','Completed','Invoiced','Invoice Paid') and account_id=" + so_account_id + ' ';
	coreBOSWSAPI.doQuery(sqlr + sqlw).then(function(response) {
		$scope.ordersList = response.data.result;
		$scope.ordersItemsCount = response.data.result.length;
	});
	coreBOSWSAPI.doQuery('select count(*) from SalesOrder' + sqlw).then(function(response) {
		$scope.ordersTotalCount = response.data.result[0].count;
	});
	$scope.onServerSideOrdersRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		var where = coreBOSWSAPI.getWhereCondition($scope.ordersList[0],filterBy, filterByFields, orderBy, orderByReverse, 'and', sqlw);
		var limit = coreBOSWSAPI.getLimit(pageItems,currentPage*pageItems);
		var query = sqlr + where + limit;
		coreBOSWSAPI.doQuery(query).then(function(response) {
			$scope.ordersList = response.data.result;
			$scope.ordersItemsCount = response.data.result.length;
		});
		coreBOSWSAPI.doQuery('select count(*) from SalesOrder' + where).then(function(response) {
			$scope.ordersTotalCount = response.data.result[0].count;
		});
	};
})
.controller('orderviewCtrl',function($scope, $i18next, $routeParams, coreBOSWSAPI) {
	$scope.retrieveable = true;
	coreBOSWSAPI.doRetrieve($routeParams.id).then(function(response) {
		$scope.so = response.data.result;
		$scope.so.cf_838 = $scope.so.cf_838 ? 'Yes' : 'No';
	},function(response) {
		$scope.retrieveable = false;
	});
})
.controller('myaccountCtrl',function($scope, $i18next, coreBOSWSAPI) {
	$scope.notifyvia = [ {
		name : i18n.t('Email'),
		code : 'Email'
	}, {
		name : i18n.t('Fax'),
		code : 'Fax'
	}, {
		name : i18n.t('Phone'),
		code : 'Phone'
	}];
	$scope.accountsent = false;
	$scope.errorsending = false;
	var account_id = '3x32528'; // FIXME
	coreBOSWSAPI.doRetrieve(account_id).then(function(response) {
		$scope.ac = response.data.result;
	});
	$scope.doUpdateAccount = function() {
		$scope.ac.id = account_id; // FIXME
		coreBOSWSAPI.doUpdate('Accounts',$scope.ac).then(function(response) {
			$scope.accountsent = true;
			$scope.comment = i18n.t('okAccountInfoSent');
		},function(response) {
			$scope.errorsending = true;
			$scope.errormsg = i18n.t('nokAccountInfoSent');
		});
	};
})
.controller('moduleCtrl',function($scope, $i18next,$routeParams, coreBOSWSAPI, coreBOSAPIStatus,ngTableParams) {
	$scope.currentLang = $i18next.options.lng;
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	$scope.moduleList = [];
        $scope.module = $routeParams.module;
        $scope.moduleLabel = $routeParams.moduleLabel;
        var filter_col='';

        coreBOSWSAPI.getFilterFields($scope.module).then(function(response) {
			$scope.fields=response.data.result.fields;
                        $scope.linkfields=response.data.result.linkfields;

		});
        coreBOSWSAPI.getRelatedActions($scope.module,'LISTVIEWPORTAL').then(function(response) {
			$scope.relatedactions=response.data.result;
		});
        coreBOSWSAPI.doDescribe($scope.module).then(function(response) {
		$scope.idPrefix = response.data.result.idPrefix;
		$scope.createable = response.data.result.createable;
		$scope.updateable = response.data.result.updateable;
            });
        $routeParams.module=$routeParams.module.toLowerCase();
	coreBOSWSAPI.doQuery('select * from '+$routeParams.module).then(function(response) {
            $scope.moduleList = response.data.result;
//            if($scope.fields!='')
//            {
//                if($scope.fields.indexOf('patientvis')!='-1' ){
//                 angular.forEach($scope.moduleList, function(value, key) {
//                    coreBOSWSAPI.doQuery('select patientsname from patients where patientsid='+value.patientvis).then(function(response) {
//                        $scope.moduleList[key]['assigned_user_id']=response.data.result[0]['first_name']+' '+response.data.result[0]['last_name'];
//
//                    });
//                 });
//             }
//            }

        $scope.myPageItemsCount = response.data.result.length;
	$scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 5          // count per page

        }, {
        total: $scope.moduleList.length, // length of data
        getData: function($defer, params) {
            // use build-in angular filter
            var orderedData = $scope.moduleList;

            params.total(orderedData.length); // set total for recalc pagination
            $defer.resolve($scope.users = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        }
        });
        $scope.get_contact = function() {
		coreBOSWSAPI.doQuery('select * from vitals join patiens on pazientide=patientid where patientsname like %'+$scope.searchPat+'%').then(function(response) {
		$scope.moduleList = response.data.result;
		$scope.myPageItemsCount = response.data.result.length;
	});
	};
        if($scope.module=='Vitals'){
            less.modifyVars({
                              '@pageRightWidth': '60%',
                              '@pageLeftWidth': '37%'
        });
        }
        else{
            less.modifyVars({
                              '@pageRightWidth': '27%',
                              '@pageLeftWidth': '70%'
        });
        }
    if($scope.module=='Vitals'){
//    $scope.options = {
//            chart: {
//                type: 'linePlusBarChart',
//                height: 450,
//                "width": 685,
//                margin : {
//                    top: 20,
//                    right: 20,
//                    bottom: 60,
//                    left: 45
//                },
//                clipEdge: true,
//                staggerLabels: true,
//                transitionDuration: 500,
//                stacked: false,
//                xAxis: {
//                    axisLabel: 'Parametri Vitali',
//                    showMaxMin: true,
//                    tickFormat: function(d) {return d;}
//                },
//                y1Axis: {
//                    axisLabel: 'Y1 Axis',
//                    tickFormat: function(d){return d3.format(',f')(d)}
//                },
//                y2Axis: {
//                    axisLabel: 'Y2 Axis',
//                    tickFormat: function(d) { return '$' + d3.format(',.2f')(d);}
//                }
//            }
//        };
         $scope.options = {
            chart: {
              type: 'linePlusBarChart',
              height: 450,
              "width": 685,
               margin: {
                top: 30,
                right: 60,
                bottom: 50,
                left: 70
              },
                x: function(d, i){return i;},
                y: function(d){return d[1];},
                color: d3.scale.category10().range(),
                transitionDuration: 500,
                xAxis: {
                    axisLabel: 'Parametri Vitali',
                    tickFormat: function(d) {
                        var label = $scope.data[0].values[d][0];
                        return label ;
                    }
                },
                y1Axis: {
                    axisLabel: '',
                    tickFormat: function(d){return d3.format(',f')(d)}
                },
                y2Axis: {
                    axisLabel: '',
                    tickFormat: function(d) { return d3.format(',.2f')(d);}
                }
            }
        };
        var blood = [],colesterol=[],creatinemia=[],got=[],gpt=[],
                triglicerid=[],glicemia=[],bloodpressdi=[],constant=[];
//        angular.forEach($scope.moduleList, function(value, key) {
//                    blood.push({"x":value.vitalsname,  "y":value.bloodpressy});
//                    colesterol.push({"x":value.vitalsname, "y":value.colesterol});
//                    creatinemia.push({"x":value.vitalsname, "y":value.creatinemia});
//                    got.push({"x":value.vitalsname, "y":value.got});
//                    gpt.push({"x":value.vitalsname, "y":value.gpt});
//                    triglicerid.push({"x":value.vitalsname, "y":value.triglicerid});
//                    glicemia.push({"x":value.vitalsname, "y":value.glicemia});
//                    bloodpressdi.push({"x":value.vitalsname, "y":value.bloodpressdi});
//        });
        angular.forEach($scope.moduleList, function(value, key) {
                    blood.push([value.vitalsname,  value.bloodpressy]);
                    colesterol.push([value.vitalsname, value.colesterol]);
                    creatinemia.push([value.vitalsname, value.creatinemia]);
                    got.push([value.vitalsname, value.got]);
                    gpt.push([value.vitalsname, value.gpt]);
                    triglicerid.push([value.vitalsname, value.triglicerid]);
                    glicemia.push([value.vitalsname, value.glicemia]);
                    bloodpressdi.push([value.vitalsname, value.bloodpressdi]);
                    constant.push([value.vitalsname, 50]);
        });

//   $scope.$on('elementClick.directive', function(angularEvent, event){
//                alert("Hi");
//            });
        $scope.data = [
            {
                "key" : "Colesterolo Totale" ,
                 "bar": true,
//                yAxis: 1,
//                color: '#bcbd22',
                "values" :  colesterol
            },
            {
                "key" : "Creatinina" ,
//                type: "line",
//                yAxis: 2,
//                 color: '#1f77b4',
                "values" :  creatinemia
            },
            {
                "key" : "GOT" ,
                 "bar": true,
//                yAxis: 2,
//                color: 'black',
                "values" :  got
            },
            {
                "key" : "GPT" ,
                 "bar": true,
//                yAxis: 2,
//                color: 'gray',
                "values" :  gpt
            },
            {
                "key" : "Trigliceridi" ,
//                type: "line",
//                yAxis: 1,
//                color: 'red',
                "values" :  triglicerid
            },
            {
                "key" : "Glicemia" ,
//                type: "line",
//                yAxis: 1,
//                color: 'yellow',
                "values" :  glicemia
            }

        ];
    }//for Vitals ListView

         });
	/*coreBOSWSAPI.doQuery('select * from helpdesk limit 0,15').then(function(response) {
		$scope.moduleList = response.data.result;
		$scope.myPageItemsCount = response.data.result.length;
	});
	coreBOSWSAPI.doQuery('select count(*) from helpdesk').then(function(response) {
		$scope.myItemsTotalCount = response.data.result[0].count;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		var where = coreBOSWSAPI.getWhereCondition($scope.moduleList[0],filterBy, filterByFields, orderBy, orderByReverse);
		var limit = coreBOSWSAPI.getLimit(pageItems,currentPage*pageItems);
		var query = 'select * from helpdesk ' + where + limit;
		coreBOSWSAPI.doQuery(query).then(function(response) {
			$scope.moduleList = response.data.result;
			$scope.myPageItemsCount = response.data.result.length;
		});
		coreBOSWSAPI.doQuery('select count(*) from helpdesk' + where).then(function(response) {
			$scope.myItemsTotalCount = response.data.result[0].count;
		});
	};*/
})
.controller('moduleViewCtrl',function($scope, $i18next, $routeParams, $filter,$location, coreBOSWSAPI, coreBOSAPIStatus) {
	$scope.modulefieldList = [{field:'',val:''}];
	$scope.module = $routeParams.module;
        $scope.module1=$routeParams.module.toLowerCase();
        $scope.recordid = $routeParams.id;
	$scope.moduleData = {};
        $scope.entity={};
        $scope.creating=false;

        $scope.getModuleValue = function(field) {
		return $scope.moduleData[field];
	};
        coreBOSWSAPI.getRelatedModules($scope.module).then(function(response) {
                $scope.relatedmodules = response.data.result;
        });
	coreBOSWSAPI.doDescribe($scope.module).then(function(response) {
		$scope.idPrefix = response.data.result.idPrefix;
		$scope.createable = response.data.result.createable;
		$scope.updateable = response.data.result.updateable;
		$scope.deleteable = response.data.result.deleteable;
		$scope.retrieveable = response.data.result.retrieveable;
		$scope.modulename = response.data.result.name;
		$scope.modulefields = response.data.result.fields;
                $scope.labelFields = response.data.result.labelFields;
                $scope.indexFields = response.data.result.indexFields;
		if ($scope.retrieveable) {
			$scope.saveModule = function() {
                            if($scope.creating)
                            {
                               coreBOSWSAPI.doCreate($routeParams.module,$scope.moduleData).then(function(response) {
				});
                            }
                            else
                            {
				coreBOSWSAPI.doUpdate($scope.module,$scope.moduleData).then(function(response) {
				});
                            }
			};
			$scope.doCreate = function() {
				coreBOSWSAPI.doCreate('moduleData',$scope.moduleData).then(function(response) {
				});
			};
			$scope.doDelete = function() {
				coreBOSWSAPI.doDelete($scope.moduleData.id).then(function(response) {
				});
			};
			coreBOSWSAPI.doQuery('select ticket_title from '+$scope.module1).then(function(response) {
				var aarray = [];
				angular.forEach(response.data.result, function(value, key) {
					aarray.push(value.ticket_title + ' (' + value.id + ')');
				});
				$scope.accs = aarray;
			});
			coreBOSWSAPI.doQuery('select first_name,last_name from users').then(function(response) {
				var uarray = [];
				angular.forEach(response.data.result, function(value, key) {
					uarray.push(value.first_name + ' ' + value.last_name + ' (' + value.id + ')');
				});
				$scope.usrs = uarray;
			});
                        if($routeParams.id.indexOf('x')==-1)
                        {
                            $scope.creating=true;//alert($scope.creating);
                            var flds = [], cols = [];
				var moduleData = {};
                                var i=0;
				var numcols = 3;
				var lblclass = 'col-md-2', vlclass = 'col-md-2';
                                for(i=0;i<$scope.modulefields.length;i++)
				{
                                    if ($scope.modulefields[i]['name']!='id') {
					var found = $scope.modulefields[i];

					var fld = {
						label:found.label,
						labelclass:lblclass,
						field:$scope.modulefields[i]['name'],
						//val: value == '' ? 'none' : value,
						valclass:vlclass,
						uitype: found.uitype,
						type: found.type.name
					};
					//account[key] = value;
					if (found.type.name == 'reference') {

					}
					if (found.type.name == 'picklist') {
						var pl = {
							defaultValue: found.type.defaultValue,
							picklistValues: found.type.picklistValues
						};
						angular.extend(fld,pl);
					}
					cols.push(fld);
					if (cols.length == numcols) {
						flds.push(cols);
						cols = [];
					}
                                    }
                                };
				flds.push(cols);
				$scope.modulefieldList = flds;
				$scope.moduleData = moduleData;
                        }
                        else
                        {
//                            var flds = [], cols = [], ui10 = [];
//			coreBOSWSAPI.doRetrieve($routeParams.id).then(function(response) {
//				angular.forEach(response.data.result, function(value, key) {
//					var found = $filter('getArrayElementById')($scope.modulefields, key, 'name');
//                                        if(found.uitype=='10'){
//                                            coreBOSWSAPI.getReferenceValue(value).then(function(response) {
//                                                var t=response.data.result[value];
//                                                ui10[key]=t['reference'];//alert(t['reference']);
//                                            });
//                                        }
//                                });
//                            });
                       coreBOSWSAPI.doRetrieve($routeParams.id).then(function(response) {
				var flds = [], cols = [];
				var moduleData = {};
				var numcols = 3;
				var lblclass = 'col-md-2', vlclass = 'col-md-2';
				angular.forEach(response.data.result, function(value, key) {
					if (key!='id') {
                                            var found = $filter('getArrayElementById')($scope.modulefields, key, 'name');
					if (key==$scope.labelFields) {
						$scope.accountname = value;
					}

//                                        if(found.uitype=='10'){//alert(key+' '+value);
//                                            value=ui10[key];
//                                            //alert(value);
//                                        }
                                        var id10='';
//                                        if(found.uitype=='10'){
//                                            id10=value['id10'];
//                                            value=value['v10'];
////                                            coreBOSWSAPI.getReferenceValue(value).then(function(response) {
////                                                var t=response.data.result[value];
////                                                value=t;//alert(t['reference']);
////                                            });
//                                        }
					var fld = {
						label:found.label,
						labelclass:lblclass,
						field:key,
						val: value == '' ? 'none' : value,
						val10:id10,
                                                valclass:vlclass,
						uitype: found.uitype,
						type: found.type.name
					};
					moduleData[key] = value;
					if (found.type.name == 'reference') {

					}
					if (found.type.name == 'picklist') {
						var pl = {
							defaultValue: found.type.defaultValue,
							picklistValues: found.type.picklistValues
						};
						angular.extend(fld,pl);
						if(fld.field == 'ticketstatus')
						{
							$scope.ticketstatus = fld;
						}
					}
					cols.push(fld);
					if (cols.length == numcols) {
						flds.push(cols);
						cols = [];
					}
                                    }
                                });
				flds.push(cols);
				$scope.modulefieldList = flds;
				$scope.moduleData = moduleData;
			});
                }
            if($scope.module=='Vitals'){
                    $scope.bloodpresure=$scope.moduleData['bloodpresure'];
                    $scope.oxygensat=$scope.moduleData['oxygensat'];
                    $scope.weight=$scope.moduleData['weight'];
                    $scope.bloodpressdi=$scope.moduleData['bloodpressdi'];
            }

		}
	});
        $scope.relmodule=$scope.module;
        $scope.relRecordList = [];

        $scope.showRel = function(relmod,relfield){
            if(relmod!=$scope.module){

            coreBOSWSAPI.getFilterFields(relmod).then(function(response) {
			$scope.fields=response.data.result.fields;
                        $scope.linkfields=response.data.result.linkfields;
               		$scope.fieldlabels = response.data.result.fieldlabels;
                        coreBOSWSAPI.doGetUi10RelatedRecords( $scope.recordid ,$scope.module,relmod, $scope.fields).then(function(response) {
                            $scope.relRecordList =response.data.result.records;
                  });

		});

              }
            $scope.relmodule=relmod;
            $scope.relfield=relfield;
        };

        if($scope.module=='Patients'){
        coreBOSWSAPI.getVitalParameters($scope.recordid).then(function(response) {
                    $scope.visitid =response.data.result.visit[0];
                    $scope.visitname =response.data.result.visit[1];
                    $scope.prescriptionname=response.data.result.prescription[1];
                    $scope.prescriptionid=response.data.result.prescription[0];
                    $scope.vitalid=response.data.result.vitals[0];
                    $scope.vitalname=response.data.result.vitals[1];
                    $scope.bloodpresure=response.data.result.vitals[2];
                    $scope.oxygensat=response.data.result.vitals[3];
                    $scope.weight=response.data.result.vitals[4];
                    $scope.bloodpressdi=response.data.result.vitals[5];
                    $scope.pulse=response.data.result.vitals[6];
                    $scope.issues=response.data.result.issues;
                    $scope.options_blood = {
                          chart: {
                        type: 'stackedAreaChart',
                        height: 250,
                        width: 450,
                        expanded: true,
                        "tooltips": false,
                        "controlsData":["Expanded"],
                        margin : {
                            top: 20,
                            right: 20,
                            bottom: 60,
                            left: 40
                        },
                        x: function(d){return d[0];},
                        y: function(d){return d[1];},
                        useVoronoi: false,
                        clipEdge: true,
                        transitionDuration: 500,
                        useInteractiveGuideline: true,
                        xAxis: {
                            showMaxMin: false,
                            tickFormat: function(d) {return d;}
                        },
                        yAxis: {
                            tickFormat: function(d){
                                return d;
                            }
                        }
                    }
                    };

                    $scope.data_blood = [
                        {
                            "key" : "Pressione Arteriosa Diastolica" ,
                            "values" : [  [ 0 , $scope.bloodpressdi],[ 2 , $scope.bloodpressdi]  ]  },

                        {
                            "key" : "Pressione Arteriosa Sistolica" ,
                            "values" : [ [ 0 ,  $scope.bloodpresure],[ 1 , $scope.bloodpresure] ] }
                    ];
                    $scope.options = {
                        chart: {
                            type: 'bulletChart',
                            transitionDuration: 500
                        }
                    };

                    $scope.data = {
                        "title": "Impulso",
                        "subtitle": "per min",
                        "ranges": [60,70,100],
                        "measures": [$scope.pulse],
                        "markers": []
                    };

                    $scope.options2 = {
                        chart: {
                            type: 'bulletChart',
                            transitionDuration: 500,
                            color:function (d, i) { return 'red'; }
                        }
                    };

                    $scope.data2 = {
                        "title": "Peso",
                        "subtitle": "kg",
                        "ranges": [40,70,100],
                        "measures": [$scope.weight],
                        "markers": []
                    };
            });
        }

        $scope.doCreateRel = function() {
             //alert($scope.entity);
             $scope.entity[$scope.relfield]=$scope.recordid;
             $scope.entity['assigned_user_id']='19x6';
                coreBOSWSAPI.doCreate($scope.relmodule,$scope.entity).then(function(response) {
                         coreBOSWSAPI.doGetUi10RelatedRecords( $scope.recordid ,$scope.module,$scope.relmodule, $scope.fields).then(function(response) {
                         $scope.relRecordList =response.data.result.records;
                     });
                 });
         };
	// Click handler for the Save button. Saves the form to the back-end service.
	$scope.saveSignature = function saveSignature() {
		// Check for validity. AngularJS will set $valid == true if all form requirements are met.
		//if ( $scope.sigForm.$valid ) {

			var sigPadAPI = $('<div class="sig current" style="display: none;"><canvas class="pad" ng-mouseup="updateModel()" height="240" width="350" name="canvas_sign"></canvas></div>').signaturePad({
				displayOnly: true
			});
			// regenerate the signature onto the canvas
			sigPadAPI.regenerate($scope.helpdesk.signature);
			// convert the canvas to a PNG (Newer versions of Chrome, FF, and Safari only.)
			var firma = sigPadAPI.getSignatureImage().substring(22);

			var filename = $scope.helpdesk.ticket_no + '_Signature.png';

			var model_filename={
					name:filename,
					size:firma.length,
					type:'image/png',
					content:firma
			};

			var docData = {
				notes_title: 'Sign: ' + $scope.helpdesk.ticket_title,
				filename: model_filename,
				filetype: model_filename['type'],
				filesize: model_filename['size'],
				filelocationtype: 'I',
				filedownloadcount: 0,
				filestatus: 1,
				folderid: '22x1',
				relations: $scope.helpdesk.id,
			};

			coreBOSWSAPI.doCreate('Documents',docData).then(function(response) {
			});
		//}
	};
	// Clear the form fields and scope data
	$scope.clearData = function() {
		$scope.helpdesk = {
			signature: null,
		};
	};

	$scope.saveTicketComment = function() {
		coreBOSWSAPI.doAddTicketFaqComment($scope.helpdesk.id,$scope.helpdesk).then(function(response) {
			$scope.helpdesk.comments = null;

		});
	};

})
.controller('relationsCtrl',function($scope, $i18next,$routeParams,coreBOSWSAPI, coreBOSAPIStatus) {
	$scope.recordid = $routeParams.id;
        $scope.module=$routeParams.srcmodule;
        $scope.relmodule=$routeParams.rlmodule;
        $scope.relRecordList = [];

        coreBOSWSAPI.doGetRelatedRecords( $scope.recordid ,$scope.module,$scope.relmodule, "").then(function(response) {
                        $scope.relRecordList =response.data.result.records;
		});
        $scope.doCreate = function() {
             $scope.entity['related_to']=$scope.recordid;
             $scope.entity['sales_stage']='Negotiation/Review';
             $scope.srelresult=[];
                coreBOSWSAPI.doCreate($scope.module,$scope.entity).then(function(response) {
                         console.log('create:',response);
                         //$scope.srelresult=response;

                         coreBOSWSAPI.doGetRelatedRecords( $scope.recordid ,$scope.module,$scope.relmodule, "").then(function(response) {
                         $scope.relRecordList =response.data.result.records;
                     });
                 });
         };
	$scope.sendgrelCall = function() {
		$scope.grelresult = "";
		var queryParameters = {};
		if (!angular.isUndefined($scope.rpdodisc)) queryParameters.productDiscriminator = $scope.rpdodisc;
		if (!angular.isUndefined($scope.glimit)) queryParameters.limit = $scope.glimit;
		if (!angular.isUndefined($scope.groffset)) queryParameters.offset = $scope.groffset;
		if (!angular.isUndefined($scope.gorder)) queryParameters.orderby = $scope.gorder;
		if (!angular.isUndefined($scope.gcols)) queryParameters.columns = $scope.gcols;
		coreBOSWSAPI.doGetRelatedRecords($scope.grelrecord,$scope.gparentmodule,$scope.grelmodule, queryParameters).then(function(response) {
			$scope.grelresult = response.data;
		});
	};
	$scope.sendsrelCall = function() {
		$scope.srelresult = "";
		coreBOSWSAPI.doSetRelated($scope.srelrecord,$scope.srelwith).then(function(response) {
			$scope.srelresult = response.data;
		});
	};
})
;


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:descendantFocusability="blocksDescendants"
    android:orientation="horizontal"
    android:paddingTop="3dp">

    <ImageView
        android:id="@+id/listitem_img_wifi_signal_intensity"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:paddingLeft="7dp"
        android:paddingRight="7dp" />

    <View
        android:layout_width="0.5dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="7dp"
        android:layout_marginTop="7dp"
        android:background="@android:color/holo_blue_dark" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="12dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/listitem_txv_wifi_ssid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:singleLine="true"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/listitem_txv_wifi_desc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:textSize="10sp" />

    </LinearLayout>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ApplicationFeatureLibraryBooksTest\Controller\SLFactory;

use ApplicationFeatureLibraryBooks\Controller\DeleteController;
use ApplicationFeatureLibraryBooks\Controller\SLFactory\DeleteControllerSLFactory;
use Test\Bootstrap;
use Zend\Mvc\Controller\ControllerManager;

class DeleteControllerFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var DeleteControllerSLFactory
     */
    private $testedObj;

    public function setUp()
    {
        $this->testedObj = new DeleteControllerSLFactory();
    }

    public function testCreateService()
    {
        $controllerManager = new ControllerManager();
        $controllerManager->setServiceLocator(Bootstrap::getServiceManager());

        $result = $this->testedObj->createService($controllerManager);

        $this->assertInstanceOf(DeleteController::class, $result);
    }
}


text:
package com.asakusafw.compiler.flow.processor.operator;

import java.util.List;

import com.asakusafw.compiler.flow.processor.MasterBranchFlowProcessor;
import com.asakusafw.compiler.flow.testing.model.Ex1;
import com.asakusafw.compiler.flow.testing.model.Ex2;
import com.asakusafw.vocabulary.model.Key;
import com.asakusafw.vocabulary.operator.MasterBranch;
import com.asakusafw.vocabulary.operator.MasterSelection;

/**
 * An operator class for testing {@link MasterBranchFlowProcessor}.
 */
public abstract class MasterBranchFlow {

    /**
     * simple.
     * @param master the master data
     * @param model target data model
     * @return branch target
     */
    @MasterBranch
    public Speed simple(
            @Key(group = "string") Ex2 master,
            @Key(group = "string") Ex1 model) {
        return withParameter(master, model, 30);
    }

    /**
     * parameterized.
     * @param master the master data
     * @param model target data model
     * @param parameter additional parameter
     * @return branch target
     */
    @MasterBranch
    public Speed withParameter(
            @Key(group = "string") Ex2 master,
            @Key(group = "string") Ex1 model,
            int parameter) {
        if (master == null) {
            return Speed.STOP;
        }
        if (master.getValue() + model.getValue() > parameter) {
            return Speed.HIGH;
        }
        if (master.getValue() + model.getValue()  <= 0) {
            return Speed.STOP;
        }
        return Speed.LOW;
    }

    /**
     * w/ selector.
     * @param master the master data
     * @param model target data model
     * @return branch target
     */
    @MasterBranch(selection = "selector")
    public Speed selection(
            @Key(group = "string") Ex2 master,
            @Key(group = "string") Ex1 model) {
        return withParameter(master, model, 30);
    }

    /**
     * w/ parameter and (non-parameterized) selector.
     * @param master the master data
     * @param model target data model
     * @param parameter additional parameter
     * @return branch target
     */
    @MasterBranch(selection = "selector")
    public Speed selectionWithParameter0(
            @Key(group = "string") Ex2 master,
            @Key(group = "string") Ex1 model,
            int parameter) {
        return withParameter(master, model, parameter);
    }

    /**
     * w/ parameter and (parameterized) selector.
     * @param master the master data
     * @param model target data model
     * @param parameter additional parameter
     * @return branch target
     */
    @MasterBranch(selection = "selectorWithParameter")
    public Speed selectionWithParameter1(
            @Key(group = "string") Ex2 master,
            @Key(group = "string") Ex1 model,
            int parameter) {
        return withParameter(master, model, parameter);
    }

    /**
     * non-parameterized selector.
     * @param masters list of masters
     * @param model the data model
     * @return the selected master data, or {@code null} if there is no suitable master data
     */
    @MasterSelection
    public Ex2 selector(List<Ex2> masters, Ex1 model) {
        for (Ex2 master : masters) {
            if (master.getValueOption().equals(model.getValueOption())) {
                return master;
            }
        }
        return null;
    }

    /**
     * parameterized selector.
     * @param masters list of masters
     * @param model the data model
     * @param parameter the additional parameter
     * @return the selected master data, or {@code null} if there is no suitable master data
     */
    @MasterSelection
    public Ex2 selectorWithParameter(List<Ex2> masters, Ex1 model, int parameter) {
        for (Ex2 master : masters) {
            if (master.getValueOption().has(parameter)) {
                return master;
            }
        }
        return null;
    }

    /**
     * Speed kind.
     */
    public enum Speed {

        /**
         * high speed.
         */
        HIGH,

        /**
         * low speed.
         */
        LOW,

        /**
         * stopped.
         */
        STOP,
    }
}


text:
package org.springframework.social.smartcloud.api;

/**
 * User: greg
 * Date: 13-09-03
 * Time: 12:07 PM
 */
public interface UserOperations {

    SmartCloudProfile getUserProfile();
}


text:
/*
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE', which is part of this source code package.
 */

#pragma once
#include <type_traits>
#include <unordered_map>
#include <memory>

namespace web {
	struct attribute
	{
		using typeid_t = size_t;

		template <typename A>
		using is_attribute = std::is_base_of<attribute, typename std::remove_cv<A>::type>;

		virtual ~attribute() = default;
		template <typename A>
		static inline typeid_t id()
		{
			static_assert(is_attribute<A>{}, "Attribute type must inherit from web::attribute.");
			static typeid_t next_id = 0;
			static typeid_t type_id = next_id++;
			return type_id;
		}
	};

	class attributes {
		std::unordered_map<attribute::typeid_t, std::shared_ptr<attribute>> m_list;

		template <typename A>
		using is_attribute = std::is_base_of<attribute, typename std::remove_cv<A>::type>;

		template <typename A, typename Ret = void>
		using require_attribute = typename std::enable_if<is_attribute<A>::value, Ret>::type;
	public:
		template <typename Attr>
		require_attribute<Attr, bool> has_attr() const
		{
			static_assert(is_attribute<Attr>{}, "Attribute type must inherit from web::attribute.");
			auto it = m_list.find(attribute::id<Attr>());
			if (it == m_list.end())
				return false;
			return !!it->second;
		}

		template <typename Attr>
		require_attribute<Attr> set_attr(const std::shared_ptr<Attr>& attr)
		{
			static_assert(is_attribute<Attr>{}, "Attribute type must inherit from web::attribute.");
			if (attr)
				m_list[attribute::id<Attr>()] = attr;
		}

		template <typename Attr>
		require_attribute<Attr> set_attr(std::shared_ptr<Attr>&& attr)
		{
			static_assert(is_attribute<Attr>{}, "Attribute type must inherit from web::attribute.");
			if (attr)
				m_list[attribute::id<Attr>()] = std::move(attr);
		}

		template <typename Attr, typename... Args>
		require_attribute<Attr> make_attr(Args&&... args)
		{
			static_assert(is_attribute<Attr>{}, "Attribute type must inherit from web::attribute.");
			auto ptr = std::make_shared<Attr>(std::forward<Args>(args)...);
			if (ptr)
				m_list[attribute::id<Attr>()] = std::move(ptr);
		}

		template <typename Attr>
		require_attribute<Attr, std::shared_ptr<Attr>> get_attr() const
		{
			static_assert(is_attribute<Attr>{}, "Attribute type must inherit from web::attribute.");
			auto it = m_list.find(attribute::id<Attr>());
			if (it == m_list.end())
				return { };
			return it->second;
		}
	};
}


text:
/* $Id$ */
/* Copyright (c) 2015-2020 Pierre Pronchery <khorben@defora.org> */
/* This file is part of DeforaOS System libSystem */
/* All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "System/error.h"
#include "System/object.h"
#include "System/file.h"

/* File */
/* private */
/* types */
struct _File
{
	String * filename;
	FILE * fp;
	FileMode mode;
};

/* prototypes */
/* accessors */
static String const * _file_get_fmode(File * file, FileMode mode);

/* useful */
static FileError _file_error(File * file, int error);

/* public */
/* functions */
/* config_new */
File * file_new(String const * filename, FileMode mode)
{
	File * file;
	char const * fmode;

	if((file = (File *)object_new(sizeof(*file))) == NULL)
		return NULL;
	if((file->filename = string_new(filename)) == NULL
			|| (fmode = _file_get_fmode(file, mode)) == NULL)
	{
		object_delete(file);
		return NULL;
	}
	if((file->fp = fopen(filename, fmode)) == NULL)
	{
		file_delete(file);
		_file_error(file, errno);
		return NULL;
	}
	file->mode = mode;
	return file;
}

/* file_delete */
FileError file_delete(File * file)
{
	FileError ret = 0;

	if(file->fp != NULL
			&& (ret = fclose(file->fp)) != 0)
		ret = _file_error(file, errno);
	string_delete(file->filename);
	object_delete(file);
	return ret;
}

/* accessors */
/* file_get_filename */
String const * file_get_filename(File * file)
{
	return file->filename;
}

/* file_get_mode */
FileMode file_get_mode(File * file)
{
	return file->mode;
}

#if 0
/* file_set_mode */
int file_set_mode(File * file, FileMode mode)
{
	char const * fmode;

	if((fmode = _file_get_fmode(mode)) == NULL)
		return -1;
	if(freopen(file->fp, fmode) != 0)
		return _file_error(file, errno);
	return 0;
}
#endif

/* useful */
/* file_read */
FileError file_read(File * file, void * buf, size_t size, size_t * count)
{
	size_t s;

	if((s = fread(buf, size, *count, file->fp)) < *count
			&& ferror(file->fp))
	{
		*count = s;
		return _file_error(file, errno);
	}
	return 0;
}

/* file_read_buffer */
FileError file_read_buffer(File * file, Buffer * buffer)
{
	int ret;
	size_t s;

	s = buffer_get_size(buffer);
	if((ret = file_read(file, (void *)buffer_get_data(buffer),
					sizeof(BufferData), &s)) != 0)
		buffer_set_size(buffer, s);
	return ret;
}

/* file_seek */
FileError file_seek(File * file, FileSeekMode mode, FileOffset offset)
{
	switch(mode)
	{
		case FILE_SEEK_MODE_CURRENT:
			return fseek(file->fp, SEEK_CUR, offset);
		case FILE_SEEK_MODE_END:
			return fseek(file->fp, SEEK_END, offset);
		case FILE_SEEK_MODE_SET:
			return fseek(file->fp, SEEK_SET, offset);
	}
	return _file_error(file, EINVAL);
}

/* file_unlink */
FileError file_unlink(File * file)
{
	return (unlink(file->filename) != 0)
		? _file_error(file, errno) : 0;
}

/* file_write */
FileError file_write(File * file, const void * buf, size_t size, size_t * count)
{
	size_t s;

	if((s = fwrite(buf, size, *count, file->fp)) < *count)
	{
		*count = s;
		return _file_error(file, errno);
	}
	return 0;
}

/* file_write_buffer */
FileError file_write_buffer(File * file, Buffer const * buffer)
{
	size_t size;

	size = buffer_get_size(buffer);
	return file_write(file, buffer_get_data(buffer), sizeof(char), &size);
}

/* private */
/* accessors */
static String const * _file_get_fmode(File * file, FileMode mode)
{
	struct
	{
		FileMode mode;
		String const * ret;
	} modes[] =
	{
		{ FILE_MODE_WRITE
			| FILE_MODE_APPEND
			| FILE_MODE_CREATE,	"a"	},
		{ FILE_MODE_WRITE
			| FILE_MODE_APPEND
			| FILE_MODE_CREATE
			| FILE_MODE_EXCLUSIVE,	"ax"	},
		{ FILE_MODE_READ_WRITE
			| FILE_MODE_APPEND
			| FILE_MODE_CREATE,	"a+"	},
		{ FILE_MODE_READ_WRITE
			| FILE_MODE_APPEND
			| FILE_MODE_CREATE
			| FILE_MODE_EXCLUSIVE,	"a+x"	},
		{ FILE_MODE_READ,		"r"	},
		{ FILE_MODE_READ_WRITE,		"r+"	},
		{ FILE_MODE_WRITE
			| FILE_MODE_CREATE
			| FILE_MODE_TRUNCATE,	"w"	},
		{ FILE_MODE_WRITE
			| FILE_MODE_CREATE
			| FILE_MODE_TRUNCATE
			| FILE_MODE_EXCLUSIVE,	"wx"	},
		{ FILE_MODE_READ_WRITE
			| FILE_MODE_CREATE
			| FILE_MODE_TRUNCATE,	"w+"	},
		{ FILE_MODE_READ_WRITE
			| FILE_MODE_CREATE
			| FILE_MODE_TRUNCATE
			| FILE_MODE_EXCLUSIVE,	"w+x"	},
	};
	size_t i;

	for(i = 0; i < sizeof(modes) / sizeof(*modes); i++)
		if(modes[i].mode == mode)
			return modes[i].ret;
	_file_error(file, EINVAL);
	return NULL;
}

/* useful */
/* file_error */
static FileError _file_error(File * file, int error)
{
	return error_set_code(-error, "%s: %s", file->filename,
			strerror(error));
}


text:
var prependChar = '#';
var util = require('util');

function convertToLines(str) {
  return str.split('\n').map(function(newStr) {
    return prependChar + newStr;
  });
}

var newConsole = {
  log : function log() {
    convertToLines(util.format.apply(this, arguments)).forEach(function(line) {
      console.log(line);
    });
  },
  error : function error() {
    convertToLines(util.format.apply(this, arguments)).forEach(function(line) {
      console.error(line);
    });
  }
};

module.exports = newConsole;


text:
{% extends "base.html" %}

{% block title %}
     Meat Update
{% endblock %}

{% block header %}

{% endblock %}

{% block content %}

	{% include "distribution/tabnav.html" %}

    <form action="." method="POST" >
		<input name='producer-id' type='hidden' value='{{ producer.id }}' />
		<input name='avail-date' type='hidden' value='{{ avail_date }}' />

                Producer:
                {{ producer.short_name }} - {{ producer.long_name }}

                Week of:
                {{ avail_date}}

                Contact:
               {{producer.contact}}

                Phone:
                {{producer.phone}}

			{{ formset.management_form }}

					Product
					Custodian
					Date
					Ready Qty
					Received Qty
					Processor
					Process cost
					Notes

				{% for item_form in formset.forms %}

						 {{ item_form.product }}
						 {{ item_form.custodian }}
						 {{ item_form.inventory_date }}
						 {{ item_form.planned }}
						 {{ item_form.received }}
						 {{ item_form.processor }}
						 {{ item_form.cost }}
						 {{ item_form.notes }}
						{{ item_form.item_id }}

				{% endfor %}

            <input type="submit" value="Submit" />

    </form>

{% endblock %}


text:
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: Apache License, Version 2.0
 * See the LICENSE file in the root directory or visit http://www.apache.org/licenses/LICENSE-2.0
 */
package org.hibernate.query.parser.hql;

import org.hibernate.query.parser.SemanticQueryInterpreter;
import org.hibernate.sqm.query.SelectStatement;
import org.hibernate.sqm.query.expression.FromElementReferenceExpression;
import org.hibernate.sqm.query.select.Selection;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

/**
 * @author Steve Ebersole
 */
public class FromElementContainmentTests {
	@Test
	public void testFromElementReferenceInSelect() {
		final String query = "select o from Entity o";
		final ConsumerContextTestingImpl consumerContext = new ConsumerContextTestingImpl();
		SelectStatement statement = (SelectStatement) SemanticQueryInterpreter.interpret( query, consumerContext );
		assertEquals( 1, statement.getQuerySpec().getSelectClause().getSelections().size() );
		Selection selection = statement.getQuerySpec().getSelectClause().getSelections().get( 0 );
		assertThat( selection.getExpression(), instanceOf( FromElementReferenceExpression.class ) );
	}

	@Test
	public void testFromElementReferenceInOrderBy() {
		final String query = "select o from Entity o order by o";
		final ConsumerContextTestingImpl consumerContext = new ConsumerContextTestingImpl();
		SelectStatement statement = (SelectStatement) SemanticQueryInterpreter.interpret( query, consumerContext );
		assertEquals( 1, statement.getOrderByClause().getSortSpecifications().size() );
		assertThat(
				statement.getOrderByClause().getSortSpecifications().get( 0 ).getSortExpression(),
				instanceOf( FromElementReferenceExpression.class )
		);
	}
}


text: chef-client -z -o dotfiles


text:
package de.blogspot.mszalbach.iss.screenplay.tasks;

import de.blogspot.mszalbach.iss.pageobjects.SecurityListPage;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;

public class RequestASecurity
    implements Task {

    private final String isin;

    public RequestASecurity( String isin ) {
        this.isin = isin;
    }

    public static RequestASecurity called( String isin ) {
        return new RequestASecurity( isin );
    }

    @Override
    public <T extends Actor> void performAs( T actor ) {
        actor.attemptsTo( Click.on( SecurityListPage.requestActionForSecurity( isin ) ) );
    }

}


text: image credit: {{ page.featured_image_credit | markdownify | remove: '<p>' | remove: '</p>' }}


text:
layout: post
title: "Introduction to Cubing"
category: articles
tags: ["other"]
---

In 1974 Ernő Rubik accidentally invented a puzzle he couldn't solve. It took him a month of tinkering to unscramble the first Rubik's Cube. Which is to say, it's a pretty difficult puzzle to figure out on your own. Most people don't. I didn't. The fun starts when you start trying to solve it faster.

### Hardware

This is a _Rubik's Cube_.

![Rubik's Cube]({{ site.baseurl }}/images/rubiks-cube.png)

This is a _GuoGuan YueXiao Speed Cube_.

![Rubik's Cube]({{ site.baseurl }}/images/guoguan-cube.png)

You could be forgiven for mistaking the two. The Rubik's patents expired in 2000, and the subsequent copies have surpassed the original in quality and manufacture. They each have a distinct feel, but anything listed on [bestspeedcubes.com](http://www.bestspeedcube.com/) is going to work well.

### Your First Solve

The appropriately named [how-to-solve-a-rubix-cube.com](https://how-to-solve-a-rubix-cube.com/) is the best way to learn. It has clear diagrams, a nice summary, and even works on mobile! You should be able to get under three minutes pretty comfortably using this beginner's technique. I learned one step a day, so had it down within a week.

The first layer of the cube can be solved _intuitively_, meaning no moves need to be memorized. Doing this gives you a feel for how the cubies move around. A memorized series of moves, used for the final sections, is known as an _algorithm_. For this beginners method, you do need to memorize a handful of algorithms, but for the most part they are pretty straightforward patterns.

At this point, it's also worth learning how to best hold and rotate the cube using your fingers, rather than moving your entire hand for each rotation.

{% youtube rzvW3dI03ws %}

### Your Next Solve

The most common method of solving a cube today is known as either CFOP, or the Fridrich method. It starts the same as the beginner method above, by forming the white cross. Why white? Convention. A few of the top cubers today are _colour neutral_, meaning they can start with any colour, but most start with white even at the elite level.

After the cross, CFOP proceeds to solve the remainder of the first two layers (_F2L_) at the same time. This can be done intuitively! This video provides a very clear explanation and demonstration:

{% youtube 2EjpF8ORtVo %}

After solving F2L, you can use the same algoritms from the beginner technique to complete. The CFOP method provides a different strategy though, first solving the yellow face (orienting the last layer, or OLL), and then rearranging the remaining pieces (permuting the last layer, or PLL). In total, this can be done efficiently with 78 different algorithms(!)

I haven't learned all of them though. Instead, I'm currently on _two-look_ OLL and beginner two-look PLL which can be done with 9 and 2 algorithms respectively.

{% youtube IMb7hOAgmng %}

My current average solve time is around 75 seconds, using [cubetimer.com](http://www.cubetimer.com) to scramble and measure. Learning a few more algorithms for a faster two-look PLL is next on my list. Putting it all together it could eventually look something like this:

{% youtube Jcv4ePMPN_U %}

### Bonus True Facts

* The world record for a single solve was just [set by Feliks Zemdegs](https://www.youtube.com/watch?v=R07JiT0PlcE) at 4.73. That's about a 10 move per second average.
* A robot can solve it in [under a second](https://www.youtube.com/watch?v=by1yz7Toick) though.
* Every permumtation can theoretically be solved in 20 moves or fewer, but that is too hard for humans to do consistently. An average speed solve will take 40-60 moves. There is an official event where competitors get an hour to find the most efficient solve for finding a solve with the fewest moves, and results in the 20-30 range are typical.
* CFOP isn't the only way to solve. [Petrus](https://www.speedsolving.com/wiki/index.php/Petrus), [Roux](https://www.speedsolving.com/wiki/index.php/Roux), and [ZZ](https://www.speedsolving.com/wiki/index.php/ZZ) are other popular alternatives. I haven't learned them yet though.
* Blindfolded solving is an official category, where you need to memorize the entire sequence of moves to solve in the initial inspection period. This uses different algorithms to speed solving that are easier to figure out from the initial state.


text:
      Docs

    Numeral.js format pattern

      (Default: "{{ editor.field.format.type.paramDefaults.pattern }}")

<field-format-editor-pattern
  ng-model="editor.formatParams.pattern"
  placeholder="editor.field.format.type.paramDefaults.pattern"
  inputs="cntrl.sampleInputs">
</field-format-editor-pattern>


text:
<?php
/**
 * Created by: ogre
 * Date: 2015-08-20
 * Time: 16:26
 */

require_once(DIR_INC . 'classes/api/response_ok.class.php');

class ROk_Load_ADI_Vouchers extends Response_OK {
    public static $tag = 'LOAD_ADI_VOUCHERS_OK';

    function __construct($promos) {
        $this->set_response_code(Rest_Responses::$oks[self::$tag]);
        $this->set_payload($promos);
    }
}


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LTAF.TagParser;

namespace LTAF.UnitTests.TagParser
{
	[TestClass]
	public class NodeContainerTest
	{

		[TestMethod]
		public void AttributeGetShouldReturnNewAttributeCollectionWhenFirstCall()
		{
			NodeContainer target = CreateNodeContainer();
			Assert.AreEqual(0, target.Attributes.Count);
		}

		[TestMethod]
		public void AttributeGetShouldReturnExistingAttributeCollectionWhenSecondCall()
		{
			NodeContainer target = CreateNodeContainer();
			Assert.AreEqual(0, target.Attributes.Count);
			target.Attributes.Add(new LTAF.TagParser.Attribute("prefix", "localName", "value"));
			Assert.AreEqual(1, target.Attributes.Count);
		}

		[TestMethod()]
		public void HasAttributesGetShouldReturnFalseWhenNoCollection()
		{
			NodeContainer target = CreateNodeContainer();
			Assert.IsFalse(target.HasAttributes);
		}

		[TestMethod()]
		public void HasAttributesGetShouldReturnFalseWhenCollectionHasNoElements()
		{
			NodeContainer target = CreateNodeContainer();
			AttributeCollection c = target.Attributes;
			Assert.IsFalse(target.HasAttributes);
		}

		[TestMethod()]
		public void HasAttributesGetShouldReturnTrueWhenCollectionHasElements()
		{
			NodeContainer target = CreateNodeContainer();
			target.Attributes.Add(new LTAF.TagParser.Attribute("prefix", "localName", "value"));
			Assert.IsTrue(target.HasAttributes);
		}

		[TestMethod]
		public void NodesGetShouldReturnNewNodesCollectionWhenFirstCall()
		{
			NodeContainer target = CreateNodeContainer();
			Assert.AreEqual(0, target.Nodes.Count);
		}

		[TestMethod]
		public void NodesGetShouldReturnExistingNodesCollectionWhenSecondCall()
		{
			NodeContainer target = CreateNodeContainer();
			Assert.AreEqual(0, target.Nodes.Count);
			target.Nodes.Add(new MockNode());
			Assert.AreEqual(1, target.Nodes.Count);
		}

		[TestMethod()]
		public void HasChildNodesGetShouldReturnFalseWhenNoCollection()
		{
			NodeContainer target = CreateNodeContainer();
			Assert.IsFalse(target.HasChildNodes);
		}

		[TestMethod()]
		public void HasChildNodesGetShouldReturnFalseWhenCollectionHasNoElements()
		{
			NodeContainer target = CreateNodeContainer();
			NodeCollection c = target.Nodes;
			Assert.IsFalse(target.HasAttributes);
		}

		[TestMethod()]
		public void HasChildNodesGetShouldReturnTrueWhenCollectionHasElements()
		{
			NodeContainer target = CreateNodeContainer();
			target.Nodes.Add(new MockNode());
			Assert.IsTrue(target.HasChildNodes);
		}

		internal virtual NodeContainer CreateNodeContainer()
		{
			NodeContainer target = new MockNodeContainer();
			return target;
		}
	}
}


text:
* Up-to-date versions of `git`, `go` etc
* Install GitHub release tool `go get github.com/weaveworks/github-release`
* Create a [github token for
  github-release](https://help.github.com/articles/creating-an-access-token-for-command-line-use/);
set and export `$GITHUB_TOKEN` with this value
* Update all dependencies with `make update`
* Ensure you are still on the right branch, since Go may switch to `master` as part of `make update`

## Release Types

The release script behaves differently depending on the kind of
release you are doing. There are three types:

* **Mainline** - a release (typically from master) with version tag
  `vX.Y.Z` where Z is zero (e.g. `v2.1.0`)
* **Branch** - a bugfix release (typically from a branch) with version tag
  `vX.Y.Z` where Z is non-zero (e.g `v2.1.1`)
* **Prerelease** - a release from an arbitrary branch with an arbitrary
  version tag (e.g. `feature-preview-20150904`)

N.B. the release script _infers the release type from the format of the
version tag_. Ensure your tag is in the correct format and the desired
behaviours for that type of release will be obtained from the script.

## Build Phase
### Update CHANGELOG.md

* Checkout the branch from which you wish to release
* Choose a version tag (see above) henceforth referred to as `$TAG`.
* Add a changelog entry for the new tag at the top of `CHANGELOG.md`.
  The first line must be a markdown header of the form `## Release
  $TAG` for **Prerelease** builds, `## Release ${TAG#v}` otherwise.

Commit the changelog update:

    git commit -m "Add release $TAG" CHANGELOG.md

### Create Version Tag

Next you must tag the changelog commit with `$TAG`

    git tag -a -m "Release $TAG" $TAG

### Execute Build

You are now ready to perform the build. If you have skipped the
previous steps (e.g. because you're doing a rebuild), you must ensure
that `HEAD` points to the tagged commit. You may then execute

    bin/release build

This has the following effects:

* `git tag --points-at HEAD` is used to determine `$TAG` (hence the
  `HEAD` requirement)
* Your *local* repository is cloned into `releases/$TAG`
* `CHANGELOG.md` is checked to ensure it has an entry for `$TAG`
* Distributables injected with `$TAG` are built
* Tests are executed

## Draft Phase
### Push Version Tag Upstream

First you must push your branch and version tag upstream, so that an
associated GitHub release may be created:

    git push git@github.com:weaveworks/weave
    git push git@github.com:weaveworks/weave $TAG

N.B. if you're testing the release process, push to your fork
instead!

### Create Draft Release

You're now ready to draft your release notes:

    bin/release draft

This has the following effects:

* A [release](https://help.github.com/articles/about-releases) is
  created in GitHub for `$TAG`. This release is in the draft state, so
  it is only visible to contributors; for **Prerelease** builds the
  pre-release attribute will also be set
* The `weave` script is uploaded as an attachment to the release

Navigate to https://github.com/weaveworks/weave/releases, 'Edit' the
draft and input the release notes. When you are done make sure you
'Save draft' (and not 'Publish release'!).

Once the release notes have passed review, proceed to the publish
phase.

## Publish Phase
### Move/Force Push `latest_release` Tag

This step must only be performed for **Mainline** and **Branch**
releases:

    git tag -af -m "Release $TAG" latest_release $TAG
    git push -f git@github.com:weaveworks/weave latest_release

The `latest_release` tag *must* point at `$TAG`, *not* at `HEAD` -
the build script will complain otherwise.

N.B. if you're testing the release process, push to your fork
instead!

### Publish Release & Distributable Artefacts

You can now publish the release and upload the remaining
distributables to DockerHub:

    bin/release publish

The effects of this step depend on the inferred release type. The
following occurs for all types:

* Docker images are tagged `$TAG` and pushed to DockerHub
* GitHub release moves from draft to published state

Additionally, for **Mainline** and **Branch** types:

* Release named `latest_release` is updated on GitHub

Finally, for **Mainline** releases only:

* Images tagged `latest` are updated on DockerHub

### Finish up

* If not on master, merge branch into master and push to GitHub.
* Merge the branch you are on into `latest_doc_release_updates` and push to GitHub.
* Close the [milestone](https://github.com/weaveworks/weave/milestones) in GitHub and create the next milestone
* Update the `#weavenetwork` topic heading on freenode (requires 'chanops' permission)

## Troubleshooting

There's a few things that can go wrong.

 * If the build is wonky, e.g., the tests don't pass, you can delete
   the directory in `./releases/`, fix whatever it is, move the
   version tag (which should still be only local) and have another go.
 * If the DockerHub pushes fail (which sadly seems to happen a lot),
   you can just run `./bin/release publish` again.
 * If you need to overwrite a release you can do so by manually
   deleting the GitHub version release and re-running the process.
   Please note that the DockerHub `latest` images, GitHub
   `latest_release` and download links may be in an inconsistent state
   until the overwrite is completed.


text:
package cn.luo.yuan.maze.server.servcie;

import cn.luo.yuan.maze.model.*;
import cn.luo.yuan.maze.model.goods.Goods;
import cn.luo.yuan.maze.model.skill.Skill;
import cn.luo.yuan.maze.persistence.DataManagerInterface;
import cn.luo.yuan.serialize.ObjectTable;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * Created by luoyuan on 2017/9/19.
 */
public class ServerDataManager implements DataManagerInterface {
    private Hero hero;
    private NeverEndConfig config;
    public ServerDataManager(Hero hero, NeverEndConfig config){
        this.hero = hero;
        this.config = config;
    }

    @Override
    public ObjectTable<NPCLevelRecord> getNPCTable() {
        return null;
    }

    @Override
    public Goods loadGoods(String name) {
        return null;
    }

    @Override
    public List<Skill> loadAllSkill() {
        return Arrays.asList(hero.getSkills());
    }

    @Override
    public void save(IDModel o) {

    }

    @Override
    public void add(IDModel o) {

    }

    @Override
    public List<Pet> loadPets(int start, int rows, String keyWord, Comparator<Pet> comparator) {
        return new ArrayList<>(hero.getPets());
    }

    @Override
    public void saveSkill(Skill skill) {

    }

    @Override
    public Skill loadSkill(String name) {
        for(Skill s : hero.getSkills()){
            if(s.getClass().getSimpleName().equals(name)){
                return s;
            }
        }
        return null;
    }

    @Override
    public Accessory findAccessoryByName(@NotNull String name) {
        return null;
    }

    @NotNull
    @Override
    public List<Pet> findPetByType(@NotNull String type) {
        return Collections.emptyList();
    }

    @Override
    public void saveAccessory(Accessory accessory) {

    }

    @Override
    public void savePet(@NotNull Pet pet) {

    }

    @Override
    public NeverEndConfig loadConfig() {
        return config;
    }
}


text:
package com.xianyue.retrofit.service;

import com.xianyue.retrofit.BaseMockServer;
import com.xianyue.retrofit.endpoint.GitHubEndPoint;
import java.io.IOException;
import java.util.Map;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class GitHubServiceTest extends BaseMockServer{

    @Autowired
    private GitHubEndPoint gitHubEndPoint;

    @Test
    public void getUserInfo() throws IOException {
        Map<String, Object> infos = gitHubEndPoint.getUserInfo().execute().body();
        System.out.println(infos);
    }

    @Override
    public String identify() {
        return "git";
    }
}


text:
package org.dnwiebe.orienteer;

import org.dnwiebe.orienteer.converters.Converter;
import org.dnwiebe.orienteer.converters.Converters;
import org.dnwiebe.orienteer.helpers.Fragmenter;
import org.dnwiebe.orienteer.helpers.Fragments;
import org.dnwiebe.orienteer.lookups.Lookup;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.logging.Logger;

/**
 * Created by dnwiebe on 2/17/17.
 */

/**
 * Main public class for Orienteer.
 */
public class Orienteer {
  Converters converters = new Converters ();
  Fragmenter fragmenter = new Fragmenter ();
  boolean initialCheck = true;
  Logger logger = Logger.getLogger (Orienteer.class.getName ());

  /**
   * Add a type Converter for general use to enable a new return type to be mentioned in the configuration interface
   * passed to Orienteer.make().  If you add multiple Converters that all produce the same type, only the last will be
   * used.
   * @param converter Custom Converter for the new type.
   * @return Orienteer object for operation chaining.
   */
  public Orienteer addConverter (Converter converter) {
    return addConverter (converter, null);
  }

  /**
   * Add a type Converter for use only on values returned from a particular kind of Lookup, to enable a new return type
   * to be mentioned in the configuration interface passed to Orienteer.make().  If you add multiple Converters that
   * all produce the same type for the same Lookup class, only the last will be used.
   * @param converter Custom Converter for the new type.
   * @param lookupType Only use this converter for configuration values from a Lookup of this type.
   * @return Orienteer object for operation chaining.
   */
  public <T extends Lookup> Orienteer addConverter (Converter converter, Class<T> lookupType) {
    try {
      Method convertMethod = converter.getClass ().getMethod ("convert", String.class);
      Class targetType = convertMethod.getReturnType ();
      converters.add (targetType, lookupType, converter);
    }
    catch (Exception e) {
      throw new IllegalStateException (e);
    }
    return this;
  }

  /**
   * Call this if for some reason you don't want make() to run its standard initial check to make sure all the
   * configuration values are readable.
   * @return Orienteer object for operation chaining.
   */
  public Orienteer inhibitInitialCheck () {
    initialCheck = false;
    return this;
  }

  /**
   * Manufacture and return an object of a class that implements the provided interface, such that methods called
   * on that object will produce the highest-priority configuration values available for them.
   *
   * The provided interface must contain only methods that accept no parameters and return object (not primitive or
   * void) types.
   *
   * Immediately upon creating the object, Orienteer will call all its methods to make sure seeking values does not
   * throw exceptions.  However, if a value is readily provided at make() time, but is not as forthcoming when it is
   * sought later, you may get exceptions at runtime past startup.
   *
   * @param singletonInterface Interface for configuration object
   * @param lookups Lookups to be consulted in order of priority.  If a particular Lookup successfully provides a
   *                configuration value, later-specified Lookups are not consulted.
   * @return Object of a generated class that implements singletonInterface.
   */
  public <T> T make (Class<T> singletonInterface, Lookup... lookups) {
    validateInterface (singletonInterface);
    T singleton = (T)Proxy.newProxyInstance (
        Orienteer.class.getClassLoader(),
        new Class[] {singletonInterface},
        new ConfigurationHandler(fragmenter, lookups, converters, logger)
    );
    if (initialCheck) {verifyAccess (singletonInterface, singleton);}
    return singleton;
  }

  private void validateInterface (Class singletonInterface) {
    validateClassObject (singletonInterface);
    Method[] methods = singletonInterface.getMethods ();
    for (Method method : methods) {
      validateReturnType (method);
      validateParameters (method);
    }
  }

  private void validateClassObject (Class singletonInterface) {
    if (!singletonInterface.isInterface ()) {
      throw new IllegalArgumentException ("Configuration singletons must be built on interfaces, not classes like " +
          singletonInterface.getName () + ".");
    }
  }

  private void validateReturnType (Method method) {
    if (!converters.getTargetTypes ().contains (method.getReturnType())) {
      StringBuilder buf = new StringBuilder();
      for (Class type : converters.getTargetTypes()) {
        if (buf.length() > 0) {
          buf.append(", ");
        }
        buf.append(type.getName());
      }
      throw new IllegalArgumentException("The " + method.getName() + " method of the " +
          method.getDeclaringClass().getName() +
          " interface returns type " + method.getReturnType ().getName () +
          ". Methods on configuration interfaces must return one of the following types: " + buf.toString ()
      );
    }
  }

  private void validateParameters (Method method) {
    if (method.getParameterTypes ().length > 0) {
      throw new IllegalArgumentException("The " + method.getName() + " method of the " +
          method.getDeclaringClass().getName() +
          " interface takes a parameter. Methods on configuration interfaces must be parameterless."
      );
    }
  }

  private <T> void verifyAccess (Class<T> type, T singleton) {
    Method[] methods = type.getMethods ();
    List<String> problems = new ArrayList<String> ();
    for (Method method : methods) {
      try {
        method.invoke (singleton);
      }
      catch (IllegalAccessException e) {
        // never happen
        throw new IllegalStateException (e);
      }
      catch (InvocationTargetException e) {
        Throwable cause = e.getCause ();
        logger.severe (dumpStackTrace (cause));
        problems.add (method.getName ());
      }
    }
    if (!problems.isEmpty ()) {
      throw new IllegalStateException ("Couldn't retrieve configurations: " + join (problems));
    }
  }

  private String dumpStackTrace (Throwable e) {
    StringWriter sw = new StringWriter ();
    PrintWriter pw = new PrintWriter (sw);
    e.printStackTrace (pw);
    return sw.toString ();
  }

  private String join (List<String> list) {
    StringBuilder buf = new StringBuilder ();
    for (String string : list) {
      if (buf.length () > 0) {buf.append (", ");}
      buf.append (string);
    }
    return buf.toString ();
  }

  private static class ConfigurationHandler implements InvocationHandler {
    private final Lookup[] lookups;
    private final Converters converters;
    private final Fragmenter fragmenter;
    private final Logger logger;

    ConfigurationHandler(Fragmenter fragmenter, Lookup[] lookups, Converters converters, Logger logger) {
      this.fragmenter = fragmenter;
      this.lookups = new Lookup[lookups.length];
      for (int i = 0; i < lookups.length; i++) {this.lookups[i] = lookups[i];}
      this.converters = converters;
      this.logger = logger;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      logger.info ("Seeking configuration value for '" + method.getName () + "'");
      List<String> fragments = getFragments (method);
      for (Lookup lookup : lookups) {
        String name = lookup.nameFromFragments (fragments);
        String value = lookup.valueFromName (name, method.getDeclaringClass ());
        Object result = processValue (method, lookup, name, value);
        if (result != null) {return result;}
      }
      logger.warning ("NOT CONFIGURED: " + method.getDeclaringClass ().getName () + "." + method.getName () + "()");
      return null;
    }

    private List<String> getFragments (Method method) {
      Fragments annotation = method.getAnnotation (Fragments.class);
      if (annotation != null) {
        return Arrays.asList (annotation.value ());
      }
      else {
        return fragmenter.fragment (method.getName ());
      }
    }

    private Object processValue (Method method, Lookup lookup, String name, String value) throws Exception {
      String logPreamble = "  Consulting " + lookup.getName () + " for '" + name + "': ";
      if (value == null) {
        logger.info (logPreamble + "not found");
        return null;
      }
      else {
        Converter<?> converter = converters.find (method.getReturnType (), lookup.getClass ());
        Object result = converter.convert (value);
        logger.info (logPreamble + "found '" + result + "'");
        logger.info ("Configured: " + method.getDeclaringClass().getName () + "." + method.getName () +
            "() <- " + result);
        return result;
      }
    }
  }

}


text:
layout: default
title: Changes for 0.0.4
no_toc: true
---

# Changelog for release 0.0.4-alpha (11/19/2014)

This release focuses mostly on new features and bug fixing.

- Added experimental support for MariaDB / MySQL / MySQL Cluster. See
        Using DeepDive with MySQL for
        details, including limitations of the current support. The code base was
        refactored to make it much easier to add support for additional DBMS in the
        future.
- Ported [Tuffy](http://i.stanford.edu/hazy/tuffy/doc/) to DeepDive. It is now
        possible to run Tuffy programs for Markov Logic Networks on DeepDive. See
        Markov Logic Networks for details.
- Added a graphical interface called *Mindtagger* to label data products for
        estimating precision/recall.  See [Labeling Data Products of
        DeepDive](../labeling.md) and files under `examples/labeling/` in
        the source tree.
- Added support for the `DEEPDIVE_HOME` environmental variable. It's now possible
        to run applications from any location, when this variable is set. See
        [Installation](../installation.md) for details.
- Added support for `-c datacopies` to the DimmWitted sampler (Linux only!).
        This allows to control the number of replications of the data. It is useful
        for performing inference on very large factor graphs while leveraging on
        NUMA. See [The DimmWitted High-Speed Sampler](../sampler.md) for
        details.
- Fixed integer overflow bug (and use of scientific notation) in `tobinary.py`.
        This allows to use DeepDive for inference on very large factor graphs.
- Fix a bug when using multinomial and GreenPlum: the mapping from weight ID and
  weight description is not consistent
- Fixed various bugs (including known JDBC bug) that prevented DeepDive from
        performing inference on very large factor graphs.


text:
module GamesHelper
  # boolean check on whether currently logged in user is a host
  def current_user_is_host?
    logged_in? && (current_user.id == @game.host_id)
    # binding.pry
  end

  # boolean check on whether currently logged in user is signed up for game
  def current_user_signed_up?
    logged_in? && !current_user_is_host? && @game.players.include?(current_user)
  end
end


text:
use std::intrinsics::abort;
use std::cmp::min;

pub struct StreamHandler {
    max_packet: uint,
    data1: bool,
    buf: Option<*mut u8>,
    transfer_size: uint,
    position: uint,
}

impl StreamHandler {
    /// Create a new StreamHandler
    pub fn new(max: uint) -> StreamHandler {
        StreamHandler {
            max_packet: max,
            data1: false,
            buf: None,
            transfer_size: 0,
            position: 0,
        }
    }

    /// Prepare to receive setup transaction
    pub fn setup(&mut self, buf: &mut [u8], data1: bool) {
        // Ensure there is no pending transaction
        if self.transfer_size != 0 {
            unsafe { abort(); }
        }

        // Save dst buffer
        self.position = 0;
        self.transfer_size = buf.len();
        self.buf = Some(buf.as_mut_ptr());

        // Set data toggle
        self.data1 = data1;
    }

    /// Update state, return true if finished
    pub fn on_token(&mut self, length: uint) -> bool {
        // Update counters
        self.transfer_size -= length;
        self.position += length;

        // Find out if transfer is finished
        // TODO: Need to know the max packet size to detect short transaction
        if self.transfer_size == 0 || length < self.max_packet {
            // TODO: Reset stream

            true
        } else {
            // Toggle DATA01
            self.data1 = !self.data1;
            false
        }
    }

    pub fn address(&self) -> *mut u8 {
        self.buf.unwrap()
    }

    pub fn len(&self) -> uint {
        min(self.max_packet, self.transfer_size)
    }

    pub fn data1(&self) -> bool {
        self.data1
    }
}


text:
@import MediaPlayer;
#import "ViewController.h"
#import "PlaylistDataSource.h"
#import "SamplePlaylistItem.h"
#import "PlaylistHeaderView.h"

@interface ViewController () <MPMediaPickerControllerDelegate>

@property (nonatomic) MPMediaItemCollection *playlist;
@property (nonatomic) MPMusicPlayerController *player;
@property (nonatomic) UIBarButtonItem *playButton;

@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
@property (nonatomic, weak) IBOutlet Playerbar *playerBar;
@property (nonatomic, weak) IBOutlet UIView *headerContainerView;
@property (nonatomic) IBOutlet PlaylistDataSource *playlistDataSource;
@end

@implementation ViewController

#pragma mark - View Lifecycle Methods

- (void)viewDidLoad {
    [super viewDidLoad];
    self.player = [[MPMusicPlayerController alloc] init];

    // Place the collection view slightly under the Navbar
    self.collectionView.contentInset = UIEdgeInsetsMake(-64, 0, 44, 0);

    // Set-up CollectionView Header to display playing song
    UINib *headerNib = [UINib nibWithNibName:@"PlaylistHeaderView"
                                      bundle:nil];
    NSArray *objects = [headerNib instantiateWithOwner:self
                                              options:nil];

    UICollectionViewFlowLayout *flowlayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;

    CGSize itemSize = flowlayout.itemSize;
    itemSize.width = self.view.frame.size.width;
    flowlayout.itemSize = itemSize;

    PlaylistHeaderView *header = [objects firstObject];
    [self.headerContainerView addSubview:header];

#if TARGET_IPHONE_SIMULATOR // In Simulator Add Sample Playlist Items
    NSArray *items = @[
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"inutero.jpg"] artist:@"Nirvana" title:@"Heart-Shaped Box"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"inrainbows.jpg"] artist:@"Radiohead" title:@"House of Cards"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"aenima.jpg"] artist:@"Tool" title:@"Forty-six and Two"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"meddle.jpg"] artist:@"Pink Floyd" title:@"Echoes"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"andjustice.jpg"] artist:@"Metallica" title:@"One"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"bloodsugar.jpg"] artist:@"Red Hot Chili Peppers" title:@"Give it Away"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"inrainbows.jpg"] artist:@"Radiohead" title:@"House of Cards"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"ten.jpg"] artist:@"Pearl Jam" title:@"Ten"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"darkside.jpg"] artist:@"Pink Floyd" title:@"The Great Gig in the Sky"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"dummy.jpg"] artist:@"Portishead" title:@"Strangers"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"suburbs.jpg"] artist:@"Arcade Fire" title:@"Modern Man"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"housesoftheholy.jpg"] artist:@"Led Zeppelin" title:@"No Quarter"],
                       [[SamplePlaylistItem alloc] initWithImage:[UIImage imageNamed:@"kindofblue.jpg"] artist:@"Miles Davis" title:@"Freddie Freeloader"]
                       ];

    self.playlistDataSource.items = items;
    self.playerBar.enabled = YES;
#endif

    // set the playlist header view to the header subview
    self.playlistDataSource.playlistHeaderView = header;
}

#pragma mark - Player Actions

- (IBAction)addMusic:(id)sender {
    MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
    mediaPicker.prompt = @"Add music to your playlist";
    mediaPicker.showsCloudItems = YES;
    mediaPicker.delegate = self;
    mediaPicker.allowsPickingMultipleItems = YES;
    [self presentViewController:mediaPicker animated:YES completion:nil];
}

- (void)playPause {
    if (self.player.playbackState == MPMusicPlaybackStatePlaying) {
        [self.player pause];
        [self.playerBar setPlayButtonState:NO];
    } else {
        [self.player play];
        [self.playerBar setPlayButtonState:YES];
    }
}

- (IBAction)playPauseToggle:(id)sender {
    [self playPause];
}

- (UIBarButtonItem *)playButtonItemForPlaybackState:(MPMusicPlaybackState)playbackState {
    UIBarButtonSystemItem systemItem;
    if (playbackState == MPMusicPlaybackStatePlaying) {
        // if playing set the button to pause
        systemItem = UIBarButtonSystemItemPause;
    } else {
        // otherwise set the button to play
        systemItem = UIBarButtonSystemItemPlay;
    }

    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:systemItem
                                                                                target:self
                                                                                action:@selector(playPauseToggle:)];
    return buttonItem;
}

#pragma mark - MPMediaPickerController Delegate Methods

- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {

    if (!self.playlist) {
        self.playlist = mediaItemCollection;
    } else {
        NSMutableArray *items = [NSMutableArray arrayWithCapacity:self.playlist.count + mediaItemCollection.count];
        [items addObject:self.playlist];
        [items addObject:mediaItemCollection];
        MPMediaItemCollection *collection = [MPMediaItemCollection collectionWithItems:items];
        self.playlist = collection;
    }

    self.playerBar.enabled = YES;

    // Console Output
    int index = 1;
    for (MPMediaItem *item in self.playlist.items) {
        NSLog(@"%d) %@ - %@", index++, item.artist, item.title);
    }

    [self.player setQueueWithItemCollection:self.playlist];
    self.playlistDataSource.items = self.playlist.items;

    if (self.player.playbackState != MPMusicPlaybackStatePlaying) {
        [self.player play];
    }

    NSLog(@"%@", NSStringFromSelector(_cmd));
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Playerbar Delegate Methods

- (void)playerbarPreviousTrack:(Playerbar *)playerbar {
    self.playlistDataSource.currentTrackIndex -= 1;
}

- (void)playerbarNextTrack:(Playerbar *)playerbar {
    self.playlistDataSource.currentTrackIndex += 1;
}

- (void)playerbarPlayPause:(Playerbar *)playerbar {
    [self playPause];
}

@end


text:
void log_func_var(int level, const char* fmt, ...);
void logFileOpen(const std::string& logFile);

#define LOG_ERROR(msg, ...)   log_func_var(LLL_ERR, msg, ##__VA_ARGS__)
#define LOG_WARNING(msg, ...) log_func_var(LLL_WARN, msg, ##__VA_ARGS__)
#define LOG_INFO(msg, ...)    log_func_var(LLL_NOTICE, msg, ##__VA_ARGS__)


text:
annotationSchema = new SimpleSchema({
  "authorReference" : {
    type: ReferenceSchema
    },
  "authorString" : {
    type: String
    },
  "time" : {
    type: DateTime
    },
  "text" : {
    type: String
    }
});


text:
using System;
using TrackableEntities.Patterns;
using WebApiSample.Service.Persistence.Repositories;

namespace WebApiSample.Service.Persistence.UnitsOfWork
{
    public interface INorthwindUnitOfWork : IUnitOfWork, IUnitOfWorkAsync
    {
        ICustomerRepository CustomerRepository { get; }
        IOrderRepository OrderRepository { get; }
    }
}


text:
<?php

/**
 * Base class for working with Jetpack Modules.
 */
abstract class Jetpack_JSON_API_Modules_Endpoint extends Jetpack_JSON_API_Endpoint {

	protected $modules = array();

	protected $bulk = true;

	static $_response_format = array(
		'id'          => '(string)   The module\'s ID',
		'active'      => '(boolean)  The module\'s status.',
		'name'        => '(string)   The module\'s name.',
		'description' => '(safehtml) The module\'s description.',
		'sort'        => '(int)      The module\'s display order.',
		'introduced'  => '(string)   The Jetpack version when the module was introduced.',
		'changed'     => '(string)   The Jetpack version when the module was changed.',
		'free'        => '(boolean)  The module\'s Free or Paid status.',
		'module_tags' => '(array)    The module\'s tags.',
		'override'    => '(string)   The module\'s override. Empty if no override, otherwise \'active\' or \'inactive\'',
	);

	protected function result() {

		$modules = $this->get_modules();

		if ( ! $this->bulk && ! empty( $modules ) ) {
			return array_pop( $modules );
		}

		return array( 'modules' => $modules );

	}

	/**
	 * Walks through either the submitted modules or list of themes and creates the global array
	 * @param $theme
	 *
	 * @return bool
	 */
	protected function validate_input( $module) {
		$args = $this->input();
		// lets set what modules were requested, and validate them
		if ( ! isset( $module ) || empty( $module ) ) {

			if ( ! $args['modules'] || empty( $args['modules'] ) ) {
				return new WP_Error( 'missing_module', __( 'You are required to specify a module.', 'jetpack' ), 400 );
			}
			if ( is_array( $args['modules'] ) ) {
				$this->modules = $args['modules'];
			} else {
				$this->modules[] = $args['modules'];
			}
		} else {
			$this->modules[] = urldecode( $module );
			$this->bulk = false;
		}

		if ( is_wp_error( $error = $this->validate_modules() ) ) {
			return $error;
		}

		return parent::validate_input( $module );
	}

	/**
	 * Walks through submitted themes to make sure they are valid
	 * @return bool|WP_Error
	 */
	protected function validate_modules() {
		foreach ( $this->modules as $module ) {
			if ( ! Jetpack::is_module( $module ) ) {
				return new WP_Error( 'unknown_jetpack_module', sprintf( __( 'Module not found: `%s`.', 'jetpack' ), $module ), 404 );
			}
		}
		return true;
	}

	protected static function format_module( $module_slug ) {
		$module_data = Jetpack::get_module( $module_slug );

		$module = array();
		$module['id']                = $module_slug;
		$module['active']            = Jetpack::is_module_active( $module_slug );
		$module['name']              = $module_data['name'];
		$module['short_description'] = $module_data['description'];
		$module['sort']              = $module_data['sort'];
		$module['introduced']        = $module_data['introduced'];
		$module['changed']           = $module_data['changed'];
		$module['free']              = $module_data['free'];
		$module['module_tags']       = $module_data['module_tags'];

		$overrides_instance = Jetpack_Modules_Overrides::instance();
		$module['override']         = $overrides_instance->get_module_override( $module_slug );

		// Fetch the HTML formatted long description
		ob_start();
		/** This action is documented in class.jetpack-modules-list-table.php */
		do_action( 'jetpack_module_more_info_' . $module_slug );
		$module['description']  = ob_get_clean();

		return $module;
	}

	/**
	 * Format a list of modules for public display, using the supplied offset and limit args
	 * @uses   WPCOM_JSON_API_Endpoint::query_args()
	 * @return array         Public API modules objects
	 */
	protected function get_modules() {
		$modules = array_values( $this->modules );
		// do offset & limit - we've already returned a 400 error if they're bad numbers
		$args = $this->query_args();

		if ( isset( $args['offset'] ) )
			$modules = array_slice( $modules, (int) $args['offset'] );
		if ( isset( $args['limit'] ) )
			$modules = array_slice( $modules, 0, (int) $args['limit'] );

		return array_map( array( $this, 'format_module' ), $modules );
	}

}


text:
package org.apache.batik.apps.svgbrowser;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JCheckBox;
import javax.swing.JLabel;

import org.apache.batik.util.gui.ExtendedGridBagConstraints;

/**
 * This class represents a panel to choose the color model
 * of the PNG, i.e. RGB or INDEXED.
 *
 * @author Jun Inamori
 * @version $Id$
 */
public class PNGOptionPanel extends OptionPanel {

    /**
     * The check box for outputing an indexed PNG.
     */
    protected JCheckBox check;

    /**
     * Creates a new panel.
     */
    public PNGOptionPanel() {
        super(new GridBagLayout());

        ExtendedGridBagConstraints constraints =
            new ExtendedGridBagConstraints();

        constraints.insets = new Insets(5, 5, 5, 5);
        constraints.weightx = 0;
        constraints.weighty = 0;
        constraints.fill = GridBagConstraints.NONE;
        constraints.setGridBounds(0, 0, 1, 1);
        add(new JLabel(resources.getString("PNGOptionPanel.label")),
            constraints);

        check = new JCheckBox();

        constraints.weightx = 1.0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.setGridBounds(1, 0, 1, 1);
        add(check, constraints);
    }

    /**
     * Returns if indexed or not
     */
    public boolean isIndexed() {
        return check.isSelected();
    }

    /**
     * Shows a dialog to choose the indexed PNG.
     */
    public static boolean showDialog(Component parent) {
        String title = resources.getString("PNGOptionPanel.dialog.title");
        PNGOptionPanel panel = new PNGOptionPanel();
        Dialog dialog = new Dialog(parent, title, panel);
        dialog.pack();
        dialog.setVisible(true);
        return panel.isIndexed();
    }
}