text:
<?php

namespace Parc\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class DocumentType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $container = new ContainerBuilder();
		$builder
            ->add('fichier','file')
            ->add('categorie','choice', array('choices'=>array("Baguage" =>'Baguage', "Formulaire"=>'Formulaire', "Divers"=>'Divers')))
            ->add('nom')
            ->add('Enregistrer','submit',array('attr' => array('class' => 'button_submit button_enregistrer' ),))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Parc\AdminBundle\Entity\Document'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'parc_adminbundle_document';
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Proxies\__CG__\Front\UserBundle\Entity;

/**
 * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
 */
class User extends \Front\UserBundle\Entity\User implements \Doctrine\ORM\Proxy\Proxy
{
    private $_entityPersister;
    private $_identifier;
    public $__isInitialized__ = false;
    public function __construct($entityPersister, $identifier)
    {
        $this->_entityPersister = $entityPersister;
        $this->_identifier = $identifier;
    }
    /** @private */
    public function __load()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;

            if (method_exists($this, "__wakeup")) {
                // call this after __isInitialized__to avoid infinite recursion
                // but before loading to emulate what ClassMetadata::newInstance()
                // provides.
                $this->__wakeup();
            }

            if ($this->_entityPersister->load($this->_identifier, $this) === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            unset($this->_entityPersister, $this->_identifier);
        }
    }

    /** @private */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int) $this->_identifier["id"];
        }
        $this->__load();
        return parent::getId();
    }

    public function setUsername($username)
    {
        $this->__load();
        return parent::setUsername($username);
    }

    public function getUsername()
    {
        $this->__load();
        return parent::getUsername();
    }

    public function setFirstName($firstName)
    {
        $this->__load();
        return parent::setFirstName($firstName);
    }

    public function getFirstName()
    {
        $this->__load();
        return parent::getFirstName();
    }

    public function setLastName($lastName)
    {
        $this->__load();
        return parent::setLastName($lastName);
    }

    public function getLastName()
    {
        $this->__load();
        return parent::getLastName();
    }

    public function __sleep()
    {
        return array('__isInitialized__', 'id', 'username', 'firstName', 'lastName');
    }

    public function __clone()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;
            $class = $this->_entityPersister->getClassMetadata();
            $original = $this->_entityPersister->load($this->_identifier);
            if ($original === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            foreach ($class->reflFields as $field => $reflProperty) {
                $reflProperty->setValue($this, $reflProperty->getValue($original));
            }
            unset($this->_entityPersister, $this->_identifier);
        }

    }
}


text:
var Ostatus = require("ostatus")
,   As = Ostatus.as
,   Util = require("util")
,	Flow = require("flow")
,	Http = require("../support/http")
,	Url = require("url")
,   Shoutr = require("shoutr")
,   Api = require("../service/api");

function routes(app){

    app.get('/users/:user', function(req, res, next){
    	var username = req.params.user;
    	var profile, updates;
    	var host = Shoutr.config.host;
    	var api = new Api();
    	Flow.exec(
			function() {
				api.getProfile(username, this);
			},
    		function (err, result) {
	    		if (err) return Http.response(res, err.message, 500, "text/plain");
	    		profile = result;
	    		profile.username = username;
	        	api.getActivities(username, this);
			},
			function (err, result) {
				if (err) return Http.response(res, err.message, 500, "text/plain");
				updates = result;
				Mu.compile(Path.join(__dirname,'../templates/user.html.mu'), this);
			},
			function (err, parsed) {
				    if (err) return Http.response(res, err.message, 500, "text/plain");
				    var buffer = '';
				    var context = profile;
				    context.updates = updates;
				    context.host = host;
				    if (updates && updates.length > 0) context.updated = updates[0].updated;
				    Mu.render(parsed,context)
				      .on('data', function (c) { buffer += c.toString(); })
				      .on('end', function () {Http.response(res, buffer, 200, "text/html");})
				      .on('error', function(err) {Http.response(res, err.message, 500, "text/plain");});
			});
    });
}

exports.routes  = routes;


text:
extern cv::SurfFeatureDetector surfDetector;
extern cv::SurfDescriptorExtractor surfExtractor;

namespace pmv {
    class Object {
        private:
            cv::Mat imageMat;
            cv::vector<cv::KeyPoint> keypoints;
            cv::Mat descriptors;
            cv::Scalar color;
            std::string name;

        public:
            Object(const char *fileName);
            cv::Mat getImageMat();
            cv::vector<cv::KeyPoint> getKeypoints();
            cv::Mat getDescriptors();
            cv::Scalar getColor();
            std::string getName();
    };
}

#endif


text:
function limitTextLength(config) {
	if (!config.element) {
		throw new Error("No element provided");
	}
	if(!config.maxLength) {
		throw new Error("No maxLength provided");
	}
	element = jQuery(config.element);
	var originalText = element.text();
	if (originalText.length > config.maxLength) {
		var trimmedText = originalText.substring(0, config.maxLength),
			trimmedText = trimmedText.substring(0, Math.min(trimmedText.length, trimmedText.lastIndexOf(" "))),
			leftOut = originalText.substring(trimmedText.length),
			hoverCTA = jQuery("<span>...</span>");
		if (config.class) {
			hoverCTA.addClass(config.class);
		}
		if (config.css) {
			hoverCTA.css(config.css);
		}
		if (typeof config.enter !== "function") {
			config.enter = function () {
				jQuery(this).text(leftOut);
			}
		}
		if (typeof config.leave !== "function") {
			config.leave = function () {
				jQuery(this).text("...");
			}
		}

		hoverCTA.on("mouseenter", function () {
			config.enter.apply(this, [leftOut, originalText]);
		});

		hoverCTA.on("mouseleave", function () {
			config.leave.apply(this, [leftOut, originalText]);
		});

		element.text(trimmedText).append(hoverCTA);
	}
}


text:
using namespace cocos2d;

namespace dragonBones
{
    Armature* CCDragonBones::buildArmature(const char* skeletonXMLFile,
        const char* textureXMLFile,
        const char* dragonBonesName,
        const char* armatureName,
        const char* animationName)
    {
        Cocos2dxFactory *fac = Cocos2dxFactory::getInstance();
        fac->loadSkeletonFile(skeletonXMLFile, dragonBonesName);
        fac->loadTextureAtlasFile(textureXMLFile, dragonBonesName);
        return fac->buildArmature(armatureName, animationName, dragonBonesName);
    }

    CCDragonBones*	CCDragonBones::create(const char* skeletonXMLFile,
        const char* dragonBonesName,
        const char* armatureName)
    {
        return CCDragonBones::create(skeletonXMLFile,
            "texture.xml",
            dragonBonesName,
            armatureName,
            "");
    }

    CCDragonBones*	CCDragonBones::create(const char* skeletonXMLFile,
        const char* textureXMLFile,
        const char* dragonBonesName,
        const char* armatureName,
        const char* animationName)
    {
        CCDragonBones* pNew = new CCDragonBones();
        if (pNew && pNew->init())
        {
            Armature* arm = CCDragonBones::buildArmature(skeletonXMLFile,
                textureXMLFile,
                dragonBonesName,
                armatureName,
                animationName);
            pNew->initWithArmature(arm);
            pNew->autorelease();
            return pNew;
        }
        CC_SAFE_DELETE(pNew);
        return NULL;
    }

    CCDragonBones* CCDragonBones::create(Armature*arm)
    {
        CCDragonBones* pNew = new CCDragonBones();
        if (pNew && pNew->init())
        {
            pNew->initWithArmature(arm);
            pNew->autorelease();
            return pNew;
        }
        CC_SAFE_DELETE(pNew);
        return NULL;
    }

    CCDragonBones::CCDragonBones()
    {

    }

    CCDragonBones::~CCDragonBones()
    {
//        DB_SAFE_DELETE(m_Armature);
//        this->unscheduleAllSelectors();
    }

    void CCDragonBones::update(float dt)
    {
        if (m_Armature)
            m_Armature->advanceTime(dt);
    }

    CCNode* CCDragonBones::getDisplayNode()
    {
        return static_cast<CocosNode*>(m_Armature->getDisplay())->getNode();
    }

    Armature* CCDragonBones::getArmature()
    {
        return m_Armature;
    }

    void  CCDragonBones::addEventListener(const String &type, const String &key, cocos2d::CCObject*pObj, SEL_CallFuncND callback)
    {
        m_Caller = pObj;
        m_Callback = callback;
//        EventDispatcher::Function f = &CCDragonBones::eventBridge;
//        Function f = std::bind(&CCDragonBones::eventBridge, this, std::placeholders::_1);
        m_Armature->addEventListener(type, this, function_selector(CCDragonBones::eventBridge), key);
    }

    bool CCDragonBones::hasEventListener(const String &type)
    {
        return m_Armature->hasEventListener(type);
    }
    void CCDragonBones::removeEventListener(const String &type, const std::string &key)
    {
        m_Armature->removeEventListener(type, key);
    }
    void CCDragonBones::dispatchEvent(Event *event)
    {
        m_Armature->dispatchEvent(event);
    }

    void CCDragonBones::eventBridge(Event*e){
        (m_Caller->*m_Callback)(this, e);
    }

    void CCDragonBones::gotoAndPlay(
        const String &animationName,
        Number fadeInTime,
        Number duration,
        Number loop,
        uint layer,
        const String &group,
        const String &fadeOutMode,
        bool displayControl,
        bool pauseFadeOut,
        bool pauseFadeIn
        )
    {
        getAnimation()->gotoAndPlay(animationName,
            fadeInTime,
            duration,
            loop,
            layer,
            group,
            fadeOutMode,
            displayControl,
            pauseFadeOut,
            pauseFadeIn
            );
    }

    void CCDragonBones::initWithArmature(Armature*arm)
    {
        this->m_Armature = arm;
        this->schedule(schedule_selector(CCDragonBones::update), 0);
        this->addChild(static_cast<CocosNode*>(m_Armature->getDisplay())->node);
    }

    void CCDragonBones::setBoneTexture(const char* boneName, const char* textureName, const char* textureAtlasName)
    {

        Cocos2dxFactory* fac = Cocos2dxFactory::getInstance();
        Object* clothesObj = fac->getTextureDisplay(textureName, textureAtlasName);

        //CCLOG("CLOSE %d", clothesObj);

        Bone* bone = getArmature()->getBone(boneName);
        CocosNode* oldClothesObj = static_cast<CocosNode*>(bone->getDisplay());
        bone->setDisplay(clothesObj);
    }

    Animation* CCDragonBones::getAnimation()
    {
        return m_Armature->getAnimation();
    }

    CCArray* CCDragonBones::getAnimationList()
    {
         std::vector<String> aniList = getAnimation()->getAnimationList();
        CCArray* aniArr = CCArray::createWithCapacity(static_cast<unsigned int>(aniList.size()));
#if 1
        for (int i=0; i < aniList.size(); i++) {
            aniArr->addObject(CCString::create(aniList[i].c_str()));
        }
#else
        for (auto aniName : aniList)
        {
            aniArr->addObject(CCString::create(aniName.c_str()));
            CCLOG("###########\n aniName %s ########\n", aniName.c_str());
        }
#endif
        return aniArr;
    }
#if 1
    void CCDragonBones::onExit()
    {
		DB_SAFE_DELETE(m_Armature);
        this->unscheduleAllSelectors();
        CCNode::onExit();
    }
#endif
}


text:
set -e # fail on unhandled error
set -u # fail on undefined variable
#set -x # debug

readonly tmpFile=$(pwd)/.hf.bl.txt
declare -a sysTools=("perl" "cut" "sort" "paste" "wc" "tr" "cat")

usage() {
cat <<_EOF

  Usage: $(basename $0) [options]
    OPTIONS:
      -i|--input   : input crash(es) directory / file
      -B|--bl-file : output file to save found hashes (merge if exists)
      -e|--ext     : file extension of fuzzer files (e.g. fuzz)
      -a|--arch    : arch fuzzer have run against ('MAC' or 'LINUX')

    INFO:
      * Blacklist file sort mode only requires [-B/--bl-file] argument
      * Hashes gather mode requires all argument to be set
_EOF
  exit 1
}

command_exists () {
    type "$1" &> /dev/null ;
}

# Check that system tools exist
for i in "${sysTools[@]}"
do
  if ! command_exists $i; then
    echo "[-] '$i' command not found"
    exit 1
  fi
done

INPUT_DIR=""
BL_FILE=""
FILE_EXT=""
ARCH=""

nArgs=$#
while [[ $# > 1 ]]
do
  arg="$1"
  case $arg in
    -i|--input)
      INPUT_DIR="$2"
      shift
      ;;
    -B|--bl-file)
      BL_FILE="$2"
      shift
      ;;
    -e|--ext)
      FILE_EXT="$2"
      shift
      ;;
    -a|--arch)
      ARCH="$2"
      shift
      ;;
    *)
      echo "[-] Invalid argument '$1'"
      usage
      ;;
  esac
  shift
done

gatherMode=false

# Sort only mode
if [[ "$BL_FILE" == "" ]]; then
  echo "[-] Missing blacklist file"
  usage
fi

# Hashes gather mode
if [ $nArgs -gt 2 ]; then
  if [[ "$INPUT_DIR" == "" || ! -e "$INPUT_DIR" ]]; then
    echo "[-] Missing or invalid input directory"
    usage
  fi

  if [[ "$FILE_EXT" == "" ]]; then
    echo "[-] Missing file extension"
    usage
  fi

  if [[ "$ARCH" != "MAC" && "$ARCH" != "LINUX" ]]; then
    echo "[-] Invalid architecture, expecting 'MAC' or 'LINUX'"
    usage
  fi

  if [[ "$ARCH" == "LINUX" ]]; then
    STACKHASH_FIELD=5
  elif [[ "$ARCH" == "MAC" ]]; then
    STACKHASH_FIELD=6
  else
    echo "[-] Unsupported architecture"
    exit 1
  fi
  gatherMode=true
fi

# save old data
if [ -f $BL_FILE ]; then
  cat $BL_FILE > $tmpFile
  oldCount=$(cat $BL_FILE | wc -l | tr -d " ")
else
  oldCount=0
fi

if $gatherMode; then
  echo "[*] Processing files from '$INPUT_DIR' ..."
  find $INPUT_DIR -type f -iname "*.$FILE_EXT" | while read -r FILE
  do
    fileName=$(basename $FILE)
    if ! echo $fileName | grep -qF ".STACK."; then
      echo "[!] Skipping '$FILE'"
      continue
    fi
    stackHash=$(echo $fileName | cut -d '.' -f$STACKHASH_FIELD)

    # We don't want to lose crashes where unwinder failed
    if [[ "$stackHash" != "0" && ! "$stackHash" =~ ^badbad.* ]]; then
      echo $stackHash >> $tmpFile
    fi
  done
fi

# sort hex values
echo "[*] Sorting blacklist file entries"
perl -lpe '$_=hex' $tmpFile | \
paste -d" " - $tmpFile  | sort -nu | cut -d" " -f 2- \
> $BL_FILE

entries=$(cat $BL_FILE | wc -l | tr -d " ")
echo "[*] $BL_FILE contains $entries blacklisted stack hashes"

rm $tmpFile


text:
package com.shunwang.apitools.util.compile;

import com.shunwang.apitools.constant.Constants;
import com.shunwang.apitools.core.listener.AppConfig;
import com.shunwang.apitools.util.wildcard.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @author min.da
 * @since 2015-12-11
 */
public class Compiler {

    private static final Logger logger = LoggerFactory.getLogger(Compiler.class);

    private static Compiler instance = new Compiler();

    private Compiler() {
    }

    public static Compiler getInstance() {
        return instance;
    }

    public boolean run(String sourcePath) {
        logger.info("准备编译,目标地址[{}]", sourcePath);
        Paths paths = new Paths(sourcePath, Constants.ALL_JAVA_PATTERNS);

        List<File> files = new ArrayList<File>();
        Set<String> names = new HashSet<String>();
        for (File file : paths.getFiles()) {
            //这里直接约定好过滤同名的java文件,所以demo中要避免同名的类文件,还有一种方式是截取java目录下的完整类路径(含包路径),相同的过滤。
            String name = file.getName();
            if (!names.contains(name)) {
                try {
                    logger.info("扫描待编译java源文件[{}]", file.getCanonicalPath());
                } catch (IOException ignored) {
                }
                names.add(name);
                files.add(file);
            }
        }

        if (files.size() == 0) return false;

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);

//        URL url = Thread.currentThread().getContextClassLoader().getResource("");
//        String classPath = url != null ? url.getPath() : null;
        String classPath = AppConfig.getOutputPath();

        logger.info("classPath[{}]", classPath);
        // javac -help
        // -d <目录> 指定存放生成的类文件的位置
        // -cp <路径> 指定查找用户类文件的位置(主要解决要编译的java文件中import的一些其他类)
        // -sourcepath <路径> 指定查找输入源文件的位置
        // -classpath <路径> 指定查找用户类文件的位置
        Iterable<String> options = Arrays.asList("-d", classPath, "-cp", classPath, "-sourcepath", sourcePath, "-encoding", Constants.CHARSET_UTF8);

        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);

        logger.info("Performs this compilation task...");
        boolean result = task.call();
        logger.info("Compile complete");

        if (!result) {
            for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
                logger.error(diagnostic.getCode());
                logger.error(String.valueOf(diagnostic.getKind()));
                logger.error(String.valueOf(diagnostic.getPosition()));
                logger.error(String.valueOf(diagnostic.getStartPosition()));
                logger.error(String.valueOf(diagnostic.getEndPosition()));
                logger.error(String.valueOf(diagnostic.getSource()));
                logger.error(diagnostic.getMessage(null));
            }
        }

        try {
            fileManager.close();
        } catch (IOException ignored) {
            // ignored
        }

        return result;
    }
}


text:
@interface AppDelegate () <UISplitViewControllerDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //友盟分享
    [self configUmengShareFunction];

    [[FBSDKApplicationDelegate sharedInstance] application:application
                             didFinishLaunchingWithOptions:launchOptions];

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self choseWindowRootViewController];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(choseWindowRootViewController) name:changeWindowRootViewNotifaction object:nil];
    HDLog(@"%@", NSStringFromCGRect(ScreenBounds));

    return YES;
}

- (void)choseWindowRootViewController
{
//    if (!read(guide))
//    {
//        self.window.rootViewController = [[GuideViewController alloc] init];
//    }else if (!read(login))
//    {
//        self.window.rootViewController = [[LoginViewController alloc] init];
//    }else
//    {
//        self.tabBarCtl = [[XXTabBarController alloc] init];
//        self.window.rootViewController = self.tabBarCtl;
//    }
    self.tabBarCtl = [[XXTabBarController alloc] init];
    self.window.rootViewController = self.tabBarCtl;
    [self.window makeKeyAndVisible];
}

- (void)configUmengShareFunction
{
    //设置友盟社会化组件appkey
    [UMSocialData setAppKey:UmengAppkey];

    //打开调试log的开关
    [UMSocialData openLog:YES];

    //如果你要支持不同的屏幕方向,需要这样设置,否则在iPhone只支持一个竖屏方向
    //    [UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskAll];

    //设置微信AppId,设置分享url,默认使用友盟的网址
    [UMSocialWechatHandler setWXAppId:@"wxdc1e388c3822c80b" appSecret:@"a393c1527aaccb95f3a4c88d6d1455f6" url:@"http://www.umeng.com/social"];

    // 打开新浪微博的SSO开关
    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"3921700954"
                                              secret:@"04b48b094faeb16683c32669824ebdad"
                                         RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];

    //    //设置分享到QQ空间的应用Id,和分享url 链接
    [UMSocialQQHandler setQQWithAppId:@"100424468" appKey:@"c7394704798a158208a74ab60104f0ba" url:@"http://www.umeng.com/social"];
    //    //设置支持没有客户端情况下使用SSO授权
    [UMSocialQQHandler setSupportWebView:YES];

    //设置facebook应用ID及URL    506027402887373
    [UMSocialFacebookHandler setFacebookAppID:@"506027402887373" shareFacebookWithURL:@"http://www.umeng.com/social"];
    //
    ////    下面打开Instagram的开关
    [UMSocialInstagramHandler openInstagramWithScale:NO paddingColor:[UIColor blackColor]];

    //默认使用iOS自带的Twitter分享framework,在iOS 6以上有效。若要使用我们提供的twitter分享需要使用此开关:
    [UMSocialTwitterHandler openTwitter];
    // 集成的TwitterSDK仅在iOS7.0以上有效,在iOS 6.x上自动调用系统内置Twitter授权
    if (UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        [UMSocialTwitterHandler setTwitterAppKey:@"fB5tvRpna1CKK97xZUslbxiet" withSecret:@"YcbSvseLIwZ4hZg9YmgJPP5uWzd4zr6BpBKGZhf07zzh3oj62K"];
    }

}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
                                                                  openURL:url
                                                        sourceApplication:sourceApplication
                                                               annotation:annotation
                    ];
    // 在此添加任意自定义逻辑。
    return handled;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
/*global xit,it,describe,before,after,beforeEach,afterEach,require*/
"use strict";
require("requirish")._(module);
var assert = require("better-assert");
var should = require("should");
var async = require("async");
var _ = require("underscore");

var opcua = require("index.js");

var OPCUAClient = opcua.OPCUAClient;
var ClientSession = opcua.ClientSession;

var build_server_with_temperature_device = require("test/helpers/build_server_with_temperature_device").build_server_with_temperature_device;
var perform_operation_on_client_session = require("test/helpers/perform_operation_on_client_session").perform_operation_on_client_session;

var _port = 2000;

var resourceLeakDetector = require("test/helpers/resource_leak_detector").resourceLeakDetector;

var securityMode = opcua.MessageSecurityMode.NONE;
var securityPolicy = opcua.SecurityPolicy.None;

// bug : server reported to many datavalue changed when client monitored a UAVariable consructed with variation 1");

describe("Testing bug #73 -  Server resets sequence number after secure channel renewal ", function () {

    var options = {
        securityMode: securityMode,
        securityPolicy: securityPolicy,
        serverCertificate: null,
        defaultSecureTokenLifetime: 100   // << Use a very small secure token lifetime to speed up test !
    };

    this.timeout(5000);

    var server, client, temperatureVariableId, endpointUrl;

    before(function (done) {
        resourceLeakDetector.start();
        // we use a different port for each tests to make sure that there is
        // no left over in the tcp pipe that could generate an error
        server = build_server_with_temperature_device({port: _port}, function (err) {

            endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
            temperatureVariableId = server.temperatureVariableId;
            done(err);
        });
    });

    beforeEach(function (done) {
        client = new OPCUAClient(options);
        done();
    });

    afterEach(function (done) {
        client.disconnect(done);
        client = null;
    });

    after(function (done) {
        server.shutdown(function (err) {
            resourceLeakDetector.stop();
            done(err);
        });
        server = null;
    });

    it("should not reset sequence number after secure channel renewal ", function (done) {

        var old_client_connect =  client.connect;

        var sequenceNumbers = [];
        var messages = [];

        function new_client_connect(endpoint_url, callback) {
            var self = this;
            old_client_connect.call(this,endpoint_url,function(err){

                self._secureChannel.messageBuilder.on("message",function(msg){

                    messages.push(msg.constructor.name);

                    if (self._secureChannel) {
                        sequenceNumbers.push(self._secureChannel.messageBuilder.sequenceHeader.sequenceNumber);
                        // console.log(" msg = ",msg.constructor.name,self._secureChannel.messageBuilder.sequenceHeader.sequenceNumber);
                    }
                });
                // call default implementation
                callback.apply(self,arguments);

            })
        }
        client.connect = new_client_connect;

        perform_operation_on_client_session(client, endpointUrl, function (session, inner_done) {

            session.should.be.instanceOf(ClientSession);

            setTimeout(function() {

                // verify that Token has been renewed ...
                // ( i.e we have received multiple OpenSecureChannel
                _.filter(messages,function(a){ return a ==="OpenSecureChannelResponse"}).length.should.be.greaterThan(2);

                // sequence number should be increasing monotonically
                console.log(sequenceNumbers);

                for (var i=1;i<sequenceNumbers.length;i++) {
                    sequenceNumbers[i].should.be.greaterThan(sequenceNumbers[i-1]);
                }
                inner_done();
            },1000);

        },done);

    });
});


text:
{{::appName}}

{{::jpAppName}}

    {{::link.name}}


text:
import cStringIO as StringIO

from twisted.internet import reactor
from twisted.web.client import getPage
from twisted.python.util import println
from lxml import etree

def parseHtml(html):
    parser = etree.HTMLParser(encoding='utf8')
    tree = etree.parse(StringIO.StringIO(html), parser)
    return tree

def extractTitle(tree):
    titleText = unicode(tree.xpath("//title/text()")[0])
    return titleText

d = getPage('http://www.google.com')
d.addCallback(parseHtml)
d.addCallback(extractTitle)
d.addBoth(println)

reactor.run()


text:
saferAI

building the future ALL want, for everybody

index, about

 saferAI.com has a five years plan:

 start up

 safer AI

 AI CEO runs the company

 build the AI President

 World Peace!

We'll let you know when the years start counting.

saferAI.com is here to take the AI safety concern from the people and give it to them, the big companies.


text:
using Chloe.Server.Dtos;
using System.Collections.Generic;

namespace Chloe.Server.Services.Contracts
{
    public interface IAuthorService
    {
        AuthorAddOrUpdateResponseDto AddOrUpdate(AuthorAddOrUpdateRequestDto request);
        ICollection<AuthorDto> Get();
        AuthorDto GetById(int id);
        dynamic Remove(int id);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>::: JobShoppa.com :::</title>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />

 25 people like this

Home

Post a job

Find a Job

Find a Professional

Help

 Home

»

Abuse Report

Login

|

Signup

            <input type="text" value="What Job Do You need?" onfocus="if(this.value=='What Job Do You need?')this.value='';" onblur="if(this.value=='')this.value='What Job Do You need?';" />

            <input type="text" value="Category" onfocus="if(this.value=='Category')this.value='';" onblur="if(this.value=='')this.value='Category';" />

            <input type="submit" value="Search"  onclick="window.location.href='find-a-job.html'" />

Abuse Report

Please take a moment and fill the form out below.

* Required field

First Name * :

                            <input name="" type="text" size="48" />

Last Name :

                            <input name="" type="text" size="48" />

Contact No * :

                            <input name="" type="text" size="50" />

Email Address * :

                            <input name="" type="text" size="50" />

Please provide your comments * :

                            <textarea name="" cols="" rows="6"></textarea>

Word Verification * :

Type the characters you see in the picture below.

                        <input name="" type="text" size="50" />

Letters are not case-sensitive

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

Clients »

Post a Job free

How it Works

FAQ

Service Professional »

Find a Job

How it Works

FAQ

About Us »

About Us

Career

Legal »

Privacy Policy

Terms & Conditions

Abuse Report

Support »

Customer Support

Help

Blog

Contact Us

© Copyright 2011 by JobShoppa.com. All Rights Reserved.

Follow us:

How do you like to choose to use Jobshoppa

Professional Registration

Client Registration


text:
"use strict";

var app = angular.module('eDAB-app', ['eDAB-utils']);

app.config(function ($routeProvider, $locationProvider) {
	$locationProvider.html5Mode(true);
	$locationProvider.hashPrefix("");

	$routeProvider
		.when('/agenda', {controller: AgendaCtrl, templateUrl: '/partials/agenda.html'})
		.when('/settings', {controller: SettingsCtrl, templateUrl: '/partials/settings.html'})
		.when('/users/:username', {controller: UserCtrl, templateUrl: '/partials/user.html'})
		.when('/courses', {controller: CourseListCtrl, templateUrl: '/partials/course_list.html'})
		.when('/courses/:courseId', {controller: CourseCtrl, templateUrl: '/partials/course_view.html'})
		.when('/courses/:courseId/edit', {controller: CourseEditCtrl, templateUrl: '/partials/course_edit.html'})
		.when('/courses/:courseId/assignments/:asgnId', {controller: AssignmentCtrl, templateUrl: '/partials/asgn.html'})
		.otherwise({redirectTo: '/agenda'});

	$locationProvider.html5Mode(true).hashPrefix("");
});

// This needs to be cleaned up. Big time.
app.service('appService', function ($http, $window, $q, $rootScope) {
	var self = this;

	// Default handling for authorized requests.
	self._reqHandler = {
		success: function (response) {
			self.auth.logged_in = true;
			return response;
		},
		error: function (response) {
			console.info("Request error", response.data.error);

			if (response.data.error) {

				// If the session needs to be initialized, we can retry it. But only retry once.
				if (response.data.error.name == "InvalidSession" && !response.config.retry) {
					console.log("Invalid session. Will retry request");
					response.config.retry = true;
					return $http(response.config)
						.then(self._reqHandler.success, self._reqHandler.error);
				}

				// If we're not logged in
				else if (response.data.error.name == "NotLoggedIn") {
					self.auth.user = null;
					self.auth.logged_in = false;
				}

				else if (response.data.error.name == "NeedsApproval") {
					alert("Lalala you need to be manually approved first");
				}

				else {
					throw response.data.error;
				}

			} else {
				throw {
					name: response.status,
					message: "Unexpected HTTP error"
				};
			}

			return $q.reject(response);
		}
	};

	self.auth = {

		logged_in: null, // null=loading, true, false

		user: null,

		updateUser: function (newUser) {
			newUser = angular.copy(newUser);

			return $http({
				method: "PUT",
				url: "/rest/users/me",
				data: newUser
			})
			.then(self._reqHandler.success, self._reqHandler.error)
			.then(function (response) {
				console.log("Saved user. Response: ", response);
				self.auth.user = newUser;
			});
		},

		login: function () {
			// $window.location.replace("/login");
			$window.open("/login?close", "login");

			$window.loginCallback = function () {
				$rootScope.$apply(function () { // get inside angular lifecycle or whatnot
					self.auth.check();
				});
			};
		},

		logout: function () {
			$http({
				method: "POST",
				url: "/logout"
			})
			.then(function (resp) {
				self.auth.check();
			});
		},

		check: function () {
			$http({
				method: "GET",
				url: "/rest/users/me"
			})
			.then(self._reqHandler.success, self._reqHandler.error)
			.then(function (response) {
				console.log("Loaded user. Response:", response);
				self.auth.user = response.data;
			});
		}
	};

});

app.run(function (appService, $rootScope) {
	appService.auth.check();

	$rootScope.$watch(function () { return appService.auth.logged_in; }, function (newVal) {
		$rootScope.$broadcast("loginStateChange", newVal);
	});
});

function AppCtrl($scope, $exceptionHandler) {
	$scope.getErrorMsg = function () {
		return $exceptionHandler.errorMsg;
	};
}

function InfoboxCtrl($scope, appService, $exceptionHandler) {
	$scope.login = function () {
		appService.auth.login();
	};

	$scope.infoboxState = function () {
		if (appService.auth.logged_in === false) {
			return "login";
		} else if (appService.auth.logged_in === null) {
			return "loading";
		}
		return false;
	};
}

function NavCtrl($scope, $location, appService) {
	$scope.getName = function () {
		return appService.auth.user && appService.auth.user.name;
	};

	$scope.onPage = function (path) {
		return $location.path() == path;
	};
}

function SettingsCtrl($scope, $location, appService, $window, Utils) {
	$scope.service = appService;
	$scope.user = angular.copy(appService.auth.user);

	$scope.$on("loginStateChange", function (newState) {
		$scope.user = angular.copy(appService.auth.user);
	});

	$scope.schools = [
		{"name": "Rachel Carson MS"},
		{"name": "Thomas Jefferson HSST"}
	];
	$scope.teams = [
		{"grade": 7, "letter": "A", "name": "Star Jumps"},
		{"grade": 7, "letter": "B", "name": "Trail Mix"},
		{"grade": 7, "letter": "C", "name": "Dictionaries"},
		{"grade": 7, "letter": "D", "name": "Dream On"},
		{"grade": 7, "letter": "E", "name": "Eggplants"},
		{"grade": 8, "letter": "V", "name": "Valedictors"},
		{"grade": 8, "letter": "W", "name": "Narwhals"},
		{"grade": 8, "letter": "X", "name": "Radiation"},
		{"grade": 8, "letter": "Y", "name": "Bumblebees"},
		{"grade": 8, "letter": "Z", "name": "Zebras"}
	];

	$scope.isUnchanged = function () {
		return angular.equals(appService.auth.user, $scope.user);
	};
	$scope.save = function () {
		// so people don't accidentally submit twice
		$scope.disableButtons = true;

		appService.auth.updateUser($scope.user)
		.then(function () {
			$scope.disableButtons = false;
		}, function () {
			$scope.disableButtons = false;
		});
	};
	$scope.reset = function () {
		$scope.user = angular.copy(appService.auth.user);
	};

	$scope.$watch(function () {
		return appService.auth.user;
	}, function () {
		$scope.reset();
	});

	// Initialize Google+ badge
	Utils.loadGPlusBadge();
}

function UserCtrl($scope, $routeParams, $http, $location, appService) {
	var username = $routeParams.username;
	$http({
		method: "GET",
		url: "/rest/users/" + username
	})
	.then(function (response) {
		console.log("Loaded user: ", response);
		$scope.user = response.data;
	}, function (response) {
		if (response.status == 404) {
			alert("User not found!");
			return;
		}

		// uh idk
		appService._reqHandler.error(response);
	});
}


text:
{% load i18n mezzanine_tags comment_tags %}

{% trans "Comments" %}

{% if settings.COMMENTS_DISQUS_SHORTNAME %}
{% include "generic/includes/disqus_comments.html" %}
{% else %}

{% comment_thread object_for_comments %}

{% endif %}
{#
#}
{#
#}
{#
{% trans "New Comment" %}
#}
{##}
{#{% if not request.POST.replied_to %}#}
{#		{% include "generic/includes/comment_form.html" with comment_form=posted_comment_form %}#}
{#    {% else %}#}
{#    {{% include "generic/includes/comment_form.html" with comment_form=unposted_comment_form %}#}
{#    {% endif %}#}
{##}
{##}
{#
#}
{#
#}


text:
package com.mcleodmoores.financial.function.trade.functions;

import java.util.List;

import com.mcleodmoores.financial.function.trade.DiscountBondDetailsFunction;
import com.mcleodmoores.financial.function.trade.FixedCouponBondDetailsFunction;
import com.mcleodmoores.financial.function.trade.FixedRateFunction;
import com.mcleodmoores.financial.function.trade.FxForwardDetailsFunction;
import com.mcleodmoores.financial.function.trade.FxNdfDetailsFunction;
import com.mcleodmoores.financial.function.trade.SwapDetailsFunction;
import com.opengamma.engine.function.config.AbstractFunctionConfigurationBean;
import com.opengamma.engine.function.config.FunctionConfiguration;
import com.opengamma.engine.function.config.FunctionConfigurationSource;

/**
 * Adds functions that provide information about trades.
 */
public class TradeFunctions extends AbstractFunctionConfigurationBean {

  /**
   * Creates an instance of this function configuration source.
   * @return  the populated source
   */
  public static FunctionConfigurationSource instance() {
    return new TradeFunctions().getObjectCreating();
  }

  @Override
  protected void addAllConfigurations(final List<FunctionConfiguration> functions) {
    functions.add(functionConfiguration(FixedRateFunction.class));
    functions.add(functionConfiguration(FxForwardDetailsFunction.class));
    functions.add(functionConfiguration(FxNdfDetailsFunction.class));
    functions.add(functionConfiguration(SwapDetailsFunction.class));
    functions.add(functionConfiguration(FixedCouponBondDetailsFunction.class));
    functions.add(functionConfiguration(DiscountBondDetailsFunction.class));
  }
}


text:
'use strict';
import { Container } from 'pixi.js';
import { Sprite } from 'pixi.js';
import { BLEND_MODES } from 'pixi.js';
import { Graphics } from 'pixi.js';
import AbstractPixiView from "../abstractPixi/AbstractPixiView.js";

export default class BrodyBattlefieldView extends AbstractPixiView  {

  constructor(model) {
    super(model);
    this._holeList = [];
    this._settings = null;
  }

  configure(settings) {
    this._settings = settings;
  }

  _create(container) {
    let background = Sprite.from('battlefield');
    container.addChild(background);

    let groundMask = new Graphics();
    groundMask.beginFill(0x0000ff, 1);
    groundMask.moveTo(25, 25);
    groundMask.lineTo(900-25, 25);
    groundMask.lineTo(900-25, 600-25);
    groundMask.lineTo(90, 600-25);
    groundMask.lineTo(90, 600-35);
    groundMask.lineTo(25, 600-35);
    groundMask.lineTo(25, 25);
    groundMask.endFill();

    this._craterContainer = new Container();
    this._craterContainer.mask = groundMask;
    container.addChild(this._craterContainer);
    container.addChild(groundMask);

    let wallMask = new Graphics();
    wallMask.beginFill(0x0000ff, 0.4);
    wallMask.moveTo(15, 15);
    wallMask.lineTo(900-15, 15);
    wallMask.lineTo(900-15, 600-15);
    wallMask.lineTo(80, 600-15);
    wallMask.lineTo(80, 600-25);
    wallMask.lineTo(15, 600-25);
    wallMask.lineTo(15, 15);
    wallMask.lineTo(25, 25);
    wallMask.lineTo(25, 600-25);
    wallMask.lineTo(80, 600-25);
    wallMask.lineTo(80, 600-25);
    wallMask.lineTo(900-25, 600-25);
    wallMask.lineTo(900-25, 25);
    wallMask.lineTo(25, 25);
    wallMask.endFill();
    this._holesContainer = new Container();
    this._holesContainer.mask = wallMask;
    container.addChild(this._holesContainer);
    container.addChild(wallMask);
  }

  addCrater(x, y) {
    let crater = Sprite.from('crater');
    crater.anchor.set(0.5);
    crater.x = x - this.model.offsetX;
    crater.y = y - this.model.offsetY;
    crater.blendMode = BLEND_MODES.MULTIPLY;
    crater.alpha = 0.8;
    this._craterContainer.addChild(crater);
  }

  update() {
    super.update();
    this._holesContainer.visible = (this._settings.skratchLimit > 0);
    this._craterContainer.visible = this._settings.showCraters;
  }

  addBulletHole(x, y, power) {
    let rotation = 0;
    if(Math.abs(y - this.model.maxY) < 10) {
      y = this.model.maxY + 3 +  Math.random()*3;
    } else if(Math.abs(y - this.model.minY) < 10) {
      y = this.model.minY - 3 -  Math.random()*3;
    } else if(Math.abs(x - this.model.maxX) < 10) {
      x = this.model.maxX + 3 +  Math.random()*3;
      rotation = Math.PI/2;
    } else if(Math.abs(x - this.model.minX) < 10) {
      x = this.model.minX - 3 -  Math.random()*3;
      rotation = Math.PI/2;
    } else {
      return;
    }

    let hole = Sprite.from('hole');
    hole.anchor.set(0.5);
    hole.x = x - this.model.offsetX;
    hole.y = y - this.model.offsetY;
    hole.rotation = rotation;
    hole.scale.x = hole.scale.y = 0.7 + 0.5*power;
    this._holesContainer.addChild(hole);
    this._holeList.push(hole);
    let limit = this._settings ? this._settings.skratchLimit : 20;
    while(this._holeList.length > limit) {
      hole = this._holeList.shift();
      hole.parent.removeChild(hole);
    }
  }

}


text:
module Str(str) where

import Language.Haskell.TH
import Language.Haskell.TH.Quote

str = QuasiQuoter { quoteExp = stringE }


text:
require 'observer'
require 'test/unit'
require_relative 'contracts'

class BoardModel
	include Test::Unit::Assertions
	include Observable
	def initialize()
		@board_array = Array.new(6){Array.new(7,0)}
		@rows = 6
		@columns = 7
	end

	def get_array
		changed
		notify_observers(Time.now)
		return @board_array
	end

	def to_s

		return_str = ""
		@board_array.reverse.each do |row|
			return_str=return_str+row.to_s+"\n"
		end
		return return_str
	end

	def add_piece(player_id, button_id)
		# observable
		column = button_id%7
		old_column_checksum = @board_array.transpose[column].inject(0){|sum,x| sum + x }
		begin
			# p "beforeeeeee"
			pre_add_piece(player_id, button_id, @board_array, @rows, @columns)
			# p "passed 1"
			# p "player id"
			# p player_id
			@board_array.each do |row|
				# p row[column]
				if row[column]==0
					row[column]=player_id
					changed
					notify_observers(Time.now)
					# p "test1"
					post_add_piece(@board_array, @rows, @columns){old_column_checksum < @board_array.transpose[column].inject(0){|sum,x| sum + x }}
					# p "passed add piece"
					return true
				end
			end
		rescue #Test::Unit::AssertionFailedError

			# p "test2"
			post_add_piece(@board_array, @rows, @columns){old_column_checksum == @board_array.transpose[column].inject(0){|sum,x| sum + x }}
			# p "its false"
			return false
		end

		#post
	end

	def clear
		pre_clear(@board_array, @rows, @columns)
		@board_array = Array.new(6){Array.new(7,0)}
		changed
		notify_observers(Time.now)
		post_clear(@board_array, @rows, @columns)
	end

	# def get_win_pattern(winpattern)
	# 	a= winpattern[0]
	# 	b=winpattern[1]

	# 	if !block_given?
	# 		myproc = Proc.new{}

	# 	end

	# end

	def check_for_winner(player)
		pre_check_for_winner(player, @board_array, @rows, @columns)
		win_pattern=player.get_win_pattern
		if horizontal_score_iterator(win_pattern) || vertical_score_iterator(win_pattern) || diagonal_right_check(win_pattern) || diagonal_left_check(win_pattern)
			post_score(@board_array, @rows, @columns)
			return true
		end
		post_score(@board_array, @rows, @columns)
		return false
	end

	def horizontal_score_iterator(win_pattern)
		pre_score(win_pattern)
		@board_array.each do |row|
			counter = 0
			row.each do |column|
				if column == win_pattern[counter]
					counter=counter+1
					if counter == win_pattern.length
						# p "horizontal winner"
						post_score(@board_array, @rows, @columns)
						return true
					end
				else
					counter=0
				end
			end
		end
		post_score(@board_array, @rows, @columns)
		return false
	end

	def vertical_score_iterator(win_pattern)
		pre_score(win_pattern)
		for column_index in 0..@columns-1
			counter = 0
			@board_array.each do |row|
				if row[column_index] == win_pattern[counter]
					counter=counter+1
					if counter == win_pattern.length
						# p "vertical winner"
						post_score(@board_array, @rows, @columns)
						return true
					end
				else
					counter=0
				end
			end
		end
		post_score(@board_array, @rows, @columns)
		return false
	end

	def diagonal_right_check(win_pattern)
		pre_score(win_pattern)
		for row_index in 0..@rows-1
			for column_index in 0..@columns-1
				if @board_array[row_index][column_index] == win_pattern[0]
					temp_row=row_index
					temp_column=column_index
					check_value=win_pattern[0]
					counter=0

					while (check_value==win_pattern[counter])
						counter = counter + 1
						if counter == win_pattern.length
							# p "diagonal winner"
							post_score(@board_array, @rows, @columns)
							return true
						end

						temp_row = temp_row + 1
						temp_column = temp_column + 1
						if temp_column >= @columns || temp_row >= @rows
							break
						end

						check_value=@board_array[temp_row][temp_column]

					end
				end
			end

		end
		post_score(@board_array, @rows, @columns)
		return false
	end

	def diagonal_left_check(win_pattern)
		pre_score(win_pattern)
		for row_index in 0..@rows-1
			for column_index in 0..@columns-1
				if @board_array[row_index][column_index] == win_pattern[0]
					temp_row=row_index
					temp_column=column_index
					check_value=win_pattern[0]
					counter=0

					while (check_value==win_pattern[counter])
						counter = counter + 1
						if counter == win_pattern.length
							# p "diagonal left winner"
							post_score(@board_array, @rows, @columns)
							return true
						end

						temp_row = temp_row + 1
						temp_column = temp_column - 1
						if temp_column < 0 || temp_row >= @rows
							break
						end

						check_value=@board_array[temp_row][temp_column]

					end
				end
			end

		end
		post_score(@board_array, @rows, @columns)
		return false
	end
end


text:
namespace base {
class ListValue;
}

// The data for the TemplateURL.  Separating this into its own class allows most
// users to do SSA-style usage of TemplateURL: construct a TemplateURLData with
// whatever fields are desired, then create an immutable TemplateURL from it.
struct TemplateURLData {
  TemplateURLData();
  TemplateURLData(const TemplateURLData& other);
  // Creates a TemplateURLData suitable for prepopulated engines.
  // Note that unlike in the default constructor, |safe_for_autoreplace| will
  // be set to true. date_created and last_modified will be set to null time
  // value, instead of current time.
  // StringPiece in arguments is used to pass const char* pointer members
  // of PrepopulatedEngine structure which can be nullptr.
  TemplateURLData(const base::string16& name,
                  const base::string16& keyword,
                  base::StringPiece search_url,
                  base::StringPiece suggest_url,
                  base::StringPiece instant_url,
                  base::StringPiece image_url,
                  base::StringPiece new_tab_url,
                  base::StringPiece contextual_search_url,
                  base::StringPiece search_url_post_params,
                  base::StringPiece suggest_url_post_params,
                  base::StringPiece instant_url_post_params,
                  base::StringPiece image_url_post_params,
                  base::StringPiece favicon_url,
                  base::StringPiece encoding,
                  const base::ListValue& alternate_urls_list,
                  base::StringPiece search_terms_replacement_key,
                  int prepopulate_id);

  ~TemplateURLData();

  // A short description of the template. This is the name we show to the user
  // in various places that use TemplateURLs. For example, the location bar
  // shows this when the user selects a substituting match.
  void SetShortName(const base::string16& short_name);
  const base::string16& short_name() const { return short_name_; }

  // The shortcut for this TemplateURL.  |keyword| must be non-empty.
  void SetKeyword(const base::string16& keyword);
  const base::string16& keyword() const { return keyword_; }

  // The raw URL for the TemplateURL, which may not be valid as-is (e.g. because
  // it requires substitutions first).  This must be non-empty.
  void SetURL(const std::string& url);
  const std::string& url() const { return url_; }

  // Optional additional raw URLs.
  std::string suggestions_url;
  std::string instant_url;
  std::string image_url;
  std::string new_tab_url;
  std::string contextual_search_url;

  // The following post_params are comma-separated lists used to specify the
  // post parameters for the corresponding URL.
  std::string search_url_post_params;
  std::string suggestions_url_post_params;
  std::string instant_url_post_params;
  std::string image_url_post_params;

  // Optional favicon for the TemplateURL.
  GURL favicon_url;

  // URL to the OSD file this came from. May be empty.
  GURL originating_url;

  // Whether it's safe for auto-modification code (the autogenerator and the
  // code that imports data from other browsers) to replace the TemplateURL.
  // This should be set to false for any TemplateURL the user edits, or any
  // TemplateURL that the user clearly manually edited in the past, like a
  // bookmark keyword from another browser.
  bool safe_for_autoreplace;

  // The list of supported encodings for the search terms. This may be empty,
  // which indicates the terms should be encoded with UTF-8.
  std::vector<std::string> input_encodings;

  // Unique identifier of this TemplateURL. The unique ID is set by the
  // TemplateURLService when the TemplateURL is added to it.
  TemplateURLID id;

  // Date this TemplateURL was created.
  //
  // NOTE: this may be 0, which indicates the TemplateURL was created before we
  // started tracking creation time.
  base::Time date_created;

  // The last time this TemplateURL was modified by a user, since creation.
  //
  // NOTE: Like date_created above, this may be 0.
  base::Time last_modified;

  // True if this TemplateURL was automatically created by the administrator via
  // group policy.
  bool created_by_policy;

  // Number of times this TemplateURL has been explicitly used to load a URL.
  // We don't increment this for uses as the "default search engine" since
  // that's not really "explicit" usage and incrementing would result in pinning
  // the user's default search engine(s) to the top of the list of searches on
  // the New Tab page, de-emphasizing the omnibox as "where you go to search".
  int usage_count;

  // If this TemplateURL comes from prepopulated data the prepopulate_id is > 0.
  int prepopulate_id;

  // The primary unique identifier for Sync. This set on all TemplateURLs
  // regardless of whether they have been associated with Sync.
  std::string sync_guid;

  // A list of URL patterns that can be used, in addition to |url_|, to extract
  // search terms from a URL.
  std::vector<std::string> alternate_urls;

  // A parameter that, if present in the query or ref parameters of a search_url
  // or instant_url, causes Chrome to replace the URL with the search term.
  std::string search_terms_replacement_key;

 private:
  // Private so we can enforce using the setters and thus enforce that these
  // fields are never empty.
  base::string16 short_name_;
  base::string16 keyword_;
  std::string url_;
};

#endif  // COMPONENTS_SEARCH_ENGINES_TEMPLATE_URL_DATA_H_


text:
var express = require('express');
var router = express.Router();

router.get('/',  (req, res) => {
  res.send('About page.');
});

module.exports = router;


text:
from cbint.utils.detonation import DetonationDaemon, ConfigurationError
from cbint.utils.detonation.binary_analysis import (BinaryAnalysisProvider,
                                                    AnalysisPermanentError,
                                                    AnalysisTemporaryError,
                                                    AnalysisResult)
import cbint.utils.feed
import logging
from analysis_apiclient import AnalysisClient, AnalysisAPIError, FileNotAvailableError
from time import sleep
import re

log = logging.getLogger(__name__)

class LastlineProvider(BinaryAnalysisProvider):
    def __init__(self, name, lastline_url, lastline_api_key, lastline_api_token, verify_ssl=False):
        super(LastlineProvider, self).__init__(name)
        self.lastline_analysis = AnalysisClient(lastline_url, lastline_api_key, lastline_api_token,
                                                verify_ssl=verify_ssl)
        self.feed_link_prefix = "%s/portal#/analyst/task/" % lastline_url
        if self.feed_link_prefix.lower().find("analysis.lastline.com") >= 0:
            self.feed_link_prefix = "https://user.lastline.com/portal#/analyst/task/"

    def get_uuid(self, response):
        try:
            task_uuid = response.get('data', {}).get('task_uuid', None)
        except AttributeError:
            raise AnalysisTemporaryError(message="Invalid response from LastLine: %s" % response, retry_in=120)
        else:
            if not task_uuid:
                raise AnalysisTemporaryError(message="No UUID for result: %s" % response, retry_in=120)

        return task_uuid

    def make_result(self, task_uuid):
        try:
            result = self.lastline_analysis.get_result(task_uuid)
            result = result.get('data', {})
        except Exception as e:
            raise AnalysisTemporaryError(message="API error: %s" % str(e), retry_in=120)
        else:
            if 'error' in result:
                raise AnalysisTemporaryError(message=result['error'], retry_in=120)
            score = int(result.get('score', 0))
            if score == 0:
                malware_result = "Benign"
            else:
                reasons = "; ".join(result.get('malicious_activity', []))
                malware_result = "Potential malware: %s" % reasons

            return AnalysisResult(message=malware_result, extended_message="",
                                  link=re.sub("(?<!:)/{2,}", "/", "%s/%s" % (self.feed_link_prefix, task_uuid)),
                                  score=score)

    def check_result_for(self, md5sum):
        try:
            response = self.lastline_analysis.submit_file_hash(md5=md5sum)
        except FileNotAvailableError as e:
            log.info("check_result_for: FileNotAvailable")
            # the file does not exist yet.
            return None
        except AnalysisAPIError as e:
            raise AnalysisTemporaryError(message="API error: %s" % str(e), retry_in=120)
        else:
            task_uuid = self.get_uuid(response)
            return self.make_result(task_uuid)

    def analyze_binary(self, md5sum, binary_file_stream):
        log.info("Submitting binary %s to LastLine" % md5sum)

        try:
            response = self.lastline_analysis.submit_file(binary_file_stream)
        except AnalysisAPIError as e:
            raise AnalysisTemporaryError(message="API error: %s" % str(e), retry_in=120)

        task_uuid = self.get_uuid(response)

        retries = 10
        while retries:
            sleep(10)
            result = self.lastline_analysis.get_progress(task_uuid)
            if result.get('data', {}).get('completed', 0) == 1:
                return self.make_result(task_uuid)
            retries -= 1

        raise AnalysisTemporaryError(message="Maximum retries (10) exceeded submitting to LastLine", retry_in=120)

class LastlineConnector(DetonationDaemon):
    @property
    def filter_spec(self):
        filters = []
        max_module_len = 10 * 1024 * 1024
        filters.append('(os_type:windows OR os_type:osx) orig_mod_len:[1 TO %d]' % max_module_len)
        additional_filter_requirements = self.get_config_string("binary_filter_query", None)
        if additional_filter_requirements:
            filters.append(additional_filter_requirements)

        return ' '.join(filters)

    @property
    def integration_name(self):
        return 'Cb LastLine Connector 1.2.12'

    @property
    def num_quick_scan_threads(self):
        return self.get_config_integer("lastline_quick_scan_threads", 1)

    @property
    def num_deep_scan_threads(self):
        return self.get_config_integer("lastline_deep_scan_threads", 3)

    def get_provider(self):
        lastline_provider = LastlineProvider(self.name, self.lastline_url, self.lastline_api_key,
                                             self.lastline_api_token, verify_ssl=self.lastline_verify_ssl)
        return lastline_provider

    def get_metadata(self):
        return cbint.utils.feed.generate_feed(self.name, summary="Lastline Detonation Analysis",
                                              tech_data="An on-premise LastLine device or LastLine cloud service account is required to use this feed. There are no requirements to share any data with Carbon Black to use this feed. However, binaries may be shared with Lastline.",
                                              provider_url="http://www.lastline.com/",
                                              icon_path='/usr/share/cb/integrations/lastline/lastline-logo.png',
                                              display_name="Lastline", category="Connectors")

    def validate_config(self):
        super(LastlineConnector, self).validate_config()

        self.check_required_options(["lastline_url", "lastline_api_key", "lastline_api_token"])
        self.lastline_url = self.get_config_string("lastline_url", None)
        self.lastline_api_key = self.get_config_string("lastline_api_key", None)
        self.lastline_api_token = self.get_config_string("lastline_api_token", None)
        self.lastline_verify_ssl = self.get_config_boolean("lastline_server_sslverify", False)

        return True

if __name__ == '__main__':
    import os

    my_path = os.path.dirname(os.path.abspath(__file__))
    temp_directory = "/tmp/lastline"

    config_path = os.path.join(my_path, "testing.conf")
    daemon = LastlineConnector('lastlinetest', configfile=config_path, work_directory=temp_directory,
                               logfile=os.path.join(temp_directory, 'test.log'), debug=True)
    daemon.start()


text:
%--- help for abstvar/residuals ---
%
%  Computes the residuals given the parameters
%
%


text:
require "delegate"

module Ddr::Index
  #
  # Wraps an index query response
  #
  class Response < SimpleDelegator

    def docs
      response["docs"]
    end

    def num_found
      response["numFound"].to_i
    end

    def facet_counts
      self["facet_counts"] || {}
    end

    def facet_fields
      facet_counts["facet_fields"] || {}
    end

    def response
      self["response"]
    end

  end
end


text:
package org.wso2.developerstudio.eclipse.gmf.esb;

import org.eclipse.emf.common.util.EList;

/**
 *
 * A representation of the model object 'URL Rewrite Mediator'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteMediator#getUrlRewriteRules Url Rewrite Rules}

 *
{@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteMediator#getInProperty In Property}

 *
{@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteMediator#getOutProperty Out Property}

 *
{@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteMediator#getInputConnector Input Connector}

 *
{@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteMediator#getOutputConnector Output Connector}

 *

 *
 * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getURLRewriteMediator()
 * @model
 * @generated
 */
public interface URLRewriteMediator extends Mediator {
    /**
     * Returns the value of the 'Url Rewrite Rules' containment reference list.
     * The list contents are of type {@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteRule}.
     *
     *

     * If the meaning of the 'Url Rewrite Rules' containment reference list isn't clear,
     * there really should be more of a description here...
     *

     *
     * @return the value of the 'Url Rewrite Rules' containment reference list.
     * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getURLRewriteMediator_UrlRewriteRules()
     * @model containment="true"
     * @generated
     */
    EList<URLRewriteRule> getUrlRewriteRules();

    /**
     * Returns the value of the 'In Property' attribute.
     *
     *

     * If the meaning of the 'In Property' attribute isn't clear,
     * there really should be more of a description here...
     *

     *
     * @return the value of the 'In Property' attribute.
     * @see #setInProperty(String)
     * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getURLRewriteMediator_InProperty()
     * @model
     * @generated
     */
    String getInProperty();

    /**
     * Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteMediator#getInProperty In Property}' attribute.
     *
     *
     * @param value the new value of the 'In Property' attribute.
     * @see #getInProperty()
     * @generated
     */
    void setInProperty(String value);

    /**
     * Returns the value of the 'Out Property' attribute.
     *
     *

     * If the meaning of the 'Out Property' attribute isn't clear,
     * there really should be more of a description here...
     *

     *
     * @return the value of the 'Out Property' attribute.
     * @see #setOutProperty(String)
     * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getURLRewriteMediator_OutProperty()
     * @model
     * @generated
     */
    String getOutProperty();

    /**
     * Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteMediator#getOutProperty Out Property}' attribute.
     *
     *
     * @param value the new value of the 'Out Property' attribute.
     * @see #getOutProperty()
     * @generated
     */
    void setOutProperty(String value);

    /**
     * Returns the value of the 'Input Connector' containment reference.
     *
     *

     * If the meaning of the 'Input Connector' containment reference isn't clear,
     * there really should be more of a description here...
     *

     *
     * @return the value of the 'Input Connector' containment reference.
     * @see #setInputConnector(URLRewriteMediatorInputConnector)
     * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getURLRewriteMediator_InputConnector()
     * @model containment="true"
     * @generated
     */
    URLRewriteMediatorInputConnector getInputConnector();

    /**
     * Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteMediator#getInputConnector Input Connector}' containment reference.
     *
     *
     * @param value the new value of the 'Input Connector' containment reference.
     * @see #getInputConnector()
     * @generated
     */
    void setInputConnector(URLRewriteMediatorInputConnector value);

    /**
     * Returns the value of the 'Output Connector' containment reference.
     *
     *

     * If the meaning of the 'Output Connector' containment reference isn't clear,
     * there really should be more of a description here...
     *

     *
     * @return the value of the 'Output Connector' containment reference.
     * @see #setOutputConnector(URLRewriteMediatorOutputConnector)
     * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getURLRewriteMediator_OutputConnector()
     * @model containment="true"
     * @generated
     */
    URLRewriteMediatorOutputConnector getOutputConnector();

    /**
     * Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.URLRewriteMediator#getOutputConnector Output Connector}' containment reference.
     *
     *
     * @param value the new value of the 'Output Connector' containment reference.
     * @see #getOutputConnector()
     * @generated
     */
    void setOutputConnector(URLRewriteMediatorOutputConnector value);

} // URLRewriteMediator


text:
<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<script src="script-tests/negative-scroll-positions.js"></script>
</body>
</html>


text:
<?php

namespace sndsgd;

/**
 * Function and method utility methods
 */
class Fn
{
   /**
    * Verify a callable provided as a string
    *
    * @param string $fn The callable to verify
    * @return string|null
    * @return string The method or function WAS found
    * @return null No method or function was found
    */
   public static function exists($fn)
   {
      if (strpos($fn, '::') !== false) {
         list($class, $method) = explode('::', $fn);
         return (method_exists($class, $method)) ? $fn : null;
      }
      else if (!function_exists($fn)) {
         return null;
      }
      return $fn;
   }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using System.Xml;

namespace RSSReader
{
    public class RSSManager : IRSSManager
    {
        private ICollection<Feed> feedList;

        /// <summary>
        /// Creates a new RSSManager and populates the feedList
        /// </summary>
        public RSSManager()
        {
            feedList = new List<Feed>();
            PopulateFeedList();
        }

        /// <summary>
        /// Clears the feedList and re-populates from the database
        /// </summary>
        private void PopulateFeedList()
        {
            feedList.Clear();
            using(var ctx = new RssReaderDbContext())
            {
                feedList = ctx.Feeds.Include("FeedItems").ToList();
            }
        }

        /// <summary>
        /// Retrieves the currently retrieved list of feeds
        /// </summary>
        public ICollection<Feed> GetFeeds()
        {
            return feedList != null ? feedList : new List<Feed>();
        }

        /// <summary>
        /// Takes a fee url, verifies it, and adds it to the database
        /// </summary>
        /// <param name="url">An RSS feed</param>
        /// <returns>True if the feed was successfully added, false otherwise</returns>
        public Boolean AddFeed(String url)
        {
            Boolean returnValue = false;

            //verify the url isn't already in our list
            if (feedList.Where(f => f.Url.ToLower().Contains(url.ToLower())).Any())
                return true;

            //get the feed info
            Feed internalFeed;
            SyndicationFeed feed;
            try
            {
                feed = SyndicationFeed.Load(XmlReader.Create(url));
                internalFeed = new Feed();
                internalFeed.Title = feed.Title.Text;
                internalFeed.Url = url;

                //add the Feed to the db
                if (internalFeed != null)
                {
                    using (var ctx = new RssReaderDbContext())
                    {
                        ctx.Feeds.Add(internalFeed);
                        ctx.SaveChanges();
                        returnValue = true;
                    }
                }
            }
            catch (Exception)
            {
                returnValue = false;
            }

            PopulateFeedList();

            return returnValue;
        }

        /// <summary>
        /// Deletes the specified feed from the database and re-populates the local feedlist
        /// </summary>
        /// <param name="feedToRemove">A Feed object</param>
        /// <returns>True if the feed was removed.</returns>
        public Boolean RemoveFeed(Feed feedToRemove)
        {
            Boolean returnValue = false;

            using (var ctx = new RssReaderDbContext())
            {
                ctx.Feeds.Remove(feedToRemove);
                returnValue = true;
            }

            PopulateFeedList();
            return returnValue;
        }
    }
}


text:
<?php
	require_once(dirname(__FILE__) . '/../Bank.php');
	require_once(dirname(__FILE__) . '/../Account.php');
	require_once(dirname(__FILE__) . '/../Transaction.php');

	require_once(dirname(__FILE__) . '/../3rdparty/simpletest/browser.php');
	require_once(dirname(__FILE__) . '/../3rdparty/phpquery/phpQuery/phpQuery.php');

	/**
	 * Code to pretend to be the HSBC Mobile app, this will allow us to scrape HSBC
	 * for recent transactions without needing the securekey.
	 */
	class HSBCMobile extends WebBank {
		private $account = '';
		private $password = '';
		private $memorableinfo = '';

		private $deviceId = '';
		private $securityDomain = 'www.mobile.security.hsbc.co.uk';
		private $saasDomain = 'www.hsbc.co.uk';

		private $accounts = null;
		private $accountLinks = array();

		/**
		 * Create a HSBCMobile.
		 *
		 * @param $account Account number (IB...)
		 * @param $password Secret Word
		 * @param $memorableinfo Secure Key Code
		 */
		public function __construct($account, $password, $memorableinfo) {
			parent::__construct();
			$this->account = $account;
			$this->password = $password;
			// The '.' is to push everything back one for login.
			$this->memorableinfo = '.'.$memorableinfo;

			$this->deviceId = $this->getDeviceData('eth0');
		}

		private function getDeviceData($iface) {
			$data = array();

			$mac = trim(file_get_contents('/sys/class/net/'.$iface.'/address'));
			$ip = trim(exec('ip addr show dev '.$iface.' | grep "inet " | cut -d " " -f 6  | cut -f 1 -d "/"'));

			return md5($mac . ' ' . $ip);
		}

		protected function newBrowser($loadCookies = true) {
			parent::newBrowser($loadCookies);

			$this->browser->setUserAgent('com.htsu.hsbcpersonalbanking/1.5.18.0 (Linux; U; Android 6.0; en; hammerhead) Apache-HttpClient/UNAVAILABLE (java 1.4)');
			$this->browser->addHeader('native-app: htsu-rbwm-v1.5.18.0');
			$this->browser->addHeader('device-type: Android 6.0');
			$this->browser->addHeader('device-status: {"rooted":"false"}');
			$this->browser->addHeader('device-id: Android_Nexus 5_' . $this->deviceId);
			$this->browser->addHeader('device-model: LGE Nexus 5');

			// $this->browser->addHeader('imsi_serial_id:	111111111111111');
			// $this->browser->addHeader('mcc:	12345');
			$this->browser->addHeader('gps_long_long:	0.0');
			$this->browser->addHeader('wifi_bssid_connected:	ff:ee:dd:cc:bb:aa');
			$this->browser->addHeader('data_enabled:	0');
			$this->browser->addHeader('hooking_frameworks:	0');
			$this->browser->addHeader('gps_location_enabled:	1');
			$this->browser->addHeader('untrusted_screeen_readers:	0');
			$this->browser->addHeader('device_root:	0');
			$this->browser->addHeader('application_language:	en');
			$this->browser->addHeader('running_on_emulator:	0');
			$this->browser->addHeader('time_zone:	GMT+00:00');
			$this->browser->addHeader('wifi_status:	1');
			$this->browser->addHeader('data_network_name:	');
			$this->browser->addHeader('untrusted_keyboard:	0');
			$this->browser->addHeader('native_code_hooks:	0');
			$this->browser->addHeader('application_repackaged:	0');
			$this->browser->addHeader('gps_long_lat:	0.0');
			$this->browser->addHeader('os_version:	Android 6.0');
			$this->browser->addHeader('debugger_attactched:	0');
			$this->browser->addHeader('ADRUM_1:	isMobile:true');
			$this->browser->addHeader('ADRUM:	isAjax:true');
		}

		/**
		 * String representation of this bank.
		 */
		public function __toString() {
			return 'HSBCMobile/' . $this->account;
		}

		/**
		 * Handle any form-based redirects.
		 *
		 * @param $page (By Ref) Page that we want to check for redirects.
		 */
		public function followFormRedirect(&$page) {
			while (true) {
				$oldURL = $this->browser->getUrl();

				$tempForm = preg_match('#document\.tempForm\.submit#Ums', $page) || preg_match("#document\.getElementById\('tempForm'\)\.submit\(\)#Ums", $page);
				$autoSubmitForm = preg_match('#var autoSubmitForm = document.getElementById\("([^"]+)"\);#Ums', $page, $m);
				$windowLocationHref = preg_match('#window.location.href = "([^"]+)";.*<body>Please wait...</body>#Ums', $page, $m2);

				if ($tempForm) {
					$method = 'tempForm';
					$page = $this->browser->submitFormByName('tempForm');
				} else if ($autoSubmitForm) {
					$method = 'autoSubmitForm';
					$page = $this->browser->submitFormByName($m[1]);
				} else if ($windowLocationHref) {
					$method = 'windowLocationHref';
					$urlInfo = parse_url($this->browser->getUrl());

					if ($m2[1][0] == '/') {
						$newURL = $urlInfo['scheme'] . '://' . $urlInfo['host'] . $m2[1];
						if (isset($urlInfo['query']) && !empty($urlInfo['query'])) {
							$newURL .= '&';
							$newURL .= $urlInfo['query'];
						}
					} else {
						$newURL = $m2[1];
					}

					$page = $this->browser->get($newURL);
					if (empty($page)) {
						// Sometimes the page comes back empty... try again.
						// echo 'REPEATED: ';
						$page = $this->browser->get($newURL);
					}

				} else {
					break;
				}

				// echo $oldURL, ' -[', $method, ']-> ', $this->browser->getUrl(), "\n";
			}
		}

		public function handleRedirects(&$page) {
			$this->followFormRedirect($page);
		}

		private function hsbcPost($url, $data, $trylogin = true) {
			if ($this->browser == null) { $this->newBrowser(false); }

			$data['locale'] = 'en';
			$data['devtype'] = 'M';
			$data['platform'] = 'A';
			$data['ver'] = '1.1';
			$data['json'] = '';

			$page = $this->browser->post($url, $data);
			$this->followFormRedirect($page);
			$decoded = @json_decode($page);

			if ($trylogin && ($decoded === null || $decoded->header->statusCode != '0000')) {
				$this->login();

				$page = $this->browser->post($url, $data);
				$decoded = @json_decode($page);
			}

			return $decoded;
		}

		/**
		 * Force a fresh login.
		 *
		 * @return true if login was successful, else false.
		 */
		public function login($fresh = false) {
			// Reset saasDomain and Security Domain
			$this->securityDomain = 'www.mobile.security.hsbc.co.uk';
			$this->saasDomain = 'www.hsbc.co.uk';

			$this->newBrowser(false);
			$config = $this->browser->get('https://' . $this->saasDomain . '/content_static/mobile/1/5/18/0/config-android.json?' . time());
			$this->followFormRedirect($config);

			$mspconfig = $this->browser->get('https://' . $this->saasDomain . '/content_static/mobile/1/5/18/0/0/MSP_config.txt?' . time());
			$this->followFormRedirect($mspconfig);

			$tokens = $this->hsbcPost('https://' . $this->saasDomain . '/1/2/?idv_cmd=idv.GetCommToken&nextPage=/group/gpib/cmn/layouts/default.html&CHANNEL=MOBILE&function=Saas_Authentication', array('country' => 'UK', 'region' => 'HBEU', 'targetCam' => '30'), false);

			// You would expect this to be a thing, but it seems to be the wrong
			// domain....
			// $ipURL = $tokens->body->IP_URL;

			// Set it by hand for now then.
			$ipURL = 'https://' . $this->securityDomain . '/gsa/';

			$tokenData = array('__initialAccess' => 'true',
				               '__initialLogon' => 'true',
				               'SAAS_TOKEN_ID' => $tokens->body->SAAS_TOKEN_ID,
				               'SAAS_TOKEN_ASSERTION_ID' => $tokens->body->SAAS_TOKEN_ASSERTION_ID,
				               );
			$cookieGetter = $this->hsbcPost($ipURL . '?idv_cmd=idv.SaaSSecurityCommand&CHANNEL=MOBILE', $tokenData, false);

			$loginData = array('initialAccess' => 'true',
				               'nextPage' => 'MOBILE_CAM10_AUTHENTICATION',
				               'cookieuserid' => 'false',
				               '__locale' => 'en',
				               'LANGTAG' => 'en',
				               'COUNTRYTAG' => 'US',
				               'userid' => $this->account,
				               );
			$initialLogin = $this->hsbcPost($ipURL . '?idv_cmd=idv.Authentication&nextPage=MOBILE_CAM10_AUTHENTICATION&CHANNEL=MOBILE', $loginData, false);

			if ($initialLogin == null) { return FALSE; }

			$wanted = explode(',', $initialLogin->body->rccDigits);
			$digits = array();
			foreach ($wanted as $d) {
				if ($d == '8') { $d = strlen($this->memorableinfo) - 1; }
				if ($d == '7') { $d = strlen($this->memorableinfo) - 2; }

				$digits[] = $this->memorableinfo[$d];
			}

			$interimCookieGetter = $this->hsbcPost('https://' . $this->securityDomain . '/?idv_cmd=idv.AuthenticateAtMSFCommand&nextPage=MOBILE_CAM3040_FIRST&CHANNEL=MOBILE', array(), false);

			$data = array('__logonFlag' => 'true',
			              '__checkSOTPStatus' => 'true',
			              'memorableAnswer' => $this->password,
			              'password' => implode('', $digits),
			              '__locale' => 'en',
			              'OAUTH_APP' => 'null',
			              'OAUTH_DEVICE_ID' => 'null',
			              );

			$decoded = $this->hsbcPost($ipURL . '?idv_cmd=idv.Authentication&nextPage=MOBILE_CAM30_AUTHENTICATION&CHANNEL=MOBILE&__flag_logon_timeout=Y&devicestatus=true', $data, false);

			if ($decoded->body->lastLogonDate !== NULL) {
				$interimTokens = $this->hsbcPost($ipURL . 'SaaSMobileLogoutCAM0Resource/?CHANNEL=MOBILE', array(), false);
				$newTokenData = array('SAAS_TOKEN_ID' => $interimTokens->body->SAAS_TOKEN_ID,
				                      'SAAS_TOKEN_ASSERTION_ID' => $interimTokens->body->SAAS_TOKEN_ASSERTION_ID,
				                      );
				// https://www.hsbc.co.uk/1/2/?idv_cmd=idv.SaaSSecurityCommand&CHANNEL=MOBILE&function=postCommToken
				//
				// This looks to be $tokens->body->postCommTokenAfterIPTerm, so
				// lets use that!
				$newParams = $this->hsbcPost($tokens->body->postCommTokenAfterIPTerm, $newTokenData, false);

				$cmdIn = $this->hsbcPost('https://' . $this->saasDomain . '/1/3/mobile-1-5/entitlement-enquiry?ver=1.1&json=true', array('cmd_in' => 'cmd_in'), false);
				$menuRefresh = $this->hsbcPost('https://' . $this->saasDomain . '/1/3/mobile-1-5/scm?ver=1.1&json=true', array('__cmd-All_MenuRefresh' => '__cmd-All_MenuRefresh'), false);
				return true;
			}

			return false;
		}

		public function isLoggedIn($page) {
			// Always return true as there is no GET pages to test against.
			return true;
		}

		private function getType($typecode) {
			$typecodes[')))'] = 'Contactless debit card payment';
			$typecodes['ATM'] = 'Cash machine';
			$typecodes['BP'] = 'Bill payment';
			$typecodes['CHQ'] = 'Cheque';
			$typecodes['CR'] = 'Credit';
			$typecodes['DD'] = 'Direct Debit or other BACS debit';
			$typecodes['DIV'] = 'Dividend';
			$typecodes['DR'] = 'Debit';
			$typecodes['SO'] = 'Standing order';
			$typecodes['TFR'] = 'Internal Transfer';
			$typecodes['VIS'] = 'Visa Card Payment';
			$typecodes['SOL'] = 'Solo Card Payment';
			$typecodes['MAE'] = 'Maestro Card Payment';

			return isset($typecodes[$typecode]) ? $typecodes[$typecode] : $typecode;
		}

		/**
		 * Take transaction data, and clean it up a bit.
		 *
		 * @param $transaction Input transaction
		 * @return cleaned up transaction
		 */
		private function cleanTransaction($transaction) {
			// Get a better date
			$bits = explode('/', $transaction['date']);
			$transaction['date'] = $bits[1].'/'.$bits[0].'/'.$bits[2];
			$transaction['date'] = strtotime($transaction['date'] . ' Europe/London');

			// Rather than separate in/out, lets just have a +/- amount
			if (!empty($transaction['out'])) {
				$transaction['amount'] = $transaction['out'];
			} else if (!empty($transaction['in'])) {
				$transaction['amount'] = $transaction['in'];
			}

			// Unset any unneeded values
			unset($transaction['out']);
			unset($transaction['in']);

			return $transaction;
		}

		/**
		 * Take a Balance as exported by HSBCMobile, and return it as a standard balance.
		 *
		 * @param $balance Balance input (eg: "£1.00" or "-£1.00")
		 * @return Correct balance (eg: "1.00" or "-1.00")
		 */
		private function parseBalance($balance) {
			if (empty($balance)) { return ''; }
			$negative = strpos($balance, '-') !== FALSE;
			$balance = str_replace(',', '', $balance);
			preg_match('@([0-9]+.[0-9]+)$@', $balance, $matches);
			return $negative ? 0 - $matches[1] : $matches[1];
		}

		/**
		 * Get the sub-accounts of this login.
		 * This will return cached account objects.
		 *
		 * @param $useCached (Default: true) Return cached values if possible?
		 * @param $transactions (Default: false) Also update transactions?
		 *                      (This will force a reload of the accounts only if
		 *                       none of them have any associated transactions)
		 * @param $historical (Default: false) Also try to get historical
		 *                    transactions?
		 * @param $historicalVerbose (Default: false) Should verbose data be
		 *                           collected for historical, or is a single-line
		 *                           description ok?
		 * @return accounts associated with this login.
		 */
		public function getAccounts($useCached = true, $transactions = false, $historical = false, $historicalVerbose = false, $historicalLimit = 0) {
			// Check if we only want cached data.
			if ($useCached) {
				// Check if we have some accounts.
				if ($this->accounts != null && count($this->accounts) > 0) {
					// If we want transactions, check that at least one has some.
					if ($transactions) {
						foreach ($this->accounts as $a) {
							if (count($a->getTransactions() > 0)) {
								// Found some transactions, return the cache!
								return $this->accounts;
							}
						}
					} else {
						return $this->accounts;
					}
				}
			}

			$this->accounts = array();
			$data = array('requestName' => 'ac_summary',
			              '__cmd-All_MenuRefresh' => '__cmd-All_MenuRefresh',
			              );
			$decoded = $this->hsbcPost('https://' . $this->saasDomain . '/1/3/mobile-1-5/accounts?CSA_DynamicBrandKey=MOBILE15', $data);
			if ($decoded == null) { return false; }

			$accounts = array();
			foreach ($decoded->body->entities[0]->accountGroups[0]->accounts as $acc) {
				$account = new Account();
				$account->setSource($this->__toString());
				$account->setType($acc->desc);
				$account->setOwner($this->account);

				$number = explode(' ', $acc->accountNum);

				if (!isset($number[1]) || isset($number[2])) {
					$account->setSortCode('00-00-02');
					$account->setAccountNumber($acc->accountNum);
				} else {
					$account->setSortCode($number[0]);
					$account->setAccountNumber($number[1]);
				}

				$account->setBalance($this->parseBalance($acc->balance));

				$accountKey = preg_replace('#[^0-9]#', '', $account->getSortCode().$account->getAccountNumber());
				$this->accountLinks[$accountKey] = array('id' => $acc->id, 'type' => $acc->type);

				if ($transactions) {
					$this->updateTransactions($account, $historical, $historicalVerbose, $historicalLimit = 0);
				}

				$accounts[] = $account;
			}

			return $accounts;
		}

		/**
		 * Update the transactions on the given account object.
		 *
		 * @param $account Account to update.
		 * @param $historical (Default: false) Also try to get historical
		 *                    transactions?
		 * @param $historicalVerbose (Default: false) Should verbose data be
		 *                           collected for historical, or is a single-line
		 *                           description ok?
		 */
		public function updateTransactions($account, $historical = false, $historicalVerbose = true, $historicalLimit = 0) {
			$account->clearTransactions();
			$accountKey = preg_replace('#[^0-9]#', '', $account->getSortCode().$account->getAccountNumber());

			$accData = $this->accountLinks[$accountKey];
			$isCC = ($accData['type'] == 'PCC');

			$data = array('requestName' => $isCC ? 'ac_cc_history' : 'ac_history',
			              'account_index' => $accData['id'],
			              'account_type' => $accData['type'],
			              'cmd-All_in' => 'cmd-All_in',
			              'statement' => '0',
			              );

			$decoded = $this->hsbcPost('https://' . $this->saasDomain . '/1/3/mobile-1-5/accounts?CSA_DynamicBrandKey=MOBILE15', $data);

			if ($decoded == null) { return false; }

			$transactions = array();
			$items = $isCC ? $decoded->body->histories[0]->ccTxns : $decoded->body->histories;

			$lastBalance = $isCC ? $this->parseBalance($decoded->body->balance) : 0;

			// TODO: Historical?

			foreach ($items as $trans) {
				echo 'Got Item', "\n";

				// Pull out the data
				$transaction = array();
				$transaction['date'] = ($isCC) ? $trans->txnDate : $trans->date;
				$transaction['typecode'] = ($isCC) ? ($trans->ccTxnAmtDrCr ? 'DR' : 'CR') : $trans->type;
				$transaction['type'] = $this->getType($transaction['typecode']);
				$transaction['description'] = preg_replace('#\s+#', ' ', implode(' // ', (($isCC) ? str_split($trans->ccTxnMerchant, 35) : $trans->details)));

				// Fix some known brokenness...
				if ($transaction['description'] == 'ADDED NET INT') { $transaction['description'] = 'ADDED NET INTEREST'; }

				if ($isCC) {
					$bal = $this->parseBalance($trans->ccTxnAmt);
					$transaction['out'] = $trans->ccTxnAmtDrCr ? $bal : '';
					$transaction['in'] = $trans->ccTxnAmtDrCr ? '' : $bal;
					$transaction['balance'] = $lastBalance;
					$lastBalance -= $bal;

					// Hack, the above doesn't really handle being "0" very well...
					if ($lastBalance < 0.01 && $lastBalance > -0.01) { $lastBalance = 0; }
				} else {
					$transaction['out'] = $this->parseBalance($trans->debitAmt);
					$transaction['in'] = $this->parseBalance($trans->creditAmt);
					$transaction['balance'] = $this->parseBalance($trans->balance);
				}
				$transaction = $this->cleanTransaction($transaction);

				$transactions[] = $transaction;
			}

			// Now go through the transactions bottom-top so that we have them in the
			// order that they occured.
			$transactions = array_reverse($transactions);

			// To make ordering the transactions easier, rather than having
			// all the days transactions having the same time, we add a second
			// each time. (so the first transaction of the day happened at
			// 00:00:00 the second at 00:00:01 and so on.
			$dayCount = 0;
			$lastDate = 0;

			// Ignore transactions on the most-recent current date, as there may be more to come.
			if (count($transactions) > 0) {
				$firstDate = $transactions[count($transactions) -1 ]['date'];
				foreach ($transactions as $transaction) {
					// Skip the first day, cos we can't be sure we have all the
					// transactions for it.
					// if ($transaction['date'] == $firstDate) { continue; }

					if ($lastDate == $transaction['date']) {
						$dayCount++;
						$transaction['date'] += $dayCount;
					} else {
						$lastDate = $transaction['date'];
						$dayCount = 0;
					}
					$account->addTransaction(new Transaction($this->__toString(), $account->getAccountKey(), $transaction['date'], $transaction['type'], $transaction['typecode'], $transaction['description'], $transaction['amount'], $transaction['balance']));
				}
			}
		}
	}
?>


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Usage;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.UnitTests
{
    public partial class CA2229FixerTests : CodeFixTestBase
    {
        protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
        {
            return new SerializationRulesDiagnosticAnalyzer();
        }

        [WorkItem(858655)]
        protected override CodeFixProvider GetBasicCodeFixProvider()
        {
            return new CA2229CodeFixProvider();
        }

        protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
        {
            return new SerializationRulesDiagnosticAnalyzer();
        }

        protected override CodeFixProvider GetCSharpCodeFixProvider()
        {
            return new CA2229CodeFixProvider();
        }

        #region CA2229

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public void CA2229NoConstructorFix()
        {
            VerifyCSharpFix(@"
using System;
using System.Runtime.Serialization;
[Serializable]
public class CA2229NoConstructor : ISerializable
{
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        throw new NotImplementedException();
    }
}", @"
using System;
using System.Runtime.Serialization;
[Serializable]
public class CA2229NoConstructor : ISerializable
{
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        throw new NotImplementedException();
    }

    protected CA2229NoConstructor(SerializationInfo serializationInfo, StreamingContext streamingContext)
    {
        throw new NotImplementedException();
    }
}");

            VerifyBasicFix(@"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public Class CA2229NoConstructor
    Implements ISerializable

    Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
        throw new NotImplementedException()
    End Sub
End Class", @"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public Class CA2229NoConstructor
    Implements ISerializable

    Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
        throw new NotImplementedException()
    End Sub

    Protected Sub New(serializationInfo As SerializationInfo, streamingContext As StreamingContext)
        Throw New NotImplementedException()
    End Sub
End Class");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public void CA2229HasConstructorWrongAccessibilityFix()
        {
            VerifyCSharpFix(@"
using System;
using System.Runtime.Serialization;
[Serializable]
public class CA2229HasConstructorWrongAccessibility : ISerializable
{
    public CA2229HasConstructorWrongAccessibility(SerializationInfo info, StreamingContext context) { }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        throw new NotImplementedException();
    }
}", @"
using System;
using System.Runtime.Serialization;
[Serializable]
public class CA2229HasConstructorWrongAccessibility : ISerializable
{
    protected CA2229HasConstructorWrongAccessibility(SerializationInfo info, StreamingContext context) { }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        throw new NotImplementedException();
    }
}");

            VerifyBasicFix(@"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public Class CA2229HasConstructorWrongAccessibility
    Implements ISerializable

    Public Sub New(info As SerializationInfo, context As StreamingContext)
    End Sub

    Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
        throw new NotImplementedException()
    End Sub
End Class", @"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public Class CA2229HasConstructorWrongAccessibility
    Implements ISerializable

    Protected Sub New(info As SerializationInfo, context As StreamingContext)
    End Sub

    Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
        throw new NotImplementedException()
    End Sub
End Class");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public void CA2229HasConstructorWrongAccessibility2Fix()
        {
            VerifyCSharpFix(@"
using System;
using System.Runtime.Serialization;
[Serializable]
public sealed class CA2229HasConstructorWrongAccessibility2 : ISerializable
{
    protected internal CA2229HasConstructorWrongAccessibility2(SerializationInfo info, StreamingContext context) { }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        throw new NotImplementedException();
    }
}", @"
using System;
using System.Runtime.Serialization;
[Serializable]
public sealed class CA2229HasConstructorWrongAccessibility2 : ISerializable
{
    private CA2229HasConstructorWrongAccessibility2(SerializationInfo info, StreamingContext context) { }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        throw new NotImplementedException();
    }
}");

            VerifyBasicFix(@"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public NotInheritable Class CA2229HasConstructorWrongAccessibility2
    Implements ISerializable

    Protected Friend Sub New(info As SerializationInfo, context As StreamingContext)
    End Sub

    Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
        throw new NotImplementedException()
    End Sub
End Class", @"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public NotInheritable Class CA2229HasConstructorWrongAccessibility2
    Implements ISerializable

    Private Sub New(info As SerializationInfo, context As StreamingContext)
    End Sub

    Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
        throw new NotImplementedException()
    End Sub
End Class");
        }

        #endregion
    }
}