text:
<?php
	//include pmprogateway
	require_once(dirname(__FILE__) . "/class.pmprogateway.php");

	//load classes init method
	add_action('init', array('PMProGateway_cybersource', 'init'));

	class PMProGateway_cybersource extends PMProGateway
	{
		function PMProGateway_cybersource($gateway = NULL)
		{
			if(!class_exists("CyberSourceSoapClient"))
				require_once(dirname(__FILE__) . "/../../includes/lib/CyberSource/cyber_source_soap_client.php");

			$this->gateway = $gateway;
			return $this->gateway;
		}

		/**
		 * Run on WP init
		 *
		 * @since 1.8
		 */
		static function init()
		{
			//make sure CyberSource is a gateway option
			add_filter('pmpro_gateways', array('PMProGateway_cybersource', 'pmpro_gateways'));

			//add fields to payment settings
			add_filter('pmpro_payment_options', array('PMProGateway_cybersource', 'pmpro_payment_options'));
			add_filter('pmpro_payment_option_fields', array('PMProGateway_cybersource', 'pmpro_payment_option_fields'), 10, 2);
		}

		/**
		 * Make sure this gateway is in the gateways list
		 *
		 * @since 1.8
		 */
		static function pmpro_gateways($gateways)
		{
			if(empty($gateways['cybersource']))
				$gateways['cybersource'] = __('CyberSource', 'pmpro');

			return $gateways;
		}

		/**
		 * Get a list of payment options that the this gateway needs/supports.
		 *
		 * @since 1.8
		 */
		static function getGatewayOptions()
		{
			$options = array(
				'sslseal',
				'nuclear_HTTPS',
				'gateway_environment',
				'cybersource_merchantid',
				'cybersource_securitykey',
				'currency',
				'use_ssl',
				'tax_state',
				'tax_rate',
				'accepted_credit_cards'
			);

			return $options;
		}

		/**
		 * Set payment options for payment settings page.
		 *
		 * @since 1.8
		 */
		static function pmpro_payment_options($options)
		{
			//get stripe options
			$cybersource_options = PMProGateway_cybersource::getGatewayOptions();

			//merge with others.
			$options = array_merge($cybersource_options, $options);

			return $options;
		}

		/**
		 * Display fields for this gateway's options.
		 *
		 * @since 1.8
		 */
		static function pmpro_payment_option_fields($values, $gateway)
		{
		?>
		<tr class="pmpro_settings_divider gateway gateway_cybersource" <?php if($gateway != "cybersource") { ?>style="display: none;"<?php } ?>>

				<?php _e('CyberSource Settings', 'pmpro'); ?>

		<tr class="gateway gateway_cybersource" <?php if($gateway != "cybersource") { ?>style="display: none;"<?php } ?>>

				<?php _e('Note', 'pmpro');?>: <?php _e('This gateway option is in beta. Some functionality may not be available. Please contact Paid Memberships Pro with any issues you run into. Please be sure to upgrade Paid Memberships Pro to the latest versions when available.', 'pmpro');?>

		<tr class="gateway gateway_cybersource" <?php if($gateway != "cybersource") { ?>style="display: none;"<?php } ?>>

				<?php _e('Merchant ID', 'pmpro');?>:

				<input type="text" id="cybersource_merchantid" name="cybersource_merchantid" size="60" value="<?php echo esc_attr($values['cybersource_merchantid'])?>" />

		<tr class="gateway gateway_cybersource" <?php if($gateway != "cybersource") { ?>style="display: none;"<?php } ?>>

				<?php _e('Transaction Security Key', 'pmpro');?>:

				<textarea id="cybersource_securitykey" name="cybersource_securitykey" rows="3" cols="80"><?php echo esc_textarea($values['cybersource_securitykey']);?></textarea>

		<?php
		}

		/**
		 * Process checkout.
		 *
		 */
		function process(&$order)
		{
			//check for initial payment
			if(floatval($order->InitialPayment) == 0)
			{
				//auth first, then process
				if($this->authorize($order))
				{
					$this->void($order);
					if(!pmpro_isLevelTrial($order->membership_level))
					{
						//subscription will start today with a 1 period trial
						$order->ProfileStartDate = date("Y-m-d") . "T0:0:0";
						$order->TrialBillingPeriod = $order->BillingPeriod;
						$order->TrialBillingFrequency = $order->BillingFrequency;
						$order->TrialBillingCycles = 1;
						$order->TrialAmount = 0;

						//add a billing cycle to make up for the trial, if applicable
						if(!empty($order->TotalBillingCycles))
							$order->TotalBillingCycles++;
					}
					elseif($order->InitialPayment == 0 && $order->TrialAmount == 0)
					{
						//it has a trial, but the amount is the same as the initial payment, so we can squeeze it in there
						$order->ProfileStartDate = date("Y-m-d") . "T0:0:0";
						$order->TrialBillingCycles++;

						//add a billing cycle to make up for the trial, if applicable
						if($order->TotalBillingCycles)
							$order->TotalBillingCycles++;
					}
					else
					{
						//add a period to the start date to account for the initial payment
						$order->ProfileStartDate = date("Y-m-d", strtotime("+ " . $order->BillingFrequency . " " . $order->BillingPeriod, current_time("timestamp"))) . "T0:0:0";
					}

					$order->ProfileStartDate = apply_filters("pmpro_profile_start_date", $order->ProfileStartDate, $order);
					return $this->subscribe($order);
				}
				else
				{
					if(empty($order->error))
						$order->error = __("Unknown error: Authorization failed.", "pmpro");
					return false;
				}
			}
			else
			{
				//charge first payment
				if($this->charge($order))
				{
					//set up recurring billing
					if(pmpro_isLevelRecurring($order->membership_level))
					{
						if(!pmpro_isLevelTrial($order->membership_level))
						{
							//subscription will start today with a 1 period trial
							$order->ProfileStartDate = date("Y-m-d") . "T0:0:0";
							$order->TrialBillingPeriod = $order->BillingPeriod;
							$order->TrialBillingFrequency = $order->BillingFrequency;
							$order->TrialBillingCycles = 1;
							$order->TrialAmount = 0;

							//add a billing cycle to make up for the trial, if applicable
							if(!empty($order->TotalBillingCycles))
								$order->TotalBillingCycles++;
						}
						elseif($order->InitialPayment == 0 && $order->TrialAmount == 0)
						{
							//it has a trial, but the amount is the same as the initial payment, so we can squeeze it in there
							$order->ProfileStartDate = date("Y-m-d") . "T0:0:0";
							$order->TrialBillingCycles++;

							//add a billing cycle to make up for the trial, if applicable
							if(!empty($order->TotalBillingCycles))
								$order->TotalBillingCycles++;
						}
						else
						{
							//add a period to the start date to account for the initial payment
							$order->ProfileStartDate = date("Y-m-d", strtotime("+ " . $this->BillingFrequency . " " . $this->BillingPeriod, current_time("timestamp"))) . "T0:0:0";
						}

						$order->ProfileStartDate = apply_filters("pmpro_profile_start_date", $order->ProfileStartDate, $order);
						if($this->subscribe($order))
						{
							return true;
						}
						else
						{
							if($this->void($order))
							{
								if(!$order->error)
									$order->error = __("Unknown error: Payment failed.", "pmpro");
							}
							else
							{
								if(!$order->error)
									$order->error = __("Unknown error: Payment failed.", "pmpro");

								$order->error .= " " . __("A partial payment was made that we could not void. Please contact the site owner immediately to correct this.", "pmpro");
							}

							return false;
						}
					}
					else
					{
						//only a one time charge
						$order->status = "success";	//saved on checkout page
						return true;
					}
				}
				else
				{
					if(empty($order->error))
						$order->error = __("Unknown error: Payment failed.", "pmpro");

					return false;
				}
			}
		}

		function getCardType($name)
		{
			$card_types = array(
				'Visa' => '001',
				'MasterCard' => '002',
				'Master Card' => '002',
				'AMEX' => '003',
				'American Express' => '003',
				'Discover' => '004',
				'Diners Club' => '005',
				'Carte Blanche' => '006',
				'JCB' => '007'
			);

			if(isset($card_types[$name]))
				return $card_types[$name];
			else
				return false;
		}

		function getWSDL($order)
		{
			//which gateway environment?
			if(empty($order->gateway_environment))
				$gateway_environment = pmpro_getOption("gateway_environment");
			else
				$gateway_environment = $order->gateway_environment;

			//which host?
			if($gateway_environment == "live")
					$host = "ics2ws.ic3.com";
				else
					$host = "ics2wstest.ic3.com";

			//path
			$path = "/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.90.wsdl";

			//build url
			$wsdl_url = "https://" . $host . $path;

			//filter
			$wsdl_url = apply_filters("pmpro_cybersource_wsdl_url", $wsdl_url, $gateway_environment);

			return $wsdl_url;
		}

		function authorize(&$order)
		{
			global $pmpro_currency;

			if(empty($order->code))
				$order->code = $order->getRandomCode();

			$wsdl_url = $this->getWSDL($order);

			//what amount to authorize? just $1 to test
			$amount = "1.00";

			//combine address
			$address = $order->Address1;
			if(!empty($order->Address2))
				$address .= "\n" . $order->Address2;

			//customer stuff
			$customer_email = $order->Email;
			$customer_phone = $order->billing->phone;

			if(!isset($order->membership_level->name))
				$order->membership_level->name = "";

			//to store our request
			$request = new stdClass();

			//which service?
			$ccAuthService = new stdClass();
			$ccAuthService->run = "true";
			$request->ccAuthService = $ccAuthService;

			//merchant id and order code
			$request->merchantID = pmpro_getOption("cybersource_merchantid");
			$request->merchantReferenceCode = $order->code;

			//bill to
			$billTo = new stdClass();
			$billTo->firstName = $order->FirstName;
			$billTo->lastName = $order->LastName;
			$billTo->street1 = $address;
			$billTo->city = $order->billing->city;
			$billTo->state = $order->billing->state;
			$billTo->postalCode = $order->billing->zip;
			$billTo->country = $order->billing->country;
			$billTo->email = $order->Email;
			$billTo->ipAddress = $_SERVER['REMOTE_ADDR'];
			$request->billTo = $billTo;

			//card
			$card = new stdClass();
			$card->cardType = $this->getCardType($order->cardtype);
			$card->accountNumber = $order->accountnumber;
			$card->expirationMonth = $order->expirationmonth;
			$card->expirationYear = $order->expirationyear;
			$card->cvNumber = $order->CVV2;
			$request->card = $card;

			//currency
			$purchaseTotals = new stdClass();
			$purchaseTotals->currency = $pmpro_currency;
			$request->purchaseTotals = $purchaseTotals;

			//item/price
			$item0 = new stdClass();
			$item0->unitPrice = $amount;
			$item0->quantity = "1";
			$item0->productName = $order->membership_level->name . " Membership";
			$item0->productSKU = $order->membership_level->id;
			$item0->id = $order->membership_id;
			$request->item = array($item0);

			$soapClient = new CyberSourceSoapClient($wsdl_url, array("merchantID"=>pmpro_getOption("cybersource_merchantid"), "transactionKey"=>pmpro_getOption("cybersource_securitykey")));
			$reply = $soapClient->runTransaction($request);

			if($reply->reasonCode == "100")
			{
				//success
				$order->payment_transaction_id = $reply->requestID;
				$order->updateStatus("authorized");
				return true;
			}
			else
			{
				//error
				$order->errorcode = $reply->reasonCode;
				$order->error = $this->getErrorFromCode($reply->reasonCode);
				$order->shorterror = $this->getErrorFromCode($reply->reasonCode);
				return false;
			}
		}

		function void(&$order)
		{
			//need a transaction id
			if(empty($order->payment_transaction_id))
				return false;

			//get wsdl
			$wsdl_url = $this->getWSDL($order);

			//to store our request
			$request = new stdClass();

			//which service?
			$voidService = new stdClass();
			$voidService->run = "true";
			$voidService->voidRequestID = $order->payment_transaction_id;
			$request->voidService = $voidService;

			//merchant id and order code
			$request->merchantID = pmpro_getOption("cybersource_merchantid");
			$request->merchantReferenceCode = $order->code;

			$soapClient = new CyberSourceSoapClient($wsdl_url, array("merchantID"=>pmpro_getOption("cybersource_merchantid"), "transactionKey"=>pmpro_getOption("cybersource_securitykey")));
			$reply = $soapClient->runTransaction($request);

			if($reply->reasonCode == "100")
			{
				//success
				$order->payment_transaction_id = $reply->requestID;
				$order->updateStatus("voided");
				return true;
			}
			else
			{
				//error
				$order->errorcode = $reply->reasonCode;
				$order->error = $this->getErrorFromCode($reply->reasonCode);
				$order->shorterror = $this->getErrorFromCode($reply->reasonCode);
				return false;
			}
		}

		function charge(&$order)
		{
			global $pmpro_currency;

			//get a code
			if(empty($order->code))
				$order->code = $order->getRandomCode();

			//get wsdl
			$wsdl_url = $this->getWSDL($order);

			//what amount to charge?
			$amount = $order->InitialPayment;

			//tax
			$order->subtotal = $amount;
			$tax = $order->getTax(true);
			$amount = round((float)$order->subtotal + (float)$tax, 2);

			//combine address
			$address = $order->Address1;
			if(!empty($order->Address2))
				$address .= "\n" . $order->Address2;

			//customer stuff
			$customer_email = $order->Email;
			$customer_phone = $order->billing->phone;

			if(!isset($order->membership_level->name))
				$order->membership_level->name = "";

			//to store our request
			$request = new stdClass();

			//authorize and capture
			$ccAuthService = new stdClass();
			$ccAuthService->run = "true";
			$request->ccAuthService = $ccAuthService;

			$ccCaptureService = new stdClass();
			$ccCaptureService->run = "true";
			$request->ccCaptureService = $ccCaptureService;

			//merchant id and order code
			$request->merchantID = pmpro_getOption("cybersource_merchantid");
			$request->merchantReferenceCode = $order->code;

			//bill to
			$billTo = new stdClass();
			$billTo->firstName = $order->FirstName;
			$billTo->lastName = $order->LastName;
			$billTo->street1 = $address;
			$billTo->city = $order->billing->city;
			$billTo->state = $order->billing->state;
			$billTo->postalCode = $order->billing->zip;
			$billTo->country = $order->billing->country;
			$billTo->email = $order->Email;
			$billTo->ipAddress = $_SERVER['REMOTE_ADDR'];
			$request->billTo = $billTo;

			//card
			$card = new stdClass();
			$card->cardType = $this->getCardType($order->cardtype);
			$card->accountNumber = $order->accountnumber;
			$card->expirationMonth = $order->expirationmonth;
			$card->expirationYear = $order->expirationyear;
			$card->cvNumber = $order->CVV2;
			$request->card = $card;

			//currency
			$purchaseTotals = new stdClass();
			$purchaseTotals->currency = $pmpro_currency;
			$request->purchaseTotals = $purchaseTotals;

			//item/price
			$item0 = new stdClass();
			$item0->unitPrice = $amount;
			$item0->quantity = "1";
			$item0->productName = $order->membership_level->name . " Membership";
			$item0->productSKU = $order->membership_level->id;
			$item0->id = $order->membership_id;
			$request->item = array($item0);

			$soapClient = new CyberSourceSoapClient($wsdl_url, array("merchantID"=>pmpro_getOption("cybersource_merchantid"), "transactionKey"=>pmpro_getOption("cybersource_securitykey")));
			$reply = $soapClient->runTransaction($request);

			if($reply->reasonCode == "100")
			{
				//success
				$order->payment_transaction_id = $reply->requestID;
				$order->updateStatus("success");
				return true;
			}
			else
			{
				//error
				$order->errorcode = $reply->reasonCode;
				$order->error = $this->getErrorFromCode($reply->reasonCode);
				$order->shorterror = $this->getErrorFromCode($reply->reasonCode);
				return false;
			}
		}

		function subscribe(&$order)
		{
			global $currency;

			//create a code for the order
			if(empty($order->code))
				$order->code = $order->getRandomCode();

			//filter order before subscription. use with care.
			$order = apply_filters("pmpro_subscribe_order", $order, $this);

			//get wsdl
			$wsdl_url = $this->getWSDL($order);

			//to store our request
			$request = new stdClass();

			//set service type
			$paySubscriptionCreateService = new stdClass();
			$paySubscriptionCreateService->run = 'true';
			$paySubscriptionCreateService->disableAutoAuth = 'true';	//we do our own auth check
			$request->paySubscriptionCreateService  = $paySubscriptionCreateService;

			//merchant id and order code
			$request->merchantID = pmpro_getOption("cybersource_merchantid");
			$request->merchantReferenceCode = $order->code;

			/*
				set up billing amount/etc
			*/
			//figure out the amounts
			$amount = $order->PaymentAmount;
			$amount_tax = $order->getTaxForPrice($amount);
			$amount = round((float)$amount + (float)$amount_tax, 2);

			/*
				There are two parts to the trial. Part 1 is simply the delay until the first payment
				since we are doing the first payment as a separate transaction.
				The second part is the actual "trial" set by the admin.
			*/
			//figure out the trial length (first payment handled by initial charge)
			if($order->BillingPeriod == "Year")
				$trial_period_days = $order->BillingFrequency * 365;	//annual
			elseif($order->BillingPeriod == "Day")
				$trial_period_days = $order->BillingFrequency * 1;		//daily
			elseif($order->BillingPeriod == "Week")
				$trial_period_days = $order->BillingFrequency * 7;		//weekly
			else
				$trial_period_days = $order->BillingFrequency * 30;	//assume monthly

			//convert to a profile start date
			$order->ProfileStartDate = date("Y-m-d", strtotime("+ " . $trial_period_days . " Day", current_time("timestamp"))) . "T0:0:0";

			//filter the start date
			$order->ProfileStartDate = apply_filters("pmpro_profile_start_date", $order->ProfileStartDate, $order);

			//convert back to days
			$trial_period_days = ceil(abs(strtotime(date("Y-m-d"), current_time('timestamp')) - strtotime($order->ProfileStartDate, current_time("timestamp"))) / 86400);

			//now add the actual trial set by the site
			if(!empty($order->TrialBillingCycles))
			{
				$trialOccurrences = (int)$order->TrialBillingCycles;
				if($order->BillingPeriod == "Year")
					$trial_period_days = $trial_period_days + (365 * $order->BillingFrequency * $trialOccurrences);	//annual
				elseif($order->BillingPeriod == "Day")
					$trial_period_days = $trial_period_days + (1 * $order->BillingFrequency * $trialOccurrences);		//daily
				elseif($order->BillingPeriod == "Week")
					$trial_period_days = $trial_period_days + (7 * $order->BillingFrequency * $trialOccurrences);	//weekly
				else
					$trial_period_days = $trial_period_days + (30 * $order->BillingFrequency * $trialOccurrences);	//assume monthly
			}

			//convert back into a date
			$profile_start_date = date("Ymd", strtotime("+ " . $trial_period_days . " Days"));

			//figure out the frequency
			if($order->BillingPeriod == "Year")
			{
				$frequency = "annually";	//ignoring BillingFrequency set on level.
			}
			elseif($order->BillingPeriod == "Month")
			{
				if($order->BillingFrequency == 6)
					$frequency = "semi annually";
				elseif($order->BillingFrequency == 3)
					$frequency = "quarterly";
				else
					$frequency = "monthly";
			}
			elseif($order->BillingPeriod == "Week")
			{
				if($order->BillingFrequency == 4)
					$frequency = "quad-weekly";
				elseif($order->BillingFrequency == 2)
					$frequency = "bi-weekly";
				else
					$frequency = "weekly";
			}
			elseif($order->BillingPeriod == "Day")
			{
				if($order->BillingFrequency == 365)
					$frequency = "annually";
				elseif($order->BillingFrequency == 182)
					$frequency = "semi annually";
				elseif($order->BillingFrequency == 183)
					$frequency = "semi annually";
				elseif($order->BillingFrequency == 90)
					$frequency = "quaterly";
				elseif($order->BillingFrequency == 30)
					$frequency = "monthly";
				elseif($order->BillingFrequency == 15)
					$frequency = "semi-monthly";
				elseif($order->BillingFrequency == 28)
					$frequency = "quad-weekly";
				elseif($order->BillingFrequency == 14)
					$frequency = "bi-weekly";
				elseif($order->BillingFrequency == 7)
					$frequency = "weekly";
			}

			//set subscription info for API
			$subscription = new stdClass();
			$subscription->title = $order->membership_level->name;
			$subscription->paymentMethod = "credit card";
			$request->subscription = $subscription;

			//recurring info
			$recurringSubscriptionInfo = new stdClass();
			$recurringSubscriptionInfo->amount = number_format($amount, 2);
			$recurringSubscriptionInfo->startDate = $profile_start_date;
			$recurringSubscriptionInfo->frequency = $frequency;
			if(!empty($order->TotalBillingCycles))
				$recurringSubscriptionInfo->numberOfPayments = $order->TotalBillingCycles;
			$request->recurringSubscriptionInfo = $recurringSubscriptionInfo;

			//combine address
			$address = $order->Address1;
			if(!empty($order->Address2))
				$address .= "\n" . $order->Address2;

			//bill to
			$billTo = new stdClass();
			$billTo->firstName = $order->FirstName;
			$billTo->lastName = $order->LastName;
			$billTo->street1 = $address;
			$billTo->city = $order->billing->city;
			$billTo->state = $order->billing->state;
			$billTo->postalCode = $order->billing->zip;
			$billTo->country = $order->billing->country;
			$billTo->email = $order->Email;
			$billTo->ipAddress = $_SERVER['REMOTE_ADDR'];
			$request->billTo = $billTo;

			//card
			$card = new stdClass();
			$card->cardType = $this->getCardType($order->cardtype);
			$card->accountNumber = $order->accountnumber;
			$card->expirationMonth = $order->expirationmonth;
			$card->expirationYear = $order->expirationyear;
			$card->cvNumber = $order->CVV2;
			$request->card = $card;

			//currency
			$purchaseTotals = new stdClass();
			$purchaseTotals->currency = $pmpro_currency;
			$request->purchaseTotals = $purchaseTotals;

			$soapClient = new CyberSourceSoapClient($wsdl_url, array("merchantID"=>pmpro_getOption("cybersource_merchantid"), "transactionKey"=>pmpro_getOption("cybersource_securitykey")));
			$reply = $soapClient->runTransaction($request);

			if($reply->reasonCode == "100")
			{
				//success
				$order->subscription_transaction_id = $reply->requestID;
				$order->status = "success";
				return true;
			}
			else
			{
				//error
				$order->status = "error";
				$order->errorcode = $reply->reasonCode;
				$order->error = $this->getErrorFromCode($reply->reasonCode);
				$order->shorterror = $this->getErrorFromCode($reply->reasonCode);
				return false;
			}
		}

		function update(&$order)
		{
			//get wsdl
			$wsdl_url = $this->getWSDL($order);

			//to store our request
			$request = new stdClass();

			//set service type
			$paySubscriptionUpdateService  = new stdClass();
			$paySubscriptionUpdateService ->run = "true";
			$request->paySubscriptionUpdateService   = $paySubscriptionUpdateService ;

			//merchant id and order code
			$request->merchantID = pmpro_getOption("cybersource_merchantid");
			$request->merchantReferenceCode = $order->code;

			//set subscription info for API
			$recurringSubscriptionInfo = new stdClass();
			$recurringSubscriptionInfo->subscriptionID  = $order->subscription_transaction_id;
			$request->recurringSubscriptionInfo = $recurringSubscriptionInfo;

			//combine address
			$address = $order->Address1;
			if(!empty($order->Address2))
				$address .= "\n" . $order->Address2;

			//bill to
			$billTo = new stdClass();
			$billTo->firstName = $order->FirstName;
			$billTo->lastName = $order->LastName;
			$billTo->street1 = $address;
			$billTo->city = $order->billing->city;
			$billTo->state = $order->billing->state;
			$billTo->postalCode = $order->billing->zip;
			$billTo->country = $order->billing->country;
			$billTo->email = $order->Email;
			$billTo->ipAddress = $_SERVER['REMOTE_ADDR'];
			$request->billTo = $billTo;

			//card
			$card = new stdClass();
			$card->cardType = $this->getCardType($order->cardtype);
			$card->accountNumber = $order->accountnumber;
			$card->expirationMonth = $order->expirationmonth;
			$card->expirationYear = $order->expirationyear;
			$card->cvNumber = $order->CVV2;
			$request->card = $card;

			$soapClient = new CyberSourceSoapClient($wsdl_url, array("merchantID"=>pmpro_getOption("cybersource_merchantid"), "transactionKey"=>pmpro_getOption("cybersource_securitykey")));
			$reply = $soapClient->runTransaction($request);

			if($reply->reasonCode == "100")
			{
				//success
				return true;
			}
			else
			{
				//error
				$order->errorcode = $reply->reasonCode;
				$order->error = $this->getErrorFromCode($reply->reasonCode);
				$order->shorterror = $this->getErrorFromCode($reply->reasonCode);
				return false;
			}
		}

		function cancel(&$order)
		{
			//require a subscription id
			if(empty($order->subscription_transaction_id))
				return false;

			//get wsdl
			$wsdl_url = $this->getWSDL($order);

			//to store our request
			$request = new stdClass();

			//which service?
			$paySubscriptionDeleteService  = new stdClass();
			$paySubscriptionDeleteService ->run = "true";
			$request->paySubscriptionDeleteService  = $paySubscriptionDeleteService ;

			//which order
			$recurringSubscriptionInfo  = new stdClass();
			$recurringSubscriptionInfo->subscriptionID = $order->subscription_transaction_id;
			$request->recurringSubscriptionInfo = $recurringSubscriptionInfo;

			//merchant id and order code
			$request->merchantID = pmpro_getOption("cybersource_merchantid");
			$request->merchantReferenceCode = $order->code;

			$soapClient = new CyberSourceSoapClient($wsdl_url, array("merchantID"=>pmpro_getOption("cybersource_merchantid"), "transactionKey"=>pmpro_getOption("cybersource_securitykey")));
			$reply = $soapClient->runTransaction($request);

			if($reply->reasonCode == "100")
			{
				//success
				$order->updateStatus("cancelled");
				return true;
			}
			else
			{
				//error
				$order->errorcode = $reply->reasonCode;
				$order->error = $this->getErrorFromCode($reply->reasonCode);
				$order->shorterror = $this->getErrorFromCode($reply->reasonCode);
				return false;
			}
		}

		function getErrorFromCode($code)
		{
			$error_messages = array(
				"100" => "Successful transaction.",
				"101" => "The request is missing one or more required fields.",
				"102" => "One or more fields in the request contains invalid data. Check that your billing address is valid.",
				"104" => "Duplicate order detected.",
				"110" => "Only partial amount was approved.",
				"150" => "Error: General system failure.",
				"151" => "Error: The request was received but there was a server timeout.",
				"152" => "Error: The request was received, but a service did not finish running in time. ",
				"200" => "Address Verification Service (AVS) failure.",
				"201" => "Authorization failed.",
				"202" => "Expired card or invalid expiration date.",
				"203" => "The card was declined.",
				"204" => "Insufficient funds in the account.",
				"205" => "Stolen or lost card.",
				"207" => "Issuing bank unavailable.",
				"208" => "Inactive card or card not authorized for card-not-present transactions.",
				"209" => "American Express Card Identification Digits (CID) did not match.",
				"210" => "The card has reached the credit limit. ",
				"211" => "Invalid card verification number.",
				"221" => "The customer matched an entry on the processors negative file. ",
				"230" => "Card verification (CV) check failed.",
				"231" => "Invalid account number.",
				"232" => "The card type is not accepted by the payment processor.",
				"233" => "General decline by the processor.",
				"234" => "There is a problem with your CyberSource merchant configuration.",
				"235" => "The requested amount exceeds the originally authorized amount.",
				"236" => "Processor failure.",
				"237" => "The authorization has already been reversed.",
				"238" => "The authorization has already been captured.",
				"239" => "The requested transaction amount must match the previous transaction amount.",
				"240" => "The card type sent is invalid or does not correlate with the credit card number.",
				"241" => "The referenced request id is invalid for all follow-on transactions.",
				"242" => "The request ID is invalid.",
				"243" => "The transaction has already been settled or reversed.",
				"246" => "The capture or credit is not voidable because the capture or credit information has already been submitted to your processor. Or, you requested a void for a type of transaction that cannot be voided.",
				"247" => "You requested a credit for a capture that was previously voided.",
				"250" => "Error: The request was received, but there was a timeout at the payment processor.",
				"520" => "Smart Authorization failed."
			);

			if(isset($error_messages[$code]))
				return $error_messages[$code];
			else
				return "Unknown error.";
		}
	}


text:
<?php

namespace Anax\Threads;

/**
 * Model for Forum.
 *
 */
class Thread extends \Anax\MVC\CDatabaseModel
{

}

redpajama_set_name: RedPajamaGithub


text:
@import url("../styles.css");

.html {
    font-family: Courier New, Courier;
}

.code {
    font-family: Courier New, Courier;
}

.code-block {
    font-family: Courier New, Courier;
    margin: 1em;
}

.highlight {
    background: #FFFFE0;
}

.itf-member {
    margin: 1em 0;
    padding: 1em;
    border: 1px solid #ddd;
}

.itf-member-prototype {
    font-family: Courier New, Courier;
}

.itf-member-description {
    margin: 1em 1em 0 1em;
}

.itf-member-name {
    font-family: Courier New, Courier;
    font-weight: bold;
    color: #008;
}

.itf-member-param {
    font-family: Courier New, Courier;
    font-style: italic;
}


text:
TrafficLight
============

Simple Arduino Traffic light controlled by Android and LabVIEW (Learning project for Arduino, Android, LabVIEW WebServices)


text:
package utils.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.webkit.MimeTypeMap;

import utils.data.FileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class IntentUtil {

    /**
     * 微信包名
     */
    private static final String WEIXIN_PACKAGE = "com.tencent.mm";
    private static final String QQ_PACKAGE = "com.tencent.mobileqq";

    /**
     * 微信分享到朋友圈
     */
    private static final String WEIXIN_SHARE_TIME_LINE_COMPONENT = "com.tencent.mm.ui.tools.ShareToTimeLineUI";
    /**
     * 微信分享给朋友
     */
    private static final String WEIXIN_SHARE_FRIENDS_COMPONENT = "com.tencent.mm.ui.tools.ShareImgUI";

    /**
     * 获取符合Intent响应条件的Activity信息列表
     */
    public static List<ResolveInfo> queryIntentActivities(Context context, Intent intent) {
        return context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    }

    /**
     * 安装Apk
     */
    public static Intent installApk(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        return intent;
    }

    /**
     * 调用系统拨号功能
     *
     * @param phoneNumber 电话号码
     * @param autoCall    是否自动开始拨号
     *                    如果不支持打电话返回null(一般平板不支持打电话)
     */
    public static Intent phoneCall(Context context, String phoneNumber, boolean autoCall) {
        Intent intent;
        if (autoCall) {// 自动拨号
            intent = new Intent(Intent.ACTION_CALL);
        } else {// 打开拨号界面不自动拨号
            intent = new Intent(Intent.ACTION_DIAL);
        }
        intent.setData(Uri.parse("tel:" + phoneNumber));
        List<ResolveInfo> list = queryIntentActivities(context, intent);
        if (list.isEmpty()) {
            return null;
        }
        return intent;
    }

    /**
     * 调用系统发短信功能
     *
     * @param phoneNumber 电话号码
     */
    public static Intent sendSMS(Context context, String phoneNumber) {
        Intent intent = new Intent();
        // 系统默认的action,用来打开默认的短信界面
        intent.setAction(Intent.ACTION_SENDTO);
        // 需要发短息的号码
        intent.setData(Uri.parse("smsto:" + phoneNumber));
        List<ResolveInfo> list = queryIntentActivities(context, intent);
        if (list.isEmpty()) {
            return null;
        }
        return intent;
    }

    /**
     * 分享文字

     * 可选择多个应用: startActivity(Intent.createChooser(intent, "请选择"));

     * 也可以指定某个应用: intent.setPackage(packageName);
     *
     * @param text    文字内容
     * @param subject 主题(有些应用会忽略)
     */
    public static Intent shareText(String text, String subject) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, text);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    /**
     * 分享图片
     *
     * @param uri 本地图片,Uri.fromFile(file)或由ContentResolver获取
     */
    public static Intent shareImage(Uri uri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    /**
     * 分享图片和文字
     *
     * @param uri  本地图片,Uri.fromFile(file)或由ContentResolver获取
     * @param text 此时有些应用会忽略文字
     */
    public static Intent shareImage(Uri uri, String text, String subject) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.putExtra(Intent.EXTRA_TEXT, text);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    /**
     * 分享多个图片
     */
    public static Intent shareImage(ArrayList<Uri> uris) {
        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        intent.setType("image/*");
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    /**
     * 选择系统图片
     */
    public static Intent imagePick() {
        return new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    }

    /**
     * 调用系统相机
     */
    public static Intent camera() {
        return new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    }

    /**
     * 调用系统相机
     * 拍摄照片保存的文件Uri
     */
    public static Intent camera(Uri fileUri) {
        Intent intent = camera();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        return intent;
    }

    /**
     * 调用系统相机
     * 拍摄照片保存的文件
     */
    public static Intent camera(File file) {
        Intent intent = camera();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        return intent;
    }

    public static Intent CropIntent(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true);
        return intent;
    }

    /**
     * 发送广播以通知系统添加文件到媒体库,常用于拍照后让照片出现在图库
     */
    public static Intent addToAlbum(File file) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        return intent;
    }

    /**
     * 跳转到系统设置页面
     */
    public static Intent goSystemSetting(Uri uri) {
        return new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + "com.eelly.seller"));
    }

    /**
     * 打开应用信息的页面
     */
    public static Intent goSystemSetting(String packageName) {
//        "package:" + "com.eelly.seller"
        return goSystemSetting(Uri.parse("package:" + packageName));
    }

    /*前往应用市场*/
    public static void goGooglePlay(Context context) {
        Intent marketIntent = IntentUtil.googlePlay(context.getPackageName());
        marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (marketIntent.resolveActivity(context.getPackageManager()) != null) { // 判断应用是否存在
            context.startActivity(marketIntent);
        } else {
            ToastUtil.show(context, "请先安装应用市场");
        }
    }

    /**
     * 打开Google Play上某个应用的页面
     *
     * @param packageName 应用包名
     */
    public static Intent googlePlay(String packageName) {
        Uri uri = Uri.parse("market://details?id=" + packageName);
        return new Intent(Intent.ACTION_VIEW, uri);
    }

    /**
     * 分享图片到朋友圈
     */
    public static boolean share2WeChatCircle(Context context, File file) {
        boolean isAvliable = isAvailable(context, WEIXIN_PACKAGE);
        if (isAvliable) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(WEIXIN_PACKAGE, WEIXIN_SHARE_TIME_LINE_COMPONENT));
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_SEND);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            context.startActivity(intent);
        } else {
            ToastUtil.show(context, "请安装微信");
        }
        return isAvliable;
    }

    /**
     * 分享多张图片到朋友圈
     */
    public static boolean share2WeChatCircle(Context context, ArrayList<File> files) {
        boolean isAvliable = isAvailable(context, WEIXIN_PACKAGE);
        if (isAvliable) {
            ArrayList<Uri> uris = new ArrayList<>();
            for (File image : files) {
                Uri uri = Uri.fromFile(image);
                uris.add(uri);
            }
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(WEIXIN_PACKAGE, WEIXIN_SHARE_TIME_LINE_COMPONENT));
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
            context.startActivity(intent);
        } else {
            ToastUtil.show(context, "请安装微信");
        }
        return isAvliable;
    }

    /**
     * 直接分享图片给好友
     */
    public static boolean share2WeChatFriend(Context context, File file) {
        boolean isAvliable = isAvailable(context, WEIXIN_PACKAGE);
        if (isAvliable) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(WEIXIN_PACKAGE, WEIXIN_SHARE_FRIENDS_COMPONENT));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction("android.intent.action.SEND");
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            context.startActivity(intent);
        } else {
            ToastUtil.show(context, "请安装微信");
        }
        return isAvliable;
    }

    /**
     * 分享图片文件给qq
     */
    public static boolean share2QQ(Context context, File file) {
        boolean isAvaliable = isAvailable(context, QQ_PACKAGE);
        if (isAvaliable) {
            Intent shareIntent = IntentUtil.shareImage(Uri.fromFile(file));
            shareIntent.setPackage("com.tencent.mobileqq");
            ResolveInfo ri = context.getPackageManager().resolveActivity(shareIntent, 0);
            context.startActivity(shareIntent);
        }
        return isAvaliable;
    }

    /**
     * 判断是否有这个包名
     *
     * @param packageName
     * @return
     */
    public static boolean isAvailable(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pInfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pInfo.size(); i++) {
            if (pInfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    /**
     * 打开一个网页,类别是Intent.ACTION_VIEW
     */
    public Intent openBrowser(String url) {
        Uri uri = Uri.parse(url);
        return new Intent(Intent.ACTION_VIEW, uri);
    }

    /**
     * 打开一个网页,类别是Intent.ACTION_VIEW
     */
    public Intent openBrowser(Uri uri) {
        return new Intent(Intent.ACTION_VIEW, uri);
    }

    /**
     * 打开地图并定位到一个点
     */
    public Intent openMap(Uri uri) {
        return new Intent(Intent.ACTION_VIEW, uri);
    }

    /**
     * 打开地图并定位到一个点
     */
    public Intent openMap(Point point) {
        Uri uri = Uri.parse("geo:" + point.x + ":" + point.y);
//        Uri uri = Uri.parse("geo:52.76,-79.0342");
        return new Intent(Intent.ACTION_VIEW, uri);
    }

    /**
     * 打开图片查看器
     */
    protected void imageBrower(Context mContext, int position, ArrayList<String> urls2) {
        try {
            String EXTRA_IMAGE_INDEX = "image_index";
            String EXTRA_IMAGE_URLS = "image_urls";
            String action = "cn.it.image_browser.ACTION_IMAGE_BROWSER";
            Intent intent = new Intent(action);
            // 图片url,为了演示这里使用常量,一般从数据库中或网络中获取
            intent.putExtra(EXTRA_IMAGE_URLS, urls2);
            intent.putExtra(EXTRA_IMAGE_INDEX, position);
            mContext.startActivity(intent);
        } catch (Exception e) {

            ToastUtil.show(mContext, "未安装ImageBrowserDemo");
            e.printStackTrace();
        }
    }

    /**
     * 卸载应用
     */
    public Intent deleteApp(String packName) {
        Uri uri = Uri.fromParts("package", packName, null);
        return new Intent(Intent.ACTION_DELETE, uri);
    }

    /**
     * 获取安装App(支持6.0)的意图
     *
     * @param filePath 文件路径
     * @return intent
     */
    public static Intent getInstallAppIntent(String filePath) {
        return getInstallAppIntent(FileUtils.getFileByPath(filePath));
    }

    /**
     * 获取安装App(支持6.0)的意图
     *
     * @param file 文件
     * @return intent
     */
    public static Intent getInstallAppIntent(File file) {
        if (file == null) return null;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String type;
        if (Build.VERSION.SDK_INT < 23) {
            type = "application/vnd.android.package-archive";
        } else {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FileUtils.getFileExtension(file));
        }
        return intent.setDataAndType(Uri.fromFile(file), type);
    }

    /**
     * 获取卸载App的意图
     *
     * @param packageName 包名
     * @return intent
     */
    public static Intent getUninstallAppIntent(String packageName) {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:" + packageName));
        return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    /**
     * 获取打开App的意图
     *
     * @param context     上下文
     * @param packageName 包名
     * @return intent
     */
    public static Intent getLaunchAppIntent(Context context, String packageName) {
        return context.getPackageManager().getLaunchIntentForPackage(packageName);
    }

    /**
     * 获取App信息的意图
     *
     * @param packageName 包名
     * @return intent
     */
    public static Intent getAppInfoIntent(String packageName) {
        Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
        return intent.setData(Uri.parse("package:" + packageName));
    }

    /**
     * 获取分享文本的意图
     *
     * @param content 分享文本
     * @return intent
     */
    public static Intent getShareTextIntent(String content) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, content);
        return intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    /**
     * 获取分享图片的意图
     *
     * @param content 分享文本
     * @param uri     图片uri
     * @return intent
     */
    public static Intent getShareImageIntent(String content, Uri uri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_TEXT, content);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.setType("image/*");
        return intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    /**
     * 获取分享图片的意图
     *
     * @param content   文本
     * @param imagePath 图片文件路径
     * @return intent
     */
    public static Intent getShareImageIntent(String content, String imagePath) {
        return getShareImageIntent(content, FileUtils.getFileByPath(imagePath));
    }

    /**
     * 获取分享图片的意图
     *
     * @param content 文本
     * @param image   图片文件
     * @return intent
     */
    public static Intent getShareImageIntent(String content, File image) {
        if (!FileUtils.isFileExists(image)) return null;
        return getShareImageIntent(content, Uri.fromFile(image));
    }

    /**
     * 获取其他应用组件的意图
     *
     * @param packageName 包名
     * @param className   全类名
     * @return intent
     */
    public static Intent getComponentIntent(String packageName, String className) {
        return getComponentIntent(packageName, className, null);
    }

    /**
     * 获取其他应用组件的意图
     *
     * @param packageName 包名
     * @param className   全类名
     * @return intent
     */
    public static Intent getComponentIntent(String packageName, String className, Bundle bundle) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (bundle != null) intent.putExtras(bundle);
        ComponentName cn = new ComponentName(packageName, className);
        intent.setComponent(cn);
        return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    /**
     * 获取拍照的意图
     *
     * @param outUri 输出的uri
     * @return 拍照的意图
     */
    public static Intent getCaptureIntent(Uri outUri) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
    }

    /**
     * 获取选择照片的Intent
     *
     * @return
     */
    public static Intent getPickIntentWithGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        return intent.setType("image/*");
    }

    /**
     * 获取从文件中选择照片的Intent
     *
     * @return
     */
    public static Intent getPickIntentWithDocuments() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        return intent.setType("image/*");
    }

    public static Intent buildImageGetIntent(Uri saveTo, int outputX, int outputY, boolean returnData) {
        return buildImageGetIntent(saveTo, 1, 1, outputX, outputY, returnData);
    }

    public static Intent buildImageGetIntent(Uri saveTo, int aspectX, int aspectY,
                                             int outputX, int outputY, boolean returnData) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT < 19) {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        } else {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        }
        intent.setType("image/*");
        intent.putExtra("output", saveTo);
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", returnData);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        return intent;
    }

    public static Intent buildImageCropIntent(Uri uriFrom, Uri uriTo, int outputX, int outputY, boolean returnData) {
        return buildImageCropIntent(uriFrom, uriTo, 1, 1, outputX, outputY, returnData);
    }

    public static Intent buildImageCropIntent(Uri uriFrom, Uri uriTo, int aspectX, int aspectY,
                                              int outputX, int outputY, boolean returnData) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uriFrom, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("output", uriTo);
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", returnData);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        return intent;
    }

    public static Intent buildImageCaptureIntent(Uri uri) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        return intent;
    }

}


text:
from collections import defaultdict
import numpy as np
import pandas as pd

# from scipy.sparse import coo_matrix
from cooler.core import _IndexingMixin

def arg_prune_partition(seq, step):
    """
    Take a monotonic sequence of integers and downsample it such that they
    are at least ``step`` apart (roughly), preserving the first and last
    elements. Returns indices, not values.

    """
    lo, hi = seq[0], seq[-1]
    num = 2 + (hi - lo) // step
    cuts = np.linspace(lo, hi, num, dtype=int)
    return np.unique(np.searchsorted(seq, cuts))

class CSRSelector(_IndexingMixin):
    """
    Instantiates 2D range queries.

    Example
    -------
    >>> selector = CSRSelector(h5, (100, 100), 'count', 10000)
    >>> query = selector[lo1:hi1, lo2:hi2]

    """

    def __init__(self, grp, shape, field, chunksize):
        self.grp = grp
        self.shape = shape
        self.field = field
        self.chunksize = chunksize
        self.offset_selector = grp["indexes"]["bin1_offset"]
        self.bin1_selector = grp["pixels"]["bin1_id"]
        self.bin2_selector = grp["pixels"]["bin2_id"]
        self.data_selector = grp["pixels"][field]

    def _make_getchunk(self, ispan, jspan):
        # Factory for function that executes any piece of a 2D range query by
        # index.

        bin1_selector = self.bin1_selector
        bin2_selector = self.bin2_selector
        data_selector = self.data_selector
        field = self.field
        i0, i1 = ispan
        j0, j1 = jspan

        # coarsegrain the offsets to extract a big chunk of rows at a time
        if (i1 - i0 < 1) or (j1 - j0 < 1):
            offsets = []
            loc_pruned_offsets = []
        else:
            offsets = self.offset_selector[i0 : i1 + 1]
            loc_pruned_offsets = arg_prune_partition(offsets, self.chunksize)

        self._loc_pruned_offsets = loc_pruned_offsets
        # i0 -- matrix row number offset
        # o0 -- corresponding pixel id offset = offsets[0]

        # let's take the downsampled subset of pixel id offsets [o0, ...., o1]
        # each successive pair corresponds to a "piece" of the query
        def getchunk(chunk_id, include_index=False):
            out = {"bin1_id": [], "bin2_id": [], field: []}
            if include_index:
                out["__index"] = []

            # extract a chunk of on-disk rows
            oi, of = loc_pruned_offsets[chunk_id], loc_pruned_offsets[chunk_id + 1]
            p0, p1 = offsets[oi], offsets[of]
            slc = slice(p0, p1)

            bin2_extracted = bin2_selector[slc]
            data_extracted = data_selector[slc]
            if include_index:
                ind_extracted = np.arange(slc.start, slc.stop)

            # go row by row and filter
            for i in range(oi, of):
                # correct the offsets
                lo = offsets[i] - p0
                hi = offsets[i + 1] - p0

                # this row
                bin2 = bin2_extracted[lo:hi]

                # filter for the range of j values we want
                mask = (bin2 >= j0) & (bin2 < j1)
                cols = bin2[mask]

                # apply same mask for data
                data = data_extracted[lo:hi][mask]

                # shortcut for row data
                rows = np.full(len(cols), i0 + i, dtype=bin1_selector.dtype)

                out["bin1_id"].append(rows)
                out["bin2_id"].append(cols)
                out[field].append(data)
                if include_index:
                    out["__index"].append(ind_extracted[lo:hi][mask])

            if len(out):
                for k in out.keys():
                    out[k] = np.concatenate(out[k], axis=0)
            else:
                out["bin1_id"] = np.array([], dtype=bin1_selector.dtype)
                out["bin2_id"] = np.array([], dtype=bin2_selector.dtype)
                out[field] = np.array([], dtype=data_selector.dtype)
                if include_index:
                    out["__index"] = np.array([], dtype=np.int64)

            return out

        return getchunk, loc_pruned_offsets

    def __getitem__(self, key):
        s1, s2 = self._unpack_index(key)
        ispan = self._process_slice(s1, self.shape[0])
        jspan = self._process_slice(s2, self.shape[1])
        getchunk, loc_pruned_offsets = self._make_getchunk(ispan, jspan)
        return RangeQuery(self, ispan, jspan, self.field, getchunk, loc_pruned_offsets)

class RangeQuery(object):
    """
    Executor that fulfills a partitioned 2D range query using a variety of outputs.

    """

    def __init__(self, selector, ispan, jspan, field, getchunk, loc_pruned_offsets):
        self.selector = selector
        self.ispan = ispan
        self.jspan = jspan
        self.field = field
        self.n_chunks = len(loc_pruned_offsets) - 1
        self._locs = loc_pruned_offsets
        self._getchunk = getchunk

    def read_chunk(self, i, include_index=False):
        """Read any chunk of the partitioned query as a dictionary."""
        if not 0 <= i < self.n_chunks:
            raise IndexError(i)
        return self._getchunk(i, include_index)

    def read_chunked(self, include_index=False):
        """Iterator over chunks (as dictionaries)."""
        for i in range(self.n_chunks):
            yield self._getchunk(i, include_index)

    def read(self, include_index=False):
        """Read the complete range query as a dictionary"""
        result = list(self.read_chunked(include_index))
        return {
            k: np.concatenate([d[k] for d in result], axis=0)
            for k in ["bin1_id", "bin2_id", self.field]
        }

    def __repr__(self):
        return (
            "{self.__class__.__name__}"
            '({self.ispan}, {self.jspan}, "{self.field}", ...) '
            "[{n} piece(s)]"
        ).format(self=self, n=self.n_chunks)


text:
package com.ltsllc.miranda.session;

import com.ltsllc.commons.util.ImprovedRandom;
import com.ltsllc.miranda.clientinterface.basicclasses.User;

import java.security.GeneralSecurityException;

/**
 * Created by Clark on 3/30/2017.
 */
public class Session {
    private User user;
    private long expires;
    private long id;

    public void setUser(User user) {
        this.user = user;
    }

    public User getUser() {
        return user;
    }

    public long getExpires() {
        return expires;
    }

    public void setExpires(long expires) {
        this.expires = expires;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public Session () {
    }
    public Session(User user, long expires, long id) {
        this.user = user;
        this.expires = expires;
        this.id = id;
    }

    public boolean equals(Object o) {
        if (null == o || !(o instanceof Session))
            return false;

        Session other = (Session) o;
        return getUser().equals(other.getUser()) && getExpires() == other.getExpires() && getId() == other.getId();
    }

    public void extendExpires(long time) {
        expires += time;
    }

    public static Session random (ImprovedRandom improvedRandom) throws GeneralSecurityException {
        Session session = new Session();

        User aUser = User.createRandom(improvedRandom);
        session.setUser(aUser);

        session.setExpires(improvedRandom.nextNonNegativeLong());
        session.setId(improvedRandom.nextNonNegativeLong());

        return session;
    }
}


text:
var PlayerUtils = new function() {
}

// Prepares a video element for playback by setting default event handlers
// and source attribute.
PlayerUtils.registerDefaultEventListeners = function(player) {
  Utils.timeLog('Registering video event handlers.');
  // Map from event name to event listener function name.  It is common for
  // event listeners to be named onEventName.
  var eventListenerMap = {
    'encrypted': 'onEncrypted',
    'webkitneedkey': 'onWebkitNeedKey',
    'webkitkeymessage': 'onWebkitKeyMessage',
    'webkitkeyadded': 'onWebkitKeyAdded',
    'webkitkeyerror': 'onWebkitKeyError'
  };
  for (eventName in eventListenerMap) {
    var eventListenerFunction = player[eventListenerMap[eventName]];
    if (eventListenerFunction) {
      player.video.addEventListener(eventName, function(e) {
        player[eventListenerMap[e.type]](e);
      });
    }
  }

  player.video.addEventListener('error', function(error) {
    // This most likely happens on pipeline failures (e.g. when the CDM
    // crashes).
    Utils.timeLog('onHTMLElementError', error);
    Utils.failTest(error);
  });
};

// Register the necessary event handlers needed when playing encrypted content
// using the unprefixed API. Returns a promise that resolves to the player.
PlayerUtils.registerEMEEventListeners = function(player) {
  player.video.addEventListener('encrypted', function(message) {

    function addMediaKeySessionListeners(mediaKeySession) {
      mediaKeySession.addEventListener('message', function(message) {
        player.video.receivedKeyMessage = true;
        if (Utils.isRenewalMessage(message)) {
          Utils.timeLog('MediaKeySession onMessage - renewal', message);
          player.video.receivedRenewalMessage = true;
        } else {
          if (message.messageType != 'license-request') {
            Utils.failTest('Unexpected message type "' + message.messageType +
                               '" received.',
                           EME_MESSAGE_UNEXPECTED_TYPE);
          }
        }
        player.onMessage(message);
      });
    }

    try {
      if (player.testConfig.sessionToLoad) {
        Utils.timeLog('Loading session: ' + player.testConfig.sessionToLoad);
        var session =
            message.target.mediaKeys.createSession('persistent-license');
        addMediaKeySessionListeners(session);
        session.load(player.testConfig.sessionToLoad)
            .then(
                function(result) {
                  if (!result)
                    Utils.failTest('Session not found.', EME_SESSION_NOT_FOUND);
                },
                function(error) { Utils.failTest(error, EME_LOAD_FAILED); });
      } else {
        Utils.timeLog('Creating new media key session for initDataType: ' +
                      message.initDataType + ', initData: ' +
                      Utils.getHexString(new Uint8Array(message.initData)));
        var session = message.target.mediaKeys.createSession();
        addMediaKeySessionListeners(session);
        session.generateRequest(message.initDataType, message.initData)
            .catch(function(error) {
              // Ignore the error if a crash is expected. This ensures that
              // the decoder actually detects and reports the error.
              if (this.testConfig.keySystem !=
                  'org.chromium.externalclearkey.crash') {
                Utils.failTest(error, EME_GENERATEREQUEST_FAILED);
              }
            });
      }
    } catch (e) {
      Utils.failTest(e);
    }
  });

  this.registerDefaultEventListeners(player);
  player.video.receivedKeyMessage = false;
  Utils.timeLog('Setting video media keys: ' + player.testConfig.keySystem);
  var config = {};
  if (player.testConfig.sessionToLoad) {
    config = {
        persistentState: "required",
        sessionTypes: ["temporary", "persistent-license"]
    };
  }
  return navigator.requestMediaKeySystemAccess(
      player.testConfig.keySystem, [config])
      .then(function(access) { return access.createMediaKeys(); })
      .then(function(mediaKeys) {
        return player.video.setMediaKeys(mediaKeys);
      })
      .then(function(result) { return player; })
      .catch(function(error) { Utils.failTest(error, NOTSUPPORTEDERROR); });
};

// Register the necessary event handlers needed when playing encrypted content
// using the prefixed API. Even though the prefixed API is all synchronous,
// returns a promise that resolves to the player.
PlayerUtils.registerPrefixedEMEEventListeners = function(player) {
 player.video.addEventListener('webkitneedkey', function(message) {
    var initData = message.initData;
    if (player.testConfig.sessionToLoad) {
      Utils.timeLog('Loading session: ' + player.testConfig.sessionToLoad);
      initData =
          Utils.convertToUint8Array(PREFIXED_EME_API_LOAD_SESSION_HEADER +
                                    player.testConfig.sessionToLoad);
    }
    Utils.timeLog(player.testConfig.keySystem +
                  ' Generate key request, initData: ' +
                  Utils.getHexString(initData));
    try {
      message.target.webkitGenerateKeyRequest(player.testConfig.keySystem,
                                              initData);
    } catch (e) {
      Utils.failTest(e);
    }
  });

  player.video.addEventListener('webkitkeyadded', function(message) {
    Utils.timeLog('onWebkitKeyAdded', message);
    message.target.receivedKeyAdded = true;
  });

  player.video.addEventListener('webkitkeyerror', function(error) {
    Utils.timeLog('onWebkitKeyError',
                  'KeySystem: ' + error.keySystem + ', sessionId: ' +
                      error.sessionId + ', errorCode: ' + error.errorCode.code +
                      ', systemCode: ' + error.systemCode);
    Utils.failTest(error, PREFIXED_EME_ERROR_EVENT);
  });

  player.video.addEventListener('webkitkeymessage', function(message) {
    Utils.timeLog('onWebkitKeyMessage', message);
    message.target.receivedKeyMessage = true;
    if (Utils.isRenewalMessagePrefixed(message.message)) {
      Utils.timeLog('onWebkitKeyMessage - renewal', message);
      message.target.receivedRenewalMessage = true;
    }
  });

  // The prefixed API is all synchronous, so wrap the calls in a promise.
  return new Promise(function(resolve, reject) {
    PlayerUtils.registerDefaultEventListeners(player);
    player.video.receivedKeyMessage = false;
    resolve(player);
  });
};

PlayerUtils.setVideoSource = function(player) {
  if (player.testConfig.useMSE) {
    Utils.timeLog('Loading media using MSE.');
    var mediaSource =
        MediaSourceUtils.loadMediaSourceFromTestConfig(player.testConfig);
    player.video.src = window.URL.createObjectURL(mediaSource);
  } else {
    Utils.timeLog('Loading media using src.');
    player.video.src = player.testConfig.mediaFile;
  }
};

// Initialize the player to play encrypted content. Returns a promise that
// resolves to the player.
PlayerUtils.initEMEPlayer = function(player) {
  return player.registerEventListeners().then(function(result) {
    PlayerUtils.setVideoSource(player);
    return player;
  });
};

// Return the appropriate player based on test configuration.
PlayerUtils.createPlayer = function(video, testConfig) {
  // Update keySystem if using prefixed Clear Key since it is not available as a
  // separate key system to choose from; however it can be set in URL query.
  var usePrefixedEME = testConfig.usePrefixedEME;
  if (testConfig.keySystem == CLEARKEY && usePrefixedEME)
    testConfig.keySystem = PREFIXED_CLEARKEY;

  function getPlayerType(keySystem) {
    switch (keySystem) {
      case WIDEVINE_KEYSYSTEM:
        if (usePrefixedEME)
          return PrefixedWidevinePlayer;
        return WidevinePlayer;
      case PREFIXED_CLEARKEY:
        return PrefixedClearKeyPlayer;
      case EXTERNAL_CLEARKEY:
      case CLEARKEY:
        if (usePrefixedEME)
          return PrefixedClearKeyPlayer;
        return ClearKeyPlayer;
      case FILE_IO_TEST_KEYSYSTEM:
        return FileIOTestPlayer;
      default:
        Utils.timeLog(keySystem + ' is not a known key system');
        if (usePrefixedEME)
          return PrefixedClearKeyPlayer;
        return ClearKeyPlayer;
    }
  }
  var Player = getPlayerType(testConfig.keySystem);
  return new Player(video, testConfig);
};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <!--

        Licensed to the Apache Software Foundation (ASF) under one or more
        contributor license agreements.  See the NOTICE file distributed with
        this work for additional information regarding copyright ownership.
        The ASF licenses this file to You under the Apache License, Version 2.0
        (the "License"); you may not use this file except in compliance with
        the License.  You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.

    -->

    <!-- $Rev: 432962 $ $Date: 2006-08-20 03:47:39 -0700 (Sun, 20 Aug 2006) $ -->

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>xbean</artifactId>
        <groupId>org.apache.xbean</groupId>
        <version>4.2-SNAPSHOT</version>
    </parent>

    <artifactId>xbean-spring</artifactId>
    <packaging>bundle</packaging>
    <name>Apache XBean :: Spring</name>

    <description>xbean-spring provides a schema-driven proprietary namespace handler for spring contexts</description>

    <properties>
    </properties>

    <dependencies>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.thoughtworks.qdox</groupId>
            <artifactId>qdox</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>ant</groupId>
            <artifactId>ant</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <build>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
            <testResource>
                <directory>target/test-generated</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>**/BeerUsingXBeanNSTest.java</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <taskdef classname="org.apache.xbean.spring.generator.MappingGeneratorTask" name="mapping">
                                    <classpath>
                                        <pathelement path="${basedir}/target/classes" />
                                        <pathelement path="${basedir}/target/test-classes" />
                                        <path refid="maven.runtime.classpath" />
                                    </classpath>
                                </taskdef>
                                <mapping namespace="http://xbean.apache.org/schemas/pizza" srcdir="src/test/java" destFile="target/restaurant.xsd" metaInfDir="${basedir}/target/test-generated/" />
                                <copy todir="${basedir}/target/test-classes">
                                    <fileset dir="${basedir}/target/test-generated" />
                                </copy>
                            </tasks>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Import-Package>
                            com.thoughtworks.qdox*;resolution:=optional,
                            org.apache.tools.ant*;resolution:=optional,
                            org.springframework.*;version="[2.5,4)",
                            org.springframework.core;resolution:=optional;version="[2.5,4)",
                            org.springframework.web*;resolution:=optional;version="[2.5,4)",
                            *
                        </Import-Package>
                        <DynamicImport-Package>META-INF.services.org.apache.xbean.spring.*,META-INF.services.org.xbean.spring</DynamicImport-Package>
                        <_failok>true</_failok>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
package org.algo;

import java.util.Date;

import org.algo.machine.Hardware;
import org.algo.machine.VirtualMachine;
import org.algo.netio.BasicLogger;
import org.algo.type.StandardType;

public abstract class OjAlgoUtils {

    /**
     * This is set for you, but you may want to set it to something different/better. Create a
     * {@linkplain Hardware} instance and then call {@linkplain Hardware#virtualise()}.
     */
    public static VirtualMachine ENVIRONMENT = null;

    static {

        final String tmpArchitecture = VirtualMachine.getArchitecture();
        final long tmpMemory = VirtualMachine.getMemory();
        final int tmpThreads = VirtualMachine.getThreads();

        for (final Hardware tmpHardware : Hardware.PREDEFINED) {
            if (tmpHardware.architecture.equals(tmpArchitecture) && (tmpHardware.threads <= tmpThreads) && (tmpHardware.memory >= tmpMemory)) {
                ENVIRONMENT = tmpHardware.virtualise();
            }
        }

        if (ENVIRONMENT == null) {
            if (System.getProperty("shut.up.ojAlgo") == null) {
                BasicLogger.debug("ojAlgo includes a small set of predefined hardware profiles,");
                BasicLogger.debug("none of which were deemed suitable for the hardware you're currently using.");
                BasicLogger.debug("You should set org.ojalgo.OjAlgoUtils.ENVIRONMENT to something that matches the hardware/OS/JVM you're running on.");
                BasicLogger.debug("Additionally it would be appreciated if you contribute your hardware profile to ojAlgo.");
                BasicLogger.debug("https://lists.sourceforge.net/lists/listinfo/ojalgo-user");
                BasicLogger.debug("https://github.com/optimatika/ojAlgo/issues");
                BasicLogger.debug("Architecture={} Threads={} Memory={}", tmpArchitecture, tmpThreads, tmpMemory);
            }
            ENVIRONMENT = Hardware.makeSimple(tmpArchitecture, tmpMemory, tmpThreads).virtualise();
        }

    }

    /**
     * @see Package#getSpecificationVersion()
     */
    public static String getDate() {

        final String tmpManifestValue = OjAlgoUtils.class.getPackage().getSpecificationVersion();

        return tmpManifestValue != null ? tmpManifestValue : StandardType.SQL_DATE.format(new Date());
    }

    /**
     * @see Package#getImplementationTitle()
     */
    public static String getTitle() {

        final String tmpManifestValue = OjAlgoUtils.class.getPackage().getImplementationTitle();

        return tmpManifestValue != null ? tmpManifestValue : "ojAlgo";
    }

    /**
     * @see Package#getImplementationVendor()
     */
    public static String getVendor() {

        final String tmpManifestValue = OjAlgoUtils.class.getPackage().getImplementationVendor();

        return tmpManifestValue != null ? tmpManifestValue : "Optimatika";
    }

    /**
     * @see Package#getImplementationVersion()
     */
    public static String getVersion() {

        final String tmpManifestValue = OjAlgoUtils.class.getPackage().getImplementationVersion();

        return tmpManifestValue != null ? tmpManifestValue : "X.X";
    }

    private OjAlgoUtils() {
        super();
    }

}


text:
class SessionsController < ApplicationController
  layout 'login'

  def login
  end

  def logout
    session[:current_user] = nil
    redirect_to login_path
  end

  def create
    if auth_hash[:info][:email] =~ Rails.application.config.valid_email
      session[:current_user] = auth_hash[:info]
      redirect_to admin_root_path
    else
      flash[:danger] = "Unauthorized email used."
      redirect_to login_path
    end
  end

  def auth_failure
    flash[:danger] = params[:message]
    redirect_to login_path
  end

  protected

  def auth_hash
    request.env['omniauth.auth']
  end
end


text:
<?php

namespace L3l0Labs\Archive;

class Filename
{
    private $path;

    public function __construct($path)
    {
        $this->path = $path;
    }

    public function path()
    {
        return $this->path;
    }

    public function __toString()
    {
        return $this->path();
    }

    public static function create($name)
    {
        return new self($name);
    }

    public function name()
    {
        // TODO: write logic here
    }
}


text:
package io.getlime.security.powerauth.lib.nextstep.model.response;

import io.getlime.security.powerauth.lib.nextstep.model.entity.CredentialSecretDetail;
import io.getlime.security.powerauth.lib.nextstep.model.entity.UserContactDetail;
import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.UserIdentityStatus;
import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Response object used for creating a user identity.
 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
@Data
public class CreateUserResponse {

    @NotBlank
    @Size(min = 1, max = 256)
    private String userId;

    @NotNull
    private UserIdentityStatus userIdentityStatus;

    @NotNull
    private final Map<String, Object> extras = new LinkedHashMap<>();

    @NotNull
    private final List<String> roles = new ArrayList<>();

    @NotNull
    private final List<UserContactDetail> contacts = new ArrayList<>();

    @NotNull
    private final List<CredentialSecretDetail> credentials = new ArrayList<>();

}


text:
namespace offline_items_collection {

using FileIdPairVector = FileExistenceChecker::FileWithIdCollection<int64_t>;
using FileIdPairSet = std::set<std::pair<base::FilePath, int64_t>>;
namespace {

FileIdPairSet CheckForMissingFiles(
    const scoped_refptr<base::TestSimpleTaskRunner>& task_runner,
    FileIdPairVector file_paths) {
  FileIdPairSet missing_files;
  FileExistenceChecker::CheckForMissingFiles(
      task_runner, std::move(file_paths),
      base::BindOnce(
          [](FileIdPairSet* set_alias, FileIdPairVector result) {
            set_alias->insert(result.begin(), result.end());
          },
          &missing_files));
  task_runner->RunUntilIdle();
  return missing_files;
}

}  // namespace

class FileExistenceCheckerTest : public testing::Test {
 public:
  FileExistenceCheckerTest();
  ~FileExistenceCheckerTest() override;

  FileIdPairVector CreateTestFiles(int64_t count);

  base::TestSimpleTaskRunner* task_runner() { return task_runner_.get(); }
  scoped_refptr<base::TestSimpleTaskRunner>& task_runner_ref() {
    return task_runner_;
  }

 private:
  base::ScopedTempDir temp_directory_;
  scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
  base::ThreadTaskRunnerHandle task_runner_handle_;
};

FileExistenceCheckerTest::FileExistenceCheckerTest()
    : task_runner_(new base::TestSimpleTaskRunner),
      task_runner_handle_(task_runner_) {
  EXPECT_TRUE(temp_directory_.CreateUniqueTempDir());
}

FileExistenceCheckerTest::~FileExistenceCheckerTest() {}

FileIdPairVector FileExistenceCheckerTest::CreateTestFiles(int64_t count) {
  base::FilePath file_path;
  FileIdPairVector created_files;
  for (int64_t i = 0; i < count; i++) {
    EXPECT_TRUE(
        base::CreateTemporaryFileInDir(temp_directory_.GetPath(), &file_path));
    created_files.push_back(std::make_pair(file_path, i));
  }

  return created_files;
}

TEST_F(FileExistenceCheckerTest, NoFilesMissing) {
  FileIdPairVector files = CreateTestFiles(2);
  FileIdPairSet missing_files = CheckForMissingFiles(task_runner_ref(), files);
  EXPECT_TRUE(missing_files.empty());
}

TEST_F(FileExistenceCheckerTest, MissingFileFound) {
  FileIdPairVector files = CreateTestFiles(2);

  base::DeleteFile(files[0].first);

  FileIdPairSet missing_files = CheckForMissingFiles(task_runner_ref(), files);

  EXPECT_EQ(1UL, missing_files.size());
  EXPECT_EQ(1UL, missing_files.count(files[0]));
  EXPECT_EQ(0UL, missing_files.count(files[1]));
}

}  // namespace offline_items_collection


text:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ProgressBar
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/progressBar"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:indeterminate="false"/>

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="正在加入"
            android:id="@+id/textView"
            android:layout_below="@+id/progressBar"
            android:layout_centerHorizontal="true"/>
</RelativeLayout>


text:
from __future__ import absolute_import
import numpy as np
import time
import sys
import six

def get_from_module(identifier, module_params, module_name, instantiate=False, kwargs=None):
    if isinstance(identifier, six.string_types):
        res = module_params.get(identifier)
        if not res:
            raise Exception('Invalid ' + str(module_name) + ': ' + str(identifier))
        if instantiate and not kwargs:
            return res()
        elif instantiate and kwargs:
            return res(**kwargs)
        else:
            return res
    return identifier

def make_tuple(*args):
    return args

def printv(v, prefix=''):
    if type(v) == dict:
        if 'name' in v:
            print(prefix + '#' + v['name'])
            del v['name']
        prefix += '...'
        for nk, nv in v.items():
            if type(nv) in [dict, list]:
                print(prefix + nk + ':')
                printv(nv, prefix)
            else:
                print(prefix + nk + ':' + str(nv))
    elif type(v) == list:
        prefix += '...'
        for i, nv in enumerate(v):
            print(prefix + '#' + str(i))
            printv(nv, prefix)
    else:
        prefix += '...'
        print(prefix + str(v))

class Progbar(object):
    def __init__(self, target, width=30, verbose=1):
        '''
            @param target: total number of steps expected
        '''
        self.width = width
        self.target = target
        self.sum_values = {}
        self.unique_values = []
        self.start = time.time()
        self.total_width = 0
        self.seen_so_far = 0
        self.verbose = verbose

    def update(self, current, values=[]):
        '''
            @param current: index of current step
            @param values: list of tuples (name, value_for_last_step).
            The progress bar will display averages for these values.
        '''
        for k, v in values:
            if k not in self.sum_values:
                self.sum_values[k] = [v * (current - self.seen_so_far), current - self.seen_so_far]
                self.unique_values.append(k)
            else:
                self.sum_values[k][0] += v * (current - self.seen_so_far)
                self.sum_values[k][1] += (current - self.seen_so_far)
        self.seen_so_far = current

        now = time.time()
        if self.verbose == 1:
            prev_total_width = self.total_width
            sys.stdout.write("\b" * prev_total_width)
            sys.stdout.write("\r")

            numdigits = int(np.floor(np.log10(self.target))) + 1
            barstr = '%%%dd/%%%dd [' % (numdigits, numdigits)
            bar = barstr % (current, self.target)
            prog = float(current)/self.target
            prog_width = int(self.width*prog)
            if prog_width > 0:
                bar += ('='*(prog_width-1))
                if current < self.target:
                    bar += '>'
                else:
                    bar += '='
            bar += ('.'*(self.width-prog_width))
            bar += ']'
            sys.stdout.write(bar)
            self.total_width = len(bar)

            if current:
                time_per_unit = (now - self.start) / current
            else:
                time_per_unit = 0
            eta = time_per_unit*(self.target - current)
            info = ''
            if current < self.target:
                info += ' - ETA: %ds' % eta
            else:
                info += ' - %ds' % (now - self.start)
            for k in self.unique_values:
                if type(self.sum_values[k]) is list:
                    info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1]))
                else:
                    info += ' - %s: %s' % (k, self.sum_values[k])

            self.total_width += len(info)
            if prev_total_width > self.total_width:
                info += ((prev_total_width-self.total_width) * " ")

            sys.stdout.write(info)
            sys.stdout.flush()

            if current >= self.target:
                sys.stdout.write("\n")

        if self.verbose == 2:
            if current >= self.target:
                info = '%ds' % (now - self.start)
                for k in self.unique_values:
                    info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1]))
                sys.stdout.write(info + "\n")

    def add(self, n, values=[]):
        self.update(self.seen_so_far+n, values)


text:
// code to overlay console.log and console.error onto page

const log = document.getElementsByClassName('logs')[0];

const prepend = (level, line) => {
  const p = document.createElement('p');
  p.textContent = line;
  p.className = level;
  log.prepend(document.createElement('br'));
  log.prepend(p);
};

const info = console.log.bind(console);
console.log = (...messages) => {
  const logMessages = messages.join(' ')
  if (logMessages.indexOf('https://phaser.io') <= -1) {
    prepend('log', logMessages);
    info(...messages);
  }
};

const error = console.error.bind(console);
console.error = (...messages) => {
  prepend('error', messages.join(' '));
  error(...messages);
};