text:
package cli

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/bitrise-io/bitrise/log"
	"github.com/bitrise-io/bitrise/models"
	"github.com/bitrise-io/bitrise/output"
	"github.com/bitrise-io/go-utils/colorstring"
	"github.com/bitrise-io/go-utils/pointers"
	"github.com/urfave/cli"
)

// --------------------
// Utility
// --------------------

func registerFatal(errorMsg string, warnings []string, format string) {
	message := ValidationItemModel{
		IsValid:  (len(errorMsg) > 0),
		Error:    errorMsg,
		Warnings: warnings,
	}

	if format == output.FormatRaw {
		for _, warning := range message.Warnings {
			log.Warnf("warning: %s", warning)
		}
		failf(message.Error)
	} else {
		bytes, err := json.Marshal(message)
		if err != nil {
			failf("Failed to parse error model, error: %s", err)
		}

		log.Print(string(bytes))
		os.Exit(1)
	}
}

func migratePatternToParams(params RunAndTriggerParamsModel, isPullRequestMode bool) RunAndTriggerParamsModel {
	if isPullRequestMode {
		params.PushBranch = ""
		params.PRSourceBranch = params.TriggerPattern
		params.PRTargetBranch = ""
		params.Tag = ""
	} else {
		params.PushBranch = params.TriggerPattern
		params.PRSourceBranch = ""
		params.PRTargetBranch = ""
		params.Tag = ""
	}

	params.TriggerPattern = ""

	return params
}

func getPipelineAndWorkflowIDByParams(triggerMap models.TriggerMapModel, params RunAndTriggerParamsModel) (string, string, error) {
	for _, item := range triggerMap {
		match, err := item.MatchWithParams(params.PushBranch, params.PRSourceBranch, params.PRTargetBranch, params.Tag)
		if err != nil {
			return "", "", err
		}
		if match {
			return item.PipelineID, item.WorkflowID, nil
		}
	}

	return "", "", fmt.Errorf("no matching pipeline & workflow found with trigger params: push-branch: %s, pr-source-branch: %s, pr-target-branch: %s, tag: %s", params.PushBranch, params.PRSourceBranch, params.PRTargetBranch, params.Tag)
}

// migrates deprecated params.TriggerPattern to params.PushBranch or params.PRSourceBranch based on isPullRequestMode
// and returns the triggered workflow id
func getPipelineAndWorkflowIDByParamsInCompatibleMode(triggerMap models.TriggerMapModel, params RunAndTriggerParamsModel, isPullRequestMode bool) (string, string, error) {
	if params.TriggerPattern != "" {
		params = migratePatternToParams(params, isPullRequestMode)
	}

	return getPipelineAndWorkflowIDByParams(triggerMap, params)
}

// --------------------
// CLI command
// --------------------

func triggerCheck(c *cli.Context) error {
	warnings := []string{}

	//
	// Expand cli.Context
	var prGlobalFlagPtr *bool
	if c.GlobalIsSet(PRKey) {
		prGlobalFlagPtr = pointers.NewBoolPtr(c.GlobalBool(PRKey))
	}

	triggerPattern := c.String(PatternKey)
	if triggerPattern == "" && len(c.Args()) > 0 {
		triggerPattern = c.Args()[0]
	}

	pushBranch := c.String(PushBranchKey)
	prSourceBranch := c.String(PRSourceBranchKey)
	prTargetBranch := c.String(PRTargetBranchKey)
	tag := c.String(TagKey)

	bitriseConfigBase64Data := c.String(ConfigBase64Key)
	bitriseConfigPath := c.String(ConfigKey)
	deprecatedBitriseConfigPath := c.String(PathKey)
	if bitriseConfigPath == "" && deprecatedBitriseConfigPath != "" {
		warnings = append(warnings, "'path' key is deprecated, use 'config' instead!")
		bitriseConfigPath = deprecatedBitriseConfigPath
	}

	inventoryBase64Data := c.String(InventoryBase64Key)
	inventoryPath := c.String(InventoryKey)

	jsonParams := c.String(JSONParamsKey)
	jsonParamsBase64 := c.String(JSONParamsBase64Key)

	format := c.String(OuputFormatKey)

	triggerParams, err := parseTriggerCheckParams(
		triggerPattern,
		pushBranch, prSourceBranch, prTargetBranch, tag,
		format,
		bitriseConfigPath, bitriseConfigBase64Data,
		inventoryPath, inventoryBase64Data,
		jsonParams, jsonParamsBase64)
	if err != nil {
		registerFatal(fmt.Sprintf("Failed to parse trigger check params, err: %s", err), warnings, triggerParams.Format)
	}
	//

	// Inventory validation
	inventoryEnvironments, err := CreateInventoryFromCLIParams(triggerParams.InventoryBase64Data, triggerParams.InventoryPath)
	if err != nil {
		registerFatal(fmt.Sprintf("Failed to create inventory, err: %s", err), warnings, triggerParams.Format)
	}

	// Config validation
	bitriseConfig, warns, err := CreateBitriseConfigFromCLIParams(triggerParams.BitriseConfigBase64Data, triggerParams.BitriseConfigPath)
	warnings = append(warnings, warns...)
	if err != nil {
		registerFatal(fmt.Sprintf("Failed to create config, err: %s", err), warnings, triggerParams.Format)
	}

	// Format validation
	if triggerParams.Format == "" {
		triggerParams.Format = output.FormatRaw
	} else if !(triggerParams.Format == output.FormatRaw || triggerParams.Format == output.FormatJSON) {
		registerFatal(fmt.Sprintf("Invalid format: %s", triggerParams.Format), warnings, output.FormatJSON)
	}

	// Trigger filter validation
	if triggerParams.TriggerPattern == "" &&
		triggerParams.PushBranch == "" && triggerParams.PRSourceBranch == "" && triggerParams.PRTargetBranch == "" && triggerParams.Tag == "" {
		registerFatal("No trigger pattern nor trigger params specified", warnings, triggerParams.Format)
	}
	//

	//
	// Main
	isPRMode, err := isPRMode(prGlobalFlagPtr, inventoryEnvironments)
	if err != nil {
		registerFatal(fmt.Sprintf("Failed to check  PR mode, err: %s", err), warnings, triggerParams.Format)
	}

	pipelineToRunID, workflowToRunID, err := getPipelineAndWorkflowIDByParamsInCompatibleMode(bitriseConfig.TriggerMap, triggerParams, isPRMode)
	if err != nil {
		registerFatal(err.Error(), warnings, triggerParams.Format)
	}

	triggerModel := map[string]string{}
	if pipelineToRunID != "" {
		triggerModel["pipeline"] = pipelineToRunID
	}
	if workflowToRunID != "" {
		triggerModel["workflow"] = workflowToRunID
	}

	if triggerParams.TriggerPattern != "" {
		triggerModel["pattern"] = triggerParams.TriggerPattern
	} else {
		if triggerParams.PushBranch != "" {
			triggerModel["push-branch"] = triggerParams.PushBranch
		} else if triggerParams.PRSourceBranch != "" || triggerParams.PRTargetBranch != "" {
			if triggerParams.PRSourceBranch != "" {
				triggerModel["pr-source-branch"] = triggerParams.PRSourceBranch
			}
			if triggerParams.PRTargetBranch != "" {
				triggerModel["pr-target-branch"] = triggerParams.PRTargetBranch
			}
		} else if triggerParams.Tag != "" {
			triggerModel["tag"] = triggerParams.Tag
		}
	}

	switch triggerParams.Format {
	case output.FormatRaw:
		msg := ""
		for key, value := range triggerModel {
			if key == "pipeline" || key == "workflow" {
				msg = msg + fmt.Sprintf("-> %s", colorstring.Blue(value))
			} else {
				msg = fmt.Sprintf("%s: %s ", key, value) + msg
			}
		}
		log.Print(msg)
		break
	case output.FormatJSON:
		bytes, err := json.Marshal(triggerModel)
		if err != nil {
			registerFatal(fmt.Sprintf("Failed to parse trigger model, err: %s", err), warnings, triggerParams.Format)
		}

		log.Print(string(bytes))
		break
	default:
		registerFatal(fmt.Sprintf("Invalid format: %s", triggerParams.Format), warnings, output.FormatJSON)
	}
	//

	return nil
}


text:
  {{>header {title: "Menu"}}}

      Change campaign

      Manage languages

    <a class="list-group-item nm-list-group-item-drawer {{#languages.length < 2}}is-disabled{{/}}" on-click="showLanguage()" href="#">

      View content for a language

redpajama_set_name: RedPajamaGithub


text:
/**
 * TODO: There is an identical file in server-base. WTH?! We need to review and factorise.
 * DO NOT change/diverge any of these files before that!
 */

/*
 * Utils to extract the rendered kNetwork in KnetMaps (Network View), fetch back-end API summary/metadata and upload/save to knetspace via API.
 * Authors: singha, hearnshawj
 */

/* Function to save knetwork rendered in knetmaps (cyJS) to knetspace via POST. */
 function exportAsJson(networkId, requestParams) {
   var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`

   var exportJson= cy.json(); // full graphJSON

   var exportedJson= filterJsonToExport(cy, exportJson); // the final "graph" to export
   var thumbnail_image= exportThumbnail(cy); // fetch knetwork thumbnail as well.
   // fetch total node & edge count for this knetwork.
   var totalNodes= cy.$(':visible').nodes().size();
   var totalEdges= cy.$(':visible').edges().size();
   // formatted date: yyyy-mm-dd hh:mm (mm: January=0)
   var currentDate= new Date();
   var knet_date= currentDate.getFullYear() +'-'+ String(currentDate.getMonth() + 1).padStart(2, '0') +'-'+ String(currentDate.getDate()).padStart(2, '0')
           +' '+ currentDate.getHours() +':'+ ('0'+currentDate.getMinutes()).slice(-2);

   //console.log("knet-save.js: networkId= "+ networkId); // test
   var knet_name= "knetwork", apiGraphSummary= null;
   if(networkId === null) { // for a new knetwork, fetch graphSummary from KnetMiner server API.
      //console.log("fetch graphSummary from KnetMiner server API..."); // test
      apiGraphSummary= getGraphDBSummary();
     }

   // add api_graphSummary to the above as well, if exists.
   var speciesTaxid= null, speciesName= null, dbVersion= null, dbDateCreated= null, sourceOrganization= null, provider= null;
   if(apiGraphSummary !== null && apiGraphSummary.size > 0) {
        var currentSpecies =  multiSpeciesFeature.speciesData(apiGraphSummary.species)
      speciesTaxid= currentSpecies.taxId;
      speciesName= currentSpecies.scientificName;
      dbVersion= apiGraphSummary.version;
      dbDateCreated= apiGraphSummary.creationDate;
      sourceOrganization= apiGraphSummary.organization;
      provider= apiGraphSummary.organization;
      //console.log(speciesTaxid +","+ speciesName +","+ dbVersion +","+ dbDateCreated +","+ sourceOrganization +","+ provider); // test
     }

   // get keyword and gene list too (if found) to save.
   var keywords= null, gene_list= null;
   if(requestParams !== null) { // for a new knetwork, fetch graphSummary from KnetMiner server API.
      gene_list= JSON.stringify(requestParams.list);
      if(requestParams.keyword !== null) { keywords= requestParams.keyword; }
     // console.log("gene_list: "+ gene_list +", keywords: "+ keywords); // test
     }

   // default knetName & knetDesc for modal (jBox)
   var knetName= knet_name;
   var knetDesc= knetName;

   // POST to knetspace via /api/v1/networks/
  // var knetspace_api_host= "http://babvs72.rothamsted.ac.uk:8000"; //or "http://localhost:8000";
   var knetspace_api_host; // relative domain
   getKsAPI().then(function(ksAddress) {
       knetspace_api_host = ksAddress;
      // console.log("fetched knetspace_api_host: "+ knetspace_api_host); // test
    });
    isLoggedIn().then(function (bool) {
        if (bool) {
            if (networkId === null) {
                //if(typeof api_url !== "undefined") { // if it's within knetminer (DISABLED: as it breaks genepage api)
                userPlan().then(function (userBool) {
                    if (!userBool) {
                        // jBox modal to let Pro users enter knetName & knetDesc and save when POSTing a new kNetwork. also set private slider as set true/private by default.
                        var uploadHtml = "<form class='form' method='post' action='#'>"
                                + "Knetwork name" + "

"
                                + "<input style='height:20px;width:450px;' maxlength='30' placeholder="+knet_name+" type='text' name='knetName' id='kNetName'>" + "

"
                                + "Description" + "

"
                                + "<textarea style='height:100px;width:450px;' placeholder='Enter your description here...' name='knetDesc' id='knetDescription'></textarea>" + "

"
                                + "
Private:"
                                + ""
                                + "<input type='checkbox' id='privateCheck' checked=true>"
                                + "
" + "

"
                                + "<input type='button' name='KnetSubmit' id='KnetSubmit' value='Save'>" + "</form>";
                    } else { //free user (now also enable private slider and set true/private by default)
                            var uploadHtml = "<form class='form' method='post' action='#'>"
                                + "Knetwork name" + "

"
                                + "<input style='height:20px;width:450px;' maxlength='30' placeholder="+knet_name+" type='text' name='knetName' id='kNetName'>" + "

"
                                + "Description" + "

"
                                + "<textarea style='height:100px;width:450px;' placeholder='Enter your description here...' name='knetDesc' id='knetDescription'></textarea>" + "

"
                                + "
Private:"
                                + ""
                                + "<input type='checkbox' id='privateCheck' checked=true>"
                                + "
" + "

"
                                + "<input type='button' name='KnetSubmit' id='KnetSubmit' value='Save'>" + "</form>";
                    }

                var uploadModal = new jBox('Modal', {
                    title: 'Save to KnetSpace',
                    animation: 'pulse', content: uploadHtml, width: 500, cancelButton: 'Exit', draggable: 'title',
                    position: {x: 'center', y: 'top'}, offset: {x: 0, y: 150}, delayOpen: 50
                });
                uploadModal.open(); // open
                if (userBool) {
                    new jBox('Tooltip', {
                        attach: '#priv-lab',
                        pointer: 'center',
                        content: "Knetwork is private. Turn this toggle off to make it public."
                    });
                } else {
                    new jBox('Tooltip', {
                        attach: '#priv-lab',
                        pointer: 'center',
                        content: "Knetwork is private. Turn this toggle off to make it public."
                    });
                }

                $('#KnetSubmit').on('keypress click', function (e) {
                    if (e.which === 13 || e.type === 'click') {
                        //console.log("user inputs: "+ $('input[name=knetName]').val() +", "+ $('textarea#knetDescription').val());
                        if ($('input[name=knetName]').val()) {
                            knetName = $('input[name=knetName]').val();
                        } else {
                            knetName = knet_name;
                        }

                        if ($('textarea#knetDescription').val()) {
                            knetDesc = $.trim($('textarea#knetDescription').val());
                        } else {
                            knetDesc = "Network for " + knetName;
                        }
                        if (!userBool) { // pro user
                            var privateBool = document.getElementById('privateCheck').checked;
                            var isknetpublic= !privateBool;
                        } else { // free user
                            var privateBool = document.getElementById('privateCheck').checked;
                            var isknetpublic= !privateBool;
                        }
                        console.log("added by user: knetName= "+ knetName + ", desc= "+ knetDesc); // test
                        console.log("Free user? : " + userBool +", public knet? : "+ isknetpublic);

                        // POST a new knetwork to knetspace with name, date_created, apiGraphSummary fields plus this graph, image, numNodes, numEdges.
                        var post_json = JSON.stringify({name: knetName, dateCreated: knet_date, numNodes: totalNodes, numEdges: totalEdges, graph: JSON.parse(exportedJson),
                            image: thumbnail_image, speciesTaxid: speciesTaxid, speciesName: speciesName, dbVersion: dbVersion, dbDateCreated: dbDateCreated,
                            sourceOrganization: sourceOrganization, provider: provider, description: knetDesc, gene: gene_list, keyword: keywords, is_public: isknetpublic });
                        if (keywords === null || keywords === "") { // for non-keyword search
                            post_json = JSON.stringify({name: knetName, dateCreated: knet_date, numNodes: totalNodes, numEdges: totalEdges, graph: JSON.parse(exportedJson),
                                image: thumbnail_image, speciesTaxid: speciesTaxid, speciesName: speciesName, dbVersion: dbVersion, dbDateCreated: dbDateCreated,
                                sourceOrganization: sourceOrganization, provider: provider, description: knetDesc, gene: gene_list, is_public: isknetpublic });
                        }

                        $.ajax({
                            type: 'POST',
                            url: knetspace_api_host + '/api/v1/networks/',
                            timeout: 1000000,
                            xhrFields: {withCredentials: true},
                            headers: {
                                "Accept": "application/json; charset=utf-8",
                                "Content-Type": "application/json; charset=utf-8"
                            },
                            datatype: "json",
                            data: post_json,
                            beforeSend: function() {
                                jboxNotice("Saving to KnetSpace...", 'blue', 60, 1000);
                            }
                        }).fail(function (errorlog) {
                            $('#overlay').fadeOut();
                            if(JSON.stringify(errorlog.responseText).includes("quota")) {
                                uploadModal.toggle();
                                var failedMsgQ = "You've exceeded your KnetSpace Knetwork quota!

" + "Click here to buy more Knetworks.";
                                jboxNotice(failedMsgQ, 'red', 60, 15000);
                            } else {
                                uploadModal.toggle();
                                var failedMsg = "Failed to upload kNetwork " + knetName;
                                jboxNotice(failedMsg, 'red', 60, 2500);
                                console.log("POST error: " + JSON.stringify(errorlog));
                            }
                        }).success(function (data) {
                            $('#overlay').fadeOut();
                            uploadModal.toggle();
                            var netContentSuccess = "Successfully saved!

" + "View it in KnetSpace";
                            jboxNotice(netContentSuccess, 'blue', 60, 15000);
                        });
                        // jBox modal - tasks completed.
                        uploadModal.destroy(); // destroy jBox modal when done
                    }
                });
            });
                //}
            } else { // PATCH existing networkId with updated graph, image, numNodes, numEdges, dateModified.
                var patch_json = JSON.stringify({dateModified: knet_date, numNodes: totalNodes, numEdges: totalEdges,
                    graph: JSON.parse(exportedJson), image: thumbnail_image});
                $.ajax({
                    type: 'PATCH',
                    url: knetspace_api_host + '/api/v1/networks/' + networkId + '/',
                    timeout: 1000000,
                    xhrFields: {withCredentials: true},
                    headers: {
                        "Accept": "application/json; charset=utf-8",
                        "Content-Type": "application/json; charset=utf-8"
                    },
                    datatype: "json",
                    data: patch_json,
                    beforeSend: function () {
                        jboxNotice("Sending Knetwork to KnetSpace...", 'blue', 60, 1000);
                    }
                })
                        .fail(function (errorlog) {
                            $('#overlay').fadeOut();
                            uploadModal.toggle();
                            var failedMsg = "Failed to upload kNetwork " + knetName;
                            jboxNotice(failedMsg, 'red', 60, 1000);
                            console.log("PATCH error: " + JSON.stringify(errorlog));
                        })
                        .success(function (data) {
                            $('#overlay').fadeOut();
                            uploadModal.toggle();
                            var netContentSuccess = "Network " + knetName + " submitted!

" + "View it in KnetSpace";
                            jboxNotice(netContentSuccess, 'blue', 60, 15000);
                        });
            }

        } else {
            $('#loginBox').remove();
            loginModalInit();
        }
    });
};

 // generate pure JSON to export from KnetMaps for graphJSON and metadata
 function filterJsonToExport(cy, exportJson) {
   var elesToRetain= []; // to streamline content exported in exportJson (graphJSON) & metaJSON (allGraphData).
   cy.$(':visible').forEach(function (ele) { elesToRetain.push(ele.id()); });

   // remove hidden nodes/edges metadata from exportJson.
   exportJson.elements.nodes= exportJson.elements.nodes.filter( function( con ) {
	   return elesToRetain.includes(con.data.id); });
   exportJson.elements.edges= exportJson.elements.edges.filter( function( rel ) {
	   return elesToRetain.includes(rel.data.id); });

   // remove hidden nodes/edges metadata from metaJSON (allGraphData).
   var metaJSON= allGraphData; // differs from knetspace/knetmaps
   metaJSON.ondexmetadata.concepts= metaJSON.ondexmetadata.concepts.filter( function( con ) {
	   return elesToRetain.includes(con.id); });
   metaJSON.ondexmetadata.relations= metaJSON.ondexmetadata.relations.filter( function( rel ) {
	   return elesToRetain.includes(rel.id); });
   // remove other redundant metaJSON entries.
   var omit_redundant= ["graphName","numberOfConcepts","numberOfRelations","version"];
   omit_redundant.forEach(function (entry) { delete metaJSON.ondexmetadata[entry]; });

   var json_response= '{"graphJSON":'+ JSON.stringify(exportJson) + ', "allGraphData":' + JSON.stringify(metaJSON) +'}';
   return json_response;
  }

 // fetch graphSummary from KnetMiner server API.
 function getGraphDBSummary() {
   var graphSummary= '';
   if(typeof api_url !== "undefined") {
        $.ajax({
            async: false,
            type: 'GET',
            url: api_url + '/dataset-info',
            success: function (data) {
                graphSummary = data
           }
       });
     }
    return graphSummary;
  }

  // Export the network thumbnail.
  function exportThumbnail(cy) {
   var png64 = cy.png({ "scale" : 2.0 /*0.8*/, "output" : 'base64'}); // .setAttribute('crossOrigin', 'anonymous');

   return png64.replace("data:image/png;base64,", "");
  }


text:
package fi.pyppe.ircbot

import org.slf4j.LoggerFactory
import com.typesafe.scalalogging.Logger

trait LoggerSupport { self =>

  implicit lazy val logger: Logger =
    Logger(LoggerFactory.getLogger(self.getClass.getName.replaceAll("\\$$", "")))

}


text:
package com.glooory.flatreader.util;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.view.View;
import android.widget.Toast;

/**
 * Created by Glooory on 2016/10/6 0006 17:28.
 */

public class StringUtils {

    /**
     * 复制到粘贴板
     * @param context
     * @param text
     * @param success
     */
    public static void copyToClipBoardToast(Context context, String text, String success) {
        ClipData clipData = ClipData.newPlainText("flat_reader", text);
        ClipboardManager manager = (ClipboardManager) context.getSystemService(
                Context.CLIPBOARD_SERVICE);
        manager.setPrimaryClip(clipData);
        Toast.makeText(context, success, Toast.LENGTH_SHORT).show();
    }

    public static void copyToClipBoardSnackbar(Context context, View view, String text, String success) {
        ClipData clipData = ClipData.newPlainText("flat_reader", text);
        ClipboardManager manager = (ClipboardManager) context.getSystemService(
                Context.CLIPBOARD_SERVICE);
        manager.setPrimaryClip(clipData);
        SnackbarUtils.makeShort(view, success).confirm();
    }

}


text:
( function ( $ ) {

    oxDropDown = {

        options: {
            sSubmitActionClass  : 'js-fnSubmit',
            sLinkActionClass    : 'js-fnLink',
            sDisabledClass      : 'js-disabled'
        },

         _create: function(){

            var self = this,
                options = self.options;

            this.head               = this.element;
            this.oxDropDown         = this.head.parent( 'div' );
            this.valueList          = this.oxDropDown.children( 'ul' );
            this.selectedValueLabel = $( 'p span', this.oxDropDown );
            this.selectedValue      = $( 'input', this.oxDropDown );
            this.blSubmit           = this.oxDropDown.hasClass( options.sSubmitActionClass );
            this.blLink             = this.oxDropDown.hasClass( options.sLinkActionClass );
            this.actionForm         = this.oxDropDown.closest( 'form' );

            // clicking on drop down header
            this.head.click(function() {
                self.toggleDropDown();
                return false;
            });

            // selecting value
            $( 'a', this.valueList ).click( function (){
                self.select( $(this) );
                self.hideDropDown();
                return self.action();
            });

            // clicking else where
            $( document ).click( function(){
                self.hideAll();
            });
        },

        /**
         * execute action after select: do nothing, submit, go link
         *
         * @return boolean
         */
        action : function(){

            // on submit
            if( this.blSubmit ){
                this.actionForm.submit();
                return false;
            }

            // on link
            if( this.blLink ){
               return true;
            }

            // just setting
            return false;
        },

        /**
         * set selected value
         *
         * @return null
         */
        select : function( oSelectLink ) {
            this.selectedValue.val( oSelectLink.attr('data-selection-id') );
            this.selectedValueLabel.text( oSelectLink.text() );
            $('a', this.valueList).removeClass('selected');
            oSelectLink.addClass('selected');
        },

        /**
         * toggle oxDropDown
         *
         * @return null
         */
        toggleDropDown : function() {
            if ( !this.isDisabled() ) {
                if (this.valueList.is(':visible')) {
                    this.hideDropDown();
                }
                else {
                    this.showDropDown();
                }
            }
        },

        /**
         * show value list
         *
         * @return null
         */
        showDropDown : function (){

           this.hideAll();

           //adding additional
 for default value from dropbox header
           this.valueList.prepend('

');
           this.head.clone().appendTo($("li.value", this.valueList));
           $('li.value p', this.valueList ).removeClass('underlined');
           $('li.value p', this.valueList ).css('padding-right', '5px');

           // set width
           this.valueList.css("width", this.oxDropDown.outerWidth());

           this.valueList.show();
        },

        /**
         * hide values list
         *
         * @return null
         */
        hideDropDown : function() {
            this.valueList.hide();
            $("li.value").remove();
        },

        /**
         * hide all opend oxDropDown
         *
         * @return null
         */
        hideAll : function() {
            $("li.value").remove();
            $('ul.drop').hide();
        },

        /**
         * check is dropdown disabled
         *
         * @return boolean
         */
        isDisabled : function() {
            return this.head.hasClass( this.options.sDisabledClass );
        }
    }

   $.widget("ui.oxDropDown", oxDropDown );

})( jQuery );


text:
Scripts and Dockerfiles to create a docker image for fuzzing with Fuzzilli.

## Overview

The container image produced by the main build script ([build.sh](./build.sh)) will contain

- The Fuzzilli binary at ~/Fuzzilli compiled from the current source code, and
- One or more JavaScript engines compiled as specified in their respective [target directory](../../Targets). The necessary files to run the engine (the binary, possibly various libraries, and any other resource files required by the engine) will be located in a subdirectory of the home directory: ~/jsc, ~/spidermonkey, ~/v8, ~/duktape, ~/jerryscript

The container image will *not* contain any temporary build artifacts, source code, etc. to reduce its size.

## Quickstart

1. Make sure docker is installed
2. Run `./build.sh [jsc|spidermonkey|v8|duktape|jerryscript|major]`

The build script might have to run as root, depending on how [docker is configured](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user).

Afterwards, a docker image named "fuzzilli" will be available and can be used to fuzz any of the compiled JS engines (in this example JavaScriptCore) with Fuzzilli: `docker run -ti fuzzilli ./Fuzzilli --profile=jsc ./jsc/jsc`

It is also possible to only rebuild Fuzzilli and use previously compiled engines by running `./build.sh fuzzilli`

Under the hood, here is roughly what happens during building:

- Depending on the arguments, the [root build script](./build.sh) will invoke a number of builders, located in the \*Builder subdirectories. Fuzzilli is always (re-)build (by the FuzzilliBuilder) as well as all of the requested JS engines
- The builders will generally first copy all the necessary files (Fuzzilli soure code, engine patches, target revision, etc.) from the repository root into the builder's directory (this is necessary as they have to be in a subdirectory for docker to be able to access them), then build the docker image, fetching any source code, checking out the requested revision (from the [target's](../../Targets) REVISION file) and building the final product (e.g. Fuzzilli or a JS engine). Afterwards, all build products are copied out of the container image into the out/ directory of that builder.
- Finally, the root build script copies all available build products (that may include build products from previous builds if an engine had been built before and not rebuilt this time) into the final fuzzilli docker image.


text:
Release
=======

> Although not very tricky, it is quite easy to deploy something that doesn't quite work as expected. The following steps
> navigate a through some of the release gotchas and will hopefully result in a successful release¹.

STEPS:
------

1. Update CHANGELOG
2. Bump version in `lib/mongoid/uuid/version.rb`
3. Push changes
4. Create a tag

Glossary
--------

¹ [Ember CLI RELEASE]

[Ember CLI RELEASE]: https://raw.githubusercontent.com/ember-cli/ember-cli/master/RELEASE.md "Ember CLI RELEASE"


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

{% block title %}Vnos kategorije{% endblock title %}

{% block containter %}

{% if admin and logiran %}

Vnos nove kategorije

Tukaj vnašamo novo kategorijo. Ker imam rad red in poenostavljenje se vsako novo kategorijo vnese preko tega sistema... čeprav bi bilo verjetno lažje na roke narest ;) Posledica tega je da mi za vsako novo kategorijo ni potrebno kode spreminjat! :)

                    <form action="/kreirajkat?%s"
                            enctype="multipart/form-data"
                            method="post">

                                Ime kategorije
                                <input type="text" class="form-control" name="kat_naslov">

                                Izberi slikco za kategorijo
                                <input type="file" class="btn btn-default" name="kat_slika"/>

                                Opis kategorije
                                <textarea name="kat_opis" class="form-control" rows="6"></textarea>

                                <button type="submit" class="btn btn-default">Shrani</button>

                    </form>

{% else %}

BUZZ OFF!

{% endif %}
{% endblock containter %}


text:
<<error>missing-element</error> xmlns="urn:test:simple.rnc">
</<error>missing-element</error>


text:
(function(Module) {

	function Provider() {}

	Provider.prototype = {

		factory: null,

		manager: null,

		constructor: Provider,

		destructor: function destructor(cascadeDestroy) {
			if (cascadeDestroy && this.factory) {
				this.factory.destructor();
			}

			this.factory = this.manager = null;
		},

		_createModuleClass: function _createModuleClass(type) {
			return "module " + type.charAt(0).toLowerCase() + type.slice(1, type.length)
				.replace(/(\.[A-Z])/g, function(match, $1) {
					return "-" + $1.replace(/\./g, "").toLowerCase();
				})
				.replace(/Module$/, "")
				.replace(/^\s+|\s+$/g, "");
		},

		createModule: function createModule(element, type, options) {
			var module = this.factory.getInstance(type);
			var className = this._createModuleClass(type);

			element.className += element.className ? " " + className : className;

			module.setElement(element);
			module.setOptions(options);

			if (options.defaultModule) {
				this.manager.setDefaultModule(module);
			}

			return module;
		},

		createModules: function createModule(metaData, callback, context) {
			var modules = [],
			    module,
			    callback = callback || function() {};

			metaData.forEach(function(element, type, options) {
				module = this.createModule(element, type, options);
				modules.push(module);
				callback.call(context, module, element, type, options);
			}, this);

			callback = context = module = null;

			return modules;
		}

	};

	Module.Provider = Provider;

})(window.Module || {});


text:
<!DOCTYPE html>

	<title>Fun-N-Fitness</title>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
	<meta name="description" content="" />

	<link rel="stylesheet" type="text/css" href="css/kickstart.css" media="all" />
	<link rel="stylesheet" type="text/css" href="style.css" media="all" />
	<link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />

 Home

 About Us

 Staff

 Class Descriptions

 Schedule

 Tuition

 Birthday Parties

 New Happenings

 Contact Us

  Hours and Directions

Fun-N-Fitness

About Us

Who We Are:

Fun-N-Fitness is a recreational facility providing gymnastics and other sports' skills for students to gain both the physical skills as well as the confidence that comes with even the simplest of accomplishments.  In order for our students to be successful, we build upon the basics to provide the best foundation for future skills.  This will promote each student's learning and safety.

Our Philosophy:

Our philosophy is to teach gymnastics and other sports' related skills in a fun, safe and positive environment while at the same time raising each student's self-esteem.

Our Mission Statement:

Our mission is to provide movement education for students to gain awareness for physical fitness, which will promote positive lifestyle and fitness habits.

		<button class="large red">Our Staff</button>

		<button class="large red">Our Classes</button>

		<button class="large red">Contact <Us></Us></button>

1505 S. Byrkit

Mishawaka, IN  4654

(574) 259-FUNN

Check us out on Facebook

© Copyright 2015 | All Rights Reserved. This website was built with HTML KickStart and made with  by Shanaz Chowdhery


text:
package ca.firstvoices.maintenance.common;

import ca.firstvoices.core.io.utils.PropertyUtils;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.SystemPrincipal;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventContext;
import org.nuxeo.ecm.core.event.EventProducer;
import org.nuxeo.ecm.core.event.impl.InlineEventContext;
import org.nuxeo.runtime.api.Framework;

public class RequiredJobsUtils {

  private RequiredJobsUtils() {
    throw new IllegalStateException("Utility class");
  }

  public static void addToRequiredJobs(DocumentModel jobContainer, String jobId) {
    Event event = createEvent(CommonConstants.ADD_TO_REQUIRED_JOBS_EVENT_ID, jobContainer, jobId);
    Framework.getService(EventProducer.class).fireEvent(event);
  }

  public static void addToRequiredJobs(DocumentModel jobContainer, Set<String> jobIds) {
    Event event = createEvent(CommonConstants.ADD_TO_REQUIRED_JOBS_EVENT_ID, jobContainer, jobIds);
    Framework.getService(EventProducer.class).fireEvent(event);
  }

  public static void removeFromRequiredJobs(DocumentModel jobContainer, String jobId,
      boolean success) {
    Event event = createEvent(CommonConstants.REMOVE_FROM_REQUIRED_JOBS_EVENT_ID, jobContainer,
        jobId);
    event.getContext().setProperty("success", success);

    Framework.getService(EventProducer.class).fireEvent(event);

  }

  static Event createEvent(String eventId, DocumentModel jobContainer, String jobId) {
    Set<String> jobIds = new HashSet<>(Collections.singletonList(jobId));
    return createEvent(eventId, jobContainer, jobIds);
  }

  static Event createEvent(String eventId, DocumentModel jobContainer, Set<String> jobIds) {
    Map<String, Serializable> eventProperties = new HashMap<>();
    eventProperties.put("jobContainer", (Serializable) jobContainer);
    eventProperties.put("jobIds", (Serializable) jobIds);

    EventContext ctx = new InlineEventContext(new SystemPrincipal(null), eventProperties);
    return ctx.newEvent(eventId);
  }

  public static boolean hasRequiredJobs(DocumentModel jobContainer, String jobId) {
    return PropertyUtils
        .getValuesAsList(jobContainer, CommonConstants.REQUIRED_JOBS_FULL_FIELD).contains(jobId);
  }
}


text:
/*	$NetBSD: dict_surrogate.c,v 1.1.1.2 2014/07/06 19:27:57 tron Exp $	*/

/*++
/* NAME
/*	dict_surrogate 3
/* SUMMARY
/*	surrogate table for graceful "open" failure
/* SYNOPSIS
/*	#include <dict_surrogate.h>
/*
/*	DICT	*dict_surrogate(dict_type, dict_name,
/*				open_flags, dict_flags,
/*				format, ...)
/*	const char *dict_type;
/*	const char *dict_name;
/*	int	open_flags;
/*	int	dict_flags;
/*	const char *format;
/*
/*	int	dict_allow_surrogate;
/* DESCRIPTION
/*	dict_surrogate() either terminates the program with a fatal
/*	error, or provides a dummy dictionary that fails all
/*	operations with an error message, allowing the program to
/*	continue with reduced functionality.
/*
/*	The global dict_allow_surrogate variable controls the choice
/*	between fatal error or reduced functionality. The default
/*	value is zero (fatal error). This is appropriate for user
/*	commands; the non-default is more appropriate for daemons.
/*
/*	Arguments:
/* .IP dict_type
/* .IP dict_name
/* .IP open_flags
/* .IP dict_flags
/*	The parameters to the failed dictionary open() request.
/* .IP format, ...
/*	The reason why the table could not be opened. This text is
/*	logged immediately as an "error" class message, and is logged
/*	as a "warning" class message upon every attempt to access the
/*	surrogate dictionary, before returning a "failed" completion
/*	status.
/* SEE ALSO
/*	dict(3) generic dictionary manager
/* LICENSE
/* .ad
/* .fi
/*	The Secure Mailer license must be distributed with this software.
/* AUTHOR(S)
/*	Wietse Venema
/*	IBM T.J. Watson Research
/*	P.O. Box 704
/*	Yorktown Heights, NY 10598, USA
/*--*/

/* System library. */

#include <sys_defs.h>
#include <errno.h>

/* Utility library. */

#include <mymalloc.h>
#include <msg.h>
#include <compat_va_copy.h>
#include <dict.h>

/* Application-specific. */

typedef struct {
    DICT    dict;			/* generic members */
    char   *reason;			/* open failure reason */
} DICT_SURROGATE;

/* dict_surrogate_sequence - fail lookup */

static int dict_surrogate_sequence(DICT *dict, int unused_func,
			               const char **key, const char **value)
{
    DICT_SURROGATE *dp = (DICT_SURROGATE *) dict;

    msg_warn("%s:%s is unavailable. %s",
	     dict->type, dict->name, dp->reason);
    DICT_ERR_VAL_RETURN(dict, DICT_ERR_RETRY, DICT_STAT_ERROR);
}

/* dict_surrogate_update - fail lookup */

static int dict_surrogate_update(DICT *dict, const char *unused_name,
				         const char *unused_value)
{
    DICT_SURROGATE *dp = (DICT_SURROGATE *) dict;

    msg_warn("%s:%s is unavailable. %s",
	     dict->type, dict->name, dp->reason);
    DICT_ERR_VAL_RETURN(dict, DICT_ERR_RETRY, DICT_STAT_ERROR);
}

/* dict_surrogate_lookup - fail lookup */

static const char *dict_surrogate_lookup(DICT *dict, const char *unused_name)
{
    DICT_SURROGATE *dp = (DICT_SURROGATE *) dict;

    msg_warn("%s:%s is unavailable. %s",
	     dict->type, dict->name, dp->reason);
    DICT_ERR_VAL_RETURN(dict, DICT_ERR_RETRY, (char *) 0);
}

/* dict_surrogate_delete - fail delete */

static int dict_surrogate_delete(DICT *dict, const char *unused_name)
{
    DICT_SURROGATE *dp = (DICT_SURROGATE *) dict;

    msg_warn("%s:%s is unavailable. %s",
	     dict->type, dict->name, dp->reason);
    DICT_ERR_VAL_RETURN(dict, DICT_ERR_RETRY, DICT_STAT_ERROR);
}

/* dict_surrogate_close - close fail dictionary */

static void dict_surrogate_close(DICT *dict)
{
    DICT_SURROGATE *dp = (DICT_SURROGATE *) dict;

    myfree((char *) dp->reason);
    dict_free(dict);
}

int     dict_allow_surrogate = 0;

/* dict_surrogate - terminate or provide surrogate dictionary */

DICT   *dict_surrogate(const char *dict_type, const char *dict_name,
		               int open_flags, int dict_flags,
		               const char *fmt,...)
{
    va_list ap;
    va_list ap2;
    DICT_SURROGATE *dp;
    VSTRING *buf;
    void    (*log_fn) (const char *, va_list);
    int     saved_errno = errno;

    /*
     * Initialize argument lists.
     */
    va_start(ap, fmt);
    VA_COPY(ap2, ap);

    /*
     * Log the problem immediately when it is detected. The table may not be
     * accessed in every program execution (that is the whole point of
     * continuing with reduced functionality) but we don't want the problem
     * to remain unnoticed until long after a configuration mistake is made.
     */
    log_fn = dict_allow_surrogate ? vmsg_error : vmsg_fatal;
    log_fn(fmt, ap);
    va_end(ap);

    /*
     * Log the problem upon each access.
     */
    dp = (DICT_SURROGATE *) dict_alloc(dict_type, dict_name, sizeof(*dp));
    dp->dict.lookup = dict_surrogate_lookup;
    if (open_flags & O_RDWR) {
	dp->dict.update = dict_surrogate_update;
	dp->dict.delete = dict_surrogate_delete;
    }
    dp->dict.sequence = dict_surrogate_sequence;
    dp->dict.close = dict_surrogate_close;
    dp->dict.flags = dict_flags | DICT_FLAG_PATTERN;
    dp->dict.owner.status = DICT_OWNER_TRUSTED;
    buf = vstring_alloc(10);
    errno = saved_errno;
    vstring_vsprintf(buf, fmt, ap2);
    va_end(ap2);
    dp->reason = vstring_export(buf);
    return (DICT_DEBUG (&dp->dict));
}


text:
class CreateCreditcardPayments < ActiveRecord::Migration
  def self.up
    rename_table :credit_cards, :creditcard_payments
    rename_table :credit_card_txns, :creditcard_txns

    change_table :creditcard_payments do |t|
      t.remove :verification_value
    end

    change_table :creditcard_txns do |t|
      t.rename :credit_card_id, :creditcard_payment_id
    end
  end

  def self.down
  end
end


text:
<?php

namespace ConfigToken\TreeCompiler\Exception;

class CircularReferenceException extends \Exception
{
}


text:
describe("Job Create Form", () => {
  function openTab(tab) {
    cy.get(".menu-tabbed-item-label").contains(tab).click();
  }

  function submit() {
    cy.contains("Submit").click();
  }

  function typeInInput(inputName, text) {
    cy.get(".create-service-modal-form")
      .find('.form-control[name="' + inputName + '"]')
      .type(text);
  }

  function getActiveTabErrorBadge() {
    return cy.get('.active > .menu-tabbed-item-label span[role="button"]');
  }

  beforeEach(() => {
    cy.configureCluster({
      jobDetails: true,
      mesos: "1-for-each-health",
      nodeHealth: true,
    });
    cy.visitUrl({ url: "/jobs/overview" });
  });

  context("Error badges for the jobs tabs", () => {
    beforeEach(() => {
      // Click 'Create a job'
      cy.get(".button.button-primary-link.button-narrow").click();

      // Wait for the 'New Job' dialog to appear
      cy.get(".modal-header").contains("New Job");
    });

    context("General tab", () => {
      it("displays an error when id is missing", () => {
        // Fill-in the input elements
        cy.get("label").contains("Command Only").click();
        cy.getFormGroupInputFor("Command *").type(
          "while true; do echo 'test' ; sleep 100 ; done"
        );

        // Try to submit the form
        submit();

        // Error banner lists errors
        cy.get(".errorsAlert-listItem").should(($items) => {
          expect($items.length).to.equal(1);
        });

        // Error badge appears
        getActiveTabErrorBadge().contains("1");

        // Fix error
        cy.getFormGroupInputFor("Job ID *").retype("simple");

        // Error badge disappears
        getActiveTabErrorBadge().should("not.be.visible");
      });

      it("adds and removes a dependency", () => {
        cy.get("label:contains(Dependencies)").click();
        cy.get("[data-cy=PopoverListItem]:contains(bar)").click();
        cy.get("[data-cy=badge]:contains(bar) [role=button]").click();
      });
    });

    context("Container Runtime tab", () => {
      it("displays an error badge for parameters", () => {
        openTab("Container Runtime");
        cy.get(".form-control-toggle").contains("Docker Engine").click();
        cy.get(".button-primary-link").contains("Add Parameter").click();
        typeInInput("key.0.dockerParams", " ");
        submit();
        getActiveTabErrorBadge().contains("1");
        typeInInput("key.0.dockerParams", "{selectall}{backspace}");
        getActiveTabErrorBadge().should("not.exist");
      });
    });

    context("Schedule tab", () => {
      it("displays an error badge for missing schedule id", () => {
        openTab("Schedule");
        typeInInput("id.schedules", " ");
        submit();
        getActiveTabErrorBadge().contains("2");
        typeInInput("id.schedules", "{selectall}{backspace}");
        getActiveTabErrorBadge().should("not.exist");
      });
    });

    context("Environment tab", () => {
      it("displays an error badge for environment variables", () => {
        openTab("Environment");
        cy.get(".button-primary-link")
          .contains("Add Environment Variable")
          .click();
        typeInInput("0.0.env", " ");
        submit();
        getActiveTabErrorBadge().contains("1");
        typeInInput("0.0.env", "{selectall}{backspace}");
        getActiveTabErrorBadge().should("not.exist");
      });
    });

    context("Volumes tab", () => {
      it("displays an error badge for volume", () => {
        openTab("Volumes");
        cy.get(".button-primary-link").contains("Add Volume").click();
        typeInInput("containerPath.0.volumes", " ");
        submit();
        getActiveTabErrorBadge().contains("2");
        typeInInput("containerPath.0.volumes", "{selectall}{backspace}");
        getActiveTabErrorBadge().should("not.exist");
      });
    });

    context("Placement tab", () => {
      it("displays an error badge for constraints", () => {
        openTab("Placement");
        cy.get(".button-primary-link")
          .contains("Add Placement Constraint")
          .click();
        typeInInput("attribute.0.placementConstraints", " ");
        submit();
        getActiveTabErrorBadge().contains("2");
        typeInInput(
          "attribute.0.placementConstraints",
          "{selectall}{backspace}"
        );
        getActiveTabErrorBadge().should("not.exist");
      });
    });
  });
});


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceResult;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class WithdrawByoipCidrResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * Information about the address pool.
     *

     */
    private ByoipCidr byoipCidr;

    /**
     *

     * Information about the address pool.
     *

     *
     * @param byoipCidr
     *        Information about the address pool.
     */

    public void setByoipCidr(ByoipCidr byoipCidr) {
        this.byoipCidr = byoipCidr;
    }

    /**
     *

     * Information about the address pool.
     *

     *
     * @return Information about the address pool.
     */

    public ByoipCidr getByoipCidr() {
        return this.byoipCidr;
    }

    /**
     *

     * Information about the address pool.
     *

     *
     * @param byoipCidr
     *        Information about the address pool.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public WithdrawByoipCidrResult withByoipCidr(ByoipCidr byoipCidr) {
        setByoipCidr(byoipCidr);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getByoipCidr() != null)
            sb.append("ByoipCidr: ").append(getByoipCidr());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof WithdrawByoipCidrResult == false)
            return false;
        WithdrawByoipCidrResult other = (WithdrawByoipCidrResult) obj;
        if (other.getByoipCidr() == null ^ this.getByoipCidr() == null)
            return false;
        if (other.getByoipCidr() != null && other.getByoipCidr().equals(this.getByoipCidr()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getByoipCidr() == null) ? 0 : getByoipCidr().hashCode());
        return hashCode;
    }

    @Override
    public WithdrawByoipCidrResult clone() {
        try {
            return (WithdrawByoipCidrResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }
}


text:
namespace {

  class OffsetRequestTest : public BaseTest {
    protected:

      OffsetRequestTest() { }
      virtual ~OffsetRequestTest() { }
      virtual void SetUp() { }
      virtual void TearDown() { }
  };

  TEST_F(OffsetRequestTest, Constructor) {

    OffsetRequest *or1 = createOffsetRequest();
    EXPECT_NE(or1, (void*)0);
    unsigned char * message = or1->toWireFormat();
    int size = or1->getWireFormatSize(true);
    EXPECT_EQ(or1->size(), size);

    OffsetRequest *or2 = new OffsetRequest(message);

    EXPECT_NE(or2, (void*)0);
    EXPECT_EQ(or2->size(), or1->size());
    EXPECT_EQ(or2->replicaId, or1->replicaId);
    for (int i=0; i<or2->offsetTopicArraySize; i++) {
      EXPECT_EQ(*(or2->offsetTopicArray[i]), *(or1->offsetTopicArray[i]));
    }

    delete or1;
    delete or2;
  }

}  // namespace


text:
#pragma once

using namespace std;

#include <Arduino.h>
#include <WifiUart.h>

#define WIFIU_MISC_RESPONSE_OK 0
#define WIFIU_MISC_RESPONSE_ERR -1
#define WIFIU_MISC_PASSLENGTH 6
struct WifiUartMiscPasswordResponse {
    int code;
    char password[WIFIU_MISC_PASSLENGTH+1];
};
struct WifiUartMiscWebServiceResponse {
    int code;
    bool isEnabled;
    int port;
};

class WifiUartMisc {
    public:
        WifiUartMisc ();
        ~WifiUartMisc ();

        static struct WifiUartMiscPasswordResponse getSystemPassword (WifiUart *wifi); // PASS
        static bool setSystemPassword (WifiUart *wifi, char *newPass);

        static struct WifiUartMiscWebServiceResponse getWebServiceStatus (WifiUart *wifi); // WEBS
        static bool setWebServiceStatus(WifiUart *wifi, bool status, int port);

 // #define WIFIU_ATP_NULL "" // Null command
 // #define WIFIU_ATP_ENTS "ENTS" // Enter sleeping mode
 // #define WIFIU_ATP_IOC "IOC" // GPIO Control
 // #define WIFIU_ATP_IOM "IOM" // Set or query GPIO mode
 // #define WIFIU_ATP_PMTF "PMFT" // Update parameters in memory to flash
 // #define WIFIU_ATP_QVER "QVER" // Query version

};


text:
var Y;
(function (Y) {
    /**
     * 骆驼命名转换
     * 把 padding-top变成paddingTop
     * @param {string} text - 要转变的字符串
     * @return {string} -转换后的字符串
     */
    function camelize(text) {
        // /\-(\w)/g 正则内的 (\w) 是一个捕获,捕获的内容对应后面 function 的 letter
        // 意思是将 匹配到的 -x 结构的 x 转换为大写的 X (x 这里代表任意字母)
        return text.replace(/\-(\w)/g, function (all, letter) { return letter.toUpperCase(); });
    }
    Y.camelize = camelize;
    Y.numberRegx = /([+\-]?)(\d{1,3}(?:,?\d{3})*)(.\d+)?/;
    var idSeed = 0;
    var idTime = "_";
    function genId() {
        if (++idSeed === 2100000000) {
            idSeed = 0;
            idTime = "_";
        }
        return idTime + idSeed.toString();
    }
    Y.genId = genId;
    /**
     * 去掉前后空格的正则对象
     */
    Y.trimRegx = /^\s+|\s+$/;
    /**
     * 去掉前后空格
     * 把 padding-top变成paddingTop
     * @param {string} text - 要去掉前后空格的字符串
     * @return {string} -转换后的字符串
     */
    function trim(text) { return text.replace(Y.trimRegx, ""); }
    Y.trim = trim;
    ///////////////////////////////////////////////////////////////
    /// DOM
    ////////////////////////////////////////////////////////////////
    var divContainer = document.createElement("div");
    var p_maps = {
        "TD": document.createElement("tr"),
        "TH": document.createElement("tr"),
        "TR": document.createElement("tbody"),
        "TBODY": document.createElement("table"),
        "LI": document.createElement("ul"),
        "OPTION": document.createElement("select"),
        "DT": document.createElement("dl")
    };
    p_maps.THEAD = p_maps.TFOOT = p_maps.TBODY;
    p_maps.DD = p_maps.DT;
    p_maps.OPTIONGROUP = p_maps.OPTION;
    /**
    * 克隆一个html元素
    * @method
    * @param {HTMLElement} toBeClone - 要克隆的元素
    * @return - 克隆的新的元素。其结构与属性与toBeClone一模一样
    */
    function cloneNode(toBeClone) {
        var p = p_maps[toBeClone.tagName] || divContainer;
        var html = toBeClone.outerHTML + "";
        p.innerHTML = html;
        var node = p.firstChild;
        p.removeChild(node);
        return node;
    }
    Y.cloneNode = cloneNode;
    if (divContainer.addEventListener) {
        Y.attach = function (element, evtname, handler) { return element.addEventListener(evtname, handler, false); };
        Y.detech = function (element, evtname, handler) { return element.removeEventListener(evtname, handler, false); };
    }
    else if (divContainer["attachEvent"]) {
        Y.attach = function (element, evtname, handler) { return element.attachEvent("on" + evtname, handler); };
        Y.detech = function (element, evtname, handler) { return element.detechEvent("on" + evtname, handler); };
    }
    function cancelEvent(evt) {
        evt || (evt = event);
        evt.cancelBubble = true;
        evt.returnValue = false;
        if (evt.preventDefault)
            evt.preventDefault();
        if (evt.stopPropagation)
            evt.stopPropagation();
        return false;
    }
    Y.cancelEvent = cancelEvent;
    function setStyle(elem, style, value) { elem.style[camelize(style)] = value; }
    Y.setStyle = setStyle;
    // 主流浏览器
    if (window.getComputedStyle) {
        Y.getStyle = function (elem, style) { return getComputedStyle(elem, null).getPropertyValue(style); };
    }
    else {
        function getIEOpacity(elem) {
            var filter = null;
            // 早期的 IE 中要设置透明度有两个方法:
            // 1、alpha(opacity=0)
            // 2、filter:progid:DXImageTransform.Microsoft.gradient( GradientType= 0 , startColorstr = '#ccccc', endColorstr = '#ddddd' );
            // 利用正则匹配
            filter = elem.style.filter.match(/progid:DXImageTransform.Microsoft.Alpha\(.?opacity=(.*).?\)/i) || elem.style.filter.match(/alpha\(opacity=(.*)\)/i);
            if (filter) {
                var value = parseFloat(filter);
                if (NaN !== value) {
                    // 转化为标准结果
                    return value ? value / 100 : 0;
                }
            }
            // 透明度的值默认返回 1
            return 1;
        }
        Y.getStyle = function (elem, style) {
            // IE 下获取透明度
            if (style == "opacity") {
                getIEOpacity(elem);
                // IE687 下获取浮动使用 styleFloat
            }
            else if (style == "float") {
                return elem.currentStyle.getAttribute("styleFloat");
                // 取高宽使用 getBoundingClientRect
            }
            else if ((style == "width" || style == "height") && (elem.currentStyle[style] == "auto")) {
                var clientRect = elem.getBoundingClientRect();
                return (style == "width" ? clientRect.right - clientRect.left : clientRect.bottom - clientRect.top) + "px";
            }
            // 其他样式,无需特殊处理
            return elem.currentStyle.getAttribute(camelize(style));
        };
    }
    Y.setOpacity = function (elem, val) {
        var value = parseFloat(val);
        elem.style.opacity = value.toString();
        elem.style.filter = "alpha(opacity=" + (value * 100) + ")";
        return elem;
    };
    Y.displayValues = {};
    function hasClass(element, css) {
        var cssStr = element.className;
        var begin = cssStr.indexOf(css);
        if (begin < 0)
            return false;
        var end = begin + css.length;
        if (begin == 0) {
            if (end == cssStr.length)
                return true;
            return /^\s$/.test(cssStr[begin + 1]);
        }
        if (!/^\s$/.test(cssStr[begin - 1]))
            return false;
        if (end == cssStr.length)
            return true;
        return /^\s$/.test(cssStr[end + 1]);
    }
    Y.hasClass = hasClass;
    function addClass(element, css) {
        if (hasClass(element, css))
            return false;
        var cssStr = element.className;
        if (cssStr === "")
            element.className = css;
        else if (/^\s$/.test(cssStr[cssStr.length - 1]))
            cssStr += css;
        else
            cssStr += ' ' + css;
        element.className = cssStr;
        return true;
    }
    Y.addClass = addClass;
    function removeClass(element, css) {
        var cssStr = element.className;
        var s = cssStr.split(/\s+/);
        var hasIt = false;
        for (var i = 0, j = s.length; i < j; i++) {
            var c = s.shift();
            if (c !== css)
                s.push(c);
            else
                hasIt = true;
        }
        if (hasIt)
            element.className = s.join(" ");
        return hasIt;
    }
    Y.removeClass = removeClass;
    var Eventable = (function () {
        function Eventable() {
        }
        Eventable.prototype.subscribe = function (name, handler) {
            var handlers;
            if (typeof name === "string") {
                var events = this.__y_eventable_events || (this.__y_eventable_events = { "@.@": [] });
                handlers = events[name] || (events[name] = []);
            }
            else {
                handlers = this.__y_eventable_defaults || (this.__y_eventable_defaults = []);
                handler = name;
            }
            handlers.push(handler);
            return this;
        };
        Eventable.prototype.unsubscribe = function (name, handler) {
            var handlers;
            if (typeof name === "string") {
                var events = this.__y_eventable_events;
                if (!events)
                    return this;
                handlers = events[name];
            }
            else {
                handlers = this.__y_eventable_defaults;
            }
            if (!handlers || handlers.length == 0)
                return this;
            for (var i = 0, j = handlers.length; i < j; i++) {
                var h = handlers.shift();
                if (h !== handler)
                    handlers.push(h);
            }
            return this;
        };
        Eventable.prototype.notify = function (name, evtArgs) {
            var handlers;
            if (evtArgs !== undefined) {
                var events = this.__y_eventable_events;
                if (!events)
                    return this;
                handlers = events[name];
            }
            else {
                handlers = this.__y_eventable_defaults;
                evtArgs = name;
            }
            if (!handlers || handlers.length == 0)
                return this;
            for (var i = 0, j = handlers.length; i < j; i++) {
                var h = handlers.shift();
                if (h.call(this, evtArgs) !== false)
                    handlers.push(h);
            }
            return this;
        };
        return Eventable;
    }());
    Y.Eventable = Eventable;
})(Y || (Y = {}));


text:
create database sumk;
use sumk;
SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `demo_user`;
CREATE TABLE `demo_user` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `last_update` timestamp NULL DEFAULT NULL,
  `enable` tinyint(4) DEFAULT '1' COMMENT '1表示有效记录,0表示记录已被删除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `generate`;
CREATE TABLE `generate` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `multikey`;
CREATE TABLE `multikey` (
  `id1` varchar(255) NOT NULL COMMENT '联合主键1',
  `id2` varchar(255) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL COMMENT '联合主键2',
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id1`,`id2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `odd`;
CREATE TABLE `odd` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `data` mediumblob,
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2208669043496333243 DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `school_fuzhou`;
CREATE TABLE `school_fuzhou` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `lastUpdate` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `test_table`;
CREATE TABLE `test_table` (
  `id` bigint(20) NOT NULL COMMENT 'Long 类型,第1列',
  `userid` varchar(255) NOT NULL COMMENT 'String 类型,联合索引1,第2列',
  `enable` bit(1) NOT NULL COMMENT 'boolean 类型,联合索引2,第3列',
  `height` smallint(6) DEFAULT NULL COMMENT 'Short 类型,第4列',
  `age` tinyint(4) DEFAULT NULL COMMENT 'byte 类型,第5列',
  `f` decimal(12,3) DEFAULT NULL COMMENT 'float 类型,第6列',
  `d` decimal(20,5) DEFAULT NULL COMMENT 'double 类型,第7列',
  `valid` bit(1) DEFAULT b'1' COMMENT '1表示有效记录,0表示记录已被删除',
  PRIMARY KEY (`id`),
  KEY `testtable_index1` (`userid`,`enable`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用来测试表格自动生成';

DROP TABLE IF EXISTS `timedemo`;
CREATE TABLE `timedemo` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `lastUpdate` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `user_detail`;
CREATE TABLE `user_detail` (
  `id` bigint(20) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `addr` varchar(255) DEFAULT NULL,
  `height` int(11) DEFAULT NULL,
  `valid` char(1) DEFAULT '1' COMMENT '1表示有效记录,0表示记录已被删除',
  PRIMARY KEY (`id`),
  KEY `user_detail_index1` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
template<size_t N>
std::string_view StringLiteral(const char(&ptr)[N])
{
	return std::string_view(ptr, N - 1);
}


text:
@class IDEViewController, NSString, QLPreviewView;

@interface IDEQuickLookEditor : IDEEditor <QLPreviewViewDelegate, NSUserInterfaceValidations, IDEComparisonEditorHostContext>
{
    QLPreviewView *_qlView;
    IDEViewController *_hostViewController;
}

+ (long long)version;
+ (void)configureStateSavingObjectPersistenceByName:(id)arg1;
+ (id)defaultViewNibName;
@property(retain) IDEViewController *hostViewController; // @synthesize hostViewController=_hostViewController;
@property(retain) QLPreviewView *qlView; // @synthesize qlView=_qlView;
- (void).cxx_destruct;
- (BOOL)editorDocumentIsCurrentRevision;
- (BOOL)editorIsHostedInComparisonEditor;
- (void)commitStateToDictionary:(id)arg1;
- (void)revertStateWithDictionary:(id)arg1;
- (void)printDocument:(id)arg1;
- (void)runPageLayout:(id)arg1;
- (BOOL)findBarSupported;
- (void)takeFocus;
- (void)selectDocumentLocations:(id)arg1;
- (id)currentSelectedDocumentLocations;
- (void)selectPreviousContentSibling:(id)arg1;
- (void)selectNextContentSibling:(id)arg1;
- (void)pause:(id)arg1;
- (void)play:(id)arg1;
- (void)nextPage:(id)arg1;
- (void)previousPage:(id)arg1;
- (BOOL)validateUserInterfaceItem:(id)arg1;
- (void)primitiveInvalidate;
- (void)previewView:(id)arg1 didChangeDisplayStateForPreviewItem:(id)arg2;
- (void)previewView:(id)arg1 willShowPreviewItem:(id)arg2;
- (void)loadView;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
namespace ash {
class ArcCustomTab;
}  // namespace ash

namespace contents {
class WebContents;
}  // namespace contents

namespace gfx {
class Point;
class Size;
}  // namespace gfx

namespace web_modal {
class ModalDialogHostObserver;
}  // namespace web_modal

// Implements a WebContentsModalDialogHost for an ARC Custom Tab. This allows a
// web contents modal dialog to be drawn in the ARC Custom Tab.
// The WebContents hosted by this object must outlive it.
class ArcCustomTabModalDialogHost
    : public web_modal::WebContentsModalDialogHost,
      public web_modal::WebContentsModalDialogManagerDelegate {
 public:
  ArcCustomTabModalDialogHost(std::unique_ptr<ash::ArcCustomTab> custom_tab,
                              content::WebContents* web_contents);
  ~ArcCustomTabModalDialogHost() override = 0;

  // web_modal::WebContentsModalDialogManagerDelegate:
  web_modal::WebContentsModalDialogHost* GetWebContentsModalDialogHost()
      override;

  // web_modal::WebContentsModalDialogHost:
  gfx::NativeView GetHostView() const override;
  gfx::Point GetDialogPosition(const gfx::Size& size) override;
  gfx::Size GetMaximumDialogSize() override;
  void AddObserver(web_modal::ModalDialogHostObserver* observer) override;
  void RemoveObserver(web_modal::ModalDialogHostObserver* observer) override;

 protected:
  std::unique_ptr<ash::ArcCustomTab> custom_tab_;
  content::WebContents* web_contents_;

  DISALLOW_COPY_AND_ASSIGN(ArcCustomTabModalDialogHost);
};

#endif  // CHROME_BROWSER_UI_ASH_ARC_CUSTOM_TAB_MODAL_DIALOG_HOST_H_


text:
package org.jbpm.casemgmt;

import java.util.List;

import org.jbpm.test.JbpmJUnitBaseTestCase;
import org.junit.Test;
import org.kie.api.definition.process.Process;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.task.TaskService;
import org.kie.api.task.model.Task;
import org.kie.api.task.model.TaskSummary;

public class CaseMgmtDynamicTest extends JbpmJUnitBaseTestCase {

    public CaseMgmtDynamicTest() {
        super(true, true);
    }

    @Test
    public void testDynamicTask() {
        createRuntimeManager("EmptyCase.bpmn2");
        RuntimeEngine runtimeEngine = getRuntimeEngine();
        CaseMgmtService caseMgmtService = new CaseMgmtUtil(runtimeEngine);

        ProcessInstance processInstance = caseMgmtService.startNewCase(null);

        List<TaskSummary> tasks = runtimeEngine.getTaskService()
            .getTasksAssignedAsPotentialOwner("krisv", "en-UK");
        assertEquals(0, tasks.size());

        caseMgmtService.createDynamicHumanTask(
            processInstance.getId(), "Do something",
            "krisv", null, "You need to do something", null);

        TaskService taskService = runtimeEngine.getTaskService();
        tasks = taskService.getTasksAssignedAsPotentialOwner("krisv", "en-UK");
        assertEquals(1, tasks.size());
        TaskSummary task = tasks.get(0);
        assertEquals((Long) processInstance.getId(), task.getProcessInstanceId());

        Task[] activeTasks = caseMgmtService.getActiveTasks(processInstance.getId());
        prettyPrintActiveTasks(activeTasks);
        assertEquals(1, activeTasks.length);

        taskService.start(task.getId(), "krisv");
        taskService.complete(task.getId(), "krisv", null);

        activeTasks = caseMgmtService.getActiveTasks(processInstance.getId());
        assertEquals(0, activeTasks.length);
    }

    @Test
    public void testDynamicProcess() {
        createRuntimeManager("EmptyCase.bpmn2", "CaseUserTask.bpmn2");
        RuntimeEngine runtimeEngine = getRuntimeEngine();
        CaseMgmtService caseMgmtService = new CaseMgmtUtil(runtimeEngine);

        ProcessInstance processInstance = caseMgmtService.startNewCase(null);

        List<TaskSummary> tasks = runtimeEngine.getTaskService()
            .getTasksAssignedAsPotentialOwner("krisv", "en-UK");
        assertEquals(0, tasks.size());

        Process[] processes = caseMgmtService.getAvailableProcesses();
        prettyPrintProcesses(processes);
        assertEquals(2, processes.length);

        caseMgmtService.createDynamicProcess(
            processInstance.getId(), "CaseUserTask", null);

        ProcessInstance[] activeSubProcesses = caseMgmtService.getActiveSubProcesses(processInstance.getId());
        prettyPrintActiveSubProcesses(activeSubProcesses);
        assertEquals(1, activeSubProcesses.length);

        TaskService taskService = runtimeEngine.getTaskService();
        tasks = taskService.getTasksAssignedAsPotentialOwner("krisv", "en-UK");
        assertEquals(1, tasks.size());
        TaskSummary task = tasks.get(0);
        taskService.start(task.getId(), "krisv");
        taskService.complete(task.getId(), "krisv", null);

        activeSubProcesses = caseMgmtService.getActiveSubProcesses(processInstance.getId());
        assertEquals(0, activeSubProcesses.length);
    }

    public void prettyPrintActiveTasks(Task[] tasks) {
        System.out.println("***** Active Tasks: *****");
        for (Task task: tasks) {
            System.out.println(task.getName() + " (processInstanceId="
                + task.getTaskData().getProcessInstanceId() + ")");
        }
    }

    public void prettyPrintProcesses(Process[] processes) {
        System.out.println("***** Available processes: *****");
        for (Process process: processes) {
            System.out.println(process.getName() + " (id=" + process.getId() + ")");
        }
    }

    public void prettyPrintActiveSubProcesses(ProcessInstance[] processInstances) {
        System.out.println("***** Active SubProcesses: *****");
        for (ProcessInstance processInstance: processInstances) {
            System.out.println(processInstance.getProcessId()
                + " (id=" + processInstance.getId() + ")");
        }
    }

}


text:
import datetime
import factory
import random
from factory.base import BaseFactory, FactoryMetaClass, CREATE_STRATEGY
from factory.fuzzy import (
    BaseFuzzyAttribute, FuzzyChoice, FuzzyDate, FuzzyDateTime, FuzzyInteger)
from factory.compat import UTC
from ggrc import models
from ggrc.models.reflection import AttributeInfo

def random_string(prefix='', no_unicode=False):
  return u'{prefix}{suffix}{extra}'.format(
      prefix=prefix,
      suffix=random.randint(0, 9999999999),
      extra='' if no_unicode else u'\xff'
  )

def random_string_attribute(prefix=''):
  return factory.LazyAttribute(lambda m: random_string(prefix))

class FuzzyEmail(BaseFuzzyAttribute):
  def fuzz(self):
    return u"{0}@{1}.{2}".format(
        random_string('user-', True), random_string('domain-', True), 'com')

class FactoryStubMarker(object):
  def __init__(self, class_):
    self.class_ = class_

class FactoryAttributeGenerator(object):
  """Use the SQLAlchemy ORM model to generate factory attributes."""
  @classmethod
  def generate(cls, attrs, model_class, attr):
    """Generate a factory attribute for `attr` by inspecting the mapping
    type of the attribute in `model_class`. Add the attribute to the
    `attrs` dictionary.
    """
    if (hasattr(attr, '__call__')):
      attr_name = attr.attr_name
      value = []
    else:
      attr_name = attr
      class_attr = getattr(model_class, attr_name)
      # look up the class method to use to generate the attribute
      method = getattr(cls, class_attr.__class__.__name__)
      value = method(attr_name, class_attr)
    attrs[attr_name] = value

  @classmethod
  def InstrumentedAttribute(cls, attr_name, class_attr):
    method = getattr(cls, class_attr.property.__class__.__name__)
    return method(attr_name, class_attr)

  @classmethod
  def ColumnProperty(cls, attr_name, class_attr):
    method = getattr(
        cls,
        class_attr.property.expression.type.__class__.__name__,
        cls.default_column_handler)
    return method(attr_name, class_attr)

  @classmethod
  def default_column_handler(cls, attr_name, class_attr):
    return random_string_attribute(attr_name)

  @classmethod
  def DateTime(cls, attr_name, class_attr):
    return FuzzyDateTime(
        datetime.datetime(2013, 1, 1, tzinfo=UTC),
        datetime.datetime.now(UTC) + datetime.timedelta(days=730),
    )

  @classmethod
  def Date(cls, attr_name, class_attr):
    return FuzzyDate(
        datetime.date(2013, 1, 1),
        datetime.date.today() + datetime.timedelta(days=730),
    )

  @classmethod
  def Boolean(cls, attr_name, class_attr):
    return FuzzyChoice([True, False])

  @classmethod
  def Integer(cls, attr_name, class_attr):
    return FuzzyInteger(0, 100000)

  @classmethod
  def RelationshipProperty(cls, attr_name, class_attr):
    if class_attr.property.uselist:
      return []
    else:
      columns = tuple(class_attr.property.local_columns)
      # FIXME: ? Doesn't handle multiple local columns, so won't work for
      #   polymorphic links
      if columns[0].nullable:
        # Not a required association, so skip it
        return None
      elif columns[0].primary_key:
        # This is a 'reverse' association, so skip it (primary keys are
        #   not nullable, but the relationship may still be optional)
        return None
      else:
        return FactoryStubMarker(class_attr.property.mapper.class_)

  @classmethod
  def AssociationProxy(cls, attr_name, class_attr):
    return []

  @classmethod
  def property(cls, attr_name, class_attr):
    return None

  @classmethod
  def simple_property(cls, attr_name, class_attr):
    return None

class ModelFactoryMetaClass(FactoryMetaClass):
  def __new__(cls, class_name, bases, attrs, extra_attrs=None):
    """Use model reflection to build up the list of factory attributes.
    The default attributes can be overridden by defining a subclass
    of `ModelFactory` and defining the attribute to be overriden.
    """
    model_class = attrs.pop('MODEL', None)
    if model_class:
      attrs['FACTORY_FOR'] = dict
      attribute_info = AttributeInfo(model_class)
      for attr in attribute_info._create_attrs:
        if hasattr(attr, '__call__'):
          attr_name = attr.attr_name
        else:
          attr_name = attr
        if attr_name not in attrs:
          FactoryAttributeGenerator.generate(attrs, model_class, attr)
    return super(ModelFactoryMetaClass, cls).__new__(
        cls, class_name, bases, attrs)

ModelFactory = ModelFactoryMetaClass(
    'ModelFactory', (BaseFactory,), {
        'ABSTRACT_FACTORY': True,
        'FACTORY_STRATEGY': CREATE_STRATEGY,
        '__doc__': """ModelFactory base with build and create support.

        This class has supports SQLAlchemy ORM.
        """,
    })

def factory_for(model_class):
  """Get the factory for a model by name or by class.
  If there is a factory defined for this model in globals() that factory
  will be used. Otherwise, one will be created and added to globals().
  """
  if isinstance(model_class, (str, unicode)):
    if '.' in model_class:
      import sys
      path = model_class.split('.')
      module_name = '.'.join(path[:-1])
      factory_name = path[-1]
      __import__(module_name)
      model_class = getattr(sys.modules[module_name], factory_name, None)
    else:
      factory_name = model_class
      import ggrc.models
      model_class = ggrc.models.get_model(model_class)
  else:
    factory_name = model_class.__name__
  factory_name = '{0}Factory'.format(factory_name)
  factory = globals().get(factory_name, None)
  if not factory:
    class model_factory(ModelFactory):
      MODEL = model_class
    model_factory.__name__ = factory_name
    globals()[factory_name] = model_factory
    factory = model_factory
  return factory

class PersonFactory(ModelFactory):
  MODEL = models.Person
  email = FuzzyEmail()

# Governance Objects

class ProgramFactory(ModelFactory):
  MODEL = models.Program
  kind = FuzzyChoice(['Directive', 'Company Controls'])
  status = FuzzyChoice(MODEL.VALID_STATES)

class ContractFactory(ModelFactory):
  MODEL = models.Contract
  kind = FuzzyChoice(MODEL.valid_kinds)
  status = FuzzyChoice(MODEL.VALID_STATES)

class PolicyFactory(ModelFactory):
  MODEL = models.Policy
  kind = FuzzyChoice(MODEL.valid_kinds)
  status = FuzzyChoice(MODEL.VALID_STATES)

class RegulationFactory(ModelFactory):
  MODEL = models.Regulation
  kind = FuzzyChoice(MODEL.valid_kinds)
  status = FuzzyChoice(MODEL.VALID_STATES)

class StandardFactory(ModelFactory):
  MODEL = models.Standard
  kind = FuzzyChoice(MODEL.valid_kinds)
  status = FuzzyChoice(MODEL.VALID_STATES)

class SectionFactory(ModelFactory):
  MODEL = models.Section
  # Explicit `directive` factory is necessary, since it's a `nullable`
  # column, but uses @validate to maintain requirement
  directive = FactoryStubMarker(models.Regulation)

class ClauseFactory(ModelFactory):
  MODEL = models.Clause

class ObjectiveFactory(ModelFactory):
  MODEL = models.Objective
  status = FuzzyChoice(MODEL.VALID_STATES)

class ControlFactory(ModelFactory):
  MODEL = models.Control
  status = FuzzyChoice(MODEL.VALID_STATES)

# Business Objects
class DataAssetFactory(ModelFactory):
  MODEL = models.DataAsset
  status = FuzzyChoice(MODEL.VALID_STATES)

class AccessGroupFactory(ModelFactory):
  MODEL = models.AccessGroup
  status = FuzzyChoice(MODEL.VALID_STATES)

class FacilityFactory(ModelFactory):
  MODEL = models.Facility
  status = FuzzyChoice(MODEL.VALID_STATES)

class MarketFactory(ModelFactory):
  MODEL = models.Market
  status = FuzzyChoice(MODEL.VALID_STATES)

class OrgGroupFactory(ModelFactory):
  MODEL = models.OrgGroup
  status = FuzzyChoice(MODEL.VALID_STATES)

class ProductFactory(ModelFactory):
  MODEL = models.Product
  status = FuzzyChoice(MODEL.VALID_STATES)

class ProjectFactory(ModelFactory):
  MODEL = models.Project
  status = FuzzyChoice(MODEL.VALID_STATES)

class SystemFactory(ModelFactory):
  MODEL = models.System
  status = FuzzyChoice(MODEL.VALID_STATES)

class ProcessFactory(ModelFactory):
  MODEL = models.Process
  status = FuzzyChoice(MODEL.VALID_STATES)

# Audit Objects

class AuditFactory(ModelFactory):
  MODEL = models.Audit
  status = FuzzyChoice(MODEL.VALID_STATES)

class RequestFactory(ModelFactory):
  MODEL = models.Request
  status = FuzzyChoice(MODEL.VALID_STATES)
  request_type = FuzzyChoice(MODEL.VALID_TYPES)

class ResponseFactory(ModelFactory):
  MODEL = models.Response
  status = FuzzyChoice(MODEL.VALID_STATES)

class DocumentationResponseFactory(ResponseFactory):
  MODEL = models.DocumentationResponse
  response_type = 'documentation'

class InterviewResponseFactory(ResponseFactory):
  MODEL = models.InterviewResponse
  response_type = 'interview'

class PopulationSampleResponseFactory(ResponseFactory):
  MODEL = models.PopulationSampleResponse
  response_type = 'population sample'

# Category Objects

class ControlCategoryFactory(ModelFactory):
  MODEL = models.ControlCategory
  type = "ControlCategory"

class ControlAssertionFactory(ModelFactory):
  MODEL = models.ControlAssertion
  type = "ControlAssertion"

# Mapping Objects

class ControlControlFactory(ModelFactory):
  MODEL = models.ControlControl
  status = FuzzyChoice(MODEL.VALID_STATES)

class ControlSectionFactory(ModelFactory):
  MODEL = models.ControlSection
  status = FuzzyChoice(MODEL.VALID_STATES)

class DirectiveControlFactory(ModelFactory):
  MODEL = models.DirectiveControl
  status = FuzzyChoice(MODEL.VALID_STATES)

class ObjectControlFactory(ModelFactory):
  MODEL = models.ObjectControl
  status = FuzzyChoice(MODEL.VALID_STATES)
  controllable = FactoryStubMarker(models.Market)

class ObjectDocumentFactory(ModelFactory):
  MODEL = models.ObjectDocument
  status = FuzzyChoice(MODEL.VALID_STATES)
  documentable = FactoryStubMarker(models.Market)

class ObjectOwnerFactory(ModelFactory):
  MODEL = models.ObjectOwner
  status = FuzzyChoice(MODEL.VALID_STATES)
  ownable = FactoryStubMarker(models.Market)

class ObjectPersonFactory(ModelFactory):
  MODEL = models.ObjectPerson
  status = FuzzyChoice(MODEL.VALID_STATES)
  personable = FactoryStubMarker(models.Market)

class ProgramControlFactory(ModelFactory):
  MODEL = models.ProgramControl
  status = FuzzyChoice(MODEL.VALID_STATES)

class ProgramDirectiveFactory(ModelFactory):
  MODEL = models.ProgramDirective
  status = FuzzyChoice(MODEL.VALID_STATES)

class RelationshipFactory(ModelFactory):
  MODEL = models.Relationship
  status = FuzzyChoice(MODEL.VALID_STATES)
  source = FactoryStubMarker(models.Market)
  destination = FactoryStubMarker(models.Process)

# ggrc_basic_permissions model factories
class RoleFactory(ModelFactory):
  MODEL = models.get_model("Role")

class UserRoleFactory(ModelFactory):
  MODEL = models.get_model("UserRole")

class ContextImplicationFactory(ModelFactory):
  MODEL = models.get_model("ContextImplication")

# ggrc_gdrive_integration model factories
class ObjectFileFactory(ModelFactory):
  MODEL = models.get_model("ObjectFile")
  fileable = FactoryStubMarker(models.DocumentationResponse)

class ObjectFolderFactory(ModelFactory):
  MODEL = models.get_model("ObjectFolder")
  folderable = FactoryStubMarker(models.Audit)

class ObjectEventFactory(ModelFactory):
  MODEL = models.get_model("ObjectEvent")
  eventable = FactoryStubMarker(models.Meeting)


text:
using System;

namespace Itinero.Optimization.Tests.Functional.Performance
{
    /// <summary>
    /// Extension methods for the performance info class.
    /// </summary>
    public static class PerformanceInfoConsumerExtensions
    {
        /// <summary>
        /// Tests performance for the given action.
        /// </summary>
        public static void TestPerf(this Action action, string name)
        {
            var info = new PerformanceInfoConsumer(name);
            info.Start();
            action();
            info.Stop(string.Empty);
        }

        /// <summary>
        /// Tests performance for the given action.
        /// </summary>
        public static void TestPerf(this Action action, string name, int count)
        {
            var info = new PerformanceInfoConsumer(name + " x " + count.ToString(), 10000, count);
            info.Start();
            var message = string.Empty;
            while (count > 0)
            {
                action();
                count--;
            }

            info.Stop(message);
        }

        /// <summary>
        /// Tests performance for the given action.
        /// </summary>
        public static void TestPerf(this Func<string> action, string name)
        {
            var info = new PerformanceInfoConsumer(name);
            info.Start();
            var message = action();
            info.Stop(message);
        }

        /// <summary>
        /// Tests performance for the given action.
        /// </summary>
        public static void TestPerf(this Func<string> action, string name, int count)
        {
            var info = new PerformanceInfoConsumer(name + " x " + count.ToString(), 10000);
            info.Start();
            var message = string.Empty;
            while (count > 0)
            {
                message = action();
                count--;
            }

            info.Stop(message);
        }

        /// <summary>
        /// Tests performance for the given function.
        /// </summary>
        public static T TestPerf<T>(this Func<PerformanceTestResult<T>> func, string name)
        {
            var info = new PerformanceInfoConsumer(name);
            info.Start();
            var res = func();
            info.Stop(res.Message);
            return res.Result;
        }

        /// <summary>
        /// Tests performance for the given function.
        /// </summary>
        public static T TestPerf<T>(this Func<PerformanceTestResult<T>> func, string name, int count)
        {
            var info = new PerformanceInfoConsumer(name + " x " + count.ToString(), 10000);
            info.Start();
            PerformanceTestResult<T> res = null;
            while (count > 0)
            {
                res = func();
                count--;
            }

            info.Stop(res.Message);
            return res.Result;
        }

        /// <summary>
        /// Tests performance for the given function.
        /// </summary>
        public static TResult TestPerf<T, TResult>(this Func<T, PerformanceTestResult<TResult>> func, string name, T a)
        {
            var info = new PerformanceInfoConsumer(name);
            info.Start();
            var res = func(a);
            info.Stop(res.Message);
            return res.Result;
        }

        /// <summary>
        /// Tests performance for the given function.
        /// </summary>
        public static TResult TestPerf<T, TResult>(this Func<T, PerformanceTestResult<TResult>> func, string name, T a, int count)
        {
            var info = new PerformanceInfoConsumer(name, count);
            info.Start();
            var res = func(a);
            count--;
            while (count > 0)
            {
                res = func(a);
                count--;
            }
            info.Stop(res.Message);
            return res.Result;
        }

        /// <summary>
        /// Tests performance for the given function.
        /// </summary>
        public static T TestPerf<T>(this Func<T> func, string name)
        {
            var info = new PerformanceInfoConsumer(name);
            info.Start();
            var res = func();
            info.Stop(string.Empty);
            return res;
        }

        /// <summary>
        /// Tests performance for the given function.
        /// </summary>
        public static T TestPerf<T>(this Func<T> func, string name, int count)
        {
            var res = default(T);
            var info = new PerformanceInfoConsumer(name + " x " + count.ToInvariantString(), count);
            info.Start();
            while (count > 0)
            {
                res = func();
                count--;
            }
            info.Stop(string.Empty);
            return res;
        }

        /// <summary>
        /// Tests performance for the given function.
        /// </summary>
        public static TResult TestPerf<T, TResult>(this Func<T, TResult> func, string name, T a)
        {
            var info = new PerformanceInfoConsumer(name);
            info.Start();
            var res = func(a);
            info.Stop(string.Empty);
            return res;
}
    }
}


text:
meteor-twitter-login
====================

Awesome Twitter Login functionality in meteor :) http://kannan-twitter.meteor.com/


text:
//  2016/05/08: Note this is only for iOS (working as how Androd to link jni functions)

#ifndef _forcephone_h_
#define _forcephone_h_

// NOTE: JNI_FUNC_NAME needs to be declared before include "libas_utils.h"
#ifdef DEV_NDK
#define JNI_FUNC_NAME(name) Java_umich_cse_yctung_demoforcephone_JNICallback_ ## name
#else
#define JNI_FUNC_NAME(name) haha_ ## name
#endif

#define haha 5

#include "libas_utils.h"

#ifdef __cplusplus
extern "C" {
#endif
    JNI_FUNC_HEAD void JNI_FUNC_NAME(debugTest)(JNI_FUNC_NO_PARAM);

#ifdef __cplusplus
}
#endif

#endif /* _forcephone_h_ */