text:
window.onload = function( ) {

    var audio = document.getElementById('audio'),// 音乐
    sourceList = audio.getElementsByTagName('source'),// 音乐列表
    play = document.getElementById('play'),// play
    prev = document.getElementById('prev'),// prev
    next = document.getElementById('next'),// next
    jingyin = document.getElementById('mute'), // 静音
	voiceBar = document.getElementById('voice-bar'), // 音量调节
	musicBar = document.getElementById('music-bar'), // 播放进度控制
	playedBar = document.getElementById('played-bar'), // 已播放进度条
	voicedBar = document.getElementById('voiced-bar'), // 已播放音乐条
	musicTitle = document.getElementById('title'), // 音乐标题
	loadBar = document.getElementById('load-bar'), // 加载进度条
	currentTime = document.getElementById('current-time'), // 当前音乐时间
	totalTime = document.getElementById('total-time'), // 当前音乐时间
	musicImg = document.getElementById('music-img'), // 音乐封面
	xunhuan = document.getElementById('xunhuan'); // 循环按钮
	currentSrcIndex = 0;

	// 是否循环播放
	audio.loop = false;

	// 是否自动播放
	audio.autoplay = false;

	//初始化音量
	audio.volume = 0.5;
	var voicedBarWidth = (audio.volume / 1) * voiceBar.clientWidth;
	voicedBar.style.width = voicedBarWidth + 'px';

	// 显示第一首歌曲时长
	(function () {
		var fen = parseInt(audio.duration / 60);
		var miao = parseInt(audio.duration % 60);
		if (miao < 10) {
			miao = '0'+miao;
		}
		totalTime.innerHTML = fen + ':' + miao;
	})();

	// 播放 暂停
	play.onclick = function () {
        if (audio.paused) {
			audio.play();
			this.innerHTML = 'Pause';
			musicImg.style.animation = 'xuanzhuan 5s linear infinite';
		} else {
			audio.pause();
			this.innerHTML = 'Play';
			musicImg.removeAttribute('style');
		}
		musicTime();
	};

	// 上一曲
	prev.onclick = function () {
		changeMusic('prev');
	};

	// 下一曲
	next.onclick = function () {
		changeMusic('next');
	};

	// 切换歌曲
	function changeMusic (direct) {
		if (direct === 'next') {
			++ currentSrcIndex > sourceList.length - 1 && (currentSrcIndex = 0); // next music
		}
		else {
			-- currentSrcIndex < 0 && (currentSrcIndex = sourceList.length - 1); //prev music
 		}
		currentSrc = sourceList[currentSrcIndex].getAttribute('src');
		currentImg = sourceList[currentSrcIndex].getAttribute('data-img');
		musicTitle.innerHTML = sourceList[currentSrcIndex].title;
		musicImg.setAttribute('src',currentImg);
		audio.setAttribute('src',currentSrc);
		audio.play();
		play.innerHTML = 'Pause';
		musicImg.style.animation = 'xuanzhuan 5s liner infinite';
		musicTime;
	}

	// 音量调节(增加黄色现在音量显示)
	voiceBar.onclick = function (event) {
		var voiceBarWidth = voiceBar.clientWidth;
		var newVolume = (event.offsetX / voiceBarWidth);
		audio.volume = newVolume;

		// 音量大小更新
		var voicedBarWidth = (audio.volume / 1) * voiceBarWidth;
		voicedBar.style.width = voicedBarWidth + 'px';
	};

	// 播放进度控制
	musicBar.onclick = function (event) {
		var musicBarWidth = musicBar.clientWidth;
		var newCurrentTime = (event.offsetX / musicBarWidth) * audio.duration;
		audio.currentTime = newCurrentTime;
		var playedBarWidth = (audio.currentTime / audio.duration) * musicBarWidth;
		playedBar.style.width = playedBarWidth + 'px';
	};

	// 播放进度实时更新(修改为歌曲播放时开启定时器,暂停和页面load时清除定时器)
	setInterval(function updatePlayedBar (){
		var musicBarWidth = musicBar.clientWidth;
		var playedBarWidth = (audio.currentTime / audio.duration) * musicBarWidth;
		playedBar.style.width = playedBarWidth + 'px';
		if (audio.currentTime % 60 < 10) {
			currentTime.innerHTML = parseInt(audio.currentTime / 60) + ':0' + parseInt(audio.currentTime % 60);
		} else {
			currentTime.innerHTML = parseInt(audio.currentTime / 60) + ':' + parseInt(audio.currentTime % 60);
		}
		//如果是时间结束,并且是非单曲循环,自动下一曲
		if (audio.currentTime === audio.duration && !audio.loop) {
			next.onclick();
		}
	}, 1000);

	// 静音
	jingyin.onclick = function () {
		if (!audio.muted) {
			audio.muted = true;
			voicedBar.style.width = 0 +'px';
		}else {
			audio.muted = false;
			var voiceBarWidth = voiceBar.clientWidth;

			// 音量大小更新
			var voicedBarWidth = (audio.volume / 1) * voiceBarWidth;
			voicedBar.style.width = voicedBarWidth + 'px';
		}
	};

	// 是否单曲循环
	xunhuan.onclick = function () {
		if (audio.loop) {
			audio.loop = false;
			this.innerHTML = '循环';
		} else {
			audio.loop = true;
			this.innerHTML = '单曲';
		}
	};

	// 计算音乐时间
	function musicTime() {
		// 更换播放歌曲
		musicTitle.innerHTML = sourceList[currentSrcIndex].title;
		// 播放时间显示
		audio.addEventListener("canplay", function(){
			var sc=audio.duration;
			var fen = parseInt(sc / 60);
			var miao = parseInt(sc % 60);
			if (miao < 10) {
				totalTime.innerHTML = fen + ':0' + miao;
			}else {
				totalTime.innerHTML = fen + ':' + miao;
			}
		});
	};

}


text:
<!-- Auto-generated by x/build/update-readmes.go -->

[![Go Reference](https://pkg.go.dev/badge/golang.org/x/build/cmd/upload.svg)](https://pkg.go.dev/golang.org/x/build/cmd/upload)

# golang.org/x/build/cmd/upload

The upload command writes a file to Google Cloud Storage.

redpajama_set_name: RedPajamaGithub


text:
/**
 * @class Context
 */
class Context
{
    /**
     * Constructor
     * @param {Object} routing
     * @param {String} siteId
     * @param {String} language
     * @param {Object} user
     * @param {Array}  siteLanguages
     */
    constructor({routing, siteId, language, user, siteLanguages}) {
        this.routing = routing;
        this.siteId = siteId;
        this.language = language;
        this.user = user;
        this.siteLanguages = siteLanguages;
    }

    /**
     * Reset context on server and reload pages
     */
    refreshContext() {
        let url = Routing.generate('clearContext');
        $.get(url).done(() => window.location.reload());
    }

    /**
     * Update user access rights
     * @param {String} section
     * @param {String} access
     */
    updateUserAccessSection(section, access) {
        if (typeof this.user !== 'undefined' && typeof this.user.access_section !== 'undefined') {
            this.user.access_section[section] = access;
        }
    }

    /**
     * Get a context property
     * @param {String} property
     *
     * @return {mixed}
     */
    get(property) {
        if (this.hasOwnProperty(property)) {
            return this[property];
        }

        throw new Error('Missing property ' + property + ' in context');
    }

    /**
     * Set a context property
     * @param {String} property
     * @param {mixed}  value
     */
    set(property, value) {
        this[property] = value;
    }
}

export default Context;


text:
Thank you for your interest in contributing to this project!

* If you're confident you've identified a bug, or have already written a
  patch, feel free to open an issue or pull request. Otherwise, please discuss
  on the `mezzanine-users <http://groups.google.com/group/mezzanine-users/topics>`_ mailing list first.
* For large features or bug fixes it's always a good idea to open an issue before you start developing your solution. This way the right approach and ideas can be discussed upfront instead of after spending time and energy developing it.
* Contributions must be made available on a separately named branch,
  based on the latest version of the master branch.
* If you are adding new functionality, you must include basic tests
  and documentation.
* Please add your name to the end of the AUTHORS file as part of your pull
  request.

Testing
-------

After cloning the repository and working on your contribution, install the extra testing requirements and run ``pytest``.

.. code-block:: bash

    pip install -e ".[testing]"
    pytest

Since the test suite is quite big you may want to run only a specific test case:

.. code-block:: bash

    # Test the "galleries" app only
    pytest tests/test_galleries.py

Code Style
----------

Python code style is enforced with ``flake8`` and  ``black``. You can install and run both as follows:

.. code-block:: bash

  pip install -e ".[codestyle]"
  black . --check # Omit the flag to have black autofix errors
  flake8 .

If your editor is configured to integrate with ``black`` and ``flake8`` it should pick up the project's configuration automatically.

Continous Integration
---------------------

When you are ready to contribute your changes `create and submit a pull request <https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request>`_ against the ``master`` branch. This will run all tests in all supported Python and Django versions and alert you if any of them fail.


text:
package fr.m1info.rv2j.forms;

import java.sql.Date;

import javax.servlet.http.HttpServletRequest;

import fr.m1info.rv2j.beans.Commentary;
import fr.m1info.rv2j.dao.CommentaryDAO;
import fr.m1info.rv2j.dao.DAOException;

public class AdminCommentaryEdition extends Forms{
	public final static String ID_FIELD = "id";
	public final static String TEXT_FIELD = "text";

	private CommentaryDAO commentaryDAO;

	/**	CONSTRUCTEURS	**/
	public AdminCommentaryEdition() {
		super();
	}

	public AdminCommentaryEdition(CommentaryDAO commentaryDAO) {
		super();
		this.commentaryDAO = commentaryDAO;
	}

	public Commentary editCommentary(HttpServletRequest request) {
		Commentary commentary = new Commentary();

		String id = getFieldValue(request, ID_FIELD);
		String text = getFieldValue(request, TEXT_FIELD);

		try {
			commentary.setID(Integer.parseInt(id));
			textProcessing(text, commentary);
			lastUpdateProcessing(commentary);

			if (errors.isEmpty()) {
				commentaryDAO.update(id, commentary);
				result = "Succès de l'édition du commentaire.";
			} else
				result = "Échec de l'édition du commentaire.";
		} catch(DAOException E) {
			result = "Échec de l'édition : une erreur imprévue est survenue, merci de réessayer dans quelques instants.";
			E.printStackTrace();
		}

		return commentary;
	}

	private void textProcessing(String text, Commentary commentary) {
		try {
			checkText(text);
			commentary.setText(text);
		} catch (FormValidationException E) {
			E.printStackTrace();
			addErrors(TEXT_FIELD, E.getMessage());
		}
	}

	private void checkText(String text) throws FormValidationException {
		if(text != null) {
			if(text.length() < 5)
				throw new FormValidationException("Merci d'entrer une présentation d'au moins 10 caractères.");
		}	else
			throw new FormValidationException("Merci d'entrer une présentation d'au moins 10 caractères.");
	}

	private void lastUpdateProcessing(Commentary commentary) {
			commentary.setLastUpdate(new Date(System.currentTimeMillis()));
	}
}


text:
Next %, to give a qualitative sense of the kinds of properties analyzed
% during the course of our evaluation,
we present a brief overview of the verification of \libtext, which
is the standard library used for serious unicode text processing.
\libtext uses byte arrays and stream fusion to guarantee
performance while providing a high-level API.
In our evaluation of \toolname on \libtext,%~\cite{text},
we focused on two types of properties:
(1) the safety of array index and write operations, and
(2) the functional correctness of the top-level API.
%
These are both made more interesting by the fact that
\libtext internally encodes characters using UTF-16,
in which characters are stored in either two or four bytes.
%
\libtext is a vast library spanning 39 modules and 5,700 lines of
code, however we focus on the 17 modules that are relevant
to the above properties.
%
While we have verified exact functional correctness size properties
for the top-level API, we focus here on the low-level functions
and interaction with unicode.

\spara{Arrays and Texts}
A @Text@ consists of an (immutable) @Array@ of 16-bit words,
an offset into the @Array@, and a length describing the
number of @Word16@s in the @Text@.
The @Array@ is created and filled using a
\emph{mutable} @MArray@.
All write operations in \libtext are performed on @MArray@s
in the @ST@ monad, but they are \emph{frozen} into @Array@s
before being used by the @Text@ constructor.
%
We write a measure for the size of an @MArray@ and use
it to type the write and freeze operations.
%
\begin{code}
  measure malen       :: MArray s -> Int
  predicate EqLen A MA = alen A = malen MA
  predicate Ok I A     = 0 <= I < malen A
  type VO A            = {v:Int| Ok v A}

  unsafeWrite  :: m:MArray s
               -> VO m -> Word16 -> ST s ()
  unsafeFreeze :: m:MArray s
               -> ST s {v:Array | EqLen v m}
\end{code}

\spara{Reasoning about Unicode}
The function @writeChar@ (abbreviating the function \texttt{unsafeWrite} from \texttt{UnsafeChar})
writes a @Char@ into an @MArray@.
\libtext uses UTF-16 to represent characters internally,
meaning that every @Char@ will be encoded using two or
four bytes (one or two @Word16@s).
%
\begin{code}
  writeChar marr i c
      | n < 0x10000 = do
          unsafeWrite marr i (fromIntegral n)
          return 1
      | otherwise = do
          unsafeWrite marr i lo
          unsafeWrite marr (i+1) hi
          return 2
      where n = ord c
            m = n - 0x10000
            lo = fromIntegral
               $ (m `shiftR` 10) + 0xD800
            hi = fromIntegral
               $ (m .&. 0x3FF) + 0xDC00
\end{code}
%
The UTF-16 encoding complicates the specification of the function
as we cannot simply require @i@ to be less than the length of
@marr@; if @i@ were @malen marr - 1@ and @c@ required two
@Word16@s, we would perform an out-of-bounds write.
%
We account for this subtlety with a predicate that states
there is enough @Room@ to encode @c@.
%
% measure ord         :: Char -> Int
\begin{code}
  predicate OkN I A N  = Ok (I+N-1) A
  predicate Room I A C = if ord C < 0x10000
                         then OkN I A 1
                         else OkN I A 2

  type OkSiz I A = {v:Nat  | OkN  I A v}
  type OkChr I A = {v:Char | Room I A v}
\end{code}
%
@Room i marr c@ says
``if @c@ is encoded using one @Word16@,
  then @i@ must be less than @malen marr@,
  otherwise @i@ must be less than @malen marr - 1@.''
%
@OkSiz I A@ is an alias for a valid number of @Word16@s
remaining after the index @I@ of array @A@.
@OkChr@ specifies the @Char@s for which there is room (to write)
at index @I@ in array @A@.
%
The specification for @writeChar@ states that given an array \hbox{@marr@,}
an index @i@, and a valid @Char@ for which there is room at index \hbox{@i@,}
the output is a monadic action returning the number of @Word16@ occupied
by the @char@.
%
\begin{code}
  writeChar :: marr:MArray s
            -> i:Nat
            -> OkChr i marr
            -> ST s (OkSiz i marr)
\end{code}
%
\spara{Bug}
Thus, clients of @writeChar@ should only call it with suitable indices
and characters.
%
Using \toolname we found an error in one client, @mapAccumL@,
which combines a map and a fold over a @Stream@, and stores
the result of the map in a @Text@. Consider the inner loop of @mapAccumL@.
%
% \begin{code}
% mapAccumL f z0 (Stream next0 s0 len) =
%   (nz, Text na 0 nl)
%  where
%   mlen = upperBound 4 len
%   (na,(nz,nl)) = runST $ do
%        (marr,x) <- (new mlen >>= \arr ->
%                     outer arr mlen z0 s0 0)
%        arr      <- unsafeFreeze marr
%        return (arr,x)
%   outer arr top = loop
%    where
%     loop !z !s !i =
%       case next0 s of
%         Done          -> return (arr, (z,i))
%         Skip s'       -> loop z s' i
%         Yield x s'
%           | j >= top  -> do
%             let top' = (top + 1) `shiftL` 1
%             arr' <- new top'
%             copyM arr' 0 arr 0 top
%             outer arr' top' z s i
%           | otherwise -> do
%             let (z',c) = f z x
%             d <- writeChar arr i c
%             loop z' s' (i+d)
%           where j | ord x < 0x10000 = i
%                   | otherwise       = i + 1
% \end{code}
\begin{code}
  outer arr top = loop
   where
    loop !z !s !i =
      case next0 s of
        Done          -> return (arr, (z,i))
        Skip s'       -> loop z s' i
        Yield x s'
          | j >= top  -> do
            let top' = (top + 1) `shiftL` 1
            arr' <- new top'
            copyM arr' 0 arr 0 top
            outer arr' top' z s i
          | otherwise -> do
            let (z',c) = f z x
            d <- writeChar arr i c
            loop z' s' (i+d)
          where j | ord x < 0x10000 = i
                  | otherwise       = i + 1
\end{code}
%
Let's focus on the @Yield x s'@ case.
%
We first compute the maximum index @j@ to
which we will write and determine the safety of a write.
%
If it is safe to write to @j@ we call the provided
function @f@ on the accumulator @z@ and the character
@x@, and write the \emph{resulting} character @c@ into the array.
%
However, we know nothing about @c@, in particular,
whether @c@ will be stored as one or two @Word16@s!
Thus, \toolname flags the call to @writeChar@ as \emph{unsafe}.
The error can be fixed by lifting @f z x@ into the @where@ clause and defining the
write index @j@ by comparing @ord c@ (not @ord x@). \toolname (and the authors)
readily accepted our fix.

%% INCLUDEPROOF To illustrate why the call is in fact buggy,
%% INCLUDEPROOF consider a sample iteration of @loop@
%% INCLUDEPROOF where @i = malen arr - 1@ and
%% INCLUDEPROOF @ord x < 0x10000@.
%% INCLUDEPROOF %
%% INCLUDEPROOF In this case @j@ will equal @i@ and we will enter
%% INCLUDEPROOF the @otherwise@ branch.
%% INCLUDEPROOF %
%% INCLUDEPROOF Next, suppose @f z x@ returns a
%% INCLUDEPROOF @c@ such that  @ord c >= 0x10000@.
%% INCLUDEPROOF %
%% INCLUDEPROOF The action @writeChar arr i c@ will write to
%% INCLUDEPROOF indices @i@ \emph{and} @i+1@ of @arr@, but
%% INCLUDEPROOF @i+1 = malen arr@ and is not a valid index
%% INCLUDEPROOF for writing!
%% INCLUDEPROOF %
%% INCLUDEPROOF The error lies dormant till the next loop
%% INCLUDEPROOF iteration, when @i = malen arr + 1@ and we
%% INCLUDEPROOF trigger the @j >= top@ branch.
%% INCLUDEPROOF %
%% INCLUDEPROOF Here, we allocate a larger array and copy
%% INCLUDEPROOF the contents of the previous array into the
%% INCLUDEPROOF new array.
%% INCLUDEPROOF %
%% INCLUDEPROOF The @copyM arr' 0 arr 0 top@ call
%% INCLUDEPROOF only copies @top@ elements, \ie it
%% INCLUDEPROOF \emph{does not}
%% INCLUDEPROOF copy the element \emph{at} \texttt{top},
%% INCLUDEPROOF \emph{losing} a @Word16@ and so
%% INCLUDEPROOF yielding the wrong  output.
%% INCLUDEPROOF The fix is to replace...
%% INCLUDEPROOF \begin{code}
%% INCLUDEPROOF    | j >= top  -> do ...
%% INCLUDEPROOF    | otherwise -> do
%% INCLUDEPROOF      d <- writeChar arr i c
%% INCLUDEPROOF      loop z' s' (i+d)
%% INCLUDEPROOF    where (z',c) = f z x
%% INCLUDEPROOF          j | ord c < 0x10000 = i
%% INCLUDEPROOF            | otherwise       = i + 1
%% INCLUDEPROOF \end{code}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End:


text:
package DDS;

public interface RETCODE_NO_DATA
{
    public static final int value = 11;
}


text:
'use strict';

const path = require('path');
const glob = require('glob');

// To make sure that any leftover JavaScript files (e.g. that were outputs from now-removed tests)
// aren't incorrectly included, we glob for the TypeScript files instead and use that
// to instruct Mocha to run the output JavaScript file.
let testFiles = glob.sync(path.join(__dirname, '**/*_test.ts')).map(fileName => fileName.replace(/\.ts$/, '.js'));

// Respect the test file if defined.
// This way you can test one single file instead of running all e2e tests every time.
testFiles = process.env['TEST_FILE'] || testFiles;

// When we are debugging, we don't want to timeout any test. This allows to inspect the state
// of the application at the moment of the timeout. Here, 0 denotes "indefinite timeout".
const timeout = process.env['DEBUG'] ? 0 : 5 * 1000;

module.exports = {
  file: path.join(__dirname, '..', 'conductor', 'mocha_hooks.js'),
  spec: testFiles,
  timeout,
}


text:
from messages import Action

class Bot(object):
    def __init__(self, id, credits, big_blind_amount, small_blind_amount, *args, **kwargs):
        self.id = id
        self.initial_credits = credits
        self.credits = self.initial_credits
        self.big_blind_amount = big_blind_amount
        self.small_blind_amount = small_blind_amount
        self.event_queue = []

    def get_name(self):
        if hasattr(self, 'name'):
            return self.name
        else:
            return self.__class__.__name__

    def log(self, message):
        print '%s(%d): %s' % (self.get_name(), self.id, message)

    def action(self, type, amount=None):
        action = Action(type=type)
        if amount is not None:
            action.amount = amount
        return action

    def turn(self):
        raise NotImplementedError

    def __repr__(self):
        return "<%s player_id=%d>" % (self.get_name(), self.id)


text:
import axios from 'axios';
import CONFIG from './../../server/config';

const URL = `${CONFIG.URL}`;
const LOGIN_URL=`${URL}${CONFIG.PORT}/api/login/`;
const PROFILES_URL = `${URL}${CONFIG.PORT}/api/profiles/`;
const ACTIVITIES_URL = `${URL}${CONFIG.PORT}/api/activities/`;
const TRANSACTIONS_URL = `${URL}${CONFIG.PORT}/api/transactions/`;
const BLOG_URL = `${URL}${CONFIG.PORT}/api/blog/`;

export const LOGGEDIN = 'LOGGEDIN';
export const LOGGEDOUT = 'LOGGEDOUT';
export const FETCH_USER_PROFILES = 'FETCH_USER_PROFILES';
export const CREATE_LOGIN_PROFILE = 'CREATE_LOGIN_PROFILE';
export const UPDATE_LOGIN_PROFILE = 'UPDATE_LOGIN_PROFILE';
export const FETCH_ROSTER = 'FETCH_ROSTER';
export const FETCH_PROFILE = 'FETCH_PROFILE';
export const CREATE_PROFILE = 'CREATE_PROFILE';
export const UPDATE_PROFILE = 'UPDATE_PROFILE';
export const FETCH_TRANSACTIONS = 'FETCH_TRANSACTIONS';
export const FETCH_ALL_TRANSACTIONS = 'FETCH_ALL_TRANSACTIONS';
export const CREATE_TRANSACTION = 'CREATE_TRANSACTION';
export const FETCH_POST = 'FETCH_POST';
export const FETCH_POSTS = 'FETCH_POSTS';
export const CREATE_POST = 'CREATE_POST';
export const FETCH_TAGS = 'FETCH_TAGS';
export const CREATE_TAG = 'CREATE_TAG';
export const DELETE_POST = 'DELETE_POST';
export const CREATE_BLOG_CONTENT = 'CREATE_BLOG_CONTENT';
export const MERGE_BLOG_TAGS = 'MERGE_BLOG_TAGS';
export const CREATE_ACTIVITY = 'CREATE_ACTIVITY';
export const LINK_PARTICIPANTS_TO_ACITIVTY = 'LINK_PARTICIPANTS_TO_ACITIVTY';
export const FETCH_ACTIVITY = 'FETCH_ACTIVITY';
export const FETCH_ATTENDED_ACTIVITIES = 'FETCH__ATTENDED_ACTIVITIES';
export const FETCH_ALL_PARTICIPANTS = 'FETCH_ALL_PARTICIPANTS';

export function loggedIn() {
  return {
    type: LOGGEDIN,
    payload: true
  }
}

export function loggedOut() {
  return {
    type: LOGGEDOUT,
    payload: false
  }
}

export function getUserProfiles() {
  const request = axios.get(LOGIN_URL);
  return {
    type: FETCH_USER_PROFILES,
    payload: request
  }
}

export function createLoginProfile(props) {
  const request = axios.post(LOGIN_URL, props);
  return {
    type: CREATE_LOGIN_PROFILE,
    payload: request
  }
}

export function updateLoginProfile(props) {
  const request = axios.put(LOGIN_URL+props.loginid, props);
  return {
    type: UPDATE_LOGIN_PROFILE,
    payload: request
  }
}

export function fetchRoster() {
   const request = axios.get(PROFILES_URL);
   return {
      type: FETCH_ROSTER,
      payload: request
   };
}

export function fetchProfile(props) {
   const request = axios.get(PROFILES_URL + props);
   return {
      type: FETCH_PROFILE,
      payload: request
   }
}

export function createProfile(props) {
   const request = axios.post(PROFILES_URL, props);
   return {
      type: CREATE_PROFILE,
      payload: request
   }
}

export function updateProfile(props) {
   const request = axios.put(PROFILES_URL+props.id,  props);
   return {
      type: UPDATE_PROFILE,
      payload: request
   }
}

export function deleteProfile(props) {
   const request = axios.delete(PROFILES_URL + props);
   return {
      type: CREATE_PROFILE,
      payload: request
   }
}

export function submitMessage() {
   alert('Message function error. Message not sent.')
   const request = null;
   return {
      type: 'NONE',
      payload: request
   }
}

export function fetchAllTransactions() {
  const request = axios.get(TRANSACTIONS_URL);
  return {
    type: FETCH_ALL_TRANSACTIONS,
    payload: request
  }
}

export function fetchAccountTransactions(props) {
  const request = axios.get(TRANSACTIONS_URL+props);
  return {
    type: FETCH_TRANSACTIONS,
    payload: request
  }
}

export function createTransaction(props) {
  const request = axios.post(TRANSACTIONS_URL, props);
  return {
    type: CREATE_TRANSACTION,
    payload: request
  }
}

export function createPost(props) {
  const request = axios.post(BLOG_URL, props);
  return {
    type: CREATE_POST,
    payload: request
  }
}

export function fetchTags() {
  const request = axios.get(BLOG_URL+'tag')
  return {
    type: FETCH_TAGS,
    payload: request
  }
}

export function createTags(tag) {
  const request = axios.post(BLOG_URL+'tag',tag)
  return {
    type: CREATE_TAG,
    payload: request
  }
}

export function mergeBlogTags(props) {
  const request = axios.post(BLOG_URL+'tagConnection',props);
  return {
    type: MERGE_BLOG_TAGS,
    payload: request
  }
}

export function fetchPosts() {
  const request = axios.get(BLOG_URL);
  return {
    type: FETCH_POSTS,
    payload: request
  }
}

export function fetchPost(id) {
  const request = axios.get(BLOG_URL);
  return {
    type: FETCH_POST,
    payload: request
  }
}

export function deletePost(id) {
  const request = axios.delete('');
  return {
    type: DELETE_POST,
    payload: request
  }
}

export function createActivity(props) {
  const request = axios.post(ACTIVITIES_URL, props);
  return {
    type: CREATE_ACTIVITY,
    payload: request
  }
}

export function linkParticipantstoActivity(props) {
  const actid = props.actid, profileid = props.profileid;
  const request = axios.post(`${ACTIVITIES_URL}${actid}/${profileid}`);
  return {
    type: LINK_PARTICIPANTS_TO_ACITIVTY,
    payload: request
  }
}

export function fetchAllActivities() {
  const request = axios.get(ACTIVITIES_URL);
  return {
    type: FETCH_ACTIVITY,
    payload: request
  }
}

export function fetchAllAttendedActivities() {
  const request = axios.get(ACTIVITIES_URL+'attended');
  return {
    type: FETCH_ATTENDED_ACTIVITIES,
    payload: request
  }
}

export function fetchAllParticipants() {
  const request = axios.get(`${ACTIVITIES_URL}participants`)
  return {
    type: FETCH_ALL_PARTICIPANTS,
    payload: request
  }
}


text:
package com.dennisxu.lib.core.exception;

public class APiErrorMessage {

    public String errorNo;
    public String errorMsg;

}


text:
'''
Copyright 2013 Cosnita Radu Viorel

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

.. codeauthor:: Radu Viorel Cosnita <radu.cosnita@gmail.com>
.. py:module:: fantastico.contrib.roa_discovery.tests.itest_discovery_controller
'''
from fantastico.server.tests.itest_dev_server import DevServerIntegration
from urllib.request import Request
import json
import urllib

class RoaDiscoveryControllerIntegration(DevServerIntegration):
    '''This class provides the integration test cases for resources listing.'''

    SAMPLE_RESOURCE_NAME = "Sample Resource"

    _response = None

    def init(self):
        '''This method automatically set common dependencies for all tests.'''

        self._response = None

    def test_listing_contains_resource(self):
        '''This test case ensures that discovery and listing of resources work as expected.'''

        def request_logic(server):
            request = Request(self._get_server_base_url(server, "/roa/resources"))
            self._response = urllib.request.urlopen(request)

        def assert_logic(server):
            self.assertIsNotNone(self._response)
            self.assertEqual(200, self._response.status)
            self.assertEqual("application/json; charset=UTF-8", self._response.info()["Content-Type"])

            body = self._response.read().decode()

            self.assertIsNotNone(body)

            resources = json.loads(body)

            sample = resources.get(RoaDiscoveryControllerIntegration.SAMPLE_RESOURCE_NAME)

            self.assertIsNotNone(sample)
            self.assertEqual(sample.get("1.0"), "/api/1.0/sample-resources")
            self.assertEqual(sample.get("latest"), "/api/latest/sample-resources")

        self._run_test_against_dev_server(request_logic, assert_logic)


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

    <include
        android:id="@+id/headLayout"
        layout="@layout/common_header_bar" />

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/comment_swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/edit_layout"
        android:layout_below="@+id/headLayout"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/comment_list_rv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/main_bg"
            android:scrollbars="vertical" />
    </android.support.v4.widget.SwipeRefreshLayout>

    <RelativeLayout
        android:id="@+id/edit_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/btn_corner_bg"
        android:padding="1dp"
        android:visibility="visible">

        <EditText
            android:id="@+id/comment_edit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/post_comment_tv"
            android:background="@color/white"
            android:gravity="start|center_vertical"
            android:hint="评论点啥好呢"
            android:padding="10dp"
            android:textColor="@color/select_text"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/post_comment_tv"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/comment_edit"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@drawable/btn_bottom_confirm_bg_selector"
            android:gravity="center"
            android:padding="10dp"
            android:text="发送"
            android:textColor="@color/white"
            android:textSize="18sp" />
    </RelativeLayout>

    <Button
        android:id="@+id/login_btn"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_alignParentBottom="true"
        android:background="@color/btn_orange"
        android:minHeight="0dp"
        android:text="立即登录"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:visibility="gone" />
</RelativeLayout>


text:
/*global $, console, util, addon, self, SETTINGS, acom_analytics */
/*jslint devel: true, browser: true, nomen: true, maxlen: 80 */

$(function () {
    'use strict';

    var doneHandler = function () {
        util.messageToMain(
            {
                main_op: "file_spec_done",
                dest_folder: $(".selected").parent().data("id"),
                filename: $(".filename").val()
            }
        );
    },
        params, param, filename, blobPromise = $.Deferred();

    function selectFolder($folder) {
        $(".selected").removeClass("selected");
        $folder.children(".folder-display").addClass("selected");
    }

    function rootFolderOnly() {
        $(".nofolders-message").removeClass("hidden");
    }

    function renderFolders(request) {
        var $folder = $(".folder").detach(),
            root,
            INDENT = 20,    // px
            $root;

        function renderFolder(name, id, $parent, indent) {
            var $f = $folder
                        .clone()
                        .data("id", id)
                        .css("margin-left", indent + "px")
                        // so our test scripts can find it
                        .addClass("folder-found")
                        .appendTo($parent);

            $f.find(".folder-name").text(name || "root");
            return $f;
        }

        function addFolder(folders, parent, $context, offset) {
            var list = $.grep(
                folders,
                function (f) {
                    return f.parent_id === parent;
                }
            );
            $.each(list, function (index, folder) {
                var $f = renderFolder(folder.name, folder.id, $context, offset);

                addFolder(folders, folder.id, $f, offset + INDENT);
            });
        }
        root = $.grep(
            request.folders,
            function (f) {
                return f.object_type === "root";
            }
        )[0];
        $root = renderFolder(root.name, root.id, $(".folders"), 0);
        addFolder(request.folders, root.id, $root, INDENT);
        selectFolder($root);
        if (request.folders.length === 1) {
            rootFolderOnly();
        }
    }

    function setTitle(title) {
        $(".header-text")
            .text(title)
            .removeClass("hidden");
    }

    function setBusy(busy) {
        if (busy) {
            $(".progress").removeClass("hidden");
        } else {
            $(".progress").addClass("hidden");
        }
    }

    function setError(msg) {
        setBusy(false);
        $("#error")
            .removeClass("hidden")
            .text(msg);

        $(".content, .footer").addClass("hidden");
    }

    function analytics(str) {
        acom_analytics.event(str);
    }

    function handler(msg) {
        util.consoleLog("handler message: ");
        //util.consoleLogDir(msg);
        if (msg.progress_op === "set-text") {
            setTitle(msg.text);
            setBusy(msg.busy);
        }
        if (msg.progress_op === "set-error") {
            setError(msg.text);
        }
        if (msg.progress_op === "folders") {
            renderFolders(msg);
        }

        if (msg.progress_op === "html-blob") {
            util.consoleLog(msg.blob.html.length);
            util.consoleLog("received html blob");
            setBusy(false);
            if (msg.error) {
                setError(msg.error);
                setTitle("Oops!");
                util.consoleLog(msg.error);
                analytics(acom_analytics.e.HTML_SOURCE_SIZE_TOO_LARGE_ERROR);
            } else {
                // uncomment this to see the contents of the html
                setTitle("HTML Ready for Upload and Conversion");
                // Natia:
                // For debugging purposes, we'll keep the logic behind
                // this promise object (the post to the local server)
                // but the main processing will happen from session.js
                blobPromise.resolve(msg.blob);

                //log analytics
                var blobSize = msg.blob.currentSize / 1048576; //convert to MB
                acom_analytics.checkAndLogHTMLBlobSize(blobSize);
            }
        }
    }

    $(".translate").each(function () {
        util.translateElement(this);
    });

    function decodeParam(val) {
        return decodeURIComponent(val.replace(/\+/g, " "));
    }

    if (location.hash.length > 1) {
        params = location.hash.substring(1).split("&");

        $.each(params, function () {
            param = this.split("=");

            if (param[0] === "filename") {
                filename = decodeParam(param[1]);
                $(".fileicon")
                    .removeClass("hidden");
                $(".done").removeClass("hidden");
                $(".filelabel")
                    .text(filename)
                    .removeClass("hidden");
                $(".filename")
                    .val(filename)
                    .removeClass("hidden");

                $(".folders").removeClass("hidden");
                setBusy(false);
            }

            if (param[0] === "message") {
                setTitle(decodeParam(param[1]));
            }

            if (param[0] === "busy") {
                setBusy(param[1] === "true");
            }
            //Use local node server only if USE_ECHO_SERVICE is set to true
            if (SETTINGS.USE_ECHO_SERVICE) {
                if (param[0] === "progress_op" && param[1] === "htmlToPdf") {
                    doneHandler = function () {
                        blobPromise.then(function (data) {
                            // send the blob to our local echoservice
                            $.ajax("http://127.0.0.1:1234/", {
                                type: "POST",
                                data: JSON.stringify(data),
                                contentType: "application/json"
                            }).then(
                                function (data) {
                                    self.close();
                                },
                                function () {
                                    setError(
                                        "To see intermediate results," +
                                            " run the local echo service"
                                    );
                                }
                            );
                        });
                    };
                }
            }
            if (param[0] === "unavailable") {
                setTitle("Oops!");
                if (param[1] === "html_to_pdf") {
                    $("#message")
                        .addClass("error")
                        .text("HTML to PDF not yet available."  +
                              "We know you want it.  " +
                              "We want it too. " +
                              "Please give us a few months to work on it.")
                        .removeClass("hidden");

                    $(".right-content, .progress").addClass("hidden");
                }
                if (param[1] === "flickr") {
                    $("#message")
                        .addClass("error")
                        .text("Flickr apps not yet available.")
                        .removeClass("hidden");
                    $(".right-content, .progress").addClass("hidden");
                }

            }
        });
        window.location.hash = "";
    }

    $(".folders").click(
        function (e) {
            if ($(e.target).is(".folder-display *")) {
                selectFolder($(e.target).parent().parent());
            }
        }
    );

    function done() {
        doneHandler();
    }

    $(".done").click(
        function () {
            var filename = $(".filename").val();
            $(".fileicon")
                .removeClass("hidden");
            $(".filelabel")
                .text(filename)
                .removeClass("hidden");

            $(".done, .right-content").addClass("hidden");
            setBusy(true);
            done();
        }
    );
    util.addMainListener(handler);
});


text:
package com.intellij.refactoring.classMembers;

import com.intellij.psi.NavigatablePsiElement;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Dennis.Ushakov
 */
public abstract class AbstractUsesDependencyMemberInfoModel<T extends NavigatablePsiElement, C extends PsiElement, M extends MemberInfoBase<T>> extends DependencyMemberInfoModel<T, M> {
  protected final C myClass;

  public AbstractUsesDependencyMemberInfoModel(C aClass, @Nullable C superClass, boolean recursive) {
    super(new UsesMemberDependencyGraph<>(aClass, superClass, recursive), ERROR);
    myClass = aClass;
    setTooltipProvider(new MemberInfoTooltipManager.TooltipProvider<T, M>() {
      @Override
      public String getTooltip(M memberInfo) {
        return ((UsesMemberDependencyGraph<T, C, M>) myMemberDependencyGraph).getElementTooltip(memberInfo.getMember());
      }
    });
  }

  @Override
  public int checkForProblems(@NotNull M memberInfo) {
    final int problem = super.checkForProblems(memberInfo);
    return doCheck(memberInfo, problem);
  }

  protected abstract int doCheck(@NotNull M memberInfo, int problem);

  public void setSuperClass(C superClass) {
    setMemberDependencyGraph(new UsesMemberDependencyGraph<>(myClass, superClass, false));
  }

  @Override
  public boolean isCheckedWhenDisabled(M member) {
    return false;
  }

  @Override
  public Boolean isFixedAbstract(M member) {
    return null;
  }
}


text:
using Cofoundry.Domain.Data;

namespace Cofoundry.Domain.Internal;

public class GetUpdateUserCommandByIdQueryHandler
    : IQueryHandler<GetPatchableCommandByIdQuery<UpdateUserCommand>, UpdateUserCommand>
    , ISignedInPermissionCheckHandler
{
    private readonly CofoundryDbContext _dbContext;
    private readonly IPermissionValidationService _permissionValidationService;
    private readonly IUserAreaDefinitionRepository _userAreaDefinitionRepository;

    public GetUpdateUserCommandByIdQueryHandler(
        CofoundryDbContext dbContext,
        IPermissionValidationService permissionValidationService,
        IUserAreaDefinitionRepository userAreaDefinitionRepository
        )
    {
        _dbContext = dbContext;
        _permissionValidationService = permissionValidationService;
        _userAreaDefinitionRepository = userAreaDefinitionRepository;
    }

    public async Task<UpdateUserCommand> ExecuteAsync(GetPatchableCommandByIdQuery<UpdateUserCommand> query, IExecutionContext executionContext)
    {
        var dbUser = await _dbContext
            .Users
            .AsNoTracking()
            .FilterNotDeleted()
            .FilterNotSystemAccount()
            .FilterById(query.Id)
            .SingleOrDefaultAsync();

        if (dbUser == null) return null;

        if (dbUser.UserAreaCode == CofoundryAdminUserArea.Code)
        {
            _permissionValidationService.EnforceCurrentUserOrHasPermission<CofoundryUserReadPermission>(query.Id, executionContext.UserContext);
        }
        else
        {
            _permissionValidationService.EnforceCurrentUserOrHasPermission<NonCofoundryUserReadPermission>(query.Id, executionContext.UserContext);
        }

        var userArea = _userAreaDefinitionRepository.GetByCode(dbUser.UserAreaCode);

        var user = new UpdateUserCommand()
        {
            Email = dbUser.Email,
            FirstName = dbUser.FirstName,
            LastName = dbUser.LastName,
            RequirePasswordChange = dbUser.RequirePasswordChange,
            RoleId = dbUser.RoleId,
            UserId = dbUser.UserId,
            IsAccountVerified = dbUser.AccountVerifiedDate.HasValue,
            IsActive = !dbUser.DeactivatedDate.HasValue
        };

        if (!userArea.UseEmailAsUsername)
        {
            user.Username = dbUser.Username;
        }

        return user;
    }
}


text:
/*
 * Rob Braun <bbraun@synack.net>
 * 23-Apr-2005
 * Copyright (c) 2004 Rob Braun.  All rights reserved.
 */
/*
 * Portions Copyright 2006, Apple Computer, Inc.
 * Christopher Ryan <ryanc@apple.com>
*/

#ifndef _XAR_DARWINATTR_H_
#define _XAR_DARWINATTR_H_
xar_file_t xar_underbar_check(xar_t x, xar_file_t f, const char* file);
int32_t xar_darwinattr_archive(xar_t x, xar_file_t f, const char* file, const char *buffer, size_t len);
int32_t xar_darwinattr_extract(xar_t x, xar_file_t f, const char* file,	char *buffer, size_t len);
#endif /* _XAR_DARWINATTR_H_ */


text:
#ifndef HEADER_DVLINNCOUKEXAKTINPUTS1
#define HEADER_DVLINNCOUKEXAKTINPUTS1

#include <OpenHome/Types.h>
#include <OpenHome/Buffer.h>
#include <OpenHome/Net/Core/DvDevice.h>
#include <OpenHome/Net/Core/DvProvider.h>

namespace OpenHome {
namespace Net {

class DviDevice;
class IDviInvocation;
class PropertyInt;
class PropertyUint;
class PropertyBool;
class PropertyString;
class PropertyBinary;

/**
 * Provider for the linn.co.uk:ExaktInputs:1 UPnP service
 * @ingroup Providers
 */
class DvProviderLinnCoUkExaktInputs1 : public DvProvider
{
public:
    virtual ~DvProviderLinnCoUkExaktInputs1() {}
    /**
     * Set the value of the Associations property
     *
     * Can only be called if EnablePropertyAssociations has previously been called.
     *
     * @return  true if the value has been updated; false if aValue was the same as the previous value
     */
    TBool SetPropertyAssociations(const Brx& aValue);
    /**
     * Get a copy of the value of the Associations property
     *
     * Can only be called if EnablePropertyAssociations has previously been called.
     */
    void GetPropertyAssociations(Brhz& aValue);
protected:
    /**
     * Constructor
     *
     * @param[in] aDevice  Device which owns this provider
     */
    DvProviderLinnCoUkExaktInputs1(DvDevice& aDevice);
    /**
     * Constructor.  Not for external use.
     *
     * @param[in] aDevice  Device which owns this provider
     */
    DvProviderLinnCoUkExaktInputs1(DviDevice& aDevice);
    /**
     * Enable the Associations property.
     */
    void EnablePropertyAssociations();
    /**
     * Signal that the action GetAssociation is supported.
     * The action's availability will be published in the device's service.xml.
     * GetAssociation must be overridden if this is called.
     */
    void EnableActionGetAssociation();
    /**
     * Signal that the action SetAssociation is supported.
     * The action's availability will be published in the device's service.xml.
     * SetAssociation must be overridden if this is called.
     */
    void EnableActionSetAssociation();
    /**
     * Signal that the action ClearAssociation is supported.
     * The action's availability will be published in the device's service.xml.
     * ClearAssociation must be overridden if this is called.
     */
    void EnableActionClearAssociation();
    /**
     * Signal that the action InputCount is supported.
     * The action's availability will be published in the device's service.xml.
     * InputCount must be overridden if this is called.
     */
    void EnableActionInputCount();
private:
    /**
     * GetAssociation action.
     *
     * Will be called when the device stack receives an invocation of the
     * GetAssociation action for the owning device.
     * Must be implemented iff EnableActionGetAssociation was called.
     */
    virtual void GetAssociation(IDvInvocation& aInvocation, TUint aInputIndex, IDvInvocationResponseString& aDeviceId);
    /**
     * SetAssociation action.
     *
     * Will be called when the device stack receives an invocation of the
     * SetAssociation action for the owning device.
     * Must be implemented iff EnableActionSetAssociation was called.
     */
    virtual void SetAssociation(IDvInvocation& aInvocation, TUint aInputIndex, const Brx& aDeviceId);
    /**
     * ClearAssociation action.
     *
     * Will be called when the device stack receives an invocation of the
     * ClearAssociation action for the owning device.
     * Must be implemented iff EnableActionClearAssociation was called.
     */
    virtual void ClearAssociation(IDvInvocation& aInvocation, TUint aInputIndex);
    /**
     * InputCount action.
     *
     * Will be called when the device stack receives an invocation of the
     * InputCount action for the owning device.
     * Must be implemented iff EnableActionInputCount was called.
     */
    virtual void InputCount(IDvInvocation& aInvocation, IDvInvocationResponseUint& aInputCount);
private:
    DvProviderLinnCoUkExaktInputs1();
    void Construct();
    void DoGetAssociation(IDviInvocation& aInvocation);
    void DoSetAssociation(IDviInvocation& aInvocation);
    void DoClearAssociation(IDviInvocation& aInvocation);
    void DoInputCount(IDviInvocation& aInvocation);
private:
    PropertyString* iPropertyAssociations;
};

} // namespace Net
} // namespace OpenHome

#endif // HEADER_DVLINNCOUKEXAKTINPUTS1


text:
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
             xmlns:g='urn:import:com.google.gwt.user.client.ui'>
    <ui:with field="res" type="org.consumersunion.stories.dashboard.client.resource.Resources"/>
    <ui:style>
        .wrapper {
            min-height: 20px;
            height: 100%;
            width: 99%;
            -webkit-border-radius: 4px;
            -moz-border-radius: 4px;
            border-radius: 4px;
        }

        .wrapper:focus {
            outline: none;
        }
    </ui:style>

    <g:FocusPanel ui:field="main" styleName="{style.wrapper}">
        <g:HTMLPanel>
            <g:FlowPanel ui:field="tags" styleName="{res.generalStyleCss.floatLeft}"/>
            <g:SuggestBox ui:field="itemBox" styleName="{res.generalStyleCss.hiddenTextBox}"/>
            <div class="{res.generalStyleCss.clearBoth}"/>
        </g:HTMLPanel>
    </g:FocusPanel>
</ui:UiBinder>


text:
/*
 *	2015/11/22
 *	Tony Guo
 *	R04458006
 *
 *	HW4
 *
 */

#ifndef _COMPRESSION_
#define _COMPRESSION_

#include <iostream>
#include <fstream>
#include <sstream>

#include <algorithm>
#include <string>
#include <vector>
#include <bitset>
#include <map>

#include <cmath>

#include <memory>

enum{
   FULL = 0,
   FAST
};

enum{
   INTRA = 0,
   INTER
};

class Compression
{
   public:
      Compression(std::string path,unsigned int raw_width,unsigned int raw_height,unsigned int block_size = 8):
	 path(path),raw_width(raw_width),raw_height(raw_height),block_size(block_size){}
      void LoadRawImage(std::vector<std::vector<unsigned char> >&);
      void LoadRawVideo(std::vector<std::vector<std::vector<unsigned char> > >&);
      void OneD_Block_DCT(std::vector<std::vector<unsigned char> >&,std::vector<std::vector<double> >&);
      void OneD_Block_IDCT(std::vector<std::vector<double> >&,std::vector<std::vector<unsigned char> >&);
      void Quantization(std::vector<std::vector<double> >&,const int);
      void IQuantization(std::vector<std::vector<double> >&,const int);
      void NextFrame(std::vector<std::vector<std::vector<unsigned char> > >&,std::vector<std::vector<unsigned char> >&,unsigned int);
      void ME(std::vector<std::vector<unsigned char> >&,std::vector<std::vector<unsigned char> >&,int,unsigned int);
      void MC(std::vector<std::vector<unsigned char> >&,std::vector<std::vector<unsigned char> >&);

      void SubImage(std::vector<std::vector<unsigned char> > &src1,std::vector<std::vector<unsigned char> > &src2,std::vector<std::vector<unsigned char> > &dst)
      {
	 for(size_t i = 0;i < src1.size();++i){
	    for(size_t j = 0;j < src1[i].size();++j){
	       dst[i][j] = limit(src1[i][j] - src2[i][j]);
	    }
	 }
      }
      void AddImage(std::vector<std::vector<unsigned char> > &src1,std::vector<std::vector<unsigned char> > src2,std::vector<std::vector<unsigned char> > dst)
      {
	 for(size_t i = 0;i < src1.size();++i){
	    for(size_t j = 0;j < src1[i].size();++j){
	       dst[i][j] = limit(src1[i][j] + src2[i][j]);
	    }
	 }
      }

      inline unsigned int TotalFrame(){return total_frame;}

      inline double PSNRComputing(std::vector<std::vector<unsigned char> > &origin_image,std::vector<std::vector<unsigned char> > &idct)
      {
	 double mse = 0,psnr = 0;

	 for(int i = 0;i < raw_width;i++){
	    for(int j = 0;j < raw_height;j++){
	       mse += (origin_image[i][j] - idct[i][j]) * (origin_image[i][j] - idct[i][j]);
	    }
	 }

	 if(mse != 0){
	    mse /= raw_width * raw_height;
	    psnr = 10 * std::log10((255 * 255) / mse);
	 }
	 else{
	    psnr = 999999;
	 }

	 //std::cout << "PSNR : " << psnr << " dB" << std::endl;
	 return psnr;
      }

      inline double C(double value)
      {
	 return (value == 0)?1.0f/std::sqrt(2.0f):1.0f;
      }

      inline double limit(double value)
      {
	 return (value < 0)?0:(value > 255)?255:value;
      }
   private:
      std::string path;
      unsigned int raw_width,raw_height;
      unsigned int block_size;
      unsigned int total_frame;

      std::vector< std::pair<int,int> > MV;
      /*
      std::vector<std::vector<unsigned char> > origin_image;
      std::vector<std::vector<double> > dct;
      std::vector<std::vector<unsigned char> > idct;

      std::vector<std::vector<std::vector<unsigned char> > > video;
      */
};

#endif


text:
var app = require('express')();
var Filter = require('bad-words')
var emoji = require('node-emoji')
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require("express");
var fs = require('fs');
filter = new Filter();
var port = 25501; // port for server to run on
var motd = "";
var usid = [];
var user_ver = JSON.parse(fs.readFileSync(__dirname + '/data/ids', 'utf8'));
var unam_ver = JSON.parse(fs.readFileSync(__dirname + '/data/uss', 'utf8'));
var itadmin = fs.readFileSync(__dirname + '/data/admin', 'utf8');

app.get('/', function(req, res){
  res.sendFile(__dirname + '/static/index.html');
});
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
    next();
});
var onlinep = 0;
app.use('/external/', express.static(__dirname + "/static/"));
io.on('connection', function(socket){

});

io.on('connection', function(socket){
  socket.on('join', function(msg){
    if (typeof msg == "object") {
      if (msg.length == 2) {
        username = clean(msg[0]);
    if (msg[0] == "") {
      io.emit("post", "<server>SERVER:</server> an unnamed user connected");
      this.emit("note", "<server>SERVER:</server> To change your username, type in /username (username)");
      usid = usid.concat([[socket.id, "", msg[1]]]);
    } else {
      usid = usid.concat([[socket.id, username, msg[1]]]);
      var app;
      if (user_ver.indexOf(msg[1]) != -1) {
        if (unam_ver[user_ver.indexOf(msg[1])] == msg[0]) {
        app = "√ ";
      } else {
        app = "";
      }
      } else {
        app = "";
      }

    io.emit("post", "<server>SERVER: </server>" + app + username + " joined the server");
  }
  motd = "<motd>Welcome to BasicChat version 0.1.0
To view the list of commands, enter /help in the chat box at the bottom of the page
View the source at https://github.com/DatOneLefty/basic-chat
There is currently " + onlinep + " online</motd>";      //set this message to what you want to show users every time they log on
  this.emit("motd", motd);
} else {
  this.emit("note", "<server>ERROR:</server> join array error. you may want to reset your browser cache");

}
} else {
  this.emit("note", "<server>ERROR:</server> join array error. you may want to reset your browser cache");

}
  });
});

function clean(msg) {
  msg = String(msg);
  msg = msg.replace(/>/g, ">")
  msg = msg.replace(/</g, "<")
  msg = msg.replace(/[^A-Za-z 0-9 \.,\?""'!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '');
  msg = msg.substring(0,500);
  msg = filter.clean(msg);
  msg = emoji.emojify(msg);
  return msg;
}

function addFormatting(item) {
  item = item.split(" ");
  var i = 0;
  item.forEach(function(ite) {
    if (ite.startsWith("https://")) {
      item[i] = "" + ite + "";
    }
    if (ite.startsWith("http://")) {
      item[i] = "" + ite + "";
    }
    i++;
  });
  return item.join(" ");
}

io.on('connection', function(socket){
  socket.on('message', function(msg){
        if (typeof msg == "object") {
          if (msg.length == 3) {
            if (msg[1] != "") {
            if (user_ver.indexOf(msg[2]) != -1) {
              if (unam_ver[user_ver.indexOf(msg[2])] == msg[0]) {
              app = "√ ";
            } else {
              app = "";
            }
            } else {
              app = "";
            }

            msg[0] = clean(msg[0]);
              if (msg[2] == itadmin.replace(/\n|\r/g, "")) {

              msg[0] = "" + msg[0] + "";
            }

            if (msg[2] == "BasicBot") {
              msg[0] = "" + msg[0] + "";
            }
            msg = "" + app  + msg[0] + ": " + addFormatting(clean(msg[1]));
            io.emit("post", msg);
          } else {
            this.emit("note", "<server>SERVER:</server> you cannot send empty messages");

          }
  } else {
    this.emit("note", "<server>SERVER:</server> message not sent properly, clear browser cache?");
  }

} else {
  this.emit("note", "<server>SERVER:</server> message is not array, clear browser cache?");
}
  });
});

http.listen(port, function(){
  console.log('Server started. listening on port ' + port);
});

io.on('connect', function () {
onlinep++;
});

io.on('connection', function(socket){
  socket.on('disconnect', function () {
onlinep--;

  usid.forEach(function(ite) {
    if (ite[0] == socket.id) {
      if (user_ver.indexOf(ite[2]) != -1) {
        if (unam_ver[user_ver.indexOf(ite[2])] == ite[1]) {
        app = "√ ";
      } else {
        app = "";
      }
      } else {
        app = "";
      }

      io.emit("post", "<server>SERVER: </server>" + app + ite[1] + " left the server");

    }
  });
  });

  socket.on('change-username', function(msg){
    if (typeof msg == "string") {
      msg = msg + " ";
    msg = msg.split(" ");
    if (msg[1].length > 4 && msg[1].length < 15) {
        msg = [clean(msg[0]),clean(msg[1])];
    console.log("COMMAND: user " + msg[0] + " changed their username to " + msg[1]);
    io.emit("post", "<server>SERVER:</server> user " + msg[0] + " changed their username to " + msg[1]);
  } else {
    this.emit("note", "<server>SERVER:</server> your username has to be > 4 and < 15 characters");

  }
} else {
  this.emit("note", "<server>SERVER:</server> trying to crash my server...hmmmm?");

}
  });
});

io.on('connection', function(socket){
  socket.on('afk-on', function(msg){
        username = clean(msg[0]);
        if (username == "") {
          console.log("COMMAND: afk enabled for an unnamed user");
          io.emit("post", "<server>AFK: </server>an unnamed user is afk");
        } else {

          if (typeof msg == "object") {
            if (msg.length == 2) {
              if (user_ver.indexOf(msg[1]) != -1) {
                if (unam_ver[user_ver.indexOf(msg[1])] == msg[0]) {
                app = "√ ";
              } else {
                app = "";
              }
              } else {
                app = "";
              }
              if (msg[1] == itadmin.replace(/\n|\r/g, "")) {
                username = "" + username + "";
              }
              console.log("COMMAND: afk enabled for " + msg);
              io.emit("post", "<server>AFK: </server>" + app + username + " is afk");
          } else {
          this.emit("note", "<server>SERVER:</server> verification array issue, clear browser cache?");
          }

          } else {
          this.emit("note", "<server>SERVER:</server> verification array issue, clear browser cache?");
          }

  }
  });
});
io.on('connection', function(socket){
  socket.on('afk-off', function(msg){
        username = clean(msg[0]);
                if (username == "") {
                  console.log("COMMAND: afk disabled for an unnamed user");
                  io.emit("post", "<server>AFK: </server>an unnamed user is now not afk");
                } else {

                  if (typeof msg == "object") {
                    if (msg.length == 2) {
                      if (user_ver.indexOf(msg[1]) != -1) {
                        if (unam_ver[user_ver.indexOf(msg[1])] == msg[0]) {
                        app = "√ ";
                      } else {
                        app = "";
                      }
                      } else {
                        app = "";
                      }

                      if (msg[1] == itadmin.replace(/\n|\r/g, "")) {
                        username = "" + username + "";
                      }
                      console.log("COMMAND: afk disabled for " + username);
                      io.emit("post", "<server>AFK: </server>" + app + username + " is now not afk");
                  } else {
                  this.emit("note", "<server>SERVER:</server> verification array issue, clear browser cache?");
                  }

                  } else {
                  this.emit("note", "<server>SERVER:</server> verification array issue, clear browser cache?");
                  }

  }
  });
});

io.on('connection', function(socket){
  socket.on('get-logged-in', function(msg){
        this.emit("current", onlinep);
  });
});

io.on('connection', function(socket){
  socket.on('ping-send', function(msg){
    console.log("COMMAND: ping");
    this.emit("ping-return", "");
  });
});

io.on('connection', function(socket){
  socket.on('adm-command', function(msg){
    if (typeof msg == "object") {
      if (msg.length == 2) {
        if (msg[0] != itadmin.replace(/\n|\r/g, "")) {
          this.emit("note", "<server>SERVER:</server> authentication denied");

        } else {
          command = msg[1];
          console.log("SERVER RUN: " + msg);
          if (command[1] == "reload") {
            user_ver = JSON.parse(fs.readFileSync(__dirname + '/data/ids', 'utf8'));
            unam_ver = JSON.parse(fs.readFileSync(__dirname + '/data/uss', 'utf8'));
            itadmin = fs.readFileSync(__dirname + '/data/admin', 'utf8');
            this.emit("note", "<server>SERVER:</server> reloaded verification settings");
          }
          else if (command[1] == "verify") {
            var vid = command[2];
            var uid = command[3];
            user_ver = user_ver.concat(vid);
            unam_ver = unam_ver.concat(uid);
            fs.writeFile(__dirname + "/data/ids", JSON.stringify(user_ver));
            fs.writeFile(__dirname + "/data/uss", JSON.stringify(unam_ver));
            this.emit("note", "<server>SERVER:</server> verified user " + uid + " with the id of " + vid);

          } else if (command[1] == "help") {
            this.emit("note", "<server>SERVER:</server> HELP:
reload: reload verification
verify [id] [name]: add verified user");

          } else {
            this.emit("note", "<server>SERVER:</server> unknown command");
          }
        }
      } else {
        this.emit("note", "<server>SERVER:</server> verification array issue, clear browser cache?");

      }
    } else {
      this.emit("note", "<server>SERVER:</server> verification array issue, clear browser cache?");

    }
  });
});

setInterval(function() {
  io.emit("online");
}, 5000);


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2012 FuseSource
  ~
  ~ 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.
  -->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:ctx="http://www.springframework.org/schema/context"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:osgix="http://www.springframework.org/schema/osgi-compendium"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd
        http://www.springframework.org/schema/osgi-compendium http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium.xsd">

    <osgix:cm-properties id="osgi.properties" persistent-id="com.fusesource.examples.horoweb">
        <prop key="server">localhost</prop>
    </osgix:cm-properties>

    <ctx:property-placeholder properties-ref="osgi.properties"/>

    <osgi:reference id="sqlSessionFactory" interface="org.apache.ibatis.session.SqlSessionFactory"
                    filter="(database=horo-app)"/>
    <osgi:reference id="horoscopeDAO" interface="com.fusesource.examples.horo.db.HoroscopeDAO" />

</beans>


text:
class Garbage::Agents::Tasks::Node::CategoriesController < ApplicationController
  include Cms::PublicFilter::Node

  def generate
    generate_node_with_pagination @node
  end

  def import
    importer = Garbage::Node::CategoryImporter.new(@site, @node, @user)
    importer.import(@file, task: @task)
    @file.destroy
    head :ok
  end
end


text:
            <select class="" data-dojo-type="dijit/form/Select" style="width:100%;table-layout:fixed;" data-dojo-attach-event="onChange:_handleFirstOperandChange" data-dojo-attach-point="_firstOperandSelect">
            </select>

            <select class="" data-dojo-type="dijit/form/Select" data-dojo-attach-event="onChange:_handleOperatorChange" style="width:100%;table-layout:fixed;" data-dojo-attach-point="_operatorSelect">
              <option value="where">${i18n.where}</option>
              <option value="intersects">${i18n.intersects}</option>
              <option value="notIntersects">${i18n.notIntersects}</option>
              <option value="withinDistance">${i18n.withinDistance}</option>
              <option value="notWithinDistance">${i18n.notWithinDistance}</option>
              <option value="contains">${i18n.contains}</option>
              <option value="notContains">${i18n.notContains}</option>
              <option value="within">${i18n.within}</option>
              <option value="notWithin">${i18n.notWithin}</option>

            </select>

              <input type="text" data-dojo-type="dijit/form/NumberTextBox" data-dojo-attach-event="onChange:_handleDistanceInputChange" data-dojo-props="intermediateChanges:true" data-dojo-attach-point="_distanceInput" style="width:20%;"></input>
              <select data-dojo-type="dijit/form/Select"  data-dojo-attach-point="_distanceUnitsSelect"  style="width:20%;table-layout:fixed;">
                <option value="Miles">${i18n.miles}</option>
                <option value="Yards">${i18n.yards}</option>
                <option value="Feet">${i18n.feet}</option>
                <option type="separator"></option>
                <option value="Kilometers">${i18n.kilometers}</option>
                <option value="Meters">${i18n.meters}</option>
                <option value="NauticalMiles">${i18n.nautMiles}</option>
              </select>
               ${i18n.from}

            <select class="" data-dojo-type="dijit/form/Select" style="width:75%;table-layout:fixed;" data-dojo-attach-point="_secondOperandSelect" data-dojo-attach-event="onChange:_handleSecondOperandChange">
            </select>

        ${i18n.add}

        ${i18n.close}


text:
"""Helper module for easier pyVmomi use.

Yes, these are my first bigger Python scripts and this is my first foolish
and very amateur try of a Python module. Maybe, one day, it will be a real
module and make everything right.
"""

from pyVim import connect
from pyVmomi import vim
import time
import sys
import ssl       # imported to define SSL context (see below)
import requests  # imported to disable SSL warning

# returns everything we need to work with vCenter
def vcenter_connect(host, username, password):
    """Connect to vCenter and return all variables needed."""
    # No warnign for self signed SSL certificates
    requests.packages.urllib3.disable_warnings()
    # Disabling SSL certificate verification
    # Fix for python 2.7.10+ and vSphere 6. For details see:
    # https://github.com/mistio/mist.io/issues/691
    # https://github.com/vmware/pyvmomi/issues/212
    # Disabling SSL certificate verification
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    context.verify_mode = ssl.CERT_NONE
    instance = connect.SmartConnect(
        host=host,
        user=username,
        pwd=password,
        sslContext=context
    )
    # Getting instance content
    content = instance.RetrieveContent()
    datacenters = content.rootFolder.childEntity
    datacenter = datacenters[0]
    vm_folder = datacenter.vmFolder

    return instance, content, datacenters, datacenter, vm_folder

# create folder
def create_folder(content, vm_folder, foldername):
    """Create folder in VM view."""
    if (get_obj(content, 'folder', foldername)) is None:
        vm_folder.CreateFolder(foldername)
        print "Folder '%s' created" % (foldername)
    else:
        print "Folder with name '%s' already exists" % (foldername)

def get_obj(content, type, name):
    """Get object from vCenter server inventory."""
    vimtype = None
    if type == 'datacenter':
        vimtype = [vim.Datacenter]
    elif type == 'cluster':
        vimtype = [vim.ClusterComputeResource]
    elif type == 'respool':
        vimtype = [vim.ResourcePool]
    elif type == 'folder':
        vimtype = [vim.Folder]
    elif type == 'vm':
        vimtype = [vim.VirtualMachine]
    elif type == 'template':
        vimtype = [vim.VirtualMachine]
    elif type == 'datastore':
        vimtype = [vim.Datastore]
    elif type == 'dstorecluster':
        vimtype = [vim.StoragePod]
    elif type == 'network':
        vimtype = [vim.Network]
    elif type == 'dvsportgroup':
        vimtype = [vim.dvs.DistributedVirtualPortgroup]

    obj = None
    container = content.viewManager.CreateContainerView(
        content.rootFolder,
        vimtype,
        True
    )
    container_object_list = container.view
    # destroying the container to free up resources on the vCenter
    container.Destroy()
    for container_object in container_object_list:
        if container_object.name == name:
            obj = container_object
            break

    return obj

def get_dvsportgroup_by_key(content, key):
    """Get DVS port group by key from vCenter inventory."""
    vimtype = [vim.dvs.DistributedVirtualPortgroup]
    dvsportgroup = None
    container = content.viewManager.CreateContainerView(
        content.rootFolder,
        vimtype,
        True
    )
    obj_list = container.view
    # destroying the container to free up resources on the vCenter
    container.Destroy()
    for obj in obj_list:
        if obj.key == key:
            dvsportgroup = obj
            break
    return dvsportgroup

def get_dvsportgroup_by_name(content, name):
    """Get DVS port group by name from vCenter inventory."""
    vimtype = [vim.dvs.DistributedVirtualPortgroup]
    dvsportgroup = None
    container = content.viewManager.CreateContainerView(
        content.rootFolder,
        vimtype,
        True
    )
    obj_list = container.view
    # destroying the container to free up resources on the vCenter
    container.Destroy()
    for obj in obj_list:
        if obj.name == name:
            dvsportgroup = obj
            break
    return dvsportgroup

def print_vm_info(vm):
    """Print some VM info (including snapshots)."""
    summary = vm.summary
#   config = vm.config
    print 'VM name        :', summary.config.name
    print 'Guest OS       :', summary.config.guestFullName
    print 'Hostname       :', summary.guest.hostName
    print 'UUID           :', summary.config.uuid
    print 'Folder         :', vm.parent.name
    print 'State          :', summary.runtime.powerState
    print 'Tools status   :', summary.guest.toolsRunningStatus
    print 'IP address     :', summary.guest.ipAddress
    print 'vCPU           :', summary.config.numCpu
    print 'vRAM (MB)      :', summary.config.memorySizeMB
    print 'Ethernet cards :', summary.config.numEthernetCards
    print 'vDisks         :', summary.config.numVirtualDisks
    print 'VM path        :', summary.config.vmPathName

    # If the object has a currentSnapshot, we want to decend the hierarchy down
    # max 3 levels (root snapshot + 2 additional snapshots). If there is more,
    # the user needs to take a look with the vSphere client
    snapshot = vm.snapshot
    if hasattr(snapshot, 'currentSnapshot'):
        sys.stdout.write('Snapshots      : ')
        # Getting info about the root snapshot and displaying it
        root_snapshot = snapshot.rootSnapshotList[0]
        root_snapshot_name = root_snapshot.name
        root_snapshot_date = root_snapshot.createTime
        print "%s: %s" % (root_snapshot_date, root_snapshot_name)
        # If the root snapshot has children, lets see its ugly faces
        if (root_snapshot.childSnapshotList):
            for first_snapshot in root_snapshot.childSnapshotList:
                print "                 %s: %s" % (
                    first_snapshot.createTime,
                    first_snapshot.name
                )
                # Let's see if the first snapshots has any child objects
                if (first_snapshot.childSnapshotList):
                    for second_snapshot in first_snapshot.childSnapshotList:
                        print "                 %s: %s" % (
                            second_snapshot.createTime,
                            second_snapshot.name
                        )
                        # To see more snapshots, use the vSphere Client
                        if (second_snapshot.childSnapshotList):
                            print '                 WARNING:' \
                                ' This VM has more than 3 snapshots'
    # VM has no snapshots :(
    else:
        print 'Snapshots      : No'
    # We need some distance (divider)
    print ""

def print_csv_vm_info(vm, content):
    """Detailed VM information in CSV format."""
    vm_name = vm.summary.config.name
    guest_os = vm.summary.config.guestFullName
    hostname = vm.summary.guest.hostName
    uuid = vm.summary.config.uuid
    folder = vm.parent.name
    state = vm.summary.runtime.powerState
    tools_state = vm.summary.guest.toolsRunningStatus
    ip_address = vm.summary.guest.ipAddress
    vcpu = vm.summary.config.numCpu
    vram = vm.summary.config.memorySizeMB
    vnics = vm.summary.config.numEthernetCards
    vdisks = vm.summary.config.numVirtualDisks
    vmpath = vm.summary.config.vmPathName
    slot = 1
    maxslots = 4
    networks = []
    """
    The function prints the data in the following order:
    VM ID,VM name,VM UUID,State,IP address,Hostname,GuestOS,vCPU,vRAM,
    no. of vDisks, no. of vNICs,Network 1,Network 2,Network 3,Network 4,
    VMware Tools, Folder,VM path
    """
    for device in vm.config.hardware.device:
        # If the device is our network device
        if isinstance(device, vim.vm.device.VirtualEthernetCard):
            # We only print out a max of 4 networks
            if slot > maxslots:
                return
            try:
                old_network_pgkey = device.backing.port.portgroupKey
                dvsportgrp = get_dvsportgroup_by_key(content,
                                                     old_network_pgkey
                                                     )
                networks.append(dvsportgrp.name)
            except:
                vswitch_name = device.backing.deviceName
                networks.append(vswitch_name)
            slot + 1

    open_slots = maxslots - len(networks)
    while open_slots > 0:
        networks.append('n/a')
        open_slots -= 1

    network1 = networks[0]
    network2 = networks[1]
    network3 = networks[2]
    network4 = networks[3]

    print "%s,%s,%s,%s,%s,%s,%s,%s,%s,\
        %s,%s,%s,%s,%s,%s,%s,%s,%s" % (vm,
                                       vm_name,
                                       uuid,
                                       state,
                                       ip_address,
                                       hostname,
                                       guest_os,
                                       vcpu,
                                       vram,
                                       vdisks,
                                       vnics,
                                       network1,
                                       network2,
                                       network3,
                                       network4,
                                       tools_state,
                                       folder,
                                       vmpath
                                       )

def vm_info(data_item, type, content, depth=1):
    """We just descend recursively until we reached max depth of 20."""
    maxdepth = 25
    if depth > maxdepth:
        return
    # If the object is a virtual machine, we want to display it's information
    if isinstance(data_item, vim.VirtualMachine):
        if type == 'csv':
            print_csv_vm_info(data_item, content)
        elif type == 'text':
            print_vm_info(data_item)
        else:
            print 'Wrong type, neither text nor csv'
            return
    # If the object has child entities, we follow down the rabbit hole until we
    # reach maxdepth and identify every object on our way
    if hasattr(data_item, 'childEntity'):
        data_item_list = data_item.childEntity
        for item in data_item_list:
            vm_info(item, type, content, depth + 1)
        return

def list_vms_with_snapshots(item):
    """Look through all objects and identify Virtual Machines."""
    if isinstance(item, vim.VirtualMachine):
        if check_for_snapshots(item):
            print_vm_info(item)

    if hasattr(item, 'childEntity'):
        item_list = item.childEntity
        for subitem in item_list:
            list_vms_with_snapshots(subitem)

def check_if_template(object):
    """Check if object is a VM template."""
    if object.config.template is True:
        return True
    else:
        return False

def check_for_snapshots(virtual_machine):
    """Check if the Virtual Machine has any snapshots."""
    snapshot = virtual_machine.snapshot
    if hasattr(snapshot, 'currentSnapshot'):
        return True

def check_on_task(task):
    """Check on a task sent to vCenter."""
    progress = ['|', '/', '-', '\\']
    sys.stdout.write('Progress:  ')
    sys.stdout.flush()
    while task.info.state == vim.TaskInfo.State.running:
        for i in progress:
            sys.stdout.write("\b%s" % i)
            sys.stdout.flush()
            time.sleep(0.2)

    if task.info.state == vim.TaskInfo.State.success:
        print "\bDone"
        print 'Task successfully completed'
    else:
        print 'Task failed! Check VMware logs:'
        print task.info.error

def clone_vm(template, target, folder, datastore, respool):
    """Clone a Virtual Machine."""
    print 'Preparing relocating specification...'
    relspec = vim.vm.RelocateSpec()
    relspec.datastore = datastore
    relspec.pool = respool
    print 'Preparing cloning specification...'
    clonespec = vim.vm.CloneSpec(
        powerOn=False,
        template=False,
        location=relspec
    )
    print "Starting cloning process for new VM '%s'..." % target
    task = template.Clone(
        name=target,
        folder=folder,
        spec=clonespec
    )
    check_on_task(task)

# def vm_change_host(vm, target_host, respool):
# def vm_change_dstore(vm, target_dstore, respool):

def vcenter_disconnect(service_instance):
    """Disconnect from vCenter after our work is done."""
    connect.Disconnect(service_instance)

# Start program
if __name__ == "__main__":
    print "This is a module and cannot directly be used"
    sys.exit(0)


text:
/*************************************************************************/
/*  audio_listener_3d.cpp                                                */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "audio_listener_3d.h"

#include "scene/main/viewport.h"

void AudioListener3D::_update_audio_listener_state() {
}

void AudioListener3D::_request_listener_update() {
	_update_listener();
}

bool AudioListener3D::_set(const StringName &p_name, const Variant &p_value) {
	if (p_name == "current") {
		if (p_value.operator bool()) {
			make_current();
		} else {
			clear_current();
		}
	} else {
		return false;
	}

	return true;
}

bool AudioListener3D::_get(const StringName &p_name, Variant &r_ret) const {
	if (p_name == "current") {
		if (is_inside_tree() && get_tree()->is_node_being_edited(this)) {
			r_ret = current;
		} else {
			r_ret = is_current();
		}
	} else {
		return false;
	}

	return true;
}

void AudioListener3D::_get_property_list(List<PropertyInfo> *p_list) const {
	p_list->push_back(PropertyInfo(Variant::BOOL, "current"));
}

void AudioListener3D::_update_listener() {
	if (is_inside_tree() && is_current()) {
		get_viewport()->_listener_transform_3d_changed_notify();
	}
}

void AudioListener3D::_notification(int p_what) {
	switch (p_what) {
		case NOTIFICATION_ENTER_WORLD: {
			bool first_listener = get_viewport()->_audio_listener_3d_add(this);
			if (!get_tree()->is_node_being_edited(this) && (current || first_listener)) {
				make_current();
			}
		} break;
		case NOTIFICATION_TRANSFORM_CHANGED: {
			_request_listener_update();
		} break;
		case NOTIFICATION_EXIT_WORLD: {
			if (!get_tree()->is_node_being_edited(this)) {
				if (is_current()) {
					clear_current();
					current = true; //keep it true

				} else {
					current = false;
				}
			}

			get_viewport()->_audio_listener_3d_remove(this);

		} break;
	}
}

Transform3D AudioListener3D::get_listener_transform() const {
	return get_global_transform().orthonormalized();
}

void AudioListener3D::make_current() {
	current = true;

	if (!is_inside_tree()) {
		return;
	}

	get_viewport()->_audio_listener_3d_set(this);
}

void AudioListener3D::clear_current() {
	current = false;
	if (!is_inside_tree()) {
		return;
	}

	if (get_viewport()->get_audio_listener_3d() == this) {
		get_viewport()->_audio_listener_3d_set(nullptr);
		get_viewport()->_audio_listener_3d_make_next_current(this);
	}
}

bool AudioListener3D::is_current() const {
	if (is_inside_tree() && !get_tree()->is_node_being_edited(this)) {
		return get_viewport()->get_audio_listener_3d() == this;
	} else {
		return current;
	}

	return false;
}

void AudioListener3D::_bind_methods() {
	ClassDB::bind_method(D_METHOD("make_current"), &AudioListener3D::make_current);
	ClassDB::bind_method(D_METHOD("clear_current"), &AudioListener3D::clear_current);
	ClassDB::bind_method(D_METHOD("is_current"), &AudioListener3D::is_current);
	ClassDB::bind_method(D_METHOD("get_listener_transform"), &AudioListener3D::get_listener_transform);
}

AudioListener3D::AudioListener3D() {
	set_notify_transform(true);
}

AudioListener3D::~AudioListener3D() {
}


text:
class Api::CsrfController < ApplicationController
  def index
    render json: { request_forgery_protection_token => form_authenticity_token}
    .to_json
  end
end