text:
package org.gradoop.flink.model.impl.operators.statistics.functions;

import com.google.common.collect.Lists;
import org.apache.flink.api.common.functions.GroupCombineFunction;
import org.apache.flink.api.common.functions.GroupReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.flink.model.impl.tuples.WithCount;

import java.util.List;
import java.util.Set;

/**
 * This UDF counts the number of distinct property values grouped by a key K
 * <p>
 * Reduces {@code <K, Set<PropertyValue>> --> <K, Long>}
 *
 * @param <K> the grouping key
 */
public class CombinePropertyValueDistribution<K> implements
  GroupCombineFunction<Tuple2<K, Set<PropertyValue>>, Tuple2<K, Set<PropertyValue>>>,
  GroupReduceFunction<Tuple2<K, Set<PropertyValue>>, WithCount<K>> {

  @Override
  public void combine(Iterable<Tuple2<K, Set<PropertyValue>>> values,
    Collector<Tuple2<K, Set<PropertyValue>>> out) throws Exception {

    List<Tuple2<K, Set<PropertyValue>>> pairs = Lists.newArrayList(values);
    out.collect(Tuple2.of(pairs.get(0).f0, combineSets(pairs)));
  }

  @Override
  public void reduce(Iterable<Tuple2<K, Set<PropertyValue>>> values,
    Collector<WithCount<K>> collector) throws Exception {

    List<Tuple2<K, Set<PropertyValue>>> pairs = Lists.newArrayList(values);
    collector.collect(new WithCount<>(pairs.get(0).f0, (long) combineSets(pairs).size()));
  }

  /**
   * Extracts sets of property values from tuples and combines them into one set.
   *
   * @param values list of {@code <K, Set<PropertyValue>>} tuples
   * @return combined set of all PropertyValues
   */
  private Set<PropertyValue> combineSets(List<Tuple2<K, Set<PropertyValue>>> values) {
    return values.stream()
      .map(triple -> triple.f1)
      .reduce((lhs, rhs) -> {
        lhs.addAll(rhs);
        return lhs;
      })
      .get();
  }
}


text:
package org.apache.activemq.artemis.tests.integration.stomp.util;

public class StompFrameFactoryV12 extends StompFrameFactoryV11 {

   @Override
   public String[] handleHeaders(String header) {
      // split the header into the key and value at the ":" since there shouldn't be any unescaped colons in the header
      // except for the one separating the key and value
      String[] result = header.split(":");

      for (int j = 0; j < result.length; j++) {
         StringBuffer decodedHeader = new StringBuffer();
         boolean isEsc = false;

         for (int i = 0; i < result[j].length(); i++) {
            char b = result[j].charAt(i);

            switch (b) {
               //escaping
               case '\\': {
                  if (isEsc) {
                     //this is a backslash
                     decodedHeader.append(b);
                     isEsc = false;
                  } else {
                     //begin escaping
                     isEsc = true;
                  }
                  break;
               }
               case 'c': {
                  if (isEsc) {
                     decodedHeader.append(":");
                     isEsc = false;
                  } else {
                     decodedHeader.append(b);
                  }
                  break;
               }
               case 'n': {
                  if (isEsc) {
                     decodedHeader.append('\n');
                     isEsc = false;
                  } else {
                     decodedHeader.append(b);
                  }
                  break;
               }
               case 'r': {
                  if (isEsc) {
                     decodedHeader.append('\r');
                     isEsc = false;
                  } else {
                     decodedHeader.append(b);
                  }
                  break;
               }
               default: {
                  decodedHeader.append(b);
               }
            }
         }

         result[j] = decodedHeader.toString();
      }

      return result;
   }

   @Override
   public ClientStompFrame newFrame(String command) {
      return new ClientStompFrameV12(command);
   }

   @Override
   public ClientStompFrame newAnyFrame(String command) {
      return new ClientStompFrameV12(command, true, false);
   }

}

redpajama_set_name: RedPajamaGithub


text:
import cgi
import oauth2 as oauth  # https://github.com/simplegeo/python-oauth2

def get_secret_for_consumer(consumer):
    """Given an API user, return the associated secret."""
    if 'test-consumer' == consumer:
        return 'test-secret'

    # Implement more advanced access control here.
    raise ValueError(consumer)

class TwoLeggedOAuth(object):
    scheme = 'OAuth'
    server = oauth.Server({ 'HMAC-SHA1': oauth.SignatureMethod_HMAC_SHA1() })

    @classmethod
    def authenticate(cls, request):
        # Copy params and remove any POSTed files from the list.
        params = dict([(k,v) for k,v in request.params.iteritems() if not isinstance(v, cgi.FieldStorage)])
        # Create the OAuth request and consumer objects, and try to verify.
        oauth_request = oauth.Request.from_request(
            http_method=request.method,
            http_url=request.url,
            headers=request.headers,
            parameters=params,
            query_string=request.query_string)

        consumer = params['oauth_consumer_key']
        oauth_consumer = oauth.Consumer(
            key=consumer,
            secret=get_secret_for_consumer(consumer))

        cls.server.verify_request(oauth_request, oauth_consumer, None)

def verify_auth(auth_cls=TwoLeggedOAuth, error_code=401):
    def wrapper(method):
        def authenticate(handler, *args, **kwargs):
            try:
                auth_cls.authenticate(handler.request)
            except Exception, e:
                handler.response.headers['WWW-Authenticate'] = auth_cls.scheme
                return handler.error(error_code)

            return method(handler, *args, **kwargs)
        return authenticate
    return wrapper


text:
var data = require('../data.json');

exports.view = function(req, res){
	var incoming = data['users'][0];

  res.render('home', incoming);
};


text:
package br.ufc.great.jcaehv.checker;

import java.util.Set;

import br.ufc.great.jcaehv.context.ContextState;
import br.ufc.great.jcaehv.model.property.Property;

public class KripkeModelToSCXML {

	public StringBuffer generateFile(long time, KripkeModel kripke, Set<Property> properties) {
		StringBuffer buffer = new StringBuffer();

		buffer.append("<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\" ");
		buffer.append("initialstate=\"");
		for (ContextState state : kripke.getInitialStates()) {
			buffer.append(state.getStringId());
			buffer.append("\">");
			break;
		}

		if (kripke.getReachableStateNumber() > 0) {
			for (ContextState state : kripke.getReachableStates()) {
				buffer.append("\n<state id=\"");
				buffer.append(state.isExceptional() ? "*" : "");
				buffer.append(state.getStringId() + "\" ");
				if (state.isInitial()) {
					buffer.append("initial=\"true\"");
				}
				buffer.append(">");
				buffer.append("\n\t<onentry>");
				buffer.append("\n\t\t<log expr=\"" + state.getLabel() + "\"/>");
				buffer.append("\n\t</onentry>");

				int[] nextStatesId = state.getNextStatesId();
				for (int nextStateId : nextStatesId) {
					ContextState next = kripke.getState(nextStateId);
					buffer.append("\n\t<transition target=\"");
					buffer.append(next.isExceptional() ? "*" : "");
					buffer.append(next.getStringId());
					buffer.append("\">");
					buffer.append("</transition>");
				}
				buffer.append("\n</state>");
			}
		}

		buffer.append("\n</scxml>");

		return buffer;
	}
}

//TODO: Created


text:
require "rails_helper"

feature "Super User - Dashboard Links", type: :feature do
  fixtures :all

  it "displays correct links for a researcher" do
    sign_in(users(:admin1))
    visit "/think_feel_do_dashboard"

    expect(page).to have_link "Arms", href: "/think_feel_do_dashboard/arms"
  end
end


text:
<?php

if ($_SERVER['SCRIPT_FILENAME'] == __FILE__)
    die('Access denied.');

if (!class_exists('ZWT_Module')) {

    /**
     * Abstract class to define/implement base methods for all module classes
     * @package ZWT_Base
     * @author Zanto Translate
     */
    abstract class ZWT_Module {

        private static $instances = array();

        /*
         * Magic methods
         */

        /**
         * Public getter for protected variables
         * @mvc Model
         * @author Zanto Translate
         * @param string $variable
         * @return mixed
         */
        public function __get($variable) {
            $module = get_called_class();

            if (in_array($variable, $module::$readableProperties))
                return $this->$variable;
            else
                throw new Exception(__METHOD__ . " error: $" . $variable . " doesn't exist or isn't readable.");
        }

        /**
         * Public setter for protected variables
         * @mvc Model
         * @author Zanto Translate
         * @param string $variable
         * @param mixed $value
         */
        public function __set($variable, $value) {
            $module = get_called_class();

            if (in_array($variable, $module::$writeableProperties)) {
                $this->$variable = $value;

                if (!$this->isValid())
                    throw new Exception(__METHOD__ . ' error: $' . $value . ' is not valid.');
            }
            else
                throw new Exception(__METHOD__ . " error: $" . $variable . " doesn't exist or isn't writable.");
        }

        /*
         * Non-abstract methods
         */

        /**
         * Provides access to a single instance of a module using the singleton pattern
         * @mvc Controller
         * @author Zanto Translate
         * @return object
         */
        public static function getInstance() {
            $module = get_called_class();

            if (!isset(self::$instances[$module]))
                self::$instances[$module] = new $module();

            return self::$instances[$module];
        }

        /*
         * Abstract methods
         */

        /**
         * Constructor
         * @mvc Controller
         * @author Zanto Translate
         */
        abstract protected function __construct();

        /**
         * Prepares sites to use the plugin during single or network-wide activation
         * @mvc Controller
         * @param bool $networkWide
         * @author Zanto Translate
         */
        abstract public function activate();

        /**
         * Rolls back activation procedures when de-activating the plugin
         * @mvc Controller
         * @author Zanto Translate
         */
        abstract public function deactivate();

        /**
         * Register callbacks for actions and filters
         * @mvc Controller
         * @author Zanto Translate
         */
        abstract public function registerHookCallbacks();

        /**
         * Initializes variables
         * @mvc Controller
         * @author Zanto Translate
         */
        abstract public function init();

        /**
         * Checks if the plugin was recently updated and upgrades if necessary
         * @mvc Controller
         * @author Zanto Translate
         * @param string $dbVersion
         */
        abstract public function upgrade($dbVersion = 0);

        /**
         * Checks that the object is in a correct state
         * @mvc Model
         * @author Zanto Translate
         * @param string $property An individual property to check, or 'all' to check all of them
         * @return bool
         */
        abstract protected function isValid($property = 'all');
    }

    // end ZWT_Module
}
?>


text:
import asyncio
from urllib.parse import urljoin

import requests

from beam_interactive_unofficial.progress_update import *
from beam_interactive_unofficial.exceptions import *
from beam_interactive_unofficial.beam_interactive_modified import start, proto, connection

from requests.exceptions import ConnectionError

URL = "https://beam.pro/api/v1/"

# noinspection PyAttributeOutsideInit
class BeamInteractiveClient:
    def __init__(self, oauth, timeout: int, on_connect=lambda x: None, on_report=lambda x: None, debug=False,
                 on_error=lambda x: None, auto_reconnect=False, max_reconnect_attempts=-1, reconnect_delay=5):

        self._on_connect, self._on_report, self._on_error = on_connect, on_report, on_error
        self._max_reconn, self._auto_reconnect = max_reconnect_attempts, auto_reconnect
        self._reconnect_delay = reconnect_delay
        self._oauth = oauth
        self._timeout = timeout
        self._debug = debug
        self._handlers = {
            proto.id.handshake_ack: asyncio.coroutine(on_connect),
            proto.id.report: asyncio.coroutine(on_report),
            proto.id.error: asyncio.coroutine(on_error)
        }

    def start(self, _attempt=0, _reconnect=False):
        """Start the connection to Beam."""

        self.state = None
        self._started = False
        self._num_buttons = None

        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        e = None
        try:
            e = self.loop.run_until_complete(asyncio.gather(
                self._run(delay=(self._reconnect_delay if _reconnect else None)), return_exceptions=True))
        finally:
            tasks = asyncio.gather(*asyncio.Task.all_tasks(), return_exceptions=True)
            tasks.cancel()
            self.loop.run_until_complete(tasks)
            self.loop.close()

            if e is not None:
                if isinstance(e[0], asyncio.TimeoutError):
                    print("Disconnected from Beam!")
                    self.start(_attempt=1, _reconnect=True)
                if isinstance(e[0], ConnectionError):
                    if _attempt == self._max_reconn or not _reconnect or not self._auto_reconnect:
                        raise ConnectionFailedError("Failed to {}connect to Beam{}!"
                                                    .format("re" if _reconnect else "",
                                                            " after {} attempts"
                                                            .format(self._max_reconn)) if _reconnect else "")
                    self.start(_attempt=_attempt + 1, _reconnect=True)

    def send(self, update: (ProgressUpdate, JoystickUpdate, TactileUpdate, ScreenUpdate, dict, str)):
        """Send a progress update to Beam."""
        self._check_started()

        if isinstance(update, ProgressUpdate):
            progress = update
        elif isinstance(update, (JoystickUpdate, TactileUpdate, ScreenUpdate)):
            progress = update.wrap()
        elif isinstance(update, dict):
            progress = ProgressUpdate.from_dict(update)
        elif isinstance(update, str):
            progress = ProgressUpdate.from_json(update)
        else:
            raise ValueError("Invalid data type - must be a ProgressUpdate, TactileUpdate, ScreenUpdate, dict or str.")

        if progress.state is not None:
            self.state = progress.state
        progress_probuf = progress.to_probuf()
        self.connection.send(progress_probuf)

    def set_state(self, state):
        progress = ProgressUpdate()
        progress.state = str(state)
        self.send(progress)

    def tactile_fire(self, tactile_id=None):
        update_on, update_off = ProgressUpdate(), ProgressUpdate()
        if tactile_id is None:
            for i in range(self._num_buttons):
                update_on.tactile_updates.append(TactileUpdate(id_=i, fired=True))
                update_off.tactile_updates.append(TactileUpdate(id_=i, fired=False))
            self.send(update_on)
            self.send(update_off)
            return

        try:
            for id_ in tactile_id:
                update_on.tactile_updates.append(TactileUpdate(id_=id_, fired=True))
                update_off.tactile_updates.append(TactileUpdate(id_=id_, fired=False))
        except TypeError:
            self.send(TactileUpdate(id_=tactile_id, fired=True))
            self.send(TactileUpdate(id_=tactile_id, fired=False))

    def tactile_cooldown(self, length, tactile_id=None):
        if tactile_id is None:
            progress = ProgressUpdate()
            for i in range(self._num_buttons):
                progress.tactile_updates.append(TactileUpdate(id_=i, cooldown=length))
            self.send(progress)
            return

        try:
            progress = ProgressUpdate()
            for id_ in tactile_id:
                progress.tactile_updates.append(TactileUpdate(id_=id_, cooldown=length))
            self.send(progress)
        except TypeError:
            self.send(TactileUpdate(id_=tactile_id, cooldown=length))

    # <editor-fold desc="Private Functions">

    @asyncio.coroutine
    def _run(self, delay=None):
        if delay is not None:
            print("Couldn't connect to Beam - trying again in 5 seconds...")
            yield from asyncio.sleep(delay)
        try:
            if self._debug:
                print("Getting user data...")
            self.user_data = self._get_user_data()  # type: dict
            if self._debug:
                print("Retrieved.")
        except (KeyError, TypeError):
            raise InvalidAuthenticationError()

        try:
            self.channel_id = self.user_data["channel"]["id"]
        except ConnectionError:
            raise ConnectionFailedError("Please check your internet connection.")
        except (KeyError, ValueError):
            raise ConnectionFailedError(self.user_data["message"])

        if self._debug:
            print("Getting interactive connection info...")
        self.data = self._join_interactive()  # type: dict
        if self._debug:
            print("Retrieved.")
        self.connection = \
            yield from start(self.data["address"], self.channel_id, self.data["key"], self.loop)  # type: connection
        self._started = True
        while (yield from asyncio.wait_for(self.connection.wait_message(), self._timeout)):
            yield from self._handle_packet(self.connection.get_packet())

    @asyncio.coroutine
    def _handle_packet(self, packet):
        decoded, _ = packet
        packet_id = proto.id.get_packet_id(decoded)

        if packet_id == proto.id.report:
            self._num_buttons = len(decoded.tactile)

        if packet_id in self._handlers:
            yield from self._handlers[packet_id](decoded)
        elif decoded is None:
            print("Unknown bytes were received. Uh oh!", packet_id)
        else:
            print("We got packet {} but didn't handle it!".format(packet_id))

    # <editor-fold desc="helper functions">
    def _get_user_data(self):
        """Log into Beam via the API."""
        return requests.get(self._build("/users/current"),
                            headers={"Authorization": ("Bearer " + self._oauth)}).json()

    @staticmethod
    def _build(endpoint):
        """Build an address for an API endpoint."""
        return urljoin(URL, endpoint.lstrip('/'))

    def _join_interactive(self):
        """Retrieve interactive connection information."""
        return requests.get(self._build("/interactive/{channel}/robot").format(
            channel=self.channel_id), headers={"Authorization": ("Bearer " + self._oauth)}).json()

    def _check_started(self):
        if not self._started:
            raise ClientNotConnectedError()

    # </editor-fold>

    # </editor-fold>

    pass


text:
package controllers

import (
	"USTB-TeachSystem-API/models"

	"github.com/astaxie/beego"
)

// Operations about Users
type GetCetScoreController struct {
	beego.Controller
}

// @Title GetAll
// @Description get all cetScore
// @Success 200 {object} models.cetScore
// @router / [get]
func (cetScore *GetCetScoreController) GetAll() {
	userName := cetScore.GetString("username")
	password := cetScore.GetString("password")

	cetScore.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	cetScore.Ctx.ResponseWriter.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
	cetScore.Ctx.ResponseWriter.Header().Set("content-type", "application/json")             //返回数据格式是json

	res := models.GetCETScoreFromLogin(userName, password)
	cetScore.Data["json"] = res
	cetScore.ServeJSON()
}


text:
package cli

import (
	"github.com/spf13/cobra"
)

var (
	upCmd = &cobra.Command{
		Use:   "up <group> [scale]",
		Short: "Bring a group up",
		Long:  "Submit a group, with an optional scale, and start it",
		Run:   upRun,
	}
)

func upRun(cmd *cobra.Command, args []string) {
	submitRun(cmd, args)

	// If a scale argument has been passed to submit,
	// remove it from the args list, as start doesn't want it.
	if len(args) > 1 {
		args = args[:1]
	}

	startRun(cmd, args)
}


text:
package org.fugerit.java.ext.doc.tlds;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

/*
 *
 *
 * @author Morozko
 *
 */
public class UrlTag extends TagSupport {

	/* (non-Javadoc)
	 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
	 */
	@Override
	public int doStartTag() throws JspException {
		StringBuilder buffer = new StringBuilder();
		if ( "true".equalsIgnoreCase( this.getRelative() ) ) {
			HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
			buffer.append( request.getScheme() );
			buffer.append( "://" );
			buffer.append( request.getServerName() );
			buffer.append( ":" );
			buffer.append( request.getServerPort() );
			buffer.append( request.getContextPath() );
		}
		buffer.append( this.getUrl() );
		System.out.println( "URL : "+buffer );
		try {
			this.pageContext.getOut().print( buffer.toString() );
		} catch (Exception e) {}
		return EVAL_PAGE;
	}

	/*
	 *
	 */
	private static final long serialVersionUID = -6000737096593291817L;

	private String url;

	private String relative;

	/*
	 * @return the relative
	 */
	public String getRelative() {
		return relative;
	}

	/*
	 * @param relative the relative to set
	 */
	public void setRelative(String relative) {
		this.relative = relative;
	}

	/*
	 * @return the url
	 */
	public String getUrl() {
		return url;
	}

	/*
	 * @param url the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

}


text:
import {ModuleWithProviders} from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomePageComponent} from './home-page/home-page.component';
import {TranslatePageComponent} from './translate-page/translate-page.component';
import {FilterPageComponent} from './filter-page/filter-page.component';
import {ActiveProjectGuard} from './active-project.guard';
import {CreateProjectPageComponent} from './create-project-page/create-project-page.component';
import {EditProjectPageComponent} from './edit-project-page/edit-project-page.component';
import {AutoTranslateSummaryPageComponent} from './auto-translate-summary-page/auto-translate-summary-page.component';
import {ConfigureAutoTranslatePageComponent} from './configure-auto-translate-page/configure-auto-translate-page.component';
import {ConfigureGithubPageComponent} from './file-accessors/github/configure-github-page/configure-github-page.component';
import {PublishProjectPageComponent} from './publish-project-page/publish-project-page.component';

/**
 * Created by martin on 23.03.2017.
 * Routing informations.
 */

const appRoutes: Routes = [
  { path: 'home', component: HomePageComponent },
  { path: 'createproject', component: CreateProjectPageComponent },
  { path: 'editproject', component: EditProjectPageComponent, canActivate: [ActiveProjectGuard] },
  { path: 'publishproject', component: PublishProjectPageComponent, canActivate: [ActiveProjectGuard]},
  { path: 'translate', component: TranslatePageComponent, canActivate: [ActiveProjectGuard] },
  { path: 'selectfilter', component: FilterPageComponent, canActivate: [ActiveProjectGuard] },
  { path: 'autotranslatesummary', component: AutoTranslateSummaryPageComponent},
  { path: 'configureautotranslate', component: ConfigureAutoTranslatePageComponent},
  { path: 'configuregithub', component: ConfigureGithubPageComponent},
  { path: '', redirectTo: '/translate', pathMatch: 'full' },
];

export const appRoutingProviders: any[] = [

];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, { useHash: true });


text:
<!DOCTYPE html>

<meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="stylesheets/default.css">
  <title>My Blog Template</title>

        Home
        About Me
        Projects
        Blog
        Résumé
        Contact

Jason Allen

Junior Web Developer

Jason's Work

Content coming soon!


text:
<?php
/**
 * @link       http://zoopcommerce.github.io/shard
 * @package    Zoop
 * @license    MIT
 */
namespace Zoop\Shard\SoftDelete\DataModel;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Zoop\Shard\Annotation\Annotations as Shard;

/**
 *
 * @since   1.0
 * @author  Tim Roediger <superdweebie@gmail.com>
 */
trait RestoredByTrait
{
    /**
     * @ODM\String
     * @ODM\Index
     * @Shard\SoftDelete\RestoredBy
     * @Shard\Validator\Slug
     */
    protected $restoredBy;

    /**
     *
     * @return string
     */
    public function getRestoredBy()
    {
        return $this->restoredBy;
    }
}


text:
// Copyright (C) E5R Development Team. All rights reserved.
// Licensed under the MIT License. See LICENSE file for license information.

using System.Threading.Tasks;

namespace E5R.Framework.Security.Auth
{
    public interface IResourceEndPoint
    {
        string EndPoint { get; }
        Task<object> ExecAsync(string fragmentUri);
    }
}


text:
angular.module('adminApp.customInsert', [])

.controller('CustomInsertCtrl', ['$scope', 'FileUploader', '$timeout', function($scope, FileUploader, $timeout) {

/*
 * Upload Section
 */

  $scope.message = null;
  //Options for type: alert, success, info
  $scope.messageType = null;

  $scope.fileReader = new FileReader();
  $scope.fileReader.progress = 0;
  $scope.fileReader.uploadReady = false;

  $scope.uploader = new FileUploader({
    filters:[{
      name: "CSV-only",
      fn: function(item) {
        var isCSV = !!item.name.match(/^.*\.csv$/);
        return isCSV;
      }
    }],
    removeAfterUpload: true,
    queueLimit: 1
  });

  $scope.params = {
    type: "ae"
  };

  $scope.displayMessage = function(msg, time, type) {
    $scope.message = msg;
    $scope.messageType = type;
    $timeout( $scope.clearMessage, time );
  }

  $scope.clearMessage = function() {
    $scope.message = null;
    $scope.messageType = null;
  }

  $scope.clearFile = function() {
    angular.element( document.getElementById('file-input') ).val(null);

    $scope.fileReader.progress = 0;
    $scope.fileReader.uploadReady = false;

    $scope.uploader.clearQueue();
  }

  $scope.setUploaderCallbacks = function( uploader ) {
    var formatParsedData = function( results ) {
      var byUser = {};

      _.forEach(results, function( cit ) {
        var userId, keyword, urlOrOffer, country, type;

        if ( ( userId = cit["UserID"] ) && ( keyword = cit["Keyword"] ) && (urlOrOffer = cit["URL/Offer"] ) && ( country = cit["Country"] ) ) {
          byUser[userId] = byUser[userId] || [];

          byUser[userId].push( {
            term: keyword,
            destination: urlOrOffer,
            country: country
          } )
        }

      } );

      return byUser;
    }

    uploader.onWhenAddingFileFailed = function( filter ) {
      console.log("File adding failed. Failing filter: ", filter);
      $scope.displayMessage("Upload only supports CSV Files!", 4000, "alert");
    }

    uploader.onAfterAddingFile = function( item ) {
      var file = item._file;
      Papa.parse(file, {
        header: true,
        complete: function( results, file ) {
          var byUser = formatParsedData( results.data );
          console.log("File parssed: ", byUser);
        }
      } );
      // $scope.fileReader.readAsText( file );
    }

    uploader.onSuccessItem = function() {
      $scope.displayMessage("Successfully Uploaded File. An email summary will be sent to you soon.", 4000, "success");
    }

    uploader.onErrorItem = function( item, response, stat, headers ) {
      console.log("File upload error. Debug info dump: item, response, status, headers", item, response, stat, headers)
      $scope.displayMessage("File upload failed!", 6000, "alert");
      //This needs to be asynchronous, so the uploader knows the file has failed upload
      setTimeout( function() { $scope.clearFile() }, 10)
    }
  }

  $scope.setFileReaderCallbacks = function( fileReader ) {
    fileReader.onprogress = function( e, fileName ) {
      $scope.fileReader.progress = e.loaded / e.total * 100;
      $scope.$digest();
    }

    fileReader.onloadend = function( e ) {
      $scope.fileReader.uploadReady = true;
      $scope.$digest();
    }
  }

  $scope.setUploaderCallbacks($scope.uploader);
  $scope.setFileReaderCallbacks($scope.fileReader);

/*
 * Download section
 */

  $scope.clearIds = function() {
    $scope.download.ids = [];
  }

  $scope.download = {
    ids: []
  };

  $scope.filterNonIds = function(id) {
    var id = id.replace(/\s+/g, "");
    var isId = !!id.match(/^\d+$/)
    return ( isId ) ? id : "";
  }
} ] );


text:
package cluster_test

import (
	"testing"

	"github.com/lxc/lxd/lxd/cluster"
	"github.com/lxc/lxd/lxd/db"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// The server configuration is initially empty.
func TestConfigLoad_Initial(t *testing.T) {
	tx, cleanup := db.NewTestClusterTx(t)
	defer cleanup()

	config, err := cluster.ConfigLoad(tx)

	require.NoError(t, err)
	assert.Equal(t, map[string]interface{}{}, config.Dump())

	assert.Equal(t, float64(20), config.OfflineThreshold().Seconds())
}

// If the database contains invalid keys, they are ignored.
func TestConfigLoad_IgnoreInvalidKeys(t *testing.T) {
	tx, cleanup := db.NewTestClusterTx(t)
	defer cleanup()

	err := tx.UpdateConfig(map[string]string{
		"foo":             "garbage",
		"core.proxy_http": "foo.bar",
	})
	require.NoError(t, err)

	config, err := cluster.ConfigLoad(tx)

	require.NoError(t, err)
	values := map[string]interface{}{"core.proxy_http": "foo.bar"}
	assert.Equal(t, values, config.Dump())
}

// Triggers can be specified to execute custom code on config key changes.
func TestConfigLoad_Triggers(t *testing.T) {
	tx, cleanup := db.NewTestClusterTx(t)
	defer cleanup()

	config, err := cluster.ConfigLoad(tx)

	require.NoError(t, err)
	assert.Equal(t, map[string]interface{}{}, config.Dump())
}

// Offline threshold must be greater than the heartbeat interval.
func TestConfigLoad_OfflineThresholdValidator(t *testing.T) {
	tx, cleanup := db.NewTestClusterTx(t)
	defer cleanup()

	config, err := cluster.ConfigLoad(tx)
	require.NoError(t, err)

	_, err = config.Patch(map[string]interface{}{"cluster.offline_threshold": "2"})
	require.EqualError(t, err, "cannot set 'cluster.offline_threshold' to '2': value must be greater than '4'")

}

// If some previously set values are missing from the ones passed to Replace(),
// they are deleted from the configuration.
func TestConfig_ReplaceDeleteValues(t *testing.T) {
	tx, cleanup := db.NewTestClusterTx(t)
	defer cleanup()

	config, err := cluster.ConfigLoad(tx)
	require.NoError(t, err)

	changed, err := config.Replace(map[string]interface{}{"core.proxy_http": "foo.bar"})
	assert.NoError(t, err)
	assert.Equal(t, map[string]string{"core.proxy_http": "foo.bar"}, changed)

	_, err = config.Replace(map[string]interface{}{})
	assert.NoError(t, err)

	assert.Equal(t, "", config.ProxyHTTP())

	values, err := tx.Config()
	require.NoError(t, err)
	assert.Equal(t, map[string]string{}, values)
}

// If some previously set values are missing from the ones passed to Patch(),
// they are kept as they are.
func TestConfig_PatchKeepsValues(t *testing.T) {
	tx, cleanup := db.NewTestClusterTx(t)
	defer cleanup()

	config, err := cluster.ConfigLoad(tx)
	require.NoError(t, err)

	_, err = config.Replace(map[string]interface{}{"core.proxy_http": "foo.bar"})
	assert.NoError(t, err)

	_, err = config.Patch(map[string]interface{}{})
	assert.NoError(t, err)

	assert.Equal(t, "foo.bar", config.ProxyHTTP())

	values, err := tx.Config()
	require.NoError(t, err)
	assert.Equal(t, map[string]string{"core.proxy_http": "foo.bar"}, values)
}


text:
package weibo4j.model;

import java.util.ArrayList;
import java.util.List;

import weibo4j.http.Response;
import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;

/**
 * 话题
 *
 * @author SinaWeibo
 * @since weibo4j-V2 1.0.0
 */
public class UserTrend extends WeiboResponse{
    private String num;
    private String hotword = null;
    private String trendId = null;
    private static final long serialVersionUID = 1925956704460743946L;

	public UserTrend() {
		super();
	}
	public UserTrend(Response res) throws WeiboException {
		super(res);
		JSONObject json = res.asJSONObject();
		try {
			num = json.getString("num");
			hotword = json.getString("hotword");
			trendId = json.getString("trend_id");
			if( json.getString("topicid")!=null)
				trendId = json.getString("topicid");
		} catch (JSONException je) {
			throw new WeiboException(je.getMessage() + ":" + json.toString(),
					je);
		}
	}
	public UserTrend(JSONObject json) throws WeiboException {
		try {
			num = json.getString("num");
			hotword = json.getString("hotword");
			trendId = json.getString("trend_id");
		} catch (JSONException je) {
			throw new WeiboException(je.getMessage() + ":" + json.toString(),
					je);
		}
	}

	public static List<UserTrend> constructTrendList(Response res) throws WeiboException {
	   	 try {
	            JSONArray list = res.asJSONArray();
	            int size = list.length();
	            List<UserTrend> trends = new ArrayList<UserTrend>(size);
	            for (int i = 0; i < size; i++) {
	            	trends.add(new UserTrend(list.getJSONObject(i)));
	            }
	            return trends;
	        } catch (JSONException jsone) {
	            throw new WeiboException(jsone);
	        } catch (WeiboException te) {
	            throw te;
	        }

	   }
	public String getNum() {
		return num;
	}
	public void setNum(String num) {
		this.num = num;
	}
	public String getHotword() {
		return hotword;
	}
	public void setHotword(String hotword) {
		this.hotword = hotword;
	}
	public String gettrendId() {
		return trendId;
	}
	public void settrendId(String trendId) {
		this.trendId = trendId;
	}
	@Override
	public String toString() {
		return "Trend [num=" + num + ", hotword=" + hotword + ", trendId="
				+ trendId + "]";
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using Ao3tracksync.Models;

namespace Ao3tracksync.Auth
{
    public class UserPrincipal : IPrincipal
    {
        public UserIdentity Identity { get; private set; }
        public User User { get { return Identity.User; } }

        public string[] Roles { get; private set; }

        public UserPrincipal(UserIdentity ident)
        {
            this.Identity = ident;
            this.Roles = Identity.Roles.Split(',');
        }

        IIdentity IPrincipal.Identity
        {
            get { return Identity; }
        }

        bool IPrincipal.IsInRole(string role)
        {
            return Roles.Contains(role.ToLowerInvariant());
        }
    }
}


text:
package com.xantoria.flippy.serialization

import org.scalatest.Suites

class SerializationSuite extends Suites(
  new SerializerSpec,
  new StringSerializerSpec,
  new NetworkingSerializerSpec,
  new NumberSerializerSpec
)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Twitterizer;

namespace Twitterizer2.TestCases
{
    [TestFixture]
    public static class UserIdListTests
    {
        [Test]
        public static void GetFriendIds()
        {
            OAuthTokens tokens = Configuration.GetTokens();

            var response = TwitterFriendship.FriendsIds(tokens, new UsersIdsOptions());
            Assert.IsNotNull(response);
            Assert.That(response.Result == RequestResult.Success);
            Assert.IsNotNull(response.ResponseObject);
            Assert.IsNotEmpty(response.ResponseObject);
        }
    }
}


text:
title: 'V8 release v9.0'
author: 'Ingvar Stepanyan ([@RReverser](https://twitter.com/RReverser)), standing inline'
avatars:
 - 'ingvar-stepanyan'
date: 2021-03-17
tags:
 - release
description: 'V8 release v9.0 brings support for RegExp match indices and various performance improvements.'
tweet: '1372227274712494084'
---
Every six weeks, we create a new branch of V8 as part of our [release process](https://v8.dev/docs/release-process). Each version is branched from V8's Git master immediately before a Chrome Beta milestone. Today we're pleased to announce our newest branch, [V8 version 9.0](https://chromium.googlesource.com/v8/v8.git/+log/branch-heads/9.0), which is in beta until its release in coordination with Chrome 90 Stable in several weeks. V8 v9.0 is filled with all sorts of developer-facing goodies. This post provides a preview of some of the highlights in anticipation of the release.

## JavaScript

### RegExp match indices

Starting in v9.0, developers may opt into getting an array of the start and end positions of matched capture groups in regular expression matches. This array is available via the `.indices` property on match objects when the regular expression has the `/d` flag.

```javascript
const re = /(a)(b)/d;      // Note the /d flag.
const m = re.exec('ab');
console.log(m.indices[0]); // Index 0 is the whole match.
// → [0, 2]
console.log(m.indices[1]); // Index 1 is the 1st capture group.
// → [0, 1]
console.log(m.indices[2]); // Index 2 is the 2nd capture group.
// → [1, 2]
```

Please see [our explainer](https://v8.dev/features/regexp-match-indices) for an in-depth dive.

### Faster `super` property access

Accessing `super` properties (for example, `super.x`) has been optimized by using V8's inline cache system and optimized code generation in TurboFan. With these changes, `super` property access is now closer to being on par with regular property access, as can be seen from the graphs below.

![Compare super property access to regular property access, optimized](/_img/fast-super/super-opt.svg)

Please see [the dedicated blog post](https://v8.dev/blog/fast-super) for more details.

### `for ( async of` disallowed

A [grammar ambiguity](https://github.com/tc39/ecma262/issues/2034) was recently discovered and [fixed](https://chromium-review.googlesource.com/c/v8/v8/+/2683221) in V8 v9.0.

The token sequence `for ( async of` now no longer parses.

## WebAssembly

### Faster JS-to-Wasm calls

V8 uses different representations for the parameters of WebAssembly and JavaScript functions. For this reason, when JavaScript calls an exported WebAssembly function, the call goes through a so-called *JS-to-Wasm wrapper*, responsible for adapting parameters from JavaScript land to WebAssembly land as well as adapting results in the opposite direction.

Unfortunately, this comes with a performance cost, which meant that calls from JavaScript to WebAssembly were not as fast as calls from JavaScript to JavaScript. To minimize this overhead the JS-to-Wasm wrapper can now be inlined at the call site, simplifying the code and removing this extra frame.

Let's say we have a WebAssembly function to add two double floating point numbers, like this:

```cpp
double addNumbers(double x, double y) {
  return x + y;
}
```

and say we call that from JavaScript to add some vectors (represented as typed arrays):

```javascript
const addNumbers = instance.exports.addNumbers;

function vectorSum(len, v1, v2) {
  const result = new Float64Array(len);
  for (let i = 0; i < len; i++) {
    result[i] = addNumbers(v1[i], v2[i]);
  }
  return result;
}

const N = 100_000_000;
const v1 = new Float64Array(N);
const v2 = new Float64Array(N);
for (let i = 0; i < N; i++) {
  v1[i] = Math.random();
  v2[i] = Math.random();
}

// Warm up.
for (let i = 0; i < 5; i++) {
  vectorSum(N, v1, v2);
}

// Measure.
console.time();
const result = vectorSum(N, v1, v2);
console.timeEnd();
```

On this simplified microbenchmark, we see the following improvements:

![Microbenchmark comparison](/_img/v8-release-90/js-to-wasm.svg)

The feature is still experimental and can be enabled through the `--turbo-inline-js-wasm-calls` flag.

For more details, see the [design document](https://docs.google.com/document/d/1mXxYnYN77tK-R1JOVo6tFG3jNpMzfueQN1Zp5h3r9aM/edit).

## V8 API

Please use `git log branch-heads/8.9..branch-heads/9.0 include/v8.h` to get a list of the API changes.

Developers with an active V8 checkout can use `git checkout -b 9.0 -t branch-heads/9.0` to experiment with the new features in V8 v9.0. Alternatively you can [subscribe to Chrome's Beta channel](https://www.google.com/chrome/browser/beta.html) and try the new features out yourself soon.


text:
package org.wso2.carbon.identity.sso.saml.builders.assertion;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xml.security.signature.XMLSignature;
import org.joda.time.DateTime;
import org.opensaml.Configuration;
import org.opensaml.common.SAMLVersion;
import org.opensaml.saml1.core.NameIdentifier;
import org.opensaml.saml2.core.*;
import org.opensaml.saml2.core.impl.*;
import org.opensaml.xml.schema.XSString;
import org.opensaml.xml.schema.impl.XSStringBuilder;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.sso.saml.SAMLSSOConstants;
import org.wso2.carbon.identity.sso.saml.builders.SignKeyDataHolder;
import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOAuthnReqDTO;
import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil;

import java.util.Iterator;
import java.util.Map;

public class DefaultSAMLAssertionBuilder implements SAMLAssertionBuilder {

    private static Log log = LogFactory.getLog(DefaultSAMLAssertionBuilder.class);

    @Override
    public void init() throws IdentityException {
    }

    @Override
    public Assertion buildAssertion(SAMLSSOAuthnReqDTO authReqDTO, DateTime notOnOrAfter, String sessionId) throws IdentityException {
        try {
            DateTime currentTime = new DateTime();
            Assertion samlAssertion = new AssertionBuilder().buildObject();
            samlAssertion.setID(SAMLSSOUtil.createID());
            samlAssertion.setVersion(SAMLVersion.VERSION_20);
            samlAssertion.setIssuer(SAMLSSOUtil.getIssuer());
            samlAssertion.setIssueInstant(currentTime);
            Subject subject = new SubjectBuilder().buildObject();

            NameID nameId = new NameIDBuilder().buildObject();

            if (authReqDTO.getUseFullyQualifiedUsernameAsSubject()) {
                nameId.setValue(authReqDTO.getUser().getAuthenticatedSubjectIdentifier());
                if (authReqDTO.getNameIDFormat() != null) {
                    nameId.setFormat(authReqDTO.getNameIDFormat());
                } else {
                    nameId.setFormat(NameIdentifier.EMAIL);
                }
            } else {
                // get tenant domain name from the username
                String tenantDomainFromUserName = authReqDTO.getUser().getTenantDomain();
                String authenticatedUserTenantDomain = SAMLSSOUtil.getUserTenantDomain();

                if (authenticatedUserTenantDomain == null
                        || !authenticatedUserTenantDomain.equals(tenantDomainFromUserName)) {
                    // this means username comes from a federated Idp. no local
                    // authenticator used.
                    // no asserted identity for the user.
                    nameId.setValue(authReqDTO.getUser().getAuthenticatedSubjectIdentifier());
                } else {
                    nameId.setValue(authReqDTO.getUser().getUserName());
                }

                nameId.setFormat(authReqDTO.getNameIDFormat());
            }

            subject.setNameID(nameId);

            SubjectConfirmation subjectConfirmation = new SubjectConfirmationBuilder()
                    .buildObject();
            subjectConfirmation.setMethod(SAMLSSOConstants.SUBJECT_CONFIRM_BEARER);
            SubjectConfirmationData scData = new SubjectConfirmationDataBuilder().buildObject();
            scData.setRecipient(authReqDTO.getAssertionConsumerURL());
            scData.setNotOnOrAfter(notOnOrAfter);
            if (!authReqDTO.isIdPInitSSO()) {
                scData.setInResponseTo(authReqDTO.getId());
            }
            subjectConfirmation.setSubjectConfirmationData(scData);
            subject.getSubjectConfirmations().add(subjectConfirmation);

            if (authReqDTO.getRequestedRecipients() != null && authReqDTO.getRequestedRecipients().length > 0) {
                for (String recipient : authReqDTO.getRequestedRecipients()) {
                    subjectConfirmation = new SubjectConfirmationBuilder()
                            .buildObject();
                    subjectConfirmation.setMethod(SAMLSSOConstants.SUBJECT_CONFIRM_BEARER);
                    scData = new SubjectConfirmationDataBuilder().buildObject();
                    scData.setRecipient(recipient);
                    scData.setNotOnOrAfter(notOnOrAfter);
                    if (!authReqDTO.isIdPInitSSO()) {
                        scData.setInResponseTo(authReqDTO.getId());
                    }
                    subjectConfirmation.setSubjectConfirmationData(scData);
                    subject.getSubjectConfirmations().add(subjectConfirmation);
                }
            }

            samlAssertion.setSubject(subject);

            AuthnStatement authStmt = new AuthnStatementBuilder().buildObject();
            authStmt.setAuthnInstant(new DateTime());

            AuthnContext authContext = new AuthnContextBuilder().buildObject();
            AuthnContextClassRef authCtxClassRef = new AuthnContextClassRefBuilder().buildObject();
            authCtxClassRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX);
            authContext.setAuthnContextClassRef(authCtxClassRef);
            authStmt.setAuthnContext(authContext);
            if (authReqDTO.isDoSingleLogout()) {
                authStmt.setSessionIndex(sessionId);
            }
            samlAssertion.getAuthnStatements().add(authStmt);

            /*
                * If <AttributeConsumingServiceIndex> element is in the <AuthnRequest> and according to
                * the spec 2.0 the subject MUST be in the assertion
                */
            Map<String, String> claims = SAMLSSOUtil.getAttributes(authReqDTO);
            if (claims != null && !claims.isEmpty()) {
                AttributeStatement attrStmt = buildAttributeStatement(claims);
                if(attrStmt != null) {
                    samlAssertion.getAttributeStatements().add(attrStmt);
                }
            }

            AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder()
                    .buildObject();
            Audience issuerAudience = new AudienceBuilder().buildObject();
            issuerAudience.setAudienceURI(authReqDTO.getIssuerWithDomain());
            audienceRestriction.getAudiences().add(issuerAudience);
            if (authReqDTO.getRequestedAudiences() != null) {
                for (String requestedAudience : authReqDTO.getRequestedAudiences()) {
                    Audience audience = new AudienceBuilder().buildObject();
                    audience.setAudienceURI(requestedAudience);
                    audienceRestriction.getAudiences().add(audience);
                }
            }
            Conditions conditions = new ConditionsBuilder().buildObject();
            conditions.setNotBefore(currentTime);
            conditions.setNotOnOrAfter(notOnOrAfter);
            conditions.getAudienceRestrictions().add(audienceRestriction);
            samlAssertion.setConditions(conditions);

            if (authReqDTO.getDoSignAssertions()) {
                SAMLSSOUtil.setSignature(samlAssertion, XMLSignature.ALGO_ID_SIGNATURE_RSA,
                        new SignKeyDataHolder(authReqDTO.getUser().getAuthenticatedSubjectIdentifier()));
            }

            return samlAssertion;
        } catch (Exception e) {
            log.error("Error when reading claim values for generating SAML Response", e);
            throw new IdentityException(
                    "Error when reading claim values for generating SAML Response", e);
        }
    }

    private AttributeStatement buildAttributeStatement(Map<String, String> claims) {

        AttributeStatement attStmt = new AttributeStatementBuilder().buildObject();
        Iterator<String> ite = claims.keySet().iterator();
        boolean atLeastOneNotEmpty = false;
        for (int i = 0; i < claims.size(); i++) {
            String claimUri = ite.next();
            String claimValue = claims.get(claimUri);
            if(claimUri != null && !claimUri.trim().isEmpty() && claimValue != null && !claimValue.trim().isEmpty()) {
                atLeastOneNotEmpty = true;
                Attribute attrib = new AttributeBuilder().buildObject();
                attrib.setName(claimUri);
                //setting NAMEFORMAT attribute value to basic attribute profile
                attrib.setNameFormat(SAMLSSOConstants.NAME_FORMAT_BASIC);
                // look
                // https://wiki.shibboleth.net/confluence/display/OpenSAML/OSTwoUsrManJavaAnyTypes
                XSStringBuilder stringBuilder = (XSStringBuilder) Configuration.getBuilderFactory().
                        getBuilder(XSString.TYPE_NAME);
                XSString stringValue = stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME);
                stringValue.setValue(claims.get(claimUri));
                attrib.getAttributeValues().add(stringValue);
                attStmt.getAttributes().add(attrib);
            }
        }
        if(atLeastOneNotEmpty){
            return attStmt;
        } else {
            return null;
        }
    }
}


text:
import React from 'react'
import { css } from 'glamor'

const Group = ({ children, flexDirection, ...props }) => (
  <div role='group' {...styles.group(flexDirection)} {...props}>
    { children }
  </div>
)

Group.defaultProps = {
  flexDirection: 'column'
}

const styles = {
  group: flexDirection => css({
    display: 'flex',
    alignItems: flexDirection === 'row' ? 'flex-end' : 'initial',
    flexDirection,
    border: 'none',
    padding: '5px 0',
    margin: 0
  })
}

export default Group


text:
package com.fruit.core.persistence.convention.exception;

import com.fruit.core.persistence.convention.constant.ExceptionConstant;

/**
 *
Description: 实体类主键不存在异常

 * @author zhangyang
 *
日期:2015年4月8日 上午11:10:14

 * @version V1.0
 */
public class PrimaryKeyNotFoundException extends RuntimeException {

	/**
	* @Fields serialVersionUID : TODO
	*/
	private static final long serialVersionUID = 1L;

    public PrimaryKeyNotFoundException(){
        super(ExceptionConstant.PrimaryKeyNotFoundMsg);
    }

    public PrimaryKeyNotFoundException(String msg){
        super(msg);
    }

    public PrimaryKeyNotFoundException(Throwable cause){
        super(cause);
    }

    public PrimaryKeyNotFoundException(String msg, Throwable cause){
        super(msg, cause);
    }

}


text:
@interface NSData (SHA)
- (NSData *)sha256;
@end


text:
using System;

namespace EightPuzzle.Costs
{
    /// <summary>
    /// Class AStarCost. This class cannot be inherited.
    /// </summary>
    sealed class AStarCost : CostBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CostBase" /> class.
        /// </summary>
        /// <param name="weight"></param>
        /// <param name="heuristic">The heuristic.</param>
        /// <exception cref="ArgumentNullException">
        /// Weight was <see langword="null"/>
        /// or
        /// Heuristic was <see langword="null"/>
        /// </exception>
        public AStarCost(IWeight weight, IHeuristic heuristic)
            : base(weight, heuristic)
        {
        }

        /// <summary>
        /// Determines the cost to perform the move, given the state.
        /// <para>
        /// This is the core of the search algorithm. A best-first search
        /// takes into account only the weight, greedy best-first only
        /// the heuristic and A* the sum of weight and heuristic.
        /// </para>
        /// </summary>
        /// <param name="prior">The a priori state.</param>
        /// <param name="posterior">The a posteriori state.</param>
        /// <param name="move">The move.</param>
        /// <returns>The cost of this operation.</returns>
        /// <exception cref="ArgumentNullException">State must not be null</exception>
        public override float DetermineCost(int[] prior, int[] posterior, Move move)
        {
            if (ReferenceEquals(prior, null)) throw new ArgumentNullException("prior", "State must not be null");
            if (ReferenceEquals(posterior, null)) throw new ArgumentNullException("posterior", "State must not be null");

            var weight = Weight.DetermineWeight(posterior, move);
            var heuristic = Heuristic.DetermineHeuristic(posterior, move);

            // A* search determines it's path cost by summing weight and heuristic
            var cost = weight + heuristic;
            return cost;
        }
    }
}


text:
package es.ucm.gpd.irparser;

import es.ucm.gpd.irparser.ast.VerificationUnit;
import es.ucm.sexp.SexpFileParser;
import es.ucm.sexp.SexpParser;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static es.ucm.gpd.irparser.Sexp2Ast.parseVU;

/**
 * This is the IR File Parser as implemented to return directly the AST in the
 * form of toplevel definitions.
 *
 * @author Santiago Saavedra
 * @see #parseAllToplevel()
 */
public class IRFileParser implements Iterator<VerificationUnit> {
    private final SexpFileParser sexp;

    public IRFileParser(InputStream in) {
        this(new SexpFileParser(in));
    }

    public IRFileParser(SexpFileParser sexp) {
        this.sexp = sexp;
    }

    public static void main(String[] args) {
        InputStream data = System.in;

        if (args.length > 0) {
            if (args[0].equals("--help")) {
                usage();
                return;
            }

            if (!args[0].equals("-")) {
                try {
                    data = new FileInputStream(args[0]);
                } catch (FileNotFoundException e) {
                    System.err.printf("File %s was not found", args[0]);
                    System.exit(1);
                }
            }
        }

        try {
            data = new FileInputStream("../cl-vc-gen/test/qsort.clir");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        List<VerificationUnit> file = new IRFileParser(data).parseAllToplevel();

        System.out.println(file);

    }

    private static void usage() {
        System.out.println("Usage: java -jar IRFileParser file.clir");
    }

    public List<VerificationUnit> parseAllToplevel() {
        List<VerificationUnit> toplevel = new ArrayList<>();
        while (sexp.hasNext()) {
            toplevel.add(next());
        }
        return toplevel;
    }

    @Override
    public boolean hasNext() {
        return sexp.hasNext();
    }

    @Override
    public VerificationUnit next() {
        try {
            return parseVU(sexp);
        } catch (SexpParser.ParseException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
<?php
namespace Application\Model;

use Application\Model\BasicModelAdapter;

class OutfitBought extends BasicModelAdapter
{

    public function __construct()
    {
    }

}


text:
namespace g{
namespace Uno{
namespace Collections{

// public abstract interface IEnumerable<T> :693
// {
uInterfaceType* IEnumerable_typeof();

struct IEnumerable
{
    void(*fp_GetEnumerator)(uObject*, uObject**);
    static uObject* GetEnumerator(const uInterface& __this) { uObject* __retval; return __this.VTable<IEnumerable>()->fp_GetEnumerator(__this, &__retval), __retval; }
};
// }

}}} // ::g::Uno::Collections


text:
@interface XCResourceManage ()
{
    XCResource *_appResource;
}
@end

@implementation XCResourceManage
- (void)dealloc
{
    [_appResource release];
    [_mainBundle release];
    [super dealloc];
}

DEFINE_SINGLETON_FOR_CLASS(XCResourceManage);

- (id)init
{
    if (self = [super init])
    {
        self.mainBundle = [[NSBundle mainBundle] bundlePath];
    }
    return self;
}

- (void)initResource
{
    _appResource = [[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:VTAPP_CURRENT_RES]] retain];
    if (_appResource == nil)
    {
        _appResource = [[XCResource alloc] init];
        _appResource.pageSettingPath = @"/Pages.bundle";
        _appResource.cssStylePath = @"/CSS.bundle";
        _appResource.imagesPath = @"/Images.bundle";
        _appResource.configPath = @"/Config.bundle";
        _appResource.xmlPath = @"/XML.bundle";

        [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:_appResource] forKey:VTAPP_CURRENT_RES];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (XCResource *)settingResource:(NSString *)imagesPath xmlPath:(NSString *)xmlPath pageSettingPath:(NSString *)pageSettingPath cssStylePath:(NSString *)cssStylePath configPath:(NSString *)configPath
{
    if (imagesPath)
        _appResource.imagesPath = imagesPath;

    if (xmlPath)
        _appResource.xmlPath = xmlPath;

    if (pageSettingPath)
        _appResource.pageSettingPath = pageSettingPath;

    if (cssStylePath)
        _appResource.cssStylePath = cssStylePath;

    if (configPath)
        _appResource.configPath = configPath;

    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:_appResource] forKey:VTAPP_CURRENT_RES];
    [[NSUserDefaults standardUserDefaults] synchronize];

    return _appResource;
}

- (NSString *)getImagesPath:(NSString *)file
{
    return [self.mainBundle stringByAppendingFormat:@"%@/%@",_appResource.imagesPath,file];
}
- (NSString *)getXmlPath:(NSString *)file
{
    return [self.mainBundle stringByAppendingFormat:@"%@/%@",_appResource.xmlPath,file];
}
- (NSString *)getPageSettingPath:(NSString *)file
{
    return [self.mainBundle stringByAppendingFormat:@"%@/%@",_appResource.pageSettingPath,file];
}
- (NSString *)getCssStylePath:(NSString *)file
{
    return [self.mainBundle stringByAppendingFormat:@"%@/%@",_appResource.cssStylePath,file];
}
- (NSString *)getConfigPath:(NSString *)file
{
    return [self.mainBundle stringByAppendingFormat:@"%@/%@",_appResource.configPath,file];
}

//获取资源包路径
- (NSString *)getImagesPath
{
    return [self.mainBundle stringByAppendingFormat:@"%@",_appResource.imagesPath];
}
- (NSString *)getXmlPath
{
    return [self.mainBundle stringByAppendingFormat:@"%@",_appResource.xmlPath];
}
- (NSString *)getPageSettingPath
{
    return [self.mainBundle stringByAppendingFormat:@"%@",_appResource.pageSettingPath];
}
- (NSString *)getCssStylePath
{
    return [self.mainBundle stringByAppendingFormat:@"%@",_appResource.cssStylePath];
}
- (NSString *)getConfigPath
{
    return [self.mainBundle stringByAppendingFormat:@"%@",_appResource.configPath];
}

- (UIImage *)getImage:(NSString *)image
{
    return [UIImage imageWithContentsOfFile:[self getImagesPath:image]];
}
@end

@implementation XCResource
- (void)dealloc
{
    [_imagesPath release];
    [_xmlPath release];
    [_pageSettingPath release];
    [_cssStylePath release];
    [_configPath release];
    [super dealloc];
}

//将对象编码(即:序列化)
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_imagesPath==nil?@"":_imagesPath forKey:@"imagesPath"];
    [aCoder encodeObject:_xmlPath==nil?@"":_xmlPath forKey:@"xmlPath"];
    [aCoder encodeObject:_pageSettingPath==nil?@"":_pageSettingPath forKey:@"pageSettingPath"];
    [aCoder encodeObject:_cssStylePath==nil?@"":_cssStylePath forKey:@"cssStylePath"];
    [aCoder encodeObject:_configPath==nil?@"":_configPath forKey:@"configPath"];
}

//将对象解码(反序列化)
- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self=[super init])
    {
        self.imagesPath =[aDecoder decodeObjectForKey:@"imagesPath"];
        self.xmlPath = [aDecoder decodeObjectForKey:@"xmlPath"];
        self.pageSettingPath =[aDecoder decodeObjectForKey:@"pageSettingPath"];
        self.cssStylePath =[aDecoder decodeObjectForKey:@"cssStylePath"];
        self.configPath = [aDecoder decodeObjectForKey:@"configPath"];
    }
    return (self);

}
@end


text:
<!DOCTYPE html>
<html>
<head>
  <link href="css/web.css" rel="stylesheet" type="text/css">
  <script src="js/jquery.js"></script>
  <script src="js/d3.js"></script>
  <script src="js/widgets.js"></script>

  <script type="text/javascript">
    $(document).ready(function() {
    });
  </script>
</head>

<body>
  <div class="content">
    <script src="js/viz.js" type="text/javascript"> </script>
  </div>
</body>

</html>


text:
package cgeo.geocaching.loaders;

import cgeo.geocaching.CacheListActivity;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.utils.Log;

import android.app.Activity;
import android.support.v4.content.AsyncTaskLoader;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.util.Collection;

import io.reactivex.functions.Function;

public abstract class AbstractSearchLoader extends AsyncTaskLoader<SearchResult> {

    public enum CacheListLoaderType {
        OFFLINE,
        POCKET,
        HISTORY,
        NEAREST,
        COORDINATE,
        KEYWORD,
        ADDRESS,
        FINDER,
        OWNER,
        MAP,
        NEXT_PAGE;

        public int getLoaderId() {
            return ordinal();
        }
    }

    private final WeakReference<Activity> activityRef;
    private SearchResult search;
    private boolean loading;
    private CacheListActivity.AfterLoadAction afterLoadAction = CacheListActivity.AfterLoadAction.NO_ACTION;

    private static class NoConnectorException extends RuntimeException {

        /**
         *
         */
        private static final long serialVersionUID = -3068184330294931088L;
    }

    /**
     * Run {@link SearchResult#parallelCombineActive(Collection, Function)} if there is at least one active connector
     * in <tt>connectors</tt>, and throw <tt>NoConnectorException</tt> otherwise.
     *
     * @param connectors
     *            a collection of connectors
     * @param func
     *            a function to apply to every connector
     * @param <C>
     *            the type of connectors
     * @return the result of {@link SearchResult#parallelCombineActive(Collection, Function)} if there is at least one
     *         active connector
     */
    protected static <C extends IConnector> SearchResult nonEmptyCombineActive(final Collection<C> connectors,
                                                                               final Function<C, SearchResult> func) {
        for (final IConnector connector : connectors) {
            if (connector.isActive()) {
                return SearchResult.parallelCombineActive(connectors, func);
            }
        }
        throw new NoConnectorException();
    }

    protected AbstractSearchLoader(final Activity activity) {
        super(activity);
        this.activityRef = new WeakReference<>(activity);
    }

    public abstract SearchResult runSearch();

    public boolean isLoading() {
        return loading;
    }

    @Override
    public SearchResult loadInBackground() {
        loading = true;
        try {
            if (search == null) {
                search = runSearch();
            } else {
                // Unless we make a new Search the Loader framework won't deliver results. It doesn't do equals only identity
                search = new SearchResult(search);
            }
        } catch (final NoConnectorException ignored) {
            final Activity activity = activityRef.get();
            if (activity != null) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, R.string.warn_no_connector, Toast.LENGTH_LONG).show();
                        activity.finish();
                    }
                });
            }
        } catch (final Exception e) {
            Log.e("Error in Loader ", e);
        }
        loading = false;
        if (search == null) {
            search = new SearchResult();
        }
        return search;
    }

    @Override
    protected void onStartLoading() {
        forceLoad();
    }

    @Override
    public void reset() {
        super.reset();
        search = null;
    }

    public CacheListActivity.AfterLoadAction getAfterLoadAction() {
        return afterLoadAction;
    }

    public void setAfterLoadAction(final CacheListActivity.AfterLoadAction afterLoadAction) {
        this.afterLoadAction = afterLoadAction;
    }
}


text:
.class Landroid/support/v4/net/TrafficStatsCompat$BaseTrafficStatsCompatImpl$SocketTags;
.super Ljava/lang/Object;
.source "TrafficStatsCompat.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/net/TrafficStatsCompat$BaseTrafficStatsCompatImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "SocketTags"
.end annotation

# instance fields
.field public statsTag:I

# direct methods
.method private constructor <init>()V
    .locals 1

    .prologue
    .line 41
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 42
    const/4 v0, -0x1

    iput v0, p0, Landroid/support/v4/net/TrafficStatsCompat$BaseTrafficStatsCompatImpl$SocketTags;->statsTag:I

    .line 41
    return-void
.end method

.method synthetic constructor <init>(Landroid/support/v4/net/TrafficStatsCompat$BaseTrafficStatsCompatImpl$SocketTags;)V
    .locals 0

    .prologue
    invoke-direct {p0}, Landroid/support/v4/net/TrafficStatsCompat$BaseTrafficStatsCompatImpl$SocketTags;-><init>()V

    return-void
.end method


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (C) 2018 The Android Open Source Project
  Licensed 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.
  -->
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#FFF"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="Title"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        android:text="Name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtTitle" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
class FilterExpression(object):
    def __init__(self, operator=None, value=None):
        self.operator = operator
        self.value = value

    def __lt__(self, other):
        return self.__class__('__lt__', other)

    def __le__(self, other):
        return self.__class__('__le__', other)

    def __eq__(self, other):
        return self.__class__('__eq__', other)

    def __ne__(self, other):
        return self.__class__('__ne__', other)

    def __gt__(self, other):
        return self.__class__('__gt__', other)

    def __ge__(self, other):
        return self.__class__('__ge__', other)

class AttributeFilter(FilterExpression):
    def __init__(self, operator=None, value=None, attribute=None):
        FilterExpression.__init__(self, operator, value)
        self.attribute = attribute

    def new(self, operator=None, value=None, attribute=None):
        return self.__class__(operator,value, attribute)

    def __lt__(self, other):
        return self.__class__('__lt__', other, self.attribute)

    def __le__(self, other):
        return self.__class__('__le__', other, self.attribute)

    def __eq__(self, other):
        return self.__class__('__eq__', other, self.attribute)

    def __ne__(self, other):
        return self.__class__('__ne__', other, self.attribute)

    def __gt__(self, other):
        return self.__class__('__gt__', other, self.attribute)

    def __ge__(self, other):
        return self.__class__('__ge__', other, self.attribute)

    def __getattr__(self, name):
        return self.__class__(operator = self.operator, value=self.value, attribute=name)

    def __getitem__(self, item):
        return self.__class__(operator = self.operator, value=self.value, attribute=item)

class GroupByFilter(FilterExpression):
    def __init__(self, value=None):
        FilterExpression.__init__(self, operator='groupby', value=value)

    def __call__(self, value):
        return self.__class__(value)

    def __getitem__(self, value):
        return self.__class__(value)

class FlexibleOperatorMixin(object):
    def _op_function(self, dataframe):
        return getattr(dataframe, self.operator)

class AttributeFlexibleOperatorMixin(object):
    def _op_function(self, dataframe):
        return getattr(dataframe[self.attribute], self.operator)


text:
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using ps.dmv.common.Security;
using ps.dmv.domain.application.Core;
using ps.dmv.infrastructure.Models;
using ps.dmv.interfaces.Managers;

namespace ps.dmv.domain.application.Managers
{
    public class SecurityManager : ManagerBase<object>, ISecurityManager
    {
        public UserManager<ApplicationUser> _userManager { get; private set; }

        public SecurityManager()
        {
            _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        }

        public async Task<ApplicationUser> GetUserAsync(string userName, string password)
        {
            ApplicationUser user = await _userManager.FindAsync(userName, password);

            return user;
        }

        public async Task<ClaimsIdentity> CreateIdentityAsync(ApplicationUser applicationUser, string defaultAuthenticationTypes)
        {
            return await _userManager.CreateIdentityAsync(applicationUser, defaultAuthenticationTypes);
        }

        public async Task<IdentityResult> CreateRegistrationAsync(ApplicationUser applicationUser, string password)
        {
            return await _userManager.CreateAsync(applicationUser, password);
        }

        public async Task<IdentityResult> RemoveLoginAsync(string userId, UserLoginInfo login)
        {
            return await _userManager.RemoveLoginAsync(userId, login);
        }

        public async Task<IdentityResult> ChangePasswordAsync(string userId, string currentPassword, string newPassword)
        {
            return await _userManager.ChangePasswordAsync(userId, currentPassword, newPassword);
        }

        public async Task<IdentityResult> AddPasswordAsync(string userId, string password)
        {
            return await _userManager.AddPasswordAsync(userId, password);
        }

        public async Task<ApplicationUser> FindAsync(UserLoginInfo login)
        {
            return await _userManager.FindAsync(login);
        }

        public async Task<IdentityResult> AddLoginAsync(string userId, UserLoginInfo login)
        {
            return await _userManager.AddLoginAsync(userId, login);
        }

        public async Task<IdentityResult> CreateAsync(ApplicationUser user)
        {
            return await _userManager.CreateAsync(user);
        }

        public void Dispose()
        {
            _userManager.Dispose();
        }

        public IList<UserLoginInfo> GetLogins(string userId)
        {
            return _userManager.GetLogins(userId);
        }

        public ApplicationUser FindById(string userId)
        {
            return _userManager.FindById(userId);
        }

        public bool HasPassword(string userId)
        {
            var user = this.FindById(userId);

            if (user != null)
            {
                return user.PasswordHash != null;
            }
            return false;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PSW
{
    public partial class products : System.Web.UI.Page
    {
        public static List<string> lista = new List<string>();

        protected void Page_Load(object sender, EventArgs e)
        {
            pizzas.Visible = false;
            pastas.Visible = false;
            salad.Visible = false;

            countValue.Text = "0";
        }

        public void productsVisibility(object sender, EventArgs e)
        {
            pizzas.Visible = RadioButtonList1.SelectedItem.Text.Equals("Pizza");
            pastas.Visible = RadioButtonList1.SelectedItem.Text.Equals("Makarony");
            salad.Visible = RadioButtonList1.SelectedItem.Text.Equals("Sałatki");
        }

        public void koszyk(object sender, EventArgs e)
        {
            if (Margerita.Checked && Array.IndexOf(lista.ToArray(), "Margerita") == -1)
            {
                lista.Add("Margerita");
            }
            if (Roma.Checked && Array.IndexOf(lista.ToArray(), "Roma") == -1)
            {
                lista.Add("Roma");
            }
            if (Funghi.Checked && Array.IndexOf(lista.ToArray(), "Funghi") == -1)
            {
                lista.Add("Funghi");
            }
            if (Hawaii.Checked && Array.IndexOf(lista.ToArray(), "Hawaii") == -1)
            {
                lista.Add("Hawaii");
            }
            if (Carbonara.Checked && Array.IndexOf(lista.ToArray(), "Carbonara") == -1)
            {
                lista.Add("Carbonara");
            }
            if (Bolognese.Checked && Array.IndexOf(lista.ToArray(), "Bolognese") == -1)
            {
                lista.Add("Bolognese");
            }
            if (Napoli.Checked && Array.IndexOf(lista.ToArray(), "Napoli") == -1)
            {
                lista.Add("Napoli");
            }
            if (Grecka.Checked && Array.IndexOf(lista.ToArray(), "Grecka") == -1)
            {
                lista.Add("Grecka");
            }
            if (Cezar.Checked && Array.IndexOf(lista.ToArray(), "Cezar") == -1)
            {
                lista.Add("Cezar");
            }
            if (Wiosenna.Checked && Array.IndexOf(lista.ToArray(), "Wiosenna") == -1)
            {
                lista.Add("Wiosenna");
            }
            if (Caprese.Checked && Array.IndexOf(lista.ToArray(), "Caprese") == -1)
            {
                lista.Add("Caprese");
            }

            countValue.Text = lista.Count.ToString();
        }

        public void czysc(object sender, EventArgs e)
        {
            lista.Clear();
            Margerita.Checked = false;
            Roma.Checked = false;
            Funghi.Checked = false;
            Hawaii.Checked = false;
            Carbonara.Checked = false;
            Bolognese.Checked = false;
            Napoli.Checked = false;
            Grecka.Checked = false;
            Cezar.Checked = false;
            Wiosenna.Checked = false;
            Caprese.Checked = false;

            countValue.Text = lista.Count.ToString();
        }
    }
}


text:
<?php

namespace ickx\fw2\mvc\app\controllers\interfaces;

/**
 * Flywheel2 コントローラインターフェースです。
 *
 * @category	Flywheel2
 * @package		mvc
 * @author		wakaba <wakabadou@gmail.com>
 * @license		http://opensource.org/licenses/MIT The MIT License MIT
 * @varsion		2.0.0
 */
interface IController {
	const NEXT_RENDERING	= 'NEXT_RENDERING';
	const NEXT_REDIRECT		= 'NEXT_REDIRECT';
	const NEXT_FORWARD		= 'NEXT_FORWARD';
	const NEXT_CALLER		= 'NEXT_CALLER';

	const DEFAULT_CONTROLLER	= 'index';
	const DEFAULT_ACTION		= 'index';
	const DEFAULT_NEXT_NAME		= 0;

	const SAFIX_APPSETUP	= 'AppSetup';
	const SAFIX_SETUP		= 'Setup';
	const SAFIX_VALIDATE	= 'Validate';
	const SAFIX_ACTION		= 'Action';
	const SAFIX_Rule		= 'Rule';
	const SAFIX_RENDER		= 'Render';
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.less">

                PBCN

Background

Activities

Cases

Contact

Donate

Philippine Breast Cancer Network

Cases of Breast Cancer

Absence of truthful information is a patient's worst nightmare!

                <

Breast cancer won't be fatal for as long as it stays restricted to one's breast - a non-vital organ. Only when the cancer spreads (metastasizes) to a life-sustaining organ (lungs, liver or brain) does the cancer become life-threatening.

 Breast cancer takes many forms and affects each woman differently. Some cancer will never spread beyond the breast or metastasize to vital organs and some will. However, patients more than often receive full and similar treatments no matter what type  their individual cancer is.

At the time of diagnosis, it can not be determined with certainty whether or not one's breast cancer will be life-threatening. It is next to impossible to know who will benefit from surgery, chemotherapy and radiation and who will not - leaving patients with more questions than answers about their treatment options.

Many cases of breast cancer after surgery do not require chemotherapy and radiation. Reducing the risk of recurrence or metastasis can be achieved through non-toxic means. In fact, chemotherapy  can cause damage to healthy cells which triggers them to secrete a protein that sustains tumour growth and resistance to further treatment

Following are cases to help you to learn from the experiences

of others that you may find basis for your treatment options:

Early Intervention

A suspicious breast abnormality that may be seen with thermal breast imaging.
This is reason enough to intervene, not waiting for a malignant diagnosis before action is taken.

Rosalisa K. Alindahao - Diagnosed at age 42

Born on 14 December 1961 in Paco, Manila, her menarche was at age 12. At age 4, she suffered from asthma and received continuous medications. With an M.S. Degree in Economics, Shalee has been in the banking industry ever since. She started taking birth control pills intermittently at age 27 over a 10-year period.  She gave birth by cesarean section to all of her four children at ages 29, 30, 37 and 39. At the onset of her 2nd pregnancy, she experienced gestational diabetes. The longest breastfed was her 3rd child for a period of six months and the shortest was her eldest at only two weeks. Her first born died at an early age and deeply depressed her for a long period.

Rosalisa K. Alindahao - Diagnosed at age 42

Born on 14 December 1961 in Paco, Manila, her menarche was at age 12. At age 4, she suffered from asthma and received continuous medications. With an M.S. Degree in Economics, Shalee has been in the banking industry ever since. She started taking birth control pills intermittently at age 27 over a 10-year period.  She gave birth by cesarean section to all of her four children at ages 29, 30, 37 and 39. At the onset of her 2nd pregnancy, she experienced gestational diabetes. The longest breastfed was her 3rd child for a period of six months and the shortest was her eldest at only two weeks. Her first born died at an early age and deeply depressed her for a long period.

Living with Breast Cancer

The breast is not a vital organ and only when the cancer has affected the lungs or liver is one's life threatened.  Isolating the cancer and keeping it from spreading is best achieved thru non-toxic and non-invasive regimens. The PBCN has had very encouraging results with its protocol for more than 10 years.

PBCN (c) 2014, All Rights Reserved

From Webnified with <3


text:
using NUnit.Framework;

[TestFixture]
public class ComplementTest
{
  [Test]
  public void Rna_complement_of_cytosine_is_guanine()
  {
    Assert.That(Complement.OfDna("C"), Is.EqualTo("G"));
  }

  [Test]
  public void Rna_complement_of_guanine_is_cytosine()
  {
    Assert.That(Complement.OfDna("G"), Is.EqualTo("C"));
  }

  [Test]
  public void Rna_complement_of_thymine_is_adenine()
  {
    Assert.That(Complement.OfDna("T"), Is.EqualTo("A"));
  }

  [Test]
  public void Rna_complement_of_adenine_is_uracil()
  {
    Assert.That(Complement.OfDna("A"), Is.EqualTo("U"));
  }

  [Test]
  public void Rna_complement()
  {
    Assert.That(Complement.OfDna("ACGTGGTCTTAA"), Is.EqualTo("UGCACCAGAAUU"));
  }
}


text:
package org.apache.tajo.worker;

import org.apache.tajo.catalog.statistics.TableStats;
import org.apache.tajo.util.FileUtil;
import org.mortbay.log.Log;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import org.apache.tajo.QueryUnitAttemptId;
import org.apache.tajo.catalog.proto.CatalogProtos;
import org.apache.tajo.common.ProtoObject;

import java.util.Collections;
import java.util.List;

import static org.apache.tajo.TajoProtos.TaskAttemptState;
import org.apache.tajo.ipc.TajoWorkerProtocol.TaskHistoryProto;
import org.apache.tajo.ipc.TajoWorkerProtocol.FetcherHistoryProto;

/**
 * The history class for Task processing.
 */
public class TaskHistory implements ProtoObject<TaskHistoryProto> {

  private QueryUnitAttemptId queryUnitAttemptId;
  private TaskAttemptState state;
  private float progress;
  private long startTime;
  private long finishTime;
  private CatalogProtos.TableStatsProto inputStats;
  private CatalogProtos.TableStatsProto outputStats;
  private String outputPath;
  private String workingPath;

  private int finishedFetchCount;
  private int totalFetchCount;
  private List<FetcherHistoryProto> fetcherHistories;

  private String status;
  private String uri;
  private long fileLen;
  private int messageReceiveCount;

  public TaskHistory(QueryUnitAttemptId queryUnitAttemptId, TaskAttemptState state, float progress,
                     long startTime, long finishTime, CatalogProtos.TableStatsProto inputStats) {
    init();
    this.queryUnitAttemptId = queryUnitAttemptId;
    this.state = state;
    this.progress = progress;
    this.startTime = startTime;
    this.finishTime = finishTime;
    this.inputStats = inputStats;
  }

//<<<<<<< HEAD
//    private String status;
//    private String uri;
//    private long fileLen;
//    private int messageReceiveCount;
//    private int startcount=1;
//    private int finishcount=1;
//
//    public long getStartTime() {
//        Log.info("====================>" + startcount + "Fetch Start time : " + startTime);
//        startcount++;
//        return startTime; }
//=======
  public TaskHistory(TaskHistoryProto proto) {
    this.queryUnitAttemptId = new QueryUnitAttemptId(proto.getQueryUnitAttemptId());
    this.state = proto.getState();
    this.progress = proto.getProgress();
    this.startTime = proto.getStartTime();
    this.finishTime = proto.getFinishTime();
    this.inputStats = proto.getInputStats();

    if (proto.hasOutputStats()) {
      this.outputStats = proto.getOutputStats();
    }

    if (proto.hasOutputPath()) {
      this.outputPath = proto.getOutputPath();
    }

//<<<<<<< HEAD
//    public long getFinishTime() {
//        Log.info("====================>" + finishcount + "Fetch Finish time : " + finishTime);
//        finishcount++;
//        return finishTime; }
//=======
    if (proto.hasWorkingPath()) {
      this.workingPath = proto.getWorkingPath();
    }

    if (proto.hasFinishedFetchCount()) {
      this.finishedFetchCount = proto.getFinishedFetchCount();
    }

    if (proto.hasTotalFetchCount()) {
      this.totalFetchCount = proto.getTotalFetchCount();
    }

    this.fetcherHistories = proto.getFetcherHistoriesList();
  }

  private void init() {
    this.fetcherHistories = Lists.newArrayList();
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(queryUnitAttemptId, state);
  }

  @Override
  public boolean equals(Object o) {
    if (o instanceof TaskHistory) {
      TaskHistory other = (TaskHistory) o;
      return getProto().equals(other.getProto());
    }
    return false;
  }

  @Override
  public TaskHistoryProto getProto() {
    TaskHistoryProto.Builder builder = TaskHistoryProto.newBuilder();
    builder.setQueryUnitAttemptId(queryUnitAttemptId.getProto());
    builder.setState(state);
    builder.setProgress(progress);
    builder.setStartTime(startTime);
    builder.setFinishTime(finishTime);
    builder.setInputStats(inputStats);

    if (outputStats != null) {
      builder.setOutputStats(outputStats);
    }

    if (workingPath != null) {
      builder.setWorkingPath(workingPath);
    }

    if (totalFetchCount > 0) {
      builder.setTotalFetchCount(totalFetchCount);
      builder.setFinishedFetchCount(finishedFetchCount);
    }

    builder.addAllFetcherHistories(fetcherHistories);
    return builder.build();
  }

  public long getStartTime() { return startTime; }

  public long getFinishTime() { return finishTime; }

  public List<FetcherHistoryProto> getFetcherHistories() {
    return Collections.unmodifiableList(fetcherHistories);
  }

  public boolean hasFetcherHistories(){
    return totalFetchCount > 0;
  }

  public void addFetcherHistory(FetcherHistoryProto fetcherHistory) {
    fetcherHistories.add(fetcherHistory);
  }

  public QueryUnitAttemptId getQueryUnitAttemptId() {
    return queryUnitAttemptId;
  }

  public TaskAttemptState getState() {
    return state;
  }

  public float getProgress() {
    return progress;
  }

  public CatalogProtos.TableStatsProto getInputStats() {
    return inputStats;
  }

  public String getOutputPath() {
    return outputPath;
  }

  public void setOutputPath(String outputPath) {
    this.outputPath = outputPath;
  }

  public String getWorkingPath() {
    return workingPath;
  }

  public void setWorkingPath(String workingPath) {
    this.workingPath = workingPath;
  }

  public Integer getFinishedFetchCount() {
    return finishedFetchCount;
  }

  public void setFinishedFetchCount(int finishedFetchCount) {
    this.finishedFetchCount = finishedFetchCount;
  }

  public Integer getTotalFetchCount() {
    return totalFetchCount;
  }

  public void setTotalFetchCount(int totalFetchCount) {
    this.totalFetchCount = totalFetchCount;
  }

  public CatalogProtos.TableStatsProto getOutputStats() {
    return outputStats;
  }

  public void setOutputStats(CatalogProtos.TableStatsProto outputStats) {
    this.outputStats = outputStats;
  }
}


text:
<?php

namespace Kunstmaan\NodeSearchBundle\Tests\DependencyInjection;

use Kunstmaan\NodeSearchBundle\DependencyInjection\KunstmaanNodeSearchExtension;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Kunstmaan\AdminBundle\Tests\unit\AbstractPrependableExtensionTestCase;

/**
 * Class KunstmaanNodeSearchExtensionTest
 */
class KunstmaanNodeSearchExtensionTest extends AbstractPrependableExtensionTestCase
{
    /**
     * @return ExtensionInterface[]
     */
    protected function getContainerExtensions()
    {
        return [new KunstmaanNodeSearchExtension()];
    }

    public function testCorrectParametersHaveBeenSet()
    {
        $this->load();

        $this->assertContainerBuilderHasParameter('kunstmaan_node_search.search_configuration.node.class', 'Kunstmaan\NodeSearchBundle\Configuration\NodePagesConfiguration');
        $this->assertContainerBuilderHasParameter('kunstmaan_node_search.indexname', 'nodeindex');
        $this->assertContainerBuilderHasParameter('kunstmaan_node_search.indextype', 'page');
        $this->assertContainerBuilderHasParameter('kunstmaan_node_search.search.node.class', 'Kunstmaan\NodeSearchBundle\Search\NodeSearcher');
        $this->assertContainerBuilderHasParameter('kunstmaan_node_search.search_service.class', 'Kunstmaan\NodeSearchBundle\Services\SearchService');
        $this->assertContainerBuilderHasParameter('kunstmaan_node_search.node_index_update.listener.class', 'Kunstmaan\NodeSearchBundle\EventListener\NodeIndexUpdateEventListener');
    }
}


text:
<?php

class Google_Service_Dfareporting_MobileCarriersListResponse extends Google_Collection
{
  protected $collection_key = 'mobileCarriers';
  public $kind;
  protected $mobileCarriersType = 'Google_Service_Dfareporting_MobileCarrier';
  protected $mobileCarriersDataType = 'array';

  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  /**
   * @param Google_Service_Dfareporting_MobileCarrier[]
   */
  public function setMobileCarriers($mobileCarriers)
  {
    $this->mobileCarriers = $mobileCarriers;
  }
  /**
   * @return Google_Service_Dfareporting_MobileCarrier[]
   */
  public function getMobileCarriers()
  {
    return $this->mobileCarriers;
  }
}


text:
package com.github.dreamhead.moco.parser.model;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.dreamhead.moco.RequestMatcher;
import com.github.dreamhead.moco.parser.RequestMatcherFactory;
import com.google.common.base.MoreObjects;

import java.util.Map;

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class RequestSetting extends BaseResourceSetting {
    private final RequestMatcherFactory factory = new DynamicRequestMatcherFactory();

    private TextContainer uri;

    private TextContainer method;
    private TextContainer version;
    private Object json;

    private Map<String, TextContainer> headers;
    private Map<String, TextContainer> xpaths;
    @JsonProperty("json_paths")
    private Map<String, TextContainer> jsonPaths;
    private Map<String, TextContainer> queries;
    private Map<String, TextContainer> cookies;
    private Map<String, TextContainer> forms;

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this).omitNullValues()
                .add("version", version)
                .add("URI", uri)
                .add("text", text)
                .add("file", file)
                .add("path resource", pathResource)
                .add("json", json)
                .add("method", method)
                .add("headers", headers)
                .add("xpaths", xpaths)
                .add("json path", jsonPaths)
                .add("queries", queries)
                .add("cookies", cookies)
                .add("forms", forms)
                .toString();
    }

    public RequestMatcher getRequestMatcher() {
        return factory.createRequestMatcher(this);
    }
}


text:
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
namespace Microsoft.HBase.Client.Filters
{
    using System.Globalization;
    using Microsoft.HBase.Client.Internal;

    /// <summary>
    ///
    /// </summary>
    public class WhileMatchFilter : Filter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WhileMatchFilter"/> class.
        /// </summary>
        /// <param name="filter">The filter.</param>
        public WhileMatchFilter(Filter filter)
        {
            filter.ArgumentNotNull("filter");

            Filter = filter;
        }

        /// <summary>
        /// Gets the filter.
        /// </summary>
        /// <value>
        /// The filter.
        /// </value>
        public Filter Filter { get; private set; }

        /// <inheritdoc/>
        public override string ToEncodedString()
        {
            const string filterPattern = @"{{""type"":""WhileMatchFilter"",""filters"":[{0}]}}";
            return string.Format(CultureInfo.InvariantCulture, filterPattern, Filter.ToEncodedString());
        }
    }
}


text:
typedef void (^selectCellBlock)(NSDictionary* dict);

@interface ParameterTableViewController : UITableViewController

- (void)setSelectCellBlock:(selectCellBlock)block;
@property (nonatomic, strong)NSString* vcTitle;

@end