text:
from ctypes import *
import unittest

class StringBufferTestCase(unittest.TestCase):

    def test_buffer(self):
        b = create_string_buffer(32)
        self.assertEqual(len(b), 32)
        self.assertEqual(sizeof(b), 32 * sizeof(c_char))
        self.assertTrue(type(b[0]) is bytes)

        b = create_string_buffer(b"abc")
        self.assertEqual(len(b), 4) # trailing nul char
        self.assertEqual(sizeof(b), 4 * sizeof(c_char))
        self.assertTrue(type(b[0]) is bytes)
        self.assertEqual(b[0], b"a")
        self.assertEqual(b[:], b"abc\0")
        self.assertEqual(b[::], b"abc\0")
        self.assertEqual(b[::-1], b"\0cba")
        self.assertEqual(b[::2], b"ac")
        self.assertEqual(b[::5], b"a")

    def test_buffer_interface(self):
        self.assertEqual(len(bytearray(create_string_buffer(0))), 0)
        self.assertEqual(len(bytearray(create_string_buffer(1))), 1)

    try:
        c_wchar
    except NameError:
        pass
    else:
        def test_unicode_buffer(self):
            b = create_unicode_buffer(32)
            self.assertEqual(len(b), 32)
            self.assertEqual(sizeof(b), 32 * sizeof(c_wchar))
            self.assertTrue(type(b[0]) is str)

            b = create_unicode_buffer("abc")
            self.assertEqual(len(b), 4) # trailing nul char
            self.assertEqual(sizeof(b), 4 * sizeof(c_wchar))
            self.assertTrue(type(b[0]) is str)
            self.assertEqual(b[0], "a")
            self.assertEqual(b[:], "abc\0")
            self.assertEqual(b[::], "abc\0")
            self.assertEqual(b[::-1], "\0cba")
            self.assertEqual(b[::2], "ac")
            self.assertEqual(b[::5], "a")

        def test_unicode_conversion(self):
            b = create_unicode_buffer("abc")
            self.assertEqual(len(b), 4) # trailing nul char
            self.assertEqual(sizeof(b), 4 * sizeof(c_wchar))
            self.assertTrue(type(b[0]) is str)
            self.assertEqual(b[0], "a")
            self.assertEqual(b[:], "abc\0")
            self.assertEqual(b[::], "abc\0")
            self.assertEqual(b[::-1], "\0cba")
            self.assertEqual(b[::2], "ac")
            self.assertEqual(b[::5], "a")

if __name__ == "__main__":
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="icon" href="http://getbootstrap.com/favicon.ico">

    <title>AngularJS & Firebase Web App</title>

    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://getbootstrap.com/examples/signin/signin.css" rel="stylesheet">

    <link href="justified-nav.css" rel="stylesheet">

AngularJS & Firebase App!

        <form class="form-signin" role="form">
            <input  ng-model="user.email" type="email" class="form-control" placeholder="Email address" required="" autofocus="">
            <input ng-model="user.password" type="password" class="form-control" placeholder="Password" required="">

                 Sign Up</>

        <button ng-click="SignIn($event)" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
      </form>


text:
const wdioConf = require('../wdio.conf')

module.exports = function (config) {
  const baseConfig = wdioConf.config
  for (const attrname in config) {
    baseConfig[attrname] = config[attrname]
  }

  return baseConfig
}


text:
package com.github.frtu.simple.logs.bridge;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.junit.Test;
import org.slf4j.helpers.MessageFormatter;

public class MessageFormatterFormatArrayTest {
    @Test
    public void testFormat() {
        String messageFormat = "arg1={} arg2={} final text";
        Object[] arguments = new Object[] { 1, "2" };
        String format = MessageFormatter.arrayFormat(messageFormat, arguments).getMessage();
        assertEquals("arg1=1 arg2=2 final text", format);
    }

//    @Test
//    public void testFormatWithDate() {
//        Calendar calendar = new GregorianCalendar();
//        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
//        calendar.set(2014, 11, 31, 23, 59, 59);
//        calendar.set(Calendar.MILLISECOND, 999);
//        String date = "2014-12-31T23:59:59.999Z";
//
//        String messageFormat = "arg1={} arg2={} final text";
//        Object[] arguments = new Object[] { 1, calendar };
//
//        String format = MessageFormatter.arrayFormat(messageFormat, arguments).getMessage();
//        assertEquals("arg1=1 arg2=" + date + " final text", format);
//    }

    @Test
    public void testFormatWithPlaceholderAtEdges() {
        String messageFormat = "{} arg2={}";
        Object[] arguments = new Object[] { 1, "2" };
        String format = MessageFormatter.arrayFormat(messageFormat, arguments).getMessage();
        assertEquals("1 arg2=2", format);
    }

    @Test
    public void testFormatNullOrEmpty() {
        String messageFormat = "{} arg2={}";
        Object[] arguments = new Object[] { 1, "2" };

        assertNull(MessageFormatter.arrayFormat(null, arguments).getMessage());
        assertEquals(messageFormat, MessageFormatter.arrayFormat(messageFormat, null).getMessage());
        assertEquals(messageFormat, MessageFormatter.arrayFormat(messageFormat, new Object[0]).getMessage());
    }

    @Test
    public void testFormatAsymetric() {
        String messageFormat = "arg1={} arg2={} final text";
        Object[] arguments = new Object[] { 1 };
        String format = MessageFormatter.arrayFormat(messageFormat, arguments).getMessage();
        assertEquals("arg1=1 arg2={} final text", format);
    }
}


text:
module Wobsurv.Util.MasterThread where

import BasePrelude hiding (forkFinally)
import Control.Monad.Trans.Reader
import qualified BasePrelude
import qualified STMContainers.Set as Set
import qualified Wobsurv.Util.PartialHandler as H

-- |
-- A monad, which adds a functionality of forking of slave threads,
-- while binding them to their master thread in such a manner
-- that when the master is killed, they get killed too.
-- It also rethrows exceptions from the slave threads in the main thread,
-- so they don't get lost.
type MasterThread =
  ReaderT Context IO

type Context =
  (Set.Set ThreadId)

type MT =
  MasterThread

run :: MT a -> IO a
run mt =
  do
    context <- atomically $ Set.new
    catch (runReaderT mt context) $ \(e :: SomeException) -> do
      -- Kill all slaves
      traverse_ killThread =<< do
        atomically $ Set.foldM (\l -> return . (: l)) [] context
      -- Wait for all slaves to die
      atomically $ Set.null context >>= bool retry (return ())
      throwIO e

forkFinally :: MT () -> IO () -> MT ThreadId
forkFinally main finalizer =
  ReaderT $ \context -> do
    thread <- myThreadId
    slaveContext <- atomically $ Set.new
    let
      onDeath r =
        do
          -- Finalization and rethrowing of exceptions into the master thread:
          do
            r' <- try $ finalizer
            forM_ (left r <|> left r') $
              H.toTotal $ H.onThreadKilled (return ()) <> H.rethrowTo thread
          -- Context management:
          do
            traverse_ killThread =<< do
              atomically $ Set.foldM (\l -> return . (: l)) [] slaveContext
            slaveThread <- myThreadId
            -- Ensures that it waits for all slaves to die
            -- before informing the master that it died itself.
            -- And so on recursively.
            atomically $ do
              Set.null slaveContext >>= \case
                True -> Set.delete slaveThread context
                False -> retry
        where
          left = either Just (const Nothing)
    slaveThread <- BasePrelude.forkFinally (runReaderT main slaveContext) onDeath
    atomically $ Set.insert slaveThread context
    return slaveThread

fork :: MT () -> MT ThreadId
fork main =
  forkFinally main (return ())

-- |
-- Run the 'MasterThread' monad, which performs no subforking.
runWithoutForking :: MT a -> IO a
runWithoutForking mt =
  runReaderT mt (error "Attempt to fork when run with 'runWithoutForking'")


text:
package software.amazon.awssdk.services.json.model;

import software.amazon.awssdk.annotations.Generated;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.eventstream.DefaultEventStreamResponseHandlerBuilder;
import software.amazon.awssdk.awscore.eventstream.EventStreamResponseHandlerFromBuilder;

@Generated("software.amazon.awssdk:codegen")
@SdkInternalApi
final class DefaultEventStreamOperationResponseHandlerBuilder
        extends
        DefaultEventStreamResponseHandlerBuilder<EventStreamOperationResponse, EventStream, EventStreamOperationResponseHandler.Builder>
        implements EventStreamOperationResponseHandler.Builder {
    @Override
    public EventStreamOperationResponseHandler.Builder subscriber(EventStreamOperationResponseHandler.Visitor visitor) {
        subscriber(e -> e.accept(visitor));
        return this;
    }

    @Override
    public EventStreamOperationResponseHandler build() {
        return new Impl(this);
    }

    @Generated("software.amazon.awssdk:codegen")
    private static final class Impl extends EventStreamResponseHandlerFromBuilder<EventStreamOperationResponse, EventStream>
            implements EventStreamOperationResponseHandler {
        private Impl(DefaultEventStreamOperationResponseHandlerBuilder builder) {
            super(builder);
        }
    }
}


text:
/**
 * @fileoverview Externs for the pathfinding
 * @externs
 */

/**
 * @constructor
 */
PF.Heuristic = function() {};

  /**
   * @param {number} dx
   * @param {number} dy
   * @return {number}
   */
PF.Heuristic.manhattan = function(dx, dy) {};

  /**
   * @param {number} dx
   * @param {number} dy
   * @return {number}
   */
PF.Heuristic.euclidean = function(dx, dy) {};

  /**
   * @param {number} dx
   * @param {number} dy
   * @return {number}
   */
PF.Heuristic.chebyshev = function(dx, dy) {};


text:
<?php
//----------------------------------------------------------------------------
// This software is licensed under the MIT license. Use as you wish but give
// and take credit where due.
//
// Author: Paul Lemmons
//----------------------------------------------------------------------------
?>
<?php
include 'include/RegFunctions.php';

if ($Admin != 'Y')
{
   header("refresh: 0; URL=Admin.php");
   die();
}

$EventID = isset($_REQUEST['EventID']) ? $_REQUEST['EventID'] : "";
$SchedID = isset($_REQUEST['SchedID']) ? $_REQUEST['SchedID'] : "";

if ($SchedID == "" or $EventID == "")
{
   header("refresh: 0; URL=Admin.php");
   die();
}

$results = $db->query("Select  TeamEvent,
                                EventName,
                                IndividualAwards
                        from    $EventsTable
                        where   EventID = $EventID
                       ")
           or die ("Unable to determine event type:" . sqlError());
$row = $results->fetch(PDO::FETCH_ASSOC);
$EventName        = $row['EventName'];
$TeamEvent        = ($row['TeamEvent']        == 'Y');
$IndividualAwards = ($row['IndividualAwards'] == 'Y');

if ($TeamEvent)
{

   $results = $db->query("Select  c.ChurchName,
                                   c.ChurchID,
                                   concat('Team No: ',t.TeamID) Name,
                                   IFNULL(Award,'Not Assigned') Award,
                                   t.TeamID ParticipantID
                           from    $RegistrationTable r,
                                   $EventsTable       e,
                                   $ChurchesTable     c,
                                   $TeamsTable        t
                           where r.EventID       = $EventID
                           and   r.SchedID       = $SchedID
                           and   r.ParticipantID = t.TeamID
                           and   e.EventID       = r.EventID
                           and   c.ChurchID      = r.ChurchID
                           and   e.TeamEvent     = 'Y'
                           order by c.ChurchName,t.TeamID
                          ")
              or die ("Unable to get event Member list:" . sqlError());
}
else
{
   $results = $db->query("Select  p.ParticipantID,
                                   c.ChurchName,
                                   c.ChurchID,
                                   concat(p.FirstName,' ',p.LastName) Name,
                                   IFNULL(Award,'Not Assigned') Award
                           from    $RegistrationTable r,
                                   $EventsTable       e,
                                   $ParticipantsTable p,
                                   $ChurchesTable     c
                           where   r.EventID       = $EventID
                           and     r.SchedID       = $SchedID
                           and     p.ParticipantID = r.ParticipantID
                           and     e.EventID       = r.EventID
                           and     c.ChurchID      = r.ChurchID
                           and     e.TeamEvent    != 'Y'
                           order by c.ChurchName,p.LastName,p.FirstName
                          ")
              or die ("Unable to get event Member list:" . sqlError());
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <title>
         Awards Report
      </title>
      <meta http-equiv="Content-Language" content="en-us" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <link rel="stylesheet" href="include/registration.css" type="text/css" />

         <?php
         //--------------------------------------------------------------------
         // No loop through the events reporting on the details
         //--------------------------------------------------------------------
         $prevChurchName='';
         $pageBreak='';
         while ($row = $results->fetch(PDO::FETCH_ASSOC))
         {
            $ChurchName      = $row['ChurchName'];
            $ChurchID        = $row['ChurchID'];
            $ParticipantID   = $row['ParticipantID'];
            $PatricipantName = $row['Name'];
            $Award           = $row['Award'];

            if ($TeamEvent)
            {
               $memberCnt = $db->query("select count(*) count
                                         from   $TeamMembersTable  m
                                         where  m.TeamID = $ParticipantID
                                       ")
                           or die ("Unable to get event Team Member list:" . sqlError());
               $row         = $memberCnt->fetch(PDO::FETCH_ASSOC);
               $MemberCount = $row['count'];
            }
            else
               $MemberCount = 0;

            if ((!$TeamEvent) or ($TeamEvent and $MemberCount > 0))
            {
               if ($prevChurchName != $ChurchName)
               {
                  if ($prevChurchName != '')
                  {
                  ?>

                  <?php
                  }
                  ?>
                  <div <?php print $pageBreak;$pageBreak="style=\"page-break-before:always;\"";?>>

Awards Report

<?php print $EventName?>

                  <?php
                     if (isset($_REQUEST['Warn']))
                        print "
*** Warning there are entries without awards Assigned ***
"
                  ?>

               <?php
                  $prevChurchName = $ChurchName;
               }
               ?>

                  <?php print $ChurchName;?>
                  <?php print $EventName;?>
                  <?php print $PatricipantName;?>
                  <?php print $Award;?>

            <?php
               if ($TeamEvent)
               {
                  $memberList = $db->query("select concat(p.FirstName,' ',p.LastName) MemberName,
                                                    IFNULL(m.Award,'Not Assigned') Award
                                             from   $ParticipantsTable p,
                                                    $TeamMembersTable  m
                                             where  m.TeamID        = $ParticipantID
                                             and    p.ParticipantID = m.ParticipantID
                                             order by p.LastName
                                            ")
                                or die ("Unable to get event Team Member list:" . sqlError());
                  while ($row = $memberList->fetch(PDO::FETCH_ASSOC))
                  {
                     $MemberName      = $row['MemberName'];
                  ?>

                        <?php print $MemberName?>
                        <?php
                        if ($IndividualAwards)
                        {
                           $Award = $row['Award'];
                        ?>
                           <?php print $Award?>
                        <?php
                        }
                        else
                        {
                        ?>

                        <?php
                        }
                        ?>

                  <?php
                  }
               }
            }
         }
         ?>


text:
package br.com.sabium;

import java.io.IOException;

import org.eclipse.jgit.api.errors.GitAPIException;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import br.com.sabium.GitVersion;

@RunWith(JUnit4.class)
public class GitVersionTest {
    private static final String TAG_PATTERN = "(\\d+\\.\\d+\\.\\d+)(.*)$";
    static GitVersion buildVersion;

    @BeforeClass
    public static void setup() {
        buildVersion = new GitVersion("/home/michel/WorkspaceGit/MeuWorkspace/libs-sabium-i18n");
    }

    @Test
    public void testGetLatestReleaseTag() throws Exception {
        Assert.assertTrue(buildVersion.getLatestReleaseTag("^v(\\d+\\.\\d+\\.\\d+)(.*)$")
                                      .matches("^v(\\d+\\.\\d+\\.\\d+)(.*)$"));
    }

    @Test
    public void testNextPreReleaseVersion() throws IOException, GitAPIException {
        Assert.assertEquals("2.3.1-rc.1", buildVersion.nextPreReleaseVersion("2.3.0", TAG_PATTERN));
        Assert.assertEquals("2.3.2-rc.2", buildVersion.nextPreReleaseVersion("2.3.2-rc.1", TAG_PATTERN));
    }

    @Test
    public void testNextReleaseVersion() {
        Assert.assertEquals("2.3.1", buildVersion.nextReleaseVersion("2.3.1-rc.5", TAG_PATTERN));
        Assert.assertEquals("2.3.1", buildVersion.nextReleaseVersion("2.3.0", TAG_PATTERN));
    }

    @Test
    public void testNextSnapshotVersion() {
        Assert.assertEquals("2.3.0", buildVersion.nextSnapshotVersion("2.2.1", TAG_PATTERN));
        Assert.assertEquals("2.6.0", buildVersion.nextSnapshotVersion("2.5.9-rc.1", TAG_PATTERN));
    }
}


text:
function [ns] = ms2ns(ms)
% Convert time from milliseconds to nanoseconds.
% Chad Greene 2012
ns = ms*1000000 ;


text:
class Solution(object):
    def findNthDigit(self, n):
        """
        :type n: int
        :rtype: int
        """
        # math: number of n digit: n*9*10^(n-1)
        digitcnt,digitbase=1,9
        # 1. get the candicate digit count,11 locate in 2
        while n>digitcnt*digitbase:
            n-=digitcnt*digitbase
            digitcnt+=1
            digitbase*=10
        # n already minus the g(n-1)
        # n start with the range first number
        rangeidx=(n-1)/digitcnt
        numidx=(n-1)%digitcnt
        num=10**(digitcnt-1)+rangeidx
        return int(str(num)[numidx])


text:
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
	public float walkSpeed = 20f;
	public float runSpeed = 50f;
	public float rollSpeed = 200f;
	public float speed = 5f;
	Vector3 movement;
	Animator anim;
	Rigidbody rb;
	int JumpHeight = 1600;
	float gravity = -50f;
	AudioSource catAudio;

	public bool IsGrounded;
	//private AnimatorStateInfo currentBaseState;

	void Awake(){
		anim = GetComponent <Animator> ();
		rb = GetComponent <Rigidbody> ();
		catAudio = GetComponent<AudioSource> ();
	}
	void Update(){
		float moveHorizontal = Input.GetAxisRaw ("Horizontal");
		float moveVertical = Input.GetAxisRaw ("Vertical");
		Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

		if (Input.GetKey ("left shift")) {
			speed = walkSpeed;
		}
		if (Input.GetKeyDown("space")){
			Jump ();
		}

		//currentBaseState = anim.GetCurrentAnimatorStateInfo(0);
		rb.AddForce(movement * speed);
		Physics.gravity = new Vector3(0, gravity, 0);
		//movement.y -= gravity * Time.deltaTime;
		Move (moveHorizontal,moveVertical);
		Turning (moveHorizontal, moveVertical);
		Animating (moveHorizontal,moveVertical);

	}

	void Move (float h, float v){
		movement.Set (h,0f,v);
		movement = movement.normalized * speed * Time.deltaTime;
		rb.MovePosition (transform.position + movement);
	}
	public void Jump(){
		if (IsGrounded) {
			anim.SetTrigger ("Jump");
			catAudio.Play ();
			rb.AddForce(Vector3.up * JumpHeight);
			IsGrounded = false;
		}
	}

	void OnCollisionStay(Collision collisionInfo) {
		//we are on something
		if ( CollisionFlags.CollidedBelow != 0)
		{
			IsGrounded = true;
		}

	}

	void Turning(float h, float v){
		bool walking = h !=0f || v !=0f;
		if (walking) {
			transform.forward = Vector3.Normalize(new Vector3(h, 0f,v));
		}
	}

	void Animating(float h, float v){
		bool walking = h !=0f || v !=0f;
		anim.SetBool ("IsWalking", walking);
		speed = walkSpeed;
		if (Input.GetKeyDown ("r")) {
			anim.SetTrigger ("Roll");
			speed = rollSpeed;
		}
	}

}


text:
import os
import sys
import json
import itertools
from typing import Any, List
import unittest

import gpu_path_util
from gpu_tests import common_typing as ct
from gpu_tests import gpu_integration_test

html_path = os.path.join(gpu_path_util.CHROMIUM_SRC_DIR, 'content', 'test',
                         'data', 'gpu', 'webcodecs')
data_path = os.path.join(gpu_path_util.CHROMIUM_SRC_DIR, 'media', 'test',
                         'data')
four_colors_img_path = os.path.join(data_path, 'four-colors.y4m')

frame_sources = [
    'camera', 'capture', 'offscreen', 'arraybuffer', 'hw_decoder', 'sw_decoder'
]
video_codecs = ['avc1.42001E', 'vp8', 'vp09.00.10.08', 'av01.0.04M.08']
accelerations = ['prefer-hardware', 'prefer-software']

class WebCodecsIntegrationTest(gpu_integration_test.GpuIntegrationTest):
  @classmethod
  def Name(cls) -> str:
    return 'webcodecs'

# pylint: disable=too-many-branches

  @classmethod
  def GenerateGpuTests(cls, options: ct.ParsedCmdArgs) -> ct.TestGenerator:
    tests = itertools.chain(cls.GenerateFrameTests(), cls.GenerateVideoTests(),
                            cls.GenerateAudioTests())
    for test in tests:
      yield test

  @classmethod
  def GenerateFrameTests(cls) -> ct.TestGenerator:
    for source_type in frame_sources:
      yield ('WebCodecs_DrawImage_' + source_type, 'draw-image.html', [{
          'source_type':
          source_type
      }])
      yield ('WebCodecs_TexImage2d_' + source_type, 'tex-image-2d.html', [{
          'source_type':
          source_type
      }])
      yield ('WebCodecs_copyTo_' + source_type, 'copyTo.html', [{
          'source_type':
          source_type
      }])
      yield ('WebCodecs_GPUExternalTexture_expired_' + source_type,
             'gpu-external-texture-expired.html', [{
                 'source_type': source_type,
                 'use_worker': False
             }])
      yield ('WebCodecs_GPUExternalTexture_expired_worker_' + source_type,
             'gpu-external-texture-expired.html', [{
                 'source_type': source_type,
                 'use_worker': True
             }])
      yield ('WebCodecs_device_destroy_expired_texture_' + source_type,
             'gpu-device-destroy-expire-active-external-texture.html', [{
                 'source_type':
                 source_type,
                 'device_destroyed_before_import':
                 False
             }])
      yield ('WebCodecs_texture_expired_from_destroyed_device_' + source_type,
             'gpu-device-destroy-expire-active-external-texture.html', [{
                 'source_type':
                 source_type,
                 'device_destroyed_before_import':
                 True
             }])

  @classmethod
  def GenerateAudioTests(cls) -> ct.TestGenerator:
    yield ('WebCodecs_AudioEncoding_AAC_LC', 'audio-encode-decode.html', [{
        'codec':
        'mp4a.67',
        'sample_rate':
        48000,
        'channels':
        2
    }])

  @classmethod
  def GenerateVideoTests(cls) -> ct.TestGenerator:
    yield ('WebCodecs_WebRTCPeerConnection_Window',
           'webrtc-peer-connection.html', [{
               'use_worker': False
           }])
    yield ('WebCodecs_WebRTCPeerConnection_Worker',
           'webrtc-peer-connection.html', [{
               'use_worker': True
           }])

    for codec in video_codecs:
      yield ('WebCodecs_EncodeDecode_' + codec, 'encode-decode.html', [{
          'codec':
          codec
      }])

    for source_type in frame_sources:
      for codec in video_codecs:
        for acc in accelerations:
          args = (source_type, codec, acc)
          yield ('WebCodecs_Encode_%s_%s_%s' % args, 'encode.html', [{
              'source_type':
              source_type,
              'codec':
              codec,
              'acceleration':
              acc
          }])

    for codec in video_codecs:
      for acc in accelerations:
        for bitrate_mode in ['constant', 'variable']:
          for latency_mode in ['realtime', 'quality']:
            source_type = 'offscreen'
            args = (source_type, codec, acc, bitrate_mode, latency_mode)
            yield ('WebCodecs_EncodingModes_%s_%s_%s_%s_%s' % args,
                   'encoding-modes.html', [{
                       'source_type': source_type,
                       'codec': codec,
                       'acceleration': acc,
                       'bitrate_mode': bitrate_mode,
                       'latency_mode': latency_mode
                   }])

    for codec in video_codecs:
      for layers in [2, 3]:
        args = (codec, layers)
        yield ('WebCodecs_SVC_%s_layers_%d' % args, 'svc.html', [{
            'codec':
            codec,
            'layers':
            layers
        }])

    for codec in video_codecs:
      for acc in accelerations:
        args = (codec, acc)
        yield ('WebCodecs_EncodeColorSpace_%s_%s' % args,
               'encode-color-space.html', [{
                   'codec': codec,
                   'acceleration': acc
               }])
# pylint: enable=too-many-branches

  def RunActualGpuTest(self, test_path: str, args: ct.TestArgs) -> None:
    url = self.UrlOfStaticFilePath(html_path + '/' + test_path)
    tab = self.tab
    arg_obj = args[0]
    os_name = self.platform.GetOSName()
    arg_obj['validate_camera_frames'] = self.CameraCanShowFourColors(os_name)
    tab.Navigate(url)
    tab.action_runner.WaitForJavaScriptCondition(
        'document.readyState == "complete"')
    tab.EvaluateJavaScript('TEST.run(' + json.dumps(arg_obj) + ')')
    tab.action_runner.WaitForJavaScriptCondition('TEST.finished', timeout=60)
    if tab.EvaluateJavaScript('TEST.skipped'):
      self.skipTest('Skipping test:' + tab.EvaluateJavaScript('TEST.summary()'))
    if not tab.EvaluateJavaScript('TEST.success'):
      self.fail('Test failure:' + tab.EvaluateJavaScript('TEST.summary()'))

  @staticmethod
  def CameraCanShowFourColors(os_name: str) -> bool:
    return os_name not in ('android', 'chromeos')

  @classmethod
  def SetUpProcess(cls) -> None:
    super(WebCodecsIntegrationTest, cls).SetUpProcess()
    args = [
        '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream',
        '--enable-unsafe-webgpu'
    ]

    # If we don't call CustomizeBrowserArgs cls.platform is None
    cls.CustomizeBrowserArgs(args)
    platform = cls.platform

    if cls.CameraCanShowFourColors(platform.GetOSName()):
      args.append('--use-file-for-fake-video-capture=' + four_colors_img_path)
      cls.CustomizeBrowserArgs(args)

    cls.StartBrowser()
    cls.SetStaticServerDirs([html_path, data_path])

  @classmethod
  def ExpectationsFiles(cls) -> List[str]:
    return [
        os.path.join(os.path.dirname(os.path.abspath(__file__)),
                     'test_expectations', 'webcodecs_expectations.txt')
    ]

def load_tests(loader: unittest.TestLoader, tests: Any,
               pattern: Any) -> unittest.TestSuite:
  del loader, tests, pattern  # Unused.
  return gpu_integration_test.LoadAllTestsInModule(sys.modules[__name__])


text:
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.NetAnalyzers;
using Microsoft.CodeAnalysis.Operations;

namespace Microsoft.NetCore.Analyzers.Runtime
{
    using static MicrosoftNetCoreAnalyzersResources;

    /// <summary>
    /// CA1307: Specify StringComparison
    /// </summary>
    [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
    public sealed class SpecifyStringComparisonAnalyzer : AbstractGlobalizationDiagnosticAnalyzer
    {
        private const string RuleId_CA1307 = "CA1307";
        private const string RuleId_CA1310 = "CA1310";

        private static readonly ImmutableArray<string> s_CA1310MethodNamesWithFirstStringParameter =
            ImmutableArray.Create("Compare", "StartsWith", "EndsWith", "IndexOf", "LastIndexOf");

        internal static readonly DiagnosticDescriptor Rule_CA1307 = DiagnosticDescriptorHelper.Create(
            RuleId_CA1307,
            CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1307Title)),
            CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1307Message)),
            DiagnosticCategory.Globalization,
            RuleLevel.Disabled,
            description: CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1307Description)),
            isPortedFxCopRule: true,
            isDataflowRule: false);

        internal static readonly DiagnosticDescriptor Rule_CA1310 = DiagnosticDescriptorHelper.Create(
            RuleId_CA1310,
            CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1310Title)),
            CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1310Message)),
            DiagnosticCategory.Globalization,
            RuleLevel.IdeHidden_BulkConfigurable,
            description: CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1310Description)),
            isPortedFxCopRule: false,
            isDataflowRule: false);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule_CA1307, Rule_CA1310);

        protected override void InitializeWorker(CompilationStartAnalysisContext context)
        {
            var stringComparisonType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemStringComparison);
            var stringType = context.Compilation.GetSpecialType(SpecialType.System_String);

            // Without these symbols the rule cannot run
            if (stringComparisonType == null)
            {
                return;
            }

            var overloadMap = GetWellKnownStringOverloads(context.Compilation, stringType, stringComparisonType);

            var linqExpressionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemLinqExpressionsExpression1);

            context.RegisterOperationAction(oaContext =>
            {
                var invocationExpression = (IInvocationOperation)oaContext.Operation;
                var targetMethod = invocationExpression.TargetMethod;

                if (targetMethod.IsGenericMethod ||
                    targetMethod.ContainingType == null ||
                    targetMethod.ContainingType.IsErrorType())
                {
                    return;
                }

                // Check if we are in a Expression<Func<T...>> context, in which case it is possible
                // that the underlying call doesn't have the comparison option so we want to bail-out.
                if (invocationExpression.IsWithinExpressionTree(linqExpressionType))
                {
                    return;
                }

                // Report correctness issue CA1310 for known string comparison methods that default to culture specific string comparison:
                // https://learn.microsoft.com/dotnet/standard/base-types/best-practices-strings#string-comparisons-that-use-the-current-culture
                if (targetMethod.ContainingType.SpecialType == SpecialType.System_String &&
                    !overloadMap.IsEmpty &&
                    overloadMap.ContainsKey(targetMethod))
                {
                    ReportDiagnostic(
                        Rule_CA1310,
                        oaContext,
                        invocationExpression,
                        targetMethod,
                        overloadMap[targetMethod]);

                    return;
                }

                // Report maintainability issue CA1307 for any method that has an additional overload with the exact same parameter list,
                // plus as additional StringComparison parameter. Default StringComparison may or may not match user's intent,
                // but it is recommended to explicitly specify it for clarity and readability:
                // https://learn.microsoft.com/dotnet/standard/base-types/best-practices-strings#recommendations-for-string-usage
                IEnumerable<IMethodSymbol> methodsWithSameNameAsTargetMethod = targetMethod.ContainingType.GetMembers(targetMethod.Name).OfType<IMethodSymbol>();
                if (methodsWithSameNameAsTargetMethod.HasMoreThan(1))
                {
                    var correctOverload = methodsWithSameNameAsTargetMethod
                                            .GetMethodOverloadsWithDesiredParameterAtTrailing(targetMethod, stringComparisonType)
                                            .FirstOrDefault();

                    if (correctOverload != null)
                    {
                        ReportDiagnostic(
                            Rule_CA1307,
                            oaContext,
                            invocationExpression,
                            targetMethod,
                            correctOverload);
                    }
                }
            }, OperationKind.Invocation);

            static ImmutableDictionary<IMethodSymbol, IMethodSymbol> GetWellKnownStringOverloads(
                Compilation compilation,
                INamedTypeSymbol stringType,
                INamedTypeSymbol stringComparisonType)
            {
                var objectType = compilation.GetSpecialType(SpecialType.System_Object);
                var booleanType = compilation.GetSpecialType(SpecialType.System_Boolean);
                var integerType = compilation.GetSpecialType(SpecialType.System_Int32);
                var stringCompareToNamedMethods = stringType.GetMembers("CompareTo").OfType<IMethodSymbol>();
                var stringCompareToParameterString = stringCompareToNamedMethods.GetFirstOrDefaultMemberWithParameterInfos(
                                                         GetParameterInfo(stringType));
                var stringCompareToParameterObject = stringCompareToNamedMethods.GetFirstOrDefaultMemberWithParameterInfos(
                                                         GetParameterInfo(objectType));

                var stringCompareNamedMethods = stringType.GetMembers("Compare").OfType<IMethodSymbol>();
                var stringCompareParameterStringStringBool = stringCompareNamedMethods.GetFirstOrDefaultMemberWithParameterInfos(
                                                                 GetParameterInfo(stringType),
                                                                 GetParameterInfo(stringType),
                                                                 GetParameterInfo(booleanType));
                var stringCompareParameterStringStringStringComparison = stringCompareNamedMethods.GetFirstOrDefaultMemberWithParameterInfos(
                                                                             GetParameterInfo(stringType),
                                                                             GetParameterInfo(stringType),
                                                                             GetParameterInfo(stringComparisonType));
                var stringCompareParameterStringIntStringIntIntBool = stringCompareNamedMethods.GetFirstOrDefaultMemberWithParameterInfos(
                                                                          GetParameterInfo(stringType),
                                                                          GetParameterInfo(integerType),
                                                                          GetParameterInfo(stringType),
                                                                          GetParameterInfo(integerType),
                                                                          GetParameterInfo(integerType),
                                                                          GetParameterInfo(booleanType));
                var stringCompareParameterStringIntStringIntIntComparison = stringCompareNamedMethods.GetFirstOrDefaultMemberWithParameterInfos(
                                                                                GetParameterInfo(stringType),
                                                                                GetParameterInfo(integerType),
                                                                                GetParameterInfo(stringType),
                                                                                GetParameterInfo(integerType),
                                                                                GetParameterInfo(integerType),
                                                                                GetParameterInfo(stringComparisonType));

                var overloadMapBuilder = ImmutableDictionary.CreateBuilder<IMethodSymbol, IMethodSymbol>();
                overloadMapBuilder.AddKeyValueIfNotNull(stringCompareToParameterString, stringCompareParameterStringStringStringComparison);
                overloadMapBuilder.AddKeyValueIfNotNull(stringCompareToParameterObject, stringCompareParameterStringStringStringComparison);
                overloadMapBuilder.AddKeyValueIfNotNull(stringCompareParameterStringStringBool, stringCompareParameterStringStringStringComparison);
                overloadMapBuilder.AddKeyValueIfNotNull(stringCompareParameterStringIntStringIntIntBool, stringCompareParameterStringIntStringIntIntComparison);

                foreach (var methodName in s_CA1310MethodNamesWithFirstStringParameter)
                {
                    var methodsWithMethodName = stringType.GetMembers(methodName).OfType<IMethodSymbol>();
                    foreach (var method in methodsWithMethodName)
                    {
                        if (!method.Parameters.IsEmpty &&
                            method.Parameters[0].Type.SpecialType == SpecialType.System_String &&
                            !method.Parameters[^1].Type.Equals(stringComparisonType))
                        {
                            var recommendedMethod = methodsWithMethodName
                                                    .GetMethodOverloadsWithDesiredParameterAtTrailing(method, stringComparisonType)
                                                    .FirstOrDefault();
                            if (recommendedMethod != null)
                            {
                                overloadMapBuilder.AddKeyValueIfNotNull(method, recommendedMethod);
                            }
                        }
                    }
                }

                return overloadMapBuilder.ToImmutable();
            }
        }

        private static void ReportDiagnostic(
            DiagnosticDescriptor rule,
            OperationAnalysisContext oaContext,
            IInvocationOperation invocationExpression,
            IMethodSymbol targetMethod,
            IMethodSymbol correctOverload)
        {
            oaContext.ReportDiagnostic(
                invocationExpression.CreateDiagnostic(
                    rule,
                    targetMethod.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat),
                    oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat),
                    correctOverload.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
        }

        private static ParameterInfo GetParameterInfo(INamedTypeSymbol type, bool isArray = false, int arrayRank = 0, bool isParams = false)
        {
            return ParameterInfo.GetParameterInfo(type, isArray, arrayRank, isParams);
        }
    }
}


text:
package me.yifeiyuan.utils;

import android.os.Environment;

/**
 * Created by 程序亦非猿 on 15/12/28.
 */
public class SDCardUtil {

    private SDCardUtil() {
        //no instance
        throw new AssertionError("No instances.");
    }

    /**
     * @return 外部SD卡是否可用
     */
    public static boolean isSDCardMounted(){
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }
}


text:
'use strict';
const app = rootRequire('src/app');
const alexia = require('alexia');

describe('(Alexa Skill) App', () => {
  it('should create app', () => {
    expect(app).to.be.ok;
  });

  it('should register all intents', () => {
    const intentNames = Object.keys(app.intents);
    expect(intentNames).to.have.length.above(0);
  });

  it('should handle LaunchRequest', done => {
    const launchRequest = alexia.createLaunchRequest();

    app.handle(launchRequest, data => {
      const text = data.response.outputSpeech.text;
      expect(text).to.equal('Welcome to Alexia Starter Kit 7');
      done();
    });
  });
});


text:
#import "EC2DescribeInstanceAttributeRequestMarshaller.h"

@implementation EC2DescribeInstanceAttributeRequestMarshaller

+(AmazonServiceRequest *)createRequest:(EC2DescribeInstanceAttributeRequest *)describeInstanceAttributeRequest
{
    AmazonServiceRequest *request = [[EC2Request alloc] init];

    [request setParameterValue:@"DescribeInstanceAttribute"           forKey:@"Action"];
    [request setParameterValue:@"2013-10-15"   forKey:@"Version"];

    [request setDelegate:[describeInstanceAttributeRequest delegate]];
    [request setCredentials:[describeInstanceAttributeRequest credentials]];
    [request setEndpoint:[describeInstanceAttributeRequest requestEndpoint]];
    [request setRequestTag:[describeInstanceAttributeRequest requestTag]];

    if (describeInstanceAttributeRequest != nil) {
        if (describeInstanceAttributeRequest.dryRunIsSet) {
            [request setParameterValue:(describeInstanceAttributeRequest.dryRun ? @"true":@"false") forKey:[NSString stringWithFormat:@"%@", @"DryRun"]];
        }
    }
    if (describeInstanceAttributeRequest != nil) {
        if (describeInstanceAttributeRequest.instanceId != nil) {
            [request setParameterValue:[NSString stringWithFormat:@"%@", describeInstanceAttributeRequest.instanceId] forKey:[NSString stringWithFormat:@"%@", @"InstanceId"]];
        }
    }
    if (describeInstanceAttributeRequest != nil) {
        if (describeInstanceAttributeRequest.attribute != nil) {
            [request setParameterValue:[NSString stringWithFormat:@"%@", describeInstanceAttributeRequest.attribute] forKey:[NSString stringWithFormat:@"%@", @"Attribute"]];
        }
    }

    return [request autorelease];
}

@end


text:
from JumpScale import j

import JumpScale.grid.zdaemon

j.application.start("zdaemon")

j.logger.consoleloglevel = 6

zd = j.core.zdaemon.getZDaemon(port=3333, nrCmdGreenlets=50)

class MyCommands():

    def __init__(self, daemon):
        self.daemon = daemon

    def authenticate(self, user, login, **args):
        return True  # will authenticall all (is std)

    def pingcmd(self, **args):
        return "pong"

    def echo(self, msg="", **args):
        return msg

zd.addCMDsInterface(MyCommands,"acategory")  # pass as class not as object !!!
zd.start()

j.application.stop()


text:
import { Component, OnInit } from '@angular/core';
import { DiscourseService } from '../shared/discourseService/discourse.service';
import { DataService } from '../shared/dataService/data-service.service';

@Component({
  selector: 'app-get-involved',
  templateUrl: './get-involved.component.html',
  styleUrls: ['./get-involved.component.scss']
})
export class GetInvolvedComponent implements OnInit {

  tid;
  cid;
  think;
  res;
  err;

  constructor(private discoursesvcWwd: DiscourseService, private datasvcGi: DataService) { }

  ngOnInit() {
  }

  postDataToServer(raw: string) {
    this.tid = '67';
    this.cid = '12';
    this.res = '';
    this.err = '';
    this.discoursesvcWwd.postDiscoursePostRestful(raw, this.cid, this.tid)
      .subscribe(
      data => this.res = data,
      err => {
        this.err = err,
          console.log(err)
      },
      () => console.log('POST Complete')
      );
  }

}


text:
var babylon = (function () {
	var pagesTitle = "Babylon 10 Translation Software and Dictionary Tool";
	var disFromTop, pageToLoad, topHP, isHP, hpAnimatevar;
	var refUrlIE = true;
	var isJSfooter = false;
	var page = location.pathname;
	if ( !$.browser.msie ) {
		var num665 = "655px";
	}
	if ( $.browser.msie ) {
		var num665 = "690px";
	}

	backToHomePage = true;

	var hrefHP1 = "/";
	var hrefHP2 = "/index";
	var hrefHP3 = "/index.html";
	var hrefHP4 = "#index";

	var urlHashIE = function () {
		if ( window.location.hash ) {
			var a = window.location.hash;
			a = a.split("#");
			a = a[1].split('&')[0];
			window.location.hash = a;
		}
		return a;
	};

	var loadHashIE = function () {
		if ( window.location.hash ) {
			var a = window.location.hash;
			a = a.split("#");
			a = a[1].split('&')[0];
			a = a.split("?")[0];
		}
		return a;
	};

	var checkHomePage = function () {

		if ( location.pathname == hrefHP1 || location.pathname == hrefHP2 || location.pathname == hrefHP3 ) {
			isHP = true;
			$('.wrapNav').css('top','450px !important');

		}

	};

	var jsFotter = function () {
	    return isJSfooter;
	};

	var menuLangBar = function (HC) {

		$('.menuLangBar').html($(HC).children('.menuLangBar2').html());
		$('.menuLangBar2').remove();

	};

	// click on navigation bar and ajax loader
	var clickLinkIe = true;
	$('a[data-link="inner"]').live('click', function (e) {
		$('body').children().each(function(){
			if ( $(this).attr('class') != "wrapheader" && $(this).attr('class') != "content" && $(this).attr('class') != "wrapfooter" ) {
				 $(this).remove()
			}
		});
		historyBackButton();
		clickLinkIe = true;
		if ( $.browser.msie )
			page = location.hash;
		$('.nav li a').removeAttr('class');

		refUrlIE = false;
		$('#tohomepage').attr("data-link", "inner");
		$('#tohomepage').attr("href", "http://www.babylon.com");
		var disFromTopOS = ($(".wraphead").outerHeight()+"px");
		var homePage = false;
		var skip = true;

		pageToLoad = $(this).attr('href');

		if ( $(this).attr('href') == "http://www.babylon.com" ) {
			pageToLoad = "/index";
		}

		// checking about HP
		if ( ( $(this).attr("href") == "index" || $(this).attr("href") == "/" || $(this).attr("href") == "index.html" ) && ( location.pathname == hrefHP1 || location.pathname == hrefHP2 || location.pathname == hrefHP3 ) ) {
			loadContent(pageToLoad);
		}
		else {
			if ( !$.browser.msie ) {
				if ( pageToLoad == "/index" && isHP ) {
					loadContent(pageToLoad);
					homePage = true;
					isHP = false;
				} // go to HP
				if ( pageToLoad == "/index" ) {
					backToHP(pageToLoad, num665);
					$('#tohomepage').removeAttr("data-link");
					$('#tohomepage').removeAttr("href");
					homePage = true;
					skip = false;
				} // leaving HP
				if ( ( location.pathname == hrefHP1 || location.pathname == hrefHP2 || location.pathname == hrefHP3 || location.hash == hrefHP4 ) && skip ) {
					hpAnimate(pageToLoad, disFromTopOS);
					topHP = num665;
					homePage = true;
				}
				else if ( !homePage ) {
					loadContent(pageToLoad);
				}
			}

			if ( $.browser.msie ) {
				urlHashIE();
				if ( pageToLoad == "/index" ) {
					backToHP(pageToLoad , num665);
					$('#tohomepage').removeAttr("data-link");
					$('#tohomepage').removeAttr("href");
					homePage = true;
					isHP = false;
				} // go to HP
				if ( page.replace('#','') == hrefHP4.replace('#','/') || ( location.pathname == hrefHP2 && !window.location.hash ) || ( location.pathname == hrefHP1 && !window.location.hash ) ) {
					hpAnimate(pageToLoad, disFromTopOS);
					homePage = true;
					skip = false;
				}
				else if ( !homePage && ( location.hash != hrefHP4 ) && page != "#/index" ) {
					loadContent(pageToLoad);
				}
			}
		}
		if ( !$.browser.msie )
			window.history.pushState(null, pagesTitle, pageToLoad);
		if ( $.browser.msie ) {
			page = location.hash;
			location.hash = pageToLoad;
		}
		e.preventDefault();
	});

	// make sure the back and forword working
	var historyBackButton = function () {
		(function resumeLoadHistory () {
			window.onpopstate = function (event) {
				var skip = true;
				var beforeUrlChange = true;
				pageToLoad = location.pathname;

				if ( true ) {
					$('.wrap_footer').hide();
					loadContent(pageToLoad);

					if ( pageToLoad != "/index" && pageToLoad != "/" ) {
						//$(".wrapNav").css('position','fixed');
						//$(".wrapNav").css('top','64px');
						$('#tohomepage').attr("data-link", "inner");
						$('#tohomepage').attr("href", "http://www.babylon.com");
					}
					else if ( pageToLoad == "/index" || pageToLoad == "/" ) {
						$('#tohomepage').removeAttr("data-link");
						$('#tohomepage').removeAttr("href");
						//$(".wrapNav").css('position','absolute');
						//$(".wrapNav").css('top','655px');
					}
					$('.deletPageCss').remove();
				}
				History.pushState(null, pagesTitle, pageToLoad);
				hpAnimatevar = true;
				event.preventDefault();
			};
		})();
	};
	if ( $.browser.msie ) {
		var hashChangeIE = (function () { // back button in IE
			$(window).bind('hashchange', function () {
				if ( !clickLinkIe ) {
					loadContent(location.hash.replace('#',''));
					if ( location.hash == "#/index" || location.hash == "#/" ) {
						setTimeout(function(){
							//$(".wrapNav").css('position','absolute');
							//$(".wrapNav").css('top','655px');
						},100);
					}
					if ( location.hash == "" && (location.pathname == "/" || location.pathname == "/index" || location.pathname == "//index") ) {
						setTimeout(function(){
							//$(".wrapNav").css('position','absolute');
							//$(".wrapNav").css('top','655px');
						},100);
					}
					else if ( location.hash != "" ) {
						//$(".wrapNav").css('position','fixed');
						//$(".wrapNav").css('top','64px');
					}
				}
				clickLinkIe = false;
			});
		})();
	}

	var checkIfContentEmpty = function (e,url) {
		if ( e == "" ) {
			window.location.href = "http://" + location.host + url;
		}
	};
	// if leave Hp
	var hpAnimate = function (url, headHiegth) {
		$('.wrap_footer').hide();
		var holdHTML = $('.content').html();
		$(".content").before('

');
		$('.content').html('');
		$(".content").hide();
		$('.wrap_footer').hide();
		$(".holdHTML").html(holdHTML);
		$(".holdHTML").show();
		$(".holdHTML").animate({ marginTop: '-1150px' }, 1700, function () {
			var HC = "";
			var holdHead = "";
			var holdBody = "";
			$.post(url + '.html', function(e){
				HC = e;
				pagesTitle = e.split(/(?:<title>|<\/title>)/ig)[1];
				document.title = pagesTitle;
				setTimeout(function(){
					menuLangBar(HC)
				},2000);
				$(".nav a[href='"+url+"']").attr('class','navCurrent');
				holdHead = HC.split(/(?:|<\/head>)/ig)[1];
				holdHead = $(holdHead).filter('.removePageCss')
				holdBody = HC.split(/(?:|<\/body>)/ig)[1];
				var splitBody = "";
				var splitBody2 = $(holdBody).filter('.content').html();
				holdBody = splitBody2 + splitBody;
				$('.content').hide();
				$('.wrap_footer').hide();
				$('.content').html(holdBody);
				checkIfContentEmpty(e, url);
				checkStyleCSS(holdHead);
			});

			$(".holdHTML").remove();
			$(".content").css('margin-top','0px');
			$('.deletPageCss').remove();

		});
		$('.content').delay(2000).fadeIn();
		$('.wrapcontiner').delay(2000).fadeIn();
		$('.wrap_footer').delay(2800).fadeIn();
		//$(".wrapNav").css('position','fixed');
		/*if ( !$.browser.msie ) {
			$(".wrapNav").css('top','753px');
		}
		if ( $.browser.msie ) {
			$(".wrapNav").css('top','788px');
		}*/
		//$(".wrapNav").animate({ top: headHiegth }, 1250);
		$('.content title').remove();
		hpAnimatevar = false;
	};

	// if back to HP
	var backToHP = function (url, topHP) {
		$('body,html').animate({ scrollTop: 0 }, 100);
		$('.wrap_footer').hide();
		var contentHeight = 955;    // HP height
		var holdHTML = $('.content').html();
		$(".content").after('

');
		$(".holdHTML").css('visibility','hidden');
		$('.content').html('');

		var HC = "";
		var holdHead = "";
		var holdBody = "";
		$.post(url + '.html', function(e){
			HC = e;
			pagesTitle = e.split(/(?:<title>|<\/title>)/ig)[1];
			document.title = pagesTitle;
			setTimeout(function(){
				menuLangBar(HC)
			},2000);
			$(".nav a[href='"+url+"']").attr('class','navCurrent');
			holdHead = HC.split(/(?:|<\/head>)/ig)[1];
			holdHead = $(holdHead).filter('.removePageCss')
			holdBody = HC.split(/(?:|<\/body>)/ig)[1];
			var splitBody = "";
			var splitBody2 = $(holdBody).filter('.content').html();
			holdBody = splitBody2 + splitBody;
			$('.content').html(holdBody);
			checkIfContentEmpty(e, url);
			checkStyleCSS(holdHead);
		});
		$(".holdHTML").css('height','5000px');
		$(".content").css("margin-top", "-1150px");
		$(".holdHTML").html(holdHTML);
		$(".content").animate({ marginTop: "0px" }, 1500,
			function () {
				$(".holdHTML").remove();
				$('.deletPageCss').remove();
			});
		$(".content").animate({ marginTop: "0px" }, 1500);
		//$(".wrapNav").css('top','-35px');
		//$(".wrapNav").css('position','absolute');
		//$(".wrapNav").animate({ top: topHP }, 1500);
		$('.wrap_footer').show();
		$('.content title').remove();
		hpAnimatevar = false;
	};

	// if regular loading pages
	var loadContent = function (url) {
		$('.wrap_footer').hide();
		if ( url != "/index" ) {
			$('.content').hide();
		}
		$('.content').empty();
		var HC = "";
		var holdHead = "";
		var holdBody = "";
		$.post(url + '.html', function(e){
			HC = e;
			pagesTitle = e.split(/(?:<title>|<\/title>)/ig)[1];
			document.title = pagesTitle;
			menuLangBar(HC);
			$(".nav a[href='"+url+"']").attr('class','navCurrent');
			checkIfContentEmpty(e, url);
			holdHead = HC.split(/(?:|<\/head>)/ig)[1];
			holdHead = $(holdHead).filter('.removePageCss')
			holdBody = HC.split(/(?:|<\/body>)/ig)[1];
			var splitBody = "";
			var splitBody2 = $(holdBody).filter('.content').html();
			holdBody = splitBody2 + splitBody;
			$('.content').html(holdBody);
			checkStyleCSS(holdHead);
		});

		$('.wrap_footer').before('

');
		$('.content title').remove();
		hpAnimatevar = false;
		if ( $.browser.msie ) {
			$('.menuLangBar a').click(function(){
				$(this).attr('href', $(this).attr('href') + location.hash);

			});
		}
	};

	var after_LoadContent = function () {
				$('.ajaxLoad').remove();
				$('.content').show();
				$('.wrap_footer').show();
	};

	var checkStyleCSS = function (holdHead) {
		var dontAdd1	= "http://img.babylon.com/site/images/babylon10/append.js";
		var dontAdd2 = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js";
		var dontAdd3 = "http://img.babylon.com/site/images/babylon10/modernizr.js";
		var dontAdd4 = "http://img.babylon.com/site/images/babylon10/history.js";
		var dontAdd5 = "http://img.babylon.com/site/images/babylon10/scripts.js";
		$('.removePageCss[rel="stylesheet"]').remove();
		for (var arr = 0; arr < holdHead.length; arr++){

			if ( ($('head').find('.removePageCss[type="text/javascript"]').attr('src') != holdHead[arr].src && holdHead[arr].src != undefined && dontAdd1 != holdHead[arr].src && dontAdd2 != holdHead[arr].src && dontAdd3 != holdHead[arr].src && dontAdd4 != holdHead[arr].src && dontAdd5 != holdHead[arr].src) || ($('head').find('.removePageCss[rel="stylesheet"]').attr('href') != holdHead[arr].href && holdHead[arr].href != undefined)  ) {

				$(holdHead[arr]).addClass('removePageCss');
				holdHead[arr].onload = function () {
					window.setTimeout(function () {
						after_LoadContent();
					}, $.browser.msie || $.browser.mozilla ? 700 : 0)
				};
				$(holdHead[arr]).appendTo('head');
			}
		}
	}

	var urlForIE = function () {

		if ( $.browser.msie && window.location.hash && refUrlIE ) {

			var hash = window.location.hash.split("#");
			hash = hash[hash.length-1].split("?");
			hash[0] = hash[0].replace('.','').replace('html','');
			if ( hash[0][0] == "/" ) {
				window.location.href = "http://" + window.location.hostname + hash[0];
			}
		}

	};

	$('#tohomepage').click(function(){
		backToHomePage = false;
	});

	$(window).ready(function() {

		if ( $.browser.msie && window.location.hash ) {
			urlForIE();
		}

		$(".wrapheader").load(function(){
			$('.menuLangBar').html($('.menuLangBar2').html());
			$('.menuLangBar2').remove();
			if ( location.pathname == hrefHP1 || location.pathname == hrefHP2 || location.pathname == hrefHP3 ) {
				$('#tohomepage').removeAttr("data-link");
				$('#tohomepage').removeAttr("href");
			}
			var locPathname = window.location.pathname;
			$(".nav a[href='"+locPathname+"']").attr('class', 'navCurrent');
		});
		$(".wrapfooter").load(function () {
			$('.divWithoutJavascript').remove();
		    isJSfooter = true;
		});

		var checkCart = function () {
			var cookie = document.cookie;
			if ( cookie != ""  ) {
				cookie = cookie.split(";");
				for ( var i=0; i < cookie.length; i++ ) {
					if ( cookie[i].indexOf("cart") == 1 )
						return true;
				}
			}
		};

		var changeCartColor = (function () {
		var buyTrans = ['Buy',	'شراء',	'Acheter',	'Kaufen',	'קנה',	'Acquista',	'購入',	'Comprar',	'Comprar'];
		var cartTrans = ['Cart',	'عربة التسوق',	'Panier',	'Einkaufswagen',	'סל קניות',	'Carrello',	'カート',	'Carrinho',	'Cesta de compra'];

		if ( !checkCart() ) {
			$('.cart').css('background-color','#80b946');
			for ( var i=0; i < cartTrans.length; i++ ) {
				$('.cart').html(''+$('.cart').text().replace(cartTrans[i],buyTrans[i]).replace('(0)',''));
				if ( location.hostname == "www.babylon.com" )
					$('.cart').css("width", "70px");
				if ( location.hostname == "deutsch.babylon.com" ) {
					$('.cart').css("font-size", "14px");
					$('.cart').css("width", "80px");
				}
				if ( location.hostname == "espanol.babylon.com" ) {
					$('.cart').css("font-size", "14px");
					$('.cart').css("width", "90px");
				}
				if ( location.hostname == "italiano.babylon.com" )
					$('.cart').css("width", "98px");
				if ( location.hostname == "francais.babylon.com" )
					$('.cart').css("width", "90px");
				if ( location.hostname == "portugues.babylon.com" )
					$('.cart').css("width", "95px");
				if ( location.hostname == "hebrew.babylon.com" )
					$('.cart').css("width", "75px");
				if ( location.hostname == "japanese.babylon.com" )
					$('.cart').css("width", "72px");
				if ( location.hostname == "arabic.babylon.com" )
					$('.cart').css("width", "70px");
			}
			$('.cart').hover(function(){$(this).css('background-color','#74ab3e')},function(){$(this).css('background-color','#80b946')});
			$('.cart').parent().attr('href','https://store.babylon.com/?trid=HPBUY');
			}
			else {
			$('.cart').css('background-color','#10c2e8');
			for ( var i=0; i < cartTrans.length; i++ ) {
				$('.cart').html(''+$('.cart').text().replace(buyTrans[i],cartTrans[i]));
			}
			if ( location.hostname == "portugues.babylon.com" )
					$('.cart').css("width", "115px");
			$('.cart').hover(function(){$(this).css('background-color','#10afd1')},function(){$(this).css('background-color','#10c2e8')});
			$('.cart').parent().attr('href',$('.cart').parent().attr('href')+'&trid=HPBUY');
			}
		})();

		var img = document.createElement('img');
		img.src = "http://img.babylon.com/site/images/babylon10/homepage/bg_img.jpg";
	});

	return { hpAnimate: hpAnimate, menuLangBar: menuLangBar, jsFotter: jsFotter }

})();


text:
package com.scaleunlimited.tenaya;

import java.util.List;

import com.scaleunlimited.tenaya.metadata.*;

public class DataFetchTool {

	public static void main(String[] args) throws Exception {
		if (args.length == 0) {
			printUsageAndExit();
		}
		for (String experiment : args) {
			List<String> runAccessions = ExperimentMetadata.createFromAccession(experiment).getRunAccessions();
			for (String acc : runAccessions) {
				System.out.println(acc);
			}
		}
	}

	public static void printUsageAndExit() {
		System.err.println("Usage: fetch FILE1 FILE2 ...");
		System.exit(-1);
	}

}


text:
*Released on 2017-09-10*

- Removed polyfill for `addEventListener` on IE8.
- `dialog()` now returns a `Promise` (no more callbacks) resolving to the result object (previously known as `returnObj`).
- Renamed `vars` → `data`, both in the options for `dialog` and in the `Promise` resolved object.

NB: These changes break compatibility with v2.x. Please read the new documentation for further details.

NB: This version drops support for older browsers and IE. Consider using polyfills for `addEventListener` and `Promise` for browsers not supporting them.

## Version 2 ##

### 2.1 ###

*Released on 2017-07-14*

- `returnObj.value` is correctly set to `undefined` if a dialog is not of "prompt" type.
- Renamed button classes (`dialog-continue-button` → `dialog-continue-btn`, `dialog-cancel-button` → `dialog-cancel-btn`).
- Removed unneeded `data-action` attributes on dialog buttons.
- Simplified code (increased readability).

### 2.0.1 ###

*Released on 2017-02-18*

- Minor bugfixes.

### 2.0.0 ###

*Released on 2015-10-18*

- Reconception of the majority of the code.
- Uploaded the project on GitHub.
- Removed `data-*` attributes for styling, now using classes (refer to style.css file to see new classes used).
- Renamed callBack → callback, which is now a reference to a function (with `returnObj` passed as first argument), not an executable string (not `eval` anymore!).
- Renamed returnObj.boolean → returnObj.action (same behavior).
- Title and content can't contain HTML anymore. However LF characters and whitespaces are preserved.
- Adding to the DOM only the visible elements (removed `display: none` hack).
- Fixed a bug with the `keyup` event listener.

NB: These changes break compatibility with v1.x. Please read the new documentation for further details.

## Version 1 ##

### 1.1 ###

*Released on 2012-13-09*

- Fixed a problem with the XHTML syntax. Now the function works good both in HTML and XHTML, automatically.

### 1.0 ###

*Released on 2012-08-07*

- This is the first version of the code, which includes the 3 objects `dialogSettings`, `dialog()` and `returnObj`.
- The code integrates the default stylesheet. The semitransparent background of the dialog doesn't work with IE < 9.
- When pressing enter the script will emulate the *ok* or *continue* button click, and the esc key will emulate the *cancel* button click when the cancel button is shown.


text:
- [x] alertPlugin
- [x] animatePlugin
- [x] touchPlugin

## Contact

**author:** Andy Jin
**Email:** andy_ios@163.com

##Licenses

All source code is licensed under the [MIT License](https://github.com/andy0323/jQuery-practice/blob/master/LICENSE).


text:
DatabaseFunctions::<BIG>CopyDBTableToFile</BIG>

RC
RJ

<short_desc xmlns="">
              This routine will copy the contents of a DBTable  to a file.
              </short_desc>

<detailed_desc xmlns="">
                 This routine will export the contents of a DBTable  to a delimeted file.

                 A data source name [DSN] and Query String is required. You also have to specify
                 a variable to get the status code.  And optionally user id and password (this is
                 because some drivers don't need a user/password).

                 To do: if user id and/or password are not specified, don't include them in the
                 connection string. This would allow the possibility to specify them in the
                 data source definition.  If no output directory is specified, the result file
		 get saved under "Datapool\Test\".

</detailed_desc>

Fields: [ ]=Optional with Default Value

DBSourceName

<short_desc xmlns="">
                 Name of the Datasource containing the DBTable
              </short_desc>

FileOut

<short_desc xmlns="">
                 Name of the output file.
              </short_desc>

DBTableName

<short_desc xmlns="">
                 Name of the TABLE to access within the DBSourceName
           </short_desc>

[ ColumnCount =  ]

<short_desc xmlns="">
                 If specified the output file will contain only the number of columns specified.
              </short_desc>

<detailed_desc xmlns="">

                 OPTIONAL parameter. If specified the output file will contain only the
                 number of columns specified. This number will become the first dimension
                 of the retreival array. If NOT specified the function will copy a maximum
                 of 100 columns. (arbitrary limit for now)

</detailed_desc>

[ RowCount =  ]

<short_desc xmlns="">
                 If specified the output file will contain only the number of rows specified.
              </short_desc>

<detailed_desc xmlns="">

                 OPTIONAL parameter. If specified the output file will contain only the
                 number of columns specified. This number will become the first dimension
                 of the retreival array. If NOT specified the function will copy a maximum
                 of 100 columns. (arbitrary limit for now)

</detailed_desc>

[ SQLQuery =  ]

<short_desc xmlns="">
                 OPTIONAL parameter. If specified, the file will contain the results of the
                 executed Query. The query is NOT validated by this function.
              </short_desc>

[ delimiter =  ]

<short_desc xmlns="">
                 OPTIONAL parameter. If not specified the default ',' seperator will be used.
              </short_desc>

[ DirectoryOut =  ]

<short_desc xmlns="">
                 OPTIONAL parameter. If not specified the file will be stored under the
                 project "Datapool\Test\" directory.
              </short_desc>

SQLStatus

<short_desc xmlns="">
                 A variable which holds the current SQL run status.
              </short_desc>

[ UserID =  ]

<short_desc xmlns="">
                 UserID for accessing the Datasource (if required).
              </short_desc>

[ Password =  ]

<short_desc xmlns="">
                 Password for accessing the Datasource (if required).
              </short_desc>

[ Prompt =  ]

<short_desc xmlns="">
                 Optional parameter valid values 1 - 4 [default is 4 no prompt] for ODBC driver login window.
              </short_desc>

Examples:

<usage xmlns="">T, ADBAlias, ATableAlias, CopyDBTableToFile, Data Source Name (dsn), ^OutputFileName, tableName, [^ColumnCount],[^rowCount], [^SQLQuery], [^Delimiter], [^OutputDirectory], ^sqlStatus, "[UID]", "[PWD]", "[prompt]"</usage>

<short_desc xmlns="">
                 This routine will export the contents of a DBTable  to a delimeted file.
              </short_desc>

<detailed_desc xmlns="">
                  This routine will export the contents of a DBTable  to a delimeted file.
              </detailed_desc>

[How To Read This Reference]


text:
Filtering and listing resources is one of the most important tasks for
administering a web application. Active Admin provides many different tools for
you to build a compelling interface into your data for the admin staff.

Built in, Active Admin has the following index renderers:

* *Table*: A table drawn with each row being a resource ([View Table Docs](3-index-pages/index-as-table.md))
* *Grid*: A set of rows and columns each cell being a resource ([View Grid Docs](3-index-pages/index-as-grid.md))
* *Blocks*: A set of rows (not tabular) each row being a resource ([View Blocks Docs](3-index-pages/index-as-block.md))
* *Blog*: A title and body content, similar to a blog index ([View Blog Docs](3-index-pages/index-as-blog.md))

All index pages also support scopes, filters, pagination, action items, and
sidebar sections.

## Multiple Index Pages

Sometime you may want more than one index page for a resource to represent
different views to the user. If multiple index pages exist, Active Admin will
automatically build links at the top of the default index page. Including
multiple views is simple and requires creating multiple index components in
your resource.

```ruby
index do
  id_column
  column :image_title
  actions
end

index as: :grid do |product|
  link_to image_tag(product.image_path), admin_product_path(product)
end
```

The first index component will be the default index page unless you indicate
otherwise by setting `:default` to true.

```ruby
index do
  column :image_title
  actions
end

index as: :grid, default: true do |product|
  link_to image_tag(product.image_path), admin_product_path(product)
end
```

## Custom Index

Active Admin does not limit the index page to be a table, block, blog or grid.
If you've created your own [custom index](3-index-pages/custom-index.md) page it
can be included by setting `:as` to the class of the index component you created.

```ruby
index as: ActiveAdmin::Views::IndexAsMyIdea do
  column :image_title
  actions
end
```

## Index Filters

By default the index screen includes a "Filters" sidebar on the right hand side
with a filter for each attribute of the registered model. You can customize the
filters that are displayed as well as the type of widgets they use.

To display a filter for an attribute, use the `filter` method

```ruby
ActiveAdmin.register Post do
  filter :title
end
```

Out of the box, Active Admin supports the following filter types:

* *:string* - A search field
* *:date_range* - A start and end date field with calendar inputs
* *:numeric* - A drop down for selecting "Equal To", "Greater Than" or "Less
  Than" and an input for a value.
* *:select* - A drop down which filters based on a selected item in a collection
  or all.
* *:check_boxes* - A list of check boxes users can turn on and off to filter

By default, Active Admin will pick the most relevant filter based on the
attribute type. You can force the type by passing the `:as` option.

```ruby
filter :author, as: :check_boxes
```

The `:check_boxes` and `:select` types accept options for the collection. By default
it attempts to create a collection based on an association. But you can pass in
the collection as a proc to be called at render time.

```ruby
filter :author, as: :check_boxes, collection: proc { Author.all }
```

You can change the filter label by passing a label option:

```ruby
filter :author, label: 'Something else'
```

By default, Active Admin will try to use ActiveModel I18n to determine the label.

You can also filter on more than one attribute of a model using the
[Ransack search predicate syntax](https://github.com/activerecord-hackery/ransack/wiki/Basic-Searching). If using a custom search method, you will
also need to specify the field type using `:as` and the label.

```ruby
filter :first_name_or_last_name_cont, as: :string, label: "Name"
```

Filters can also be disabled for a resource, a namespace or the entire
application.

To disable for a specific resource:

```ruby
ActiveAdmin.register Post do
  config.filters = false
end
```

To disable for a namespace, in the initializer:

```ruby
ActiveAdmin.setup do |config|
  config.namespace :my_namespace do |my_namespace|
    my_namespace.filters = false
  end
end
```

Or to disable for the entire application:

```ruby
ActiveAdmin.setup do |config|
  config.filters = false
end
```

You can also add a filter and still preserve the default filters:

```ruby
preserve_default_filters!
filter :author
```

## Index Scopes

You can define custom scopes for your index page. This will add a tab bar above
the index table to quickly filter your collection on pre-defined scopes. There are
a number of ways to define your scopes:

```ruby
scope :all, default: true

# assumes the model has a scope called ':active'
scope :active

# renames model scope ':leaves' to ':subcategories'
scope "Subcategories", :leaves

# Dynamic scope name
scope ->{ Date.today.strftime '%A' }, :published_today

# custom scope not defined on the model
scope("Inactive") { |scope| scope.where(active: false) }

# conditionally show a custom controller scope
scope "Published", if: proc { current_admin_user.can? :manage, Posts } do |posts|
  posts.published
end
```

## Index default sort order

You can define the default sort order for index pages:

```ruby
ActiveAdmin.register Post do
  config.sort_order = 'name_asc'
end
```

## Index pagination

You can set the number of records per page as default:

```ruby
ActiveAdmin.setup do |config|
  config.default_per_page = 30
end
```

You can set the number of records per page per resources:

```ruby
ActiveAdmin.register Post do
  config.per_page = 10
end
```

You can change it per request / action too:

```ruby
controller do
  before_filter :only => :index do
    @per_page = 100
  end
end
```

You can also disable pagination:

```ruby
ActiveAdmin.register Post do
  config.paginate = false
end
```

If you have a very large database, you might want to disable `SELECT COUNT(*)`
queries caused by the pagination info at the bottom of the page:

```ruby
ActiveAdmin.register Post do
  index pagination_total: false do
    # ...
  end
end
```

## Customizing Download Links

You can easily remove or customize the download links you want displayed:

```ruby
# Per resource:
ActiveAdmin.register Post do

  index download_links: false
  index download_links: [:pdf]
  index download_links: proc{ current_user.can_view_download_links? }

end

# For the entire application:
ActiveAdmin.setup do |config|

  config.download_links = false
  config.download_links = [:csv, :xml, :json, :pdf]
  config.download_links = proc { current_user.can_view_download_links? }

end
```

Note: you have to actually implement PDF rendering for your action, ActiveAdmin does not provide this feature. This setting just allows you to specify formats that you want to show up under the index collection.

You'll need to use a PDF rendering library like PDFKit or WickedPDF to get the PDF generation you want.


text:
NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_BEGIN

class UserTests : public UnitTestBase
{
public:
    TEST_CLASS(UserTests);
    DEFINE_TEST_CLASS_SETUP();

    const std::wstring XboxRelyingParty = L"http://xboxlive.com";
    const std::wstring MusicRelyingParty = L"http://music.xboxlive.com";
    const std::wstring JwtTokenType = L"JWT";

    TEST_METHOD_SETUP(SetupFactory)
    {
        m_mockXboxSystemFactory = std::make_shared<MockXboxSystemFactory>();
        xbox_system_factory_winstore_impl::set_factory(m_mockXboxSystemFactory);
        return true;
    }

    TEST_METHOD(SignInAsyncGetsTokenAndSetsDisplayClaims)
    {
        DEFINE_TEST_CASE_PROPERTIES();

        auto curUser = SignInUserWithMocks();

        VERIFY_ARE_EQUAL(curUser.xbox_user_id(), L"TestXboxUserId"); // StockMock results
        VERIFY_ARE_EQUAL(curUser.gamertag(), L"TestGamerTag");
        VERIFY_IS_NOT_NULL(curUser.auth_config());
    }

    TEST_METHOD(TestGetTokenAndSignatureAsync3)
    {
        DEFINE_TEST_CASE_PROPERTIES();

        auto curUser = SignInUserWithMocks();

        pplx::task< xbox::services::xbox_live_result<token_and_signature_result> > asyncOp = curUser.get_token_and_signature(
            L"GET",
            L"https://xboxlive.com",
            L""
            );

        GetAndVerifyTokenResult( asyncOp );
    }

    TEST_METHOD(TestGetTokenAndSignatureAsync4)
    {
        DEFINE_TEST_CASE_PROPERTIES();
        auto curUser = SignInUserWithMocks();

        pplx::task< xbox::services::xbox_live_result<token_and_signature_result> > asyncOp = curUser.get_token_and_signature(
            L"GET",
            L"https://xboxlive.com",
            L"",
            L"MockRequestBody"
            );

        GetAndVerifyTokenResult(asyncOp);
    }

    TEST_METHOD(TestGetTokenAndSignatureArrayAsync)
    {
        DEFINE_TEST_CASE_PROPERTIES();
        auto curUser = SignInUserWithMocks();

        std::vector<unsigned char> requestBodyArray { 1, 2 };
        pplx::task< xbox::services::xbox_live_result<token_and_signature_result> > asyncOp = curUser.get_token_and_signature_array(
            L"GET",
            L"https://xboxlive.com",
            L"",
            requestBodyArray
            );

        GetAndVerifyTokenResult(asyncOp);
    }

    TEST_METHOD(XTokensAreCached)
    {
        DEFINE_TEST_CASE_PROPERTIES();

        const std::wstring token(L"expectedtoken");
        const std::wstring userHash(L"userhash");
        const utility::datetime notAfter = utility::datetime::utc_now() + utility::datetime::from_hours(4);

        m_mockXboxSystemFactory->GetMockXstsTokenService()->ResultValue =
            token_result(token, notAfter.to_interval(), userHash, L"gamertag", L"123456", L"123", L"", L"");

        auto curUser = SignInUserWithMocks();

        auto asyncOp = curUser.get_token_and_signature(L"GET", L"https://xboxlive.com/path", L"");
        GetAndVerifyTokenResult(asyncOp, userHash, token);
    }

    TEST_METHOD(UTokensAreCached)
    {
        DEFINE_TEST_CASE_PROPERTIES();

        std::wstring token(L"expectedtoken");
        std::wstring userHash(L"userhash");

        // U token is valid for a while
        m_mockXboxSystemFactory->GetMockUserTokenService()->ResultValue = token_result(
            L"utoken",
            (utility::datetime::utc_now() + utility::datetime::from_hours(1)).to_interval(),
            userHash,
            L"",
            L"",
            L"",
            L"",
            L"");

        // X token is already expired so it should refresh everytime
        m_mockXboxSystemFactory->GetMockXstsTokenService()->ResultValue = token_result(
            token,
            (utility::datetime::utc_now() - utility::datetime::from_hours(4)).to_interval(),
            userHash,
            L"gamertag",
            L"123456",
            L"123",
            L"123",
            L"123");

        auto curUser = SignInUserWithMocks();

        auto asyncOp = curUser.get_token_and_signature(L"GET", L"https://xboxlive.com", L"");
        GetAndVerifyTokenResult(asyncOp, userHash, token);
    }

    TEST_METHOD(XTokensAreRefreshed)
    {
        DEFINE_TEST_CASE_PROPERTIES();

        std::wstring token(L"expectedtoken");
        std::wstring userHash(L"userhash");

        // X token is about to expire so it should refresh
        m_mockXboxSystemFactory->GetMockXstsTokenService()->ResultValue = token_result(
            token,
            (utility::datetime::utc_now() + utility::datetime::from_minutes(1)).to_interval(),
            userHash,
            L"gamertag",
            L"123456",
            L"123",
            L"123",
            L"123");

        auto curUser = SignInUserWithMocks();

        auto asyncOp = curUser.get_token_and_signature(L"GET", L"https://xboxlive.com", L"");

        // Sleep for a second to make sure the background refresh thread has time to finish.
        std::this_thread::sleep_for(std::chrono::seconds(1));

        GetAndVerifyTokenResult(asyncOp, userHash, token);
    }

    TEST_METHOD(CachesMultipleTokens)
    {
        DEFINE_TEST_CASE_PROPERTIES();

        std::wstring expectedToken(L"expectedtoken");
        std::wstring expectedUserHash(L"userhash");

        m_mockXboxSystemFactory->GetMockUserTokenService()->ResultValue = token_result(
            L"utoken",
            (utility::datetime::utc_now() + utility::datetime::from_hours(1)).to_interval(),
            expectedUserHash,
            L"",
            L"",
            L"123",
            L"",
            L"");

        m_mockXboxSystemFactory->GetMockXstsTokenService()->ResultValue = token_result(
            expectedToken,
            (utility::datetime::utc_now() + utility::datetime::from_hours(1)).to_interval(),
            expectedUserHash,
            L"gamertag",
            L"123456",
            L"123",
            L"",
            L"");

        auto curUser = SignInUserWithMocks();

        auto asyncOp = curUser.get_token_and_signature(L"GET", L"https://xboxlive.com/path", L"");
        GetAndVerifyTokenResult(asyncOp, expectedUserHash, expectedToken);

        m_mockXboxSystemFactory->GetMockXstsTokenService()->ResultValue = token_result(
            expectedToken,
            (utility::datetime::utc_now() + utility::datetime::from_hours(1)).to_interval(),
            expectedUserHash,
            L"gamertag",
            L"123456",
            L"123",
            L"",
            L"");

        // TODO 718329
        //m_mockXboxSystemFactory->ExpectGetXToken(true, MusicRelyingParty, JwtTokenType);

        asyncOp = curUser.get_token_and_signature(L"GET", L"https://music.xboxlive.com", L"");
        GetAndVerifyTokenResult(asyncOp, expectedUserHash, expectedToken);

        asyncOp = curUser.get_token_and_signature(L"GET", L"https://music.xboxlive.com", L"");
        GetAndVerifyTokenResult(asyncOp, expectedUserHash, expectedToken);
    }

    TEST_METHOD(TestUserCtors)
    {
        DEFINE_TEST_CASE_PROPERTIES();

        auto curUser = SignInUserWithMocks();
        auto curUser2 = curUser;

        VERIFY_ARE_EQUAL(curUser.xbox_user_id(), curUser2.xbox_user_id());
        VERIFY_ARE_EQUAL(curUser.gamertag(), curUser2.gamertag());

        auto curUser3(curUser);

        VERIFY_ARE_EQUAL(curUser.xbox_user_id(), curUser3.xbox_user_id());
        VERIFY_ARE_EQUAL(curUser.gamertag(), curUser3.gamertag());

        //user userMoved = std::move(SignInUserWithMocks());
        //VERIFY_ARE_EQUAL(curUser.xbox_user_id(), userMoved.xbox_user_id());
        //VERIFY_ARE_EQUAL(curUser.gamertag(), userMoved.gamertag());
    }

    void GetAndVerifyTokenResult(
        pplx::task< xbox::services::xbox_live_result<token_and_signature_result> > asyncOp,
        const std::wstring& expectedUserHash = L"TestXboxUserHash",
        const std::wstring& expectedToken = L"TestToken"
        )
    {
        token_and_signature_result tokenResult;
        VERIFY_NO_THROW(tokenResult = asyncOp.get().payload());

        VERIFY_ARE_EQUAL(tokenResult.token(), L"XBL3.0 x=" + expectedUserHash + L";" + expectedToken);
        VERIFY_IS_TRUE(!tokenResult.signature().empty());
    }

    static xbox_live_user SignInUserWithMocks()
    {
        xbox_live_user userTemp;
        VERIFY_NO_THROW(userTemp.signin_silently().get());
        return userTemp;
    }
};

NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_END


text:
using System;

namespace AndroidLib.Interaction
{
    public class FileSystemObject
    {
        private string path;
        private string filename;
        private string owner;
        private string group;
        private long size;
        private FileSystemObjectPermissions permissions;
        private bool isDirectory;
        private bool isLink;
        private DateTime lastEdit;

        public FileSystemObject(string path, string filename, string owner, string group, long size, FileSystemObjectPermissions permissions, bool isDirectory, bool isLink, DateTime lastEdit)
        {
            this.path = path;
            this.filename = filename;
            this.owner = owner;
            this.group = group;
            this.size = size;
            this.permissions = permissions;
            this.isDirectory = isDirectory;
            this.isLink = isLink;
            this.lastEdit = lastEdit;
        }

        /// <summary>
        /// The full path including objectname
        /// </summary>
        public string Path
        {
            get
            {
                return path;
            }
        }

        /// <summary>
        /// The name of the object
        /// </summary>
        public string Filename
        {
            get
            {
                return filename;
            }
        }

        /// <summary>
        /// The name of the owner
        /// </summary>
        public string Owner
        {
            get
            {
                return owner;
            }
        }

        /// <summary>
        /// The name of the group the object belongs to
        /// </summary>
        public string Group
        {
            get
            {
                return group;
            }
        }

        /// <summary>
        /// The size of the object in bytes
        /// </summary>
        public long Size
        {
            get
            {
                return size;
            }
        }

        /// <summary>
        /// Represents the permissions for this object
        /// </summary>
        public FileSystemObjectPermissions Permissions
        {
            get
            {
                return permissions;
            }
        }

        /// <summary>
        /// Indicates whether the object is a directory
        /// </summary>
        public bool IsDirectory
        {
            get
            {
                return isDirectory;
            }
        }

        /// <summary>
        /// The time when the last change was made
        /// </summary>
        public DateTime LastEdit
        {
            get
            {
                return lastEdit;
            }
        }

        /// <summary>
        /// The object is a symbolic link. Can be resolved via <see cref="FileSystemManager.ResolveSymbolicLink(string)"/>
        /// </summary>
        public bool IsLink
        {
            get
            {
                return isLink;
            }
        }
    }
}


text:
/*------------------------------------------------------------------------*/
/*                 Copyright 2010 Sandia Corporation.                     */
/*  Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive   */
/*  license for use of this work by or on behalf of the U.S. Government.  */
/*  Export of this program may require a license from the                 */
/*  United States Government.                                             */
/*------------------------------------------------------------------------*/

#ifndef stk_mesh_Transaction_hpp
#define stk_mesh_Transaction_hpp

#include <set>
#include <vector>
#include <iosfwd>

namespace stk{
namespace mesh {

class Bucket;
class BulkData;
class Entity;
class Part;

    /** \brief Bucket containers used to sort mesh entities by state
     *         so that they can be accessed after modification_end()
     */
    typedef std::vector<Bucket *>                 BucketList;

/** \addtogroup stk_mesh_module
 *  \{
 */

//----------------------------------------------------------------------
/** \brief  Transaction journal of modifications to the bulk data
 *          during a transaction.  Since the modification transaction
 *          guarantees a path independent result of mesh entities when
 *          modification_end() is called, the transaction just notes
 *          the state of altered mesh entities when the transaction
 *          was started.
 */

class Transaction
{
  public:
    /* \brief The following are the variable type and valid values for
     * defining the type of transaction bucket.
     */
    typedef unsigned char                State;
    enum { NOT_IN_TRANSACTION = 0 , MODIFIED = 1, INSERTED = 2, DELETED = 3 };

    /* \brief There are two different types of transactions:
     * incremental and bulk.  This can be set when reseting a
     * transaction.
     */
    enum TransactionType { INCREMENTAL = 1 , BULK = 2 };

  public:

    /** \brief Bucket containers used to sort mesh entities by state
     *         so that they can be accessed after modification_end()
     */
    typedef std::vector<BucketList>               BucketListByType;

    /** \brief Part list for tracking bulk transactions
     */
    typedef std::set<Part *>                      PartSet;

    /** \brief Pretty print the transaction
     */
    std::ostream & print_stream ( std::ostream &os ) const;

    /** \brief Retrieve buckets of a particular type that contain
     * modified entities.
     */
    const BucketList & get_modified_buckets ( unsigned type ) const { return m_modified[type]; }

    /** \brief Retrieve buckets of a particular type that contain
     * deleted entities.
     */
    const BucketList & get_deleted_buckets ( unsigned type ) const { return m_deleted[type]; }

    /** \brief Retrieve buckets of a particular type that contain
     * inserted entities.
     */
    const BucketList & get_inserted_buckets ( unsigned type ) const { return m_inserted[type]; }

    /** \brief Retrieve a part vector of parts whose entities were
     * modified.
     */
    void get_parts_with_modified_entities ( PartVector &pv ) const
    {
      translate_partset_to_partvector ( m_modified_parts , pv );
    }

    /** \brief Retrieve a part vector of parts from which entities
     * were deleted.
     */
    void get_parts_with_deleted_entities ( PartVector &pv ) const
    {
      translate_partset_to_partvector ( m_deleted_parts , pv );
    }

    /** \brief Retrieve a part vector of parts into which entities
     * were inserted.
     */
    void get_parts_with_inserted_entities ( PartVector &pv ) const
    {
      translate_partset_to_partvector ( m_inserted_parts , pv );
    }

  private:

    /** \brief Pretty print helper
     */
    void      print_proc_transaction ( unsigned , std::ostream & ) const;
    /** \brief Pretty print helper
     */
    void  print_transaction ( unsigned , std::ostream & ) const;

    Transaction ();
    Transaction ( BulkData & , TransactionType );
    Transaction & operator = ( const Transaction & );
   ~Transaction ();

    /** \brief Unlike other parts of \ref stk::mesh , Transactions
     *         manage their own memory.  This method is called
     *         during purge() to ensure the bucket containers are
     *         in an appropriate state.  Upon destruction, this
     *         function is not called.
     */
    void allocate_bucket_lists ();

    TransactionType     m_transaction_type;

    BulkData           &m_bulk_data;
    BucketListByType    m_modified;
    BucketListByType    m_deleted;
    BucketListByType    m_inserted;

    PartSet            m_modified_parts;
    PartSet            m_deleted_parts;
    PartSet            m_inserted_parts;

    std::set<Entity *>   m_to_delete;

    void   flush_deletes ();

    /** \brief At modification_begin(), the transaction log is purged.
     * This method will empty the m_modified and m_inserted lists and
     * delete the entities in m_deleted.
     */
    void   reset ( TransactionType type = BULK );
    void   flush ();

    /** \brief Let the transaction log know this entity has been
     * modified in some way.  No relations are followed.
     */
    void   modify_sole_entity ( Entity &e );

    /** \brief Let the transaction log know this entity has been
     * modified in some way.  All entities for which e is in the
     * closure will also be marked modified.
     */
    void   modify_entity ( Entity & e );

    /** \brief Let the transaction log know this entity has been added
     * to the local mesh
     */
    void   insert_entity ( Entity & e );

    /** \brief Let the transaction log know this entity has been
     * removed from the local mesh
     */
    void   delete_entity ( Entity & e );

    /** \brief Helper method to empty m_modified and m_inserted
     */
    void   purge_map ( BucketListByType & );

    /** \brief Helper method to delete entities in m_deleted
     */
    void   purge_and_erase_map ( BucketListByType & );

    /** \brief This method will use the declase bucket method in \ref
     * stk::mesh::Bucket .  This returns the appropriate bucket to
     * store entity information in.
     */
    Bucket *get_unfilled_transaction_bucket ( const unsigned *const , EntityRank , BucketList & , State );

    /** \brief This method will use the declase bucket method in \ref
     * stk::mesh::Bucket .  This returns the appropriate bucket to
     * store entity information in. The function is templated to avoid
     * confusing header inclusions.
     */
    template <class ENTITY>
    Bucket *get_unfilled_transaction_bucket ( const ENTITY &e , BucketList &bm , State s )
     { return get_unfilled_transaction_bucket ( e.bucket().key() , e.entity_rank() , bm , s ); }

    /** \brief This method will add an entity to a transaction bucket
     */
    void   add_entity_to_transaction_bucket ( Entity & , Bucket * );

    /** \brief This method will remove an entity from its current
     * transaction bucket and place it in a new bucket.
     */
    void   swap_entity_between_transaction_buckets ( Entity & , BucketList & , BucketList & , State );

    /** \brief This method will remove an entity from a transaction
     * bucket.
     */
    void   remove_entity_from_bucket ( Entity & , BucketList & );

    /** \brief When a part contains an entity that needs logging, this
     * function will add that part to the particular part set, be it
     * modified, deleted, or inserted
     */
    void   add_parts_to_partset ( Entity & , PartSet & );

    /** \brief This functions creates a PartVector from a PartSet
     */
    void   translate_partset_to_partvector ( const PartSet & , PartVector & ) const;

    // BulkData needs access to modify_entity, insert_entity, and
    // delete_entity.
    friend class BulkData;
    friend std::ostream & operator<< ( std::ostream &os , const Transaction &rhs );

};

inline std::ostream &operator<< ( std::ostream &os , const Transaction &rhs )
{
  return rhs.print_stream ( os );
}

/** \brief Pretty print helper
 */
void  print_bucket_list ( const BucketList & , std::ostream & );
/*
 * \}
 */

}
}

#endif


text:
package mockit.internal.capturing;

import java.util.*;

import mockit.external.asm4.*;
import mockit.internal.*;
import mockit.internal.startup.*;
import mockit.internal.state.*;

public abstract class CaptureOfImplementations implements Runnable
{
   private final List<CaptureTransformer> captureTransformers;

   protected CaptureOfImplementations() { captureTransformers = new ArrayList<CaptureTransformer>(); }

   protected abstract ClassSelector createClassSelector();
   protected abstract ClassVisitor createModifier(ClassLoader cl, ClassReader cr, String capturedTypeDesc);

   public final void makeSureAllSubtypesAreModified(Class<?> baseType)
   {
      makeSureAllSubtypesAreModified(baseType, false);
   }

   public final void makeSureAllSubtypesAreModified(Class<?> baseType, boolean registerCapturedClasses)
   {
      if (baseType == null) {
         throw new IllegalArgumentException("Capturing implementations of multiple base types is not supported");
      }

      String baseTypeDesc = Type.getInternalName(baseType);
      ClassSelector classSelector = createClassSelector();
      CapturedType captureMetadata = new CapturedType(baseType, classSelector);

      redefineClassesAlreadyLoaded(captureMetadata, baseTypeDesc);
      createCaptureTransformer(captureMetadata, registerCapturedClasses);
   }

   private void redefineClassesAlreadyLoaded(CapturedType captureMetadata, String baseTypeDesc)
   {
      Class<?>[] classesLoaded = Startup.instrumentation().getAllLoadedClasses();

      for (Class<?> aClass : classesLoaded) {
         if (captureMetadata.isToBeCaptured(aClass)) {
            redefineClass(aClass, baseTypeDesc);
         }
      }
   }

   private void redefineClass(Class<?> realClass, String baseTypeDesc)
   {
      if (!TestRun.mockFixture().containsRedefinedClass(realClass)) {
         ClassReader classReader;

         try {
            classReader = ClassFile.createReaderOrGetFromCache(realClass);
         }
         catch (ClassFile.NotFoundException ignore) {
            return;
         }

         ClassVisitor modifier = createModifier(realClass.getClassLoader(), classReader, baseTypeDesc);
         classReader.accept(modifier, 0);
         byte[] modifiedClass = modifier.toByteArray();

         new RedefinitionEngine(realClass).redefineMethodsWhileRegisteringTheClass(modifiedClass);
      }
   }

   private void createCaptureTransformer(CapturedType captureMetadata, boolean registerCapturedClasses)
   {
      CaptureTransformer transformer = new CaptureTransformer(captureMetadata, this, registerCapturedClasses);
      Startup.instrumentation().addTransformer(transformer);
      captureTransformers.add(transformer);
   }

   public void cleanUp()
   {
      for (CaptureTransformer transformer : captureTransformers) {
         transformer.deactivate();
         Startup.instrumentation().removeTransformer(transformer);
      }

      captureTransformers.clear();
   }

   public final void run() { cleanUp(); }
}


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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="MessageMessageMessageMessageMessageMessageMessage"
        android:textSize="15dp"
        android:textColor="@android:color/white"
        android:background="@drawable/local_message_bg"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:paddingTop="4dp"
        android:paddingBottom="4dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="40dp"/>

    <ImageView
        android:id="@+id/lockImage"
        android:visibility="invisible"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/textView1"
        android:src="@drawable/lock"
        android:layout_marginStart="-25dp"
        android:layout_marginTop="10dp"/>

</RelativeLayout>