text:
// Copyright 2017 Google Inc.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
// limitations under the License.

/**
 * intro-player
 *
 * Intro sequencer. Waits for all the intro components to be loaded
 * and ready, then triggers the animation.
 *
 * When the animation is complete, the intro components are removed.
 *
 * Tapping on video brings up skip intro button
 * Tapping on skip intro jumps to rover landing
 *
 * All 3D objects are hidden until video is displayed
 */
import { Scene } from '../core/scene';
import { EventEmitter } from 'eventemitter3';
import { PlatformUtils } from '../utils/platform-utils';

const PRESS_AND_HOLD_TIMER = 1000;

if ( typeof AFRAME !== 'undefined' && AFRAME ) {
	AFRAME.registerComponent( 'intro-player', {

		init: function() {

			this.isVR = false;
			this.isVideoSkipped = false;
			this.animLoaded = false;
			this.introComplete = false;
			this.terrainLoaded = false;
			this.videoComplete = false;
			this.isControllerPressed = false;

			this.camera = document.getElementById( 'camera' );
			this.mapMarkers = document.getElementById( 'horizMarkers' );
			this.markers = document.getElementById( 'markers' );

			this.rover = Scene.createRover();

			// HACK
			// can't inject the video div so both video objects are added.
			// Removed the unsupported one
			if ( PlatformUtils.isMp4Supported() ) {
				const webmVideo = document.querySelector( '#intro-video-webm' );
				webmVideo.parentNode.removeChild( webmVideo );
				this.srcVideoId = 'intro-video-mp4';
			} else {
				const mp4Video = document.querySelector( '#intro-video-mp4' );
				mp4Video.parentNode.removeChild( mp4Video );
				this.srcVideoId = 'intro-video-webm';
			}

			this.video = document.createElement( 'a-entity' );
			this.video.setAttribute( 'intro-video', { src: this.srcVideoId } );
			this.video.setAttribute( 'geometry', { primitive: 'plane', width: 16 * 1, height: 9 * 1 });
			this.video.setAttribute( 'position', '5.00 1.6 0.0' );
			this.video.setAttribute( 'material', {
				color: '#FFF',
				src: "#" + this.srcVideoId,
				shader: 'flat',
				side: 'double'
			});

			this.skipintroHTML = document.querySelector( '#skip-intro' );
			this.holdToSkip = document.createElement( 'a-entity' );
			this.holdToSkip.setAttribute( 'position', '0.00 -0.6 -1.25 ' );
			this.holdToSkip.setAttribute( 'visible', 'false' );
			this.holdToSkip.setAttribute( 'text', {
				align: 'center',
				anchor: 'center',
				baseline: 'bottom',
				color: '#999',
				font: 'fonts/NowAlt-Medium.json',
				shader: 'msdf',
				value: 'H O L D  T O  S K I P',
			});

			this.holdToSkipBar = document.createElement( 'a-entity' );
			this.holdToSkipBar.setAttribute( 'geometry', 'primitive: plane; height: 0.005; width: 0.39;' );
			this.holdToSkipBar.setAttribute( 'material', 'color: #999;' );
			this.holdToSkipBar.setAttribute( 'position', '0.00 -0.6 -1.25 ' );
			this.holdToSkipBar.setAttribute( 'scale', { x: 0.0 } );

			if ( !AFRAME.utils.device.isMobile() ) {
				let videoEl = document.getElementById( this.srcVideoId );
				videoEl.muted = false;
			}

			Scene.on( 'terrain-loaded', event => {
				this.terrainLoaded = true;
				this.tryPlayAnimation();
			});

			this.video.addEventListener( 'video-ended', event => {
				this.videoComplete = true;
				this.tryPlayAnimation();
			});

			this.rover.addEventListener( 'load-complete', event => {
				this.animLoaded = true;
				this.tryPlayAnimation();
			});

			this.rover.addEventListener( 'complete', event => {
				this.el.removeState( 'playing-intro' );
				this.el.emit( 'intro-complete', null, false );
			});

			Scene.on( 'on-controls-ready', event => {
				if ( this.introComplete ) return;

				if( Scene.modeType === 'vr' ) {
					if( this.isVR ) { return; }
					this.skipintroHTML.setAttribute( 'class', 'invisible' );
					this.holdToSkip.setAttribute( 'visible', 'true' );
					this.isVR = true;
					this.tryAddingControllerListeners();
				} else if( Scene.modeType === '360' ) {
					if( !this.isVR ) { return; }
					this.skipintroHTML.removeAttribute( 'class' );
					this.holdToSkip.setAttribute( 'visible', 'false' );
					this.isVR = false;
					this.tryRemovingControllerListeners();
				}
			});

			this.skipintroHTML.addEventListener( 'click', this.onVideoClick.bind( this ) );

			this.camera.appendChild( this.holdToSkip );
			this.camera.appendChild( this.holdToSkipBar );
			this.el.appendChild( this.video );

			Scene.hideElements();

			this.el.addState( 'playing-intro' );
		},

		onVideoClick: function() {
			this.videoComplete = true;
			this.tryPlayAnimation();
			ga( 'send', 'event', 'video-intro', 'skipped', '' );

			if( Scene.controllerType === 'mouse-touch' ){
				this.skipintroHTML.removeAttribute( 'class' );
			} else {
				this.holdToSkip.setAttribute( 'visible', 'true' );
			}

			this.isVideoSkipped = true;
		},

		tryPlayAnimation: function() {
			if ( !this.animLoaded ) return;
			if ( !this.videoComplete ) return;
			if ( !this.terrainLoaded ) return;

			if ( this.introComplete ) return;
			this.introComplete = true;

			// Remove the video element
			let videoEl = document.getElementById( this.srcVideoId );
			videoEl.parentNode.removeChild( videoEl );
			this.el.removeChild( this.video );

			// Remove skip UI elements
			this.camera.removeChild( this.holdToSkip );
			this.camera.removeChild( this.holdToSkipBar );
			this.skipintroHTML.parentNode.removeChild( this.skipintroHTML );

			this.tryRemovingControllerListeners();

			this.el.emit( 'video-complete' );

			// Show the rover and start the animation
			this.rover.setAttribute( 'visible', true );
			this.rover.addState( 'animate' );
		},

		remove: function() {
			this.el.removeState( 'playing-intro' );
			Scene.hideRover();
		},

		tryAddingControllerListeners: function() {
			this.onControllerChangedRef = this.onControllerChanged.bind(this);
			var controller = document.getElementById( 'right-hand' );
			controller.addEventListener( 'buttonchanged', this.onControllerChangedRef );

			this.onTouchRef = this.onTouch.bind(this);

			if ( AFRAME.utils.device.isMobile() ) {
				this.el.sceneEl.addEventListener( 'touchstart', this.onTouchRef );
				this.el.sceneEl.addEventListener( 'touchend', this.onTouchRef );
			}
		},

		tryRemovingControllerListeners: function() {
			var controller = document.getElementById( 'right-hand' );
			controller.removeEventListener( 'buttonchanged', this.onControllerChangedRef );

			if ( AFRAME.utils.device.isMobile() ) {
				this.el.sceneEl.removeEventListener( 'touchstart', this.onTouchRef );
				this.el.sceneEl.removeEventListener( 'touchend', this.onTouchRef );
			}
		},

		onControllerDown: function( event ) {
			if ( this.isControllerPressed ) return;
			this.startTime = Date.now();
			this.isControllerPressed = true;
			this.timeCheck();
		},

		onControllerUp: function( event ) {
			if ( !this.isControllerPressed ) return;
			this.isControllerPressed = false;
			this.holdToSkipBar.setAttribute( 'scale', {x: 0});
		},

		onControllerChanged: function( event ) {
			if ( this.introComplete ) return;
			if ( event.detail.state.pressed ) {
				this.onControllerDown();
			} else {
				this.onControllerUp();
				let videoEl = document.getElementById( this.srcVideoId );
				if( videoEl.paused ) {
					videoEl.play();
				}
			}
		},

		onTouch: function( event ) {
			if ( this.introComplete ) return;
			switch(event.type) {
				case "touchstart":
					this.onControllerDown();
					break;
				case "touchend":
					this.onControllerUp();
					let videoEl = document.getElementById( this.srcVideoId );
					if( videoEl.paused ) {
						videoEl.play();
					}
					break;
			}
		},

		timeCheck: function() {
			this.currentTime = Date.now();
			let deltaTime = this.currentTime - this.startTime;
			let scale = (this.isControllerPressed) ? deltaTime/PRESS_AND_HOLD_TIMER : 0;
			this.holdToSkipBar.setAttribute( 'scale', {x: scale});
			if( deltaTime > PRESS_AND_HOLD_TIMER ) {
				this.isControllerPressed = false;
				this.onVideoClick();
				return;
			};

			requestAnimationFrame( () => {
				if( !this.isControllerPressed ) return;
				this.timeCheck();
			});
		}
	});
}


text:
package com.facebook.buck.core.toolchain.tool.impl;

import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.util.MoreSuppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.Objects;
import java.util.function.Supplier;
import javax.annotation.Nullable;

/** A tool with a single file input. */
public class HashedFileTool implements Tool {
  @AddToRuleKey private final Supplier<? extends SourcePath> path;

  public HashedFileTool(Supplier<? extends SourcePath> path) {
    this.path = MoreSuppliers.memoize(path);
  }

  public HashedFileTool(@Nullable SourcePath path) {
    this(() -> Objects.requireNonNull(path));
  }

  @Override
  public ImmutableList<String> getCommandPrefix(SourcePathResolverAdapter resolver) {
    return ImmutableList.of(resolver.getAbsolutePath(path.get()).toString());
  }

  @Override
  public ImmutableMap<String, String> getEnvironment(SourcePathResolverAdapter resolver) {
    return ImmutableMap.of();
  }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('cms', '0022_add_categorized_faqs_page'),
    ]

    operations = [
        migrations.AddField(
            model_name='programpage',
            name='title_program_home_page_url',
            field=models.TextField(blank=True, help_text='The text for the link to an external homepage.'),
        ),
    ]


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/android1.iml" filepath="$PROJECT_DIR$/android1.iml" />
      <module fileurl="file://$PROJECT_DIR$/libraries/libraries.iml" filepath="$PROJECT_DIR$/libraries/libraries.iml" />
      <module fileurl="file://$PROJECT_DIR$/oCRTest/oCRTest.iml" filepath="$PROJECT_DIR$/oCRTest/oCRTest.iml" />
      <module fileurl="file://$PROJECT_DIR$/libraries/tess-two/tess-two.iml" filepath="$PROJECT_DIR$/libraries/tess-two/tess-two.iml" />
    </modules>
  </component>
</project>


text:
<?php defined("ALT_PATH") OR die("No direct script access.");

class Alt_Database_Query {

	// Query type
	protected $_type;

	// Execute the query during a cache hit
	protected $_force_execute = FALSE;

	// Cache lifetime
	protected $_lifetime = NULL;

	// SQL statement
	protected $_sql;

	// Quoted query parameters
	protected $_parameters = array();

	// Return results as associative arrays or objects
	protected $_as_object = FALSE;

	// Parameters for __construct when using object results
	protected $_object_params = array();

	/**
	 * Creates a new SQL query of the specified type.
	 *
	 * @param   integer  $type  query type: Alt_Database::SELECT, Alt_Database::INSERT, etc
	 * @param   string   $sql   query string
	 * @return  void
	 */
	public function __construct($type, $sql)
	{
		$this->_type = $type;
		$this->_sql = $sql;
	}

	/**
	 * Return the SQL query string.
	 *
	 * @return  string
	 */
	public function __toString()
	{
		try
		{
			// Return the SQL string
			return $this->compile(Alt_Database::instance());
		}
		catch (Exception $e)
		{
			return $e->getMessage();
		}
	}

	/**
	 * Get the type of the query.
	 *
	 * @return  integer
	 */
	public function type()
	{
		return $this->_type;
	}

	/**
	 * Enables the query to be cached for a specified amount of time.
	 *
	 * @param   integer  $lifetime  number of seconds to cache, 0 deletes it from the cache
	 * @param   boolean  whether or not to execute the query during a cache hit
	 * @return  $this
	 * @uses    Alt::$cache_life
	 */
	public function cached($lifetime = NULL, $force = FALSE)
	{
		if ($lifetime === NULL)
		{
			// Use the global setting
			$lifetime = Alt::$cache_life;
		}

		$this->_force_execute = $force;
		$this->_lifetime = $lifetime;

		return $this;
	}

	/**
	 * Returns results as associative arrays
	 *
	 * @return  $this
	 */
	public function as_assoc()
	{
		$this->_as_object = FALSE;

		$this->_object_params = array();

		return $this;
	}

	/**
	 * Returns results as objects
	 *
	 * @param   string  $class  classname or TRUE for stdClass
	 * @param   array   $params
	 * @return  $this
	 */
	public function as_object($class = TRUE, array $params = NULL)
	{
		$this->_as_object = $class;

		if ($params)
		{
			// Add object parameters
			$this->_object_params = $params;
		}

		return $this;
	}

	/**
	 * Set the value of a parameter in the query.
	 *
	 * @param   string   $param  parameter key to replace
	 * @param   mixed    $value  value to use
	 * @return  $this
	 */
	public function param($param, $value)
	{
		// Add or overload a new parameter
		$this->_parameters[$param] = $value;

		return $this;
	}

	/**
	 * Bind a variable to a parameter in the query.
	 *
	 * @param   string  $param  parameter key to replace
	 * @param   mixed   $var    variable to use
	 * @return  $this
	 */
	public function bind($param, & $var)
	{
		// Bind a value to a variable
		$this->_parameters[$param] =& $var;

		return $this;
	}

	/**
	 * Add multiple parameters to the query.
	 *
	 * @param   array  $params  list of parameters
	 * @return  $this
	 */
	public function parameters(array $params)
	{
		// Merge the new parameters in
		$this->_parameters = $params + $this->_parameters;

		return $this;
	}

	/**
	 * Compile the SQL query and return it. Replaces any parameters with their
	 * given values.
	 *
	 * @param   mixed  $db  Alt_Database instance or name of instance
	 * @return  string
	 */
	public function compile($db = NULL)
	{
		if ( ! is_object($db))
		{
			// Get the Alt_Database instance
			$db = Alt_Database::instance($db);
		}

		// Import the SQL locally
		$sql = $this->_sql;

		if ( ! empty($this->_parameters))
		{
			// Quote all of the values
			$values = array_map(array($db, "quote"), $this->_parameters);

			// Replace the values in the SQL
			$sql = strtr($sql, $values);
		}

		return $sql;
	}

	/**
	 * Execute the current query on the given Alt_Database.
	 *
	 * @param   mixed    $db  Alt_Database instance or name of instance
	 * @param   string   result object classname, TRUE for stdClass or FALSE for array
	 * @param   array    result object constructor arguments
	 * @return  object   Alt_Database_Result for SELECT queries
	 * @return  mixed    the insert id for INSERT queries
	 * @return  integer  number of affected rows for all other queries
	 */
	public function execute($db = NULL, $as_object = NULL, $object_params = NULL)
	{
		if ( ! is_object($db))
		{
			// Get the Alt_Database instance
			$db = Alt_Database::instance($db);
		}

		if ($as_object === NULL)
		{
			$as_object = $this->_as_object;
		}

		if ($object_params === NULL)
		{
			$object_params = $this->_object_params;
		}

		// Compile the SQL query
		$sql = $this->compile($db);

		if ($this->_lifetime !== NULL AND $this->_type === Alt_Database::SELECT)
		{
			// Set the cache key based on the Alt_Database instance name and SQL
			$cache_key = "Alt_Database::query(\"".$db."\", \"".$sql."\")";

			// Read the cache first to delete a possible hit with lifetime <= 0
			if (($result = Alt::cache($cache_key, NULL, $this->_lifetime)) !== NULL
				AND ! $this->_force_execute)
			{
				// Return a cached result
				return new Alt_Database_Result_Cached($result, $sql, $as_object, $object_params);
			}
		}

		// Execute the query
		$result = $db->query($this->_type, $sql, $as_object, $object_params);

		if (isset($cache_key) AND $this->_lifetime > 0)
		{
			// Cache the result array
			Alt::cache($cache_key, $result->as_array(), $this->_lifetime);
		}

		return $result;
	}

} // End Alt_Database_Query


text:
class DonorPageController {
   /* @ngInject */
  constructor(Site) {
    var ctrl = this;
        Site.hideHeaderLinks=true;

        //var Ref = firebase.database().ref('/')
        // Ref.on('value',function(snap){
        //   ctrl.donorPage = snap.val()
        // })
  }
}

export default DonorPageController;


text:
title: DetailedNetworkLinking
category: template
authors: alkaplan, apuimedo, danken, lpeer, moti
wiki_category: Template
wiki_title: Feature/DetailedNetworkLinking
wiki_revision_count: 75
wiki_last_updated: 2012-12-18
wiki_warnings: list-item?
---

# Detailed Network Linking

## Network Linking

### Summary

The network wiring feature is an enhancement for the VM Network Interface management. It supports the following actions without unplugging the Vnic, maintaining the address of the Vnic:

    * Dynamically changing the network of a running VM (without unplugging the Vnic)
    * Unwiring a network of a VM without unplugging the vnic
[Network Linking Feature Page](/Feature/NetworkLinking)

### Owner

*   Name: Alona Kaplan (alkaplan)
*   Email: <alkaplan@redhat.com>

### Current status

*   On Design
*   Last update date: 11/11/2012

### Detailed Description

#### Rest API

*   The user will enter link_state as a string ("up"/"down").
*   The link_state string will be translated to boolean before sending the entity to the backend.
*   Plug/Unplug actions will call UpdateVmInterfaceCommand instead of ActivateDeactivateVmNicCommand.

#### Engine API

      VmNetworkInterface:
        boolean linked;

#### Database Changes

**VM_INTERFACE**
{|class="wikitable" !border="1"| Column Name ||Column Type ||Null? / Default ||Definition |- |linked || boolean ||not null ||Indicates wether the vnic's link state is "up" or "down" |- |}

**VM_INTERFACE_VIEW**
{|class="wikitable" !border="1"| Column Name ||Column Type ||Definition |- |linked || boolean ||Indicates wether the vnic's link state is "up" or "down" |- |}

#### Engine Flows

##### Add Vnic

*   canDoAction- allow 'null' network just for 3.2 or upper cluster compatibility version.
*   'linkState' property of VmNetworkInterface should be stored in the DB

      VmNetworkInterfaceDAODbFacadeImpl- save

*   The 'linkState' property is sent to the VDSM by ActivateDeactivateVmNicCommand command (for running VMs with the nic set to plugged)

##### Update Vnic

*   **shouldn't** throw canDo when trying to update a nic when the vm is running and the nic is plugged.
*   canDoAction- allow 'null' network.
*   'linkState' property of VmNetworkInterface should also be stored in the DB

      VmNetworkInterfaceDAODbFacadeImpl- update

*   If the vm is up

    * plugged --> unplugged ('plugged' property was changed to false)

:\*\* Unplug should be sent to the VDSM

    * unplugged --> plugged

:\*\* Plug should be sent to the VDSM

    * plugged --> plugged

:\*\* If MAC Address or Driver Type were updated

:\*\*\* Throw canDoAction "Cannot perform hot update when updating 'Type' or 'MAC', please Unplug and then Plug again."

:\*\* Otherwise, if network is changed or disconnected

:\*\*\* If cluster c. version is 3.2 or upper updateVmDevice should be sent to the VDSM.

:\*\*\* Otherwise, throw canDoAction

    * unplugged --> unplugged

:\*\* nothing should be sent to VDSM

##### Remove Vnic

*   no change (can be done only if the VM is down or the Vnic is unplugged)

##### Run VM

*   When running a VM, the VM's Vnics' 'linkState' property should also be passed to the VDSM, for 3.2 cluster and above.

      VmInfoBuilder.addNetworkInterfaceProperties

*   network should be sent to the VDSM just if it is not null.

##### Plug nic

*   Should be used just as internal command.
*   network should be sent to the VDSM just if it is not null.
*   canDoAction should allow null network.

##### Unplug nic

*   Should be used just as internal command.

##### Other effected flows

*   ChangeVMClusterCommand
*   AddVmTemplateCommand
*   AddVmTemplateInterfaceCommand
*   UpdateVmTemplateInterfaceCommand
*   UpdateVmCommand
*   ImportVmCommand
*   ImportVmTemplateCommand
*   OvfVm
*   OvfTemplate

##### Error codes

Add translation to VDSM error codes: UPDATE_VNIC_FAILED = 'Failed to update VM Network Interface.'

#### VDSM API

##### New API

A new API is added for this feature.

    vmUpdateDevice (vmId, params)

    params = {
       'devicType': 'interface',
       'network': 'network name',     <--- bridge name. If not set, the vnic stays on the current network. If it equals to the empty string, it is taken to the dummy bridge.
       'linkActive': 'bool',
       'alias': <string>,
       'portMirroring': blue[,red],    <---  If not specified, the current portMirroring keeps in effect. Otherwise, only the specified networks will be mirrored to the vnic, e.g., empty list -> unset any mirroring.
     }

Vdsm would implement this using <http://libvirt.org/html/libvirt-libvirt.html#virDomainUpdateDeviceFlags> .

If the vnic doesn't have a network, the network will be omitted from the params sent to the vdsm.

##### Updated APIs

*   **hotplugNic**
    -   the vdsm should connect the Vnic's Network according to the 'linkState' property passed on the Vnic.
    -   If the vnic doesn't have a network, the network will be omitted from the params sent to the vdsm.
*   **createVm**
    -   the vdsm should connect each of the Vm's Vnics according to the 'linkState' property passed on the each Vnic.
    -   If the vnic doesn't have a network, the network will be omitted from the params sent to the vdsm.

In both cases, 'linkState' property would be implemented by setting libvirt's <link state> element <http://libvirt.org/formatdomain.html#elementLink> .
New vdsm errors will be added:

    UPDATE_VNIC_FAILED- code 56

#### Events

##### Add Vnic

*   AuditLogType.NETWORK_ADD_VM_INTERFACE
*   AuditLogType.NETWORK_ADD_VM_INTERFACE_FAILED

##### Update Vnic

*   AuditLogType.NETWORK_UPDATE_VM_INTERFACE
*   AuditLogType.NETWORK_UPDATE_VM_INTERFACE_FAILED

##### Remove Vnic

*   AuditLogType.NETWORK_REMOVE_VM_INTERFACE
*   AuditLogType.NETWORK_REMOVE_VM_INTERFACE_FAILED

##### Plug nic

*   AuditLogType.NETWORK_ACTIVATE_VM_INTERFACE_SUCCESS
*   AuditLogType.NETWORK_ACTIVATE_VM_INTERFACE_FAILURE;

##### Unplug nic

*   AuditLogType.NETWORK_DEACTIVATE_VM_INTERFACE_SUCCESS
*   AuditLogType.NETWORK_DEACTIVATE_VM_INTERFACE_FAILURE

#### Open Issues

1.  Should ActivateDeactivateVmNic be renamed to PlugUnplug ?

### Documentation / External references

### Stretch Goals

*   Enable hot changes in port mirroring (without plugging and unplugging)

### Comment

*   After the VM is connected to a new network, no one on that network is aware of the change. It was suggested, that much like in vm migration, the VM should emit a gratuitous arp packet, to notify the world about its existence. However note that in vm migration, the vm does not change its layer-2 subnet and telling the switch of its new location is all that is needed. This is NOT the case when the VM is connected to a different network, with its own vlan and ip limitations. One cannot assume that a guest server application would continue to operate uninterrupted.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- App Themes -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_primary_dark</item>
    </style>

    <!-- Preference TextView Style -->
    <style name="PreferenceTextStyle">
        <item name="android:textAppearance">@android:style/TextAppearance.Holo.Medium</item>
        <item name="android:singleLine">true</item>
        <item name="android:ellipsize">marquee</item>
    </style>

</resources>


text:
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { I18NService } from '@core';
import { STColumn } from '@delon/abc/st';
import { _HttpClient } from '@delon/theme';
import { getTimeDistance } from '@delon/util/date-time';
import { deepCopy } from '@delon/util/other';
import { yuan } from '@shared';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-dashboard-analysis',
  templateUrl: './analysis.component.html',
  styleUrls: ['./analysis.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DashboardAnalysisComponent implements OnInit {
  constructor(private http: _HttpClient, public msg: NzMessageService, private i18n: I18NService, private cdr: ChangeDetectorRef) {}
  data: any = {};
  loading = true;
  date_range: Date[] = [];
  rankingListData: Array<{ title: string; total: number }> = Array(7)
    .fill({})
    .map((_, i) => {
      return {
        title: this.i18n.fanyi('app.analysis.test', { no: i }),
        total: 323234
      };
    });
  titleMap = {
    y1: this.i18n.fanyi('app.analysis.traffic'),
    y2: this.i18n.fanyi('app.analysis.payments')
  };
  searchColumn: STColumn[] = [
    { title: { text: '排名', i18n: 'app.analysis.table.rank' }, index: 'index' },
    {
      title: { text: '搜索关键词', i18n: 'app.analysis.table.search-keyword' },
      index: 'keyword',
      click: item => this.msg.success(item.keyword)
    },
    {
      type: 'number',
      title: { text: '用户数', i18n: 'app.analysis.table.users' },
      index: 'count',
      sort: {
        compare: (a, b) => a.count - b.count
      }
    },
    {
      type: 'number',
      title: { text: '周涨幅', i18n: 'app.analysis.table.weekly-range' },
      index: 'range',
      render: 'range',
      sort: {
        compare: (a, b) => a.range - b.range
      }
    }
  ];

  salesType = 'all';
  salesPieData: any;
  salesTotal = 0;

  saleTabs: Array<{ key: string; show?: boolean }> = [{ key: 'sales', show: true }, { key: 'visits' }];

  offlineIdx = 0;

  ngOnInit(): void {
    this.http.get('/chart').subscribe(res => {
      res.offlineData.forEach((item: any, idx: number) => {
        item.show = idx === 0;
        item.chart = deepCopy(res.offlineChartData);
      });
      this.data = res;
      this.loading = false;
      this.changeSaleType();
    });
  }

  setDate(type: 'today' | 'week' | 'month' | 'year'): void {
    this.date_range = getTimeDistance(type);
    setTimeout(() => this.cdr.detectChanges());
  }
  changeSaleType(): void {
    this.salesPieData =
      this.salesType === 'all'
        ? this.data.salesTypeData
        : this.salesType === 'online'
        ? this.data.salesTypeDataOnline
        : this.data.salesTypeDataOffline;
    if (this.salesPieData) {
      this.salesTotal = this.salesPieData.reduce((pre: number, now: { y: number }) => now.y + pre, 0);
    }
    this.cdr.detectChanges();
  }

  handlePieValueFormat(value: string | number): string {
    return yuan(value);
  }
  salesChange(idx: number): void {
    if (this.saleTabs[idx].show !== true) {
      this.saleTabs[idx].show = true;
      this.cdr.detectChanges();
    }
  }
  offlineChange(idx: number): void {
    if (this.data.offlineData[idx].show !== true) {
      this.data.offlineData[idx].show = true;
      this.cdr.detectChanges();
    }
  }
}


text:
![Click Here](/week-2/imgs/site-map.png)
<<<<<<< HEAD

=======
>>>>>>> 91ed0fc0f90bcda675e23b3b0b7f3cccb28827f6
What are the 6 Phases of Web Design?

1. Information Gathering
2. Planning
3. Design
4. Development
5. Testing and Delivery
6. Maintenance

What is your site's primary goal or purpose? What kind of content will your site feature?

The primary purpose of this site is to serve as an online portfolio for my coding-related work.  It will give basic background and contact information along with a picture on the home page, and then also contain a blog page and a projects page.

What are your target audience's interests and how do you see your site addressing them?

My target audience would hopefully be co-workers as well as current and potential clients.  My site will clearly dsiplay necessary information about myself and my background and then give easy to view examples of my past work.

What is the primary "action" the user should take when coming to your site? Do you want them to search for information, contact you, or see your portfolio? It's ok to have several actions at once, or different actions for different kinds of visitors.

Depending on the sort of visitor, it seems like the primary action could be different.  Potential clients might first want to see some of my work or read a blog post, but I would hope they would end their experience wanting to contact me, so it might be a good idea to display contact information at the bottom of each page in the footer.

What are the main things someone should know about design and user experience?  What is user experience design and why is it valuable?

UX is a discipline concerned with how a person feels when interfacing with a system, generally a website or application, and focuses on usbaility, design, accessibility, marketing, system performance, ergonomics, HCI, utility and other human factors.  UX designers look at systems and sub-systems in order to see where websites might be losing users.

Which parts of the challenge did you find tedious?

I thought a majority of the content in the UX article was unnecessary and overly-detailed and the instructions in release 3 could have been more clear, especially the instructions about using markdown and inline image display.


text:
package com.coillighting.udder.effect;

import com.coillighting.udder.geometry.ControlQuad;

/** Convey public parameters to and from TextureEffect instances.
 *  This class serves as a JSON mapping target for Boon.
 */
public class TextureEffectState {

    /** Map this texture onto the rig. Normally we store these in
     * udder/udder/images, so a typical fileName looks like
     * "images/my_file_name.png". Several common RGB and ARGB image types are
     * theoretically supported, however we have tested only PNG and JPG. Consult
     * the Java API docs for ImageIO.read() for details.
     * TextureEffect will reload the file when this value changes.
     * Send null or the empty string for this value to be ignored, so you keep
     * showing the current file.
     */
    protected String filename = null;

    /** If true, automatically stretch and squeeze the image over the rig.
     *  If false, distort the image map according to the four corners in
     *  controlQuad.
     */
    protected boolean automatic = true;

    /** If automatic is true, then vary the stretching and squeezing motion
     *  this often or faster. (We randomly vary step time from 1 ms at the
     *  fast end to maxTempoMillis at the slow end, and each corner steps
     *  indepdently, so on average you'll see some change in your show
     *  about 4x this often, although many such random changes are subtle
     *  or even invisible.) A good value is 18000 (18 seconds).
     *  Send <=0 for this value to be ignored, retaining the current tempo.
     */
    protected int maxTempoMillis = 0;

    /** If automatic is false, then don't heed maxTempoMillis; simply obey
     *  the mapping specified here. See Stretch.stretchXY for implementation.
     *  Set to null to keep the current controlQuad.
     */
    protected ControlQuad controlQuad = null;

    public TextureEffectState(String fileName, boolean automatic,
                                int maxTempoMillis, ControlQuad controlQuad)
    {
        this.filename = filename;
        this.automatic = automatic;
        this.maxTempoMillis = maxTempoMillis;
        this.controlQuad = controlQuad;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public boolean getAutomatic() {
        return automatic;
    }

    public void setAutomatic(boolean automatic) {
        this.automatic = automatic;
    }

    public int getMaxTempoMillis() {
        return maxTempoMillis;
    }

    public void setMaxTempoMillis(int maxTempoMillis) {
        this.maxTempoMillis = maxTempoMillis;
    }

    public ControlQuad getControlQuad() {
        return controlQuad;
    }

    /** Send the unit square to reset to a 1:1 mapping. */
    public void setControlQuad(ControlQuad controlQuad) {
        this.controlQuad = controlQuad;
    }

    public String toString() {
        return "TextureEffectState(\"" + filename + "\", automatic="
            + automatic + ", maxTempoMillis=" + maxTempoMillis + ", "
            + controlQuad + ")";
    }
}


text:
package fiftyfive.wicket.resource;

import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.IRequestMapper;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler;
import org.apache.wicket.util.string.Strings;

/**
 * Enables a Wicket application to have its static resources proxied by a CDN, for example
 * by Amazon Cloudfront. This works by intercepting Wicket's default behavior for rendering
 * URLs of resource references, and then rewriting those URLs by prepending a CDN hostname
 * (or any arbitrary URL fragment). The web browser will therefore make requests to the
 * CDN host instead of the Wicket app.
 *

 * Here's an example. Normally a CSS resource reference is rendered by Wicket like this:
 *

 * /wicket/resource/com.mycompany.WicketApplication/test.css

 *

 * With {@code SimpleCDN} installed, that resource reference URL is transformed into this:
 *

 * http://age39p8hg23.cloudfront.net/wicket/resource/com.mycompany.WicketApplication/test.css

 *

 * Please note: {@code SimpleCDN} will not rewrite resource reference URLs that
 * include query string parameters. Our reasoning is that parameterized URLs usually
 * indicate that the resource is dynamic, and therefore not appropriate for serving via
 * CDN. Furthermore it should be noted that Amazon CloudFront will refuse to proxy
 * URLs that contain query string parameters (it strips the parameters off).
 *

 * When configuring the CDN host, the easiest setup is a reverse-proxy. For example, with
 * Amazon CloudFront, you would specify your Wicket app as the custom origin, and specify
 * the CloudFront host when constructing this SimpleCDN. It's that easy.
 *

 * public class MyApplication extends WebApplication
 * {
 *     @Override
 *     protected void init()
 *     {
 *         super.init();
 *         // Enable CDN when in deployment mode
 *         if(usesDeploymentConfig())
 *         {
 *             new SimpleCDN("http://age39p8hg23.cloudfront.net").install(this);
 *         }
 *     }
 * }

 * For those familiar with Ruby on Rails, {@code SimpleCDN} is inspired by the Rails
 * {@code action_controller.asset_host} configuration setting.
 *
 * @since 3.2
 */
public class SimpleCDN implements IRequestMapper
{
    private String baseUrl;
    private IRequestMapper delegate;
    private boolean delegated = false;

    /**
     * Construct a {@code SimpleCDN} that will rewrite resource reference URLs by prepending
     * the given {@code baseUrl}.
     *
     * @param baseUrl For example, "//age39p8hg23.cloudfront.net"
     */
    public SimpleCDN(String baseUrl)
    {
        this.baseUrl = baseUrl;
    }

    /**
     * Install this {@code SimpleCDN} into the given application. The {@code SimpleCDN} instance
     * will not have any effect unless it is installed.
     */
    public void install(WebApplication app)
    {
        this.delegate = app.getRootRequestMapperAsCompound();
        app.mount(this);
    }

    /**
     * If the {@code requestHandler} is a {@link ResourceReferenceRequestHandler}, delegate to
     * Wicket's default mapper for creating an appropriate URL, and then prepend the CDN
     * {@code baseUrl} that was provided to the {@code SimpleCDN} constructor.
     *
     * @return a rewritten Url to the resource, or {@code null} if {@code requestHandler} is
     *         not for a resource reference
     */
    public Url mapHandler(IRequestHandler requestHandler)
    {
        // CDN doesn't apply to non-resources
        if(!(requestHandler instanceof ResourceReferenceRequestHandler)) return null;

        // Prevent infinite recursion in case this SimpleCDN is also contained within the delegate
        if(this.delegated) return null;

        Url url = null;
        try
        {
            this.delegated = true;
            url = this.delegate.mapHandler(requestHandler);
            if(url != null && url.getQueryParameters().isEmpty())
            {
                url = Url.parse(Strings.join("/", this.baseUrl, url.toString()));
            }
        }
        finally
        {
            this.delegated = false;
        }
        return url;
    }

    /**
     * Always return {@code null}, since {@code SimpleCDN} does not play any part in handling requests
     * (they will be handled by Wicket's default mechanism).
     */
    public IRequestHandler mapRequest(Request request)
    {
        return null;
    }

    /**
     * Always return {@code 0}, since {@code SimpleCDN} does not play any part in handling requests
     * (they will be handled by Wicket's default mechanism).
     */
    public int getCompatibilityScore(Request request)
    {
        return 0;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SuperSocket;
using SuperSocket.ProtoBase;

namespace ConfigSample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var host = SuperSocketHostBuilder.Create<TextPackageInfo, LinePipelineFilter>(args)
                .UsePackageHandler(async (s, p) =>
                {
                    await s.SendAsync(Encoding.UTF8.GetBytes(p.Text + "\r\n"));
                })
                .ConfigureLogging((hostCtx, loggingBuilder) =>
                {
                    // register your logging library here
                    loggingBuilder.AddConsole();
                }).Build();

            await host.RunAsync();
        }
    }
}


text:
package org.apache.camel.component.jdbc;

import java.util.List;
import java.util.Map;

import org.apache.camel.EndpointInject;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

public class JdbcProducerOutputTypeSelectListTest extends AbstractJdbcTestSupport {

    @EndpointInject("mock:result")
    private MockEndpoint mock;

    @SuppressWarnings({"unchecked"})
    @Test
    public void testOutputTypeSelectList() throws Exception {
        mock.expectedMessageCount(1);

        template.sendBody("direct:start", "select * from customer");

        assertMockEndpointsSatisfied();

        List<?> received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());
        assertEquals(3, received.size());

        Map<String, Object> row = assertIsInstanceOf(Map.class, received.get(0));
        assertEquals("cust1", row.get("ID"));
        assertEquals("jstrachan", row.get("NAME"));

        row = assertIsInstanceOf(Map.class, received.get(1));
        assertEquals("cust2", row.get("ID"));
        assertEquals("nsandhu", row.get("NAME"));
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from("direct:start").to("jdbc:testdb?outputType=SelectList").to("mock:result");
            }
        };
    }
}


text:
package com.demo.navigator;

import android.support.test.filters.SmallTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.Gravity;

import com.demo.navigator.home.MainActivity;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.contrib.DrawerActions.open;
import static android.support.test.espresso.contrib.DrawerMatchers.isClosed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;

/**
 * Testing opening and closing {@link android.support.v4.widget.DrawerLayout} by click "close".
 */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class NavigationDrawerCloseButtonTest {

	@Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

	@Test
	public void testOnDrawerOpen() throws Exception {
		onView(withId(R.id.drawer_layout)).check(matches(isClosed(Gravity.LEFT))) // Left Drawer should be opened.
		                                  .perform(open());
		onView(withId(R.id.action_close_navigator)) // Left Drawer should be closed by clicking close.
		                                            .perform(click());
	}

}


text:
#ifndef SkYUVPlanesCache_DEFINED
#define SkYUVPlanesCache_DEFINED

#include "SkCachedData.h"
#include "SkImageInfo.h"

class SkResourceCache;

class SkYUVPlanesCache {
public:
    /**
     * The Info struct contains data about the 3 Y, U and V planes of memory stored
     * contiguously, in that order, as a single block of memory within SkYUVPlanesCache.
     *
     * fSize: Width and height of each of the 3 planes (in pixels).
     * fSizeInMemory: Amount of memory allocated for each plane (may be different from
                      "height * rowBytes", depending on the jpeg decoder's block size).
     *                The sum of these is the total size stored within SkYUVPlanesCache.
     * fRowBytes: rowBytes for each of the 3 planes (in bytes).
     * fColorSpace: color space that will be used for the YUV -> RGB conversion.
     */
    struct Info {
        SkISize fSize[3];
        size_t  fSizeInMemory[3];
        size_t  fRowBytes[3];
        SkYUVColorSpace fColorSpace;
    };
    /**
     * On success, return a ref to the SkCachedData that holds the pixels.
     *
     * On failure, return nullptr.
     */
    static SkCachedData* FindAndRef(uint32_t genID, Info* info,
                                    SkResourceCache* localCache = nullptr);

    /**
     * Add a pixelRef ID and its YUV planes data to the cache.
     */
    static void Add(uint32_t genID, SkCachedData* data, Info* info,
                    SkResourceCache* localCache = nullptr);
};

#endif


text:
package io.pkp.androidbluetooth;

import android.bluetooth.BluetoothDevice;

/**
 * Callbacks for actions related to Client mode communication with a BT server
 */
public interface OnBTServerListener {

    public void onServerConnected(BluetoothDevice device);

    public void onServerConnectionLost();

    public void onServerDataReceived(int length, byte[] data);
}


text:
import ParentBasicCase from './parent-basic-case'
import ParentBasicCaseNotes from './notes/parent-basic-case.md'
import ParentMaxWidthMaxHeight from './parent-maxw-maxh'
import ParentMaxWidthMaxHeightNotes from './notes/parent-maxw-maxh.md'
import ParentAuto from './parent-auto'
import ParentGrid from './parent-grid'
import ParentGridNotes from './notes/parent-grid.md'
import ParentGridWithOffset from './parent-grid-with-offset'
import ParentGridWithOffsetNotes from './notes/parent-grid-with-offset.md'
import ParentGridWithEvenOffset from './parent-grid-with-even-offset'
import ParentGridWithEvenOffsetNotes from './notes/parent-grid-with-even-offset.md'
import ParentGridMaxWidthMaxHeight from './parent-grid-maxw-maxh'
import ParentGridMaxWidthMaxHeightNotes from './notes/parent-grid-maxw-maxh.md'
import ParentControlledComponent from './parent-controlled-component'
import ParentControlledComponentNotes from './notes/parent-controlled-component.md'
import ParentUserSelect from './parent-user-select'

export default {
  'Parent Basic Case' : [() => new ParentBasicCase, ParentBasicCaseNotes],
  'Parent MaxWidth MaxHeight' : [() => new ParentMaxWidthMaxHeight, ParentMaxWidthMaxHeightNotes],
  'Parent Grid' : [() => new ParentGrid, ParentGridNotes],
  'Parent Auto': [() => new ParentAuto()],
  'Parent Grid With Offset' : [() => new ParentGridWithOffset, ParentGridWithOffsetNotes],
  'Parent Grid With Even Offset' : [() => new ParentGridWithEvenOffset, ParentGridWithEvenOffsetNotes],
  'Parent Grid With MaxWidth MaxHeight' : [() => new ParentGridMaxWidthMaxHeight, ParentGridMaxWidthMaxHeightNotes],
  'Parent Controlled Component' : [() => new ParentControlledComponent, ParentControlledComponentNotes],
  'Parent User Select': [() => new ParentUserSelect]
}


text:
import idc
import idaapi
import idautils
from .function import functions
from .line import lines
from .. import exceptions

class Comments(object):
    def __init__(self, segment):
        super(Comments, self).__init__()
        self._segment = segment

    @property
    def regular(self):
        return idaapi.get_segment_cmt(self._segment, False)

    @regular.setter
    def regular(self, comment):
        idaapi.set_segment_cmt(self._segment, comment, False)

    @property
    def repeat(self):
        return idaapi.get_segment_cmt(self._segment, True)

    @repeat.setter
    def repeat(self, comment):
        idaapi.set_segment_cmt(self._segment, comment, True)

class SegmentPermissions(object):
    def __init__(self, segment_t):
        super(SegmentPermissions, self).__init__()
        self._segment = segment_t

    @property
    def x(self):
        return bool(self._segment.perm & idaapi.SEGPERM_EXEC)

    @x.setter
    def x(self, value):
        if value:
            self._segment.perm |= idaapi.SEGPERM_EXEC

        else:
            self._segment.perm &= ~idaapi.SEGPERM_EXEC

    @property
    def w(self):
        return bool(self._segment.perm & idaapi.SEGPERM_WRITE)

    @w.setter
    def w(self, value):
        if value:
            self._segment.perm |= idaapi.SEGPERM_WRITE

        else:
            self._segment.perm &= ~idaapi.SEGPERM_WRITE

    @property
    def r(self):
        return bool(self._segment.perm & idaapi.SEGPERM_READ)

    @r.setter
    def r(self, value):
        if value:
            self._segment.perm |= idaapi.SEGPERM_READ

        else:
            self._segment.perm &= ~idaapi.SEGPERM_READ

    execute = x
    write = w
    read = r

    def __str__(self):
        return "".join(("R" if self.r else "", "W" if self.w else "", "X" if self.x else ""))

    def __repr__(self):
        return "<SegmentPermissions(read={}, write={}, execute={})>".format(self.r, self.w, self.x)

class Segment(object):
    BITNESS_TO_BITS = {
        0: 16,
        1: 32,
        2: 64,
    }

    BITS_TO_BITNESS = {
        16: 0,
        32: 1,
        64: 2,
    }

    class UseCurrentAddress(object):
        pass

    def __init__(self, ea=UseCurrentAddress, name=None, index=None, segment_t=None):
        """Wrapper around IDA segments.

        There are 3 ways to get a segment - by name, ea or index. Only use one.

        Args:
            ea - address in the segment
            name - name of the segment
            index - index of the segment
        """
        if sum((ea not in (self.UseCurrentAddress, None), name is not None, index is not None,
                segment_t is not None,)) > 1:
            raise ValueError((
                                 "Expected only one (ea, name, index or segment_t)."
                                 " Got (ea={!r}, name={!r}, index={!r}, segment_t={!r})"
                             ).format(ea,
                                      name,
                                      index,
                                      segment_t))

        elif segment_t is not None:
            seg = segment_t

        elif name is not None:
            seg = idaapi.get_segm_by_name(name)

        elif index is not None:
            seg = idaapi.getnseg(index)

        elif ea == self.UseCurrentAddress:
            seg = idaapi.getseg(idc.here())

        elif ea is None:
            raise ValueError("`None` is not a valid address. To use the current screen ea, "
                             "use `Function(ea=Function.UseCurrentAddress)` or supply no `ea`.")

        else:
            seg = idaapi.getseg(ea)

        self._segment = seg

    @property
    def segment_t(self):
        return self._segment

    @property
    def permissions(self):
        """Segment permissions.

        Can be used to get or set the segment permissions (r/w/x).

        Returns:
            A `SegmentPermissions` object.
        """
        return SegmentPermissions(self.segment_t)

    @property
    def startEA(self):
        return self._segment.startEA

    ea = startEA

    @property
    def endEA(self):
        return self._segment.endEA

    @property
    def name(self):
        return idaapi.get_true_segm_name(self.segment_t)

    @name.setter
    def name(self, name):
        idaapi.set_segm_name(self.segment_t, name)

    @property
    def class_(self):
        return idaapi.get_segm_class(self.segment_t)

    @class_.setter
    def class_(self, value):
        idaapi.set_segm_class(self.segment_t, value)

    @property
    def functions(self):
        """Iterate all functions in the segment."""
        return functions(self.startEA, self.endEA)

    @property
    def lines(self):
        """Iterate all lines in the segment."""
        return lines(self.startEA, self.endEA)

    @property
    def bitness(self):
        """Segment's Bitness.

        Can be 16, 32 or 64.
        """
        return self.BITNESS_TO_BITS[self.segment_t.bitness]

    @bitness.setter
    def bitness(self, bits):
        try:
            self.segment_t.bitness = self.BITS_TO_BITNESS[bits]
        except KeyError:
            raise exceptions.InvalidBitness("Got {}. Expecting 16, 32 or 64.".format(bits))

    @property
    def next(self):
        """Get the next segment."""
        seg = Segment(segment_t=idaapi.get_next_seg(self.ea))

        if seg.ea <= self.ea:
            raise exceptions.NoMoreSegments("This is the last segment. No segments exist after it.")

        return seg

    @property
    def prev(self):
        """Get the previous segment."""
        seg = Segment(segment_t=idaapi.get_prev_seg(self.ea))

        if seg.ea >= self.ea:
            raise exceptions.NoMoreSegments("This is the first segment. no segments exist before it.")

        return seg

    @property
    def comments(self):
        return Comments(self.segment_t)

    @property
    def size(self):
        return self.endEA - self.startEA

    def __repr__(self):
        return ("<Segment(ea=0x{:08X},"
                " name={!r},"
                " size=0x{:08X},"
                " permissions={!r},"
                " bitness={})>").format(self.ea,
                                        self.name,
                                        self.size,
                                        str(self.permissions),
                                        self.bitness)

def segments():
    for index in xrange(idaapi.get_segm_qty()):
        yield Segment(index=index)


text:
'use strict';

angular.module('issueApp')
	.provider('markdownConverter', function() {
		var opts = {};
		return {
			config: function(newOpts) {
				opts = newOpts;
			},
			$get: function() {
				return new Showdown.converter(opts);
			}
		};
	});


text:
namespace JustOrderIt.Data.Models.Identity
{
    using System;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Threading.Tasks;
    using Contracts;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;

    /// <summary>
    /// Inherits the IdentityRole class which is the base concrete ASP.NET implementation of a role entity.
    /// </summary>
    public class ApplicationRole : IdentityRole<string, ApplicationUserRole>, IBaseEntityModel<string>, IDeletableEntity, IAuditInfo, IAdministerable
    {
        public ApplicationRole()
            : base()
        {
            // Initialized the new role with a Guid Id. The default implementation of IdentityRole takes care of it automatically.
            // The following error occurs otherwise:
            // [DbEntityValidationException: Entity Validation Failed - errors follow:
            // JustOrderIt.Data.Models.ApplicationRole failed validation
            // - Id : The Id field is required.
            this.Id = Guid.NewGuid().ToString();
        }

        public ApplicationRole(string name)
            : this()
        {
            this.Name = name;
        }

        /// <summary>
        /// Gets or sets the date and time when the entity was created.
        /// </summary>
        /// <value>
        /// The date and time when the entity was created.
        /// </value>
        public DateTime CreatedOn { get; set; }

        /// <summary>
        /// Gets or sets the date and time when the entity was last modified.
        /// </summary>
        /// <value>
        /// The date and time when the entity was last modified.
        /// </value>
        public DateTime? ModifiedOn { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the entity is marked as deleted
        /// </summary>
        /// <value>
        /// A value indicating whether the entity is marked as deleted
        /// </value>
        [Index]
        public bool IsDeleted { get; set; }

        /// <summary>
        /// Gets or sets the date and time when the entity was marked as deleted
        /// </summary>
        /// <value>
        /// The date and time when the entity was marked as deleted
        /// </value>
        public DateTime? DeletedOn { get; set; }

        public async Task<IdentityResult> GenerateRoleAsync(RoleManager<ApplicationRole> roleManager)
        {
            var identrole = await roleManager.CreateAsync(this);

            // Customize role here
            return identrole;
        }
    }
}


text:
//  OCHamcrest by Jon Reid, http://qualitycoding.org/about/
//  Copyright 2015 hamcrest.org. See LICENSE.txt

#import <OCHamcrest/HCBaseMatcher.h>

@interface HCDescribedAs : HCBaseMatcher

+ (instancetype)describedAs:(NSString *)description
                 forMatcher:(id <HCMatcher>)matcher
                 overValues:(NSArray *)templateValues;

- (instancetype)initWithDescription:(NSString *)description
                         forMatcher:(id <HCMatcher>)matcher
                         overValues:(NSArray *)templateValues;

@end

FOUNDATION_EXPORT id HC_describedAs(NSString *description, id <HCMatcher> matcher, ...) NS_REQUIRES_NIL_TERMINATION;

#ifdef HC_SHORTHAND
/*!
 * @brief describedAs(description, matcher, ...) -
 * Adds custom failure description to a given matcher.
 * @param description Overrides the matcher's description.
 * @param matcher,... The matcher to satisfy, followed by a comma-separated list of substitution
 * values ending with nil.
 * @discussion The description may contain substitution placeholders %0, %1, etc. These will be
 * replaced by any values that follow the matcher.
 *
 * @attribute Name Clash
 * In the event of a name clash, don't #define HC_SHORTHAND and use the synonym
 * HC_describedAs instead.
 */
#define describedAs HC_describedAs
#endif


text:
package org.kie.workbench.common.stunner.core.client.canvas.command;

import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.command.CanvasViolation;
import org.kie.workbench.common.stunner.core.client.shape.MutationContext;
import org.kie.workbench.common.stunner.core.client.shape.Shape;
import org.kie.workbench.common.stunner.core.client.shape.view.BoundingBox;
import org.kie.workbench.common.stunner.core.client.shape.view.ShapeView;
import org.kie.workbench.common.stunner.core.command.CommandResult;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.view.BoundImpl;
import org.kie.workbench.common.stunner.core.graph.content.view.BoundsImpl;
import org.kie.workbench.common.stunner.core.graph.content.view.Point2D;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
import org.kie.workbench.common.stunner.core.graph.util.GraphUtils;

public abstract class AbstractRegistrationCanvasNodeCommand extends AbstractCanvasCommand {

    private final Node<? extends View<?>, Edge> candidate;
    private final String shapeSetId;

    protected AbstractRegistrationCanvasNodeCommand(final Node<? extends View<?>, Edge> candidate,
                                                    final String shapeSetId) {
        this.candidate = candidate;
        this.shapeSetId = shapeSetId;
    }

    @SuppressWarnings("unchecked")
    protected void register(final AbstractCanvasHandler context) {
        context.register(shapeSetId,
                         candidate);
        // Update view bounds for the element, if not set, by using the values from the shape view.
        final double[] size = GraphUtils.getNodeSize(candidate.getContent());
        if (size[0] <= 0 || size[1] <= 0) {
            final Shape shape = context.getCanvas().getShape(candidate.getUUID());
            final ShapeView shapeView = shape.getShapeView();
            final Point2D location = GraphUtils.getPosition(candidate.getContent());
            final BoundingBox boundingBox = shapeView.getBoundingBox();
            candidate.getContent()
                    .setBounds(new BoundsImpl(
                            new BoundImpl(location.getX(),
                                          location.getY()),
                            new BoundImpl(location.getX() + boundingBox.getWidth(),
                                          location.getY() + boundingBox.getHeight()
                            )));
        }
    }

    @Override
    public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler context) {
        register(context);
        context.applyElementMutation(candidate,
                                     MutationContext.STATIC);
        return buildResult();
    }

    public Node getCandidate() {
        return candidate;
    }

    public String getShapeSetId() {
        return shapeSetId;
    }
}


text:
<!DOCTYPE html>

<meta charset=utf-8>
<title>85 nips-2001-Grammar Transfer in a Second Order Recurrent Neural Network</title>

nips nips2001 nips2001-85 nips2001-85-reference knowledge-graph by maker-knowledge-mining

85 nips-2001-Grammar Transfer in a Second Order Recurrent Neural Network

Source: pdf

Author: Michiro Negishi, Stephen J. Hanson

Abstract: It has been known that people, after being exposed to sentences generated by an artificial grammar, acquire implicit grammatical knowledge and are able to transfer the knowledge to inputs that are generated by a modified grammar. We show that a second order recurrent neural network is able to transfer grammatical knowledge from one language (generated by a Finite State Machine) to another language which differ both in vocabularies and syntax. Representation of the grammatical knowledge in the network is analyzed using linear discriminant analysis. 1

reference text

[1] Brooks, L. R. , and Vokey, J . R. (1991) Abstract analogies and abstracted grammars: Comments on Reber (1989) and Mathews et al. (1090). Journal of Experimental Psychology: Gen eral, 120, 316-323.

[2] Dienes, Z. , Altmann, and G. , Gao , S-J. (1999) Mapping across domains without feedback: A neural network model of transfer of implicit knowledge, Cognitive Science 23, 53-82.

[3] Elman, J. L. (1991) Distributed representation , simple recurrent neural networks, and grammatical structure. Machine Learning, 7, 195-225.

[4] Giles, C. L. , Miller, C. B. , Chen, D. , Chen, H. H. , Sun, G. Z. , and Lee, Y. C. (1992) Learning and Extracting Finite State Automata with Second-Order Recurrent Neural Networks, it Neural Computation, 4 , 393-495.

[5] Hanson, S. J., Negishi, M., (2001) The emergence of explicit knowledge (symbols & rules) in (associationist) neural networks, Submitted.

[6] Reber, A. (1969) Transfer of syntactic structure in synthetic languages. Journal of Experimental Psychology, 81 , 115-119.

[7] Williams, R . J. and Zipser, D. (1989) A learning algorithm for continually running fully recurrent neural networks, Neural Computation, 1 (2) , 270.


text:
package io.skysail.server.ext.oauth2;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public class Token {

    private final String accessToken;
    private final Long expiresIn;

}


text:
const {getPlatformFromUserAgent, getPlatformLabel} = require('platform-utils')

module.exports = function updateDemoAppDownloadLink () {
  if (!document.querySelector('#download-latest-release')) return
  const platform = getPlatformFromUserAgent()

  if (!platform) return

  const releaseServer = 'https://electron-api-demos.githubapp.com/updates/'
  let assetName

  if (platform === 'darwin') assetName = 'electron-api-demos-mac.zip'
  if (platform === 'win32') assetName = 'ElectronAPIDemosSetup.exe'
  if (platform === 'linux') assetName = 'electron-api-demos-linux.zip'

  document.querySelector('#download-latest-release')
    .setAttribute('href', releaseServer + assetName)

  document.querySelector('#download-latest-release .label')
    .textContent = 'Download for ' + getPlatformLabel(platform)

  document.querySelector('#download-alternatives')
    .style.display = 'inline-block'
}


text:
Convert a three-dimensional array of spherical harmonic coefficients to a two-dimensional indexed array.

# Usage

call SHCilmToCindex (`cilm`, `cindex`, `degmax`)

# Parameters

`cilm` : input, real\*8, dimension (2, `lmaxin`+1, `lmaxin`+1)
:   The input spherical harmonic coefficients. `cilm(1,:,:)` and `cilm(2,:,:)` correspond to either the real and imaginary components, or cosine and sine coefficients, respectively.

`cindex` : output, real\*8, dimension (2, (`degmax`+1)\*(`degmax`+2)/2)
:   The indexed output spherical harmonic coefficients.

`degmax` : input, optional, integer, default = `lmaxin`
:   The maximum degree of the output coefficients.

# Description

`SHCilmToCindex` will convert a three-dimensional array of spherical harmonic coefficients to a two-dimensional indexed array.  The degree `l` and order `m` corresponds to the index `l*(l+1)/2+m+1`. The default is to convert the entire array `cilm`, but a subset of this array can be converted by specifying the optional argument `degmax`.

# See also

[shcindextocilm](shcindextocilm.html), [shcindextovector](pyshcindextovector.html), [shvectortocilm](pyshvectortocilm.html)


text:
package	org.apache.derby.impl.sql.compile;

import java.util.HashMap;
import java.util.List;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derby.iapi.sql.depend.Provider;
import org.apache.derby.iapi.sql.execute.ConstantAction;

/**
 * This class represents a GRANT statement.
 */
class GrantNode extends DDLStatementNode
{
	private PrivilegeNode privileges;
    private List<String> grantees;

    /**
     * Constructor for a GrantNode.
     *
     * @param privileges PrivilegesNode
     * @param grantees List
     * @param cm Context manager
     */
    GrantNode(PrivilegeNode privileges,
              List<String> grantees,
              ContextManager cm)
    {
        super(cm);
        this.privileges = privileges;
        this.grantees = grantees;
    }

	/**
	 * Convert this object to a String.  See comments in QueryTreeNode.java
	 * for how this should be done for tree printing.
	 *
	 * @return	This object as a String
	 */
    @Override
	public String toString()
	{
		if (SanityManager.DEBUG)
		{
            StringBuilder sb = new StringBuilder();

            for (String grantee : grantees)
			{
				if( sb.length() > 0)
					sb.append( ",");
                sb.append(grantee);
			}
			return super.toString() +
				   privileges.toString() +
				   "TO: \n" + sb.toString() + "\n";
		}
		else
		{
			return "";
		}
	} // end of toString

    String statementToString()
	{
		return "GRANT";
	}

	/**
	 * Bind this GrantNode. Resolve all table, column, and routine references.
	 *
	 *
	 * @exception StandardException	Standard error policy.
	 */
    @Override
	public void bindStatement() throws StandardException
	{
		privileges = (PrivilegeNode) privileges.bind( new HashMap<Provider,Provider>(), grantees, true);
	} // end of bind

	/**
	 * Create the Constant information that will drive the guts of Execution.
	 *
	 * @exception StandardException	Standard error policy.
	 */
    @Override
	public ConstantAction makeConstantAction() throws StandardException
	{
		return getGenericConstantActionFactory().getGrantConstantAction( privileges.makePrivilegeInfo(),
																		 grantees);
	}
}


text:
""" Example Dash application accompanying the post
at http://pbpython.com/plotly-dash-intro.html
"""

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd

# Read in the data from Excel
df = pd.read_excel(
    "https://github.com/chris1610/pbpython/blob/master/data/salesfunnel.xlsx?raw=True"
)

# Get a list of all the avilable managers
mgr_options = df["Manager"].unique()

# Create the app
app = dash.Dash()

# Populate the layout with HTML and graph components
app.layout = html.Div([
    html.H2("Sales Funnel Report"),
    html.Div(
        [
            dcc.Dropdown(
                id="Manager",
                options=[{
                    'label': i,
                    'value': i
                } for i in mgr_options],
                value='All Managers'),
        ],
        style={'width': '25%',
               'display': 'inline-block'}),
    dcc.Graph(id='funnel-graph'),
])

# Add the callbacks to support the interactive componets
@app.callback(
    dash.dependencies.Output('funnel-graph', 'figure'),
    [dash.dependencies.Input('Manager', 'value')])
def update_graph(Manager):
    if Manager == "All Managers":
        df_plot = df.copy()
    else:
        df_plot = df[df['Manager'] == Manager]

    pv = pd.pivot_table(
        df_plot,
        index=['Name'],
        columns=["Status"],
        values=['Quantity'],
        aggfunc=sum,
        fill_value=0)

    trace1 = go.Bar(x=pv.index, y=pv[('Quantity', 'declined')], name='Declined')
    trace2 = go.Bar(x=pv.index, y=pv[('Quantity', 'pending')], name='Pending')
    trace3 = go.Bar(x=pv.index, y=pv[('Quantity', 'presented')], name='Presented')
    trace4 = go.Bar(x=pv.index, y=pv[('Quantity', 'won')], name='Won')

    return {
        'data': [trace1, trace2, trace3, trace4],
        'layout':
        go.Layout(
            title='Customer Order Status for {}'.format(Manager),
            barmode='stack')
    }

if __name__ == '__main__':
    app.run_server(debug=True)


text:
using System;
using Executor.Contracts;
using Executor.Exceptions;

namespace Executor.IO.Commands
{
    public abstract class Command : IExecutable
    {
        private string input;
        private string[] data;

        protected Command(string input, string[] data)
        {
            this.Input = input;
            this.Data = data;
        }

        public string Input
        {
            get { return this.input; }

            private set
            {
                if (String.IsNullOrEmpty(value))
                {
                    throw new InvalidStringException(value);
                }

                this.input = value;
            }
        }

        public string[] Data
        {
            get { return this.data; }

            private set
            {
                if (value == null || value.Length == 0)
                {
                    throw new InvalidCommandException(this.Input);
                }

                this.data = value;
            }
        }

        public abstract void Execute();
    }
}


text:
import java.util.Scanner;

public class ChooseDrink {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String profession = scanner.nextLine();

        switch (profession)
        {
            case "Athlete":
                System.out.println("Water");
                break;
            case "Businessman":
            case "Businesswoman":
                System.out.println("Coffee");
                break;
            case "SoftUni Student":
                System.out.println("Beer");
                break;
            default:
                System.out.println("Tea");
                break;
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia, Beih. 109: 195 (1994)

#### Original name
Mycena noctilucens var. magnispora Corner

### Remarks
null


text:
/**
 * @fileoverview Gathers all entries logged to the console, including console API calls,
 * exceptions, and browser reports (on violations, interventions, deprecations, etc.).
 */

'use strict';

const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js');

/**
 * @param {LH.Crdp.Runtime.RemoteObject} obj
 * @return {string}
 */
function remoteObjectToString(obj) {
  if (typeof obj.value !== 'undefined' || obj.type === 'undefined') {
    return String(obj.value);
  }
  if (typeof obj.description === 'string' && obj.description !== obj.className) {
    return obj.description;
  }
  const type = obj.subtype || obj.type;
  const className = obj.className || 'Object';
  // Simulate calling String() on the object.
  return `[${type} ${className}]`;
}

class ConsoleMessages extends FRGatherer {
  /** @type {LH.Gatherer.GathererMeta} */
  meta = {
    supportedModes: ['timespan', 'navigation'],
  }

  constructor() {
    super();
    /** @type {LH.Artifacts.ConsoleMessage[]} */
    this._logEntries = [];

    this._onConsoleAPICalled = this.onConsoleAPICalled.bind(this);
    this._onExceptionThrown = this.onExceptionThrown.bind(this);
    this._onLogEntryAdded = this.onLogEntry.bind(this);
  }

  /**
   * Handles events for when a script invokes a console API.
   * @param {LH.Crdp.Runtime.ConsoleAPICalledEvent} event
   */
  onConsoleAPICalled(event) {
    const {type} = event;
    if (type !== 'warning' && type !== 'error') {
      // Only gather warnings and errors for brevity.
      return;
    }

    /** @type {LH.Crdp.Runtime.RemoteObject[]} */
    const args = event.args || [];
    const text = args.map(remoteObjectToString).join(' ');
    if (!text && !event.stackTrace) {
      // No useful information from Chrome. Skip.
      return;
    }

    const {url, lineNumber, columnNumber} =
      event.stackTrace && event.stackTrace.callFrames[0] || {};
    /** @type {LH.Artifacts.ConsoleMessage} */
    const consoleMessage = {
      eventType: 'consoleAPI',
      source: type === 'warning' ? 'console.warn' : 'console.error',
      level: type,
      text,
      stackTrace: event.stackTrace,
      timestamp: event.timestamp,
      url,
      lineNumber,
      columnNumber,
    };
    this._logEntries.push(consoleMessage);
  }

  /**
   * Handles exception thrown events.
   * @param {LH.Crdp.Runtime.ExceptionThrownEvent} event
   */
  onExceptionThrown(event) {
    const text = event.exceptionDetails.exception ?
          event.exceptionDetails.exception.description : event.exceptionDetails.text;
    if (!text) {
      return;
    }
    /** @type {LH.Artifacts.ConsoleMessage} */
    const consoleMessage = {
      eventType: 'exception',
      source: 'exception',
      level: 'error',
      text,
      stackTrace: event.exceptionDetails.stackTrace,
      timestamp: event.timestamp,
      url: event.exceptionDetails.url,
      lineNumber: event.exceptionDetails.lineNumber,
      columnNumber: event.exceptionDetails.columnNumber,
    };
    this._logEntries.push(consoleMessage);
  }

  /**
   * Handles browser reports logged to the console, including interventions,
   * deprecations, violations, and more.
   * @param {LH.Crdp.Log.EntryAddedEvent} event
   */
  onLogEntry(event) {
    const {source, level, text, stackTrace, timestamp, url, lineNumber} = event.entry;

    // JS events have a stack trace, which we use to get the column.
    // CSS/HTML events only expose a line number.
    const {columnNumber} = event.entry.stackTrace && event.entry.stackTrace.callFrames[0] || {};

    this._logEntries.push({
      eventType: 'protocolLog',
      source,
      level,
      text,
      stackTrace,
      timestamp,
      url,
      lineNumber,
      columnNumber,
    });
  }

  /**
   * @param {LH.Gatherer.FRTransitionalContext} passContext
   */
  async beforeTimespan(passContext) {
    const session = passContext.driver.defaultSession;

    session.on('Log.entryAdded', this._onLogEntryAdded);
    await session.sendCommand('Log.enable');
    await session.sendCommand('Log.startViolationsReport', {
      config: [{name: 'discouragedAPIUse', threshold: -1}],
    });

    session.on('Runtime.consoleAPICalled', this._onConsoleAPICalled);
    session.on('Runtime.exceptionThrown', this._onExceptionThrown);
    await session.sendCommand('Runtime.enable');
  }

  /**
   * @param {LH.Gatherer.FRTransitionalContext} passContext
   * @return {Promise<LH.Artifacts['ConsoleMessages']>}
   */
  async afterTimespan({driver}) {
    await driver.defaultSession.sendCommand('Log.stopViolationsReport');
    await driver.defaultSession.off('Log.entryAdded', this._onLogEntryAdded);
    await driver.defaultSession.sendCommand('Log.disable');
    await driver.defaultSession.off('Runtime.consoleAPICalled', this._onConsoleAPICalled);
    await driver.defaultSession.off('Runtime.exceptionThrown', this._onExceptionThrown);
    await driver.defaultSession.sendCommand('Runtime.disable');
    return this._logEntries;
  }
}

module.exports = ConsoleMessages;


text:
import bulletinModules from './remote/bulletinModules';
import cors from './remote/cors';
import corsBiddingStats from './remote/corsBiddingStats';
import examTimetable from './remote/examTimetable';
import ivle from './remote/ivle';
import moduleTimetableDelta from './remote/moduleTimetableDelta';
import venues from './remote/venues';
import mergeCorsBiddingStats from './local/mergeCorsBiddingStats';
import consolidateForSem from './local/consolidateForSem';
import consolidateForYear from './local/consolidateForYear';
import splitForSem from './local/splitForSem';
import splitForYear from './local/splitForYear';

export default {
  bulletinModules,
  cors,
  corsBiddingStats,
  examTimetable,
  ivle,
  moduleTimetableDelta,
  venues,
  mergeCorsBiddingStats,
  consolidateForSem,
  splitForSem,
  consolidateForYear,
  splitForYear,
};


text:
package com.github.dockerjava.jaxrs;

import com.github.dockerjava.api.command.VersionCmd;
import com.github.dockerjava.api.model.Version;
import com.github.dockerjava.core.DockerClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

public class VersionCmdExec extends AbstrSyncDockerCmdExec<VersionCmd, Version> implements VersionCmd.Exec {

    private static final Logger LOGGER = LoggerFactory.getLogger(VersionCmdExec.class);

    public VersionCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) {
        super(baseResource, dockerClientConfig);
    }

    @Override
    protected Version execute(VersionCmd command) {
        WebTarget webResource = getBaseResource().path("/version");

        LOGGER.trace("GET: {}", webResource);
        return webResource.request().accept(MediaType.APPLICATION_JSON).get(Version.class);
    }

}


text:
package io.storage.core.entities;

import java.time.Instant;

/**
 * An entity representing a file.
 *
 * @author Guy Raz Nir
 * @since 26/06/2017
 */
public class FileEntity extends BaseEntity {

    /**
     * File size, in bytes.
     */
    public long size;

    /**
     * Size of file in human readable format (e.g.: 1,455 bytes, 1.8GB, etc....).
     */
    public String humanReadableSize;

    /**
     * Timestamp when file was last modified. This field is optional, since not all storage service providers support file
     * modification timestamp.
     */
    public Instant modificationDate;

}


text:
class Gws::Elasticsearch::Setting::Circular
  include ActiveModel::Model
  include Gws::Elasticsearch::Setting::Base

  self.model = Gws::Circular::Post

  def menu_label
    @cur_site.menu_circular_label || I18n.t('modules.gws/circular')
  end

  def search_types
    search_types = []
    return search_types unless cur_site.menu_circular_visible?

    if Gws::Circular::Post.allowed?(:read, @cur_user, site: @cur_site)
      search_types << Gws::Circular::Post.collection_name
    end
    search_types
  end

  def translate_category(es_type, cate_name)
    # @categories ||= Gws::Board::Category.site(cur_site).to_a
    # cate = @categories.find { |cate| cate.name == cate_name }
    # return if cate.blank?
    #
    # [ cate, url_helpers.gws_circular_category_topics_path(site: cur_site, category: cate) ]
  end
end


text:
package com.xiao.ex.common;

import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * MyBatis配置
 *
 * @author 肖亭
 * @since 2017年10月11 10:29
 **/
@Configuration
public class MyBatisConfig {
    /**
     * 分页插件
     * @return
     */
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }
}


text:
/*jshint node:true*/
module.exports = {
  // see package.json
  // TLDR: 1.13.x ++
  useVersionCompatibility: true
};


text:
import Component from '@ember/component';
import ModalBase from 'shared/mixins/modal-base';
import layout from './template';
import { inject as service } from '@ember/service';
import { all } from 'rsvp'
import { get, set } from '@ember/object'
import { isArray } from '@ember/array'
import { alias } from '@ember/object/computed';

export default Component.extend(ModalBase, {
  scope: service(),

  classNames: ['medium-modal'],

  layout,
  originalModel: alias('modalService.modalOpts'),
  model: null,

  allProjects: null,
  projectId: null,

  init() {
    this._super(...arguments);
    this.set('allProjects', this.get('globalStore').all('project').filterBy('clusterId', this.get('scope.currentCluster.id')));

    let list = get(this, 'originalModel');
    if ( !isArray(list) ) {
      list = [list];
    }
    set(this, 'model', list);
  },

  actions: {
    save() {
      const promises = [];
      let list = get(this, 'model');
      if ( !isArray(list) ) {
        list = [list];
      }

      list.forEach((ns) => {
        let clone = ns.clone();
        set(clone, 'projectId', get(this, 'projectId'));
        promises.push(clone.save());
      })

      all(promises).then(() => {
        this.send('cancel')
      });
    },
  }
});


text:
// Licensed under the MIT License. See LICENSE in the git repository root for license information.

namespace Ecwid.Models
{
    /// <summary>
    /// This class is for TOrder implement
    /// TODO more
    /// </summary>
    public abstract class BaseOrder
    {
    }
}


text:
using System.Data.SqlClient;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Generators;
using FluentMigrator.Runner.Generators.SqlServer;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.Processors.SqlServer;
using FluentMigrator.Tests.Helpers;
using NUnit.Framework;
using NUnit.Should;

namespace FluentMigrator.Tests.Integration.Processors.SqlServer
{
    [TestFixture]
    [Category("Integration")]
    public class SqlServerConstraintTests : BaseConstraintTests
    {
        public SqlConnection Connection { get; set; }
        public SqlServerProcessor Processor { get; set; }
        public IQuoter Quoter { get; set; }

        [SetUp]
        public void SetUp()
        {
            Connection = new SqlConnection(IntegrationTestOptions.SqlServer2012.ConnectionString);
            Processor = new SqlServerProcessor(Connection, new SqlServer2012Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
            Quoter = new SqlServerQuoter();
            Connection.Open();
            Processor.BeginTransaction();
        }

        [TearDown]
        public void TearDown()
        {
            Processor.CommitTransaction();
            Processor.Dispose();
        }

        [Test]
        public override void CallingConstraintExistsCanAcceptConstraintNameWithSingleQuote()
        {
            var constraintName = Quoter.QuoteConstraintName("c'1");

            using (var table = new SqlServerTestTable(Processor, null, "id int", string.Format("wibble int CONSTRAINT {0} CHECK(wibble > 0)", constraintName)))
                Processor.ConstraintExists(null, table.Name, "c'1").ShouldBeTrue();
        }

        [Test]
        public override void CallingConstraintExistsCanAcceptTableNameWithSingleQuote()
        {
            using (var table = new SqlServerTestTable("Test'Table", Processor, null, "id int", "wibble int CONSTRAINT c1 CHECK(wibble > 0)"))
                Processor.ConstraintExists(null, table.Name, "c1").ShouldBeTrue();
        }

        [Test]
        public override void CallingConstraintExistsReturnsFalseIfConstraintDoesNotExist()
        {
            using (var table = new SqlServerTestTable(Processor, null, "id int"))
                Processor.ConstraintExists(null, table.Name, "DoesNotExist").ShouldBeFalse();
        }

        [Test]
        public override void CallingConstraintExistsReturnsFalseIfConstraintDoesNotExistWithSchema()
        {
            using (var table = new SqlServerTestTable(Processor, "test_schema", "id int"))
                Processor.ConstraintExists("test_schema", table.Name, "DoesNotExist").ShouldBeFalse();
        }

        [Test]
        public override void CallingConstraintExistsReturnsFalseIfTableDoesNotExist()
        {
            Processor.ConstraintExists(null, "DoesNotExist", "DoesNotExist").ShouldBeFalse();
        }

        [Test]
        public override void CallingConstraintExistsReturnsFalseIfTableDoesNotExistWithSchema()
        {
            Processor.ConstraintExists("test_schema", "DoesNotExist", "DoesNotExist").ShouldBeFalse();
        }

        [Test]
        public override void CallingConstraintExistsReturnsTrueIfConstraintExists()
        {
            using (var table = new SqlServerTestTable(Processor, null, "id int", "wibble int CONSTRAINT c1 CHECK(wibble > 0)"))
                Processor.ConstraintExists(null, table.Name, "c1").ShouldBeTrue();
        }

        [Test]
        public override void CallingConstraintExistsReturnsTrueIfConstraintExistsWithSchema()
        {
            using (var table = new SqlServerTestTable(Processor, "test_schema", "id int", "wibble int CONSTRAINT c1 CHECK(wibble > 0)"))
                Processor.ConstraintExists("test_schema", table.Name, "c1").ShouldBeTrue();
        }
    }
}


text:
'use strict';

var fs = require("fs");
var path = require("path");
var request = require("request");

var Team = require("./team.js");
var Teamset = require("./teamset.js");

global.API_URL = "http://www.worldsolarchallenge.org/api/positions";

// global.FETCH_INTERVAL = X; means check for fresh data every X seconds
global.FETCH_INTERVAL = 5 * 60;
// It looks like the API endpoint gets refreshed every 5 minutes
global.FETCH_INTERVAL = 2*60;

// This is the global shared state
var state = new Teamset();
state.loadTeams();

function fetchLiveData(state) {
	var reqDate = new Date();
	console.log(""+reqDate,"Fetching data…");
	request({
		url: API_URL,
		json: true
	}, function (error, response, body) {
		response = response || {};
		if (!error && response.statusCode === 200) {
			//console.log(body);
			if (body.length) {
				var anyDirty = false;
				var dirtyCount = 0;
				body.forEach(function(r){
//						console.log("processing",r);
					var thisDirty = state.importRow(r);
					if (thisDirty) {
						dirtyCount++;
					}
				});
				if (dirtyCount > 0) {
					console.log(""+reqDate,"Data updated for",dirtyCount,"teams!");
					state.serialize();
				} else {
					console.log(""+reqDate,"No updates.");
				}
			}
		} else {
			console.error(""+reqDate,"Error loading data!",response.statusCode,error);
		}
		setTimeout(function() {
			fetchLiveData(state);
		}, FETCH_INTERVAL*1000);
	});
}
fetchLiveData(state);


text:
var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/../dist'));
// views is directory for all template files
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/../dist');
app.set('view engine', 'html');

app.get('/', function(request, response) {
    response.render('index.html');
});

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});


text: from traitsui.theme import *


text:
import sbt._

class TestProject(info: ProjectInfo) extends DefaultProject(info)
{
	override def compileOrder = CompileOrder.JavaThenScala
}


text:
Optimize an existing feature or asset on the page.

Remove an existing feature or asset from the page.

Don't add the new feature or asset.


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

//  require('foundation.slider');
  var Locale = require("utils/locale");
  var Tips = require("utils/tips");
  var WizardFields = require("utils/wizard-fields");
  var UserInputs = require("utils/user-inputs");

  /*
    TEMPLATES
   */

  var TemplateHTML = require("hbs!./capacity-create/html");

  /*
    CONSTRUCTOR
   */

  return {
    "html": _html,
    "setup": _setup,
    "fill": _fill,
    "retrieve": _retrieve,
    "calculatedRealMemory": _calculatedRealMemory,
    "calculatedRealCpu": _calculatedRealCpu,
    "totalCost": _totalCost
  };

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML();
  }

  function _m2g(val){
    if(isNaN(val) || val == ""){
      return "";
    }

    return val / 1024;
  }

  function _g2m(val){
    if(isNaN(val) || val == ""){
      return "";
    }
    return Math.floor(val * 1024);
  }
  function convertCostNumber(number){
    if(number >= 1000000){
      number = (number / 1000000).toFixed(2);
      return number.toString() + "M";
    }
    else if (number >= 1000){
      number = (number / 1000).toFixed(2);
      return number.toString() + "K";
    }
    else if (number >= 0 && number < 1000){
      number = (typeof number === "string"? parseFloat(number) : number);
      return number.toFixed(2);
    }
    else {
      return number;
    }
  }

  function _totalCost(){
    var memory = $("#real_memory_cost").val();
    var cpu = $("#real_cpu_cost").val();
    var disk_cost = $("#total_value_disk").text();
    var elementTotalCost = document.getElementById("total_cost");
    if (disk_cost === "") {
      disk_cost = 0;
    } else {
      disk_cost = parseFloat(disk_cost);
    }
    if(elementTotalCost){
      if ((memory === undefined || memory === "") && (cpu === undefined || cpu === "")){
        elementTotalCost.textContent = "Total: " + disk_cost;
      } else if(memory === undefined || memory === ""){
        elementTotalCost.textContent = "Total: " + convertCostNumber(cpu + disk_cost);
      } else if(cpu === undefined || cpu === ""){
        elementTotalCost.textContent = "Total: " + convertCostNumber(memory + disk_cost);
      } else {
        elementTotalCost.textContent = "Total: " + convertCostNumber(memory + cpu + disk_cost);
      }
    }
  }

  function _calculatedRealMemory(context){
    var memory_cost = $("#MEMORY_COST").val() || 0;
    var type_cost   = $("#MEMORY_UNIT_COST").val() || 0;
    var memory = $("#MEMORY").val();
    var type   = $("#memory_unit").val();
    if (type_cost == "GB"){
      memory = (memory / 1024) * memory_cost * 24 * 30;
    } else {
      memory = memory * memory_cost * 24 * 30;
    }
    var realMemory = document.getElementById("real_memory_cost");
    var totalMemory = document.getElementById("total_value_memory");
    if(realMemory && totalMemory){
      realMemory.value = memory;
      totalMemory.textContent = convertCostNumber(memory);
    }

    if (memory_cost != "")
      $(".total_memory_cost", context).show();

    _totalCost();
  }

  function _calculatedRealCpu(context){
    var cpu_cost = $("#CPU_COST").val() || 0;
    var cpu      = $("#CPU").val() || 0;
    var totalValueCpu = document.getElementById("real_cpu_cost");
    cpu = cpu * cpu_cost * 24 * 30;
    document.getElementById("real_cpu_cost").value = cpu;
    if(totalValueCpu){
      totalValueCpu.textContent = convertCostNumber(cpu);
    }
    if (cpu_cost != "")
      $(".total_cpu_cost", context).show();
    _totalCost();
  }

  function _generateCores(context){
    $('#CORES_PER_SOCKET').find('option').remove();
    $("#CORES_PER_SOCKET", context).append($('<option>').val("").text(""));
    var vcpu_count =  parseInt($("#VCPU").val()) || 0;
    for (var i = 1; i <= vcpu_count; i++){
      if (vcpu_count%i === 0){
        $('#CORES_PER_SOCKET').append($('<option>').val(i).text((i).toString()));
      }
    }
    $('#CORES_PER_SOCKET option[value=""]').prop('selected', true);
  }

  function _calculateSockets(context){
    var vcpu = $("#VCPU").val();
    var cores_per_socket = $("#CORES_PER_SOCKET").val();

    if ((vcpu != "") && (cores_per_socket != "")){
      $("div.socket_info").show();
      $("#number_sockets").text(vcpu/cores_per_socket);
    }
    else{
      $("div.socket_info").hide();
    }

  }

  function _setup(context) {
    context.on("change", "#MEMORY", function() {
      _calculatedRealMemory(context);
    });

    context.on("change", "#MEMORY_GB", function() {
      _calculatedRealMemory(context);
    });

    context.on("change", "#memory_unit", function() {
      _calculatedRealMemory(context);
    });

    context.on("change", "#CPU", function() {
      _calculatedRealCpu(context);
    });

    context.on("change", "#VCPU", function(){
      _generateCores(context);
      _calculateSockets(context);
    });

    context.on("change", "#CORES_PER_SOCKET", function(){
      _calculateSockets(context);
    });
    // MB to GB
    context.on("input", "div.memory_input input", function(){
      $("div.memory_gb_input input", context).val(_m2g(this.value));
    });

    // MB to GB, range input
    context.on("input", "div.mb_unit input.user_input_params_min", function(){
      $("div.gb_unit input.user_input_params_min").val(_m2g(this.value));
    });

    context.on("input", "div.mb_unit input.user_input_params_max", function(){
      $("div.gb_unit input.user_input_params_max").val(_m2g(this.value));
    });

    // MB to GB, list input
    context.on("input", "div.memory_modify_opt.list input.mb_unit", function(){
      var val = this.value.split(",").map(_m2g).join(",");

      $("div.memory_modify_opt.list input.gb_unit", context).val(val);
    });

    // GB to MB
    context.on("input", "div.memory_gb_input input", function(){
      $("div.memory_input input", context).val(_g2m(this.value));
    });

    // GB to MB, range input
    context.on("input", "div.gb_unit input.user_input_params_min", function(){
      $("div.mb_unit input.user_input_params_min").val(_g2m(this.value));
    });

    context.on("input", "div.gb_unit input.user_input_params_max", function(){
      $("div.mb_unit input.user_input_params_max").val(_g2m(this.value));
    });

    // GB to MB, list input
    context.on("input", "div.memory_modify_opt.list input.gb_unit", function(){
      var val = this.value.split(",").map(_g2m).join(",");

      $("div.memory_modify_opt.list input.mb_unit", context).val(val);
    });

    // Unit select
    $("#memory_unit", context).on("change", function() {
      var memory_unit_val = $("#memory_unit :selected", context).val();

      if (memory_unit_val == "GB") {
        $(".mb_unit", context).hide();
        $(".gb_unit", context).show();
      } else {
        $(".mb_unit", context).show();
        $(".gb_unit", context).hide();
      }

      $(".memory_modify_unit", context).text(memory_unit_val);
    });

    $("#memory_unit", context).change();

    // Select for memory, cpu, vcpu modification on instantiate
    $.each(["memory","cpu","vcpu"], function(i,classname){
      $("."+classname+"_modify_type", context).on("change", function(){
        $("."+classname+"_modify_opt", context).hide();
        if(this.value != ""){
          $("."+classname+"_modify_opt."+this.value, context).show();
        }

        $("#memory_unit", context).change();
      });

      $("."+classname+"_modify_type", context).change();
    });
  }

  /**
   * Fills the capacity inputs
   * @param  {Object} context  JQuery selector
   * @param  {Object} template VM or VMTemplate object
   */
  function _fill(context, element) {

    var fields = $("[wizard_field]", context);

    fields.each(function() {
      var field_name = $(this).attr("wizard_field");
      $(this).data("original_value", element[field_name]);
    });

    WizardFields.fill(context, element);

    // Update memory_gb with the value set in memory
    $("div.memory_input input", context).trigger("input");

    if ($("div.memory_input input", context).val() && $("div.memory_input input", context).val() < 1024){
      $("#memory_unit", context).val("MB").change();
    } else {
      $("#memory_unit", context).val("GB").change();
    }

    var userInputsJSON = element["USER_INPUTS"];

    if (userInputsJSON) {
      $.each(["memory","cpu","vcpu"], function(i,classname){
        var name = classname.toUpperCase();

        if (userInputsJSON[name] != undefined){
          var attr = UserInputs.unmarshall(userInputsJSON[name]);

          $("."+classname+"_modify_type", context).val(attr.type).change();

          if (attr.type == "range" ||
              attr.type == "range-float"){

            var values = attr.params.split("..");  // "2..8"

            if (values.length == 2){
              var param_context = $("div."+classname+"_modify_opt."+attr.type, context);

              $("input.user_input_params_min", param_context).val(values[0]).trigger("input");
              $("input.user_input_params_max", param_context).val(values[1]).trigger("input");
            } else {
              console.error("Wrong user input parameters for \""+name+"\". Expected \"MIN..MAX\", received \""+attr.params+"\"");
            }
          } else if (attr.type == "list"){
            $("input."+classname+"_modify_opt."+attr.type, context).val(attr.params).trigger("input");
          }

          delete userInputsJSON[name];
        }
      });
    }
  }

  /**
   * Retrieves the input values
   * @param  {Object} context  JQuery selector
   * @return {Object}         If the input is not empty, returns:
   *                                  - CPU
   *                                  - MEMORY
   *                                  - VCPU
   *                                  - USER_INPUTS for cpu, memory, vcpu
   */
  function _retrieve(context) {
    var templateJSON = WizardFields.retrieve(context);

    var userInputsJSON = {};

    $.each(["memory","cpu","vcpu"], function(i,classname){
      var attr = {};

      attr.type = $("."+classname+"_modify_type", context).val();

      if (attr.type == "number" || attr.type == "number-float"){
        // Continue. No user input is the same as 'any value'
        return true;
      }

      attr.name = classname.toUpperCase();
      attr.mandatory = true;
      attr.description = "";

      if (classname == "vcpu" || attr.type == "fixed"){
        attr.mandatory = false;
      }

      attr.initial = $("input[wizard_field=\""+attr.name+"\"]", context).val();

      if (attr.type == "range" ||
          attr.type == "range-float"){

        var param_context = $("div."+classname+"_modify_opt."+attr.type, context);

        var min = $("input.user_input_params_min", param_context).val();
        var max = $("input.user_input_params_max", param_context).val();
        attr.params  = min + ".." + max;

      } else if (attr.type == "list"){
        attr.params = $("input."+classname+"_modify_opt."+attr.type, context).val();
      }

      userInputsJSON[attr.name] = UserInputs.marshall(attr);
    });

    if (!$.isEmptyObject(userInputsJSON)) {
      templateJSON["USER_INPUTS"] = userInputsJSON;
    }

    return templateJSON;
  }
});