text:
import java.util.*;
import java.util.Date;

class timezones
{

  //-----------------------------------------------------------------------
  // displayTime()
  //
  // Display the time for a given Calendar object.
  //
  //-----------------------------------------------------------------------
  static public void displayTime( Calendar cal )
  {
    TimeZone tz      = cal.getTimeZone() ;
    TimeZone tzLocal = TimeZone.getDefault() ;

    //--------------------------------------------------------------
    // Figure out if the given timezone is in daylight savings time.
    // BUG: Does not seem to be working ?
    //--------------------------------------------------------------
    boolean  localDST = tzLocal.inDaylightTime( new Date() ) ;
    boolean  calDST   = tz.inDaylightTime( new Date() ) ;

    String ampm      = "am" ;
    String advstd    = "Standard Time" ;
    String currentID = tz.getID() ;

    if ( calDST )
    {
      advstd = "Daylight Time" ;
    }

    //--------------------------------------------------------------
    // Calculate if it's morning or afternoon in the given timezone.
    //--------------------------------------------------------------
    if ( cal.get(cal.AM_PM) > 0 )
    {
      ampm = "pm" ;
    }

    int h = cal.get(cal.HOUR)   ;
    int m = cal.get(cal.MINUTE) ;
    int s = cal.get(cal.SECOND) ;

    if ( h == 0 )
    {
      h = 12 ;
    }

    String hs = Integer.toString( h ) ;
    String ms = Integer.toString( m ) ;
    String ss = Integer.toString( s ) ;

    if ( h < 10 )
    {
      hs = "0" + hs ;
    }

    if ( m < 10 )
    {
      ms = "0" + ms ;
    }

    if ( s < 10 )
    {
      ss = "0" + ss ;
    }

    System.out.println( "Time for Calendar in:" + currentID ) ;
    System.out.println( hs + ":" + ms + ":" + ss + " " + ampm + " " + advstd ) ;
  }

  //-----------------------------------------------------------------------
  // main()
  //
  // Program entry point when we are being run as a stand alone application.
  //
  //-----------------------------------------------------------------------
  static public void main( String[] args )
  {
     //------------------------------------------------------------------
     // Get a default TimeZone object that we can play with. The TimeZone
     // class cannot be instantiated by itself. Also get a Date object.
     //------------------------------------------------------------------

     TimeZone tz = TimeZone.getDefault() ;

     Date dt = new Date() ;

     //---------------------------------------------------------
     // Print the date as a string. BUG: Always prints in PDT ??
     //---------------------------------------------------------
     System.out.println( dt.toString() ) ;

     //-------------------------------------------------------------------
     // Query which time zone we are currently in.
     //
     //-------------------------------------------------------------------

     System.out.println( "Our current time zone is " + tz.getID() ) ;

     //-------------------------------------------------------------------
     // This test will check to see if the time zone that we are currently
     // in uses daylight savings time at all.
     //-------------------------------------------------------------------

     if ( tz.useDaylightTime() )
     {
       System.out.println( "Current time zone uses daylight savings time." ) ;
     }
     else
     {
       System.out.println( "Current time zone does not use daylight savings time." ) ;
     }

     //-----------------------------------------------------------------
     // This test will see if the time zone we are in is currently using
     // daylight savings time.
     //-----------------------------------------------------------------

     if ( tz.inDaylightTime( new Date() ) )
     {
       System.out.println( "Current time zone is in daylight savings time now." ) ;
     }
     else
     {
       System.out.println( "Current time zone is not in daylight savings time now." ) ;
     }

     //----------------------------------------------------------------------
     // This query will get us a list of all the available time zones, like,
     // GMT,EST,CST etc... that Java supports. We can then dump the list out.
     //----------------------------------------------------------------------

     String [] ids = tz.getAvailableIDs() ;

     System.out.println( "List of supported time zones..." ) ;

     for ( int i=0; i< ids.length; i++ )
     {
       System.out.println( ids[i] ) ;
     }

     //----------------------------------------------------------------
     // Query the raw offset, that is not modified for daylight savings
     // time from GMT for the current time zone. Note that the raw
     // offset is returned in milliseconds.
     //----------------------------------------------------------------

     int gmtOffsetMillis  = tz.getRawOffset() ;
     int gmtOffsetMinutes = gmtOffsetMillis/ (1000 * 60 ) ;

     System.out.println( "Raw offset from GMT in millis is " + gmtOffsetMillis ) ;
     System.out.println( "Offset from GMT in minutes is " + gmtOffsetMinutes ) ;

     //------------------------------------------------------------------
     // Get an instance of a Calendar object. Use this to get the current
     // time. Note that the hour is returned in 12 hour format.
     //------------------------------------------------------------------

     Calendar cal = Calendar.getInstance();

     displayTime( cal ) ;

     //----------------------------------------------------------------------
     // Get the Date object back that represents the current time. Note that
     // most of the methods in the Date class are in fact deprecated. This
     // seems like a design flaw in Java 1.1. It is odd that the Calendar
     // class would return what is basically an almost fully deprecated
     // object to us.
     //----------------------------------------------------------------------

     Date dt2 = cal.getTime() ;

     System.out.println( "Time derived from deprectated Date methods:" ) ;

     int h = dt2.getHours()   ; //DEPRECATED
     int m = dt2.getMinutes() ; //DEPRECATED
     int s = dt2.getSeconds() ; //DEPRECATED

     System.out.println( h + ":" + m + ":" + s ) ;

     System.out.println( "AM_PM value follows (0=AM, 1=PM) ..." ) ;
     System.out.println( cal.get( cal.AM_PM ) ) ;

     //-------------------------------------------------------------
     // Now let's play with a combination of TimeZone, Calendar
     // and Locale objects to calculate the time in a few different
     // timezones around the World. It is unclear how daylight
     // savings time is handled here . (???)
     //-------------------------------------------------------------

     TimeZone gmt = TimeZone.getTimeZone( "GMT" ) ;  // GMT

     TimeZone hst = TimeZone.getTimeZone( "HST" ) ;  // Hawaiin
     TimeZone pst = TimeZone.getTimeZone( "PST" ) ;  // Pacific
     TimeZone mst = TimeZone.getTimeZone( "MST" ) ;  // Mountain
     TimeZone cst = TimeZone.getTimeZone( "CST" ) ;  // Central
     TimeZone est = TimeZone.getTimeZone( "EST" ) ;  // Eastern

     TimeZone aet = TimeZone.getTimeZone( "AET" ) ;  // Australia East
     TimeZone act = TimeZone.getTimeZone( "ACT" ) ;  // Australia Central
     TimeZone jst = TimeZone.getTimeZone( "JST" ) ;  // Japan
     TimeZone nst = TimeZone.getTimeZone( "NST" ) ;  // New Zealand

     Locale usa = new Locale( "US", "EN" ) ;

     Calendar gmtCal = Calendar.getInstance( gmt, usa ) ;

     Calendar hstCal = Calendar.getInstance( hst, usa ) ;
     Calendar pstCal = Calendar.getInstance( pst, usa ) ;
     Calendar mstCal = Calendar.getInstance( mst, usa ) ;
     Calendar cstCal = Calendar.getInstance( cst, usa ) ;
     Calendar estCal = Calendar.getInstance( est, usa ) ;

     Calendar jstCal = Calendar.getInstance( jst, usa ) ;
     Calendar actCal = Calendar.getInstance( act, usa ) ;
     Calendar aetCal = Calendar.getInstance( aet, usa ) ;
     Calendar nstCal = Calendar.getInstance( nst, usa ) ;

     displayTime( gmtCal ) ;

     displayTime( hstCal ) ;
     displayTime( pstCal ) ;
     displayTime( mstCal ) ;
     displayTime( cstCal ) ;
     displayTime( estCal ) ;

     displayTime( jstCal ) ;
     displayTime( actCal ) ;
     displayTime( aetCal ) ;
     displayTime( nstCal ) ;
  }
}


text:
'use strict';
var fs = require('fs');

var angular = require('camunda-bpm-sdk-js/vendor/angular'),
  varUtils = require('./cam-variable-utils'),
  template = fs.readFileSync(__dirname + '/cam-widget-variable.html', 'utf8');

var variableTypes = varUtils.types;

var modalCtrl = varUtils.modalCtrl;

module.exports = [
  '$uibModal',
  function($modal) {
    return {
      template: template,

      scope: {
        variable: '=camVariable',
        // A variable HAS a the following information
        // {
        //   value: <Mixed>,
        //   name: <String>,
        //   type: <String>,
        //
        // A variable MAY HAVE a the following information
        //   id: <UUID>,
        //   valueInfo: {
        //     objectTypeName: <String>,
        //     serializationDataFormat: <String>
        //   },
        //
        //   activitiyInstanceId: <UUID>,
        //   caseExecutionId: <UUID>,
        //   caseInstanceId: <UUID>,
        //   executionId: <UUID>,
        //   processInstanceId: <UUID>,
        //   taskId: <UUID>
        // }
        display: '@?',
        shown: '=?',
        disabled: '=?',
        hiddenTypes: '=?'
      },

      link: function($scope, element) {
        function isShownType(what) {
          if (
            !Array.isArray($scope.hiddenTypes) ||
            !$scope.hiddenTypes.length
          ) {
            return true;
          }
          return $scope.hiddenTypes.indexOf(what) === -1;
        }

        $scope.variableTypes = variableTypes.filter(isShownType);

        var defaultValues = varUtils.defaultValues;

        $scope.isPrimitive = varUtils.isPrimitive($scope);

        $scope.useCheckbox = varUtils.useCheckbox($scope);

        $scope.isShown = function(what) {
          if (!Array.isArray($scope.shown) || !$scope.shown.length) {
            return true;
          }
          return $scope.shown.indexOf(what) > -1;
        };

        $scope.isDisabled = function(what) {
          if (!Array.isArray($scope.disabled) || !$scope.disabled.length) {
            return false;
          }
          return $scope.disabled.indexOf(what) > -1;
        };

        $scope.shownClasses = function() {
          if (!Array.isArray($scope.shown) || !$scope.shown.length) {
            return '';
          }
          return $scope.shown
            .map(function(part) {
              return 'show-' + part;
            })
            .join(' ');
        };
        $scope.$watch('shown', function() {
          element
            .removeClass('show-type show-name show-value')
            .addClass($scope.shownClasses());
        });

        var validate = varUtils.validate($scope);
        $scope.valid = true;
        $scope.$watch('variable.value', validate);
        $scope.$watch('variable.name', validate);
        $scope.$watch('variable.type', validate);
        validate();

        // backup is used to recover a variable value
        // from either type or null switch
        var backup = $scope.variable.value;

        $scope.$watch('variable.type', function(current, previous) {
          // convert the value to boolean when the type becomes Boolean
          if (current === 'Boolean') {
            // we don't do anything if the value is null
            if ($scope.variable.value !== null) {
              backup = $scope.variable.value;

              $scope.variable.value =
                $scope.variable.value === 'false'
                  ? false
                  : !!$scope.variable.value;
            }
          } else if (previous === 'Boolean') {
            $scope.variable.value = backup;
          }

          var classList = element[0].classList;
          if (previous) {
            classList.remove('var-type-' + previous.toLowerCase());
          }
          if (current) {
            classList.add('var-type-' + current.toLowerCase());
          }
        });

        $scope.isNull = function() {
          return $scope.variable.value === null;
        };
        $scope.setNonNull = function() {
          $scope.variable.value = backup || defaultValues[$scope.variable.type];
        };
        $scope.setNull = function() {
          backup = $scope.variable.value;
          $scope.variable.value = null;
        };

        $scope.editVariableValue = function() {
          $modal
            .open({
              template: varUtils.templateDialog, //templateDialog,

              controller: modalCtrl,

              windowClass: 'cam-widget-variable-dialog',

              resolve: {
                variable: function() {
                  return angular.copy($scope.variable);
                },
                readonly: function() {
                  return $scope.display;
                }
              }
            })
            .result.then(function(result) {
              $scope.variable.value = result.value;
              $scope.variable.valueInfo = result.valueInfo;
            })
            .catch(angular.noop);
        };
      }
    };
  }
];

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnInit } from '@angular/core';
import { Service997Service } from '../../services/service-997.service';

@Component({
  selector: 'app-comp-997',
  templateUrl: './comp-997.component.html',
  styleUrls: ['./comp-997.component.css']
})
export class Comp997Component implements OnInit {

  constructor(private _service: Service997Service) { }

  ngOnInit() {
  }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;

namespace HoloToolkit.Sharing.Utilities
{
    /// <summary>
    /// Utility class for automatically joining shared sessions without needing to go through a lobby.
    /// </summary>
    public class AutoJoinSession : MonoBehaviour
    {
        /// <summary>
        /// Name of the session to join.
        /// </summary>
        public string SessionName = "Default";

        /// <summary>
        /// Cached pointer to the sessions tracker.
        /// </summary>
        private ServerSessionsTracker sessionsTracker;

        private bool sessionCreationRequested;
        private string previousSessionName;

        private void Start()
        {
            // Get the ServerSessionsTracker to use later.
            // Note that if this processes takes the role of a secondary client,
            // then the sessionsTracker will always be null
            if (SharingStage.Instance != null && SharingStage.Instance.Manager != null)
            {
                sessionsTracker = SharingStage.Instance.SessionsTracker;
            }
        }

        private void Update()
        {
            if (previousSessionName != SessionName)
            {
                sessionCreationRequested = false;
                previousSessionName = SessionName;
            }

            // If we are a Primary Client and can join sessions...
            if (sessionsTracker != null && sessionsTracker.Sessions.Count > 0)
            {
                // Check to see if we aren't already in the desired session
                Session currentSession = sessionsTracker.GetCurrentSession();

                if (currentSession == null ||                                                    // We aren't in any session
                    currentSession.GetName().GetString() != SessionName ||                       // We're in the wrong session
                    currentSession.GetMachineSessionState() == MachineSessionState.DISCONNECTED) // We aren't joined or joining the right session
                {
                    if (SharingStage.Instance.ShowDetailedLogs)
                    {
                        Debug.LogFormat("AutoJoinSession: Session connected is {0} with {1} Sessions.", sessionsTracker.IsServerConnected.ToString(), sessionsTracker.Sessions.Count.ToString());
                        Debug.Log("AutoJoinSession: Looking for " + SessionName);
                    }
                    bool sessionFound = false;

                    for (int i = 0; i < sessionsTracker.Sessions.Count; ++i)
                    {
                        Session session = sessionsTracker.Sessions[i];

                        if (session.GetName().GetString() == SessionName)
                        {
                            sessionsTracker.JoinSession(session);
                            sessionFound = true;
                            break;
                        }
                    }

                    if (sessionsTracker.IsServerConnected && !sessionFound && !sessionCreationRequested)
                    {
                        if (SharingStage.Instance.ShowDetailedLogs)
                        {
                            Debug.Log("Didn't find session, making a new one");
                        }

                        if (sessionsTracker.CreateSession(new XString(SessionName)))
                        {
                            sessionCreationRequested = true;
                        }
                    }
                }
            }
        }
    }
}


text:
<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="../resources/webxr_util.js"></script>
<script src="../resources/webxr_math_utils.js"></script>
<script src="../resources/webxr_test_asserts.js"></script>
<script src="../resources/webxr_test_constants.js"></script>
<script src="../resources/webxr_test_constants_fake_world.js"></script>

<script>

// 1m above world origin.
const VIEWER_ORIGIN_TRANSFORM = {
  position: [0, 1, 0],
  orientation: [0, 0, 0, 1],
};

// 0.25m above world origin.
const FLOOR_ORIGIN_TRANSFORM = {
  position: [0, 0.25, 0],
  orientation: [0, 0, 0, 1],
};

const fakeDeviceInitParams = {
  supportedModes: ["immersive-ar"],
  views: VALID_VIEWS,
  floorOrigin: FLOOR_ORIGIN_TRANSFORM,    // aka mojo_from_floor
  viewerOrigin: VIEWER_ORIGIN_TRANSFORM,  // aka mojo_from_viewer
  supportedFeatures: ALL_FEATURES,
  world: createFakeWorld(5.0, 2.0, 5.0),  // webxr_test_constants_fake_world.js has detailed description of the fake world
};

// Generates a test function given the parameters for the hit test. It will subscribe
// to a hit test using |refSpaceName| and |ray|, and attempt to obtain poses from returned hit
// test results using a space that is known to be unlocalizable, with the expectation of
// obtaining a null pose for each hit test result.
// |ray| - ray that will be used to subscribe to hit test.
// |refSpaceName| - XRReferenceSpaceType - either 'local', 'local-floor' or 'viewer'.
let testFunctionGenerator = function(ray, refSpaceName) {
  const testFunction = function(session, fakeDeviceController, t) {

    const input_source_controller = fakeDeviceController.simulateInputSourceConnection({
      handedness: "right",
      targetRayMode: "tracked-pointer",
      pointerOrigin: IDENTITY_TRANSFORM,
      profiles: []
    });

    return Promise.all([
      session.requestReferenceSpace('local'),
      session.requestReferenceSpace('viewer'),
      session.requestReferenceSpace('local-floor'),
    ]).then(([localRefSpace, viewerRefSpace, localFloorRefSpace]) => {

      const refSpaceNameToSpace = {
        'local' : localRefSpace,
        'viewer' : viewerRefSpace,
        'local-floor' : localFloorRefSpace
      };

      const hitTestOptionsInit = {
        space: refSpaceNameToSpace[refSpaceName],
        offsetRay: ray,
      };

      return session.requestHitTestSource(hitTestOptionsInit).then(
        (hitTestSource) => new Promise((resolve, reject) => {

        const requestAnimationFrameCallback = function(time, frame) {

          const hitTestResults = frame.getHitTestResults(hitTestSource);

          t.step(() => {
            assert_true(session.inputSources.length > 0, "session.inputSources should not be empty!");
            assert_true(hitTestResults.length > 0, "Results should not be empty!");

            const input_source = session.inputSources[0];

            for(const [index, hitTestResult] of hitTestResults.entries()) {
              const pose = hitTestResult.getPose(input_source.targetRaySpace);
              assert_true(pose == null, "Pose should be null since input source is not localizable");
            }
          });

          resolve();
        };

        t.step(() => {
          assert_true(hitTestSource != null, "Hit test source should not be null");
        });

        session.requestAnimationFrame(requestAnimationFrameCallback);
      }));
    });
  };

  return testFunction;
};

// All test cases require local-floor and hit-test.
const sessionInit = { 'requiredFeatures': ['local-floor', 'hit-test'] };

xr_session_promise_test(
  "Ensures hit test result returns null pose w/unlocalizable space - viewer space",
  testFunctionGenerator(new XRRay(), 'viewer'),
  fakeDeviceInitParams, 'immersive-ar', sessionInit);

</script>


text:
<?php echo Form::open(array("class"=>"form-horizontal")); ?>
<?php $birth = Model_Customer::gengo(isset($customer) ? $customer->birthday : '');?>

		<?php echo Form::submit('submit', '登録', array('class' => 'btn btn-primary')); ?>

	<fieldset>

				<?php echo Form::label('顧客姓', 'last_name', array('class'=>'control-label')); ?>

					<?php echo Form::input('last_name', Input::post('last_name', isset($customer) ? $customer->last_name : ''), array('class' => 'form-control',  'placeholder' => '山本')); ?>

				<?php echo Form::label('顧客名', 'firs_tname', array('class'=>'control-label')); ?>

					<?php echo Form::input('firs_tname', Input::post('firs_tname', isset($customer) ? $customer->firs_tname : ''), array('class' => 'form-control', 'placeholder'=>'太郎')); ?>

	</fieldset>
	<fieldset>

				<?php echo Form::label('フリガナ姓', 'ph_family_name', array('class'=>'control-label')); ?>

					<?php echo Form::input('ph_family_name', Input::post('ph_family_name', isset($customer) ? $customer->ph_family_name : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'ヤマモト')); ?>

				<?php echo Form::label('フリガナ名', 'ph_name', array('class'=>'control-label')); ?>

					<?php echo Form::input('ph_name', Input::post('ph_name', isset($customer) ? $customer->ph_name : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'タロウ')); ?>

	</fieldset>
	<fieldset>

				<?php echo Form::label('性別', 'sex', array('class'=>'control-label')); ?>
					<?php echo Form::label('男性', 'sex_1'); ?>
					<?php echo Form::radio('sex', 1,  isset($customer) ? $customer->sex != '0' && $customer->sex == '1' : '0', array('id' => 'sex_1')); ?>
					<?php echo Form::label('女性', 'sex_2'); ?>
					<?php echo Form::radio('sex', 2,  isset($customer) ? $customer->sex != '0' && $customer->sex == '2' : '0', array('id' => 'sex_2')); ?>
					<?php
					?>

	</fieldset>
	<fieldset>

			<?php echo Form::label('担当者', 'person_id', array('class'=>'control-label')); ?>
				<?php echo Form::select('person_id', Input::post('person_id', isset($customer) ? $customer->person_id : ''), $person_selects, array('class' => 'col-md-4 form-control')); ?>
				<?php echo Form::hidden('personname', isset($customer) && $person_selects[$customer->person_id] != 0 ? $person_selects[$customer->person_id] : ''); ?>

	</fieldset>
	<fieldset>

				<?php echo Form::label('郵便番号', 'post_code', array('class'=>'control-label')); ?>

					<?php echo Form::input('post_code', Input::post('post_code', isset($customer) ? $customer->post_code : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'999-9999')); ?>

	</fieldset>
	<fieldset>

			<?php echo Form::label('住所1', 'adress1', array('class'=>'control-label')); ?>

				<?php echo Form::input('adress1', Input::post('adress1', isset($customer) ? $customer->adress1 : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'沖縄県')); ?>

	</fieldset>
	<fieldset>

			<?php echo Form::label('住所2', 'adress2', array('class'=>'control-label')); ?>

				<?php echo Form::input('adress2', Input::post('adress2', isset($customer) ? $customer->adress2 : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'那覇市上間')); ?>

	</fieldset>
	<fieldset>

			<?php echo Form::label('住所3', 'adress3', array('class'=>'control-label')); ?>

				<?php echo Form::input('adress3', Input::post('adress3', isset($customer) ? $customer->adress3 : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'1丁目99-9 メゾンオーズ 101')); ?>

	</fieldset>
	<fieldset>

			<?php echo Form::label('電話番号', 'phone', array('class'=>'control-label')); ?>

				<?php echo Form::input('phone', Input::post('phone', isset($customer) ? $customer->phone : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'090-999-9999')); ?>

	</fieldset>
	<fieldset>

			<?php echo Form::label('年齢', 'age', array('class'=>'control-label')); ?>

				<?php echo Form::input('age', Input::post('age', isset($customer) ? $customer->age : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'27')); ?>

	</fieldset>
	<fieldset>

				<?php echo Form::label('生年月日', 'gengo', array('class'=>'control-label')); ?>

					西暦 <?php echo Form::radio('gengo', 'seireki', isset($customer) ? $customer->gengo != null && $customer->gengo == 'seireki' : '', array('id' => 'gengo_1')); ?>
					大正 <?php echo Form::radio('gengo', 'taisho', isset($customer) ? $customer->gengo != null && $customer->gengo == 'taisho' : '', array('id' => 'gengo_2')); ?>
					昭和 <?php echo Form::radio('gengo', 'showa', isset($customer) ? $customer->gengo != null && $customer->gengo == 'showa' : '', array('id' => 'gengo_3')); ?>
					平成 <?php echo Form::radio('gengo', 'heisei', isset($customer) ? $customer->gengo != null && $customer->gengo == 'heisei' : '', array('id' => 'gengo_4')); ?>

	</fieldset>
	<fieldset>

				<?php echo Form::input('birthday_year',Input::post('birthday_year', isset($customer) ? $customer->birthday_year : ''),array('class' => 'col-md-3 form-control'));?>

				年

				<?php echo Form::input('birthday_month',Input::post('birthday_month', isset($customer) ? $customer->birthday_month : ''),array('class' => 'col-md-3 form-control'));?>

				月

				<?php echo Form::input('birthday_day',Input::post('birthday_day', isset($customer) ? $customer->birthday_day : ''),array('class' => 'col-md-3 form-control'));?>
			</div

				日

	</fieldset>
	<fieldset>

				<?php echo Form::label('メールアドレス', 'mail', array('class'=>'control-label')); ?>

					<?php echo Form::input('mail', Input::post('mail', isset($customer) ? $customer->mail : ''), array('class' => 'col-md-4 col-xs-7 form-control', 'placeholder'=>'example@mail.com')); ?>

	</fieldset>

	<fieldset>

			<?php echo Form::label('備考:', 'biko', array('class'=>'control-label')); ?>

				<?php echo Form::textarea('biko', Input::post('biko', isset($customer) ? $customer->biko : ''), array('class' => 'form-control', 'rows' => 6, 'cols' => 50, 'placeholder'=>'備考')); ?>

	</fieldset>

		<?php echo Form::submit('submit', '登録', array('class' => 'btn btn-primary')); ?>

<?php echo Form::close(); ?>


text:
package com.alipay.hulu.common.logger;

import android.util.Log;

import com.orhanobut.logger.FormatStrategy;

/**
 * Created by qiaoruikai on 2018/9/29 10:20 PM.
 */
public class SimpleFormatStrategy implements FormatStrategy {
    // 直接通过logcat打印
    public void log(int priority, String onceOnlyTag, String message) {
        Log.println(priority, onceOnlyTag, message);
    }
}


text:
<!doctype html>

        <meta charset="UTF-8" />
        <title>Fluid framework complete tests runner</title>

        <link rel="stylesheet" href="../infusion/tests/lib/qunit/css/qunit.css" type="text/css" media="screen">
        <link rel="stylesheet" href="../infusion/tests/lib/qunit/addons/composite/qunit-composite.css">


text:
void *xmalloc(size_t size);
char *basen(char *s);
int compare(char *a, char *b, size_t size);

#define err(x) perror(x), exit(1)


text:
BASE_DIR=`dirname $0`

karma start $BASE_DIR/karma-unit.conf.js $*


text:
* 001 [Introduction](https://www.youtube.com/watch?v=GGMfM3pYK_4)
* 002 [Pluggable Storage Engines](https://www.youtube.com/watch?v=YvK7I9fYpK4)
* 003 [MMAP Storage Engine](https://www.youtube.com/watch?v=os3591KviNM)
* 004 [WiredTiger Storage Engine](https://www.youtube.com/watch?v=aNsugW7r3mM)
* 005 [Indexes](https://www.youtube.com/watch?v=U3iWPF5jP-g)
* 006 [Creating Indexes](https://www.youtube.com/watch?v=xi2gtzZez6Q)
* 007 [Discovering and Deleting Indexes](https://www.youtube.com/watch?v=dX49IcmTrGA)
* 008 [Multikey Indexes](https://www.youtube.com/watch?v=_NGwn_X82Dw)
* 009 [Dot Notation and Multikeys](https://www.youtube.com/watch?v=wT0_ktAZbBg)
* 010 [Index Creation - Option Unique](https://www.youtube.com/watch?v=D-Ra5TEaaL4)
* 011 [Index Creation - Sparse Indexes](https://www.youtube.com/watch?v=ZznHByqtTMA)
* 012 [Index Creation - Background](https://www.youtube.com/watch?v=AchmKNj2qhw)
* 013 [Using Explain](https://www.youtube.com/watch?v=liXIn8CnJaI)
* 014 [Explain: Verbosity](https://www.youtube.com/watch?v=WxXVun6bZ20)
* 015 [Covered Queries](https://www.youtube.com/watch?v=QyV79jsSJ9Y)
* 016 [When is an Index Used?](https://www.youtube.com/watch?v=JyQlxDc549c)
* 017 [How Large is Your Index](https://www.youtube.com/watch?v=wjA0eo_lihg)
* 018 [Number of Index Entries](https://www.youtube.com/watch?v=xiujksUfzUA)
* 019 [Geospatial Indexes](https://www.youtube.com/watch?v=UKUDYqNVL6I)
* 020 [Geospatial Spherical](https://www.youtube.com/watch?v=pULU4DVsUWQ)
* 021 [Text Indexes](https://www.youtube.com/watch?v=nLau5Fx9LC8)
* 022 [Efficiency of Index Use](https://www.youtube.com/watch?v=JJmIf0pn100)
* 023 [Efficiency of Index Use Example](https://www.youtube.com/watch?v=g032EW67SRA)
* 024 [Logging Slow Queries](https://www.youtube.com/watch?v=aWuvC-O7Qkk)
* 025 [Profiling](https://www.youtube.com/watch?v=pN1Yhrup9-I)
* 026 [Mongotop](https://www.youtube.com/watch?v=D9YLXgy7NYo)
* 027 [Mongostat](https://www.youtube.com/watch?v=E2aDTSes3Wc)
* 028 [Sharding Overview](https://www.youtube.com/watch?v=BDxT-VZdYqc)

Notes:

In Video 5 (Indexes) Andrew mentions that while reads are much faster with indexes, writes to a document will happen slower. This is true, but it's worth noting a caveat here: combination operations, such as update and deletion operations, where you find the document you want and then perform a write, will benefit from the index when you're performing the query stage, and then may be slowed by the index when you perform the write. Usually you're still better off having an index, but there are some special cases where this may not be true.

He mentions that indexes in mongodb are in btrees. This is true for MMAP (and therefore for MongoDB prior to 3.0), but it does depend on your storage engine. For example, when you are using WiredTiger, as of MongoDB 3.0, indexes are implemented in b+trees. Again, you can find details in Wikipedia (links provided here for your convenience).

In Video 19 (Geospatial Indexes): This lecture uses the now deprecated ensureIndex shell command. The preferred command is createIndex. Anywhere you see me using ensureIndex, imagine I used createIndex.

In Video 20 (Geospatial Spherical): This lecture uses the now deprecated ensureIndex shell command. The preferred command is createIndex. Anywhere you see me using ensureIndex, imagine I used createIndex.

In Video 21 (Text Indexes): At 0:36, Andrew says that when you search on strings with a standard index, the entire string must match. This isn't entirely true; a regex search will search the index (rather than the full collection), and if you anchor it on the left by beginning with ^, you can often do better still.

Video 23 (Efficiency of Index Use Example): At about 3:13, Shannon mentions that MongoDB can walk the index backward in order to sort on the final_grade field. While true given that we are sorting on only this field, if we want to sort on multiple fields, the direction of each field on which we want to sort in a query must be the same as the direction of each field specified in the index. So if we want to sort using something like db.collection.find( { a: 75 } ).sort( { a: 1, b: -1 } ), we must specify the index using the same directions, e.g., db.collection.createIndex( { a: 1, b: -1 } ).

Video 24 (Logging Slow Queries): Some of this material was recorded with an older version of the database. However, the logfile format has not changed significantly so you should be able to get the gist.

Video 25 (Profiling): The exact output of the profiler varies with MongoDB version and with storage engine. We recommend you check the [docs](http://docs.mongodb.org/manual/reference/database-profiler/?_ga=1.176361957.1775304563.1450209975) for the specifics of what your query profile is telling you.


text:
package de.htwg.zeta.generatorControl.actors.developer.manager

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef
import akka.actor.Props
import com.google.inject.Injector
import de.htwg.zeta.common.models.frontend.CreateGenerator
import de.htwg.zeta.common.models.frontend.GeneratorImageNotFoundFailure
import de.htwg.zeta.common.models.worker.CreateGeneratorJob
import de.htwg.zeta.persistence.general.GeneratorImageRepository

object GeneratorManager {
  protected val messageReceive = "GeneratorManager - Received CreateGenerator 'imageId: {}'"
  protected val messageImageFound = "GeneratorManager - GeneratorImage found in database '{}'"
  protected val messageImageNotFound = "GeneratorManager - GeneratorImageNotFoundFailure: {}"

  def props(worker: ActorRef, injector: Injector): Props = Props(new GeneratorManager(worker, injector))
}

class GeneratorManager(worker: ActorRef, injector: Injector) extends Actor with ActorLogging {

  private val generatorImageRepo = injector.getInstance(classOf[GeneratorImageRepository])

  def createGenerator(create: CreateGenerator): Future[Unit] = {
    val reply = sender
    generatorImageRepo.read(create.imageId).map(image => {
      log.info(GeneratorManager.messageImageFound, image.id)
      worker ! CreateGeneratorJob(image.dockerImage, create.imageId, create.options)
    }).recover {
      case e: Exception =>
        log.error(GeneratorManager.messageImageNotFound, e.getMessage)
        reply ! GeneratorImageNotFoundFailure(e.getMessage)
    }
  }

  def receive: Receive = {
    case create: CreateGenerator =>
      log.info(GeneratorManager.messageReceive, create.imageId)
      createGenerator(create)
  }
}


text:
package com.google.cloud.dataflow.sdk.transforms;

import static com.google.cloud.dataflow.sdk.TestUtils.createInts;
import static com.google.cloud.dataflow.sdk.transforms.Partition.PartitionFn;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.google.cloud.dataflow.sdk.testing.DataflowAssert;
import com.google.cloud.dataflow.sdk.testing.TestPipeline;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.cloud.dataflow.sdk.values.PCollectionList;

import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Tests for {@link Partition}.
 */
@RunWith(JUnit4.class)
@SuppressWarnings("serial")
public class PartitionTest implements Serializable {
  static class ModFn implements PartitionFn<Integer> {
    public int partitionFor(Integer elem, int numPartitions) {
      return elem % numPartitions;
    }
  }

  static class IdentityFn implements PartitionFn<Integer> {
    public int partitionFor(Integer elem, int numPartitions) {
      return elem;
    }
  }

  @Test
  @Category(com.google.cloud.dataflow.sdk.testing.RunnableOnService.class)
  public void testEvenOddPartition() {
    TestPipeline p = TestPipeline.create();

    PCollection<Integer> input =
        createInts(p, Arrays.asList(591, 11789, 1257, 24578, 24799, 307));

    PCollectionList<Integer> outputs = input.apply(Partition.of(2, new ModFn()));
    assertTrue(outputs.size() == 2);
    DataflowAssert.that(outputs.get(0)).containsInAnyOrder(24578);
    DataflowAssert.that(outputs.get(1)).containsInAnyOrder(591, 11789, 1257,
        24799, 307);
    p.run();
  }

  @Test
  public void testModPartition() {
    TestPipeline p = TestPipeline.create();

    PCollection<Integer> input =
        createInts(p, Arrays.asList(1, 2, 4, 5));

    PCollectionList<Integer> outputs = input.apply(Partition.of(3, new ModFn()));
    assertTrue(outputs.size() == 3);
    DataflowAssert.that(outputs.get(0)).containsInAnyOrder();
    DataflowAssert.that(outputs.get(1)).containsInAnyOrder(1, 4);
    DataflowAssert.that(outputs.get(2)).containsInAnyOrder(2, 5);
    p.run();
  }

  @Test
  public void testOutOfBoundsPartitions() {
    TestPipeline p = TestPipeline.create();

    PCollection<Integer> input = createInts(p, Arrays.asList(-1));

    input.apply(Partition.of(5, new IdentityFn()));

    try {
      p.run();
    } catch (RuntimeException e) {
      assertThat(e.toString(), containsString(
          "Partition function returned out of bounds index: -1 not in [0..5)"));
    }
  }

  @Test
  public void testZeroNumPartitions() {
    TestPipeline p = TestPipeline.create();

    PCollection<Integer> input = createInts(p, Arrays.asList(591));

    try {
      input.apply(Partition.of(0, new IdentityFn()));
      fail("should have failed");
    } catch (IllegalArgumentException exn) {
      assertThat(exn.toString(), containsString("numPartitions must be > 0"));
    }
  }

  @Test
  public void testDroppedPartition() {
    TestPipeline p = TestPipeline.create();

    PCollection<Integer> input = createInts(p,
        Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12));

    // Compute the set of integers either 1 or 2 mod 3, the hard way.
    PCollectionList<Integer> outputs =
        input.apply(Partition.of(3, new ModFn()));

    List<PCollection<Integer>> outputsList = new ArrayList<>(outputs.getAll());
    outputsList.remove(0);
    outputs = PCollectionList.of(outputsList);
    assertTrue(outputs.size() == 2);

    PCollection<Integer> output = outputs.apply(Flatten.<Integer>create());
    DataflowAssert.that(output).containsInAnyOrder(2, 4, 5, 7, 8, 10, 11);
    p.run();
  }
}


text:
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import * as React from 'react';
import PropTypes from 'prop-types';
import { elementTypeAcceptingRef } from '@material-ui/utils';
import { useThemeProps } from '@material-ui/system';
import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer';
import ownerDocument from '../utils/ownerDocument';
import ownerWindow from '../utils/ownerWindow';
import useEventCallback from '../utils/useEventCallback';
import useEnhancedEffect from '../utils/useEnhancedEffect';
import { duration } from '../styles/createTransitions';
import useTheme from '../styles/useTheme';
import { getTransitionProps } from '../transitions/utils';
import NoSsr from '../NoSsr';
import SwipeArea from './SwipeArea'; // This value is closed to what browsers are using internally to
// trigger a native scroll.

import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var UNCERTAINTY_THRESHOLD = 3; // px
// This is the part of the drawer displayed on touch start.

var DRAG_STARTED_SIGNAL = 20; // px
// We can only have one instance at the time claiming ownership for handling the swipe.
// Otherwise, the UX would be confusing.
// That's why we use a singleton here.

var claimedSwipeInstance = null; // Exported for test purposes.

export function reset() {
  claimedSwipeInstance = null;
}

function calculateCurrentX(anchor, touches, doc) {
  return anchor === 'right' ? doc.body.offsetWidth - touches[0].pageX : touches[0].pageX;
}

function calculateCurrentY(anchor, touches, containerWindow) {
  return anchor === 'bottom' ? containerWindow.innerHeight - touches[0].clientY : touches[0].clientY;
}

function getMaxTranslate(horizontalSwipe, paperInstance) {
  return horizontalSwipe ? paperInstance.clientWidth : paperInstance.clientHeight;
}

function getTranslate(currentTranslate, startLocation, open, maxTranslate) {
  return Math.min(Math.max(open ? startLocation - currentTranslate : maxTranslate + startLocation - currentTranslate, 0), maxTranslate);
}
/**
 * @param {Element | null} element
 * @param {Element} rootNode
 */

function getDomTreeShapes(element, rootNode) {
  // Adapted from https://github.com/oliviertassinari/react-swipeable-views/blob/7666de1dba253b896911adf2790ce51467670856/packages/react-swipeable-views/src/SwipeableViews.js#L129
  var domTreeShapes = [];

  while (element && element !== rootNode.parentElement) {
    var style = ownerWindow(rootNode).getComputedStyle(element);

    if ( // Ignore the scroll children if the element is absolute positioned.
    style.getPropertyValue('position') === 'absolute' || // Ignore the scroll children if the element has an overflowX hidden
    style.getPropertyValue('overflow-x') === 'hidden') {// noop
    } else if (element.clientWidth > 0 && element.scrollWidth > element.clientWidth || element.clientHeight > 0 && element.scrollHeight > element.clientHeight) {
      // Ignore the nodes that have no width.
      // Keep elements with a scroll
      domTreeShapes.push(element);
    }

    element = element.parentElement;
  }

  return domTreeShapes;
}
/**
 * @param {object} param0
 * @param {ReturnType<getDomTreeShapes>} param0.domTreeShapes
 */

function computeHasNativeHandler(_ref) {
  var domTreeShapes = _ref.domTreeShapes,
      start = _ref.start,
      current = _ref.current,
      anchor = _ref.anchor;
  // Adapted from https://github.com/oliviertassinari/react-swipeable-views/blob/7666de1dba253b896911adf2790ce51467670856/packages/react-swipeable-views/src/SwipeableViews.js#L175
  var axisProperties = {
    scrollPosition: {
      x: 'scrollLeft',
      y: 'scrollTop'
    },
    scrollLength: {
      x: 'scrollWidth',
      y: 'scrollHeight'
    },
    clientLength: {
      x: 'clientWidth',
      y: 'clientHeight'
    }
  };
  return domTreeShapes.some(function (shape) {
    // Determine if we are going backward or forward.
    var goingForward = current >= start;

    if (anchor === 'top' || anchor === 'left') {
      goingForward = !goingForward;
    }

    var axis = anchor === 'left' || anchor === 'right' ? 'x' : 'y';
    var scrollPosition = Math.round(shape[axisProperties.scrollPosition[axis]]);
    var areNotAtStart = scrollPosition > 0;
    var areNotAtEnd = scrollPosition + shape[axisProperties.clientLength[axis]] < shape[axisProperties.scrollLength[axis]];

    if (goingForward && areNotAtEnd || !goingForward && areNotAtStart) {
      return true;
    }

    return false;
  });
}

var iOS = typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent);
var transitionDurationDefault = {
  enter: duration.enteringScreen,
  exit: duration.leavingScreen
};
var SwipeableDrawer = /*#__PURE__*/React.forwardRef(function SwipeableDrawer(inProps, ref) {
  var props = useThemeProps({
    name: 'MuiSwipeableDrawer',
    props: inProps
  });
  var theme = useTheme();
  var _props$anchor = props.anchor,
      anchor = _props$anchor === void 0 ? 'left' : _props$anchor,
      _props$disableBackdro = props.disableBackdropTransition,
      disableBackdropTransition = _props$disableBackdro === void 0 ? false : _props$disableBackdro,
      _props$disableDiscove = props.disableDiscovery,
      disableDiscovery = _props$disableDiscove === void 0 ? false : _props$disableDiscove,
      _props$disableSwipeTo = props.disableSwipeToOpen,
      disableSwipeToOpen = _props$disableSwipeTo === void 0 ? iOS : _props$disableSwipeTo,
      hideBackdrop = props.hideBackdrop,
      _props$hysteresis = props.hysteresis,
      hysteresis = _props$hysteresis === void 0 ? 0.52 : _props$hysteresis,
      _props$minFlingVeloci = props.minFlingVelocity,
      minFlingVelocity = _props$minFlingVeloci === void 0 ? 450 : _props$minFlingVeloci,
      _props$ModalProps = props.ModalProps;
  _props$ModalProps = _props$ModalProps === void 0 ? {} : _props$ModalProps;

  var BackdropProps = _props$ModalProps.BackdropProps,
      ModalPropsProp = _objectWithoutProperties(_props$ModalProps, ["BackdropProps"]),
      onClose = props.onClose,
      onOpen = props.onOpen,
      open = props.open,
      _props$PaperProps = props.PaperProps,
      PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps,
      SwipeAreaProps = props.SwipeAreaProps,
      _props$swipeAreaWidth = props.swipeAreaWidth,
      swipeAreaWidth = _props$swipeAreaWidth === void 0 ? 20 : _props$swipeAreaWidth,
      _props$transitionDura = props.transitionDuration,
      transitionDuration = _props$transitionDura === void 0 ? transitionDurationDefault : _props$transitionDura,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'temporary' : _props$variant,
      other = _objectWithoutProperties(props, ["anchor", "disableBackdropTransition", "disableDiscovery", "disableSwipeToOpen", "hideBackdrop", "hysteresis", "minFlingVelocity", "ModalProps", "onClose", "onOpen", "open", "PaperProps", "SwipeAreaProps", "swipeAreaWidth", "transitionDuration", "variant"]);

  var _React$useState = React.useState(false),
      maybeSwiping = _React$useState[0],
      setMaybeSwiping = _React$useState[1];

  var swipeInstance = React.useRef({
    isSwiping: null
  });
  var swipeAreaRef = React.useRef();
  var backdropRef = React.useRef();
  var paperRef = React.useRef();
  var touchDetected = React.useRef(false); // Ref for transition duration based on / to match swipe speed

  var calculatedDurationRef = React.useRef(); // Use a ref so the open value used is always up to date inside useCallback.

  useEnhancedEffect(function () {
    calculatedDurationRef.current = null;
  }, [open]);
  var setPosition = React.useCallback(function (translate) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var _options$mode = options.mode,
        mode = _options$mode === void 0 ? null : _options$mode,
        _options$changeTransi = options.changeTransition,
        changeTransition = _options$changeTransi === void 0 ? true : _options$changeTransi;
    var anchorRtl = getAnchor(theme, anchor);
    var rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchorRtl) !== -1 ? 1 : -1;
    var horizontalSwipe = isHorizontal(anchor);
    var transform = horizontalSwipe ? "translate(".concat(rtlTranslateMultiplier * translate, "px, 0)") : "translate(0, ".concat(rtlTranslateMultiplier * translate, "px)");
    var drawerStyle = paperRef.current.style;
    drawerStyle.webkitTransform = transform;
    drawerStyle.transform = transform;
    var transition = '';

    if (mode) {
      transition = theme.transitions.create('all', getTransitionProps({
        timeout: transitionDuration
      }, {
        mode: mode
      }));
    }

    if (changeTransition) {
      drawerStyle.webkitTransition = transition;
      drawerStyle.transition = transition;
    }

    if (!disableBackdropTransition && !hideBackdrop) {
      var backdropStyle = backdropRef.current.style;
      backdropStyle.opacity = 1 - translate / getMaxTranslate(horizontalSwipe, paperRef.current);

      if (changeTransition) {
        backdropStyle.webkitTransition = transition;
        backdropStyle.transition = transition;
      }
    }
  }, [anchor, disableBackdropTransition, hideBackdrop, theme, transitionDuration]);
  var handleBodyTouchEnd = useEventCallback(function (nativeEvent) {
    if (!touchDetected.current) {
      return;
    }

    claimedSwipeInstance = null;
    touchDetected.current = false;
    setMaybeSwiping(false); // The swipe wasn't started.

    if (!swipeInstance.current.isSwiping) {
      swipeInstance.current.isSwiping = null;
      return;
    }

    swipeInstance.current.isSwiping = null;
    var anchorRtl = getAnchor(theme, anchor);
    var horizontal = isHorizontal(anchor);
    var current;

    if (horizontal) {
      current = calculateCurrentX(anchorRtl, nativeEvent.changedTouches, ownerDocument(nativeEvent.currentTarget));
    } else {
      current = calculateCurrentY(anchorRtl, nativeEvent.changedTouches, ownerWindow(nativeEvent.currentTarget));
    }

    var startLocation = horizontal ? swipeInstance.current.startX : swipeInstance.current.startY;
    var maxTranslate = getMaxTranslate(horizontal, paperRef.current);
    var currentTranslate = getTranslate(current, startLocation, open, maxTranslate);
    var translateRatio = currentTranslate / maxTranslate;

    if (Math.abs(swipeInstance.current.velocity) > minFlingVelocity) {
      // Calculate transition duration to match swipe speed
      calculatedDurationRef.current = Math.abs((maxTranslate - currentTranslate) / swipeInstance.current.velocity) * 1000;
    }

    if (open) {
      if (swipeInstance.current.velocity > minFlingVelocity || translateRatio > hysteresis) {
        onClose();
      } else {
        // Reset the position, the swipe was aborted.
        setPosition(0, {
          mode: 'exit'
        });
      }

      return;
    }

    if (swipeInstance.current.velocity < -minFlingVelocity || 1 - translateRatio > hysteresis) {
      onOpen();
    } else {
      // Reset the position, the swipe was aborted.
      setPosition(getMaxTranslate(horizontal, paperRef.current), {
        mode: 'enter'
      });
    }
  });
  var handleBodyTouchMove = useEventCallback(function (nativeEvent) {
    // the ref may be null when a parent component updates while swiping
    if (!paperRef.current || !touchDetected.current) {
      return;
    } // We are not supposed to handle this touch move because the swipe was started in a scrollable container in the drawer

    if (claimedSwipeInstance !== null && claimedSwipeInstance !== swipeInstance.current) {
      return;
    }

    var anchorRtl = getAnchor(theme, anchor);
    var horizontalSwipe = isHorizontal(anchor);
    var currentX = calculateCurrentX(anchorRtl, nativeEvent.touches, ownerDocument(nativeEvent.currentTarget));
    var currentY = calculateCurrentY(anchorRtl, nativeEvent.touches, ownerWindow(nativeEvent.currentTarget));

    if (open && paperRef.current.contains(nativeEvent.target) && claimedSwipeInstance === null) {
      var domTreeShapes = getDomTreeShapes(nativeEvent.target, paperRef.current);
      var hasNativeHandler = computeHasNativeHandler({
        domTreeShapes: domTreeShapes,
        start: horizontalSwipe ? swipeInstance.current.startX : swipeInstance.current.startY,
        current: horizontalSwipe ? currentX : currentY,
        anchor: anchor
      });

      if (hasNativeHandler) {
        claimedSwipeInstance = true;
        return;
      }

      claimedSwipeInstance = swipeInstance.current;
    } // We don't know yet.

    if (swipeInstance.current.isSwiping == null) {
      var dx = Math.abs(currentX - swipeInstance.current.startX);
      var dy = Math.abs(currentY - swipeInstance.current.startY);
      var definitelySwiping = horizontalSwipe ? dx > dy && dx > UNCERTAINTY_THRESHOLD : dy > dx && dy > UNCERTAINTY_THRESHOLD;

      if (definitelySwiping && nativeEvent.cancelable) {
        nativeEvent.preventDefault();
      }

      if (definitelySwiping === true || (horizontalSwipe ? dy > UNCERTAINTY_THRESHOLD : dx > UNCERTAINTY_THRESHOLD)) {
        swipeInstance.current.isSwiping = definitelySwiping;

        if (!definitelySwiping) {
          handleBodyTouchEnd(nativeEvent);
          return;
        } // Shift the starting point.

        swipeInstance.current.startX = currentX;
        swipeInstance.current.startY = currentY; // Compensate for the part of the drawer displayed on touch start.

        if (!disableDiscovery && !open) {
          if (horizontalSwipe) {
            swipeInstance.current.startX -= DRAG_STARTED_SIGNAL;
          } else {
            swipeInstance.current.startY -= DRAG_STARTED_SIGNAL;
          }
        }
      }
    }

    if (!swipeInstance.current.isSwiping) {
      return;
    }

    var maxTranslate = getMaxTranslate(horizontalSwipe, paperRef.current);
    var startLocation = horizontalSwipe ? swipeInstance.current.startX : swipeInstance.current.startY;

    if (open && !swipeInstance.current.paperHit) {
      startLocation = Math.min(startLocation, maxTranslate);
    }

    var translate = getTranslate(horizontalSwipe ? currentX : currentY, startLocation, open, maxTranslate);

    if (open) {
      if (!swipeInstance.current.paperHit) {
        var paperHit = horizontalSwipe ? currentX < maxTranslate : currentY < maxTranslate;

        if (paperHit) {
          swipeInstance.current.paperHit = true;
          swipeInstance.current.startX = currentX;
          swipeInstance.current.startY = currentY;
        } else {
          return;
        }
      } else if (translate === 0) {
        swipeInstance.current.startX = currentX;
        swipeInstance.current.startY = currentY;
      }
    }

    if (swipeInstance.current.lastTranslate === null) {
      swipeInstance.current.lastTranslate = translate;
      swipeInstance.current.lastTime = performance.now() + 1;
    }

    var velocity = (translate - swipeInstance.current.lastTranslate) / (performance.now() - swipeInstance.current.lastTime) * 1e3; // Low Pass filter.

    swipeInstance.current.velocity = swipeInstance.current.velocity * 0.4 + velocity * 0.6;
    swipeInstance.current.lastTranslate = translate;
    swipeInstance.current.lastTime = performance.now(); // We are swiping, let's prevent the scroll event on iOS.

    if (nativeEvent.cancelable) {
      nativeEvent.preventDefault();
    }

    setPosition(translate);
  });
  var handleBodyTouchStart = useEventCallback(function (nativeEvent) {
    // We are not supposed to handle this touch move.
    // Example of use case: ignore the event if there is a Slider.
    if (nativeEvent.defaultPrevented) {
      return;
    } // We can only have one node at the time claiming ownership for handling the swipe.

    if (nativeEvent.defaultMuiPrevented) {
      return;
    } // At least one element clogs the drawer interaction zone.

    if (open && (hideBackdrop || !backdropRef.current.contains(nativeEvent.target)) && !paperRef.current.contains(nativeEvent.target)) {
      return;
    }

    var anchorRtl = getAnchor(theme, anchor);
    var horizontalSwipe = isHorizontal(anchor);
    var currentX = calculateCurrentX(anchorRtl, nativeEvent.touches, ownerDocument(nativeEvent.currentTarget));
    var currentY = calculateCurrentY(anchorRtl, nativeEvent.touches, ownerWindow(nativeEvent.currentTarget));

    if (!open) {
      if (disableSwipeToOpen || nativeEvent.target !== swipeAreaRef.current) {
        return;
      }

      if (horizontalSwipe) {
        if (currentX > swipeAreaWidth) {
          return;
        }
      } else if (currentY > swipeAreaWidth) {
        return;
      }
    }

    nativeEvent.defaultMuiPrevented = true;
    claimedSwipeInstance = null;
    swipeInstance.current.startX = currentX;
    swipeInstance.current.startY = currentY;
    setMaybeSwiping(true);

    if (!open && paperRef.current) {
      // The ref may be null when a parent component updates while swiping.
      setPosition(getMaxTranslate(horizontalSwipe, paperRef.current) + (disableDiscovery ? 15 : -DRAG_STARTED_SIGNAL), {
        changeTransition: false
      });
    }

    swipeInstance.current.velocity = 0;
    swipeInstance.current.lastTime = null;
    swipeInstance.current.lastTranslate = null;
    swipeInstance.current.paperHit = false;
    touchDetected.current = true;
  });
  React.useEffect(function () {
    if (variant === 'temporary') {
      var doc = ownerDocument(paperRef.current);
      doc.addEventListener('touchstart', handleBodyTouchStart); // A blocking listener prevents Firefox's navbar to auto-hide on scroll.
      // It only needs to prevent scrolling on the drawer's content when open.
      // When closed, the overlay prevents scrolling.

      doc.addEventListener('touchmove', handleBodyTouchMove, {
        passive: !open
      });
      doc.addEventListener('touchend', handleBodyTouchEnd);
      return function () {
        doc.removeEventListener('touchstart', handleBodyTouchStart);
        doc.removeEventListener('touchmove', handleBodyTouchMove, {
          passive: !open
        });
        doc.removeEventListener('touchend', handleBodyTouchEnd);
      };
    }

    return undefined;
  }, [variant, open, handleBodyTouchStart, handleBodyTouchMove, handleBodyTouchEnd]);
  React.useEffect(function () {
    return function () {
      // We need to release the lock.
      if (claimedSwipeInstance === swipeInstance.current) {
        claimedSwipeInstance = null;
      }
    };
  }, []);
  React.useEffect(function () {
    if (!open) {
      setMaybeSwiping(false);
    }
  }, [open]);
  return /*#__PURE__*/_jsxs(React.Fragment, {
    children: [/*#__PURE__*/_jsx(Drawer, _extends({
      open: variant === 'temporary' && maybeSwiping ? true : open,
      variant: variant,
      ModalProps: _extends({
        BackdropProps: _extends({}, BackdropProps, {
          ref: backdropRef
        })
      }, ModalPropsProp),
      hideBackdrop: hideBackdrop,
      PaperProps: _extends({}, PaperProps, {
        style: _extends({
          pointerEvents: variant === 'temporary' && !open ? 'none' : ''
        }, PaperProps.style),
        ref: paperRef
      }),
      anchor: anchor,
      transitionDuration: calculatedDurationRef.current || transitionDuration,
      onClose: onClose,
      ref: ref
    }, other)), !disableSwipeToOpen && variant === 'temporary' && /*#__PURE__*/_jsx(NoSsr, {
      children: /*#__PURE__*/_jsx(SwipeArea, _extends({
        anchor: anchor,
        ref: swipeAreaRef,
        width: swipeAreaWidth
      }, SwipeAreaProps))
    })]
  });
});
process.env.NODE_ENV !== "production" ? SwipeableDrawer.propTypes
/* remove-proptypes */
= {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * @ignore
   */
  anchor: PropTypes.oneOf(['bottom', 'left', 'right', 'top']),

  /**
   * The content of the component.
   */
  children: PropTypes.node,

  /**
   * Disable the backdrop transition.
   * This can improve the FPS on low-end devices.
   * @default false
   */
  disableBackdropTransition: PropTypes.bool,

  /**
   * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit
   * to promote accidental discovery of the swipe gesture.
   * @default false
   */
  disableDiscovery: PropTypes.bool,

  /**
   * If `true`, swipe to open is disabled. This is useful in browsers where swiping triggers
   * navigation actions. Swipe to open is disabled on iOS browsers by default.
   * @default typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent)
   */
  disableSwipeToOpen: PropTypes.bool,

  /**
   * @ignore
   */
  hideBackdrop: PropTypes.bool,

  /**
   * Affects how far the drawer must be opened/closed to change its state.
   * Specified as percent (0-1) of the width of the drawer
   * @default 0.52
   */
  hysteresis: PropTypes.number,

  /**
   * Defines, from which (average) velocity on, the swipe is
   * defined as complete although hysteresis isn't reached.
   * Good threshold is between 250 - 1000 px/s
   * @default 450
   */
  minFlingVelocity: PropTypes.number,

  /**
   * @ignore
   */
  ModalProps: PropTypes
  /* @typescript-to-proptypes-ignore */
  .shape({
    BackdropProps: PropTypes.shape({
      component: elementTypeAcceptingRef
    })
  }),

  /**
   * Callback fired when the component requests to be closed.
   *
   * @param {object} event The event source of the callback.
   */
  onClose: PropTypes.func.isRequired,

  /**
   * Callback fired when the component requests to be opened.
   *
   * @param {object} event The event source of the callback.
   */
  onOpen: PropTypes.func.isRequired,

  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool.isRequired,

  /**
   * @ignore
   */
  PaperProps: PropTypes
  /* @typescript-to-proptypes-ignore */
  .shape({
    component: elementTypeAcceptingRef,
    style: PropTypes.object
  }),

  /**
   * The element is used to intercept the touch events on the edge.
   */
  SwipeAreaProps: PropTypes.object,

  /**
   * The width of the left most (or right most) area in `px` that
   * the drawer can be swiped open from.
   * @default 20
   */
  swipeAreaWidth: PropTypes.number,

  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   * @default { enter: duration.enteringScreen, exit: duration.leavingScreen }
   */
  transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })]),

  /**
   * @ignore
   */
  variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary'])
} : void 0;
export default SwipeableDrawer;


text:
This chapter contains this sample:

* WebSampleApp

Building this sample starts with an empty ASP.NET Core Web project, and adds many features of ASP.NET Core.

To build and run the .NET Core samples, please install
* Visual Studio 2017 with the .NET Core workload

Please download and install the tools from [.NET Core downloads](https://www.microsoft.com/net/core).

For code comments and issues please check [Professional C#'s GitHub Repository](https://github.com/ProfessionalCSharp/ProfessionalCSharp6)

Please check my blog [csharp.christiannagel.com](https://csharp.christiannagel.com "csharp.christiannagel.com") for additional information for topics covered in the book.

Thank you!


text:
package org.ScripterRon.BitcoinWallet;

import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JPanel;

/**
 * ButtonPane create a JPanel containing one or more buttons arranged horizontally
 */
public class ButtonPane extends JPanel {

    /**
     * Create a JPanel containing the specified buttons
     *
     * @param       listener            Action listener
     * @param       spacing             Horizontal spacing between the buttons
     * @param       items               One or more button specifications
     */
    public ButtonPane(ActionListener listener, int spacing, String[]... items) {
        super();
        boolean addSpacer = false;
        for (String[] item : items) {
            if (addSpacer)
                add(Box.createHorizontalStrut(spacing));
            JButton button = new JButton(item[0]);
            button.setActionCommand(item[1]);
            button.addActionListener(listener);
            add(button);
            addSpacer = true;
        }
    }
}


text:
module IslayShop
  module Admin
    class PromotionsController < IslayShop::Admin::ApplicationController
      require 'csv'

      resourceful :promotion
      header 'Orders - Promotions'
      nav_scope :orders

      def index
        @promotions = Promotion.summary.page(params[:page]).filtered(params[:filter]).sorted(params[:sort])
      end

      def show
        @promotion = Promotion.find(params[:id])
      end

      def codes
        @promotion = Promotion.find(params[:id])
        if @promotion and @promotion.code_based?
          unless @promotion.codes.empty?
            csv_data = CSV.generate(:headers => :first_row) do |csv|
              csv << ['Code', 'Status']
              @promotion.codes.each {|c| csv << [c.code, c.redeemed_at.blank? ? 'Active' : "Redeemed: #{c.redeemed_at}" ] }
            end
            send_data(csv_data, :type => 'text/csv; charset=utf-8; header=present', :filename => "promotion_codes_for_#{@promotion.name.parameterize}.csv")
          end
        end
      end

      private

      def dependencies
        @skus = Sku.published.summarize_product.order("product_name ASC").map do |e|
          ["#{e.product_name} - #{e.short_desc}", e.id]
        end

        @shipping_discount_modes = [
          ["Set Total", "set"],
          ["Fixed", "fixed"],
          ["Percentage", "percentage"]
        ]

        @categories = ProductCategory.tree
        @products = Product.published
      end

      def invalid_record
        @promotion.prefill
      end

      def find_record
        if params[:action] == 'edit'
          Promotion.find(params[:id]).tap(&:prefill)
        else
          Promotion.find(params[:id])
        end
      end

      def new_record
        Promotion.new.tap(&:prefill)
      end

      def permitted_params
        params.permit(:promotion => [
          :name, :start_at, :end_at, :conditions_attributes, :effects_attributes,
          :active, :description, :application_limit, :publish_application_limit
        ])
      end
    end
  end
end


text:
import logging
from typing import Optional

import anndata
import numpy as np
import torch
from torch.distributions import Normal

from scvi import _CONSTANTS
from scvi.core.modules import TOTALVAE

from .scvi_data_loader import ScviDataLoader

logger = logging.getLogger(__name__)

def _unpack_tensors(tensors):
    x = tensors[_CONSTANTS.X_KEY]
    local_l_mean = tensors[_CONSTANTS.LOCAL_L_MEAN_KEY]
    local_l_var = tensors[_CONSTANTS.LOCAL_L_VAR_KEY]
    batch_index = tensors[_CONSTANTS.BATCH_KEY]
    labels = tensors[_CONSTANTS.LABELS_KEY]
    y = tensors[_CONSTANTS.PROTEIN_EXP_KEY]
    return x, local_l_mean, local_l_var, batch_index, labels, y

class TotalDataLoader(ScviDataLoader):
    """
    Extended data loader for totalVI.

    Parameters
    ----------
    model :
        A model instance from class ``TOTALVI``
    adata:
        A registered AnnData object
    shuffle :
        Specifies if a `RandomSampler` or a `SequentialSampler` should be used
    indices :
        Specifies how the data should be split with regards to train/test or labelled/unlabelled
    use_cuda :
        Default: ``True``
    data_loader_kwargs :
        Keyword arguments to passed into the `DataLoader`

    """

    def __init__(
        self,
        model: TOTALVAE,
        adata: anndata.AnnData,
        shuffle: bool = False,
        indices: Optional[np.ndarray] = None,
        use_cuda: bool = True,
        batch_size: int = 256,
        data_loader_kwargs=dict(),
    ):
        super().__init__(
            model,
            adata,
            shuffle=shuffle,
            indices=indices,
            use_cuda=use_cuda,
            batch_size=batch_size,
            data_loader_kwargs=data_loader_kwargs,
        )

    @property
    def _data_and_attributes(self):
        return {
            _CONSTANTS.X_KEY: np.float32,
            _CONSTANTS.BATCH_KEY: np.int64,
            _CONSTANTS.LOCAL_L_MEAN_KEY: np.float32,
            _CONSTANTS.LOCAL_L_VAR_KEY: np.float32,
            _CONSTANTS.LABELS_KEY: np.int64,
            _CONSTANTS.PROTEIN_EXP_KEY: np.float32,
        }

    @torch.no_grad()
    def elbo(self):
        elbo = self.compute_elbo(self.model)
        return elbo

    elbo.mode = "min"

    @torch.no_grad()
    def reconstruction_error(self, mode="total"):
        ll_gene, ll_protein = self.compute_reconstruction_error(self.model)
        if mode == "total":
            return ll_gene + ll_protein
        elif mode == "gene":
            return ll_gene
        else:
            return ll_protein

    reconstruction_error.mode = "min"

    @torch.no_grad()
    def marginal_ll(self, n_mc_samples=1000):
        ll = self.compute_marginal_log_likelihood()
        return ll

    @torch.no_grad()
    def get_protein_background_mean(self):
        background_mean = []
        for tensors in self:
            x, _, _, batch_index, label, y = _unpack_tensors(tensors)
            outputs = self.model.inference(
                x, y, batch_index=batch_index, label=label, n_samples=1
            )
            b_mean = outputs["py_"]["rate_back"]
            background_mean += [np.array(b_mean.cpu())]
        return np.concatenate(background_mean)

    def compute_elbo(self, vae: TOTALVAE, **kwargs):
        """
        Computes the ELBO.

        The ELBO is the reconstruction error + the KL divergences
        between the variational distributions and the priors.
        It differs from the marginal log likelihood.
        Specifically, it is a lower bound on the marginal log likelihood
        plus a term that is constant with respect to the variational distribution.
        It still gives good insights on the modeling of the data, and is fast to compute.

        Parameters
        ----------
        vae
            vae model
        **kwargs
            keyword args for forward

        """
        # Iterate once over the data loader and computes the total log_likelihood
        elbo = 0
        for _, tensors in enumerate(self):
            x, local_l_mean, local_l_var, batch_index, labels, y = _unpack_tensors(
                tensors
            )
            (
                reconst_loss_gene,
                reconst_loss_protein,
                kl_div_z,
                kl_div_gene_l,
                kl_div_back_pro,
            ) = vae(
                x,
                y,
                local_l_mean,
                local_l_var,
                batch_index=batch_index,
                label=labels,
                **kwargs,
            )
            elbo += torch.sum(
                reconst_loss_gene
                + reconst_loss_protein
                + kl_div_z
                + kl_div_gene_l
                + kl_div_back_pro
            ).item()
        n_samples = len(self.indices)
        return elbo / n_samples

    def compute_reconstruction_error(self, vae: TOTALVAE, **kwargs):
        r"""
        Computes log p(x/z), which is the reconstruction error.

        Differs from the marginal log likelihood, but still gives good
        insights on the modeling of the data, and is fast to compute

        This is really a helper function to self.ll, self.ll_protein, etc.

        """
        # Iterate once over the data loader and computes the total log_likelihood
        log_lkl_gene = 0
        log_lkl_protein = 0
        for _, tensors in enumerate(self):
            x, local_l_mean, local_l_var, batch_index, labels, y = _unpack_tensors(
                tensors
            )
            (
                reconst_loss_gene,
                reconst_loss_protein,
                kl_div_z,
                kl_div_l_gene,
                kl_div_back_pro,
            ) = vae(
                x,
                y,
                local_l_mean,
                local_l_var,
                batch_index=batch_index,
                label=labels,
                **kwargs,
            )
            log_lkl_gene += torch.sum(reconst_loss_gene).item()
            log_lkl_protein += torch.sum(reconst_loss_protein).item()

        n_samples = len(self.indices)
        return log_lkl_gene / n_samples, log_lkl_protein / n_samples

    def compute_marginal_log_likelihood(
        self, n_samples_mc: int = 100, batch_size: int = 96
    ):
        """
        Computes a biased estimator for log p(x, y), which is the marginal log likelihood.

        Despite its bias, the estimator still converges to the real value
        of log p(x, y) when n_samples_mc (for Monte Carlo) goes to infinity
        (a fairly high value like 100 should be enough). 5000 is the standard in machine learning publications.
        Due to the Monte Carlo sampling, this method is not as computationally efficient
        as computing only the reconstruction loss

        Parameters
        ----------
        n_samples_mc
             (Default value = 100)
        batch_size
             (Default value = 96)

        """
        # Uses MC sampling to compute a tighter lower bound on log p(x)
        log_lkl = 0
        for _, tensors in enumerate(self.update_batch_size(batch_size)):
            x, local_l_mean, local_l_var, batch_index, labels, y = _unpack_tensors(
                tensors
            )
            to_sum = torch.zeros(x.size()[0], n_samples_mc)

            for i in range(n_samples_mc):

                # Distribution parameters and sampled variables
                outputs = self.model.inference(x, y, batch_index, labels)
                qz_m = outputs["qz_m"]
                qz_v = outputs["qz_v"]
                ql_m = outputs["ql_m"]
                ql_v = outputs["ql_v"]
                px_ = outputs["px_"]
                py_ = outputs["py_"]
                log_library = outputs["untran_l"]
                # really need not softmax transformed random variable
                z = outputs["untran_z"]
                log_pro_back_mean = outputs["log_pro_back_mean"]

                # Reconstruction Loss
                (
                    reconst_loss_gene,
                    reconst_loss_protein,
                ) = self.model.get_reconstruction_loss(x, y, px_, py_)

                # Log-probabilities
                p_l_gene = (
                    Normal(local_l_mean, local_l_var.sqrt())
                    .log_prob(log_library)
                    .sum(dim=-1)
                )
                p_z = Normal(0, 1).log_prob(z).sum(dim=-1)
                p_mu_back = self.model.back_mean_prior.log_prob(log_pro_back_mean).sum(
                    dim=-1
                )
                p_xy_zl = -(reconst_loss_gene + reconst_loss_protein)
                q_z_x = Normal(qz_m, qz_v.sqrt()).log_prob(z).sum(dim=-1)
                q_l_x = Normal(ql_m, ql_v.sqrt()).log_prob(log_library).sum(dim=-1)
                q_mu_back = (
                    Normal(py_["back_alpha"], py_["back_beta"])
                    .log_prob(log_pro_back_mean)
                    .sum(dim=-1)
                )
                to_sum[:, i] = (
                    p_z + p_l_gene + p_mu_back + p_xy_zl - q_z_x - q_l_x - q_mu_back
                )

            batch_log_lkl = torch.logsumexp(to_sum, dim=-1) - np.log(n_samples_mc)
            log_lkl += torch.sum(batch_log_lkl).item()

        n_samples = len(self.indices)
        # The minus sign is there because we actually look at the negative log likelihood
        return -log_lkl / n_samples


text:
<?php
require_once 'include/common.inc.php';

$name    = "";
$email   = "";
$result = false;

if (isGet())
{
    $corrId = getGetParam(PARAMETER_CORRID);
    $userInfo = getUserInfo($corrId);
    if (!empty($userInfo))
    {
        $result = true;
        $name = htmlspecialchars($userInfo[KEY_NAME]);
        $email = htmlspecialchars($userInfo[KEY_EMAIL]);
    }
}
buildSubscriptionResultLayout($name, $email, $result);


text:
'use strict';

var url = require('url');

module.exports = function(webUrl, scheme, packageName) {
	var o = url.parse(webUrl);
  var pathname = o.pathname || '';
  var search = o.search || '';
  var hash = o.hash || '';
	var path = o.host + pathname + search + hash;
	var ret = [
		{
			name: 'Custom URL Scheme for Android',
			uri: scheme + path,
      platform: 'Android'
		},
		{
			name: 'App Indexing for Android (http)',
			uri: 'android-app://' + packageName + '/' + o.protocol.replace(':', '') + '/' + path,
      platform: 'Android'
		},
		{
			name: 'App Indexing for Android (custom scheme)',
			uri: 'android-app://' + packageName + '/' + scheme.replace('://', '') + '/' + path,
      platform: 'Android'
		}
	];
	return ret;
};


text:
static char const* whoami = nullptr;

void
usage()
{
    std::cerr << "Usage: " << whoami << " filename" << std::endl
              << "Prints the number of pages in filename" << std::endl;
    exit(2);
}

int
main(int argc, char* argv[])
{
    whoami = QUtil::getWhoami(argv[0]);

    if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) {
        std::cout << whoami << " version 1.3" << std::endl;
        exit(0);
    }

    if (argc != 2) {
        usage();
    }
    char const* filename = argv[1];

    try {
        QPDF pdf;
        pdf.processFile(filename);
        QPDFObjectHandle root = pdf.getRoot();
        QPDFObjectHandle pages = root.getKey("/Pages");
        QPDFObjectHandle count = pages.getKey("/Count");
        std::cout << count.getIntValue() << std::endl;
    } catch (std::exception& e) {
        std::cerr << whoami << ": " << e.what() << std::endl;
        exit(2);
    }

    return 0;
}


text:
Bash Template Engine
====================

simple templating engine for bash

Very Simple Templating Engine

#### Usage

```bash
export grove_id="001"
# USER is a global variable that will be transposed to your current user name
./tmpl.sh "Hello {{USER}}, Your Grove id is {{grove_id}}"

# transposes to :
# ./tmpl.sh "Hello ferron, Your Grove id is 001"

```


text:
package org.javaee7.websocket.client;

import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;

/**
 * @author Arun Gupta
 */
@ServerEndpoint("/websocket")
public class MyEndpoint {

    @OnMessage
    public String sayHello(String name) {
        System.out.println("Received message in endpoint : " + name);
        return "Hello " + name;
    }

}


text:
<?php

namespace VersionControl\GitControlBundle\Command;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception\ConnectionException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface;
use VersionControl\GitControlBundle\Installer\DatabaseInstall;

/**
 * Command line based installer, Use to install and set up the application.
 *
 * @author Paul Schweppe <paulschweppe@gmail.com>
 */
class InstallerCommand extends Command
{
    /** @var \Doctrine\DBAL\Connection */
    private $db;

    /** @var \VersionControl\GitControlBundle\Installer\DatabaseInstall */
    private $installer;

    /** @var \Symfony\Component\Console\Output\OutputInterface */
    private $output;

    /** @var \Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface */
    private $cacheClearer;

    /** @var \Symfony\Component\Filesystem\Filesystem */
    private $filesystem;

    /** @var string */
    private $cacheDir;

    /** @var string */
    private $environment;

    /**
     * FOS User Manager.
     *
     * @var type
     */
    private $userManager;

    const EXIT_DATABASE_NOT_FOUND_ERROR = 3;
    const EXIT_GENERAL_DATABASE_ERROR = 4;
    const EXIT_PARAMETERS_NOT_FOUND = 5;
    const EXIT_MISSING_PERMISSIONS = 7;

    public function __construct(
        Connection $db,
        DatabaseInstall $installer,
        CacheClearerInterface $cacheClearer,
        Filesystem $filesystem,
        $cacheDir,
        $environment,
        $userManager
    ) {
        $this->db = $db;
        $this->installer = $installer;
        $this->cacheClearer = $cacheClearer;
        $this->filesystem = $filesystem;
        $this->cacheDir = $cacheDir;
        $this->environment = $environment;
        $this->userManager = $userManager;
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('version:install');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->output = $output;
        $this->installer->setOutput($output);

        $this->checkPermissions();
        $this->checkParameters();
        $this->checkDatabase();

        $this->installer->importSchema();

        if ($this->environment == 'test') {
            $this->installer->importTestData();
        } else {
            $this->installer->importData();
        }

        $this->cacheClear($output);
    }

    private function checkPermissions()
    {
        if (!is_writable('app/config')) {
            $this->output->writeln('app/config is not writable');
            exit(self::EXIT_MISSING_PERMISSIONS);
        }
    }

    private function checkParameters()
    {
        $parametersFile = 'app/config/parameters.yml';
        if (!is_file($parametersFile)) {
            $this->output->writeln("Required configuration file $parametersFile not found");
            exit(self::EXIT_PARAMETERS_NOT_FOUND);
        }
    }

    private function checkDatabase()
    {
        try {
            if (!$this->configuredDatabaseExists()) {
                $this->output->writeln(
                    sprintf(
                        "The configured database '%s' does not exist. Please run 'php app/console doctrine:database:create' to create the database first",
                        $this->db->getDatabase()
                    )
                );

                exit(self::EXIT_DATABASE_NOT_FOUND_ERROR);
            }
        } catch (ConnectionException $e) {
            $this->output->writeln('An error occured connecting to the database:');
            $this->output->writeln($e->getMessage());
            $this->output->writeln('Please check the database configuration in parameters.yml');
            exit(self::EXIT_GENERAL_DATABASE_ERROR);
        }
    }

    /**
     * @throws \Exception if an unexpected database error occurs
     */
    private function configuredDatabaseExists()
    {
        try {
            $this->db->connect();
        } catch (ConnectionException $e) {
            // @todo 1049 is MySQL's code for "database doesn't exist", refactor
            if ($e->getPrevious()->getCode() == 1049) {
                return false;
            }
            throw $e;
        }

        return true;
    }

    private function cacheClear(OutputInterface $output)
    {
        if (!is_writable($this->cacheDir)) {
            throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $this->cacheDir));
        }

        $output->writeln(sprintf('Clearing cache for directory <info>%s</info>', $this->cacheDir));
        $oldCacheDir = $this->cacheDir.'_old';

        if ($this->filesystem->exists($oldCacheDir)) {
            $this->filesystem->remove($oldCacheDir);
        }

        $this->cacheClearer->clear($this->cacheDir);

        $this->filesystem->rename($this->cacheDir, $oldCacheDir);
        $this->filesystem->remove($oldCacheDir);
    }

    /**
     * Creates a new admin user.
     *
     * @param string $username
     * @param string $password
     * @param string $email
     * @param string $name
     *
     * @return \FOS\UserBundle\Model\UserInterface
     */
    protected function createUser($username, $password, $email, $name)
    {
        $user = $this->userManager->createUser();
        $user->setUsername($username);
        $user->setEmail($email);
        $user->setPlainPassword($password);
        $user->setName($name);

        $user->setEnabled((bool) true);
        $user->addRole('ROLE_ADMIN');
        //$user->setSuperAdmin((Boolean) true);

        $this->userManager->updateUser($user);

        return $user;
    }
}


text:
namespace Gaffer
{

IE_CORE_FORWARDDECLARE( StringPlug )

} // namespace Gaffer

namespace GafferImage
{

class OpenImageIOReader : public ImageNode
{

	public :

		OpenImageIOReader( const std::string &name=defaultName<OpenImageIOReader>() );
		virtual ~OpenImageIOReader();

		IE_CORE_DECLARERUNTIMETYPEDEXTENSION( GafferImage::OpenImageIOReader, OpenImageIOReaderTypeId, ImageNode );

		enum MissingFrameMode
		{
			Error = 0,
			Black,
			Hold,
		};

		Gaffer::StringPlug *fileNamePlug();
		const Gaffer::StringPlug *fileNamePlug() const;

		/// Number of times the node has been refreshed.
		Gaffer::IntPlug *refreshCountPlug();
		const Gaffer::IntPlug *refreshCountPlug() const;

		Gaffer::IntPlug *missingFrameModePlug();
		const Gaffer::IntPlug *missingFrameModePlug() const;

		Gaffer::IntVectorDataPlug *availableFramesPlug();
		const Gaffer::IntVectorDataPlug *availableFramesPlug() const;

		virtual void affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const;

		static size_t supportedExtensions( std::vector<std::string> &extensions );

		/// Returns the maximum number of bytes OIIO will use
		/// to cache file loading.
		static size_t getCacheMemoryLimit();
		/// Sets the maximum number of bytes OIIO will use to
		/// cache file loading.
		static void setCacheMemoryLimit( size_t bytes );
		/// Returns the current memory usage of OIIO's cache in bytes.
		static size_t cacheMemoryUsage();

	protected :

		virtual void hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const;
		virtual void compute( Gaffer::ValuePlug *output, const Gaffer::Context *context ) const;

		virtual void hashFormat( const GafferImage::ImagePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const;
		virtual void hashDataWindow( const GafferImage::ImagePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const;
		virtual void hashMetadata( const GafferImage::ImagePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const;
		virtual void hashChannelNames( const GafferImage::ImagePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const;
		virtual void hashChannelData( const GafferImage::ImagePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const;

		virtual GafferImage::Format computeFormat( const Gaffer::Context *context, const ImagePlug *parent ) const;
		virtual Imath::Box2i computeDataWindow( const Gaffer::Context *context, const ImagePlug *parent ) const;
		virtual IECore::ConstCompoundObjectPtr computeMetadata( const Gaffer::Context *context, const ImagePlug *parent ) const;
		virtual IECore::ConstStringVectorDataPtr computeChannelNames( const Gaffer::Context *context, const ImagePlug *parent ) const;
		virtual IECore::ConstFloatVectorDataPtr computeChannelData( const std::string &channelName, const Imath::V2i &tileOrigin, const Gaffer::Context *context, const ImagePlug *parent ) const;

	private :

		void hashFileName( const Gaffer::Context *context, IECore::MurmurHash &h ) const;

		void plugSet( Gaffer::Plug *plug );

		static size_t g_firstPlugIndex;

};

IE_CORE_DECLAREPTR( OpenImageIOReader )

} // namespace GafferImage

#endif // GAFFERIMAGE_OPENIMAGEIOREADER_H


text:
<?php

namespace Jasny\HttpMessage\Response;

use Jasny\HttpMessage\Message;

/**
 * ServerRequest protocol version methods
 */
trait ProtocolVersion
{
    use Message\ProtocolVersion;

    /**
     * Determine the protocol versions based on the server params.
     *
     * @return string
     */
    protected function determineProtocolVersion()
    {
        return "1.1";
    }
}


text:
require_relative 'preparation/cache'

module Cassie::Queries::Statement
  module Preparation
    extend ::ActiveSupport::Concern

    included do
      class << self
        attr_accessor :prepare
      end
      self.prepare = true
    end

    module ClassMethods
      def inherited(subclass)
        subclass.prepare = prepare
        super
      end

      def prepare?
        !!prepare
      end
    end

    def statement
      statement = super

      if self.class.prepare?
        key = statement.cql if statement.respond_to?(:cql)
        key ||= statement.to_s

        unbound = statement_cache.fetch(key) do
          session.prepare(statement)
        end
        unbound.bind(statement.params)
      else
        statement
      end
    end

    private

    def statement_cache
      Cassie::Queries::Statement::Preparation.cache
    end
  end
end


text: A demo game for 2015 Game on Weekend


text:
package com.blazebit.storage.core.config.wildfly.executor;

import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedScheduledExecutorService;
import javax.enterprise.inject.Produces;

public class ManagedScheduledExecutorServiceProducer {

	@Produces
	@Resource
	ManagedScheduledExecutorService executorService;
}


text:
package org.auraframework.components.ui.button;

import org.auraframework.test.util.WebDriverTestCase;
import org.auraframework.util.test.annotation.PerfTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;

@PerfTest
public class ButtonUITest extends WebDriverTestCase {

    public ButtonUITest(String name) {
        super(name);
    }

    public void testButtonLabelRequired() throws Exception {
        final String errorMsg = "COMPONENT markup://uitest:button_LabelRequiredTest is missing required attribute 'label'";
        openNoAura("/uitest/button_LabelRequiredTest.cmp");
        auraUITestingUtil.waitForDocumentReady();

        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver d) {
                return auraUITestingUtil.getAuraErrorMessage().contains(errorMsg);
            }
        }, "Required label error not displayed");
    }

    public void testDomEventAttributeOnPressEvent() throws Exception {
        open("/uitest/button_Test.cmp");
        WebElement btn = findDomElement(By.cssSelector(".testDomEventBtn"));
        btn.click();

        String valueExpression = auraUITestingUtil.getValueFromRootExpr("v.isDomEventSet");
        valueExpression = auraUITestingUtil.prepareReturnStatement(valueExpression);
        assertTrue("domEvent attribute on event should have been set",
                auraUITestingUtil.getBooleanEval(valueExpression));
    }
}


text:
package com.androidproductions.servicemonitor.backend.data;

import com.androidproductions.servicemonitor.backend.data.models.ServiceGroupRecord;
import com.androidproductions.servicemonitor.backend.data.models.SubscriptionRecord;

import java.util.Collection;

import static com.androidproductions.servicemonitor.backend.data.OfyService.ofy;

public class ServiceGroups {
    public static ServiceGroupRecord create(ServiceGroupRecord record) {
        if(exists(record.getName())) {
            return null;
        }
        ofy().save().entity(record).now();
        return record;
    }

    public static SubscriptionRecord subscribe(ServiceGroupRecord record, String user)
    {
        SubscriptionRecord sub = new SubscriptionRecord(user,null,record.getName());
        ofy().save().entity(sub).now();
        return sub;
    }

    public static ServiceGroupRecord find(String name) {
        return ofy().load().type(ServiceGroupRecord.class)
                .filter("name",name).first().now();
    }

    public static Collection<ServiceGroupRecord> search() {
        return ofy().load().type(ServiceGroupRecord.class).list();
    }

    public static boolean exists(String name) {
        return find(name) != null;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Template</title>
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">

helloWorld

            {{--{{ var_dump(action('ControllerTest@index')) }}--}}
            <form class="form" action="consumer/p" method="post">
                {!! csrf_field() !!}
                <input type="text" name="name"/>

                <input type="text" name="pass"/>

                <button type="submit">Submit</button>
            </form>


text:
from system.link_quality import Signal
import os
import pyudev
import re
import subprocess

class System():
    def __init__(self):
        self.context = pyudev.Context()
        self.signal = Signal()
        self.signal.start()

    def getSignal(self):
        return self.signal.strength

    def getTemperature(self):
        f = os.popen('vcgencmd measure_temp | grep -ohP "=[0-9]*" | cut -c 2-')
        return f.read()

    def getWirelessAdapterInfo(self):
        for device in self.context.list_devices(subsystem='net', DEVTYPE='wlan'):
            external_wlan_model = device.get('ID_MODEL_FROM_DATABASE')
            if external_wlan_model is not None:
                return external_wlan_model
        return None

    def getCameraInfo(self):
        try:
            output = subprocess.check_output("v4l2-ctl --list-devices 2>/dev/null", shell=True)
        except subprocess.CalledProcessError as e:
            output = e.output

        expr = r"(?P<model>.*) \(.*\):\n\t(?P<device>.*)"

        cameras = []

        for camera in re.finditer(expr, output.decode('utf-8')):
            cameras.append({
                    'model': camera.group('model'),
                    'device': camera.group('device')
                })

        return cameras

    def shutdown(self):
        subprocess.run(['poweroff'])

    def reboot(self):
        subprocess.run(['reboot'])


text:
namespace cold {
	class Keyboard {
	public:
		// Number of supported keys in a keyboard
		const static unsigned int KEY_COUNT = 322;

		// Gets whther a key is held down currently
		static bool down(SDLKey key) {
			return _state[key];
		}

		// Gets whether a key relased currently
		static bool up(SDLKey key) {
			return !_state[key];
		}

		// Gets whether a key has just been pressed
		static bool pressed(SDLKey key) {
			return _state[key] && _time[key] == _counter;
		}

		// Gets whether a key has just been released
		static bool released(SDLKey key) {
			return !_state[key] && _time[key] == _counter;
		}

		// Begins reading from the keyboard
		// repeat: Time the user has to hold a key to repeat it
		// freq: Frequency of the repeating
		static void begin_read(int repeat=0, int freq=0);

		// Reads an unicode character from the keyboard
		// may return multiple values in one frame
		// Returns 0 if there are no more characters to read
		// `begin_read` must be called before starting to read
		// from the keyboard
		static st_char read();

		// Ends reading from keyboard
		static void end_read();

		// Returns whether the keyboard is currently reading
		// unicode characters from the keyboard
		static bool is_reading() { return reading; }

		// Initializes the keyboard
		// ! Internal (cold/platform/application)
		static void initialize();

		// Updates the keyboard
		// ! Internal (cold/platform/application)
		static void update() {
			_counter++;
		}

		// Sets a key pressed
		// ! Internal (cold/platform/application)
		static void set_key(SDLKey key, bool value) {
			_state[key] = value;
			_time[key] = _counter;
		}

		// Writes a keypress to the buffer
		// ! Internal (cold/platform/application)
		static void write(st_char c);
	private:
		static bool _state[KEY_COUNT];
		static unsigned int _time[KEY_COUNT];
		static unsigned int _counter;
		static bool reading;
		static std::queue<st_char> read_queue;
	};
};

#endif


text:
package stroom.util.logging;

import com.google.common.base.Strings;
import org.slf4j.helpers.MessageFormatter;

public final class LogUtil {

    private LogUtil() {
        // Utility class.
    }

    /**
     * Constructs a formatted message string using a format string that takes
     * the same placeholders as SLF4J, e.g.
     * "Function called with name {} and value {}"
     *
     * @param format SLF4J style format string
     * @param args   The values for any placeholders in the message format
     * @return A formatted message
     */
    public static String message(String format, Object... args) {
        return MessageFormatter.arrayFormat(format, args).getMessage();
    }

    /**
     * Constructs a formatted message string using a format string that takes
     * the same placeholders as SLF4J, e.g.
     * "Function called with name {} and value {}"
     * This constructed message is placed inside a separator line padded out to 100 chars, e.g.
     * === Function called with name foo and value bar ====================================================
     *
     * @param format SLF4J style format string
     * @param args   The values for any placeholders in the message format
     * @return A formatted message in a separator line
     */
    public static String inSeparatorLine(final String format, final Object... args) {
        final String text = message(format, args);
        return Strings.padEnd("=== " + text + " ", 100, '=');
    }

    /**
     * Constructs a formatted message string using a format string that takes
     * the same placeholders as SLF4J, e.g.
     * "Function called with name {} and value {}"
     * This constructed message is placed inside a box after a line break
     *
     * @param format SLF4J style format string
     * @param args   The values for any placeholders in the message format
     * @return A formatted message in a box on a new line
     */
    public static String inBox(final String format, final Object... args) {
        final String text = message(format, args);

        final String line = Strings.repeat("-", text.length() + 6);
        final String boxFormat = """

                {}
                |  {}  |
                {}""";
        return message(boxFormat, line, text, line);
    }
}


text:
title: St. Louis County Library
published: true
start_at: 2017-05-03 19:00:00
show_time: true
venue:
  name: St. Louis County Library
  address: 1640 S. Lindbergh Blvd
  city: St. Louis
  state: MO
  zip:
link:
---

Author talk, Q&A, and book signing


text:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

/**
 * Generated class for the DashboardPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-dashboard',
  templateUrl: 'dashboard.html',
})
export class DashboardPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad DashboardPage');
  }

}


text:
<!DOCTYPE html>

<my-super-element></my-super-element>

<template id="my-super-element-template">

Inheritance and Nesting

Outer element:  clicks

  <button id="button" type="button">Outer Button</button>
  The outer element updates the inner element
  <my-element id="innerElement"></my-element>

</template>

<template id="my-element-template">

Inner element:  clicks

  <button id="button" type="button">Inner Button</button>
  But the inner element does not update the outer element

</template>


text:
require 'rails_helper'

RSpec.describe "airports/show", type: :view do
  before(:each) do
    @airport = assign(:airport, Airport.create!(
      :name => "Name",
      :city => nil,
      :department => 1
    ))
  end

  it "renders attributes in <p>" do
    render
    expect(rendered).to match(/Name/)
    expect(rendered).to match(//)
    expect(rendered).to match(/1/)
  end
end