text:
package org.apache.polygene.index.rdf;

import java.io.File;
import java.util.Set;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.query.Query;
import org.apache.polygene.api.query.QueryBuilder;
import org.apache.polygene.api.query.QueryExpressions;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.value.ValueBuilder;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.rdf.ContainsAllTest.ExampleEntity;
import org.apache.polygene.index.rdf.ContainsAllTest.ExampleValue;
import org.apache.polygene.index.rdf.ContainsAllTest.ExampleValue2;
import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.EntityTestAssembler;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import static org.apache.polygene.index.rdf.ContainsAllTest.TEST_STRING_1;
import static org.apache.polygene.index.rdf.ContainsAllTest.TEST_STRING_2;
import static org.apache.polygene.index.rdf.ContainsAllTest.TEST_STRING_3;
import static org.apache.polygene.index.rdf.ContainsAllTest.TEST_STRING_4;
import static org.apache.polygene.index.rdf.ContainsAllTest.setOf;

public class ContainsTest extends AbstractPolygeneTest
{
    @Rule
    public TemporaryFolder tmpDir = new TemporaryFolder();

    @Override
    public void assemble( ModuleAssembly module ) throws AssemblyException
    {
        new FileConfigurationAssembler()
            .withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
            .assemble( module );
        ModuleAssembly prefModule = module.layer().module( "PrefModule" );
        prefModule.entities( NativeConfiguration.class ).visibleIn( Visibility.application );
        prefModule.forMixin( NativeConfiguration.class ).declareDefaults()
                  .dataDirectory().set( new File( tmpDir.getRoot(), "rdf-data" ).getAbsolutePath() );
        new EntityTestAssembler().assemble( prefModule );

        module.entities( ExampleEntity.class );
        module.values( ExampleValue.class, ExampleValue2.class );

        EntityTestAssembler testAss = new EntityTestAssembler();
        testAss.assemble( module );

        RdfNativeSesameStoreAssembler rdfAssembler = new RdfNativeSesameStoreAssembler();
        rdfAssembler.assemble( module );
    }

    @Test
    public void simpleContainsSuccessTest() throws Exception
    {
        ExampleEntity result = this.performContainsStringTest(
            setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
            TEST_STRING_3
        );

        Assert.assertTrue( "The entity must have been found", result != null );
    }

    @Test
    public void simpleContainsSuccessFailTest() throws Exception
    {
        ExampleEntity result = this.performContainsStringTest(
            setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
            TEST_STRING_4
        );

        Assert.assertTrue( "The entity must not have been found", result == null );
    }

    @Test( expected = NullPointerException.class )
    public void simpleContainsNullTest() throws Exception
    {
        this.performContainsStringTest(
            setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
            null
        );
    }

    @Test
    public void simpleContainsStringValueSuccessTest() throws Exception
    {
        ExampleEntity result = this.performContainsStringValueTest(
            setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
            TEST_STRING_3
        );

        Assert.assertTrue( "The entity must have been found", result != null );
    }

    @Test
    public void simpleContainsStringValueFailTest() throws Exception
    {
        ExampleEntity result = this.performContainsStringTest(
            setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
            TEST_STRING_4
        );

        Assert.assertTrue( "The entity must not have been found", result == null );
    }

    private ExampleEntity findEntity( String string )
    {
        QueryBuilder<ExampleEntity> builder = this.queryBuilderFactory.newQueryBuilder( ExampleEntity.class );

        builder = builder.where(
            QueryExpressions.contains( QueryExpressions.templateFor( ExampleEntity.class ).strings(), string ) );
        return this.unitOfWorkFactory.currentUnitOfWork().newQuery( builder ).find();
    }

    private ExampleEntity findEntityBasedOnValueString( String valueString )
    {
        ValueBuilder<ExampleValue2> vBuilder = this.valueBuilderFactory.newValueBuilder( ExampleValue2.class );
        vBuilder.prototype().stringProperty().set( valueString );

        ValueBuilder<ExampleValue> vBuilder2 = this.valueBuilderFactory.newValueBuilder( ExampleValue.class );
        vBuilder2.prototype().valueProperty().set( vBuilder.newInstance() );

        return this.createComplexQuery( vBuilder2.newInstance() ).find();
    }

    private Query<ExampleEntity> createComplexQuery( ExampleValue value )
    {
        QueryBuilder<ExampleEntity> builder = this.queryBuilderFactory.newQueryBuilder( ExampleEntity.class );
        builder = builder.where(
            QueryExpressions.contains( QueryExpressions.templateFor( ExampleEntity.class ).complexValue(), value ) );

        return this.unitOfWorkFactory.currentUnitOfWork().newQuery( builder );
    }

    private ExampleEntity performContainsStringTest( Set<String> entityStrings, String queryableString )
        throws Exception
    {
        UnitOfWork creatingUOW = this.unitOfWorkFactory.newUnitOfWork();
        String[] entityStringsArray = new String[ entityStrings.size() ];
        ContainsAllTest.createEntityWithStrings( creatingUOW, this.valueBuilderFactory,
                                                 entityStrings.toArray( entityStringsArray ) );
        creatingUOW.complete();

        UnitOfWork queryingUOW = this.unitOfWorkFactory.newUnitOfWork();
        try
        {
            return this.findEntity( queryableString );
        }
        finally
        {
            queryingUOW.discard();
        }
    }

    private ExampleEntity performContainsStringValueTest( Set<String> entityStrings, String queryableString )
        throws Exception
    {
        UnitOfWork creatingUOW = this.unitOfWorkFactory.newUnitOfWork();
        String[] entityStringsArray = new String[ entityStrings.size() ];
        ContainsAllTest.createEntityWithComplexValues( creatingUOW, this.valueBuilderFactory,
                                                       entityStrings.toArray( entityStringsArray ) );
        creatingUOW.complete();

        UnitOfWork queryingUOW = this.unitOfWorkFactory.newUnitOfWork();
        try
        {
            return this.findEntityBasedOnValueString( queryableString );
        }
        finally
        {
            queryingUOW.discard();
        }
    }
}


text:
import os
import sys
import argparse
import solid
import logging
import glob
from . import utils
from . import rockit

logger = logging.getLogger(__name__)
DEFAULT_TEMPLATE_DIR = os.path.join(os.path.split(__file__)[0], "templates")

def get_templates(template_dir):
    Templates = os.listdir(template_dir)

def configure_logger(args):
    root_logger = logging.getLogger("rockit")
    if args.debug:
        root_logger.setLevel(logging.DEBUG)
    else:
        root_logger.setLevel(logging.INFO)
    formatter = logging.Formatter('[%(asctime)s:%(name)s:%(levelname)s]: %(message)s')
    ch = logging.StreamHandler()
    ch.setFormatter(formatter)
    root_logger.addHandler(ch)

def load_rocket_json(args):
    conf = utils.load_json(args.input_json)
    return rockit.Rockit(**conf)

def save_rocket(args, rocket):
    if not args.output_dir:
        args.output_dir = rocket.name
    if not os.path.exists(args.output_dir):
        os.mkdir(args.output_dir)
    json_path = os.path.join(args.output_dir, "%s.json" % rocket.name)
    utils.save_json(rocket, json_path)
    build = rocket.get_build()
    for part_name in build:
        if not build[part_name]:
            continue
        scad_path = os.path.join(args.output_dir, "%s_%s.scad" % (rocket.name, part_name))
        part = build[part_name]
        utils.save_scad(part, scad_path)
        if args.export_stl:
            stl_path = os.path.join(args.output_dir, "%s_%s.stl" % (rocket.name, part_name))
            utils.save_stl(args.openscad_exe, scad_path, stl_path)
        if args.export_png:
            png_path = os.path.join(args.output_dir, "%s_%s.png" % (rocket.name, part_name))
            utils.save_png(args.openscad_exe, scad_path, png_path)
        if args.export_dxf:
            dxf_path = os.path.join(args.output_dir, "%s_%s.dxf" % (rocket.name, part_name))
            utils.save_dxf(args.openscad_exe, scad_path, dxf_path)

def check_scad_exe(args):
    return os.path.isfile(args.openscad_exe) and os.access(args.openscad_exe, os.X_OK)

def find_open_scad(args):
    if check_scad_exe(args):
        return True
    if sys.platform == "darwin":
        hint = "/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD"
        args.openscad_exe = hint
        if check_scad_exe(args):
            return True
    args.openscad_exe = utils.which("openscad")
    if check_scad_exe(args):
        return True
    return False

def get_templates(template_dir=None):
    template_dir = (template_dir or DEFAULT_TEMPLATE_DIR)
    return {os.path.splitext(os.path.split(fn)[-1])[0]: fn for fn in glob.glob(os.path.join(template_dir, "*.json"))}

def get_cli():
    defaults = {
        "export_stl": False,
        "openscad_exe": '',
        "debug": False,
        "template_dir": DEFAULT_TEMPLATE_DIR,
        "export_png": False,
        "export_dxf": False,
    }

    parser = argparse.ArgumentParser(description='model rocket generator')
    parser.add_argument('-i', '--input_json', help='rocket configuration file in JSON format')
    parser.add_argument('-t', '--template', help='load builtin template (%s)' % str.join(', ', get_templates().keys()))
    parser.add_argument('-T', '--template_dir', help='template directory (default=%s)' % DEFAULT_TEMPLATE_DIR)
    parser.add_argument('-o', '--output_dir', help='output directory')
    parser.add_argument('-S', '--openscad_exe', help='path to OpenSCAD')
    parser.add_argument('-s', '--export_stl', action="store_true", help='export .STL via OpenSCAD')
    parser.add_argument('-x', '--export_dxf', action="store_true", help='export .DXF of object')
    parser.add_argument('-p', '--export_png', action="store_true", help='export image of object')
    parser.add_argument('-d', '--debug', action="store_true", help='enable debugging log')

    parser.set_defaults(**defaults)

    args = parser.parse_args()
    # Templates
    if args.template:
        jsfn = args.template + '.json'
        jsfn = utils.find(jsfn, args.template_dir)
        templates = get_templates(args.template_dir)
        if args.template not in templates:
            msg = "could not find template: %s, options are: %s" % (args.template, str.join(',', templates.keys()))
            raise RuntimeError, msg
        args.input_json = templates[args.template]
    # OpenSCAD
    if (args.export_png or args.export_stl):
        if not find_open_scad(args):
            raise RuntimeError, "Can't find OpenSCAD, is it installed?"
    return args

def main():
    args = get_cli()
    configure_logger(args)
    rocket = load_rocket_json(args)
    save_rocket(args, rocket)

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
This is the source code for [pooatcwru.com](https://pooatcwru.com). I originally wrote it around August 2014. In January 2016 I cleaned it up, rewrote some portions, and released it on GitHub. In December 2018 I rewrote it again in Ruby on Rails.

## Installation
* Clone the repo.
* Install necessary libraries (like `gem install bundler`).
* Run `bundle install`.
* Configure the user and databases in `config/database.yml`.
* Run `rails db:migrate`.
* Run `rails db:seed` to load building and floor info.
* Run `rails server`.
* Access the website at `localhost:3000`.

## References
* Buildings / Restrooms
	* https://webapps.case.edu/map/
	* https://case.edu/library/spaces/interactive-map
	* https://case.edu/lgbt/resources/transgender-resources/bathroom-inventory
* Central Authentication Service (Single Sign-On)
	* http://hacsoc.org/wiki/technical/cas.html
	* https://web.archive.org/web/20121126051658/http://wiki.case.edu/Central_Authentication_Service


text:
@implementation UAEC2NetworkInterface

@synthesize networkInterfaceID=_networkInterfaceID, subnetID=_subnetID, vpcID=_vpcID, availabilityZone=_availabilityZone, descriptionValue=_descriptionValue, ownerID=_ownerID, requesterID=_requesterID, requesterManaged=_requesterManaged, state=_state, macAddress=_macAddress, privateIPAddress=_privateIPAddress, privateDNSName=_privateDNSName, sourceDestCheck=_sourceDestCheck, groups=_groups, attachment=_attachment, association=_association, tags=_tags, privateIPAddresses=_privateIPAddresses;

- (id)init
{
	if (self = [super init])
	{

		[self UA_addAtIndexAdditionalAccessorForSelector:@selector(groupAtIndex:) propertyName:@"groups"];
		[self UA_addAtIndexAdditionalAccessorForSelector:@selector(tagAtIndex:) propertyName:@"tags"];
		[self UA_addAtIndexAdditionalAccessorForSelector:@selector(privateIPAddressAtIndex:) propertyName:@"privateIPAddresses"];
		[self UA_addAddObjectAdditionalAccessorForSelector:@selector(addGroup:) propertyName:@"groups"];
		[self UA_addAddObjectAdditionalAccessorForSelector:@selector(addTag:) propertyName:@"tags"];
		[self UA_addAddObjectAdditionalAccessorForSelector:@selector(addPrivateIPAddress:) propertyName:@"privateIPAddresses"];
	}
	return self;
}

+ (NSString *)XPathPrefix
{
    return @"./";
}

+ (NSDictionary *)XMLKeyPathsByPropertyKey
{
    // Start with super's key paths (if there are any)
    NSMutableDictionary *keyPaths = [[UAEC2Model XMLKeyPathsByPropertyKey] mutableCopy];

    [keyPaths addEntriesFromDictionary:
    @{
        @"networkInterfaceID": @"ec2:networkInterfaceId",
        @"subnetID": @"ec2:subnetId",
        @"vpcID": @"ec2:vpcId",
        @"availabilityZone": @"ec2:availabilityZone",
        @"descriptionValue": @"ec2:description",
        @"ownerID": @"ec2:ownerId",
        @"requesterID": @"ec2:requesterId",
        @"requesterManaged": @"ec2:requesterManaged",
        @"state": @"ec2:status",
        @"macAddress": @"ec2:macAddress",
        @"privateIPAddress": @"ec2:privateIpAddress",
        @"privateDNSName": @"ec2:privateDnsName",
        @"sourceDestCheck": @"ec2:sourceDestCheck",
        @"groups": @"ec2:groupSet/ec2:item",
        @"attachment": @"ec2:attachment",
        @"association": @"ec2:association",
        @"tags": @"ec2:tagSet/ec2:item",
        @"privateIPAddresses": @"ec2:privateIpAddressesSet/ec2:item"
    }];
    return [keyPaths copy];
}

+ (NSValueTransformer *)stateQueryStringTransformer
{
    return [NSValueTransformer UA_ENUMTransformerWithValues:@[ @(UAEC2NetworkInterfaceStateAvailable), @(UAEC2NetworkInterfaceStateAttaching), @(UAEC2NetworkInterfaceStateInUse), @(UAEC2NetworkInterfaceStateDetaching) ]
                                               stringValues:@[ @"available", @"attaching", @"in-use", @"detaching" ]
                                               unknownValue:@(UAEC2NetworkInterfaceStateUnknown)];
}

+ (NSValueTransformer *)groupsQueryStringTransformer
{
	return [NSValueTransformer UAMTL_QueryStringArrayTransformerWithModelClass:[UAEC2GroupIdentifier class]];
}

+ (NSValueTransformer *)attachmentQueryStringTransformer
{
	return [NSValueTransformer UAMTL_QueryStringDictionaryTransformerWithModelClass:[UAEC2NetworkInterfaceAttachment class]];
}

+ (NSValueTransformer *)associationQueryStringTransformer
{
	return [NSValueTransformer UAMTL_QueryStringDictionaryTransformerWithModelClass:[UAEC2NetworkInterfaceAssociation class]];
}

+ (NSValueTransformer *)tagsQueryStringTransformer
{
	return [NSValueTransformer UAMTL_QueryStringArrayTransformerWithModelClass:[UAEC2Tag class]];
}

+ (NSValueTransformer *)privateIPAddressesQueryStringTransformer
{
	return [NSValueTransformer UAMTL_QueryStringArrayTransformerWithModelClass:[UAEC2PrivateIPAddress class]];
}

+ (NSValueTransformer *)requesterManagedXMLTransformer
{
    return [UAMTLValueTransformer UA_XMLTransformerForBooleanString];
}

+ (NSValueTransformer *)stateXMLTransformer
{
    return [NSValueTransformer UA_ENUMTransformerWithValues:@[ @(UAEC2NetworkInterfaceStateAvailable), @(UAEC2NetworkInterfaceStateAttaching), @(UAEC2NetworkInterfaceStateInUse), @(UAEC2NetworkInterfaceStateDetaching) ]
                                               stringValues:@[ @"available", @"attaching", @"in-use", @"detaching" ]
                                               unknownValue:@(UAEC2NetworkInterfaceStateUnknown)];
}

+ (NSValueTransformer *)sourceDestCheckXMLTransformer
{
    return [UAMTLValueTransformer UA_XMLTransformerForBooleanString];
}

+ (NSValueTransformer *)groupsXMLTransformer
{
  return [NSValueTransformer UAMTL_XMLArrayTransformerWithModelClass:[UAEC2GroupIdentifier class]];
}

+ (NSValueTransformer *)attachmentXMLTransformer
{
  return [NSValueTransformer UAMTL_XMLTransformerWithModelClass:[UAEC2NetworkInterfaceAttachment class]];
}

+ (NSValueTransformer *)associationXMLTransformer
{
  return [NSValueTransformer UAMTL_XMLTransformerWithModelClass:[UAEC2NetworkInterfaceAssociation class]];
}

+ (NSValueTransformer *)tagsXMLTransformer
{
  return [NSValueTransformer UAMTL_XMLArrayTransformerWithModelClass:[UAEC2Tag class]];
}

+ (NSValueTransformer *)privateIPAddressesXMLTransformer
{
  return [NSValueTransformer UAMTL_XMLArrayTransformerWithModelClass:[UAEC2PrivateIPAddress class]];
}

@end

#pragma clang diagnostic pop


text:
package de.gammadata.microservices.addressrs.health.boundary;

import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 *
 * @author gfr
 */
@RunWith(Arquillian.class)
public class HealthResourceArquillianIT {

  public HealthResourceArquillianIT() {
  }

  @Deployment
  public static JavaArchive createDeployment() {
    JavaArchive jar = ShrinkWrap.create(JavaArchive.class)
            .addClass(HealthResource.class)
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
    System.out.println(jar.toString(true));
    return jar;
  }

  @Inject
  HealthResource instance;

  @BeforeClass
  public static void setUpClass() {

  }

  @AfterClass
  public static void tearDownClass() {
  }

  @Before
  public void setUp() {
  }

  @After
  public void tearDown() {
  }

  /**
   * Test of getPing method, of class HealthResource.
   */
  @Test
  public void testGetPing() {
    System.out.println("getPing");
    String expResult = "ping";
    String result = instance.getPing();
    assertEquals(expResult, result);
  }

}


text:
$(function() { $("body").on("input propertychange", ".floating-label-form-group", function(o) { $(this).toggleClass("floating-label-form-group-with-value", !!$(o.target).val()) }).on("focus", ".floating-label-form-group", function() { $(this).addClass("floating-label-form-group-with-focus") }).on("blur", ".floating-label-form-group", function() { $(this).removeClass("floating-label-form-group-with-focus") }) }), jQuery(document).ready(function(o) {
    var s = 1170;
    if (o(window).width() > s) {
        var i = o(".navbar-custom").height();
        o(window).on("scroll", { previousTop: 0 }, function() {
            var s = o(window).scrollTop();
            s < this.previousTop ? s > 0 && o(".navbar-custom").hasClass("is-fixed") ? o(".navbar-custom").addClass("is-visible") : o(".navbar-custom").removeClass("is-visible is-fixed") : s > this.previousTop && (o(".navbar-custom").removeClass("is-visible"), s > i && !o(".navbar-custom").hasClass("is-fixed") && o(".navbar-custom").addClass("is-fixed")), this.previousTop = s
        })
    }
});


text:
package org.xwalk.embedded.api.sample;

import org.xwalk.core.XWalkActivity;
import org.xwalk.core.XWalkNavigationHistory;
import org.xwalk.core.XWalkNavigationItem;
import org.xwalk.core.XWalkView;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class XWalkNavigationActivity extends XWalkActivity {
    private XWalkView mXWalkView;
    private ImageButton mNextButton;
    private ImageButton mPrevButton;

    String url, originalUrl, title;
    TextView text1, text2, text3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.navigation_layout);
        mXWalkView = (XWalkView) findViewById(R.id.xwalkview);
    }

    private void showNavigationItemInfo(XWalkNavigationItem navigationItem){
        url = navigationItem.getUrl();
        originalUrl = navigationItem.getOriginalUrl();
        title = navigationItem.getTitle();

        text1.setText(title);
        text2.setText(url);
        text3.setText(originalUrl);
    }

    @Override
    protected void onXWalkReady() {
        StringBuffer mess = new StringBuffer();
        mess.append("Test Purpose: \n\n")
        .append("Verifies XWalkView can forward and backward history.\n\n")
        .append("Test  Step:\n\n")
        .append("1. Search some in baidu page, and click some some searched links.\n")
        .append("2. Click the go backward button and then cilck go forward button.\n\n")
        .append("Expected Result:\n\n")
        .append("Test passes if app history can go backward and go forward.");
        new  AlertDialog.Builder(this)
        .setTitle("Info" )
        .setMessage(mess.toString())
        .setPositiveButton("confirm" ,  null )
        .show();

        mPrevButton = (ImageButton) findViewById(R.id.prev);
        mNextButton = (ImageButton) findViewById(R.id.next);

        text1 = (TextView) super.findViewById(R.id.text1);
        text2 = (TextView) super.findViewById(R.id.text2);
        text3 = (TextView) super.findViewById(R.id.text3);

        mPrevButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Go backward
                if (mXWalkView != null &&
                        mXWalkView.getNavigationHistory().canGoBack()) {
                    mXWalkView.getNavigationHistory().navigate(
                            XWalkNavigationHistory.Direction.BACKWARD, 1);
                }
                XWalkNavigationItem navigationItem = mXWalkView.getNavigationHistory().getCurrentItem();
                showNavigationItemInfo(navigationItem);
            }
        });

        mNextButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Go forward
                if (mXWalkView != null &&
                        mXWalkView.getNavigationHistory().canGoForward()) {
                    mXWalkView.getNavigationHistory().navigate(
                            XWalkNavigationHistory.Direction.FORWARD, 1);
                }
                XWalkNavigationItem navigationItem = mXWalkView.getNavigationHistory().getCurrentItem();
                showNavigationItemInfo(navigationItem);
            }
        });

        mXWalkView.load("http://www.baidu.com/", null);
    }
}


text:
ActiveRecord::Schema.define(version: 20130821235151) do

  create_table "attendees", force: true do |t|
    t.string   "name"
    t.string   "twitter_handle"
    t.text     "bio"
    t.text     "address"
    t.string   "picture"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.float    "latitude"
    t.float    "longitude"
  end

end


text:
require "spec_helper"

describe TimestampAPI::Task do
  it "inherits from Model" do
    expect(TimestampAPI::Task.superclass).to be TimestampAPI::Model
  end

  it "has `/projects` as api_path" do
    expect(TimestampAPI::Task.api_path).to eq "/tasks"
  end

  describe ".for_project_id" do
    let(:project) { double(:project, id: "p1") }

    subject { TimestampAPI::Task.for_project_id(project.id) }

    it "calls .all with proper query parameters" do
      expect(TimestampAPI::Task).to receive(:all).with(project_id: project.id)
      subject
    end
  end
end


text:
package com.xmpp.library.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.xmpp.library.model.ModelChat;
import com.xmpp.library.utils.XmppConstants;

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

/**
 * Created by ln- on 11/8/16.
 */
public class DBChat implements DBOperation {

    private static final String TAG = "DBChat";

    private SQLiteDatabase database;

    public DBChat(Context context) {
        DatabaseHelper databasehelper = DatabaseHelper.getInstance(context);
        database = databasehelper.getWritableDatabase();
    }

    @Override
    public long insert(Object object) {
        ModelChat modelChat = (ModelChat) object;
        Log.d(TAG, "insert() called with: object = [" + modelChat + "]");

        try {
            ContentValues values = new ContentValues();
            values.put(XmppConstants.CHAT.COL_CONVERSATION_ID, modelChat.getConversationId());
            values.put(XmppConstants.CHAT.COL_CONVERSATION_TYPE, modelChat.getConversationType());
            values.put(XmppConstants.CHAT.COL_RECEIPT_ID, modelChat.getReceiptId());
            values.put(XmppConstants.CHAT.COL_TO, modelChat.getToUser());
            values.put(XmppConstants.CHAT.COL_FROM, modelChat.getFromUser());
            values.put(XmppConstants.CHAT.COL_TYPE, modelChat.getType());
            values.put(XmppConstants.CHAT.COL_VALUE, modelChat.getValue());
            values.put(XmppConstants.CHAT.STORE_ID, modelChat.getStoreID());
            values.put(XmppConstants.CHAT.COL_STATUS, modelChat.getStatus());
            values.put(XmppConstants.CHAT.COL_TIMESTAMP, modelChat.getTime());
            values.put(XmppConstants.CHAT.COL_THUMB, modelChat.getThumb());
            values.put(XmppConstants.CHAT.COL_DURATION, modelChat.getDuration());
            values.put(XmppConstants.CHAT.COL_USER_NAME, modelChat.getUserName());
            values.put(XmppConstants.CHAT.COL_IS_FROM, modelChat.getIsFromUser());
            values.put(XmppConstants.CHAT.COL_LATLNG, modelChat.getLatlong() == null ? "" : modelChat.getLatlong());
            Log.e("insert ModelChat", "values: " + values);
            return database.insert(XmppConstants.CHAT.TABLE_CHAT, null, values);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int update(Object object) {
        return 0;
    }

    @Override
    public int delete(Object object) {
        return 0;
    }

    @Override
    public List getAll() {
        return null;
    }

    public ArrayList<ModelChat> getByConversationId(String currentUserId, String oppositeUserId, String CONVERSATION_TYPE) {
        ArrayList<ModelChat> modelChatArrayList = new ArrayList<>();

        String query = "Select * from " + XmppConstants.CHAT.TABLE_CHAT +
                " where " + XmppConstants.CHAT.COL_CONVERSATION_ID + "='" + XmppConstants.getConversionId(currentUserId, oppositeUserId) +
                "' OR " + XmppConstants.CHAT.COL_CONVERSATION_ID + "='" + XmppConstants.getConversionId(oppositeUserId, currentUserId) + "'" +
                " AND " + XmppConstants.CHAT.COL_CONVERSATION_TYPE + "='" + CONVERSATION_TYPE + "'" +
                "";

        Log.e("Query", query);

        Cursor cursor = database.rawQuery(query, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    ModelChat modelChat = new ModelChat();
                    modelChat.setId(cursor.getInt(cursor.getColumnIndex(XmppConstants.CHAT.COL_ID)));
                    modelChat.setConversationId(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_CONVERSATION_ID)));
                    modelChat.setConversationType(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_CONVERSATION_TYPE)));
                    modelChat.setReceiptId(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_RECEIPT_ID)));
                    modelChat.setToUser(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_TO)));
                    modelChat.setFromUser(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_FROM)));
                    modelChat.setValue(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_VALUE)));
                    modelChat.setStoreID(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.STORE_ID)));
                    modelChat.setType(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_TYPE)));
                    modelChat.setStatus(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_STATUS)));
                    modelChat.setThumb(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_THUMB)));
                    modelChat.setDuration(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_DURATION)));
                    modelChat.setUserName(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_USER_NAME)));
                    modelChat.setLatlong(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_LATLNG)));
                    modelChat.setTime(Long.parseLong(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_TIMESTAMP))));
                    //modelChat.setSender(modelChat.getToUser().equals(currentUserId));
                    modelChat.setSender(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_IS_FROM)).equals("1"));
                    modelChatArrayList.add(modelChat);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return modelChatArrayList;
    }

    public ArrayList<ModelChat> getGroupHistory(String currentUserId, String groupID, String CONVERSATION_TYPE) {
        ArrayList<ModelChat> modelChatArrayList = new ArrayList<>();

        String query = "Select * from " + XmppConstants.CHAT.TABLE_GROUP_CHAT +
                " where " + XmppConstants.CHAT.COL_CONVERSATION_ID + "='" + XmppConstants.getGroupID(groupID) +
                "'";
        /*String query = "Select * from " + XmppConstants.CHAT.TABLE_GROUP_CHAT +
                " where " + XmppConstants.CHAT.COL_CONVERSATION_ID + "='" + XmppConstants.getConversionId(currentUserId, groupID) +
                "' OR " + XmppConstants.CHAT.COL_CONVERSATION_ID + "='" + XmppConstants.getConversionId(groupID, currentUserId) + "'" +
                " AND " + XmppConstants.CHAT.COL_CONVERSATION_TYPE + "='" + CONVERSATION_TYPE + "'" +
                "";*/

        Log.e("Query", query);

        Cursor cursor = database.rawQuery(query, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    ModelChat modelChat = new ModelChat();
                    modelChat.setId(cursor.getInt(cursor.getColumnIndex(XmppConstants.CHAT.COL_ID)));
                    modelChat.setConversationId(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_CONVERSATION_ID)));
                    modelChat.setConversationType(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_CONVERSATION_TYPE)));
                    modelChat.setReceiptId(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_RECEIPT_ID)));
                    modelChat.setToUser(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_TO)));
                    modelChat.setFromUser(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_FROM)));
                    modelChat.setValue(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_VALUE)));
                    modelChat.setStoreID(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.STORE_ID)));
                    modelChat.setType(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_TYPE)));
                    modelChat.setStatus(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_STATUS)));
                    modelChat.setThumb(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_THUMB)));
                    modelChat.setDuration(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_DURATION)));
                    modelChat.setUserName(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_USER_NAME)));
                    modelChat.setLatlong(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_LATLNG)));
                    modelChat.setTime(Long.parseLong(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_TIMESTAMP))));
                    modelChat.setSender(cursor.getString(cursor.getColumnIndex(XmppConstants.CHAT.COL_IS_FROM)).equals("1"));
                    //modelChat.setSender(modelChat.getToUser().equals(currentUserId));
                    modelChatArrayList.add(modelChat);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return modelChatArrayList;
    }

    @Override
    public void deleteAll() {

    }

    @Override
    public ContentValues getContentValues(Object object) {
        return null;
    }

    public void updateReceiptStatus(String receiptId, String status) {

        ContentValues values = new ContentValues();
        values.put(XmppConstants.CHAT.COL_STATUS, status);

        // updating row
        database.update(XmppConstants.CHAT.TABLE_CHAT, values, XmppConstants.CHAT.COL_RECEIPT_ID + " = ?",
                new String[]{receiptId});

    }

    public long insertGroupData(Object object) {
        ModelChat modelChat = (ModelChat) object;
        Log.d(TAG, "insert() called with: object = [" + modelChat + "]");

        try {
            ContentValues values = new ContentValues();
            values.put(XmppConstants.CHAT.COL_CONVERSATION_ID, modelChat.getConversationId());
            values.put(XmppConstants.CHAT.COL_CONVERSATION_TYPE, modelChat.getConversationType());
            values.put(XmppConstants.CHAT.COL_RECEIPT_ID, modelChat.getReceiptId());
            values.put(XmppConstants.CHAT.COL_TO, modelChat.getToUser());
            values.put(XmppConstants.CHAT.COL_FROM, modelChat.getFromUser());
            values.put(XmppConstants.CHAT.COL_TYPE, modelChat.getType());
            values.put(XmppConstants.CHAT.COL_VALUE, modelChat.getValue());
            values.put(XmppConstants.CHAT.STORE_ID, modelChat.getStoreID());
            values.put(XmppConstants.CHAT.COL_STATUS, modelChat.getStatus());
            values.put(XmppConstants.CHAT.COL_TIMESTAMP, modelChat.getTime());
            values.put(XmppConstants.CHAT.COL_THUMB, modelChat.getThumb());
            values.put(XmppConstants.CHAT.COL_DURATION, modelChat.getDuration());
            values.put(XmppConstants.CHAT.COL_USER_NAME, modelChat.getUserName());
            values.put(XmppConstants.CHAT.COL_IS_FROM, modelChat.getIsFromUser());
            values.put(XmppConstants.CHAT.COL_LATLNG, modelChat.getLatlong() == null ? "" : modelChat.getLatlong());
            Log.e("insert ModelChat", "values: " + values);
            return database.insert(XmppConstants.CHAT.TABLE_GROUP_CHAT, null, values);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public void updateUserName(ModelChat modelChat) {
        ContentValues values = new ContentValues();
        values.put(XmppConstants.CHAT.COL_USER_NAME, modelChat.getUserName());

        // updating row for user's username
        database.update(XmppConstants.CHAT.TABLE_CHAT, values, XmppConstants.CHAT.COL_FROM + " = ?",
                new String[]{modelChat.getFromUser()});
    }
}


text:
from nova import context as nova_context
from nova.db import api as db_api
from nova.objects import virtual_interface
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.functional import fixtures as func_fixtures
from nova.tests.functional import integrated_helpers

class FillVirtualInterfaceListMigration(
        test.TestCase, integrated_helpers.InstanceHelperMixin):
    """Regression test for a bug 1825034 introduced in Stein.

    The fill_virtual_interface_list online data migration creates a mostly
    empty marker instance record and immediately (soft) deletes it just to
    satisfy a foreign key constraint with the virtual_interfaces table.

    The problem is since the fake instance marker record is mostly empty,
    it can fail to load fields in the API when listing deleted servers.
    """

    def setUp(self):
        super(FillVirtualInterfaceListMigration, self).setUp()
        api_fixture = self.useFixture(nova_fixtures.OSAPIFixture(
            api_version='v2.1'))
        self.api = api_fixture.admin_api
        self.useFixture(nova_fixtures.NeutronFixture(self))
        self.useFixture(nova_fixtures.GlanceFixture(self))
        self.useFixture(func_fixtures.PlacementFixture())
        self.start_service('conductor')
        self.start_service('scheduler')
        self.start_service('compute')

    def test_fill_vifs_migration(self):
        # Create a test server.
        self._create_server(
            flavor_id=1,
            networks=[{
                'uuid': nova_fixtures.NeutronFixture.network_1['id'],
            }],
        )
        # Run the online data migration which will create a (soft-deleted)
        # marker record.
        ctxt = nova_context.get_admin_context()
        virtual_interface.fill_virtual_interface_list(ctxt, max_count=50)
        # Now archive the deleted instance record.
        # The following (archive stuff) is used to prove that the migration
        # created a "fake instance". It is not necessary to trigger the bug.
        table_to_rows_archived, deleted_instance_uuids, total_rows_archived = (
            db_api.archive_deleted_rows(max_rows=1000))
        self.assertIn('instances', table_to_rows_archived)
        self.assertEqual(1, table_to_rows_archived['instances'])
        self.assertEqual(1, len(deleted_instance_uuids))
        self.assertEqual(virtual_interface.FAKE_UUID,
                         deleted_instance_uuids[0])
        # Since the above (archive stuff) removed the fake instance, do the
        # migration again to recreate it so we can exercise the code path.
        virtual_interface.fill_virtual_interface_list(ctxt, max_count=50)
        # Now list deleted servers. The fake marker instance should be excluded
        # from the API results.
        for detail in (True, False):
            servers = self.api.get_servers(detail=detail,
                                           search_opts={'all_tenants': 1,
                                                        'deleted': 1})
            self.assertEqual(0, len(servers))


text:
from sqlalchemy import (Boolean,
                        Column,
                        DateTime,
                        Enum,
                        ForeignKey,
                        Integer,
                        String,
                        UniqueConstraint)
from sqlalchemy.orm import relationship

from model import Base
from helper.functions import random_string

class Site(Base):
    ''' Data model for a profile. '''

    __tablename__ = 'site'
    __table_args__ = (
        UniqueConstraint('url', name='site_url'),
    )

    MATCH_TYPES = {
        'css': 'CSS Selector',
        'text': 'Text On Page',
        'xpath': 'XPath Query',
    }

    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)
    url = Column(String(255), nullable=False)
    category = Column(String(255), nullable=False)
    status_code = Column(Integer, nullable=True)
    match_type = Column(Enum(*tuple(MATCH_TYPES.keys()), name='match_type'))
    match_expr = Column(String(255), nullable=True)
    test_username_pos = Column(String(255), nullable=False)
    test_username_neg = Column(String(255), nullable=False)
    test_result_pos_id = Column(Integer,
                                ForeignKey('result.id',
                                           name='fk_pos_result'),
                                nullable=True)
    test_result_pos = relationship('Result',
                                   lazy='joined',
                                   backref='site_pos_result',
                                   foreign_keys='Site.test_result_pos_id',
                                   uselist=False,
                                   cascade='all')
    test_result_neg_id = Column(Integer,
                                ForeignKey('result.id',
                                           name='fk_neg_result'),
                                nullable=True)
    test_result_neg = relationship('Result',
                                   lazy='joined',
                                   backref='site_neg_result',
                                   foreign_keys='Site.test_result_neg_id',
                                   uselist=False,
                                   cascade='all')
    tested_at = Column(DateTime, nullable=True)
    valid = Column(Boolean, nullable=False, default=False)

    def __init__(self, name, url, category, test_username_pos,
                 status_code=None, match_type=None, match_expr=None,
                 test_username_neg=None):
        ''' Constructor. '''

        self.name = name
        self.url = url
        self.category = category
        self.status_code = status_code
        self.match_type = match_type or 'text'
        self.match_expr = match_expr
        self.test_username_pos = test_username_pos

        if test_username_neg is None:
            self.test_username_neg = random_string(16)
        else:
            self.test_username_neg = test_username_neg

    def as_dict(self):
        ''' Return dictionary representation of this site. '''

        # Preformat..
        if self.tested_at:
            tested_at = self.tested_at.isoformat()
        else:
            tested_at = None

        if self.test_result_pos:
            test_result_pos = self.test_result_pos.as_dict()
        else:
            test_result_pos = None

        if self.test_result_neg:
            test_result_neg = self.test_result_neg.as_dict()
        else:
            test_result_neg = None

        return {
            'id': self.id,
            'name': self.name,
            'url': self.url,
            'category': self.category,
            'status_code': self.status_code,
            'match_type': self.match_type,
            'match_type_description': self.MATCH_TYPES[self.match_type],
            'match_expr': self.match_expr,
            'test_username_pos': self.test_username_pos,
            'test_username_pos_url': self.get_url(self.test_username_pos),
            'test_username_neg': self.test_username_neg,
            'test_username_neg_url': self.get_url(self.test_username_neg),
            'test_result_pos': test_result_pos,
            'test_result_neg': test_result_neg,
            'tested_at': tested_at,
            'valid': self.valid,
        }

    def get_url(self, username):
        ''' Interpolate a username into this site's URL. '''
        return self.url % username


text:
/**
 *
 * @title 顶部border
 * @description `tabBarStyle`参数设置不同的tabBar样式,取值可以是'primary'、'simple'或'upborder'。
 *
 */

import React, { Component } from 'react';
import Tabs from '../../src';

const {TabPane} = Tabs;

class Demo5 extends Component {
    render() {

        return (
            <div className="Demo5">
                <Tabs
                    className="Demo5-tabs"
                    defaultActiveKey="1"
                    tabBarStyle="upborder"
                >
                    <TabPane tab='Tab 1' key="1">Content of Tab Pane 1</TabPane>
                    <TabPane tab='Tab 2' key="2">Content of Tab Pane 2</TabPane>
                    <TabPane tab='Tab 3' key="3">Content of Tab Pane 3</TabPane>
                    <TabPane tab='Tab 4' key="4">Content of Tab Pane 4</TabPane>
                    <TabPane tab='Tab 5' key="5">Content of Tab Pane 5</TabPane>
                </Tabs>
            </div>
        )
    }
}

export default Demo5;


text:
<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use backend\components\Helper;
use yii\helpers\Url;

class InsuranceController extends BaseController
{
	public $layout = "myloyout";
	public $enableCsrfValidation = false;

	public function actionIndex()
	{
		$sql = "SELECT count(*) count FROM `zh_insurance` ";
		$count = Yii::$app->db->createCommand($sql)->queryOne();

		$sql = "SELECT insurance_id,name,price,status  FROM `zh_insurance` LIMIT 10 ";
		$data = Yii::$app->db->createCommand($sql)->queryAll();
		// var_dump($data);exit;
		return $this->render('index',['data'=>$data,'count'=>$count['count'],'pag'=>'1']);
	}
	public function actionGetinsurancepage(){
		$pag = isset($_GET['pag']) ? $_GET['pag'] == 1 ? 0 : ($_GET['pag'] - 1) * 10 : 0;

		$sql = "SELECT insurance_id,name,price,status  FROM `zh_insurance` LIMIT $pag,10 ";
		$result = Yii::$app->db->createCommand($sql)->queryAll();

        if($result) {
            echo json_encode($result);
        } else {
            echo 0;
        }

	}

	public function actionDelete(){
		$db = Yii::$app->db;

		//单项删除
		if(isset($_GET['id'])) {
			$id = isset($_GET['id']) ? $_GET['id'] : '' ;

			$commen = $db->beginTransaction();
			try{
				$sql = " DELETE FROM `zh_insurance` WHERE insurance_id= $id ";

				$db->createCommand($sql)->execute();

				$commen->commit();
				Helper::show_message('删除成功', Url::toRoute(['index']));
			}catch(Exception $e){
				$commen->rollBack();
				Helper::show_message('删除失败','#');
			}

			exit;
		}
		//多项删除
		if(isset($_POST['ids'])) {

			$ids = implode('\',\'', $_POST['ids']);

			$commen = $db->beginTransaction();
			try{
				$sql = "DELETE FROM `zh_insurance` WHERE insurance_id in ('$ids')";

				$db->createCommand($sql)->execute();
				$commen->commit();
				Helper::show_message('删除成功', Url::toRoute(['index']));
			}catch(Exception $e){
				$commen->rollBack();
				Helper::show_message('删除失败','#');
			}
			exit;
		}
	}

	public function actionAdd(){
		$db = Yii::$app->db;

		if($_POST){
			$insurance_name = isset($_POST['insurance_name'])?trim($_POST['insurance_name']):'';
			$insurance_price = isset($_POST['insurance_price'])?trim($_POST['insurance_price']):'';
			$state = isset($_POST['state'])?trim($_POST['state']):'';
			$content = isset($_POST['content'])?trim($_POST['content']):'';
			$img_url = Yii::$app->params['img_url'];
			$content =  addslashes(str_replace('src="'.$img_url,'src="',$content));

			$sql = "INSERT INTO `zh_insurance` (name,content,price,status) VALUES ('{$insurance_name}','{$content}','{$insurance_price}','{$state}') ";

			$commen = $db->beginTransaction();
			try{
				$db->createCommand($sql)->execute();
				$commen->commit();
				Helper::show_message('保存成功', Url::toRoute(['index']));
			}catch(Exception $e){
				$commen->rollBack();
				Helper::show_message('保存失败','#');
			}
		}

		return $this->render('add');
	}

	public function actionEdit(){
		$db = Yii::$app->db;
		$id = isset($_GET['id'])?trim($_GET['id']):'';
		if($_POST){
			$insurance_id = isset($_POST['insurance_id'])?trim($_POST['insurance_id']):'';
			$insurance_name = isset($_POST['insurance_name'])?trim($_POST['insurance_name']):'';
			$insurance_price = isset($_POST['insurance_price'])?trim($_POST['insurance_price']):'';
			$state = isset($_POST['state'])?trim($_POST['state']):'';
			$content = isset($_POST['content'])?trim($_POST['content']):'';
			$img_url = Yii::$app->params['img_url'];
			$content =  addslashes(str_replace('src="'.$img_url,'src="',$content));

			$sql = "UPDATE `zh_insurance` SET name='{$insurance_name}',content='{$content}',price='{$insurance_price}',status='{$state}' WHERE insurance_id='{$insurance_id}' ";

			$commen = $db->beginTransaction();
			try{
				$db->createCommand($sql)->execute();
				$commen->commit();
				Helper::show_message('保存成功', Url::toRoute(['index']));
			}catch(Exception $e){
				$commen->rollBack();
				Helper::show_message('保存失败','#');
			}
		}

		$sql = "SELECT * FROM `zh_insurance` WHERE insurance_id='{$id}' ";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		return $this->render('edit',['data'=>$data]);
	}

	public function actionVerifyinsurancename(){

		$insurance_name = isset($_POST['insurance_name'])?trim($_POST['insurance_name']):'';
		$insurance_id = isset($_POST['insurance_id'])?trim($_POST['insurance_id']):'';

		if($insurance_id == ''){
			$sql = "SELECT count(*) count FROM `zh_insurance` WHERE name = '{$insurance_name}' ";
		}else{
			$sql = "SELECT count(*) count FROM `zh_insurance` WHERE  name = '{$insurance_name}' AND insurance_id!='{$insurance_id}' ";
		}

		$count = Yii::$app->db->createCommand($sql)->queryOne();

		echo (int)$count['count'];
	}

	public function actionDetail(){
		$id = isset($_GET['id'])?trim($_GET['id']):'';

		$sql = "SELECT * FROM `zh_insurance` WHERE insurance_id='{$id}' ";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		return $this->render('detail',['data'=>$data]);
	}

}


text:
package org.artifactory.storage.db.fs.dao;

import org.artifactory.storage.db.fs.entity.NodeMetaInfo;
import org.artifactory.storage.db.util.BaseDao;
import org.artifactory.storage.db.util.DbUtils;
import org.artifactory.storage.db.util.JdbcHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Nullable;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * A data access table for the node meta infos table.
 *
 * @author Yossi Shaul
 */
@Repository
public class NodeMetaInfoDao extends BaseDao {
    private static final Logger log = LoggerFactory.getLogger(NodeMetaInfoDao.class);

    @Autowired
    public NodeMetaInfoDao(JdbcHelper jdbcHelper) {
        super(jdbcHelper);
    }

    public boolean hasNodeMetadata(long nodeId) throws SQLException {
        return jdbcHelper.executeSelectCount("SELECT COUNT(1) FROM node_meta_infos WHERE node_id = ?", nodeId) > 0;
    }

    @Nullable
    public NodeMetaInfo getNodeMetadata(long nodeId) throws SQLException {
        ResultSet resultSet = null;
        try {
            // the child path must be the path+name of the parent
            resultSet = jdbcHelper.executeSelect("SELECT * FROM node_meta_infos WHERE node_id = ?", nodeId);
            if (resultSet.next()) {
                return metaInfosFromResultSet(resultSet);
            }
            return null;
        } finally {
            DbUtils.close(resultSet);
        }
    }

    public int deleteNodeMeta(long nodeId) throws SQLException {
        return jdbcHelper.executeUpdate("DELETE FROM node_meta_infos WHERE node_id = ?", nodeId);
    }

    public int create(NodeMetaInfo metaInfo) throws SQLException {
        return jdbcHelper.executeUpdate("INSERT INTO node_meta_infos VALUES(?, ?, ?)",
                metaInfo.getNodeId(), metaInfo.getPropsModified(), metaInfo.getPropsModifiedBy());
    }

    public int update(NodeMetaInfo metaInfo) throws SQLException {
        return jdbcHelper.executeUpdate("UPDATE node_meta_infos SET props_modified = ?, props_modified_by = ? " +
                "WHERE node_id = ?", metaInfo.getPropsModified(), metaInfo.getPropsModifiedBy(), metaInfo.getNodeId());
    }

    private NodeMetaInfo metaInfosFromResultSet(ResultSet resultSet) throws SQLException {
        long nodeId = resultSet.getLong(1);
        long propModified = resultSet.getLong(2);
        String propModifiedBy = resultSet.getString(3);
        return new NodeMetaInfo(nodeId, propModified, propModifiedBy);
    }

}


text:
package org.apache.ignite.internal.processors.continuous;

import java.io.Serializable;
import java.util.List;
import org.apache.ignite.internal.util.typedef.internal.S;

/**
 *
 */
public class ContinuousRoutinesJoiningNodeDiscoveryData implements Serializable {
    /** */
    private static final long serialVersionUID = 0L;

    /** */
    final List<ContinuousRoutineInfo> startedRoutines;

    /**
     * @param startedRoutines Routines registered on nodes, to be started in cluster.
     */
    ContinuousRoutinesJoiningNodeDiscoveryData(List<ContinuousRoutineInfo> startedRoutines) {
        this.startedRoutines = startedRoutines;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(ContinuousRoutinesJoiningNodeDiscoveryData.class, this);
    }
}


text:
package org.kangmo.http
/*
    HTTP.scala ; A helper for sending HTTP requests.
*/
import java.io._
import java.net.URL
import javax.net.ssl.HttpsURLConnection

object HTTP {
    def post(urlStr:String, postData:String = "", httpHeaders : Map[String,String] = collection.immutable.HashMap() ) = {
        val url = new URL(urlStr);
        val con = url.openConnection().asInstanceOf[HttpsURLConnection];

        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Add http headers if any
        httpHeaders.map{ case (header, value) =>
            con.setRequestProperty(header, value);
        }

        // Send post request
        con.setDoOutput(true);
        val wr = new DataOutputStream(con.getOutputStream());
        wr.write(postData.getBytes("UTF-8"));
        wr.flush();
        wr.close();

        val in = con.getInputStream();

        val response = io.Source.fromInputStream( in, "UTF-8").mkString("")

        in.close();

        response
    }

    def get(urlStr:String, httpHeaders : Map[String,String] = collection.immutable.HashMap() ) = {
        val url = new URL(urlStr);
        val con = url.openConnection().asInstanceOf[HttpsURLConnection];

        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Add http headers if any
        httpHeaders.map{ case (header, value) =>
            con.setRequestProperty(header, value);
        }

        val in = con.getInputStream
        val response = io.Source.fromInputStream( in, "UTF-8").mkString("")

        in.close();

        response
    }
}


text:
<?php

namespace Oro\Bundle\TranslationBundle\ImportExport\Serializer;

use Oro\Bundle\ImportExportBundle\Exception\UnexpectedValueException;
use Oro\Bundle\ImportExportBundle\Serializer\Normalizer\DenormalizerInterface;

use Oro\Bundle\TranslationBundle\Entity\Translation;
use Oro\Bundle\TranslationBundle\Manager\TranslationManager;

class TranslationNormalizer implements DenormalizerInterface
{
    /** @var TranslationManager */
    protected $translationManager;

    /**
     * @param TranslationManager $translationManager
     */
    public function __construct(TranslationManager $translationManager)
    {
        $this->translationManager = $translationManager;
    }

    /**
     * {@inheritdoc}
     */
    public function denormalize($data, $class, $format = null, array $context = [])
    {
        if (!is_array($data) || !isset($data['domain'], $data['key'], $data['value'])) {
            throw new UnexpectedValueException('Incorrect record format');
        }

        $translation = $this->translationManager->createTranslation(
            $data['key'],
            $data['value'],
            $context['language_code'],
            $data['domain']
        );

        $translation->setScope(Translation::SCOPE_UI);

        return $translation;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsDenormalization($data, $type, $format = null, array $context = [])
    {
        return $type === Translation::class && !empty($context['language_code']);
    }
}


text:
/*! \file ShadingApi.cpp
 *  \author Jared Hoberock
 *  \brief Implementation of ShadingApi class.
 */

#include "ShadingApi.h"

using namespace boost;

ShadingContext *ShadingApi
  ::context(Gotham::AttributeMap &attr,
            const boost::shared_ptr<MaterialList> &materials,
            const boost::shared_ptr<TextureList> &textures)
{
  ShadingContext *result = 0;

  result = new ShadingContext();

  // give the materials to the ShadingContext
  result->setMaterials(materials);

  // give the textures to the ShadingContext
  result->setTextures(textures);

  return result;
} // end context()


text:
<?php

/**
 * @namespace
 */
namespace Zend\Form\Decorator;

/**
 * Zend_Form_Decorator_Interface
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Decorator
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 20096 2010-01-06 02:05:09Z bkarwin $
 */
interface DecoratorInterface
{
    /**
     * Constructor
     *
     * Accept options during initialization.
     *
     * @param  array|Zend_Config $options
     * @return void
     */
    public function __construct($options = null);

    /**
     * Set an element to decorate
     *
     * While the name is "setElement", a form decorator could decorate either
     * an element or a form object.
     *
     * @param  mixed $element
     * @return Zend_Form_Decorator_Interface
     */
    public function setElement($element);

    /**
     * Retrieve current element
     *
     * @return mixed
     */
    public function getElement();

    /**
     * Set decorator options from an array
     *
     * @param  array $options
     * @return Zend_Form_Decorator_Interface
     */
    public function setOptions(array $options);

    /**
     * Set decorator options from a config object
     *
     * @param  Zend_Config $config
     * @return Zend_Form_Decorator_Interface
     */
    public function setConfig(\Zend\Config\Config $config);

    /**
     * Set a single option
     *
     * @param  string $key
     * @param  mixed $value
     * @return Zend_Form_Decorator_Interface
     */
    public function setOption($key, $value);

    /**
     * Retrieve a single option
     *
     * @param  string $key
     * @return mixed
     */
    public function getOption($key);

    /**
     * Retrieve decorator options
     *
     * @return array
     */
    public function getOptions();

    /**
     * Delete a single option
     *
     * @param  string $key
     * @return bool
     */
    public function removeOption($key);

    /**
     * Clear all options
     *
     * @return Zend_Form_Decorator_Interface
     */
    public function clearOptions();

    /**
     * Render the element
     *
     * @param  string $content Content to decorate
     * @return string
     */
    public function render($content);
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

Issue 1840

NotoSans-Regular

ԇң

NotoSans-Italic

ԇң

NotoSerif-Regular

ԇң

NotoSerif-Italic

ԇң

NotoMono-Regular

ԇң

 Test details:

Fonts used:

https://github.com/googlefonts/noto-fonts/tree/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf
 https://github.com/googlefonts/noto-fonts/tree/main/hinted/ttf/NotoSans/NotoSans-Italic.ttf
 https://github.com/googlefonts/noto-fonts/tree/main/hinted/ttf/NotoSerif/NotoSerif-Regular.ttf
 https://github.com/googlefonts/noto-fonts/tree/main/hinted/ttf/NotoSerif/NotoSerif-Italic.ttf
 https://github.com/googlefonts/noto-fonts/tree/main/hinted/ttf/NotoMono/NotoMono-Regular.ttf

Test created on:


text:
package ebpf

import (
	"errors"
	"fmt"
	"reflect"
	"testing"

	"github.com/cilium/ebpf/asm"
	"github.com/cilium/ebpf/btf"
	"github.com/cilium/ebpf/internal"
	"github.com/cilium/ebpf/internal/testutils"
)

func TestCollectionSpecNotModified(t *testing.T) {
	cs := CollectionSpec{
		Maps: map[string]*MapSpec{
			"my-map": {
				Type:       Array,
				KeySize:    4,
				ValueSize:  4,
				MaxEntries: 1,
			},
		},
		Programs: map[string]*ProgramSpec{
			"test": {
				Type: SocketFilter,
				Instructions: asm.Instructions{
					asm.LoadImm(asm.R1, 0, asm.DWord).WithReference("my-map"),
					asm.LoadImm(asm.R0, 0, asm.DWord),
					asm.Return(),
				},
				License: "MIT",
			},
		},
	}

	coll, err := NewCollection(&cs)
	if err != nil {
		t.Fatal(err)
	}
	coll.Close()

	if cs.Programs["test"].Instructions[0].Constant != 0 {
		t.Error("Creating a collection modifies input spec")
	}
}

func TestCollectionSpecCopy(t *testing.T) {
	cs := &CollectionSpec{
		Maps: map[string]*MapSpec{
			"my-map": {
				Type:       Array,
				KeySize:    4,
				ValueSize:  4,
				MaxEntries: 1,
			},
		},
		Programs: map[string]*ProgramSpec{
			"test": {
				Type: SocketFilter,
				Instructions: asm.Instructions{
					asm.LoadMapPtr(asm.R1, 0),
					asm.LoadImm(asm.R0, 0, asm.DWord),
					asm.Return(),
				},
				License: "MIT",
			},
		},
		Types: &btf.Spec{},
	}
	cpy := cs.Copy()

	if cpy == cs {
		t.Error("Copy returned the same pointner")
	}

	if cpy.Maps["my-map"] == cs.Maps["my-map"] {
		t.Error("Copy returned same Maps")
	}

	if cpy.Programs["test"] == cs.Programs["test"] {
		t.Error("Copy returned same Programs")
	}

	if cpy.Types != cs.Types {
		t.Error("Copy returned different Types")
	}
}

func TestCollectionSpecLoadCopy(t *testing.T) {
	file := fmt.Sprintf("testdata/loader-%s.elf", internal.ClangEndian)
	spec, err := LoadCollectionSpec(file)
	if err != nil {
		t.Fatal(err)
	}

	spec2 := spec.Copy()

	var objs struct {
		Prog *Program `ebpf:"xdp_prog"`
	}

	err = spec.LoadAndAssign(&objs, nil)
	testutils.SkipIfNotSupported(t, err)
	if err != nil {
		t.Fatal("Loading original spec:", err)
	}
	defer objs.Prog.Close()

	if err := spec2.LoadAndAssign(&objs, nil); err != nil {
		t.Fatal("Loading copied spec:", err)
	}
	defer objs.Prog.Close()
}

func TestCollectionSpecRewriteMaps(t *testing.T) {
	insns := asm.Instructions{
		// R1 map
		asm.LoadMapPtr(asm.R1, 0).WithReference("test-map"),
		// R2 key
		asm.Mov.Reg(asm.R2, asm.R10),
		asm.Add.Imm(asm.R2, -4),
		asm.StoreImm(asm.R2, 0, 0, asm.Word),
		// Lookup map[0]
		asm.FnMapLookupElem.Call(),
		asm.JEq.Imm(asm.R0, 0, "ret"),
		asm.LoadMem(asm.R0, asm.R0, 0, asm.Word),
		asm.Return().WithSymbol("ret"),
	}

	cs := &CollectionSpec{
		Maps: map[string]*MapSpec{
			"test-map": {
				Type:       Array,
				KeySize:    4,
				ValueSize:  4,
				MaxEntries: 1,
			},
		},
		Programs: map[string]*ProgramSpec{
			"test-prog": {
				Type:         SocketFilter,
				Instructions: insns,
				License:      "MIT",
			},
		},
	}

	// Override the map with another one
	newMap, err := NewMap(cs.Maps["test-map"])
	if err != nil {
		t.Fatal(err)
	}
	defer newMap.Close()

	err = newMap.Put(uint32(0), uint32(2))
	if err != nil {
		t.Fatal(err)
	}

	err = cs.RewriteMaps(map[string]*Map{
		"test-map": newMap,
	})
	if err != nil {
		t.Fatal(err)
	}

	if cs.Maps["test-map"] != nil {
		t.Error("RewriteMaps doesn't remove map from CollectionSpec.Maps")
	}

	coll, err := NewCollection(cs)
	if err != nil {
		t.Fatal(err)
	}
	defer coll.Close()

	ret, _, err := coll.Programs["test-prog"].Test(internal.EmptyBPFContext)
	testutils.SkipIfNotSupported(t, err)
	if err != nil {
		t.Fatal(err)
	}

	if ret != 2 {
		t.Fatal("new / override map not used")
	}
}

func TestCollectionSpecMapReplacements(t *testing.T) {
	insns := asm.Instructions{
		// R1 map
		asm.LoadMapPtr(asm.R1, 0).WithReference("test-map"),
		// R2 key
		asm.Mov.Reg(asm.R2, asm.R10),
		asm.Add.Imm(asm.R2, -4),
		asm.StoreImm(asm.R2, 0, 0, asm.Word),
		// Lookup map[0]
		asm.FnMapLookupElem.Call(),
		asm.JEq.Imm(asm.R0, 0, "ret"),
		asm.LoadMem(asm.R0, asm.R0, 0, asm.Word),
		asm.Return().WithSymbol("ret"),
	}

	cs := &CollectionSpec{
		Maps: map[string]*MapSpec{
			"test-map": {
				Type:       Array,
				KeySize:    4,
				ValueSize:  4,
				MaxEntries: 1,
			},
		},
		Programs: map[string]*ProgramSpec{
			"test-prog": {
				Type:         SocketFilter,
				Instructions: insns,
				License:      "MIT",
			},
		},
	}

	// Replace the map with another one
	newMap, err := NewMap(cs.Maps["test-map"])
	if err != nil {
		t.Fatal(err)
	}
	defer newMap.Close()

	err = newMap.Put(uint32(0), uint32(2))
	if err != nil {
		t.Fatal(err)
	}

	coll, err := NewCollectionWithOptions(cs, CollectionOptions{
		MapReplacements: map[string]*Map{
			"test-map": newMap,
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	defer coll.Close()

	ret, _, err := coll.Programs["test-prog"].Test(internal.EmptyBPFContext)
	testutils.SkipIfNotSupported(t, err)
	if err != nil {
		t.Fatal(err)
	}

	if ret != 2 {
		t.Fatal("new / override map not used")
	}

	// Check that newMap isn't closed when the collection is closed
	coll.Close()
	err = newMap.Put(uint32(0), uint32(3))
	if err != nil {
		t.Fatalf("failed to update replaced map: %s", err)
	}
}
func TestCollectionSpecMapReplacements_NonExistingMap(t *testing.T) {
	cs := &CollectionSpec{
		Maps: map[string]*MapSpec{
			"test-map": {
				Type:       Array,
				KeySize:    4,
				ValueSize:  4,
				MaxEntries: 1,
			},
		},
	}

	// Override non-existing map
	newMap, err := NewMap(cs.Maps["test-map"])
	if err != nil {
		t.Fatal(err)
	}
	defer newMap.Close()

	coll, err := NewCollectionWithOptions(cs, CollectionOptions{
		MapReplacements: map[string]*Map{
			"non-existing-map": newMap,
		},
	})
	if err == nil {
		coll.Close()
		t.Fatal("Overriding a non existing map did not fail")
	}
}

func TestCollectionSpecMapReplacements_SpecMismatch(t *testing.T) {
	cs := &CollectionSpec{
		Maps: map[string]*MapSpec{
			"test-map": {
				Type:       Array,
				KeySize:    4,
				ValueSize:  4,
				MaxEntries: 1,
			},
		},
	}

	// Override map with mismatching spec
	newMap, err := NewMap(&MapSpec{
		Type:       Array,
		KeySize:    4,
		ValueSize:  8, // this is different
		MaxEntries: 1,
	})
	if err != nil {
		t.Fatal(err)
	}
	// Map fd is duplicated by MapReplacements, this one can be safely closed.
	defer newMap.Close()

	coll, err := NewCollectionWithOptions(cs, CollectionOptions{
		MapReplacements: map[string]*Map{
			"test-map": newMap,
		},
	})
	if err == nil {
		coll.Close()
		t.Fatal("Overriding a map with a mismatching spec did not fail")
	}
	if !errors.Is(err, ErrMapIncompatible) {
		t.Fatalf("Overriding a map with a mismatching spec failed with the wrong error")
	}
}

func TestCollectionSpec_LoadAndAssign_LazyLoading(t *testing.T) {
	spec := &CollectionSpec{
		Maps: map[string]*MapSpec{
			"valid": {
				Type:       Array,
				KeySize:    4,
				ValueSize:  4,
				MaxEntries: 1,
			},
			"bogus": {
				Type:       Array,
				MaxEntries: 0,
			},
		},
		Programs: map[string]*ProgramSpec{
			"valid": {
				Type: SocketFilter,
				Instructions: asm.Instructions{
					asm.LoadImm(asm.R0, 0, asm.DWord),
					asm.Return(),
				},
				License: "MIT",
			},
			"bogus": {
				Type: SocketFilter,
				Instructions: asm.Instructions{
					// Undefined return value is rejected
					asm.Return(),
				},
				License: "MIT",
			},
		},
	}

	var objs struct {
		Prog *Program `ebpf:"valid"`
		Map  *Map     `ebpf:"valid"`
	}

	if err := spec.LoadAndAssign(&objs, nil); err != nil {
		t.Fatal("Assign loads a map or program that isn't requested in the struct:", err)
	}
	defer objs.Prog.Close()
	defer objs.Map.Close()

	if objs.Prog == nil {
		t.Error("Program is nil")
	}

	if objs.Map == nil {
		t.Error("Map is nil")
	}
}

func TestCollectionAssign(t *testing.T) {
	var specs struct {
		Program *ProgramSpec `ebpf:"prog1"`
		Map     *MapSpec     `ebpf:"map1"`
	}

	mapSpec := &MapSpec{
		Type:       Array,
		KeySize:    4,
		ValueSize:  4,
		MaxEntries: 1,
	}
	progSpec := &ProgramSpec{
		Type: SocketFilter,
		Instructions: asm.Instructions{
			asm.LoadImm(asm.R0, 0, asm.DWord),
			asm.Return(),
		},
		License: "MIT",
	}

	cs := &CollectionSpec{
		Maps: map[string]*MapSpec{
			"map1": mapSpec,
		},
		Programs: map[string]*ProgramSpec{
			"prog1": progSpec,
		},
	}

	if err := cs.Assign(&specs); err != nil {
		t.Fatal("Can't assign spec:", err)
	}

	if specs.Program != progSpec {
		t.Fatalf("Expected Program to be %p, got %p", progSpec, specs.Program)
	}

	if specs.Map != mapSpec {
		t.Fatalf("Expected Map to be %p, got %p", mapSpec, specs.Map)
	}

	if err := cs.Assign(new(int)); err == nil {
		t.Fatal("Assign allows to besides *struct")
	}

	if err := cs.Assign(new(struct{ Foo int })); err != nil {
		t.Fatal("Assign doesn't ignore untagged fields")
	}

	unexported := new(struct {
		foo *MapSpec `ebpf:"map1"`
	})

	if err := cs.Assign(unexported); err == nil {
		t.Error("Assign should return an error on unexported fields")
	}
}

func TestAssignValues(t *testing.T) {
	zero := func(t reflect.Type, name string) (interface{}, error) {
		return reflect.Zero(t).Interface(), nil
	}

	type t1 struct {
		Bar int `ebpf:"bar"`
	}

	type t2 struct {
		t1
		Foo int `ebpf:"foo"`
	}

	type t2ptr struct {
		*t1
		Foo int `ebpf:"foo"`
	}

	invalid := []struct {
		name string
		to   interface{}
	}{
		{"non-struct", 1},
		{"non-pointer struct", t1{}},
		{"pointer to non-struct", new(int)},
		{"embedded nil pointer", &t2ptr{}},
		{"unexported field", new(struct {
			foo int `ebpf:"foo"`
		})},
		{"identical tag", new(struct {
			Foo1 int `ebpf:"foo"`
			Foo2 int `ebpf:"foo"`
		})},
	}

	for _, testcase := range invalid {
		t.Run(testcase.name, func(t *testing.T) {
			if err := assignValues(testcase.to, zero); err == nil {
				t.Fatal("assignValues didn't return an error")
			} else {
				t.Log(err)
			}
		})
	}

	valid := []struct {
		name string
		to   interface{}
	}{
		{"pointer to struct", new(t1)},
		{"embedded struct", new(t2)},
		{"embedded struct pointer", &t2ptr{t1: new(t1)}},
		{"untagged field", new(struct{ Foo int })},
	}

	for _, testcase := range valid {
		t.Run(testcase.name, func(t *testing.T) {
			if err := assignValues(testcase.to, zero); err != nil {
				t.Fatal("assignValues returned", err)
			}
		})
	}

}

func TestIncompleteLoadAndAssign(t *testing.T) {
	spec := &CollectionSpec{
		Programs: map[string]*ProgramSpec{
			"valid": {
				Type: SocketFilter,
				Instructions: asm.Instructions{
					asm.LoadImm(asm.R0, 0, asm.DWord),
					asm.Return(),
				},
				License: "MIT",
			},
			"invalid": {
				Type: SocketFilter,
				Instructions: asm.Instructions{
					asm.Return(),
				},
				License: "MIT",
			},
		},
	}

	s := struct {
		// Assignment to Valid should execute and succeed.
		Valid *Program `ebpf:"valid"`
		// Assignment to Invalid should fail and cause Valid's fd to be closed.
		Invalid *Program `ebpf:"invalid"`
	}{}

	if err := spec.LoadAndAssign(&s, nil); err == nil {
		t.Fatal("expected error loading invalid ProgramSpec")
	}

	if fd := s.Valid.FD(); fd != -1 {
		t.Fatal("expected valid prog to have closed fd -1, got:", fd)
	}

	if s.Invalid != nil {
		t.Fatal("expected invalid prog to be nil due to never being assigned")
	}
}

func BenchmarkNewCollection(b *testing.B) {
	file := fmt.Sprintf("testdata/loader-%s.elf", internal.ClangEndian)
	spec, err := LoadCollectionSpec(file)
	if err != nil {
		b.Fatal(err)
	}

	spec.Maps["array_of_hash_map"].InnerMap = spec.Maps["hash_map"]
	for _, m := range spec.Maps {
		m.Pinning = PinNone
	}

	b.ReportAllocs()
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		coll, err := NewCollection(spec)
		if err != nil {
			b.Fatal(err)
		}
		coll.Close()
	}
}

func ExampleCollectionSpec_Assign() {
	spec := &CollectionSpec{
		Maps: map[string]*MapSpec{
			"map1": {
				Type:       Array,
				KeySize:    4,
				ValueSize:  4,
				MaxEntries: 1,
			},
		},
		Programs: map[string]*ProgramSpec{
			"prog1": {
				Type: SocketFilter,
				Instructions: asm.Instructions{
					asm.LoadImm(asm.R0, 0, asm.DWord),
					asm.Return(),
				},
				License: "MIT",
			},
		},
	}

	type maps struct {
		Map *MapSpec `ebpf:"map1"`
	}

	var specs struct {
		maps
		Program *ProgramSpec `ebpf:"prog1"`
	}

	if err := spec.Assign(&specs); err != nil {
		panic(err)
	}

	fmt.Println(specs.Program.Type)
	fmt.Println(specs.Map.Type)

	// Output: SocketFilter
	// Array
}

func ExampleCollectionSpec_LoadAndAssign() {
	spec := &CollectionSpec{
		Maps: map[string]*MapSpec{
			"map1": {
				Type:       Array,
				KeySize:    4,
				ValueSize:  4,
				MaxEntries: 1,
			},
		},
		Programs: map[string]*ProgramSpec{
			"prog1": {
				Type: SocketFilter,
				Instructions: asm.Instructions{
					asm.LoadImm(asm.R0, 0, asm.DWord),
					asm.Return(),
				},
				License: "MIT",
			},
		},
	}

	var objs struct {
		Program *Program `ebpf:"prog1"`
		Map     *Map     `ebpf:"map1"`
	}

	if err := spec.LoadAndAssign(&objs, nil); err != nil {
		panic(err)
	}
	defer objs.Program.Close()
	defer objs.Map.Close()

	fmt.Println(objs.Program.Type())
	fmt.Println(objs.Map.Type())

	// Output: SocketFilter
	// Array
}


text:
module Rfm
  module Factory # :nodoc: all
    class DbFactory < Rfm::CaseInsensitiveHash

      def initialize(server)
        @server = server
        @loaded = false
      end

      def [](dbname)
        super or (self[dbname] = Rfm::Database.new(dbname, @server))
      end

      def all
        if !@loaded
          Rfm::Resultset.new(@server, @server.connect('-dbnames', {}).body, nil).each {|record|
            name = record['DATABASE_NAME']
            self[name] = Rfm::Database.new(name, @server) if self[name] == nil
          }
          @loaded = true
        end
        self.values
      end

    end

    class LayoutFactory < Rfm::CaseInsensitiveHash

      def initialize(server, database)
        @server = server
        @database = database
        @loaded = false
      end

      def [](layout_name)
        super or (self[layout_name] = Rfm::Layout.new(layout_name, @database))
      end

      def all
        if !@loaded
          Rfm::Resultset.new(@server, @server.connect('-layoutnames', {"-db" => @database.name}).body, nil).each {|record|
            name = record['layout_name']
            self[name] = Rfm::Layout.new(name, @database) if name.present? && self[name] == nil
          }
          @loaded = true
        end
        self.values
      end

    end

    class ScriptFactory < Rfm::CaseInsensitiveHash

      def initialize(server, database)
        @server = server
        @database = database
        @loaded = false
      end

      def [](script_name)
        super or (self[script_name] = Rfm::Script.new(script_name, @database))
      end

      def all
        if !@loaded
          Rfm::Resultset.new(@server, @server.connect('-scriptnames', {"-db" => @database.name}).body, nil).each {|record|
            name = record['SCRIPT_NAME']
            self[name] = Rfm::Script.new(name, @database) if self[name] == nil
          }
          @loaded = true
        end
        self.values
      end

    end
  end
end


text:
package edu.uoregon.bbird.weatherdemo;

// Written by Brian Bird 7/11/15, updated 7/20/18

import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.*;

import static edu.uoregon.bbird.weatherdemo.WeatherSQLiteHelper.*;

public class ParseHandler extends DefaultHandler {
    private WeatherItems weatherItems;
    private WeatherItem item;
    private boolean isDate = false;
    private boolean isIcon = false;
    private boolean isForecastText = false;
    private boolean isTitle = false;
    private boolean isPOP = false;
    private boolean isPeriod = false;
    private boolean isDone = false;

    public WeatherItems getItems() {
        return weatherItems;
    }

    @Override
    public void startDocument() throws SAXException {
        weatherItems = new WeatherItems();
        item = new WeatherItem();
    }

    @Override
    public void startElement(String namespaceURI, String localName,
            String qName, Attributes atts) throws SAXException {

    	if (isDone) {
            // Do nothing because we've parsed everything we need
        }
        else if (qName.equals(FORECAST_DAY)) {
            item = new WeatherItem();
        }
        else if (qName.equals(DATE)) {
            isDate = true;
        }
        else if (qName.equals(ICON)) {
            isIcon = true;
        }
        else if (qName.equals(FCT_TEXT)) {
            isForecastText = true;
        }
        else if (qName.equals(TITLE)) {
            isTitle = true;
        }
        else if (qName.equals(PERIOD)) {
            isPeriod = true;
        }else if (qName.equals(POP)) {
            isPOP = true;
        }
    }

    @Override
    public void endElement(String namespaceURI, String localName,
            String qName) throws SAXException
    {
        if (!isDone && qName.equals(FORECAST_DAY)) {
            weatherItems.add(item);
        }
        else if (qName.equals("txt_forecast")) {
            isDone = true;
        }
    }

    @Override
    public void characters(char ch[], int start, int length)
    {
        String s = new String(ch, start, length);
        if (isDate) {
            weatherItems.setForecastTime(s);
            isDate = false;
    }
        else if (isIcon) {
            item.setIcon(s);
            isIcon = false;
        }
         else if (isForecastText) {
            item.setForecastText(s);
            isForecastText = false;
        }
        else if (isTitle) {
            item.setTitle(s);
            isTitle = false;
        }
        else if (isPeriod) {
            item.setPeriod(s);
            isPeriod = false;
        }
        else if (isPOP) {
            item.setPOP(s);
            isPOP = false;
        }
    }
}


text:
package mah.ui.input;

/**
 * Created by zgq on 2017-01-09 10:35
 */
public interface Input {

    void setTextState(TextState textState);

    void beginningOfLine();

    void endOfLine();

    void forwardChar();

    void backwardChar();

    void deleteChar();

    void forwardWord();

    void backwardWord();

    void killWord();

    void killWholeLine();

    void killLine();

    void setText(String text);

    void setCaretPosition(int position);

    void backwardKillWord();

    void backwardDeleteChar();

    String getText();

    void redo();

    void undo();

    void remove(int offset, int len);

    int getCaretPosition();

    void clear();

}


text:
package co.freeside.betamax.io;

import java.util.logging.*;
import org.apache.tika.mime.*;

/**
 * Maps *MIME* types to file extensions.
 */
public class FileTypeMapper {

    public static FileTypeMapper getInstance() {
        return INSTANCE;
    }

    private final MimeTypes mimeTypes = MimeTypes.getDefaultMimeTypes();

    private static final Logger LOG = Logger.getLogger(FileTypeMapper.class.getName());

    /**
     * Returns a filename consisting of `baseName` and an appropriate file
     * extension for the specified MIME type.
     *
     * @param baseName    a base file name.
     * @param contentType a MIME content type such as `text/plain`.
     * @return a filename with an appropriate extension.
     */
    public String filenameFor(String baseName, String contentType) {
        String filename;
        try {
            String extension = mimeTypes.forName(contentType).getExtension();
            filename = baseName + extension;
        } catch (MimeTypeException e) {
            LOG.warning(String.format("Could not get extension for %s content type: %s", contentType, e.getMessage()));
            filename = baseName + ".bin";
        }
        return filename;
    }

    private static final FileTypeMapper INSTANCE = new FileTypeMapper();

    private FileTypeMapper() {
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ERY.EMath;

namespace FploWannierConverter
{
	class Atom
	{
		static Dictionary<string, int> elements = new Dictionary<string, int>();

		static Atom()
		{
			string at = Resources.Atoms;
			string[] lines = at.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);

			char[] splitters = new char[] {' ', '\r', '\t', '\n'};
			foreach (var line in lines)
			{
				string[] vals = line.Split(splitters, StringSplitOptions.RemoveEmptyEntries);

				elements.Add(vals[1], int.Parse(vals[0]));
			}
		}

		/// <summary>
		/// Position of the atom in atomic units (Bohrs)
		/// </summary>
		public Vector3 Position { get; set; }
		public string Element { get; set; }

		public int AtomicNumber
		{
			get
			{
				if (string.IsNullOrEmpty(Element))
					return 0;

				return elements[Element];
			}
		}

		public override string ToString()
		{
			return string.Format("{0}: {1}", Element, Position.ToString("0.000"));
		}
	}
}


text:
package com.example;

import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;

import com.fasterxml.jackson.annotation.JsonFormat;

import org.springframework.cloud.gcp.data.spanner.core.mapping.Column;
import org.springframework.cloud.gcp.data.spanner.core.mapping.PrimaryKey;
import org.springframework.cloud.gcp.data.spanner.core.mapping.Table;

/**
 * A sample entity.
 *
 * @author Mike Eltsufin
 */
@Table(name = "traders")
public class Trader {
	@PrimaryKey
	@Column(name = "trader_id")
	private String traderId;

	@Column(name = "first_name")
	private String firstName;

	@Column(name = "last_name")
	private String lastName;

	@Column(name = "CREATED_ON")
	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MMM-dd HH:mm:ss z")
	private java.sql.Timestamp createdOn;

	@Column(name = "MODIFIED_ON")
	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MMM-dd HH:mm:ss z")
	private List<java.sql.Timestamp> modifiedOn;

	public Trader() {
	}

	public Trader(String traderId, String firstName, String lastName) {
		this.traderId = traderId;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public Trader(String traderId, String firstName, String lastName, Timestamp createdOn, List<Timestamp> modifiedOn) {
		this.traderId = traderId;
		this.firstName = firstName;
		this.lastName = lastName;
		this.createdOn = createdOn;
		this.modifiedOn = modifiedOn;
	}

	public String getTraderId() {
		return this.traderId;
	}

	public void setTraderId(String traderId) {
		this.traderId = traderId;
	}

	public String getFirstName() {
		return this.firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return this.lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return "Trader{" +
				"traderId='" + this.traderId + '\'' +
				", firstName='" + this.firstName + '\'' +
				", lastName='" + this.lastName + '\'' +
				", createdOn=" + this.createdOn +
				", modifiedOn=" + this.modifiedOn +
				'}';
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		Trader trader = (Trader) o;
		return Objects.equals(getTraderId(), trader.getTraderId()) &&
				Objects.equals(getFirstName(), trader.getFirstName()) &&
				Objects.equals(getLastName(), trader.getLastName()) &&
				Objects.equals(this.createdOn, trader.createdOn) &&
				Objects.equals(this.modifiedOn, trader.modifiedOn);
	}

	@Override
	public int hashCode() {
		return Objects.hash(getTraderId(), getFirstName(), getLastName(), this.createdOn, this.modifiedOn);
	}
}


text:
import React from 'react';
import clsx from 'clsx';
import { loadCSS } from 'fg-loadcss';
import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';
import { red } from '@material-ui/core/colors';
import Icon from '@material-ui/core/Icon';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      '& > .fa': {
        margin: theme.spacing(2),
      },
    },
    iconHover: {
      margin: theme.spacing(2),
      '&:hover': {
        color: red[800],
      },
    },
  }),
);

export default function FontAwesome() {
  const classes = useStyles();

  React.useEffect(() => {
    loadCSS(
      'https://use.fontawesome.com/releases/v5.1.0/css/all.css',
      document.querySelector('#font-awesome-css'),
    );
  }, []);

  return (
    <div className={classes.root}>
      <Icon className="fa fa-plus-circle" />
      <Icon className="fa fa-plus-circle" color="primary" />
      <Icon className="fa fa-plus-circle" color="secondary" />
      <Icon className="fa fa-plus-circle" color="action" />
      <Icon
        className={clsx(classes.iconHover, 'fa fa-plus-circle')}
        color="error"
        style={{ fontSize: 30 }}
      />
      <Icon className="fa fa-plus-circle" color="disabled" fontSize="large" />
    </div>
  );
}


text:
package com.facebook.crypto.streams;

import com.facebook.crypto.mac.NativeMac;

import java.io.IOException;
import java.io.OutputStream;

public class NativeMacLayeredOutputStream extends OutputStream {

  private final NativeMac mMac;
  private final OutputStream mOutputDelegate;

  /**
   * Creates a new output stream to write to.
   *
   * @param mac The object used to compute the mac.
   * @param outputDelegate The stream to write data to.
   */
  public NativeMacLayeredOutputStream(NativeMac mac, OutputStream outputDelegate) {
    mMac = mac;
    mOutputDelegate = outputDelegate;
  }

  @Override
  public void close() throws IOException {
    try {
      byte[] mac = mMac.doFinal();
      mOutputDelegate.write(mac);
    } finally {
      try {
        mOutputDelegate.close();
      } finally {
        mMac.destroy();
      }
    }
  }

  @Override
  public void flush() throws IOException {
    mOutputDelegate.flush();
  }

  @Override
  public void write(byte[] buffer) throws IOException {
    write(buffer, 0, buffer.length);
  }

  @Override
  public void write(byte[] buffer, int offset, int count) throws IOException {
    mMac.update(buffer, offset, count);
    mOutputDelegate.write(buffer, offset, count);
  }

  @Override
  public void write(int oneByte) throws IOException {
    mMac.update((byte) oneByte);
    mOutputDelegate.write(oneByte);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    <android.support.v7.widget.CardView
        android:id="@+id/info_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/toolbar"
        android:layout_margin="16dp"
        app:cardCornerRadius="3dp"
        >

        <TextView
            android:id="@+id/test_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/toolbar"
            android:layout_margin="16dp"
            android:fontFamily="sans-serif-condensed"
            android:textSize="17sp"
            />

    </android.support.v7.widget.CardView>

    <Button
        android:id="@+id/startTest"
        android:theme="@style/ThemeOverlay.MyDarkButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@id/info_container"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:fontFamily="sans-serif-condensed"
        android:text="Start Test"
        android:textAllCaps="false"
        android:textSize="17sp" />

</RelativeLayout>


text:
import {
  createStore,
  applyMiddleware,
  compose
} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';

const createStoreWithMiddleware = compose(
  applyMiddleware(
    thunk
  )
)(createStore);

export default function configureStore(initialState) {
  const store = createStoreWithMiddleware(rootReducer, initialState,
    typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f);
  if (module.hot) {
    module.hot.accept('../reducers', () => {
      store.replaceReducer(require('../reducers'));
    });
  }
  return store;
}


text:
package edu.vt.rhids.input;

import edu.vt.rhids.main.RHIDS;

import java.util.ArrayList;
import java.util.Collections;

/**
 * Bag of System Calls
 *
 * @author AmrAbed
 */
public class BoSC extends ArrayList<Byte> {
	private static final long serialVersionUID = 1L;

	BoSC(Window window) {
		super(Collections.nCopies(RHIDS.getInstance().getIndexMap().size() + 1, (byte) 0));
		for (String syscall : window) {
			int index = RHIDS.getInstance().getIndexMap().get(syscall);
			Byte count = get(index);
			set(index, ++count);
		}
	}

	public BoSC(String string) {
		string = string.replace("[", "");
		string = string.replace("]", "");

		for (String value : string.split(",")) {
			add(Byte.parseByte(value.trim()));
		}
	}
}


text:
<?php

namespace BCRM\BackendBundle\Entity\Event;

use PhpOption\Option;

interface EventRepository
{
    /**
     * @return Option
     */
    public function getNextEvent();

    /**
     * @param Event $event
     * @param       $day
     *
     * @return integer
     */
    public function getCapacity(Event $event, $day);
}


text:
package reducers.io;

import java.io.IOException;
import java.util.Iterator;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Reducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import data.Triple;
import data.TripleSource;

public class ImportTriplesReconstructReducer extends
		Reducer<LongWritable, LongWritable, TripleSource, Triple> {

	protected static Logger log = LoggerFactory
			.getLogger(ImportTriplesReconstructReducer.class);

	private Triple oValue = new Triple();
	private TripleSource oKey = new TripleSource();

	public void reduce(LongWritable key, Iterable<LongWritable> values,
			Context context) throws IOException, InterruptedException {

		Iterator<LongWritable> itr = values.iterator();
		int counter = 0;
		while (itr.hasNext()) {
			counter++;

			// Get the position
			long value = itr.next().get();
			long pos = value & 0x3;
			if (pos == 0) {
				oValue.setSubject(value >> 2);
			} else if (pos == 1) {
				oValue.setPredicate(value >> 2);
			} else if (pos == 2) {
				oValue.setObject(value >> 2);
				oValue.setObjectLiteral(false);
			} else if (pos == 3) {
				oValue.setObject(value >> 2);
				oValue.setObjectLiteral(true);
			} else {
				// throw new IOException("Position not clear!!");
				log.error("Position not clear!!");
			}
		}

		if (counter != 3) {
			// throw new IOException("Triple is not reconstructed!");
			log.error("Triple is not reconstructed!" + key.get());
		}

		context.getCounter("output", "records").increment(1);
		context.write(oKey, oValue);
	}

	@Override
	protected void setup(Context context) throws IOException,
			InterruptedException {
		super.setup(context);
		oKey.setStep(context.getConfiguration().getInt("inputStep", 0));
		log.info("Set step to " + oKey.getStep());
	}
}


text:
/**
 * @file
 * Additional SNMPv3 functionality RFC3414 and RFC3826.
 */

/*
 * Copyright (c) 2016 Elias Oenal.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * Author: Elias Oenal <lwip@eliasoenal.com>
 */

#ifndef LWIP_HDR_APPS_SNMP_V3_H
#define LWIP_HDR_APPS_SNMP_V3_H

#include "lwip/apps/snmp_opts.h"
#include "lwip/err.h"

#if LWIP_SNMP && LWIP_SNMP_V3

typedef enum
{
  SNMP_V3_AUTH_ALGO_INVAL = 0,
  SNMP_V3_AUTH_ALGO_MD5   = 1,
  SNMP_V3_AUTH_ALGO_SHA   = 2
} snmpv3_auth_algo_t;

typedef enum
{
  SNMP_V3_PRIV_ALGO_INVAL = 0,
  SNMP_V3_PRIV_ALGO_DES   = 1,
  SNMP_V3_PRIV_ALGO_AES   = 2
} snmpv3_priv_algo_t;

typedef enum
{
  SNMP_V3_USER_STORAGETYPE_OTHER       = 1,
  SNMP_V3_USER_STORAGETYPE_VOLATILE    = 2,
  SNMP_V3_USER_STORAGETYPE_NONVOLATILE = 3,
  SNMP_V3_USER_STORAGETYPE_PERMANENT   = 4,
  SNMP_V3_USER_STORAGETYPE_READONLY    = 5
} snmpv3_user_storagetype_t;

/*
 * The following callback functions must be implemented by the application.
 * There is a dummy implementation in snmpv3_dummy.c.
 */

void snmpv3_get_engine_id(const char **id, u8_t *len);
err_t snmpv3_set_engine_id(const char* id, u8_t len);

u32_t snmpv3_get_engine_boots(void);
void snmpv3_set_engine_boots(u32_t boots);

u32_t snmpv3_get_engine_time(void);
void snmpv3_reset_engine_time(void);

err_t snmpv3_get_user(const char* username, snmpv3_auth_algo_t *auth_algo, u8_t *auth_key, snmpv3_priv_algo_t *priv_algo, u8_t *priv_key);
u8_t snmpv3_get_amount_of_users(void);
err_t snmpv3_get_user_storagetype(const char *username, snmpv3_user_storagetype_t *storagetype);
err_t snmpv3_get_username(char *username, u8_t index);

/* The following functions are provided by the SNMPv3 agent */

void snmpv3_engine_id_changed(void);
s32_t snmpv3_get_engine_time_internal(void);

void snmpv3_password_to_key_md5(
    const u8_t *password,     /* IN */
    size_t      passwordlen,  /* IN */
    const u8_t *engineID,     /* IN  - pointer to snmpEngineID  */
    u8_t        engineLength, /* IN  - length of snmpEngineID */
    u8_t       *key);         /* OUT - pointer to caller 16-octet buffer */

void snmpv3_password_to_key_sha(
    const u8_t *password,     /* IN */
    size_t      passwordlen,  /* IN */
    const u8_t *engineID,     /* IN  - pointer to snmpEngineID  */
    u8_t        engineLength, /* IN  - length of snmpEngineID */
    u8_t       *key);         /* OUT - pointer to caller 20-octet buffer */

#endif

#endif /* LWIP_HDR_APPS_SNMP_V3_H */


text:
package net.duckling.vmt.common.adapter;

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

import net.duckling.cloudy.common.CommonUtils;
import net.duckling.vmt.api.domain.VmtApiApp;
import net.duckling.vmt.common.config.GlobalConfig;
import net.duckling.vmt.domain.VmtApp;

import org.springframework.beans.BeanUtils;

public class VmtApiApp2VmtAppAdapter {
	public static List<VmtApiApp> convert(List<VmtApp> apps){
		if(CommonUtils.isNull(apps)){
			return new ArrayList<VmtApiApp>();
		}
		List<VmtApiApp> result=new ArrayList<VmtApiApp>();
		for(VmtApp app:apps){
			VmtApiApp apiApp=new VmtApiApp();
			BeanUtils.copyProperties(app,apiApp);
			fixAbsoluteUrl(apiApp);
			result.add(apiApp);
		}
		return result;
	}
	public static void fixAbsoluteUrl(VmtApiApp app){
		String passport=GlobalConfig.get("duckling.umt.site");
		String my=GlobalConfig.get("my.base.url");
		String prefix=null;
		if(VmtApp.APP_TYPE_LOCAL.equals(app.getAppType())){
			prefix=my+"/logo/";
		}else{
			prefix=passport;
		}
		if(!CommonUtils.isNull(app.getLogo100Url())){
			app.setLogo100Url(prefix+app.getLogo100Url());
		}
		if(!CommonUtils.isNull(app.getLogo64Url())){
			app.setLogo64Url(prefix+app.getLogo64Url());
		}
		if(!CommonUtils.isNull(app.getLogo32Url())){
			app.setLogo32Url(prefix+app.getLogo32Url());
		}
		if(!CommonUtils.isNull(app.getLogo16Url())){
			app.setLogo16Url(prefix+app.getLogo16Url());
		}
		if(!CommonUtils.isNull(app.getLogoCustomUrl())){
			app.setLogoCustomUrl(prefix+app.getLogoCustomUrl());
		}
	}
}


text:
Prufa
=====

Testing, testing


text:
/**
 * Created by Administrator on 2016/9/18.
 */
define(function(require,exports) {
    var ajaxUtil = require('util/ajaxUtil').ajaxUtil;
    var logUtil = require('util/logUtil').logUtil;
    var commonUtil = require('util/commonUtil').commonUtil;

    var controls = {};
    controls.page_node=$('#page-wrapper');

    var urls = {};
    urls.get_page_part = '/admin/page/get-part';
    urls.get_update_session = '/admin/page/update-session';
    urls.get_logout = '/admin/page/logout';

    function init() {
        bindEvent();
        initIndex();
        updateSession();
    }

    function initIndex() {
        var index = $('#navigation_left').find('.menu-text:eq(0)').data('url');
        if(index) {
            ajaxUtil.doAjaxLoad(controls.page_node,urls.get_page_part,{page:index});
        }
    }

    function bindEvent() {
        $('#navigation_left').find('li>a').bind('click',function() {
            var page = $(this).find('.menu-text:eq(0)').data('url');

            if(!page) return;

            ajaxUtil.doAjaxLoad(controls.page_node,urls.get_page_part,{page:page});
        });

        $(window).on('resize', function () {
            $(window).unbind("onresize");

            $(".jqgrid-table").each(function() {
                $(this).setGridWidth(controls.page_node.width(), true);
            });

            $(window).bind("onresize", this);
        }).resize();

        $('.hoe-sidebar-toggle').bind('click',function() {
            $(".jqgrid-table").each(function() {
                $(this).setGridWidth(controls.page_node.width(), true);
            });
        });

        $("#logout").bind('click',function() {
            ajaxUtil.doAjaxGet(urls.get_logout,{}).done(function(ret) {
                setTimeout(function(){
                    window.location.reload();
                },200)
            })
        })
    }

    function updateSession() {
        setInterval(function(){
            ajaxUtil.doAjaxGet(urls.get_update_session,null);
        },1000*60*60*2);
    }

    exports.init = init;
});