code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
namespace Override\ScrumBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Override\FosUserBundle\Entity\User;
use Override\ScrumBundle\Form\UserType as UserType;
use Override\ScrumBundle\Entity\SecretaireFormation;
use Override\ScrumBundle\Entity\Professeur;
use Override\ScrumBundle\Entity\Etudiant;
/**
* User controller.
*
* @Route("/user")
*/
class UserController extends Controller
{
/**
* Lists all User entities.
*
* @Secure({"ROLE_ADMIN", "ROLE_SECRETARY"})
* @Route("/", name="user")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('OverrideFosUserBundle:User')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Displays a form to edit an existing User entity.
*
* @Secure(roles="ROLE_ADMIN")
* @Route("/{id}/edit", name="user_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('OverrideFosUserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a User entity.
*
* @param User $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(User $entity)
{
$form = $this->createForm(new UserType(), $entity, array(
'action' => $this->generateUrl('user_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing User entity.
*
* @Secure(roles="ROLE_ADMIN")
* @Route("/{id}", name="user_update")
* @Method("PUT")
* @Template("OverrideScrumBundle:User:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
/** Retrieve the user **/
$user = $em->getRepository('OverrideFosUserBundle:User')->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find User entity.');
}
/** Set edit and delete form **/
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($user);
$editForm->handleRequest($request);
/** Form is valid we can insert the user **/
if ($editForm->isValid()) {
/** Remove user from all table where he can exist**/
$issetSecretaire = $em->getRepository('OverrideScrumBundle:SecretaireFormation')->findOneBy(array('user' => $user->getId()));
if($issetSecretaire) {
$em->remove($issetSecretaire);
}
$issetProfesseur = $em->getRepository('OverrideScrumBundle:Professeur')->findOneBy(array('user' => $user->getId()));
if($issetProfesseur) {
$em->remove($issetProfesseur);
}
$issetEtudiant = $em->getRepository('OverrideScrumBundle:Etudiant')->findOneBy(array('user' => $user->getId()));
if($issetEtudiant) {
$em->remove($issetEtudiant);
}
// Flushes remove from enity
$em->flush();
// Set the user role and persist
$user->setRoles(array($editForm->get('roles')->getData()));
$em->persist($user);
/** Insert in database (depends of user role) **/
switch ($editForm->get('roles')->getData()) {
case 'ROLE_ADMIN':
$user->setRoles(array('ROLE_ADMIN'));
break;
case 'ROLE_SECRETARY':
$secretaire = new SecretaireFormation();
$secretaire->setUser($user);
$em->persist($secretaire);
break;
case 'ROLE_PROFESSOR':
$professeur = new Professeur();
$professeur->setUser($user);
$em->persist($professeur);
break;
case 'ROLE_STUDENT':
// If the diplome is null redirect the user
if($editForm->get('dernierDiplome')->getData() == NULL) {
$this->get('session')->getFlashBag()->add(
"danger",
"Le diplôme doit être rempli pour l'étudiant."
);
return $this->redirect($this->generateUrl('user_edit', array('id' => $user->getId())));
}
$etudiant = new Etudiant();
$etudiant->setUser($user);
$etudiant->setDernierDiplome($editForm->get('dernierDiplome')->getData());
$em->persist($etudiant);
break;
default:
return $this->redirect($this->generateUrl('user_edit', array('id' => $user->getId())));
break;
}
// Flush in the database
$em->flush();
// Redirect to the user list
return $this->redirect($this->generateUrl('user'));
}
// Redirect to the form when form not valid
return array(
'entity' => $user,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a User entity.
*
* @Secure(roles="ROLE_ADMIN")
* @Route("/{id}", name="user_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('OverrideFosUserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('user'));
}
/**
* Creates a form to delete a User entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('user_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
} | debflav/scrum | src/Override/ScrumBundle/Controller/UserController.php | PHP | mit | 7,518 |
dojo.provide("plugins.core.Agua.File");
/* SUMMARY: THIS CLASS IS INHERITED BY Agua.js AND CONTAINS FILE CACHE
AND FILE MANIPULATION METHODS
*/
dojo.declare( "plugins.core.Agua.File", [ ], {
/////}}}
// FILECACHE METHODS
getFoldersUrl : function () {
return Agua.cgiUrl + "agua.cgi?";
},
setFileCaches : function (url) {
console.log("Agua.File.setFileCache url: " + url);
var callback = dojo.hitch(this, function (data) {
//console.log("Agua.File.setFileCache BEFORE setData, data: ");
//console.dir({data:data});
this.setData("filecaches", data);
});
//console.log("Agua.File.setFileCache Doing this.fetchJson(url, callback)");
this.fetchJson(url, callback);
},
fetchJson : function (url, callback) {
console.log("Agua.File.fetchJson url: " + url);
var thisObject = this;
dojo.xhrGet({
url: url,
sync: false,
handleAs: "json",
handle: function(data) {
//console.log("Agua.File.fetchJson data: ");
//console.dir({data:data});
callback(data);
},
error: function(response) {
console.log("Agua.File.fetchJson Error with JSON Post, response: " + response);
}
});
},
getFileCache : function (username, location) {
console.log("Agua.File.getFileCache username: " + username);
console.log("Agua.File.getFileCache location: " + location);
var fileCaches = this.cloneData("filecaches");
console.log("Agua.File.getFileCache fileCaches: ");
console.dir({fileCaches:fileCaches});
// RETURN IF NO ENTRIES FOR USER
if ( ! fileCaches[username] ) return null;
return fileCaches[username][location];
},
setFileCache : function (username, location, item) {
console.log("Agua.File.setFileCache username: " + username);
console.log("Agua.File.setFileCache location: " + location);
console.log("Agua.File.setFileCache item: ");
console.dir({item:item});
var fileCaches = this.getData("filecaches");
console.log("Agua.File.setFileCache fileCaches: ");
console.dir({fileCaches:fileCaches});
if ( ! fileCaches ) fileCaches = {};
if ( ! fileCaches[username] ) fileCaches[username] = {};
fileCaches[username][location] = item;
var parentDir = this.getParentDir(location);
console.log("Agua.File.setFileCache parentDir: " + parentDir);
if ( ! parentDir ) {
console.log("Agua.File.setFileCache SETTING fileCaches[" + username + "][" + location + "] = item");
fileCaches[username][location] = item;
return;
}
var parent = fileCaches[username][parentDir];
console.log("Agua.File.setFileCache parent: " + parent);
if ( ! parent ) return;
console.log("Agua.File.setFileCache parent: " + parent);
this.addItemToParent(parent, item);
console.log("Agua.File.setFileCache parent: " + parent);
console.dir({parent:parent});
},
addItemToParent : function (parent, item) {
parent.items.push(item);
},
getFileSystem : function (putData, callback, request) {
console.log("Agua.File.getFileSystem caller: " + this.getFileSystem.caller.nom);
console.log("Agua.File.getFileSystem putData:");
console.dir({putData:putData});
console.log("Agua.File.getFileSystem callback: " + callback);
console.dir({callback:callback});
console.log("Agua.File.getFileSystem request:");
console.dir({request:request});
// SET DEFAULT ARGS EMPTY ARRAY
if ( ! request )
request = new Array;
// SET LOCATION
var location = '';
if ( putData.location || putData.query )
location = putData.query || putData.location;
console.log("Agua.File.getFileSystem location: " + location);
var username = putData.username;
console.log("Agua.File.getFileSystem username: " + username);
// USE IF CACHED
var fileCache = this.getFileCache(username, location);
console.log("Agua.File.getFileSystem fileCache:");
console.dir({fileCache:fileCache});
if ( fileCache ) {
console.log("Agua.File.getFileSystem fileCache IS DEFINED. Doing setTimeout callback(fileCache, request)");
// DELAY TO AVOID node is undefined ERROR
setTimeout( function() {
callback(fileCache, request);
},
10,
this);
return;
}
else {
console.log("Agua.File.getFileSystem fileCache NOT DEFINED. Doing remote query");
this.queryFileSystem(putData, callback, request);
}
},
queryFileSystem : function (putData, callback, request) {
console.log("Agua.File.queryFileSystem putData:");
console.dir({putData:putData});
console.log("Agua.File.queryFileSystem callback:");
console.dir({callback:callback});
console.log("Agua.File.queryFileSystem request:");
console.dir({request:request});
// SET LOCATION
var location = '';
if ( putData.location || putData.query )
location = putData.query;
if ( ! putData.path && location ) putData.path = location;
console.log("Agua.File.queryFileSystem location: " + location);
// SET USERNAME
var username = putData.username;
var url = this.cgiUrl + "agua.cgi";
// QUERY REMOTE
var thisObject = this;
var putArgs = {
url : url,
//url : putData.url,
contentType : "text",
sync : false,
preventCache: true,
handleAs : "json-comment-optional",
putData : dojo.toJson(putData),
handle : function(response) {
console.log("Agua.File.queryFileSystem handle response:");
console.dir({response:response});
console.log("Agua.File.queryFileSystem BEFORE this.setFileCache()");
thisObject.setFileCache(username, location, dojo.clone(response));
console.log("Agua.File.queryFileSystem AFTER this.setFileCache()");
//callback(response, request);
}
};
var deferred = dojo.xhrPut(putArgs);
deferred.addCallback(callback);
var scope = request.scope || dojo.global;
deferred.addErrback(function(error){
if(request.onError){
request.onError.call(scope, error, request);
}
});
},
removeFileTree : function (username, location) {
console.log("Agua.File.removeFileTree username: " + username);
console.log("Agua.File.removeFileTree location: " + location);
var fileCaches = this.getData("filecaches");
console.log("Agua.File.removeFileTree fileCaches: ");
console.dir({fileCaches:fileCaches});
if ( ! fileCaches ) {
console.log("Agua.File.removeFileTree fileCaches is null. Returning");
return;
}
var rootTree = fileCaches[username];
console.log("Agua.File.removeFileTree rootTree: ");
console.dir({rootTree:rootTree});
if ( ! rootTree ) {
console.log("Agua.File.removeFileTree rootTree is null. Returning");
return;
}
for ( var fileRoot in fileCaches[username] ) {
if ( fileRoot.match('^' + location +'$')
|| fileRoot.match('^' + location +'\/') ) {
console.log("Agua.File.removeFileTree DELETING fileRoot: " + fileRoot);
// delete fileCaches[username][fileRoot];
}
}
if ( ! location.match(/^(.+)\/[^\/]+$/) ) {
console.log("Agua.File.removeFileTree No parentDir. Returning");
return;
}
var parentDir = location.match(/^(.+)\/[^\/]+$/)[1];
var child = location.match(/^.+\/([^\/]+)$/)[1];
console.log("Agua.File.removeFileTree parentDir: " + parentDir);
console.log("Agua.File.removeFileTree child: " + child);
this.removeItemFromParent(fileCaches[username][parentDir], child);
var project1 = fileCaches[username][parentDir];
console.log("Agua.File.removeFileTree project1: " + project1);
console.dir({project1:project1});
console.log("Agua.File.removeFileTree END");
},
removeItemFromParent : function (parent, childName) {
for ( i = 0; i < parent.items.length; i++ ) {
var childObject = parent.items[i];
if ( childObject.name == childName ) {
parent.items.splice(i, 1);
break;
}
}
},
removeRemoteFile : function (username, location, callback) {
console.log("Agua.File.removeRemoteFile username: " + username);
console.log("Agua.File.removeRemoteFile location: " + location);
console.log("Agua.File.removeRemoteFile callback: " + callback);
// DELETE ON REMOTE
var url = this.getFoldersUrl();
var putData = new Object;
putData.mode = "removeFile";
putData.module = "Folders";
putData.sessionid = Agua.cookie('sessionid');
putData.username = Agua.cookie('username');
putData.file = location;
var thisObject = this;
dojo.xhrPut(
{
url : url,
putData : dojo.toJson(putData),
handleAs : "json",
sync : false,
handle : function(response) {
if ( callback ) callback(response);
}
}
);
},
renameFileTree : function (username, oldLocation, newLocation) {
console.log("Agua.File.renameFileTree username: " + username);
console.log("Agua.File.renameFileTree oldLocation: " + oldLocation);
console.log("Agua.File.renameFileTree newLocation: " + newLocation);
var fileCaches = this.getData("filecaches");
console.log("Agua.File.renameFileTree fileCaches: ");
console.dir({fileCaches:fileCaches});
if ( ! fileCaches ) {
console.log("Agua.File.renameFileTree fileCaches is null. Returning");
return;
}
var rootTree = fileCaches[username];
console.log("Agua.File.renameFileTree rootTree: ");
console.dir({rootTree:rootTree});
if ( ! rootTree ) {
console.log("Agua.File.renameFileTree rootTree is null. Returning");
return;
}
for ( var fileRoot in fileCaches[username] ) {
if ( fileRoot.match('^' + oldLocation +'$')
|| fileRoot.match('^' + oldLocation +'\/') ) {
console.log("Agua.File.renameFileTree DELETING fileRoot: " + fileRoot);
var value = fileCaches[username][fileRoot];
var re = new RegExp('^' + oldLocation);
var newRoot = fileRoot.replace(re, newLocation);
console.log("Agua.File.renameFileTree ADDING newRoot: " + newRoot);
delete fileCaches[username][fileRoot];
fileCaches[username][newRoot] = value;
}
}
console.log("Agua.File.renameFileTree oldLocation: " + oldLocation);
var parentDir = this.getParentDir(oldLocation);
console.log("Agua.File.renameFileTree oldLocation: " + oldLocation);
if ( ! parentDir ) return;
console.log("Agua.File.renameFileTree Doing this.renameItemInParent()");
var child = this.getChild(oldLocation);
var newChild = newLocation.match(/^.+\/([^\/]+)$/)[1];
console.log("Agua.File.renameFileTree parentDir: " + parentDir);
console.log("Agua.File.renameFileTree child: " + child);
console.log("Agua.File.renameFileTree newChild: " + newChild);
var parent = fileCaches[username][parentDir];
this.renameItemInParent(parent, child, newChild);
console.log("Agua.File.renameFileTree parent: " + parent);
console.dir({parent:parent});
console.log("Agua.File.renameFileTree END");
},
renameItemInParent : function (parent, childName, newChildName) {
for ( i = 0; i < parent.items.length; i++ ) {
var childObject = parent.items[i];
if ( childObject.name == childName ) {
var re = new RegExp(childName + "$");
parent.items[i].name= parent.items[i].name.replace(re, newChildName);
console.log("Agua.File.renameItemInParent NEW parent.items[" + i + "].name: " + parent.items[i].name);
parent.items[i].path= parent.items[i].path.replace(re, newChildName);
console.log("Agua.File.repathItemInParent NEW parent.items[" + i + "].path: " + parent.items[i].path);
break;
}
}
},
getParentDir : function (location) {
if ( ! location.match(/^(.+)\/[^\/]+$/) ) return null;
return location.match(/^(.+)\/[^\/]+$/)[1];
},
getChild : function (location) {
if ( ! location.match(/^.+\/([^\/]+)$/) ) return null;
return location.match(/^.+\/([^\/]+)$/)[1];
},
isDirectory : function (username, location) {
// USE IF CACHED
var fileCache = this.getFileCache(username, location);
console.log("Agua.File.isDirectory username: " + username);
console.log("Agua.File.isDirectory location: " + location);
console.log("Agua.File.isDirectory fileCache: ");
console.dir({fileCache:fileCache});
if ( fileCache ) return fileCache.directory;
return null;
},
isFileCacheItem : function (username, directory, itemName) {
console.log("Agua.isFileCacheItem username: " + username);
console.log("Agua.isFileCacheItem directory: " + directory);
console.log("Agua.isFileCacheItem itemName: " + itemName);
var fileCache = this.getFileCache(username, directory);
console.log("Agua.isFileCacheItem fileCache: " + fileCache);
console.dir({fileCache:fileCache});
if ( ! fileCache || ! fileCache.items ) return false;
for ( var i = 0; i < fileCache.items.length; i++ ) {
if ( fileCache.items[i].name == itemName) return true;
}
return false;
},
// FILE METHODS
renameFile : function (oldFilePath, newFilePath) {
// RENAME FILE OR FOLDER ON SERVER
var url = this.getFoldersUrl();
var query = new Object;
query.mode = "renameFile";
query.module = "Agua::Folders";
query.sessionid = Agua.cookie('sessionid');
query.username = Agua.cookie('username');
query.oldpath = oldFilePath;
query.newpath = newFilePath;
this.doPut({ url: url, query: query, sync: false });
},
createFolder : function (folderPath) {
// CREATE FOLDER ON SERVER
var url = this.getFoldersUrl();
var query = new Object;
query.mode = "newFolder";
query.module = "Agua::Folders";
query.sessionid = Agua.cookie('sessionid');
query.username = Agua.cookie('username');
query.folderpath = folderPath;
this.doPut({ url: url, query: query, sync: false });
},
// FILEINFO METHODS
getFileInfo : function (stageParameterObject, fileinfo) {
// GET THE BOOLEAN fileInfo VALUE FOR A STAGE PARAMETER
if ( fileinfo != null )
{
console.log("Agua.File.getFileInfo fileinfo parameter is present. Should you be using setFileInfo instead?. Returning null.");
return null;
}
return this._fileInfo(stageParameterObject, fileinfo);
},
setFileInfo : function (stageParameterObject, fileinfo) {
// SET THE BOOLEAN fileInfo VALUE FOR A STAGE PARAMETER
if ( ! stageParameterObject ) return;
if ( fileinfo == null )
{
console.log("Agua.File.setFileInfo fileinfo is null. Returning null.");
return null;
}
return this._fileInfo(stageParameterObject, fileinfo);
},
_fileInfo : function (stageParameterObject, fileinfo) {
// RETURN THE fileInfo BOOLEAN FOR A STAGE PARAMETER
// OR SET IT IF A VALUE IS SUPPLIED: RETURN NULL IF
// UNSUCCESSFUL, TRUE OTHERWISE
console.log("Agua.File._fileInfo plugins.core.Data._fileInfo()");
console.log("Agua.File._fileInfo stageParameterObject: ");
console.dir({stageParameterObject:stageParameterObject});
console.log("Agua.File._fileInfo fileinfo: ");
console.dir({fileinfo:fileinfo});
var uniqueKeys = ["username", "project", "workflow", "appname", "appnumber", "name", "paramtype"];
var valueArray = new Array;
for ( var i = 0; i < uniqueKeys.length; i++ ) {
valueArray.push(stageParameterObject[uniqueKeys[i]]);
}
var stageParameter = this.getEntry(this.cloneData("stageparameters"), uniqueKeys, valueArray);
console.log("Agua.File._fileInfo stageParameter found: ");
console.dir({stageParameter:stageParameter});
if ( stageParameter == null ) {
console.log("Agua.File._fileInfo stageParameter is null. Returning null");
return null;
}
// RETURN FOR GETTER
if ( fileinfo == null ) {
console.log("Agua.File._fileInfo DOING the GETTER. Returning stageParameter.exists: " + stageParameter.fileinfo.exists);
return stageParameter.fileinfo.exists;
}
console.log("Agua.File._fileInfo DOING the SETTER");
// ELSE, DO THE SETTER
stageParameter.fileinfo = fileinfo;
var success = this._removeStageParameter(stageParameter);
if ( success == false ) {
console.log("Agua.File._fileInfo Could not remove stage parameter. Returning null");
return null;
}
console.log("Agua.File._fileInfo BEFORE success = this._addStageParameter(stageParameter)");
success = this._addStageParameter(stageParameter);
if ( success == false ) {
console.log("Agua.File._fileInfo Could not add stage parameter. Returning null");
return null;
}
return true;
},
// VALIDITY METHODS
getParameterValidity : function (stageParameterObject, booleanValue) {
// GET THE BOOLEAN parameterValidity VALUE FOR A STAGE PARAMETER
//console.log("Agua.File.getParameterValidity plugins.core.Data.getParameterValidity()");
////console.log("Agua.File.getParameterValidity stageParameterObject: " + dojo.toJson(stageParameterObject));
////console.log("Agua.File.getParameterValidity booleanValue: " + booleanValue);
if ( booleanValue != null )
{
//console.log("Agua.File.getParameterValidity booleanValue parameter is present. Should you be using "setParameterValidity" instead?. Returning null.");
return null;
}
var isValid = this._parameterValidity(stageParameterObject, booleanValue);
//console.log("Agua.File.getParameterValidity '" + stageParameterObject.name + "' isValid: " + isValid);
return isValid;
},
setParameterValidity : function (stageParameterObject, booleanValue) {
// SET THE BOOLEAN parameterValidity VALUE FOR A STAGE PARAMETER
////console.log("Agua.File.setParameterValidity plugins.core.Data.setParameterValidity()");
////console.log("Agua.File.setParameterValidity stageParameterObject: " + dojo.toJson(stageParameterObject));
////console.log("Agua.File.setParameterValidity " + stageParameterObject.name + " booleanValue: " + booleanValue);
if ( booleanValue == null )
{
//console.log("Agua.File.setParameterValidity booleanValue is null. Returning null.");
return null;
}
var isValid = this._parameterValidity(stageParameterObject, booleanValue);
//console.log("Agua.File.setParameterValidity '" + stageParameterObject.name + "' isValid: " + isValid);
return isValid;
},
_parameterValidity : function (stageParameterObject, booleanValue) {
// RETURN THE parameterValidity BOOLEAN FOR A STAGE PARAMETER
// OR SET IT IF A VALUE IS SUPPLIED
////console.log("Agua.File._parameterValidity plugins.core.Data._parameterValidity()");
//console.log("Agua.File._parameterValidity stageParameterObject: " + dojo.toJson(stageParameterObject, true));
////console.log("Agua.File._parameterValidity booleanValue: " + booleanValue);
//////var filtered = this._getStageParameters();
//////var keys = ["appname"];
//////var values = ["image2eland.pl"];
//////filtered = this.filterByKeyValues(filtered, keys, values);
////////console.log("Agua.File._parameterValidity filtered: " + dojo.toJson(filtered, true));
var uniqueKeys = ["project", "workflow", "appname", "appnumber", "name", "paramtype"];
var valueArray = new Array;
for ( var i = 0; i < uniqueKeys.length; i++ )
{
valueArray.push(stageParameterObject[uniqueKeys[i]]);
}
var stageParameter = this.getEntry(this._getStageParameters(), uniqueKeys, valueArray);
//console.log("Agua.File._parameterValidity stageParameter found: " + dojo.toJson(stageParameter, true));
if ( stageParameter == null )
{
//console.log("Agua.File._parameterValidity stageParameter is null. Returning null");
return null;
}
if ( booleanValue == null )
return stageParameter.isValid;
//console.log("Agua.File._parameterValidity stageParameter: " + dojo.toJson(stageParameter, true));
//console.log("Agua.File._parameterValidity booleanValue: " + booleanValue);
// SET isValid BOOLEAN VALUE
stageParameter.isValid = booleanValue;
var success = this._removeStageParameter(stageParameter);
if ( success == false )
{
//console.log("Agua.File._parameterValidity Could not remove stage parameter. Returning null");
return null;
}
////console.log("Agua.File._parameterValidity BEFORE success = this._addStageParameter(stageParameter)");
success = this._addStageParameter(stageParameter);
if ( success == false )
{
//console.log("Agua.File._parameterValidity Could not add stage parameter. Returning null");
return null;
}
return true;
}
}); | aguadev/aguadev | html/plugins/core/Agua/File.js | JavaScript | mit | 19,766 |
<?php
/**
* LitePubl CMS
*
* @copyright 2010 - 2017 Vladimir Yushko http://litepublisher.com/ http://litepublisher.ru/
* @license https://github.com/litepubl/cms/blob/master/LICENSE.txt MIT
* @link https://github.com/litepubl\cms
* @version 7.08
*/
namespace litepubl\admin\widget;
use litepubl\admin\Link;
use litepubl\core\PropException;
class Widget extends \litepubl\admin\Panel
{
public $widget;
public function __construct()
{
parent::__construct();
$this->lang->section = 'widgets';
}
public function __get($name)
{
if (method_exists($this, $get = 'get' . $name)) {
return $this->$get();
}
throw new PropException(get_class($this), $name);
}
protected function getAdminurl()
{
return Link::url('/admin/views/widgets/?idwidget=');
}
protected function getForm(): string
{
$title = $this->widget->gettitle($this->widget->id);
$this->args->title = $title;
$this->args->formtitle = $title . ' ' . $this->lang->widget;
return $this->theme->getInput('text', 'title', $title, $this->lang->widgettitle);
}
public function getContent(): string
{
$form = $this->getForm();
return $this->admin->form($form, $this->args);
}
public function processForm()
{
$widget = $this->widget;
$widget->lock();
if (isset($_POST['title'])) {
$widget->settitle($widget->id, $_POST['title']);
}
$this->doProcessForm();
$widget->unlock();
return $this->admin->success($this->lang->updated);
}
protected function doProcessForm()
{
}
}
| litepubl/cms | lib/admin/widget/Widget.php | PHP | mit | 1,705 |
<?php
/**
* Copyright (c) Frank Förster (http://frankfoerster.com)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Frank Förster (http://frankfoerster.com)
* @link http://github.com/frankfoerster/cakephp-migrations
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class IndexAlreadyExistsException extends Exception {
}
| frankfoerster/cakephp-migrations | Model/Exception/IndexAlreadyExistsException.php | PHP | mit | 537 |
using System;
using System.Collections;
namespace AppStudio.Data
{
/// <summary>
/// Implementation of the MainSchema class.
/// </summary>
public class MainSchema : BindableSchemaBase, IEquatable<MainSchema>
{
private string _title;
private string _subtitle;
private string _image;
private string _description;
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public string Subtitle
{
get { return _subtitle; }
set { SetProperty(ref _subtitle, value); }
}
public string Image
{
get { return _image; }
set { SetProperty(ref _image, value); }
}
public string Description
{
get { return _description; }
set { SetProperty(ref _description, value); }
}
public override string DefaultTitle
{
get { return Title; }
}
public override string DefaultSummary
{
get { return Subtitle; }
}
public override string DefaultImageUrl
{
get { return Image; }
}
public override string DefaultContent
{
get { return Subtitle; }
}
override public string GetValue(string fieldName)
{
if (!String.IsNullOrEmpty(fieldName))
{
switch (fieldName.ToLowerInvariant())
{
case "title":
return String.Format("{0}", Title);
case "subtitle":
return String.Format("{0}", Subtitle);
case "image":
return String.Format("{0}", Image);
case "description":
return String.Format("{0}", Description);
case "defaulttitle":
return DefaultTitle;
case "defaultsummary":
return DefaultSummary;
case "defaultimageurl":
return DefaultImageUrl;
default:
break;
}
}
return String.Empty;
}
public bool Equals(MainSchema other)
{
if (other == null)
{
return false;
}
return this.Title == other.Title && this.Subtitle == other.Subtitle && this.Image == other.Image && this.Description == other.Description;
}
}
}
| AppStudioSamples/Menu | scr/ClientApp/AppStudio.Data/DataSchemas/MainSchema.cs | C# | mit | 2,679 |
package org.onceatime.concurrent;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class RwSample {
public static void main(String[] args) {
class CachedData {
Object data;
volatile boolean cacheValid;
final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
void processCachedData() {
rwl.readLock().lock();
if (!cacheValid) {
// Must release read lock before acquiring write lock
rwl.readLock().unlock();
rwl.writeLock().lock();
try {
// Recheck state because another thread might have
// acquired write lock and changed state before we did.
if (!cacheValid) {
data = getData();
cacheValid = true;
}
// Downgrade by acquiring read lock before releasing write lock
rwl.readLock().lock();
} finally {
rwl.writeLock().unlock(); // Unlock write, still hold read
}
}
try {
use(data);
} finally {
rwl.readLock().unlock();
}
}
private Object getData() {
// TODO Auto-generated method stub
return null;
}
private void use(Object data2) {
// TODO Auto-generated method stub
}
}}
}
| chinafzy/java-practise | src/main/java/org/onceatime/concurrent/RwSample.java | Java | mit | 1,437 |
import { globalThis } from './global-this';
/**
* Detect if running in Node.js.
* @type {boolean}
*/
const isNode = Object.prototype.toString.call(globalThis.process) === '[object process]';
export { isNode };
| zant95/otpauth | src/utils/is-node.js | JavaScript | mit | 215 |
/**
* History.js Core
* History.js HTML4 Support
* @author Benjamin Arthur Lupton <contact@balupton.com>
* @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/
define(function(require){
"use strict";
// ========================================================================
// Initialise
// Localise Globals
var
console = window.console||undefined, // Prevent a JSLint complain
document = window.document, // Make sure we are using the correct document
navigator = window.navigator, // Make sure we are using the correct navigator
sessionStorage = window.sessionStorage||false, // sessionStorage
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
setInterval = window.setInterval,
clearInterval = window.clearInterval,
JSON = window.JSON,
alert = window.alert,
History = window.History = window.History||{}, // Public History Object
history = window.history; // Old History Object
try {
sessionStorage.setItem('TEST', '1');
sessionStorage.removeItem('TEST');
} catch(e) {
sessionStorage = false;
}
// MooTools Compatibility
JSON.stringify = JSON.stringify||JSON.encode;
JSON.parse = JSON.parse||JSON.decode;
// Check Existence
if ( typeof History.init !== 'undefined' ) {
throw new Error('History.js Core has already been loaded...');
}
// Add the Adapter
History.Adapter = {
/**
* History.Adapter.handlers[uid][eventName] = Array
*/
handlers: {},
/**
* History.Adapter._uid
* The current element unique identifier
*/
_uid: 1,
/**
* History.Adapter.uid(element)
* @param {Element} element
* @return {String} uid
*/
uid: function(element){
return element._uid || (element._uid = History.Adapter._uid++);
},
/**
* History.Adapter.bind(el,event,callback)
* @param {Element} element
* @param {String} eventName - custom and standard events
* @param {Function} callback
* @return
*/
bind: function(element,eventName,callback){
// Prepare
var uid = History.Adapter.uid(element);
// Apply Listener
History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
History.Adapter.handlers[uid][eventName].push(callback);
// Bind Global Listener
element['on'+eventName] = (function(element,eventName){
return function(event){
History.Adapter.trigger(element,eventName,event);
};
})(element,eventName);
},
/**
* History.Adapter.trigger(el,event)
* @param {Element} element
* @param {String} eventName - custom and standard events
* @param {Object} event - a object of event data
* @return
*/
trigger: function(element,eventName,event){
// Prepare
event = event || {};
var uid = History.Adapter.uid(element),
i,n;
// Apply Listener
History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
// Fire Listeners
for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i<n; ++i ) {
History.Adapter.handlers[uid][eventName][i].apply(this,[event]);
}
},
/**
* History.Adapter.extractEventData(key,event,extra)
* @param {String} key - key for the event data to extract
* @param {String} event - custom and standard events
* @return {mixed}
*/
extractEventData: function(key,event){
var result = (event && event[key]) || undefined;
return result;
},
/**
* History.Adapter.onDomLoad(callback)
* @param {Function} callback
* @return
*/
onDomLoad: function(callback) {
var timeout = window.setTimeout(function(){
callback();
},2000);
window.onload = function(){
clearTimeout(timeout);
callback();
};
}
};
// Initialise HTML4 Support
History.initHtml4 = function(){
// Initialise
if ( typeof History.initHtml4.initialized !== 'undefined' ) {
// Already Loaded
return false;
}
else {
History.initHtml4.initialized = true;
}
// ====================================================================
// Properties
/**
* History.enabled
* Is History enabled?
*/
History.enabled = true;
// ====================================================================
// Hash Storage
/**
* History.savedHashes
* Store the hashes in an array
*/
History.savedHashes = [];
/**
* History.isLastHash(newHash)
* Checks if the hash is the last hash
* @param {string} newHash
* @return {boolean} true
*/
History.isLastHash = function(newHash){
// Prepare
var oldHash = History.getHashByIndex(),
isLast;
// Check
isLast = newHash === oldHash;
// Return isLast
return isLast;
};
/**
* History.isHashEqual(newHash, oldHash)
* Checks to see if two hashes are functionally equal
* @param {string} newHash
* @param {string} oldHash
* @return {boolean} true
*/
History.isHashEqual = function(newHash, oldHash){
newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
return newHash === oldHash;
};
/**
* History.saveHash(newHash)
* Push a Hash
* @param {string} newHash
* @return {boolean} true
*/
History.saveHash = function(newHash){
// Check Hash
if ( History.isLastHash(newHash) ) {
return false;
}
// Push the Hash
History.savedHashes.push(newHash);
// Return true
return true;
};
/**
* History.getHashByIndex()
* Gets a hash by the index
* @param {integer} index
* @return {string}
*/
History.getHashByIndex = function(index){
// Prepare
var hash = null;
// Handle
if ( typeof index === 'undefined' ) {
// Get the last inserted
hash = History.savedHashes[History.savedHashes.length-1];
}
else if ( index < 0 ) {
// Get from the end
hash = History.savedHashes[History.savedHashes.length+index];
}
else {
// Get from the beginning
hash = History.savedHashes[index];
}
// Return hash
return hash;
};
// ====================================================================
// Discarded States
/**
* History.discardedHashes
* A hashed array of discarded hashes
*/
History.discardedHashes = {};
/**
* History.discardedStates
* A hashed array of discarded states
*/
History.discardedStates = {};
/**
* History.discardState(State)
* Discards the state by ignoring it through History
* @param {object} State
* @return {true}
*/
History.discardState = function(discardedState,forwardState,backState){
//History.debug('History.discardState', arguments);
// Prepare
var discardedStateHash = History.getHashByState(discardedState),
discardObject;
// Create Discard Object
discardObject = {
'discardedState': discardedState,
'backState': backState,
'forwardState': forwardState
};
// Add to DiscardedStates
History.discardedStates[discardedStateHash] = discardObject;
// Return true
return true;
};
/**
* History.discardHash(hash)
* Discards the hash by ignoring it through History
* @param {string} hash
* @return {true}
*/
History.discardHash = function(discardedHash,forwardState,backState){
//History.debug('History.discardState', arguments);
// Create Discard Object
var discardObject = {
'discardedHash': discardedHash,
'backState': backState,
'forwardState': forwardState
};
// Add to discardedHash
History.discardedHashes[discardedHash] = discardObject;
// Return true
return true;
};
/**
* History.discardedState(State)
* Checks to see if the state is discarded
* @param {object} State
* @return {bool}
*/
History.discardedState = function(State){
// Prepare
var StateHash = History.getHashByState(State),
discarded;
// Check
discarded = History.discardedStates[StateHash]||false;
// Return true
return discarded;
};
/**
* History.discardedHash(hash)
* Checks to see if the state is discarded
* @param {string} State
* @return {bool}
*/
History.discardedHash = function(hash){
// Check
var discarded = History.discardedHashes[hash]||false;
// Return true
return discarded;
};
/**
* History.recycleState(State)
* Allows a discarded state to be used again
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.recycleState = function(State){
//History.debug('History.recycleState', arguments);
// Prepare
var StateHash = History.getHashByState(State);
// Remove from DiscardedStates
if ( History.discardedState(State) ) {
delete History.discardedStates[StateHash];
}
// Return true
return true;
};
// ====================================================================
// HTML4 HashChange Support
if ( History.emulated.hashChange ) {
/*
* We must emulate the HTML4 HashChange Support by manually checking for hash changes
*/
/**
* History.hashChangeInit()
* Init the HashChange Emulation
*/
History.hashChangeInit = function(){
// Define our Checker Function
History.checkerFunction = null;
// Define some variables that will help in our checker function
var lastDocumentHash = '',
iframeId, iframe,
lastIframeHash, checkerRunning,
startedWithHash = Boolean(History.getHash());
// Handle depending on the browser
if ( History.isInternetExplorer() ) {
// IE6 and IE7
// We need to use an iframe to emulate the back and forward buttons
// Create iFrame
iframeId = 'historyjs-iframe';
iframe = document.createElement('iframe');
// Adjust iFarme
// IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
// "This page contains both secure and nonsecure items" warning.
iframe.setAttribute('id', iframeId);
iframe.setAttribute('src', '#');
iframe.style.display = 'none';
// Append iFrame
document.body.appendChild(iframe);
// Create initial history entry
iframe.contentWindow.document.open();
iframe.contentWindow.document.close();
// Define some variables that will help in our checker function
lastIframeHash = '';
checkerRunning = false;
// Define the checker function
History.checkerFunction = function(){
// Check Running
if ( checkerRunning ) {
return false;
}
// Update Running
checkerRunning = true;
// Fetch
var
documentHash = History.getHash(),
iframeHash = History.getHash(iframe.contentWindow.document);
// The Document Hash has changed (application caused)
if ( documentHash !== lastDocumentHash ) {
// Equalise
lastDocumentHash = documentHash;
// Create a history entry in the iframe
if ( iframeHash !== documentHash ) {
//History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
// Equalise
lastIframeHash = iframeHash = documentHash;
// Create History Entry
iframe.contentWindow.document.open();
iframe.contentWindow.document.close();
// Update the iframe's hash
iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
}
// Trigger Hashchange Event
History.Adapter.trigger(window,'hashchange');
}
// The iFrame Hash has changed (back button caused)
else if ( iframeHash !== lastIframeHash ) {
//History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
// Equalise
lastIframeHash = iframeHash;
// If there is no iframe hash that means we're at the original
// iframe state.
// And if there was a hash on the original request, the original
// iframe state was replaced instantly, so skip this state and take
// the user back to where they came from.
if (startedWithHash && iframeHash === '') {
History.back();
}
else {
// Update the Hash
History.setHash(iframeHash,false);
}
}
// Reset Running
checkerRunning = false;
// Return true
return true;
};
}
else {
// We are not IE
// Firefox 1 or 2, Opera
// Define the checker function
History.checkerFunction = function(){
// Prepare
var documentHash = History.getHash()||'';
// The Document Hash has changed (application caused)
if ( documentHash !== lastDocumentHash ) {
// Equalise
lastDocumentHash = documentHash;
// Trigger Hashchange Event
History.Adapter.trigger(window,'hashchange');
}
// Return true
return true;
};
}
// Apply the checker function
History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
// Done
return true;
}; // History.hashChangeInit
// Bind hashChangeInit
History.Adapter.onDomLoad(History.hashChangeInit);
} // History.emulated.hashChange
// ====================================================================
// HTML5 State Support
// Non-Native pushState Implementation
if ( History.emulated.pushState ) {
/*
* We must emulate the HTML5 State Management by using HTML4 HashChange
*/
/**
* History.onHashChange(event)
* Trigger HTML5's window.onpopstate via HTML4 HashChange Support
*/
History.onHashChange = function(event){
//History.debug('History.onHashChange', arguments);
// Prepare
var currentUrl = ((event && event.newURL) || History.getLocationHref()),
currentHash = History.getHashByUrl(currentUrl),
currentState = null,
currentStateHash = null,
currentStateHashExits = null,
discardObject;
// Check if we are the same state
if ( History.isLastHash(currentHash) ) {
// There has been no change (just the page's hash has finally propagated)
//History.debug('History.onHashChange: no change');
History.busy(false);
return false;
}
// Reset the double check
History.doubleCheckComplete();
// Store our location for use in detecting back/forward direction
History.saveHash(currentHash);
// Expand Hash
if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
//History.debug('History.onHashChange: traditional anchor', currentHash);
// Traditional Anchor Hash
History.Adapter.trigger(window,'anchorchange');
History.busy(false);
return false;
}
// Create State
currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
// Check if we are the same state
if ( History.isLastSavedState(currentState) ) {
//History.debug('History.onHashChange: no change');
// There has been no change (just the page's hash has finally propagated)
History.busy(false);
return false;
}
// Create the state Hash
currentStateHash = History.getHashByState(currentState);
// Check if we are DiscardedState
discardObject = History.discardedState(currentState);
if ( discardObject ) {
// Ignore this state as it has been discarded and go back to the state before it
if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
// We are going backwards
//History.debug('History.onHashChange: go backwards');
History.back(false);
} else {
// We are going forwards
//History.debug('History.onHashChange: go forwards');
History.forward(false);
}
return false;
}
// Push the new HTML5 State
//History.debug('History.onHashChange: success hashchange');
History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
// End onHashChange closure
return true;
};
History.Adapter.bind(window,'hashchange',History.onHashChange);
/**
* History.pushState(data,title,url)
* Add a new State to the history object, become it, and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.pushState = function(data,title,url,queue){
//History.debug('History.pushState: called', arguments);
// We assume that the URL passed in is URI-encoded, but this makes
// sure that it's fully URI encoded; any '%'s that are encoded are
// converted back into '%'s
url = encodeURI(url).replace(/%25/g, "%");
// Check the State
if ( History.getHashByUrl(url) ) {
throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.pushState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.pushState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy
History.busy(true);
// Fetch the State Object
var newState = History.createStateObject(data,title,url),
newStateHash = History.getHashByState(newState),
oldState = History.getState(false),
oldStateHash = History.getHashByState(oldState),
html4Hash = History.getHash(),
wasExpected = History.expectedStateId == newState.id;
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Recycle the State
History.recycleState(newState);
// Force update of the title
History.setTitle(newState);
// Check if we are the same State
if ( newStateHash === oldStateHash ) {
//History.debug('History.pushState: no change', newStateHash);
History.busy(false);
return false;
}
// Update HTML5 State
History.saveState(newState);
// Fire HTML5 Event
if(!wasExpected)
History.Adapter.trigger(window,'statechange');
// Update HTML4 Hash
if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
History.setHash(newStateHash,false);
}
History.busy(false);
// End pushState closure
return true;
};
/**
* History.replaceState(data,title,url)
* Replace the State and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.replaceState = function(data,title,url,queue){
//History.debug('History.replaceState: called', arguments);
// We assume that the URL passed in is URI-encoded, but this makes
// sure that it's fully URI encoded; any '%'s that are encoded are
// converted back into '%'s
url = encodeURI(url).replace(/%25/g, "%");
// Check the State
if ( History.getHashByUrl(url) ) {
throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.replaceState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.replaceState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy
History.busy(true);
// Fetch the State Objects
var newState = History.createStateObject(data,title,url),
newStateHash = History.getHashByState(newState),
oldState = History.getState(false),
oldStateHash = History.getHashByState(oldState),
previousState = History.getStateByIndex(-2);
// Discard Old State
History.discardState(oldState,newState,previousState);
// If the url hasn't changed, just store and save the state
// and fire a statechange event to be consistent with the
// html 5 api
if ( newStateHash === oldStateHash ) {
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Recycle the State
History.recycleState(newState);
// Force update of the title
History.setTitle(newState);
// Update HTML5 State
History.saveState(newState);
// Fire HTML5 Event
//History.debug('History.pushState: trigger popstate');
History.Adapter.trigger(window,'statechange');
History.busy(false);
}
else {
// Alias to PushState
History.pushState(newState.data,newState.title,newState.url,false);
}
// End replaceState closure
return true;
};
} // History.emulated.pushState
// ====================================================================
// Initialise
// Non-Native pushState Implementation
if ( History.emulated.pushState ) {
/**
* Ensure initial state is handled correctly
*/
if ( History.getHash() && !History.emulated.hashChange ) {
History.Adapter.onDomLoad(function(){
History.Adapter.trigger(window,'hashchange');
});
}
} // History.emulated.pushState
}; // History.initHtml4
// Initialise History
History.init = function(options){
// Check Load Status of Adapter
if ( typeof History.Adapter === 'undefined' ) {
return false;
}
// Check Load Status of Core
if ( typeof History.initCore !== 'undefined' ) {
History.initCore();
}
// Check Load Status of HTML4 Support
if ( typeof History.initHtml4 !== 'undefined' ) {
History.initHtml4();
}
// Return true
return true;
};
// ========================================================================
// Initialise Core
// Initialise Core
History.initCore = function(options){
// Initialise
if ( typeof History.initCore.initialized !== 'undefined' ) {
// Already Loaded
return false;
}
else {
History.initCore.initialized = true;
}
// ====================================================================
// Options
/**
* History.options
* Configurable options
*/
History.options = History.options||{};
/**
* History.options.hashChangeInterval
* How long should the interval be before hashchange checks
*/
History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
/**
* History.options.safariPollInterval
* How long should the interval be before safari poll checks
*/
History.options.safariPollInterval = History.options.safariPollInterval || 500;
/**
* History.options.doubleCheckInterval
* How long should the interval be before we perform a double check
*/
History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
/**
* History.options.disableSuid
* Force History not to append suid
*/
History.options.disableSuid = History.options.disableSuid || false;
/**
* History.options.storeInterval
* How long should we wait between store calls
*/
History.options.storeInterval = History.options.storeInterval || 1000;
/**
* History.options.busyDelay
* How long should we wait between busy events
*/
History.options.busyDelay = History.options.busyDelay || 250;
/**
* History.options.debug
* If true will enable debug messages to be logged
*/
History.options.debug = History.options.debug || false;
/**
* History.options.initialTitle
* What is the title of the initial state
*/
History.options.initialTitle = History.options.initialTitle || document.title;
/**
* History.options.html4Mode
* If true, will force HTMl4 mode (hashtags)
*/
History.options.html4Mode = History.options.html4Mode || false;
/**
* History.options.delayInit
* Want to override default options and call init manually.
*/
History.options.delayInit = History.options.delayInit || false;
// ====================================================================
// Interval record
/**
* History.intervalList
* List of intervals set, to be cleared when document is unloaded.
*/
History.intervalList = [];
/**
* History.clearAllIntervals
* Clears all setInterval instances.
*/
History.clearAllIntervals = function(){
var i, il = History.intervalList;
if (typeof il !== "undefined" && il !== null) {
for (i = 0; i < il.length; i++) {
clearInterval(il[i]);
}
History.intervalList = null;
}
};
// ====================================================================
// Debug
/**
* History.debug(message,...)
* Logs the passed arguments if debug enabled
*/
History.debug = function(){
if ( (History.options.debug||false) ) {
History.log.apply(History,arguments);
}
};
/**
* History.log(message,...)
* Logs the passed arguments
*/
History.log = function(){
// Prepare
var
consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
textarea = document.getElementById('log'),
message,
i,n,
args,arg
;
// Write to Console
if ( consoleExists ) {
args = Array.prototype.slice.call(arguments);
message = args.shift();
if ( typeof console.debug !== 'undefined' ) {
console.debug.apply(console,[message,args]);
}
else {
console.log.apply(console,[message,args]);
}
}
else {
message = ("\n"+arguments[0]+"\n");
}
// Write to log
for ( i=1,n=arguments.length; i<n; ++i ) {
arg = arguments[i];
if ( typeof arg === 'object' && typeof JSON !== 'undefined' ) {
try {
arg = JSON.stringify(arg);
}
catch ( Exception ) {
// Recursive Object
}
}
message += "\n"+arg+"\n";
}
// Textarea
if ( textarea ) {
textarea.value += message+"\n-----\n";
textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;
}
// No Textarea, No Console
else if ( !consoleExists ) {
alert(message);
}
// Return true
return true;
};
// ====================================================================
// Emulated Status
/**
* History.getInternetExplorerMajorVersion()
* Get's the major version of Internet Explorer
* @return {integer}
* @license Public Domain
* @author Benjamin Arthur Lupton <contact@balupton.com>
* @author James Padolsey <https://gist.github.com/527683>
*/
History.getInternetExplorerMajorVersion = function(){
var result = History.getInternetExplorerMajorVersion.cached =
(typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
? History.getInternetExplorerMajorVersion.cached
: (function(){
var v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
return (v > 4) ? v : false;
})()
;
return result;
};
/**
* History.isInternetExplorer()
* Are we using Internet Explorer?
* @return {boolean}
* @license Public Domain
* @author Benjamin Arthur Lupton <contact@balupton.com>
*/
History.isInternetExplorer = function(){
var result =
History.isInternetExplorer.cached =
(typeof History.isInternetExplorer.cached !== 'undefined')
? History.isInternetExplorer.cached
: Boolean(History.getInternetExplorerMajorVersion())
;
return result;
};
/**
* History.emulated
* Which features require emulating?
*/
if (History.options.html4Mode) {
History.emulated = {
pushState : true,
hashChange: true
};
}
else {
History.emulated = {
pushState: !Boolean(
window.history && window.history.pushState && window.history.replaceState
&& !(
(/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
|| (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
)
),
hashChange: Boolean(
!(('onhashchange' in window) || ('onhashchange' in document))
||
(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
)
};
}
/**
* History.enabled
* Is History enabled?
*/
History.enabled = !History.emulated.pushState;
/**
* History.bugs
* Which bugs are present
*/
History.bugs = {
/**
* Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
* https://bugs.webkit.org/show_bug.cgi?id=56249
*/
setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
/**
* Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
* https://bugs.webkit.org/show_bug.cgi?id=42940
*/
safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
/**
* MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
*/
ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
/**
* MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
*/
hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
};
/**
* History.isEmptyObject(obj)
* Checks to see if the Object is Empty
* @param {Object} obj
* @return {boolean}
*/
History.isEmptyObject = function(obj) {
for ( var name in obj ) {
if ( obj.hasOwnProperty(name) ) {
return false;
}
}
return true;
};
/**
* History.cloneObject(obj)
* Clones a object and eliminate all references to the original contexts
* @param {Object} obj
* @return {Object}
*/
History.cloneObject = function(obj) {
var hash,newObj;
if ( obj ) {
hash = JSON.stringify(obj);
newObj = JSON.parse(hash);
}
else {
newObj = {};
}
return newObj;
};
// ====================================================================
// URL Helpers
/**
* History.getRootUrl()
* Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
* @return {String} rootUrl
*/
History.getRootUrl = function(){
// Create
var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
if ( document.location.port||false ) {
rootUrl += ':'+document.location.port;
}
rootUrl += '/';
// Return
return rootUrl;
};
/**
* History.getBaseHref()
* Fetches the `href` attribute of the `<base href="...">` element if it exists
* @return {String} baseHref
*/
History.getBaseHref = function(){
// Create
var
baseElements = document.getElementsByTagName('base'),
baseElement = null,
baseHref = '';
// Test for Base Element
if ( baseElements.length === 1 ) {
// Prepare for Base Element
baseElement = baseElements[0];
baseHref = baseElement.href.replace(/[^\/]+$/,'');
}
// Adjust trailing slash
baseHref = baseHref.replace(/\/+$/,'');
if ( baseHref ) baseHref += '/';
// Return
return baseHref;
};
/**
* History.getBaseUrl()
* Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
* @return {String} baseUrl
*/
History.getBaseUrl = function(){
// Create
var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
// Return
return baseUrl;
};
/**
* History.getPageUrl()
* Fetches the URL of the current page
* @return {String} pageUrl
*/
History.getPageUrl = function(){
// Fetch
var
State = History.getState(false,false),
stateUrl = (State||{}).url||History.getLocationHref(),
pageUrl;
// Create
pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
return (/\./).test(part) ? part : part+'/';
});
// Return
return pageUrl;
};
/**
* History.getBasePageUrl()
* Fetches the Url of the directory of the current page
* @return {String} basePageUrl
*/
History.getBasePageUrl = function(){
// Create
var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
return (/[^\/]$/).test(part) ? '' : part;
}).replace(/\/+$/,'')+'/';
// Return
return basePageUrl;
};
/**
* History.getFullUrl(url)
* Ensures that we have an absolute URL and not a relative URL
* @param {string} url
* @param {Boolean} allowBaseHref
* @return {string} fullUrl
*/
History.getFullUrl = function(url,allowBaseHref){
// Prepare
var fullUrl = url, firstChar = url.substring(0,1);
allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
// Check
if ( /[a-z]+\:\/\//.test(url) ) {
// Full URL
}
else if ( firstChar === '/' ) {
// Root URL
fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
}
else if ( firstChar === '#' ) {
// Anchor URL
fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
}
else if ( firstChar === '?' ) {
// Query URL
fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
}
else {
// Relative URL
if ( allowBaseHref ) {
fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
} else {
fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
}
// We have an if condition above as we do not want hashes
// which are relative to the baseHref in our URLs
// as if the baseHref changes, then all our bookmarks
// would now point to different locations
// whereas the basePageUrl will always stay the same
}
// Return
return fullUrl.replace(/\#$/,'');
};
/**
* History.getShortUrl(url)
* Ensures that we have a relative URL and not a absolute URL
* @param {string} url
* @return {string} url
*/
History.getShortUrl = function(url){
// Prepare
var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
// Trim baseUrl
if ( History.emulated.pushState ) {
// We are in a if statement as when pushState is not emulated
// The actual url these short urls are relative to can change
// So within the same session, we the url may end up somewhere different
console.log ('History.getShortUrl IE :: ' + 'shortUrl: ' + shortUrl + ' baseUrl ' + baseUrl );
shortUrl = shortUrl.replace(baseUrl,'');
}
// Trim rootUrl
shortUrl = shortUrl.replace(rootUrl,'/');
console.log('short url pre: ', shortUrl);
// Ensure we can still detect it as a state
if ( History.isTraditionalAnchor(shortUrl) ) {
// shortUrl = './'+shortUrl;
}
// Clean It
shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
console.log('short url post: ', shortUrl);
// Return
return shortUrl;
};
/**
* History.getLocationHref(document)
* Returns a normalized version of document.location.href
* accounting for browser inconsistencies, etc.
*
* This URL will be URI-encoded and will include the hash
*
* @param {object} document
* @return {string} url
*/
History.getLocationHref = function(doc) {
doc = doc || document;
// most of the time, this will be true
if (doc.URL === doc.location.href)
return doc.location.href;
// some versions of webkit URI-decode document.location.href
// but they leave document.URL in an encoded state
if (doc.location.href === decodeURIComponent(doc.URL))
return doc.URL;
// FF 3.6 only updates document.URL when a page is reloaded
// document.location.href is updated correctly
if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
return doc.location.href;
if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
return doc.location.href;
return doc.URL || doc.location.href;
};
// ====================================================================
// State Storage
/**
* History.store
* The store for all session specific data
*/
History.store = {};
/**
* History.idToState
* 1-1: State ID to State Object
*/
History.idToState = History.idToState||{};
/**
* History.stateToId
* 1-1: State String to State ID
*/
History.stateToId = History.stateToId||{};
/**
* History.urlToId
* 1-1: State URL to State ID
*/
History.urlToId = History.urlToId||{};
/**
* History.storedStates
* Store the states in an array
*/
History.storedStates = History.storedStates||[];
/**
* History.savedStates
* Saved the states in an array
*/
History.savedStates = History.savedStates||[];
/**
* History.noramlizeStore()
* Noramlize the store by adding necessary values
*/
History.normalizeStore = function(){
History.store.idToState = History.store.idToState||{};
History.store.urlToId = History.store.urlToId||{};
History.store.stateToId = History.store.stateToId||{};
};
/**
* History.getState()
* Get an object containing the data, title and url of the current state
* @param {Boolean} friendly
* @param {Boolean} create
* @return {Object} State
*/
History.getState = function(friendly,create){
// Prepare
if ( typeof friendly === 'undefined' ) { friendly = true; }
if ( typeof create === 'undefined' ) { create = true; }
// Fetch
var State = History.getLastSavedState();
// Create
if ( !State && create ) {
State = History.createStateObject();
}
// Adjust
if ( friendly ) {
State = History.cloneObject(State);
State.url = State.cleanUrl||State.url;
}
// Return
return State;
};
/**
* History.getIdByState(State)
* Gets a ID for a State
* @param {State} newState
* @return {String} id
*/
History.getIdByState = function(newState){
// Fetch ID
var id = History.extractId(newState.url),
str;
if ( !id ) {
// Find ID via State String
str = History.getStateString(newState);
if ( typeof History.stateToId[str] !== 'undefined' ) {
id = History.stateToId[str];
}
else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
id = History.store.stateToId[str];
}
else {
// Generate a new ID
while ( true ) {
id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
break;
}
}
// Apply the new State to the ID
History.stateToId[str] = id;
History.idToState[id] = newState;
}
}
// Return ID
return id;
};
/**
* History.normalizeState(State)
* Expands a State Object
* @param {object} State
* @return {object}
*/
History.normalizeState = function(oldState){
// Variables
var newState, dataNotEmpty;
// Prepare
if ( !oldState || (typeof oldState !== 'object') ) {
oldState = {};
}
// Check
if ( typeof oldState.normalized !== 'undefined' ) {
return oldState;
}
// Adjust
if ( !oldState.data || (typeof oldState.data !== 'object') ) {
oldState.data = {};
}
// ----------------------------------------------------------------
// Create
newState = {};
newState.normalized = true;
newState.title = oldState.title||'';
newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
newState.hash = History.getShortUrl(newState.url);
newState.data = History.cloneObject(oldState.data);
// Fetch ID
newState.id = History.getIdByState(newState);
// ----------------------------------------------------------------
// Clean the URL
newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
newState.url = newState.cleanUrl;
// Check to see if we have more than just a url
dataNotEmpty = !History.isEmptyObject(newState.data);
// Apply
if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
// Add ID to Hash
newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
if ( !/\?/.test(newState.hash) ) {
newState.hash += '?';
}
newState.hash += '&_suid='+newState.id;
}
// Create the Hashed URL
newState.hashedUrl = History.getFullUrl(newState.hash);
// ----------------------------------------------------------------
// Update the URL if we have a duplicate
if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
newState.url = newState.hashedUrl;
}
// ----------------------------------------------------------------
// Return
return newState;
};
/**
* History.createStateObject(data,title,url)
* Creates a object based on the data, title and url state params
* @param {object} data
* @param {string} title
* @param {string} url
* @return {object}
*/
History.createStateObject = function(data,title,url){
// Hashify
var State = {
'data': data,
'title': title,
'url': url
};
// Expand the State
State = History.normalizeState(State);
// Return object
return State;
};
/**
* History.getStateById(id)
* Get a state by it's UID
* @param {String} id
*/
History.getStateById = function(id){
// Prepare
id = String(id);
// Retrieve
var State = History.idToState[id] || History.store.idToState[id] || undefined;
// Return State
return State;
};
/**
* Get a State's String
* @param {State} passedState
*/
History.getStateString = function(passedState){
// Prepare
var State, cleanedState, str;
// Fetch
State = History.normalizeState(passedState);
// Clean
cleanedState = {
data: State.data,
title: passedState.title,
url: passedState.url
};
// Fetch
str = JSON.stringify(cleanedState);
// Return
return str;
};
/**
* Get a State's ID
* @param {State} passedState
* @return {String} id
*/
History.getStateId = function(passedState){
// Prepare
var State, id;
// Fetch
State = History.normalizeState(passedState);
// Fetch
id = State.id;
// Return
return id;
};
/**
* History.getHashByState(State)
* Creates a Hash for the State Object
* @param {State} passedState
* @return {String} hash
*/
History.getHashByState = function(passedState){
// Prepare
var State, hash;
// Fetch
State = History.normalizeState(passedState);
// Hash
hash = State.hash;
// Return
return hash;
};
/**
* History.extractId(url_or_hash)
* Get a State ID by it's URL or Hash
* @param {string} url_or_hash
* @return {string} id
*/
History.extractId = function ( url_or_hash ) {
// Prepare
var id,parts,url, tmp;
// Extract
// If the URL has a #, use the id from before the #
if (url_or_hash.indexOf('#') != -1)
{
tmp = url_or_hash.split("#")[0];
}
else
{
tmp = url_or_hash;
}
parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
url = parts ? (parts[1]||url_or_hash) : url_or_hash;
id = parts ? String(parts[2]||'') : '';
// Return
return id||false;
};
/**
* History.isTraditionalAnchor
* Checks to see if the url is a traditional anchor or not
* @param {String} url_or_hash
* @return {Boolean}
*/
History.isTraditionalAnchor = function(url_or_hash){
// Check
var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
// Return
return isTraditional;
};
/**
* History.extractState
* Get a State by it's URL or Hash
* @param {String} url_or_hash
* @return {State|null}
*/
History.extractState = function(url_or_hash,create){
// Prepare
var State = null, id, url;
create = create||false;
// Fetch SUID
id = History.extractId(url_or_hash);
if ( id ) {
State = History.getStateById(id);
}
// Fetch SUID returned no State
if ( !State ) {
// Fetch URL
url = History.getFullUrl(url_or_hash);
// Check URL
id = History.getIdByUrl(url)||false;
if ( id ) {
State = History.getStateById(id);
}
// Create State
if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
State = History.createStateObject(null,null,url);
}
}
// Return
return State;
};
/**
* History.getIdByUrl()
* Get a State ID by a State URL
*/
History.getIdByUrl = function(url){
// Fetch
var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
// Return
return id;
};
/**
* History.getLastSavedState()
* Get an object containing the data, title and url of the current state
* @return {Object} State
*/
History.getLastSavedState = function(){
return History.savedStates[History.savedStates.length-1]||undefined;
};
/**
* History.getLastStoredState()
* Get an object containing the data, title and url of the current state
* @return {Object} State
*/
History.getLastStoredState = function(){
return History.storedStates[History.storedStates.length-1]||undefined;
};
/**
* History.hasUrlDuplicate
* Checks if a Url will have a url conflict
* @param {Object} newState
* @return {Boolean} hasDuplicate
*/
History.hasUrlDuplicate = function(newState) {
// Prepare
var hasDuplicate = false,
oldState;
// Fetch
oldState = History.extractState(newState.url);
// Check
hasDuplicate = oldState && oldState.id !== newState.id;
// Return
return hasDuplicate;
};
/**
* History.storeState
* Store a State
* @param {Object} newState
* @return {Object} newState
*/
History.storeState = function(newState){
// Store the State
History.urlToId[newState.url] = newState.id;
// Push the State
History.storedStates.push(History.cloneObject(newState));
// Return newState
return newState;
};
/**
* History.isLastSavedState(newState)
* Tests to see if the state is the last state
* @param {Object} newState
* @return {boolean} isLast
*/
History.isLastSavedState = function(newState){
// Prepare
var isLast = false,
newId, oldState, oldId;
// Check
if ( History.savedStates.length ) {
newId = newState.id;
oldState = History.getLastSavedState();
oldId = oldState.id;
// Check
isLast = (newId === oldId);
}
// Return
return isLast;
};
/**
* History.saveState
* Push a State
* @param {Object} newState
* @return {boolean} changed
*/
History.saveState = function(newState){
// Check Hash
if ( History.isLastSavedState(newState) ) {
return false;
}
// Push the State
History.savedStates.push(History.cloneObject(newState));
// Return true
return true;
};
/**
* History.getStateByIndex()
* Gets a state by the index
* @param {integer} index
* @return {Object}
*/
History.getStateByIndex = function(index){
// Prepare
var State = null;
// Handle
if ( typeof index === 'undefined' ) {
// Get the last inserted
State = History.savedStates[History.savedStates.length-1];
}
else if ( index < 0 ) {
// Get from the end
State = History.savedStates[History.savedStates.length+index];
}
else {
// Get from the beginning
State = History.savedStates[index];
}
// Return State
return State;
};
/**
* History.getCurrentIndex()
* Gets the current index
* @return (integer)
*/
History.getCurrentIndex = function(){
// Prepare
var index = null;
// No states saved
if(History.savedStates.length < 1) {
index = 0;
}
else {
index = History.savedStates.length-1;
}
return index;
};
// ====================================================================
// Hash Helpers
/**
* History.getHash()
* @param {Location=} location
* Gets the current document hash
* Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
* @return {string}
*/
History.getHash = function(doc){
var url = History.getLocationHref(doc),
hash;
hash = History.getHashByUrl(url);
return hash;
};
/**
* History.unescapeHash()
* normalize and Unescape a Hash
* @param {String} hash
* @return {string}
*/
History.unescapeHash = function(hash){
// Prepare
var result = History.normalizeHash(hash);
// Unescape hash
result = decodeURIComponent(result);
// Return result
return result;
};
/**
* History.normalizeHash()
* normalize a hash across browsers
* @return {string}
*/
History.normalizeHash = function(hash){
// Prepare
var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
// Return result
return result;
};
/**
* History.setHash(hash)
* Sets the document hash
* @param {string} hash
* @return {History}
*/
History.setHash = function(hash,queue){
// Prepare
var State, pageUrl;
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.setHash: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.setHash,
args: arguments,
queue: queue
});
return false;
}
// Log
//History.debug('History.setHash: called',hash);
// Make Busy + Continue
History.busy(true);
// Check if hash is a state
State = History.extractState(hash,true);
if ( State && !History.emulated.pushState ) {
// Hash is a state so skip the setHash
//History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
// PushState
History.pushState(State.data,State.title,State.url,false);
}
else if ( History.getHash() !== hash ) {
// Hash is a proper hash, so apply it
// Handle browser bugs
if ( History.bugs.setHash ) {
// Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
// Fetch the base page
pageUrl = History.getPageUrl();
// Safari hash apply
History.pushState(null,null,pageUrl+'#'+hash,false);
}
else {
// Normal hash apply
document.location.hash = hash;
}
}
// Chain
return History;
};
/**
* History.escape()
* normalize and Escape a Hash
* @return {string}
*/
History.escapeHash = function(hash){
// Prepare
var result = History.normalizeHash(hash);
// Escape hash
result = window.encodeURIComponent(result);
// IE6 Escape Bug
if ( !History.bugs.hashEscape ) {
// Restore common parts
result = result
.replace(/\%21/g,'!')
.replace(/\%26/g,'&')
.replace(/\%3D/g,'=')
.replace(/\%3F/g,'?');
}
// Return result
return result;
};
/**
* History.getHashByUrl(url)
* Extracts the Hash from a URL
* @param {string} url
* @return {string} url
*/
History.getHashByUrl = function(url){
// Extract the hash
var hash = String(url)
.replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
;
// Unescape hash
hash = History.unescapeHash(hash);
// Return hash
return hash;
};
/**
* History.setTitle(title)
* Applies the title to the document
* @param {State} newState
* @return {Boolean}
*/
History.setTitle = function(newState){
// Prepare
var title = newState.title,
firstState;
// Initial
if ( !title ) {
firstState = History.getStateByIndex(0);
if ( firstState && firstState.url === newState.url ) {
title = firstState.title||History.options.initialTitle;
}
}
// Apply
try {
document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
}
catch ( Exception ) { }
document.title = title;
// Chain
return History;
};
// ====================================================================
// Queueing
/**
* History.queues
* The list of queues to use
* First In, First Out
*/
History.queues = [];
/**
* History.busy(value)
* @param {boolean} value [optional]
* @return {boolean} busy
*/
History.busy = function(value){
// Apply
if ( typeof value !== 'undefined' ) {
//History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
History.busy.flag = value;
}
// Default
else if ( typeof History.busy.flag === 'undefined' ) {
History.busy.flag = false;
}
// Queue
if ( !History.busy.flag ) {
// Execute the next item in the queue
clearTimeout(History.busy.timeout);
var fireNext = function(){
var i, queue, item;
if ( History.busy.flag ) return;
for ( i=History.queues.length-1; i >= 0; --i ) {
queue = History.queues[i];
if ( queue.length === 0 ) continue;
item = queue.shift();
History.fireQueueItem(item);
History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
}
};
History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
}
// Return
return History.busy.flag;
};
/**
* History.busy.flag
*/
History.busy.flag = false;
/**
* History.fireQueueItem(item)
* Fire a Queue Item
* @param {Object} item
* @return {Mixed} result
*/
History.fireQueueItem = function(item){
return item.callback.apply(item.scope||History,item.args||[]);
};
/**
* History.pushQueue(callback,args)
* Add an item to the queue
* @param {Object} item [scope,callback,args,queue]
*/
History.pushQueue = function(item){
// Prepare the queue
History.queues[item.queue||0] = History.queues[item.queue||0]||[];
// Add to the queue
History.queues[item.queue||0].push(item);
// Chain
return History;
};
/**
* History.queue (item,queue), (func,queue), (func), (item)
* Either firs the item now if not busy, or adds it to the queue
*/
History.queue = function(item,queue){
// Prepare
if ( typeof item === 'function' ) {
item = {
callback: item
};
}
if ( typeof queue !== 'undefined' ) {
item.queue = queue;
}
// Handle
if ( History.busy() ) {
History.pushQueue(item);
} else {
History.fireQueueItem(item);
}
// Chain
return History;
};
/**
* History.clearQueue()
* Clears the Queue
*/
History.clearQueue = function(){
History.busy.flag = false;
History.queues = [];
return History;
};
// ====================================================================
// IE Bug Fix
/**
* History.stateChanged
* States whether or not the state has changed since the last double check was initialised
*/
History.stateChanged = false;
/**
* History.doubleChecker
* Contains the timeout used for the double checks
*/
History.doubleChecker = false;
/**
* History.doubleCheckComplete()
* Complete a double check
* @return {History}
*/
History.doubleCheckComplete = function(){
// Update
History.stateChanged = true;
// Clear
History.doubleCheckClear();
// Chain
return History;
};
/**
* History.doubleCheckClear()
* Clear a double check
* @return {History}
*/
History.doubleCheckClear = function(){
// Clear
if ( History.doubleChecker ) {
clearTimeout(History.doubleChecker);
History.doubleChecker = false;
}
// Chain
return History;
};
/**
* History.doubleCheck()
* Create a double check
* @return {History}
*/
History.doubleCheck = function(tryAgain){
// Reset
History.stateChanged = false;
History.doubleCheckClear();
// Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
// Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
if ( History.bugs.ieDoubleCheck ) {
// Apply Check
History.doubleChecker = setTimeout(
function(){
History.doubleCheckClear();
if ( !History.stateChanged ) {
//History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
// Re-Attempt
tryAgain();
}
return true;
},
History.options.doubleCheckInterval
);
}
// Chain
return History;
};
// ====================================================================
// Safari Bug Fix
/**
* History.safariStatePoll()
* Poll the current state
* @return {History}
*/
History.safariStatePoll = function(){
// Poll the URL
// Get the Last State which has the new URL
var
urlState = History.extractState(History.getLocationHref()),
newState;
// Check for a difference
if ( !History.isLastSavedState(urlState) ) {
newState = urlState;
}
else {
return;
}
// Check if we have a state with that url
// If not create it
if ( !newState ) {
//History.debug('History.safariStatePoll: new');
newState = History.createStateObject();
}
// Apply the New State
//History.debug('History.safariStatePoll: trigger');
History.Adapter.trigger(window,'popstate');
// Chain
return History;
};
// ====================================================================
// State Aliases
/**
* History.back(queue)
* Send the browser history back one item
* @param {Integer} queue [optional]
*/
History.back = function(queue){
//History.debug('History.back: called', arguments);
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.back: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.back,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Fix certain browser bugs that prevent the state from changing
History.doubleCheck(function(){
History.back(false);
});
// Go back
history.go(-1);
// End back closure
return true;
};
/**
* History.forward(queue)
* Send the browser history forward one item
* @param {Integer} queue [optional]
*/
History.forward = function(queue){
//History.debug('History.forward: called', arguments);
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.forward: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.forward,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Fix certain browser bugs that prevent the state from changing
History.doubleCheck(function(){
History.forward(false);
});
// Go forward
history.go(1);
// End forward closure
return true;
};
/**
* History.go(index,queue)
* Send the browser history back or forward index times
* @param {Integer} queue [optional]
*/
History.go = function(index,queue){
//History.debug('History.go: called', arguments);
// Prepare
var i;
// Handle
if ( index > 0 ) {
// Forward
for ( i=1; i<=index; ++i ) {
History.forward(queue);
}
}
else if ( index < 0 ) {
// Backward
for ( i=-1; i>=index; --i ) {
History.back(queue);
}
}
else {
throw new Error('History.go: History.go requires a positive or negative integer passed.');
}
// Chain
return History;
};
// ====================================================================
// HTML5 State Support
// Non-Native pushState Implementation
if ( History.emulated.pushState ) {
/*
* Provide Skeleton for HTML4 Browsers
*/
// Prepare
var emptyFunction = function(){};
History.pushState = History.pushState||emptyFunction;
History.replaceState = History.replaceState||emptyFunction;
} // History.emulated.pushState
// Native pushState Implementation
else {
/*
* Use native HTML5 History API Implementation
*/
/**
* History.onPopState(event,extra)
* Refresh the Current State
*/
History.onPopState = function(event,extra){
// Prepare
var stateId = false, newState = false, currentHash, currentState;
// Reset the double check
History.doubleCheckComplete();
// Check for a Hash, and handle apporiatly
currentHash = History.getHash();
if ( currentHash ) {
// Expand Hash
currentState = History.extractState(currentHash||History.getLocationHref(),true);
if ( currentState ) {
// We were able to parse it, it must be a State!
// Let's forward to replaceState
//History.debug('History.onPopState: state anchor', currentHash, currentState);
History.replaceState(currentState.data, currentState.title, currentState.url, false);
}
else {
// Traditional Anchor
//History.debug('History.onPopState: traditional anchor', currentHash);
History.Adapter.trigger(window,'anchorchange');
History.busy(false);
}
// We don't care for hashes
History.expectedStateId = false;
return false;
}
// Ensure
stateId = History.Adapter.extractEventData('state',event,extra) || false;
// Fetch State
if ( stateId ) {
// Vanilla: Back/forward button was used
newState = History.getStateById(stateId);
}
else if ( History.expectedStateId ) {
// Vanilla: A new state was pushed, and popstate was called manually
newState = History.getStateById(History.expectedStateId);
}
else {
// Initial State
newState = History.extractState(History.getLocationHref());
}
// The State did not exist in our store
if ( !newState ) {
// Regenerate the State
newState = History.createStateObject(null,null,History.getLocationHref());
}
// Clean
History.expectedStateId = false;
// Check if we are the same state
if ( History.isLastSavedState(newState) ) {
// There has been no change (just the page's hash has finally propagated)
//History.debug('History.onPopState: no change', newState, History.savedStates);
History.busy(false);
return false;
}
// Store the State
History.storeState(newState);
History.saveState(newState);
// Force update of the title
History.setTitle(newState);
// Fire Our Event
History.Adapter.trigger(window,'statechange');
History.busy(false);
// Return true
return true;
};
History.Adapter.bind(window,'popstate',History.onPopState);
/**
* History.pushState(data,title,url)
* Add a new State to the history object, become it, and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.pushState = function(data,title,url,queue){
//History.debug('History.pushState: called', arguments);
// Check the State
if ( History.getHashByUrl(url) && History.emulated.pushState ) {
throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.pushState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.pushState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Create the newState
var newState = History.createStateObject(data,title,url);
// Check it
if ( History.isLastSavedState(newState) ) {
// Won't be a change
History.busy(false);
}
else {
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Push the newState
history.pushState(newState.id,newState.title,newState.url);
// Fire HTML5 Event
History.Adapter.trigger(window,'popstate');
}
// End pushState closure
return true;
};
/**
* History.replaceState(data,title,url)
* Replace the State and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.replaceState = function(data,title,url,queue){
//History.debug('History.replaceState: called', arguments);
// Check the State
if ( History.getHashByUrl(url) && History.emulated.pushState ) {
throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.replaceState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.replaceState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Create the newState
var newState = History.createStateObject(data,title,url);
// Check it
if ( History.isLastSavedState(newState) ) {
// Won't be a change
History.busy(false);
}
else {
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Push the newState
history.replaceState(newState.id,newState.title,newState.url);
// Fire HTML5 Event
History.Adapter.trigger(window,'popstate');
}
// End replaceState closure
return true;
};
} // !History.emulated.pushState
// ====================================================================
// Initialise
/**
* Load the Store
*/
if ( sessionStorage ) {
// Fetch
try {
History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
}
catch ( err ) {
History.store = {};
}
// Normalize
History.normalizeStore();
}
else {
// Default Load
History.store = {};
History.normalizeStore();
}
/**
* Clear Intervals on exit to prevent memory leaks
*/
History.Adapter.bind(window,"unload",History.clearAllIntervals);
/**
* Create the initial State
*/
History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
/**
* Bind for Saving Store
*/
if ( sessionStorage ) {
// When the page is closed
History.onUnload = function(){
// Prepare
var currentStore, item, currentStoreString;
// Fetch
try {
currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
}
catch ( err ) {
currentStore = {};
}
// Ensure
currentStore.idToState = currentStore.idToState || {};
currentStore.urlToId = currentStore.urlToId || {};
currentStore.stateToId = currentStore.stateToId || {};
// Sync
for ( item in History.idToState ) {
if ( !History.idToState.hasOwnProperty(item) ) {
continue;
}
currentStore.idToState[item] = History.idToState[item];
}
for ( item in History.urlToId ) {
if ( !History.urlToId.hasOwnProperty(item) ) {
continue;
}
currentStore.urlToId[item] = History.urlToId[item];
}
for ( item in History.stateToId ) {
if ( !History.stateToId.hasOwnProperty(item) ) {
continue;
}
currentStore.stateToId[item] = History.stateToId[item];
}
// Update
History.store = currentStore;
History.normalizeStore();
// In Safari, going into Private Browsing mode causes the
// Session Storage object to still exist but if you try and use
// or set any property/function of it it throws the exception
// "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
// add something to storage that exceeded the quota." infinitely
// every second.
currentStoreString = JSON.stringify(currentStore);
try {
// Store
sessionStorage.setItem('History.store', currentStoreString);
}
catch (e) {
if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
if (sessionStorage.length) {
// Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
// removing/resetting the storage can work.
sessionStorage.removeItem('History.store');
sessionStorage.setItem('History.store', currentStoreString);
} else {
// Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
}
} else {
throw e;
}
}
};
// For Internet Explorer
History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
// For Other Browsers
History.Adapter.bind(window,'beforeunload',History.onUnload);
History.Adapter.bind(window,'unload',History.onUnload);
// Both are enabled for consistency
}
// Non-Native pushState Implementation
if ( !History.emulated.pushState ) {
// Be aware, the following is only for native pushState implementations
// If you are wanting to include something for all browsers
// Then include it above this if block
/**
* Setup Safari Fix
*/
if ( History.bugs.safariPoll ) {
History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
}
/**
* Ensure Cross Browser Compatibility
*/
if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
/**
* Fix Safari HashChange Issue
*/
// Setup Alias
History.Adapter.bind(window,'hashchange',function(){
History.Adapter.trigger(window,'popstate');
});
// Initialise Alias
if ( History.getHash() ) {
History.Adapter.onDomLoad(function(){
History.Adapter.trigger(window,'hashchange');
});
}
}
} // !History.emulated.pushState
}; // History.initCore
// Try to Initialise History
if (!History.options || !History.options.delayInit) {
History.init();
}
return History;
}); | shovemedia/GigaJS | js/src/lib/History.js | JavaScript | mit | 71,024 |
<?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '« পূর্ববর্তী',
'next' => 'পরবর্তী »',
];
| iluminar/goodwork | resources/lang/bn/pagination.php | PHP | mit | 575 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SamLu.RegularExpression.Extend
{
/// <summary>
/// 包含所有正则复数分支的分支的集合。
/// </summary>
/// <typeparam name="T">正则接受的对象的类型。</typeparam>
public class RegexMultiBranchBranchCollection<T> : IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>, ICollection<RegexMultiBranchBranch<T>>
{
private IDictionary<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>> innerDic;
/// <summary>
/// 初始化 <see cref="RegexMultiBranchBranchCollection{T}"/> 类的新实例。
/// </summary>
public RegexMultiBranchBranchCollection() =>
this.innerDic = new Dictionary<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>>();
public RegexMultiBranchBranchCollection(IEnumerable<RegexMultiBranchBranch<T>> branches) :
this((branches ?? throw new ArgumentNullException(nameof(branches)))
.ToDictionary(branch => branch.Predicate)
)
{ }
public RegexMultiBranchBranchCollection(IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>> dictionary) :
this((dictionary ?? throw new ArgumentNullException(nameof(dictionary)))
.ToDictionary(
(pair => pair.Key),
(pair => new RegexMultiBranchBranch<T>(pair.Key, pair.Value))
)
)
{ }
protected RegexMultiBranchBranchCollection(IDictionary<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>> dictionary) =>
this.innerDic = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
public RegexObject<T> this[RegexMultiBranchBranchPredicate<T> key]
{
get => this.innerDic[key].Pattern;
set => this.innerDic[key].Pattern = value;
}
#region Predicates
/// <summary>
/// 获取 <see cref="RegexMultiBranchBranchCollection{T}"/> 的检测条件集合。
/// </summary>
public ICollection<RegexMultiBranchBranchPredicate<T>> Predicates => this.innerDic.Keys;
ICollection<RegexMultiBranchBranchPredicate<T>> IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>.Keys => this.Predicates;
#endregion
#region Patterns
/// <summary>
/// 获取 <see cref="RegexMultiBranchBranchCollection{T}"/> 的正则模式集合。
/// </summary>
public ICollection<RegexObject<T>> Patterns => new ReadOnlyCollection<RegexObject<T>>(this.innerDic.Values.Select(branch => branch.Pattern).ToList());
ICollection<RegexObject<T>> IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>.Values => this.Patterns;
#endregion
/// <summary>
/// 获取 <see cref="RegexMultiBranchBranchCollection{T}"/> 包含的元素数。
/// </summary>
public int Count => this.innerDic.Count;
#region IsReadOnly
bool ICollection<RegexMultiBranchBranch<T>>.IsReadOnly => this.innerDic.IsReadOnly;
bool ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.IsReadOnly => this.innerDic.IsReadOnly;
#endregion
#region Add
public void Add(RegexMultiBranchBranchPredicate<T> key, RegexObject<T> value) =>
this.innerDic.Add(key, new RegexMultiBranchBranch<T>(key, value));
public void Add(RegexMultiBranchBranch<T> branch) =>
this.innerDic.Add(branch.Predicate, branch);
void ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.Add(KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>> item) =>
this.Add(item.Key, item.Value);
#endregion
public void Clear() => this.innerDic.Clear();
#region Contains
public bool Contains(RegexMultiBranchBranch<T> branch)
{
if (branch == null) throw new ArgumentNullException(nameof(branch));
return this.ContainsPredicate(branch.Predicate) &&
EqualityComparer<RegexMultiBranchBranch<T>>.Default.Equals(branch, this.innerDic[branch.Predicate]);
}
bool ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.Contains(KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>> item) =>
this.ContainsPredicate(item.Key) && EqualityComparer<RegexObject<T>>.Default.Equals(this[item.Key], item.Value);
#endregion
#region ContainsPredicate
public bool ContainsPredicate(RegexMultiBranchBranchPredicate<T> predicate) =>
this.innerDic.ContainsKey(predicate);
bool IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>.ContainsKey(RegexMultiBranchBranchPredicate<T> key) =>
this.ContainsPredicate(key);
#endregion
#region CopyTo
public void CopyTo(RegexMultiBranchBranch<T>[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, $"{nameof(arrayIndex)} 的值小于 0 。");
if (array.Length - arrayIndex < this.Count) throw new ArgumentException($"源 {typeof(RegexMultiBranchBranchPredicate<T>).FullName} 中的元素数目大于从目标 {nameof(array)} 的 {nameof(arrayIndex)} 从头到尾的可用空间。");
var pairArray = new KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>>[array.Length];
this.innerDic.CopyTo(pairArray, arrayIndex);
for (int i = arrayIndex; i < array.Length; i++)
array[i] = new RegexMultiBranchBranch<T>(pairArray[i].Key, pairArray[i].Value.Pattern);
}
void ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.CopyTo(KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, $"{nameof(arrayIndex)} 的值小于 0 。");
if (array.Length - arrayIndex < this.Count) throw new ArgumentException($"源 {typeof(RegexMultiBranchBranchPredicate<T>).FullName} 中的元素数目大于从目标 {nameof(array)} 的 {nameof(arrayIndex)} 从头到尾的可用空间。");
var pairArray = new KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>>[array.Length];
this.innerDic.CopyTo(pairArray, arrayIndex);
for (int i = arrayIndex; i < array.Length; i++)
array[i] = new KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>(pairArray[i].Key, pairArray[i].Value.Pattern);
}
#endregion
#region GetEnumerator
/// <summary>
/// 返回一个循环访问集合的枚举器。
/// </summary>
/// <returns>用于循环访问集合的枚举数。</returns>
public IEnumerator<RegexMultiBranchBranch<T>> GetEnumerator()
{
var enumerator = this.innerDic.GetEnumerator();
while (enumerator.MoveNext())
{
var current = enumerator.Current;
yield return new RegexMultiBranchBranch<T>(current.Key, current.Value.Pattern);
}
}
IEnumerator<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>> IEnumerable<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.GetEnumerator()
{
var enumerator = this.innerDic.GetEnumerator();
while (enumerator.MoveNext())
{
var current = enumerator.Current;
yield return new KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>(current.Key, current.Value.Pattern);
}
}
#endregion
#region
public bool Remove(RegexMultiBranchBranchPredicate<T> key) => this.innerDic.Remove(key);
public bool Remove(RegexMultiBranchBranch<T> branch)
{
if (branch == null) throw new ArgumentNullException(nameof(branch));
if (this.Contains(branch))
{
this.Remove(branch.Predicate);
return true;
}
else return false;
}
bool ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.Remove(KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>> item)
{
if (((ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>)this).Contains(item))
{
this.Remove(item.Key);
return true;
}
else return false;
}
#endregion
public bool TryGetValue(RegexMultiBranchBranchPredicate<T> key, out RegexObject<T> value)
{
if (this.ContainsPredicate(key))
{
value = this[key];
return true;
}
else
{
value = null;
return false;
}
}
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
}
| lufengfan/SamLu.RegularExpression | src/SamLu.RegularExpression/Extend/RegexMultiBranchBranchCollection.cs | C# | mit | 9,630 |
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Igor Deplano
*
* 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.
*******************************************************************************/
package it.polito.ai.polibox.web.controllers.authentication;
import it.polito.ai.polibox.persistency.model.DeviceLogin;
import it.polito.ai.polibox.persistency.model.dao.DeviceLoginDao;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* questo filtro si occupa di autenticare ogni richiesta che viene fatta per il
* servizio rest.
*
* @author "Igor Deplano"
*
*/
@Component("customSecurityAuthenticationInterceptor")
public class CustomSecurityAuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private DeviceLoginDao deviceLoginDao;
public CustomSecurityAuthenticationInterceptor() {
}
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
DeviceLogin d=deviceLoginDao.authenticateDevice(Integer.parseInt(request.getHeader("user")),
Integer.parseInt(request.getHeader("device")),
request.getHeader("password"));
if(d!=null){
if(d.getUser()==Integer.parseInt(request.getHeader("user")))
return true;
}
return false;
}
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
public DeviceLoginDao getDeviceLoginDao() {
return deviceLoginDao;
}
public void setDeviceLoginDao(DeviceLoginDao deviceLoginDao) {
this.deviceLoginDao = deviceLoginDao;
}
}
| IDepla/polibox | src/main/java/it/polito/ai/polibox/web/controllers/authentication/CustomSecurityAuthenticationInterceptor.java | Java | mit | 3,118 |
//****************************************************************************
// Fichier: GridHelp.cpp
// Classe: CGridHelp
// Usage:
//
// To use CGridHelp. There are 3 steps:
// 1) initialization of the DLL with the method : Initialize
// 2) Open a grid and used it :
// Open
// GetValue
// GetNbCols
// GetNbRows
// 3) Close de grid: Close
//
//****************************************************************************
// 03-04-2006 Rémi Saint-Amant Initial version
//****************************************************************************
#include "stdafx.h"
#include <crtdbg.h>
#include <windows.h>
#include "Basic/UtilStd.h"
#include "ModelBase/GridHelp.h"
namespace WBSF
{
//****************************************************************************
// Summary: Constructor
//
// Description: To Create and initialize an object
//
// Input:
//
// Output:
//
// Note:
//****************************************************************************
CGridHelp::CGridHelp()
{
m_hDll = NULL;
m_OpenFunction = NULL;
m_CloseFunction = NULL;
m_GetNbColsFunction = NULL;
m_GetNbRowsFunction = NULL;
m_GetValueFunction = NULL;
m_GetValueLatLonFunction = NULL;
}
//****************************************************************************
// Summary: Destructor
//
// Description: Destroy and clean memory
//
// Input:
//
// Output:
//
// Note:
//****************************************************************************
CGridHelp::~CGridHelp()
{
if (m_hDll)
{
FreeLibrary((HMODULE)m_hDll);
m_hDll = NULL;
}
m_OpenFunction = NULL;
m_GetNbColsFunction = NULL;
m_GetNbRowsFunction = NULL;
m_GetValueFunction = NULL;
m_GetValueLatLonFunction = NULL;
m_CloseFunction = NULL;
}
//****************************************************************************
// Summary: initialize the class
//
// Description: initialize the dll with file path
//
// Input: DLLFilePath : the file path of the dll (tempGenLib.dll)
//
// Output: ERMsg : error message
//
// Note:
//****************************************************************************
ERMsg CGridHelp::Initialize(const char* DLLFilePath)
{
ERMsg message;
if (m_hDll)
{
//if a dll is loaded : free
FreeLibrary((HMODULE)m_hDll);
m_hDll = NULL;
}
//load dll
m_hDll = LoadLibraryW(convert(DLLFilePath).c_str());
if (m_hDll != NULL)
{
//if loaded : load function
m_OpenFunction = (OpenFunction)GetProcAddress((HMODULE)m_hDll, "Open");
m_CloseFunction = (CloseFunction)GetProcAddress((HMODULE)m_hDll, "Close");
m_GetNbColsFunction = (GetNbColsFunction)GetProcAddress((HMODULE)m_hDll, "GetNbCols");
m_GetNbRowsFunction = (GetNbRowsFunction)GetProcAddress((HMODULE)m_hDll, "GetNbRows");
m_GetValueFunction = (GetValueFunction)GetProcAddress((HMODULE)m_hDll, "GetValue");
m_GetValueLatLonFunction = (GetValueLatLonFunction)GetProcAddress((HMODULE)m_hDll, "GetValueLatLon");
}
else
{
message.asgType(ERMsg::ERREUR);
message.ajoute("error");
}
return message;
}
//****************************************************************************
// Summary: Open a grid
//
// Description: Open a grid for reading
//
// Input: filePath : the file path of the grid
//
// Output: ERMsg : error message
//
// Note:
//****************************************************************************
ERMsg CGridHelp::Open(const char* filePath)
{
_ASSERTE(m_OpenFunction != NULL);
ERMsg message;
char messageOut[1024] = { 0 };
if (!m_OpenFunction(filePath, messageOut))
{
message.asgType(ERMsg::ERREUR);
message.ajoute(messageOut);
}
return message;
}
//****************************************************************************
// Summary: Close a grid
//
// Description: Close a grid
//
// Input:
//
// Output:
//
// Note:
//****************************************************************************
void CGridHelp::Close()
{
_ASSERTE(m_CloseFunction != NULL);
m_CloseFunction();
}
//****************************************************************************
// Summary: Get the number of columns
//
// Description: Get the number of columns of the open grid
//
// Input:
//
// Output: the number of cols
//
// Note:
//****************************************************************************
long CGridHelp::GetNbCols()
{
_ASSERTE(m_GetNbColsFunction != NULL);
ERMsg message;
return m_GetNbColsFunction();
}
//****************************************************************************
// Summary: Get the number of rows
//
// Description: Get the number of rows of the open grid
//
// Input:
//
// Output: the number of rows
//
// Note:
//****************************************************************************
long CGridHelp::GetNbRows()
{
_ASSERTE(m_GetNbRowsFunction != NULL);
return m_GetNbRowsFunction();
}
//****************************************************************************
// Summary: Get the values
//
// Description: Get the value of a cell at the position col, row
//
// Input: col: the columns
// row: the rows
//
// Output: The value of the cell
//
// Note:
//
//****************************************************************************
double CGridHelp::GetValue(long col, long row)
{
_ASSERTE(m_GetValueFunction != NULL);
return m_GetValueFunction(col, row);
}
//****************************************************************************
// Summary: Get the values
//
// Description: Get the value of a cell at the position lat lon in decimal degrre
//
// Input: lat: latitude in degree of the cell. Negatif for southern coord.
// lon: longitude in degree of the cell. Negatif for western coord.
//
// Output: The value of the cell
//
// Note: ever if the grid is projected, the coordinate are always in degree
//
//****************************************************************************
double CGridHelp::GetValueLatLon(const double& lat, const double& lon)
{
_ASSERTE(m_GetValueLatLonFunction != NULL);
return m_GetValueLatLonFunction(lat, lon);
}
} | RNCan/WeatherBasedSimulationFramework | wbs/src/ModelBase/GridHelp.cpp | C++ | mit | 6,502 |
import logging
import time
import os
from fuocore.models import (
BaseModel,
SongModel,
LyricModel,
PlaylistModel,
AlbumModel,
ArtistModel,
SearchModel,
UserModel,
)
from .provider import provider
logger = logging.getLogger(__name__)
MUSIC_LIBRARY_PATH = os.path.expanduser('~') + '/Music'
class NBaseModel(BaseModel):
# FIXME: remove _detail_fields and _api to Meta
_api = provider.api
class Meta:
allow_get = True
provider = provider
class NSongModel(SongModel, NBaseModel):
@classmethod
def get(cls, identifier):
data = cls._api.song_detail(int(identifier))
song, _ = NeteaseSongSchema(strict=True).load(data)
return song
@classmethod
def list(cls, identifiers):
song_data_list = cls._api.songs_detail(identifiers)
songs = []
for song_data in song_data_list:
song, _ = NeteaseSongSchema(strict=True).load(song_data)
songs.append(song)
return songs
def _refresh_url(self):
"""刷新获取 url,失败的时候返回空而不是 None"""
songs = self._api.weapi_songs_url([int(self.identifier)])
if songs and songs[0]['url']:
self.url = songs[0]['url']
else:
self.url = ''
def _find_in_local(self):
# TODO: make this a API in SongModel
path = os.path.join(MUSIC_LIBRARY_PATH, self.filename)
if os.path.exists(path):
logger.debug('find local file for {}'.format(self))
return path
return None
# NOTE: if we want to override model attribute, we must
# implement both getter and setter.
@property
def url(self):
"""
We will always check if this song file exists in local library,
if true, we return the url of the local file.
.. note::
As netease song url will be expired after a period of time,
we can not use static url here. Currently, we assume that the
expiration time is 20 minutes, after the url expires, it
will be automaticly refreshed.
"""
local_path = self._find_in_local()
if local_path:
return local_path
if not self._url:
self._refresh_url()
elif time.time() > self._expired_at:
logger.info('song({}) url is expired, refresh...'.format(self))
self._refresh_url()
return self._url
@url.setter
def url(self, value):
self._expired_at = time.time() + 60 * 20 * 1 # 20 minutes
self._url = value
@property
def lyric(self):
if self._lyric is not None:
assert isinstance(self._lyric, LyricModel)
return self._lyric
data = self._api.get_lyric_by_songid(self.identifier)
lrc = data.get('lrc', {})
lyric = lrc.get('lyric', '')
self._lyric = LyricModel(
identifier=self.identifier,
content=lyric
)
return self._lyric
@lyric.setter
def lyric(self, value):
self._lyric = value
class NAlbumModel(AlbumModel, NBaseModel):
@classmethod
def get(cls, identifier):
album_data = cls._api.album_infos(identifier)
if album_data is None:
return None
album, _ = NeteaseAlbumSchema(strict=True).load(album_data)
return album
@property
def desc(self):
if self._desc is None:
self._desc = self._api.album_desc(self.identifier)
return self._desc
@desc.setter
def desc(self, value):
self._desc = value
class NArtistModel(ArtistModel, NBaseModel):
@classmethod
def get(cls, identifier):
artist_data = cls._api.artist_infos(identifier)
artist = artist_data['artist']
artist['songs'] = artist_data['hotSongs'] or []
artist, _ = NeteaseArtistSchema(strict=True).load(artist)
return artist
@property
def desc(self):
if self._desc is None:
self._desc = self._api.artist_desc(self.identifier)
return self._desc
@desc.setter
def desc(self, value):
self._desc = value
class NPlaylistModel(PlaylistModel, NBaseModel):
class Meta:
fields = ('uid')
@classmethod
def get(cls, identifier):
data = cls._api.playlist_detail(identifier)
playlist, _ = NeteasePlaylistSchema(strict=True).load(data)
return playlist
def add(self, song_id, allow_exist=True):
rv = self._api.op_music_to_playlist(song_id, self.identifier, 'add')
if rv == 1:
song = NSongModel.get(song_id)
self.songs.append(song)
return True
elif rv == -1:
return True
return False
def remove(self, song_id, allow_not_exist=True):
rv = self._api.op_music_to_playlist(song_id, self.identifier, 'del')
if rv != 1:
return False
# XXX: make it O(1) if you want
for song in self.songs:
if song.identifier == song_id:
self.songs.remove(song)
return True
class NSearchModel(SearchModel, NBaseModel):
pass
class NUserModel(UserModel, NBaseModel):
class Meta:
fields = ('cookies', )
fields_no_get = ('cookies', )
@classmethod
def get(cls, identifier):
user = {'id': identifier}
user_brief = cls._api.user_brief(identifier)
user.update(user_brief)
playlists = cls._api.user_playlists(identifier)
user['playlists'] = []
user['fav_playlists'] = []
for pl in playlists:
if pl['userId'] == identifier:
user['playlists'].append(pl)
else:
user['fav_playlists'].append(pl)
user, _ = NeteaseUserSchema(strict=True).load(user)
return user
def search(keyword, **kwargs):
_songs = provider.api.search(keyword)
id_song_map = {}
songs = []
if _songs:
for song in _songs:
id_song_map[str(song['id'])] = song
schema = NeteaseSongSchema(strict=True)
s, _ = schema.load(song)
songs.append(s)
return NSearchModel(q=keyword, songs=songs)
# import loop
from .schemas import (
NeteaseSongSchema,
NeteaseAlbumSchema,
NeteaseArtistSchema,
NeteasePlaylistSchema,
NeteaseUserSchema,
) # noqa
| cosven/feeluown-core | fuocore/netease/models.py | Python | mit | 6,421 |
import deepFreeze from 'deep-freeze';
import article_details from '../../app/assets/javascripts/reducers/article_details';
import { RECEIVE_ARTICLE_DETAILS } from '../../app/assets/javascripts/constants/article_details';
import '../testHelper';
describe('article_details reducer', () => {
it('Should return initial state if no action type matches', () => {
const mockAction = {
type: 'NO_TYPE'
};
const initialState = {};
deepFreeze(initialState);
const result = article_details(undefined, mockAction);
expect(result).to.deep.eq(initialState);
});
it('should reutrn a new state if action type is RECEIVE_ARTICLE_DETAILS', () => {
const mockAction = {
type: RECEIVE_ARTICLE_DETAILS,
articleId: 586,
data: {
article_details: 'best article ever'
}
};
const expectedState = {
586: 'best article ever'
};
expect(article_details(undefined, mockAction)).to.deep.eq(expectedState);
});
});
| sejalkhatri/WikiEduDashboard | test/reducers/article_details.spec.js | JavaScript | mit | 981 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kirppu_project.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| jlaunonen/kirppu | manage.py | Python | mit | 257 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2.Array_Elements_Egual_To_Their_Index
{
class arrElementEgualIndex
{
static void Main(string[] args)
{
int[] array = Console.ReadLine().Split(' ')
.Select(int.Parse).ToArray();
for (int i = 0; i < array.Length; i++)
{
if (array[i] == i)
{
Console.Write(array[i] + " ");
}
}
Console.WriteLine();
}
}
}
| NedkoNedevv/Fundamentals | Arrays - More Exercises/2.Array Elements Egual To Their Index/arrElementEgualIndex.cs | C# | mit | 613 |
extern "C"
{
#include "lualib.h"
#include "lauxlib.h"
}
#include "tconstant.h"
int main (void)
{
int tolua_tconstant_open (lua_State*);
lua_State* L = lua_open();
luaL_openlibs(L);
tolua_tconstant_open(L);
luaL_dofile(L,"tconstant.lua");
lua_close(L);
return 0;
}
| drupalhunter-team/TrackMonitor | ExternalComponents/Tolua/src/tests/tconstant.cpp | C++ | mit | 278 |
require 'test_helper'
class ResubmitTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| garyhsieh/mturk-survey | test/unit/resubmit_test.rb | Ruby | mit | 122 |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IWorkbookFunctionsMultiNomialRequestBuilder.
/// </summary>
public partial interface IWorkbookFunctionsMultiNomialRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IWorkbookFunctionsMultiNomialRequest Request(IEnumerable<Option> options = null);
}
}
| garethj-msft/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsMultiNomialRequestBuilder.cs | C# | mit | 1,006 |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using JigLibX.Vehicles;
using JigLibX.Collision;
namespace OurCity.PhysicObjects
{
class CarObject : PhysicObject
{
private Car car;
private Model wheel;
public CarObject(ConceptGameScreen game, Model model, Model wheels, bool FWDrive,
bool RWDrive,
float maxSteerAngle,
float steerRate,
float wheelSideFriction,
float wheelFwdFriction,
float wheelTravel,
float wheelRadius,
float wheelZOffset,
float wheelRestingFrac,
float wheelDampingFrac,
int wheelNumRays,
float driveTorque,
float gravity)
: base(game, model)
{
car = new Car(FWDrive, RWDrive, maxSteerAngle, steerRate,
wheelSideFriction, wheelFwdFriction, wheelTravel, wheelRadius,
wheelZOffset, wheelRestingFrac, wheelDampingFrac,
wheelNumRays, driveTorque, gravity);
this.body = car.Chassis.Body;
this.collision = car.Chassis.Skin;
this.wheel = wheels;
SetCarMass(100.0f);
}
private void DrawWheel(Wheel wh, bool rotated)
{
Camera camera = GameplayScreen.Camera;
foreach (ModelMesh mesh in wheel.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
float steer = wh.SteerAngle;
Matrix rot;
if (rotated) rot = Matrix.CreateRotationY(MathHelper.ToRadians(180.0f));
else rot = Matrix.Identity;
effect.World = rot * Matrix.CreateRotationZ(MathHelper.ToRadians(-wh.AxisAngle)) * // rotate the wheels
Matrix.CreateRotationY(MathHelper.ToRadians(steer)) *
Matrix.CreateTranslation(wh.Pos + wh.Displacement * wh.LocalAxisUp) * car.Chassis.Body.Orientation * // oritentation of wheels
Matrix.CreateTranslation(car.Chassis.Body.Position); // translation
effect.View = camera.View;
effect.Projection = camera.Projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
public override void Draw(GameTime gameTime)
{
DrawWheel(car.Wheels[0], true);
DrawWheel(car.Wheels[1], true);
DrawWheel(car.Wheels[2], false);
DrawWheel(car.Wheels[3], false);
base.Draw(gameTime);
}
public Car Car
{
get { return this.car; }
}
private void SetCarMass(float mass)
{
body.Mass = mass;
Vector3 min, max;
car.Chassis.GetDims(out min, out max);
Vector3 sides = max - min;
float Ixx = (1.0f / 12.0f) * mass * (sides.Y * sides.Y + sides.Z * sides.Z);
float Iyy = (1.0f / 12.0f) * mass * (sides.X * sides.X + sides.Z * sides.Z);
float Izz = (1.0f / 12.0f) * mass * (sides.X * sides.X + sides.Y * sides.Y);
Matrix inertia = Matrix.Identity;
inertia.M11 = Ixx; inertia.M22 = Iyy; inertia.M33 = Izz;
car.Chassis.Body.BodyInertia = inertia;
car.SetupDefaultWheels();
}
public override void ApplyEffects(BasicEffect effect)
{
//
}
}
}
| mrq-cz/ourcity | OurCity/OurCity/OurCity/PhysicObjects/CarObject.cs | C# | mit | 3,827 |
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_AVATOR_DATADetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Register
{
class _AVATOR_DATARegister : public IRegister
{
public:
void Register() override
{
auto& hook_core = CATFCore::get_instance();
for (auto& r : Detail::_AVATOR_DATA_functions)
hook_core.reg_wrapper(r.pBind, r);
}
};
}; // end namespace Register
END_ATF_NAMESPACE
| goodwinxp/Yorozuya | library/ATF/_AVATOR_DATARegister.hpp | C++ | mit | 679 |
var db = require('../models');
exports.checkItemsList = function (req, res, next) {
var data = {
items: []
};
db.Item.findAll().then(function (results) {
for (var i = 0; i < results.length; i++) {
data.items.push(results[i].dataValues);
}
// console.log(data.items);
console.log('items list controller working');
res.locals.items = data.items;
next();
}).catch(function (error) {
console.log(error);
console.log('items list controller error');
next();
});
};
| yoonslee/project2-game | controllers/itemController.js | JavaScript | mit | 522 |
# -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import properties
from datetime import datetime, date
from ..base_model import BaseModel
class Domain(properties.HasProperties):
"""This represents a full search query."""
OR = 'OR'
AND = 'AND'
def __init__(self, queries=None, join_with=AND):
"""Initialize a domain, with optional queries."""
self.query = []
if queries is not None:
for query in queries:
self.add_query(query, join_with)
@classmethod
def from_tuple(cls, queries):
"""Create a ``Domain`` given a set of complex query tuples.
Args:
queries (iter): An iterator of complex queries. Each iteration
should contain either:
* A data-set compatible with :func:`~domain.Domain.add_query`
* A string to switch the join type
Example::
[('subject', 'Test1'),
'OR',
('subject', 'Test2')',
('subject', 'Test3')',
]
# The above is equivalent to:
# subject:'Test1' OR subject:'Test2' OR subject:'Test3'
[('modified_at', datetime(2017, 01, 01)),
('status', 'active'),
]
# The above is equivalent to:
# modified_at:[2017-01-01T00:00:00Z TO *]
# AND status:"active"
Returns:
Domain: A domain representing the input queries.
"""
domain = cls()
join_with = cls.AND
for query in queries:
if query in [cls.OR, cls.AND]:
join_with = query
else:
domain.add_query(query, join_with)
return domain
def add_query(self, query, join_with=AND):
"""Join a new query to existing queries on the stack.
Args:
query (tuple or list or DomainCondition): The condition for the
query. If a ``DomainCondition`` object is not provided, the
input should conform to the interface defined in
:func:`~.domain.DomainCondition.from_tuple`.
join_with (str): The join string to apply, if other queries are
already on the stack.
"""
if not isinstance(query, DomainCondition):
query = DomainCondition.from_tuple(query)
if len(self.query):
self.query.append(join_with)
self.query.append(query)
def __str__(self):
"""Return a string usable as the query in an API request."""
if not self.query:
return '*'
return '(%s)' % ' '.join([str(q) for q in self.query])
class DomainCondition(properties.HasProperties):
"""This represents one condition of a domain query."""
field = properties.String(
'Field to search on',
required=True,
)
value = properties.String(
'String Value',
required=True,
)
@property
def field_name(self):
"""Return the name of the API field."""
return BaseModel._to_camel_case(self.field)
def __init__(self, field, value, **kwargs):
"""Initialize a new generic query condition.
Args:
field (str): Field name to search on. This should be the
Pythonified name as in the internal models, not the
name as provided in the API e.g. ``first_name`` for
the Customer's first name instead of ``firstName``.
value (mixed): The value of the field.
"""
return super(DomainCondition, self).__init__(
field=field, value=value, **kwargs
)
@classmethod
def from_tuple(cls, query):
"""Create a condition from a query tuple.
Args:
query (tuple or list): Tuple or list that contains a query domain
in the format of ``(field_name, field_value,
field_value_to)``. ``field_value_to`` is only applicable in
the case of a date search.
Returns:
DomainCondition: An instance of a domain condition. The specific
type will depend on the data type of the first value provided
in ``query``.
"""
field, query = query[0], query[1:]
try:
cls = TYPES[type(query[0])]
except KeyError:
# We just fallback to the base class if unknown type.
pass
return cls(field, *query)
def __str__(self):
"""Return a string usable as a query part in an API request."""
return '%s:"%s"' % (self.field_name, self.value)
class DomainConditionBoolean(DomainCondition):
"""This represents an integer query."""
value = properties.Bool(
'Boolean Value',
required=True,
)
def __str__(self):
"""Return a string usable as a query part in an API request."""
value = 'true' if self.value else 'false'
return '%s:%s' % (self.field_name, value)
class DomainConditionInteger(DomainCondition):
"""This represents an integer query."""
value = properties.Integer(
'Integer Value',
required=True,
)
def __str__(self):
"""Return a string usable as a query part in an API request."""
return '%s:%d' % (self.field_name, self.value)
class DomainConditionDateTime(DomainCondition):
"""This represents a date time query."""
value = properties.DateTime(
'Date From',
required=True,
)
value_to = properties.DateTime(
'Date To',
)
def __init__(self, field, value_from, value_to=None):
"""Initialize a new datetime query condition.
Args:
field (str): Field name to search on. This should be the
Pythonified name as in the internal models, not the
name as provided in the API e.g. ``first_name`` for
the Customer's first name instead of ``firstName``.
value_from (date or datetime): The start value of the field.
value_to (date or datetime, optional): The ending value for
the field. If omitted, will search to now.
"""
return super(DomainConditionDateTime, self).__init__(
field=field, value=value_from, value_to=value_to,
)
def __str__(self):
"""Return a string usable as a query part in an API request."""
value_to = self.value_to.isoformat() if self.value_to else '*'
return '%s:[%sZ TO %sZ]' % (
self.field_name,
self.value.isoformat(),
value_to,
)
TYPES = {
bool: DomainConditionBoolean,
int: DomainConditionInteger,
date: DomainConditionDateTime,
datetime: DomainConditionDateTime,
}
__all__ = [
'Domain',
'DomainCondition',
'DomainConditionBoolean',
'DomainConditionDateTime',
'DomainConditionInteger',
]
| LasLabs/python-helpscout | helpscout/domain/__init__.py | Python | mit | 7,131 |
<?php
/**
* This is core configuration file.
*
* Use it to configure core behavior of Cake.
*
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Config
* @since CakePHP(tm) v 0.2.9
*/
/**
* CakePHP Debug Level:
*
* Production Mode:
* 0: No error messages, errors, or warnings shown. Flash messages redirect.
*
* Development Mode:
* 1: Errors and warnings shown, model caches refreshed, flash messages halted.
* 2: As in 1, but also with full debug messages and SQL output.
*
* In production mode, flash messages redirect after a time interval.
* In development mode, you need to click the flash message to continue.
*/
Configure::write('debug', 2);
/**
* Configure the Error handler used to handle errors for your application. By default
* ErrorHandler::handleError() is used. It will display errors using Debugger, when debug > 0
* and log errors with CakeLog when debug = 0.
*
* Options:
*
* - `handler` - callback - The callback to handle errors. You can set this to any callable type,
* including anonymous functions.
* Make sure you add App::uses('MyHandler', 'Error'); when using a custom handler class
* - `level` - integer - The level of errors you are interested in capturing.
* - `trace` - boolean - Include stack traces for errors in log files.
*
* @see ErrorHandler for more information on error handling and configuration.
*/
Configure::write('Error', array(
'handler' => 'ErrorHandler::handleError',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
/**
* Configure the Exception handler used for uncaught exceptions. By default,
* ErrorHandler::handleException() is used. It will display a HTML page for the exception, and
* while debug > 0, framework errors like Missing Controller will be displayed. When debug = 0,
* framework errors will be coerced into generic HTTP errors.
*
* Options:
*
* - `handler` - callback - The callback to handle exceptions. You can set this to any callback type,
* including anonymous functions.
* Make sure you add App::uses('MyHandler', 'Error'); when using a custom handler class
* - `renderer` - string - The class responsible for rendering uncaught exceptions. If you choose a custom class you
* should place the file for that class in app/Lib/Error. This class needs to implement a render method.
* - `log` - boolean - Should Exceptions be logged?
* - `skipLog` - array - list of exceptions to skip for logging. Exceptions that
* extend one of the listed exceptions will also be skipped for logging.
* Example: `'skipLog' => array('NotFoundException', 'UnauthorizedException')`
*
* @see ErrorHandler for more information on exception handling and configuration.
*/
Configure::write('Exception', array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'ExceptionRenderer',
'log' => true
));
/**
* Application wide charset encoding
*/
Configure::write('App.encoding', 'UTF-8');
/**
* To configure CakePHP *not* to use mod_rewrite and to
* use CakePHP pretty URLs, remove these .htaccess
* files:
*
* /.htaccess
* /app/.htaccess
* /app/webroot/.htaccess
*
* And uncomment the App.baseUrl below. But keep in mind
* that plugin assets such as images, CSS and JavaScript files
* will not work without URL rewriting!
* To work around this issue you should either symlink or copy
* the plugin assets into you app's webroot directory. This is
* recommended even when you are using mod_rewrite. Handling static
* assets through the Dispatcher is incredibly inefficient and
* included primarily as a development convenience - and
* thus not recommended for production applications.
*/
//Configure::write('App.baseUrl', env('SCRIPT_NAME'));
/**
* To configure CakePHP to use a particular domain URL
* for any URL generation inside the application, set the following
* configuration variable to the http(s) address to your domain. This
* will override the automatic detection of full base URL and can be
* useful when generating links from the CLI (e.g. sending emails)
*/
//Configure::write('App.fullBaseUrl', 'http://example.com');
/**
* Web path to the public images directory under webroot.
* If not set defaults to 'img/'
*/
//Configure::write('App.imageBaseUrl', 'img/');
/**
* Web path to the CSS files directory under webroot.
* If not set defaults to 'css/'
*/
//Configure::write('App.cssBaseUrl', 'css/');
/**
* Web path to the js files directory under webroot.
* If not set defaults to 'js/'
*/
//Configure::write('App.jsBaseUrl', 'js/');
/**
* Uncomment the define below to use CakePHP prefix routes.
*
* The value of the define determines the names of the routes
* and their associated controller actions:
*
* Set to an array of prefixes you want to use in your application. Use for
* admin or other prefixed routes.
*
* Routing.prefixes = array('admin', 'manager');
*
* Enables:
* `admin_index()` and `/admin/controller/index`
* `manager_index()` and `/manager/controller/index`
*
*/
//Configure::write('Routing.prefixes', array('admin'));
/**
* Turn off all caching application-wide.
*
*/
//Configure::write('Cache.disable', true);
/**
* Enable cache checking.
*
* If set to true, for view caching you must still use the controller
* public $cacheAction inside your controllers to define caching settings.
* You can either set it controller-wide by setting public $cacheAction = true,
* or in each action using $this->cacheAction = true.
*
*/
//Configure::write('Cache.check', true);
/**
* Enable cache view prefixes.
*
* If set it will be prepended to the cache name for view file caching. This is
* helpful if you deploy the same application via multiple subdomains and languages,
* for instance. Each version can then have its own view cache namespace.
* Note: The final cache file name will then be `prefix_cachefilename`.
*/
//Configure::write('Cache.viewPrefix', 'prefix');
/**
* Session configuration.
*
* Contains an array of settings to use for session configuration. The defaults key is
* used to define a default preset to use for sessions, any settings declared here will override
* the settings of the default config.
*
* ## Options
*
* - `Session.cookie` - The name of the cookie to use. Defaults to 'CAKEPHP'
* - `Session.timeout` - The number of minutes you want sessions to live for. This timeout is handled by CakePHP
* - `Session.cookieTimeout` - The number of minutes you want session cookies to live for.
* - `Session.checkAgent` - Do you want the user agent to be checked when starting sessions? You might want to set the
* value to false, when dealing with older versions of IE, Chrome Frame or certain web-browsing devices and AJAX
* - `Session.defaults` - The default configuration set to use as a basis for your session.
* There are four builtins: php, cake, cache, database.
* - `Session.handler` - Can be used to enable a custom session handler. Expects an array of callables,
* that can be used with `session_save_handler`. Using this option will automatically add `session.save_handler`
* to the ini array.
* - `Session.autoRegenerate` - Enabling this setting, turns on automatic renewal of sessions, and
* sessionids that change frequently. See CakeSession::$requestCountdown.
* - `Session.ini` - An associative array of additional ini values to set.
*
* The built in defaults are:
*
* - 'php' - Uses settings defined in your php.ini.
* - 'cake' - Saves session files in CakePHP's /tmp directory.
* - 'database' - Uses CakePHP's database sessions.
* - 'cache' - Use the Cache class to save sessions.
*
* To define a custom session handler, save it at /app/Model/Datasource/Session/<name>.php.
* Make sure the class implements `CakeSessionHandlerInterface` and set Session.handler to <name>
*
* To use database sessions, run the app/Config/Schema/sessions.php schema using
* the cake shell command: cake schema create Sessions
*
*/
Configure::write('Session', array(
'defaults' => 'php'
));
/**
* A random string used in security hashing methods.
*/
Configure::write('Security.salt', '94846d00d3a440ae01a650d0ac5c42e2883e2b31');
/**
* A random numeric string (digits only) used to encrypt/decrypt strings.
*/
Configure::write('Security.cipherSeed', '623431653463303430653263306235');
/**
* Apply timestamps with the last modified time to static assets (js, css, images).
* Will append a query string parameter containing the time the file was modified. This is
* useful for invalidating browser caches.
*
* Set to `true` to apply timestamps when debug > 0. Set to 'force' to always enable
* timestamping regardless of debug value.
*/
//Configure::write('Asset.timestamp', true);
/**
* Compress CSS output by removing comments, whitespace, repeating tags, etc.
* This requires a/var/cache directory to be writable by the web server for caching.
* and /vendors/csspp/csspp.php
*
* To use, prefix the CSS link URL with '/ccss/' instead of '/css/' or use HtmlHelper::css().
*/
//Configure::write('Asset.filter.css', 'css.php');
/**
* Plug in your own custom JavaScript compressor by dropping a script in your webroot to handle the
* output, and setting the config below to the name of the script.
*
* To use, prefix your JavaScript link URLs with '/cjs/' instead of '/js/' or use JsHelper::link().
*/
//Configure::write('Asset.filter.js', 'custom_javascript_output_filter.php');
/**
* The class name and database used in CakePHP's
* access control lists.
*/
Configure::write('Acl.classname', 'DbAcl');
Configure::write('Acl.database', 'default');
/**
* Uncomment this line and correct your server timezone to fix
* any date & time related errors.
*/
//date_default_timezone_set('UTC');
/**
* Cache Engine Configuration
* Default settings provided below
*
* File storage engine.
*
* Cache::config('default', array(
* 'engine' => 'File', //[required]
* 'duration' => 3600, //[optional]
* 'probability' => 100, //[optional]
* 'path' => CACHE, //[optional] use system tmp directory - remember to use absolute path
* 'prefix' => 'cake_', //[optional] prefix every cache file with this string
* 'lock' => false, //[optional] use file locking
* 'serialize' => true, //[optional]
* 'mask' => 0664, //[optional]
* ));
*
* APC (http://pecl.php.net/package/APC)
*
* Cache::config('default', array(
* 'engine' => 'Apc', //[required]
* 'duration' => 3600, //[optional]
* 'probability' => 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* ));
*
* Xcache (http://xcache.lighttpd.net/)
*
* Cache::config('default', array(
* 'engine' => 'Xcache', //[required]
* 'duration' => 3600, //[optional]
* 'probability' => 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* 'user' => 'user', //user from xcache.admin.user settings
* 'password' => 'password', //plaintext password (xcache.admin.pass)
* ));
*
* Memcache (http://www.danga.com/memcached/)
*
* Cache::config('default', array(
* 'engine' => 'Memcache', //[required]
* 'duration' => 3600, //[optional]
* 'probability' => 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* 'servers' => array(
* '127.0.0.1:11211' // localhost, default port 11211
* ), //[optional]
* 'persistent' => true, // [optional] set this to false for non-persistent connections
* 'compress' => false, // [optional] compress data in Memcache (slower, but uses less memory)
* ));
*
* Wincache (http://php.net/wincache)
*
* Cache::config('default', array(
* 'engine' => 'Wincache', //[required]
* 'duration' => 3600, //[optional]
* 'probability' => 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* ));
*/
/**
* Configure the cache handlers that CakePHP will use for internal
* metadata like class maps, and model schema.
*
* By default File is used, but for improved performance you should use APC.
*
* Note: 'default' and other application caches should be configured in app/Config/bootstrap.php.
* Please check the comments in bootstrap.php for more info on the cache engines available
* and their settings.
*/
$engine = 'File';
// In development mode, caches should expire quickly.
$duration = '+999 days';
if (Configure::read('debug') > 0) {
$duration = '+10 seconds';
}
// Prefix each application on the same server with a different string, to avoid Memcache and APC conflicts.
$prefix = 'app_';
/**
* Configure the cache used for general framework caching. Path information,
* object listings, and translation cache files are stored with this configuration.
*/
Cache::config('_cake_core_', array(
'engine' => $engine,
'prefix' => $prefix . 'cake_core_',
'path' => CACHE . 'persistent' . DS,
'serialize' => ($engine === 'File'),
'duration' => $duration
));
/**
* Configure the cache for model and datasource caches. This cache configuration
* is used to store schema descriptions, and table listings in connections.
*/
Cache::config('_cake_model_', array(
'engine' => $engine,
'prefix' => $prefix . 'cake_model_',
'path' => CACHE . 'models' . DS,
'serialize' => ($engine === 'File'),
'duration' => $duration
));
| previewict/cakephp-form-builder | app/Config/core.php | PHP | mit | 13,709 |
/*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011-2012
* The Bitcoin Developers 2011-2012
*/
#include <QApplication>
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "walletframe.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "notificator.h"
#include "guiutil.h"
#include "rpcconsole.h"
#include "ui_interface.h"
#include "wallet.h"
#include "init.h"
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QMovie>
#include <QTimer>
#include <QDragEnterEvent>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
#include <QMimeData>
#include <QStyle>
#include <QSettings>
#include <QDesktopWidget>
#include <QListWidget>
#include <iostream>
const QString BitcoinGUI::DEFAULT_WALLET = "~Default";
BitcoinGUI::BitcoinGUI(QWidget *parent) :
QMainWindow(parent),
clientModel(0),
encryptWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
trayIcon(0),
notificator(0),
rpcConsole(0),
prevBlocks(0)
{
restoreWindowGeometry();
setWindowTitle(tr("Woodcoin") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
QApplication::setWindowIcon(QIcon(":icons/bitcoin"));
setWindowIcon(QIcon(":icons/bitcoin"));
#else
setUnifiedTitleAndToolBarOnMac(true);
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
// Create wallet frame and make it the central widget
walletFrame = new WalletFrame(this);
setCentralWidget(walletFrame);
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon();
// Create status bar
statusBar();
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setMinimumWidth(56);
frameBlocks->setMaximumWidth(56);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
labelEncryptionIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
rpcConsole = new RPCConsole(this);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
}
BitcoinGUI::~BitcoinGUI()
{
saveWindowGeometry();
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::instance()->setMainWindow(NULL);
#endif
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a Woodcoin address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Addresses"), this);
addressBookAction->setStatusTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setToolTip(addressBookAction->statusTip());
addressBookAction->setCheckable(true);
addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
tabGroup->addAction(addressBookAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About Woodcoin"), this);
aboutAction->setStatusTip(tr("Show information about Woodcoin"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for Woodcoin"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your Woodcoin addresses to prove you own them"));
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Woodcoin addresses"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addSeparator();
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(openRPCConsoleAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void BitcoinGUI::createToolBars()
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Replace some strings and icons, when using the testnet
if(clientModel->isTestNet())
{
setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
#ifndef Q_OS_MAC
QApplication::setWindowIcon(QIcon(":icons/bitcoin_testnet"));
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
#else
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
#endif
if(trayIcon)
{
// Just attach " [testnet]" to the existing tooltip
trayIcon->setToolTip(trayIcon->toolTip() + QString(" ") + tr("[testnet]"));
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
}
toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Receive and report messages from network/worker thread
connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));
rpcConsole->setClientModel(clientModel);
walletFrame->setClientModel(clientModel);
}
}
bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel)
{
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool BitcoinGUI::setCurrentWallet(const QString& name)
{
return walletFrame->setCurrentWallet(name);
}
void BitcoinGUI::removeAllWallets()
{
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
void BitcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
addressBookAction->setEnabled(enabled);
}
void BitcoinGUI::createTrayIcon()
{
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
trayIcon->setToolTip(tr("Woodcoin client"));
trayIcon->setIcon(QIcon(":/icons/toolbar"));
trayIcon->show();
#endif
notificator = new Notificator(QApplication::applicationName(), trayIcon);
}
void BitcoinGUI::createTrayIconMenu()
{
QMenu *trayIconMenu;
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-Mac OSes)
if (!trayIcon)
return;
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHideAction->trigger();
}
}
#endif
void BitcoinGUI::saveWindowGeometry()
{
QSettings settings;
settings.setValue("nWindowPos", pos());
settings.setValue("nWindowSize", size());
}
void BitcoinGUI::restoreWindowGeometry()
{
QSettings settings;
QPoint pos = settings.value("nWindowPos").toPoint();
QSize size = settings.value("nWindowSize", QSize(850, 550)).toSize();
if (!pos.x() && !pos.y())
{
QRect screen = QApplication::desktop()->screenGeometry();
pos.setX((screen.width()-size.width())/2);
pos.setY((screen.height()-size.height())/2);
}
resize(size);
move(pos);
}
void BitcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::gotoOverviewPage()
{
if (walletFrame) walletFrame->gotoOverviewPage();
}
void BitcoinGUI::gotoHistoryPage()
{
if (walletFrame) walletFrame->gotoHistoryPage();
}
void BitcoinGUI::gotoAddressBookPage()
{
if (walletFrame) walletFrame->gotoAddressBookPage();
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void BitcoinGUI::gotoSendCoinsPage(QString addr)
{
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Woodcoin network", "", count));
}
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
progressBarLabel->setText(tr("Synchronizing with network..."));
break;
case BLOCK_SOURCE_DISK:
progressBarLabel->setText(tr("Importing blocks from disk..."));
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
// Case: not Importing, not Reindexing and no network connection
progressBarLabel->setText(tr("No block source available..."));
break;
}
QString tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
QDateTime currentDate = QDateTime::currentDateTime();
int secs = lastBlockDate.secsTo(currentDate);
if(count < nTotalBlocks)
{
tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks);
}
else
{
tooltip = tr("Processed %1 blocks of transaction history.").arg(count);
}
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60 && count >= nTotalBlocks)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
walletFrame->showOutOfSyncWarning(false);
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
}
else
{
// Represent time from last generated block in human readable text
QString timeBehindText;
if(secs < 48*60*60)
{
timeBehindText = tr("%n hour(s)","",secs/(60*60));
}
else if(secs < 14*24*60*60)
{
timeBehindText = tr("%n day(s)","",secs/(24*60*60));
}
else
{
timeBehindText = tr("%n week(s)","",secs/(7*24*60*60));
}
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
progressBar->setMaximum(1000000000);
progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
labelBlocksIcon->setMovie(syncIconMovie);
if(count != prevBlocks)
syncIconMovie->jumpToNextFrame();
prevBlocks = count;
walletFrame->showOutOfSyncWarning(true);
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)
{
QString strTitle = tr("Woodcoin"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
// Override title based on style
QString msgType;
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
msgType = title; // Use supplied title
}
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
}
else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
}
else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
void BitcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(clientModel)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
QApplication::quit();
}
#endif
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(
this, tr("Confirm transaction fee"), strMessage,
QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address)
{
// On new transaction, make an info balloon
message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(unit, amount, true))
.arg(type)
.arg(address), CClientUIInterface::MSG_INFORMATION);
}
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
int nValidUrisFound = 0;
QList<QUrl> uris = event->mimeData()->urls();
foreach(const QUrl &uri, uris)
{
if (walletFrame->handleURI(uri.toString()))
nValidUrisFound++;
}
// if valid URIs were found
if (nValidUrisFound)
walletFrame->gotoSendCoinsPage();
else
message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Woodcoin address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
}
event->acceptProposedAction();
}
bool BitcoinGUI::eventFilter(QObject *object, QEvent *event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip)
{
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
void BitcoinGUI::handleURI(QString strURI)
{
// URI has to be valid
if (!walletFrame->handleURI(strURI))
message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Woodcoin address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::detectShutdown()
{
if (ShutdownRequested())
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
| woodedlawn/woodcoin | src/qt/bitcoingui.cpp | C++ | mit | 29,694 |
"""
Pylot command line tool
manage.py
Command line tool to manage your application
"""
import argparse
from application import get_config
import application.model as model
from pylot import utils
config = get_config()
NAME = "Pylot Manager"
__version__ = config.APP_VERSION
def setup():
# Create all db
model.db.create_all()
roles = ["user", "admin", "superadmin"]
# Setup the SUPERADMIN
email = config.ADMIN_EMAIL
name = config.ADMIN_NAME
user = model.User.get_by_email(email)
if not user:
model.User.User.new(email=email,
name=name,
role="SUPERADMIN")
def main():
parser = argparse.ArgumentParser(description="%s v.%s" % (NAME, __version__))
parser.add_argument("--setup", help="Setup the system", action="store_true")
parser.add_argument("--upload-static-to-s3", help="Upload all static files to S3", action="store_true")
arg = parser.parse_args()
if arg.setup:
# Default setup
print("Setting up...")
setup()
if arg.upload_static_to_s3:
# Upload static files to s3
import flask_s3
import run_www # Or the main application run file
print("Upload static files to S3")
flask_s3.create_all(run_www.app)
if __name__ == "__main__":
main()
| mardix/pylot | pylot/app_templates/manage.py | Python | mit | 1,343 |
import $ from 'jquery'
import template from './Loadbox.html'
import Mustache from 'mustache'
import img1 from '../../images/load-circle.png'
import img2 from '../../images/load-bg.png'
import img3 from '../../images/logo.png'
import img4 from '../../images/slogan.png'
import img5 from '../../images/panel-bg.jpg'
import img6 from '../../images/button.png'
import img7 from '../../images/leftnav.png'
import img8 from '../../images/intro_1_pic.png'
import img9 from '../../images/intro_2_pic.png'
import img10 from '../../images/intro_3_pic.png'
import img11 from '../../images/intro_1_txt.png'
import img12 from '../../images/intro_2_txt.png'
import img13 from '../../images/intro_3_txt.png'
import img14 from '../../images/intro_4_txt.png'
import img15 from '../../images/intro_5_txt.png'
import img16 from '../../images/bg.jpg'
export default class Loadbox {
constructor(type) {
this.type = type;
}
render() {
let preload = []
switch(this.type) {
case 'landing':
preload = [img1,img2,img3,img4,img5,img6,img7,img8,img9,img10,img11,img12,img13,img14,img15,img16]
break
default:
preload = []
}
$('#preload').html(
Mustache.render(template, {preload: preload})
);
}
} | RainKolwa/goon_cowala_feb | src/components/Loadbox/Index.js | JavaScript | mit | 1,235 |
const postcss = require('postcss');
const fs = require('fs');
const plugin = require('../index');
const pkg = require('../package.json');
/**
* Runs the plugins process function. Tests whether the given input is equal
* to the expected output with the given options.
*
* @param {string} input Input fixture file name.
* @param {object} opts Options to be used by the plugin.
* @return {function}
*/
function run(input, opts = {}) {
const raw = fs.readFileSync(`./test/fixtures/${input}.css`, 'utf8');
const expected = fs.readFileSync(`./test/fixtures/${input}.expected.css`, 'utf8');
return postcss([plugin(opts)]).process(raw, { from: undefined })
.then(result => {
expect(result.css).toEqual(expected);
expect(result.warnings().length).toBe(0);
});
}
it('Should replace strings in comments and styles.', () => {
return run('basic', { data: pkg });
});
it('Should throw a TypeError if invalid pattern is supplied.', () => {
return run('basic', { data: pkg, pattern: '' }).catch(e =>
expect(e).toBeInstanceOf(TypeError)
)
});
it('Should not replace anything in styles when “commentsOnly” option is set to TRUE.', () => {
return run('commentsOnly', { data: pkg, commentsOnly: true });
});
it('Should not replace anything without data', () => {
return run('noChanges');
});
it('Should not change unknown variables', () => {
return run('noChanges', { data: pkg });
});
it('Should work with deep data objects', () => {
return run('deep', { data: { level1: { level2: 'test' } } });
});
it('Should work with a custom RegEx', () => {
return run('otherRegex', { data: pkg, pattern: /%\s?([^\s]+?)\s?%/gi });
});
it('Should work with a custom RegEx object', () => {
return run('basic', { data: pkg, pattern: new RegExp(/{{\s?([^\s]+?)\s?}}/, 'gi') });
});
it('Should work with a custom RegEx string', () => {
return run('basic', { data: pkg, pattern: '{{\\s?([^\\s]+?)\\s?}}' });
});
it('Should work with another custom RegEx string', () => {
return run('otherRegex', { data: pkg, pattern: '%\\s?([^\\s]+?)\\s?%' });
});
it('Should work with empty string values', () => {
return run('empty', { data: { value: '' } });
});
it('Should work with undefined values', () => {
return run('noChanges', { data: { value: undefined } });
});
it('Should work with null values', () => {
return run('noChanges', { data: { value: null } });
});
it('Should work with null data', () => {
return run('noChanges', { data: null });
});
it('Should not replace multiple times', () => {
return run('noDuplicate', {
pattern: /(a)/g,
data: { a: 'abc'}
});
});
it('Should replace strings in selectors', () => {
return run('selectors', {
pattern: /(foo)/g,
data: { 'foo': 'bar' },
});
});
it('Should replace regex to empty in selectors', () => {
return run('regexEmpty', {
pattern: /\[.*\]:delete\s+/gi,
data: { replaceAll: '' }
});
});
it('Should replace regex to single value in selectors', () => {
return run('regexValue', {
pattern: /\[.*\]:delete/gi,
data: { replaceAll: '.newValue' }
});
});
it('Should work with custom Regex string', () => {
return run('customRegexValue', {
pattern: new RegExp(/%replace_me%/, 'gi'),
data: { replaceAll: 'new awesome string :)' }
});
});
it('Should replace properties and values', () => {
return run('replaceProperties', {
pattern: /##\((.*?)\)/g,
data: {
'prop': 'color',
'name': 'basic',
'key': 'dark',
'value': '#9c9c9c'
},
});
});
| gridonic/postcss-replace | test/index.test.js | JavaScript | mit | 3,694 |
<?php
return array (
'id' => 'htc_desire_500_ver1',
'fallback' => 'generic_android_ver4_1',
'capabilities' =>
array (
'uaprof' => 'http://www.htcmms.com.tw/Android/Vodafone/0P3Z11/ua-profile.xml',
'model_name' => 'Desire 500',
'brand_name' => 'HTC',
'release_date' => '2013_august',
'physical_screen_height' => '94',
'physical_screen_width' => '57',
'resolution_width' => '480',
'resolution_height' => '800',
'max_data_rate' => '7200',
),
);
| cuckata23/wurfl-data | data/htc_desire_500_ver1.php | PHP | mit | 489 |
require 'pry'
module Zephyre
class Controller
attr_reader :request
def initialize(env)
@request ||= Rack::Request.new(env)
end
def params
request.params
end
def response(body, status=200, header={})
@response = Rack::Response.new(body, status, header)
end
def get_response
@response
end
def render(*args)
response(render_template(*args), 200, {"Content-Type" => "text/html"})
end
def render_template(view_name, locals = {})
filename = File.join("app", "views", controller_name, "#{view_name}.erb")
# If we find a file, render it, otherwise just render whatever was passed as a string
template = File.file?(filename) ? File.read(filename) : view_name.to_s
vars = {}
instance_variables.each do |var|
key = var.to_s.gsub("@", "").to_sym
vars[key] = instance_variable_get(var)
end
ERB.new(template).result(binding)
end
def controller_name
self.class.to_s.gsub(/Controller$/, "").to_snake_case
end
def dispatch(action)
content = self.send(action)
if get_response
get_response
else
render(action)
get_response
end
end
def self.action(action_name)
-> (env) { self.new(env).dispatch(action_name) }
end
end
end | alexdovzhanyn/zephyre | lib/zephyre/controller.rb | Ruby | mit | 1,246 |
#!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP3, OP_DROP
from binascii import hexlify, unhexlify
from io import BytesIO
import time
import itertools
'''
This test is meant to exercise BIP forks
Connect to a single node.
regtest lock-in with 108/144 block signalling
activation after a further 144 blocks
mine 2 block and save coinbases for later use
mine 141 blocks to transition from DEFINED to STARTED
mine 100 blocks signalling readiness and 44 not in order to fail to change state this period
mine 108 blocks signalling readiness and 36 blocks not signalling readiness (STARTED->LOCKED_IN)
mine a further 143 blocks (LOCKED_IN)
test that enforcement has not triggered (which triggers ACTIVE)
test that enforcement has triggered
'''
class BIP9SoftForksTest(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1']],
binary=[self.options.testbinary])
def run_test(self):
self.test = TestManager(self, self.options.tmpdir)
self.test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
self.test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
tx = CTransaction()
f = BytesIO(unhexlify(rawtx))
tx.deserialize(f)
tx.nVersion = 2
return tx
def sign_transaction(self, node, tx):
signresult = node.signrawtransaction(hexlify(tx.serialize()))
tx = CTransaction()
f = BytesIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def generate_blocks(self, number, version, test_blocks = []):
for i in xrange(number):
block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
block.nVersion = version
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
self.height += 1
return test_blocks
def get_bip9_status(self, key):
info = self.nodes[0].getblockchaininfo()
for row in info['bip9_softforks']:
if row['id'] == key:
return row
raise IndexError ('key:"%s" not found' % key)
def test_BIP(self, bipName, activated_version, invalidate, invalidatePostSignature):
# generate some coins for later
self.coinbase_blocks = self.nodes[0].generate(2)
self.height = 3 # height of the next block to build
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = int(time.time())
assert_equal(self.get_bip9_status(bipName)['status'], 'defined')
# Test 1
# Advance from DEFINED to STARTED
test_blocks = self.generate_blocks(141, 4)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['status'], 'started')
# Test 2
# Fail to achieve LOCKED_IN 100 out of 144 signal bit 1
# using a variety of bits to simulate multiple parallel softforks
test_blocks = self.generate_blocks(50, activated_version) # 0x20000001 (signalling ready)
test_blocks = self.generate_blocks(20, 4, test_blocks) # 0x00000004 (signalling not)
test_blocks = self.generate_blocks(50, activated_version, test_blocks) # 0x20000101 (signalling ready)
test_blocks = self.generate_blocks(24, 4, test_blocks) # 0x20010000 (signalling not)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['status'], 'started')
# Test 3
# 108 out of 144 signal bit 1 to achieve LOCKED_IN
# using a variety of bits to simulate multiple parallel softforks
test_blocks = self.generate_blocks(58, activated_version) # 0x20000001 (signalling ready)
test_blocks = self.generate_blocks(26, 4, test_blocks) # 0x00000004 (signalling not)
test_blocks = self.generate_blocks(50, activated_version, test_blocks) # 0x20000101 (signalling ready)
test_blocks = self.generate_blocks(10, 4, test_blocks) # 0x20010000 (signalling not)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['status'], 'locked_in')
# Test 4
# 143 more version 536870913 blocks (waiting period-1)
test_blocks = self.generate_blocks(143, 4)
yield TestInstance(test_blocks, sync_every_block=False)
assert_equal(self.get_bip9_status(bipName)['status'], 'locked_in')
# Test 5
# Check that the new rule is enforced
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
invalidate(spendtx)
spendtx = self.sign_transaction(self.nodes[0], spendtx)
spendtx.rehash()
invalidatePostSignature(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
block.nVersion = activated_version
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
self.height += 1
yield TestInstance([[block, True]])
assert_equal(self.get_bip9_status(bipName)['status'], 'active')
# Test 6
# Check that the new sequence lock rules are enforced
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
invalidate(spendtx)
spendtx = self.sign_transaction(self.nodes[0], spendtx)
spendtx.rehash()
invalidatePostSignature(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
block.nVersion = 5
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
# Restart all
stop_nodes(self.nodes)
wait_bitcoinds()
shutil.rmtree(self.options.tmpdir)
self.setup_chain()
self.setup_network()
self.test.clear_all_connections()
self.test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
def get_tests(self):
for test in itertools.chain(
self.test_BIP('csv', 536870913, self.sequence_lock_invalidate, self.donothing),
self.test_BIP('csv', 536870913, self.mtp_invalidate, self.donothing),
self.test_BIP('csv', 536870913, self.donothing, self.csv_invalidate)
):
yield test
def donothing(self, tx):
return
def csv_invalidate(self, tx):
'''Modify the signature in vin 0 of the tx to fail CSV
Prepends -1 CSV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP3, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
def sequence_lock_invalidate(self, tx):
'''Modify the nSequence to make it fails once sequence lock rule is activated (high timespan)
'''
tx.vin[0].nSequence = 0x00FFFFFF
tx.nLockTime = 0
def mtp_invalidate(self, tx):
'''Modify the nLockTime to make it fails once MTP rule is activated
'''
# Disable Sequence lock, Activate nLockTime
tx.vin[0].nSequence = 0x90FFFFFF
tx.nLockTime = self.last_block_time
if __name__ == '__main__':
BIP9SoftForksTest().main()
| Kangmo/bitcoin | qa/rpc-tests/bip9-softforks.py | Python | mit | 8,775 |
require 'rails_helper'
RSpec.describe "user_infos/index", type: :view do
before(:each) do
assign(:user_infos, [
UserInfo.create!(
:hometown => "Hometown",
:major => "Major",
:age => "Age",
:description => "MyText",
:show_email => false
),
UserInfo.create!(
:hometown => "Hometown",
:major => "Major",
:age => "Age",
:description => "MyText",
:show_email => false
)
])
end
it "renders a list of user_infos" do
render
assert_select "tr>td", :text => "Hometown".to_s, :count => 2
assert_select "tr>td", :text => "Major".to_s, :count => 2
assert_select "tr>td", :text => "Age".to_s, :count => 2
assert_select "tr>td", :text => "MyText".to_s, :count => 2
assert_select "tr>td", :text => false.to_s, :count => 2
end
end
| code4naropa/ournaropa-forum | spec/views/ournaropa_forum/user_infos/index.html.erb_spec.rb | Ruby | mit | 860 |
package backend
import (
"testing"
"github.com/stretchr/testify/assert"
)
var (
testStartAttributesTestCases = []struct {
A []*StartAttributes
O []*StartAttributes
}{
{
A: []*StartAttributes{
{Language: ""},
{Language: "ruby"},
{Language: "python", Dist: "trusty"},
{Language: "python", Dist: "trusty", Group: "edge"},
{Language: "python", Dist: "frob", Group: "edge", OS: "flob"},
{Language: "python", Dist: "frob", OsxImage: "", Group: "edge", OS: "flob"},
{Language: "python", Dist: "frob", OsxImage: "", Group: "edge", OS: "flob", VMType: "premium"},
},
O: []*StartAttributes{
{Language: "default", Dist: "precise", Group: "stable", OS: "linux", VMType: "default"},
{Language: "ruby", Dist: "precise", Group: "stable", OS: "linux", VMType: "default"},
{Language: "python", Dist: "trusty", Group: "stable", OS: "linux", VMType: "default"},
{Language: "python", Dist: "trusty", Group: "edge", OS: "linux", VMType: "default"},
{Language: "python", Dist: "frob", Group: "edge", OS: "flob", VMType: "default"},
{Language: "python", Dist: "frob", OsxImage: "", Group: "edge", OS: "flob", VMType: "default"},
{Language: "python", Dist: "frob", OsxImage: "", Group: "edge", OS: "flob", VMType: "premium"},
},
},
}
)
func TestStartAttributes(t *testing.T) {
sa := &StartAttributes{}
assert.Equal(t, "", sa.Dist)
assert.Equal(t, "", sa.Group)
assert.Equal(t, "", sa.Language)
assert.Equal(t, "", sa.OS)
assert.Equal(t, "", sa.OsxImage)
assert.Equal(t, "", sa.VMType)
}
func TestStartAttributes_SetDefaults(t *testing.T) {
for _, tc := range testStartAttributesTestCases {
for i, sa := range tc.A {
expected := tc.O[i]
sa.SetDefaults("default", "precise", "stable", "linux", "default")
assert.Equal(t, expected, sa)
}
}
}
| solarce/worker | backend/start_attributes_test.go | GO | mit | 1,823 |
while True:
input_number = int(raw_input())
if input_number == 42:
break
print input_number,
exit() | sandy-8925/codechef | test.py | Python | mit | 112 |
<?php
/*
* This file is part of the zzAgenda package.
*
* (c) OV Corporation SAS <contact@ov-corporation.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ZZFramework\Event;
interface EventSubscriberInterface
{
public function getObservedEvents();
} | croziere/zzAgenda | lib/ZZFramework/Event/EventSubscriberInterface.php | PHP | mit | 374 |
// Import React
import React from "react";
// Import Spectacle Core tags
import {
BlockQuote,
Cite,
CodePane,
Deck,
Heading,
Image,
Link,
Quote,
Slide,
Spectacle,
Text,
Code,
Markdown,
List,
ListItem
} from "spectacle";
import CodeSlide from "spectacle-code-slide";
// Import image preloader util
import preloader from "spectacle/lib/utils/preloader";
// Import theme
import createTheme from "spectacle/lib/themes/default";
// Import custom component
// import Interactive from "../assets/interactive";
// Require CSS
require("normalize.css");
require("spectacle/lib/themes/default/index.css");
const images = {
styleguide: require("../assets/styleguide.png"),
invision: require("../assets/invision_styleguide.png"),
canvas: require("../assets/canvas.png"),
toggle: require("../assets/toggle.png"),
panda: require("../assets/panda.jpg"),
checkbox: require("../assets/checkbox.png"),
happy: require("../assets/happy.jpg"),
button: require("../assets/button.png"),
production: require("../assets/production.png"),
development: require("../assets/development.png"),
initial: require("../assets/initial.png"),
applyTheme: require("../assets/applyTheme.png"),
themed: require("../assets/themed.png"),
zoomed: require("../assets/zoomed.png"),
variableSupport: require("../assets/variableSupport.png"),
holyGrail: require("../assets/holyGrail.jpg"),
microservices: require("../assets/microservices.jpg")
};
preloader(images);
const theme = createTheme({
primary: "#1bb7b6"
}, {
primary: "Lato"
});
export default class Presentation extends React.Component {
render() {
return (
<Spectacle theme={theme}>
<Deck transition={["zoom", "slide"]} transitionDuration={500}>
<Slide transition={["zoom"]} bgColor="primary">
<Heading size={1} fit caps lineHeight={1} textColor="black">
Style Guide Driven Development
</Heading>
<Heading size={1} fit caps>
<i>
<small style={{ paddingRight: "4px", textTransform: "lowercase", fontWeight: "normal" }}>with</small>
</i>
React and CSS Modules
</Heading>
</Slide>
<Slide transition={["slide"]} bgColor="black"
notes={`
A little information about myself: I'm Lead UI Engineer on the UI dev team at Instructure.
We're a cross-functional team made up of designers and engineers and we work closely with
both Engineering and Product Design/UX.
Our goal is to build tools and establish processes that make it easier for our designers and
developers to more easily collaborate.
`}
>
<Heading size={1} fit caps lineHeight={1} textColor="primary">
Jennifer Stern
</Heading>
<Heading size={1} fit caps>
Lead UI Engineer @ <Link href="http://instructure.com" textColor="tertiary">Instructure</Link>
</Heading>
<Text lineHeight={1} textColor="tertiary">
jstern@instructure.com
</Text>
</Slide>
<Slide
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
What's a style guide?
Where application development is concerned:
It's all about better process and communication between designers and developers
(and in a larger org between developers -- reducing duplication of efforts)
To produce a more consistent UX and to be able to build out UI code more efficiently.
`}
>
<Heading size={1} fit caps lineHeight={1}>
What's a Style Guide?
</Heading>
<BlockQuote bgColor="rgba(0, 0, 0, 0.6)" margin="1em 0" padding="1em 1.5em">
<Quote textColor="tertiary" textSize="1em" bold={false} lineHeight={1.5}>
A style guide is a set of standards for the writing and design of documents,
either for general use or for a specific publication, organization, or field....
<Text margin="1em 0px 0px" textSize="1em" textColor="primary" caps bold lineHeight={1.2}>
A style guide establishes and enforces style to improve communication.
</Text>
</Quote>
<Cite textColor="tertiary" textSize="0.5em">
<Link textColor="tertiary" href="https://en.wikipedia.org/wiki/Style_guide">
Wikipedia
</Link>
</Cite>
</BlockQuote>
</Slide>
<Slide
notes={`
Our designers maintain a static style guide in Sketch app and they share it
with us in invision.
This document doesn't really reflect the state of the current application UI
and is time consuming to maintain.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Static Style Guide
</Text>
<div className="browser">
<Image src={images.invision.replace("/", "")} margin="0" height="500px" />
</div>
</Slide>
<Slide
notes={`
vs a "live" style guide...
In recent years it's become pretty standard to build out a "living" style
guide and there are a bunch of open source tools to help you generate documentation
from your Sass or CSS style sheets.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Live Style Guide
</Text>
<Text textSize="3rem" textColor="tertiary">(or pattern library)</Text>
<div className="browser">
<Image src={images.canvas.replace("/", "")} margin="0" height="400px" />
</div>
</Slide>
<Slide
notes={`
We've had one our living style guide for a while now and the documentation looks like this.
When I first starting building out documentation like this, I was thinking...
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
In a Live Style Guide
</Text>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Documentation lives with the source code in the same repository
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/buttons.scss")}
ranges={[
{ loc: [0, 0], title: "buttons.scss" },
{ loc: [0, 21]}
]}
/>
<Slide
bgColor="black"
transition={["slide"]}
notes={`
Is this the holy grail? Can we finally have a 'single source of truth' owned by
both design and engineering and stop manually updating documentation that is usually
out of date as soon as we write it?
`}
>
<Image src={images.holyGrail.replace("/", "")} margin="0" />
</Slide>
<Slide
bgColor="black"
transition={["slide"]}
notes={`
Well... Nope.
As it turns out, our "live" style guide is still out of sync with the application code,
and most designers and developers don't reference it when they are working on new features
(if they know it exists).
Why?
There is a steep learning curve to working in our monolithic code base, and since the old
style guide lives there and is part of that build, it's difficult to set up and
get running. So it's not really fair to ask designers to learn to update the documentation.
In fact, most developers aren't familiar with the style guide part of the build
because our current front end build process and testing setup is confusing and cumbersome.
`}
>
<Image src={images.panda.replace("/", "")} margin="0" />
</Slide>
<Slide
notes={`
So let's take a look at a custom checkbox (toggle) in our sass style guide.
Notice that there is a lot of markup to copy and paste.
Also to make it accessible we need to add some JS behavior to it.
So the documentation doesn't necessarily reflect what's in the application code
in terms of html markup or JS for behavior.
The scss code for this component lives in a common css file that is used across the
application.
Most developers are reluctant to make changes to CSS because they aren't sure what they may
break and so they probably never see the files that have the documentation comment blocks.
This leads to lots of one-off solutions and overrides, duplication of effort and
inconsistency in the UX.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
A custom checkbox in <b>Sass</b>
</Text>
<div className="browser">
<Image src={images.toggle.replace("/", "")} margin="0" height="500px" />
</div>
</Slide>
<Slide
notes={`
Let's compare that Toggle documentation with a custom checkbox (toggle)
in our new React style guide.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
A custom checkbox in <b>React</b>
</Text>
<div className="browser">
<Image src={images.checkbox.replace("/", "")} margin="0" height="500px" />
</div>
</Slide>
<Slide
notes={`
Similar to our old style guide:
the documentation is generated from the source code + markdown in comment blocks.
Examples are generated from code blocks.
Property documentation is generated from code + comment blocks using react-docgen.
But in this case, CSS, JS, HTML and documentation are bundled and documented as one
component.
Notice that here we're encapsulating style, markup and behavior for the component.
And we've replaced all of those lines of code with one.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<b>CSS, JS, HTML</b> & documentation
</Text>
<Text textColor="tertiary" caps fit>
in one place
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/checkbox.js")}
ranges={[
{ loc: [48, 270], title: "checkbox.js" },
{ loc: [21, 24]}
]}
/>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
So that's great, but how do we get designers and developers to share ownership of
our living style guide v2.0 (and actually use it)?
`}
>
<BlockQuote bgColor="rgba(0, 0, 0, 0.6)" margin="1em 0" padding="1em 1.5em">
<Quote textColor="tertiary" textSize="1em" bold={false} lineHeight={1.2}>
Make the right things easy and the wrong things hard.
</Quote>
<Cite textColor="tertiary" textSize="0.5em">
<Link textColor="tertiary" href="https://en.wikipedia.org/wiki/Style_guide">
Jonathan Snook
</Link>
</Cite>
</BlockQuote>
<Text textColor="tertiary" textSize="0.75em">And now I'll attempt to live code...</Text>
</Slide>
<Slide
notes={`
The component library code is in a separate repository and the documentation app
is easy to install and and run locally.
We've spent lots of time on scaffolding and tools to make it super easy to
spin up a new component and write documentation and tests for it.
(webpack dev server + hot reloading, eslint, stylelint)
Now designers can (at minimum) pull down code from a pull request and run it locally.
(We're working on convincing them that they can update it too :) )
The easiest thing used to be to make a one-off solution for the feature, but we've
made it a lot easier to contribute to the shared UI code instead.
`}
>
<Image src={images.happy.replace("/", "")} margin="0" />
</Slide>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
So now that we're bundling JS, CSS and HTML together into a single component, how can we be sure
that it will render the same in the application as it does in our style guide?
Can we take advantage of the fact that we're using JS to render these components?
Should we consider writing our CSS in JS (as inline styles)?
Lots of react component libraries are using frameworks like Radium and Aphrodite to write CSS in JS.
`}
>
<BlockQuote bgColor="rgba(0, 0, 0, 0.6)" margin="1em 0" padding="1em 1.5em">
<Quote textColor="tertiary" textSize="1em" bold={false} lineHeight={1.2}>
CSS in JS?
<Markdown>
{`
1. Global Namespaces
2. Dependencies
3. Dead Code Elimination
4. Minification
5. Sharing Constants
6. Non-Deterministic Resolution
7. Isolation
`}
</Markdown>
</Quote>
<Cite textColor="tertiary" textSize="0.5em">
<Link textColor="tertiary" href="">
Christopher "vjeux" Chedeau
</Link>
</Cite>
</BlockQuote>
</Slide>
<Slide
notes={`
CSS Modules solves 1-6 and half of 7
With CSS modules we can isolate components and make them more durable by
limiting the scope of their CSS.
With CSS modules we can write our class names as if they were only scoped
to the component we're working on without worrying that we'll accidentally
break something somewhere else.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
CSS Modules
</Text>
<Text textColor="tertiary" caps fit>
(isolate component styles <b>without writing CSS in JS</b>)
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/button.css")}
ranges={[
{ loc: [0, 0], title: "button.css" },
{ loc: [274, 280], title: "local classes"}
]}
/>
<Slide
notes={`
CSS Modules
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
CSS Modules
</Text>
<Text textColor="tertiary" caps fit>
loading a CSS file in a JS component
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/button.js")}
ranges={[
{ loc: [0, 0], title: "button.js" },
{ loc: [7, 9], title: "importing styles"},
{ loc: [161, 168], title: "rendering styles"},
{ loc: [184, 195] }
]}
/>
<Slide
notes={`
Generated class names in production
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<small>with</small> production config
</Text>
<div className="browser">
<Image src={images.production.replace("/", "")} margin="0" height="550px" />
</div>
</Slide>
<Slide
notes={`
Generated class names in development
Note that it's pretty similar to the BEM class name format
This makes it easy to debug issues in dev mode.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<small>with</small> development config
</Text>
<div className="browser">
<Image src={images.development.replace("/", "")} margin="0" height="550px" />
</div>
</Slide>
<Slide
notes={`
The other half of #7
Prevent the cascade with all: initial and postcss-initial
We need to roll out these components bit by bit, so they need to work when older
legacy CSS and various versions of Bootstrap CSS.
We want to be pretty sure they'll work the same in the consuming app as they do in
the documentation app.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Prevent the Cascade
</Text>
<Text textColor="tertiary" caps fit>
with <Code textSize="1em" caps={false}>all: initial</Code> and postcss-initial
</Text>
<div className="browser">
<Image src={images.initial.replace("/", "")} margin="0" width="100%" />
</div>
</Slide>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
As it turns out, bundling component JS, CSS and markup together
makes writing accessibile UIs a whole lot easier.
What does it mean for a UI to be accesible?
It's about building your UI so that it works with assistive tech like screen readers,
keyboards (for users who can't use a mouse) and for people who may be color blind or
have partial vision.
`}
>
<Heading size={1} fit caps>Accessibility</Heading>
</Slide>
<Slide
notes={`
A11y benefits (Button and Link components)
In Canvas, we fix a lot of a11y bugs around buttons. Usually
we've added onClick behavior to a div or we've styled a link to look
like a button (or vice versa).
Rule of thumb for keyboard a11y:
If it looks like a button it should behave like a button.
If it looks like a link it should behave like a link.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Accessible Buttons
</Text>
<div className="browser">
<Image src={images.button.replace("/", "")} margin="0" height="500px" />
</div>
</Slide>
<Slide
notes={`
(JS...)
A11y benefits (Button and Link components)
Take a look at the handleKeyDown method
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Adding (JS) behavior to components for <b>accessibility</b>
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/button.js")}
ranges={[
{ loc: [0, 0], title: "button.js" },
{ loc: [113, 134]}
]}
/>
<Slide
notes={`
(html...)
A11y benefits (unit tests)
We can use tools like axe-core and eslint-plugin-jsx-a11y to run unit tests to verify
that the components are accessible and lint for common a11y issues
(e.g. missing alt attributes on images).
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Unit tests for Accessibility using <b>axe-core</b>
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/checkbox.test.js")}
ranges={[
{ loc: [0, 0], title: "checkbox.test.js" },
{ loc: [79, 87]}
]}
/>
<Slide
notes={`
(color variables...)
A11y benefits (color contrast)
Notice the variables are defined in JS...
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Testing <b>color contrast</b> for a11y
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/button.test.js")}
ranges={[
{ loc: [0, 0], title: "theme.test.js" },
{ loc: [8, 14]}
]}
/>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
`}
>
<Heading size={1} caps>Themes</Heading>
</Slide>
<Slide
notes={`
Sass variables
Notice the global (color) variables.
Notice the functional (link) variables.
What's the drawback here?
We need to pre-process all of the variations and custom brands as part of our build.
How can we avoid this?
We can write our variables (not our CSS) in JS.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
SASS variables <b>in the monolith</b>
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="css"
code={require("raw!../assets/variables.scss")}
ranges={[
{ loc: [0, 0], title: "variables.scss" },
{ loc: [186, 188], title: "global variables"},
{ loc: [204, 208], title: "functional variables"}
]}
/>
<Slide
notes={`
Global/Brand JS variables
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<b>Global brand variables</b> defined in JS
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="js"
code={require("raw!../assets/brand.js")}
ranges={[
{ loc: [0, 0], title: "brand.js" },
{ loc: [4, 9], title: "global color variables"}
]}
/>
<Slide
notes={`
Component/functional variables
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<b>Component variables</b> defined in JS
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="js"
code={require("raw!../assets/theme.js")}
ranges={[
{ loc: [0, 0], title: "theme.js" },
{ loc: [7, 14], title: "component variables"}
]}
/>
<Slide
notes={`
Now these variables are accessible withing our JS code too...
and we can do run time themeing.
Here's the ApplyTheme component.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Applying themes at run time
</Text>
<div className="browser">
<Image src={images.applyTheme.replace("/", "")} margin="0" width="800px" />
</div>
</Slide>
<Slide
notes={`
How does this work without writing inline styles with JS?
...CSS custom properties
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
CSS custom properties
</Text>
<div className="browser">
<Image src={images.themed.replace("/", "")} margin="0" width="800px" />
</div>
</Slide>
<Slide
notes={`
Setting custom properties with JS
`}
>
<Code textColor="tertiary" fit lineHeight={1}>
CSSStyleDeclaration.setProperty()
</Code>
<CodePane
lang="js"
source={require("raw!../assets/setProperty.js")}
textSize="1em"
margin="1em auto"
/>
</Slide>
<Slide
notes={`
CSS custom properties have pretty good browser support
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
CSS custom properties
</Text>
<Text textSize="2rem" textColor="tertiary" lineHeight={1}>
(we wrote a polyfill for IE)
</Text>
<div className="browser">
<Image src={images.variableSupport.replace("/", "")} margin="0" width="800px" />
</div>
</Slide>
<Slide
transition={["spin", "slide"]}
bgImage={images.microservices.replace("/", "")} bgDarken={0.70}
notes={`
How's it going so far?
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Built to Scale
</Text>
<Text textSize="3rem" textColor="tertiary" bold>
We're using our UI components in multiple applications as we start breaking up the monolith
into microservices
</Text>
<Text textColor="tertiary">
&
</Text>
<Text textSize="3rem" textColor="tertiary" bold>
Our professional services team is using the library to build custom integrations with a seamless UX.
</Text>
</Slide>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.70}
notes={`
Questions
`}
>
<Heading textColor="tertiary" fit caps lineHeight={1}>
Questions?
</Heading>
<Text fit margin="2em 0" bold textColor="tertiary">
https://github.com/instructure/instructure-ui
</Text>
<Text caps lineHeight={1} textColor="primary" bold margin="1em 0">
We're Hiring!
</Text>
<Text textColor="tertiary">
Contact Ariel: apao@instructure.com
</Text>
</Slide>
<Slide
notes={`
Resources and Links
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Resources and Links
</Text>
<List textColor="tertiary">
<ListItem>
<Link textColor="tertiary" href="https://github.com/reactjs/react-docgen">react-docgen</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="http://eslint.org/">eslint</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/stylelint/stylelint">stylelint</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/dequelabs/axe-core">axe-core</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://www.npmjs.com/package/eslint-plugin-jsx-a11y">eslint-plugin-jsx-a11y</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/maximkoretskiy/postcss-initial">postcss-initial</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/css-modules/css-modules">css modules</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/webpack/css-loader">webpack css-loader</Link>
</ListItem>
</List>
</Slide>
</Deck>
</Spectacle>
);
}
}
| junyper/react-meetup | presentation/index.js | JavaScript | mit | 29,727 |
import json
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
def jsonfilter(value):
return mark_safe(json.dumps(value))
register.filter('json', jsonfilter)
| Open511/open511-server | open511_server/templatetags/open511.py | Python | mit | 220 |
<?php
namespace Anroots\Pgca\Test;
use Faker\Factory;
use Faker\Generator;
abstract class TestCase extends \PHPUnit_Framework_TestCase
{
/**
* @return Generator
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function getFaker()
{
return Factory::create();
}
}
| anroots/pgca | tests/Anroots/Pgca/Test/TestCase.php | PHP | mit | 305 |
using System;
using System.Linq;
using FluentAssertions;
using Paster.Specs.Fakes;
using Xbehave;
using xBehave.Paster.Gherkin;
using xBehave.Paster.System;
using Xunit;
namespace Paster.Specs
{
[Trait("Invalid gherkin","")]
public class BadSourceData
{
[Scenario(DisplayName = "Pasting an Empty string")]
public void EmptyString(EnvironmentClipboard clipboard, GherkinPaster sut, TestEnvironment environment)
{
"Given a complete system".Given(() =>
{
environment = FakesLibrary.CreateDefaultEnvironment();
sut = new GherkinPaster(environment);
});
"and a empty string "
.And(() => clipboard = FakesLibrary.CreateShim(String.Empty));
"When the text is pasted"
.Then(() => sut.PasteGherkin(clipboard));
"Then no lines are received by the environment"
.Then(() => environment.LinesWritten.Count()
.Should()
.Be(0));
}
[Scenario(DisplayName = "Pasting invalid gherkin")]
public void InvalidGherkin(EnvironmentClipboard clipboard, GherkinPaster sut, TestEnvironment environment)
{
"Given a complete system".Given(() =>
{
environment = FakesLibrary.CreateDefaultEnvironment();
sut = new GherkinPaster(environment);
});
"and an invalid string of gherkin"
.And(() => clipboard = FakesLibrary.CreateShim("This is not valid gherkin"));
"When the text is pasted"
.Then(() => sut.PasteGherkin(clipboard));
"Then no lines are received by the environment"
.Then(() => environment.LinesWritten.Count()
.Should()
.Be(0));
}
}
} | xbehave/xbehave.net-visual-studio | src/Paster.Specs/BadSourceData.cs | C# | mit | 1,963 |
import { Ng2PopupComponent } from "./ng2-popup.component";
import { Ng2MessagePopupComponent } from "./ng2-message-popup.component";
export { Ng2PopupComponent, Ng2MessagePopupComponent };
export declare class Ng2PopupModule {
}
| salim101/MathQuiz | frontend/node_modules/ng2-popup/dist/ng2-popup.module.d.ts | TypeScript | mit | 229 |
using System;
using TechTalk.SpecFlow;
namespace ServiceRegister.Tests.Infrastructure
{
public static class CurrentScenarioContext
{
public static Guid OrganizationId
{
get { return ScenarioContext.Current.Get<Guid>("OrganizationId"); }
set { ScenarioContext.Current.Set(value, "OrganizationId"); }
}
public static Guid ServiceId
{
get { return ScenarioContext.Current.Get<Guid>("ServiceId"); }
set { ScenarioContext.Current.Set(value, "ServiceId"); }
}
}
} | City-of-Helsinki/palvelutietovaranto | Source/ServiceRegister.Tests.Infrastructure/CurrentScenarioContext.cs | C# | mit | 570 |
package Movement;
/**
* This is an abstract class ChessUnitMovement.
* It is built to handle chess units movement.
* This class must be implemented to support a units movement.
* @author thapaliya
*/
public abstract class ChessUnitMovement
{
/**
*
* @param currentRow of the unit
* @param currentColum of the unit
* @param desiredRow for the unit
* @param desiredColum for the unit
* @return true if the move of this chess unit from the current position to the
* desired position is valid for this unit.
*/
public abstract boolean acceptMove( int currentRow, int currentColum, int desiredRow, int desiredColum);
}
| thesashi7/SimpleChess | src/Movement/ChessUnitMovement.java | Java | mit | 674 |
package config
const (
// XPathEpisodesOverviewPagePageItems to retrieve pages where videos are schon
XPathEpisodesOverviewPagePageItems = "//a[@class='pageItem']/@href"
// XPathEpisodesItems to retrieve video urls from a page
XPathEpisodesItems = "//div[@class='modCon']/div[@class='mod modD modMini']/div[@class='boxCon']/div[contains(@class, 'box')]/div[contains(@class, 'teaser')]/a[@class='linkAll']/@href"
// XPathVideoPageVideoTags to find all video tags on final video page
XPathVideoPageVideoTags = "//video/@id"
// XPathVideoPageXmlDataTag to find the concrete element where xml url can be extracted, %s is placeholder for video id
XPathVideoPageXmlDataTag = "//a[@id='%s']/@onclick"
// XPathXmlSeriesTitle title of series
XPathXmlSeriesTitle = "//avDocument/topline"
// XPathXmlEpisodeTitle title of episode
XPathXmlEpisodeTitle = "//avDocument/headline"
// XPathXmlEpisodeLanguageCode language of episode
XPathXmlEpisodeLanguageCode = "//avDocument/language"
// XPathXmlEpisodeDescription episodes description
XPathXmlEpisodeDescription = "//avDocument/broadcast/broadcastDescription"
// XPathXmlAssets documents assets where video url can be found
XPathXmlAssets = "//avDocument/assets/asset"
)
| rkl-/kika-downloader | src/kika-downloader/config/xpath.go | GO | mit | 1,236 |
package cz.crcs.ectester.standalone.libs;
import java.security.Provider;
import java.util.Set;
/**
* @author Jan Jancar johny@neuromancer.sk
*/
public class MatrixsslLib extends NativeECLibrary {
public MatrixsslLib() {
super("matrixssl_provider");
}
@Override
native Provider createProvider();
@Override
public native Set<String> getCurves();
}
| petrs/ECTester | src/cz/crcs/ectester/standalone/libs/MatrixsslLib.java | Java | mit | 385 |
// <copyright file="SwitchableSection.cs" company="Cui Ziqiang">
// Copyright (c) 2017 Cui Ziqiang
// </copyright>
namespace CrossCutterN.Weaver.Switch
{
using System;
using System.Collections.Generic;
using Mono.Cecil.Cil;
/// <summary>
/// Switchable section implementation.
/// </summary>
internal sealed class SwitchableSection : ISwitchableSection
{
/// <inheritdoc/>
public int StartIndex { private get; set; }
/// <inheritdoc/>
public int EndIndex { private get; set; }
/// <inheritdoc/>
public Instruction StartInstruction { get; private set; }
/// <inheritdoc/>
public Instruction EndInstruction { get; private set; }
/// <inheritdoc/>
public bool HasSetStartEndInstruction => StartInstruction != null && EndInstruction != null;
/// <inheritdoc/>
public void SetInstructions(IList<Instruction> instructions, Instruction defaultInstruction)
{
if (StartIndex == -1)
{
return;
}
#if DEBUG
if (EndIndex == -1)
{
throw new InvalidOperationException("End index not set yet");
}
if (EndIndex <= StartIndex)
{
throw new InvalidOperationException("End index should be above start index");
}
if (StartIndex >= instructions.Count)
{
throw new ArgumentException("Instruction list not correctly populated");
}
#endif
StartInstruction = instructions[StartIndex];
EndInstruction = EndIndex >= instructions.Count ? defaultInstruction : instructions[EndIndex];
StartIndex = -1;
EndIndex = -1;
}
/// <inheritdoc/>
public void Reset()
{
StartIndex = -1;
EndIndex = -1;
StartInstruction = null;
EndInstruction = null;
}
/// <inheritdoc/>
public void AdjustEndInstruction(Instruction originalEnd, Instruction newEnd)
{
#if DEBUG
if (newEnd == null)
{
throw new ArgumentNullException("newEnd");
}
#endif
if (EndInstruction != null && EndInstruction == originalEnd)
{
EndInstruction = newEnd;
}
}
}
}
| keeper013/CrossCutterN | CrossCutterN.Weaver/Switch/SwitchableSection.cs | C# | mit | 2,421 |
/**
* @file AccessDeniedException.java
* @brief 로그인을 하지 않았거나 세션이 끊긴 경우 발생하는 Exception
* @author 개발3/파트3
* @author 최경진
* @date 생성 : 2014. 4. 17.
* @date 최종수정: 2014. 4. 17.
*/
package com.juseyo.certification.exception;
/**
* @brief AccessDeniedException
* @author 개발3팀/파트3/최경진
* @version 1.0
* @date 생성: 2014. 4. 17.
* @date 최종수정: 2014. 4. 17.
* @remark
*/
public class SessionNotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = -5968061856227840420L;
public SessionNotFoundException() {
super();
}
public SessionNotFoundException(String msg) {
super(msg);
}
}
| zupper77/juseyo | src/main/java/com/juseyo/certification/exception/SessionNotFoundException.java | Java | mit | 778 |
<?php
/* TwigBundle:Exception:traces.xml.twig */
class __TwigTemplate_05a06802ecd3434c77ee29212d49ed457ae32c039667ade3058cbb9e3ff2db70 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo " <traces>
";
// line 2
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array()));
foreach ($context['_seq'] as $context["_key"] => $context["trace"]) {
// line 3
echo " <trace>
";
// line 4
$this->env->loadTemplate("TwigBundle:Exception:trace.txt.twig")->display(array("trace" => $context["trace"]));
// line 5
echo "
</trace>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['trace'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 8
echo " </traces>
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:traces.xml.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 39 => 8, 31 => 5, 29 => 4, 26 => 3, 22 => 2, 19 => 1,);
}
}
| thmohd/demo | app/cache/dev/twig/05/a0/6802ecd3434c77ee29212d49ed457ae32c039667ade3058cbb9e3ff2db70.php | PHP | mit | 1,699 |
class CreateApiVerifications < ActiveRecord::Migration
def up
create_table :api_verifications do |t|
t.string :name
t.string :key
t.string :secret
t.timestamps null: false
end
end
def down
drop_table :api_verifications
end
end | Christianjuth/Portfolio | db/migrate/20161104123431_create_api_verifications.rb | Ruby | mit | 273 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kayak;
namespace Pivot.Update.Server
{
class HttpErrorDataProducer : BufferedProducer
{
public HttpErrorDataProducer()
: base("The server did not understand your request.")
{
}
}
}
| hach-que/Pivot.Update | Pivot.Update.Server/HttpErrorDataProducer.cs | C# | mit | 325 |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.text import slugify
from django.contrib.auth.models import (
User
)
from pastryio.models.mixins import ArchiveMixin
class BaseProfile(ArchiveMixin):
user = models.OneToOneField(User)
avatar = models.ImageField(_("avatar"), blank=True)
def __unicode__(self):
return self.user.username
@property
def slug(self):
return slugify(self.user.first_name)
| octaflop/pastryio | apps/profiles/models.py | Python | mit | 496 |
import {
AudioSourceErrorEvent,
AudioSourceInitializingEvent,
AudioSourceOffEvent,
AudioSourceReadyEvent,
AudioStreamNodeAttachedEvent,
AudioStreamNodeAttachingEvent,
AudioStreamNodeDetachedEvent
} from 'microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/AudioSourceEvents';
export {
AudioSourceErrorEvent,
AudioSourceInitializingEvent,
AudioSourceOffEvent,
AudioSourceReadyEvent,
AudioStreamNodeAttachedEvent,
AudioStreamNodeAttachingEvent,
AudioStreamNodeDetachedEvent
};
| billba/botchat | packages/testharness/pre/external/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/AudioSourceEvents.js | JavaScript | mit | 514 |
/*
(c)2014|US-UltimateShip.
Univali - Universidade do Vale do Itajaí.
GeraçãoTec - Projeto Filnal Batalha Final em JAVA.
Criadores:
Alexandre <alexandreess@gmail.com>
Carlos Eduardo Passos de Sousa <carloseduardosousa@gmail.com>
Henrique Wilhelm <henrique.wilhelm@gmail.com>
Jaison dos santos <jaison1906@gmail.com>
Otavio Ribeiro <otavioribeiro@capflorianopolis.org.br>
*/
package br.com.intagrator.cap8;
public class TrabFlowLayout extends java.awt.Frame {
/**
*
*/
private static final long serialVersionUID = 1L;
//Método @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| carlosedusousa/curso-java-fonts | layouts-em-Java/src/br/com/intagrator/cap8/TrabFlowLayout.java | Java | mit | 653 |
package ch11.product_serial;
public class Product
{
private String name;
private double price;
private int quantity;
/**
Constructs a product with empty name and 0 price and
quantity.
*/
public Product()
{
name = "";
price = 0;
quantity = 0;
}
/**
Constructs a product with the given name, price and
quantity.
@param aName product name
@param aPrice product price
@param aQuantity product quantity
*/
public Product(String aName, double aPrice, int aQuantity)
{
name = aName;
price = aPrice;
quantity = aQuantity;
}
/**
Returns the product name.
@return the product name
*/
public String getName()
{
return name;
}
/**
Returns the product price.
@return the product price
*/
public double getPrice()
{
return price;
}
/**
Returns the product quantity.
@return the product quantity
*/
public int getQuantity()
{
return quantity;
}
/**
Sets the product price.
@param newPrice the new product price
*/
public void setPrice(double newPrice)
{
price = newPrice;
}
/**
Sets the product quantity.
@param newQuantity the new product quantity
*/
public void setQuantity(int newQuantity)
{
quantity = newQuantity;
}
public String toString() {
return super.toString()+" : "+ this.name + " (" +this.price+" , "+this.quantity+")";
}
}
| raeffu/prog2 | src/ch11/product_serial/Product.java | Java | mit | 1,562 |
var expect = chai.expect;
var assert = chai.assert;
var Utils = {
elementContainer: undefined,
_init: function(){
this.elementContainer = document.createElement('div');
this.elementContainer.setAttribute('data-element-container', '');
this.elementContainer.style.display = 'none';
document.body.appendChild(this.elementContainer);
return this;
},
append: function(selector, html){
var div = document.createElement('div');
div.innerHTML = html;
var children = Array.prototype.slice.call(div.childNodes);
var length = children.length;
var parents = document.querySelectorAll(selector);
for(var p=0; p<parents.length; p++){
var parent = parents[p];
while(children.length){
var child = children.pop();
parent.appendChild(child);
}
}
},
remove: function(parentSelector, childSelector){
var parents = document.querySelectorAll(parentSelector);
for(var p=0; p<parents.length; p++){
var parent = parents[p];
var children = parent.querySelectorAll(childSelector);
children = Array.prototype.slice.call(children);
while(children.length){
var child = children.pop();
parent.removeChild(child);
}
}
}
}._init(); | hkvalvik/element-observer | test/utils.js | JavaScript | mit | 1,413 |
from django.db import models
from django.core.exceptions import ImproperlyConfigured
from django import forms
from django.conf import settings
import warnings
try:
from keyczar import keyczar
except ImportError:
raise ImportError('Using an encrypted field requires the Keyczar module. '
'You can obtain Keyczar from http://www.keyczar.org/.')
class EncryptionWarning(RuntimeWarning):
pass
class BaseEncryptedField(models.Field):
prefix = 'enc_str:::'
def __init__(self, *args, **kwargs):
if not hasattr(settings, 'ENCRYPTED_FIELD_KEYS_DIR'):
raise ImproperlyConfigured('You must set the ENCRYPTED_FIELD_KEYS_DIR setting to your Keyczar keys directory.')
self.crypt = keyczar.Crypter.Read(settings.ENCRYPTED_FIELD_KEYS_DIR)
# Encrypted size is larger than unencrypted
self.unencrypted_length = max_length = kwargs.get('max_length', None)
if max_length:
max_length = len(self.prefix) + len(self.crypt.Encrypt('x' * max_length))
# TODO: Re-examine if this logic will actually make a large-enough
# max-length for unicode strings that have non-ascii characters in them.
kwargs['max_length'] = max_length
super(BaseEncryptedField, self).__init__(*args, **kwargs)
def to_python(self, value):
if isinstance(self.crypt.primary_key, keyczar.keys.RsaPublicKey):
retval = value
elif value and (value.startswith(self.prefix)):
retval = self.crypt.Decrypt(value[len(self.prefix):])
if retval:
retval = retval.decode('utf-8')
else:
retval = value
return retval
def get_db_prep_value(self, value, connection, prepared=False):
if value and not value.startswith(self.prefix):
# We need to encode a unicode string into a byte string, first.
# keyczar expects a bytestring, not a unicode string.
if type(value) == unicode:
value = value.encode('utf-8')
# Truncated encrypted content is unreadable,
# so truncate before encryption
max_length = self.unencrypted_length
if max_length and len(value) > max_length:
warnings.warn("Truncating field %s from %d to %d bytes" % (
self.name, len(value), max_length), EncryptionWarning
)
value = value[:max_length]
value = self.prefix + self.crypt.Encrypt(value)
return value
class EncryptedTextField(BaseEncryptedField):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return 'TextField'
def formfield(self, **kwargs):
defaults = {'widget': forms.Textarea}
defaults.update(kwargs)
return super(EncryptedTextField, self).formfield(**defaults)
def south_field_triple(self):
"Returns a suitable description of this field for South."
# We'll just introspect the _actual_ field.
from south.modelsinspector import introspector
field_class = "django.db.models.fields.TextField"
args, kwargs = introspector(self)
# That's our definition!
return (field_class, args, kwargs)
class EncryptedCharField(BaseEncryptedField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
super(EncryptedCharField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return "CharField"
def formfield(self, **kwargs):
defaults = {'max_length': self.max_length}
defaults.update(kwargs)
return super(EncryptedCharField, self).formfield(**defaults)
def south_field_triple(self):
"Returns a suitable description of this field for South."
# We'll just introspect the _actual_ field.
from south.modelsinspector import introspector
field_class = "django.db.models.fields.CharField"
args, kwargs = introspector(self)
# That's our definition!
return (field_class, args, kwargs)
| orbitvu/django-extensions | django_extensions/db/fields/encrypted.py | Python | mit | 4,102 |
package de.yellow_ray.bluetoothtest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import de.yellow_ray.bluetoothtest.protocol.Package;
public class BluetoothService<T extends BluetoothClient> {
public static final String TAG = "BluetoothService";
public static final int MESSAGE_DISCONNECTED = 0;
public static final int MESSAGE_CONNECTING = 1;
public static final int MESSAGE_CONNECTING_FAILED = 2;
public static final int MESSAGE_CONNECTED = 3;
private final BluetoothAdapter mBluetoothAdapter;
private final Handler mHandler;
private BluetoothSocket mSocket = null;
private ConnectThread mConnectThread = null;
private TechnoBluetoothClient mClientThread = null;
BluetoothService(final Handler handler) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mHandler = handler;
notifyDisconnected();
}
public void connect(final BluetoothDevice device) {
if (mSocket != null && mSocket.isConnected()) {
closeSocket();
}
notifyConnecting(device);
mConnectThread = new ConnectThread(device);
mConnectThread.start();
}
public void disconnect() {
closeSocket();
}
public void sendPackage(Package pkg) {
if (mClientThread != null) {
mClientThread.sendPackage(pkg);
}
}
public void setParameter(int id, float value) {
if (mClientThread != null) {
mClientThread.setParameter(id, value);
}
}
private void notifyDisconnected() {
notifyDisconnected("");
}
private void notifyDisconnected(final String reason) {
Message msg = mHandler.obtainMessage(MESSAGE_DISCONNECTED);
Bundle bundle = new Bundle();
bundle.putString("reason", reason);
msg.setData(bundle);
msg.sendToTarget();
}
private void notifyConnecting(final BluetoothDevice device) {
Message msg = mHandler.obtainMessage(MESSAGE_CONNECTING);
Bundle bundle = new Bundle();
bundle.putParcelable("device", device);
msg.setData(bundle);
msg.sendToTarget();
}
private void notifyConnectingFailed(final BluetoothDevice device, final String reason) {
Message msg = mHandler.obtainMessage(MESSAGE_CONNECTING_FAILED);
Bundle bundle = new Bundle();
bundle.putParcelable("device", device);
bundle.putString("reason", reason);
msg.setData(bundle);
msg.sendToTarget();
}
private void notifyConnected(final BluetoothDevice device) {
Message msg = mHandler.obtainMessage(MESSAGE_CONNECTED);
Bundle bundle = new Bundle();
bundle.putParcelable("device", device);
msg.setData(bundle);
msg.sendToTarget();
}
public void closeSocketAfterError(final String reason) {
try {
if (mSocket != null) {
mSocket.close();
}
notifyDisconnected(reason);
} catch (IOException e) {
Log.e(TAG, "Could not close the client socket", e);
notifyDisconnected("Could not close the client socket: " + e.toString());
}
}
private void closeSocket() {
try {
try {
if (mClientThread != null) {
mClientThread.stopClient();
mClientThread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (mSocket != null) {
mSocket.close();
notifyDisconnected();
}
} catch (IOException e) {
Log.e(TAG, "Could not close the client socket", e);
notifyDisconnected("Could not close the client socket: " + e.toString());
}
}
private void handleConnection(final BluetoothSocket socket) {
try {
InputStream input = mSocket.getInputStream();
OutputStream output = mSocket.getOutputStream();
mClientThread = new TechnoBluetoothClient(this, mHandler, input, output);
mClientThread.start();
notifyConnected(socket.getRemoteDevice());
} catch (IOException e) {
Log.w(TAG, e);
notifyConnectingFailed(socket.getRemoteDevice(), e.toString());
closeSocket();
}
}
private class ConnectThread extends Thread {
private BluetoothDevice mDevice = null;
public ConnectThread(BluetoothDevice device) {
mDevice = device;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
mBluetoothAdapter.cancelDiscovery();
try {
mSocket = mDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
notifyConnectingFailed(mDevice, e.toString());
closeSocket();
return;
}
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
Log.w(TAG, "Unable to connect!");
Log.w(TAG, connectException);
try {
Class<?> clazz = mSocket.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[]{Integer.valueOf(1)};
mSocket = (BluetoothSocket) m.invoke(mSocket.getRemoteDevice(), params);
mSocket.connect();
} catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
Log.w(TAG, e);
notifyConnectingFailed(mDevice, e.toString());
closeSocket();
return;
}
}
handleConnection(mSocket);
}
}
}
| m0r13/technoqualle-android | app/src/main/java/de/yellow_ray/bluetoothtest/BluetoothService.java | Java | mit | 6,754 |
/* eslint-disable no-console */
const path = require('path');
const { promisify } = require('util');
const render = require('koa-ejs');
const helmet = require('helmet');
const { Provider } = require('../lib'); // require('oidc-provider');
const Account = require('./support/account');
const configuration = require('./support/configuration');
const routes = require('./routes/koa');
const { PORT = 3000, ISSUER = `http://localhost:${PORT}` } = process.env;
configuration.findAccount = Account.findAccount;
let server;
(async () => {
let adapter;
if (process.env.MONGODB_URI) {
adapter = require('./adapters/mongodb'); // eslint-disable-line global-require
await adapter.connect();
}
const prod = process.env.NODE_ENV === 'production';
const provider = new Provider(ISSUER, { adapter, ...configuration });
const directives = helmet.contentSecurityPolicy.getDefaultDirectives();
delete directives['form-action'];
const pHelmet = promisify(helmet({
contentSecurityPolicy: {
useDefaults: false,
directives,
},
}));
provider.use(async (ctx, next) => {
const origSecure = ctx.req.secure;
ctx.req.secure = ctx.request.secure;
await pHelmet(ctx.req, ctx.res);
ctx.req.secure = origSecure;
return next();
});
if (prod) {
provider.proxy = true;
provider.use(async (ctx, next) => {
if (ctx.secure) {
await next();
} else if (ctx.method === 'GET' || ctx.method === 'HEAD') {
ctx.status = 303;
ctx.redirect(ctx.href.replace(/^http:\/\//i, 'https://'));
} else {
ctx.body = {
error: 'invalid_request',
error_description: 'do yourself a favor and only use https',
};
ctx.status = 400;
}
});
}
render(provider.app, {
cache: false,
viewExt: 'ejs',
layout: '_layout',
root: path.join(__dirname, 'views'),
});
provider.use(routes(provider).routes());
server = provider.listen(PORT, () => {
console.log(`application is listening on port ${PORT}, check its /.well-known/openid-configuration`);
});
})().catch((err) => {
if (server && server.listening) server.close();
console.error(err);
process.exitCode = 1;
});
| panva/node-oidc-provider | example/standalone.js | JavaScript | mit | 2,219 |
package com.instructure.canvasapi.api;
import com.instructure.canvasapi.model.CanvasContext;
import com.instructure.canvasapi.model.NotificationPreferenceResponse;
import com.instructure.canvasapi.utilities.APIHelpers;
import com.instructure.canvasapi.utilities.CanvasCallback;
import com.instructure.canvasapi.utilities.CanvasRestAdapter;
import java.util.ArrayList;
import retrofit.RestAdapter;
import retrofit.http.GET;
import retrofit.http.PUT;
import retrofit.http.Path;
import retrofit.http.Query;
public class NotificationPreferencesAPI {
//Frequency keys
public static final String IMMEDIATELY = "immediately";
public static final String DAILY = "daily";
public static final String WEEKLY = "weekly";
public static final String NEVER = "never";
public interface NotificationPreferencesInterface {
@GET("/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences")
void getNotificationPreferences(@Path("user_id") long userId, @Path("communication_channel_id") long communicationChannelId, CanvasCallback<NotificationPreferenceResponse> callback);
@GET("/users/{user_id}/communication_channels/{type}/{address}/notification_preferences")
void getNotificationPreferencesForType(@Path("user_id") long userId, @Path("type") String type, @Path("address") String address, CanvasCallback<NotificationPreferenceResponse> callback);
@GET("/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences/{notification}")
void getSingleNotificationPreference(@Path("user_id") long userId, @Path("communication_channel_id") long communicationChannelId, @Path("notification") String notification, CanvasCallback<NotificationPreferenceResponse> callback);
@GET("/users/{user_id}/communication_channels/{type}/{address}/notification_preferences/{notification}")
void getSingleNotificationPreferencesForType(@Path("user_id") long userId, @Path("type") String type, @Path("address") String address, @Path("notification") String notification, CanvasCallback<NotificationPreferenceResponse> callback);
@PUT("/users/self/communication_channels/{communication_channel_id}/notification_preferences/{notification}")
void updateSingleNotificationPreference(@Path("communication_channel_id") long communicationChannelId, @Path("notification") String notification, CanvasCallback<NotificationPreferenceResponse> callback);
@PUT("/users/self/communication_channels/{type}/{address}/notification_preferences/{notification}")
void updateSingleNotificationPreferenceForType(@Path("type") String type, @Path("address") String address, @Path("notification") String notification, CanvasCallback<NotificationPreferenceResponse> callback);
@PUT("/users/self/communication_channels/{communication_channel_id}/notification_preferences{notification_preferences}")
void updateMultipleNotificationPreferences(@Path("communication_channel_id") long communicationChannelId, @Path(value = "notification_preferences", encode = false) String notifications, CanvasCallback<NotificationPreferenceResponse> callback);
}
/////////////////////////////////////////////////////////////////////////
// Build Interface Helpers
/////////////////////////////////////////////////////////////////////////
private static NotificationPreferencesInterface buildInterface(CanvasCallback<?> callback, CanvasContext canvasContext) {
RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(callback, canvasContext, false);
return restAdapter.create(NotificationPreferencesInterface.class);
}
public static void getNotificationPreferences(final long userId, final long communicationChannelId, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).getNotificationPreferences(userId, communicationChannelId, callback);
}
public static void getNotificationPreferencesByType(final long userId, final String type, final String address, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).getNotificationPreferencesForType(userId, type, address, callback);
}
public static void getSingleNotificationPreference(final long userId, final long communicationChannelId, final String notification, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).getSingleNotificationPreference(userId, communicationChannelId, notification, callback);
}
public static void getSingleNotificationPreferencesForType(final long userId, final String type, final String address, final String notification, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).getSingleNotificationPreferencesForType(userId, type, address, notification, callback);
}
public static void updateSingleNotificationPreference(final long communicationChannelId, final String notification, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).updateSingleNotificationPreference(communicationChannelId, notification, callback);
}
public static void updateSingleNotificationPreferenceForType(final String type, final String address, final String notification, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).updateSingleNotificationPreferenceForType(type, address, notification, callback);
}
public static void updateMultipleNotificationPreferences(final long communicationChannelId, final ArrayList<String> notifications, final String frequency, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).updateMultipleNotificationPreferences(communicationChannelId, buildNotificationPreferenceList(notifications, frequency), callback);
}
private static String buildNotificationPreferenceList(ArrayList<String> notifications, String frequency) {
StringBuilder builder = new StringBuilder();
builder.append("?");
for(String preference : notifications) {
builder.append("notification_preferences");
builder.append("[");
builder.append(preference);
builder.append("]");
builder.append("[frequency]");
builder.append("=");
builder.append(frequency);
builder.append("&");
}
String notificationsString = builder.toString();
if(notificationsString.endsWith("&")) {
notificationsString = notificationsString.substring(0, notificationsString.length() - 1);
}
return notificationsString;
}
}
| nbutton23/CanvasAPI | src/main/java/com/instructure/canvasapi/api/NotificationPreferencesAPI.java | Java | mit | 7,235 |
// All symbols in the Vertical Forms block as per Unicode v8.0.0:
[
'\uFE10',
'\uFE11',
'\uFE12',
'\uFE13',
'\uFE14',
'\uFE15',
'\uFE16',
'\uFE17',
'\uFE18',
'\uFE19',
'\uFE1A',
'\uFE1B',
'\uFE1C',
'\uFE1D',
'\uFE1E',
'\uFE1F'
]; | mathiasbynens/unicode-data | 8.0.0/blocks/Vertical-Forms-symbols.js | JavaScript | mit | 245 |
require 'erb'
require 'tilt'
require 'rack/mime'
class MailView
autoload :Mapper, 'mail_view/mapper'
class << self
def default_email_template_path
File.expand_path('../mail_view/email.html.erb', __FILE__)
end
def default_index_template_path
File.expand_path('../mail_view/index.html.erb', __FILE__)
end
def call(env)
new.call(env)
end
end
def call(env)
@rack_env = env
path_info = env["PATH_INFO"]
if path_info == "" || path_info == "/"
links = self.actions.map do |action|
[action, "#{env["SCRIPT_NAME"]}/#{action}"]
end
ok index_template.render(Object.new, :links => links)
elsif path_info =~ /([\w_]+)(\.\w+)?$/
name = $1
format = $2 || ".html"
if actions.include?(name)
ok render_mail(name, send(name), format)
else
not_found
end
else
not_found(true)
end
end
protected
def actions
public_methods(false).map(&:to_s) - ['call']
end
def email_template
Tilt.new(email_template_path)
end
def email_template_path
self.class.default_email_template_path
end
def index_template
Tilt.new(index_template_path)
end
def index_template_path
self.class.default_index_template_path
end
private
def ok(body)
[200, {"Content-Type" => "text/html"}, [body]]
end
def not_found(pass = false)
if pass
[404, {"Content-Type" => "text/html", "X-Cascade" => "pass"}, ["Not Found"]]
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
end
def render_mail(name, mail, format = nil)
body_part = mail
if mail.multipart?
content_type = Rack::Mime.mime_type(format)
body_part = mail.parts.find { |part| part.content_type.match(content_type) } || mail.parts.first
end
email_template.render(Object.new, :name => name, :mail => mail, :body_part => body_part)
end
end
| WindStill/mail_view | lib/mail_view.rb | Ruby | mit | 1,999 |
const LOAD = 'lance-web/serviceTypes/LOAD';
const LOAD_SUCCESS = 'lance-web/serviceTypes/LOAD_SUCCESS';
const LOAD_FAIL = 'lance-web/serviceTypes/LOAD_FAIL';
const EDIT_START = 'lance-web/serviceTypes/EDIT_START';
const EDIT_STOP = 'lance-web/serviceTypes/EDIT_STOP';
const SAVE = 'lance-web/serviceTypes/SAVE';
const SAVE_SUCCESS = 'lance-web/serviceTypes/SAVE_SUCCESS';
const SAVE_FAIL = 'lance-web/serviceTypes/SAVE_FAIL';
const REMOVE = 'lance-web/serviceTypes/REMOVE';
const REMOVE_SUCCESS = 'lance-web/serviceTypes/REMOVE_SUCCESS';
const REMOVE_FAIL = 'lance-web/serviceTypes/REMOVE_FAIL';
const CLEAR_ERRORS = 'lance-web/serviceTypes/CLEAR_ERRORS';
const initialState = {
loaded: false,
editing: {},
saveError: {}
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case LOAD:
return {
...state,
loading: true
};
case LOAD_SUCCESS:
return {
...state,
loading: false,
loaded: true,
data: action.result.serviceTypes,
error: null
};
case LOAD_FAIL:
return {
...state,
loading: false,
loaded: false,
data: null,
error: action.error
};
case EDIT_START:
return {
...state,
editing: {
...state.editing,
[action.id]: true
}
};
case EDIT_STOP:
return {
...state,
editing: {
...state.editing,
[action.id]: false
}
};
case SAVE:
return {
...state,
loading: true,
error: null
};
case SAVE_SUCCESS:
return {
...state,
data: [...state.data, action.result.serviceType],
loading: false,
error: null
};
case SAVE_FAIL:
return {
...state,
loading: false,
error: action.error
};
case REMOVE:
return {
...state,
loading: true,
error: null
};
case REMOVE_SUCCESS:
let idx;
for (let jdx = 0; jdx < state.data.length; jdx++) {
if (state.data[jdx].id === action.id) {
idx = jdx;
}
}
return {
...state,
data: [
...state.data.slice(0, idx),
...state.data.slice(idx + 1)],
loading: false,
error: null
};
case REMOVE_FAIL:
return {
...state,
loading: false,
error: action.error
};
case CLEAR_ERRORS:
return {
...state,
error: null
};
default:
return state;
}
}
export function isLoaded(globalState) {
return globalState.serviceTypes && globalState.serviceTypes.loaded;
}
export function filter(term) {
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: (client) => client.post('/serviceType/filter/', {data: {title: term}}) // params not used, just shown as demonstration
};
}
export function load() {
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: (client) => client.get('/serviceType/load') // params not used, just shown as demonstration
};
}
export function save(serviceType) {
return {
types: [SAVE, SAVE_SUCCESS, SAVE_FAIL],
id: serviceType.id,
promise: (client) => client.post('/serviceType/save', {
data: serviceType
})
};
}
export function remove(id) {
return {
types: [REMOVE, REMOVE_SUCCESS, REMOVE_FAIL],
id: id,
promise: (client) => client.post('/serviceType/remove', {data: {id: id}})
};
}
export function clearErrors() {
return {
type: CLEAR_ERRORS
};
}
export function editStart(id) {
return { type: EDIT_START, id };
}
export function editStop(id) {
return { type: EDIT_STOP, id };
}
| jairoandre/lance-web-hot | src/redux/modules/serviceTypes.js | JavaScript | mit | 3,767 |
#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid Delux address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
| deluxcoin/delux | src/qt/editaddressdialog.cpp | C++ | mit | 3,729 |
package org.csap.agent.stats.service ;
import java.util.concurrent.TimeUnit ;
import javax.management.MBeanServerConnection ;
import javax.management.ObjectName ;
import org.csap.agent.CsapApis ;
import org.csap.agent.model.ServiceAlertsEnum ;
import org.csap.agent.stats.ServiceCollector ;
import org.csap.helpers.CSAP ;
import org.csap.helpers.CsapApplication ;
//import org.javasimon.CounterSample ;
//import org.javasimon.SimonManager ;
//import org.javasimon.Split ;
//import org.javasimon.StopwatchSample ;
//import org.javasimon.jmx.SimonManagerMXBean ;
import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;
import com.fasterxml.jackson.databind.ObjectMapper ;
import com.fasterxml.jackson.databind.node.ObjectNode ;
public class JmxCustomCollector {
public static final String TOMCAT_SERVLET_CONTEXT_TOKEN = "__CONTEXT__" ;
final Logger logger = LoggerFactory.getLogger( getClass( ) ) ;
ObjectMapper jacksonMapper = new ObjectMapper( ) ;
private ObjectNode deltaLastCollected = jacksonMapper.createObjectNode( ) ;
private ServiceCollector serviceCollector ;
CsapApis csapApis ;
public JmxCustomCollector ( ServiceCollector serviceCollector, CsapApis csapApis ) {
this.serviceCollector = serviceCollector ;
this.csapApis = csapApis ;
}
/**
*
* Each JVM can optionally specify additional attributes to collect
*
* @param instance
* @param serviceNamePort
* @param collectionResults
* @param mbeanConn
*/
public void collect (
MBeanServerConnection mbeanConn ,
ServiceCollectionResults collectionResults ) {
// System.err.println( "\n\n xxx logging issues\n\n " );
logger.debug( "\n\n ============================ Getting JMX Custom Metrics for {} \n\n",
collectionResults.getServiceInstance( ).getServiceName_Port( ) ) ;
collectionResults
.getServiceInstance( )
.getServiceMeters( )
.stream( )
.filter( meter -> ! meter.getMeterType( ).isHttp( ) )
.forEach( serviceMeter -> {
Object attributeCollected = 0 ;
var jmxAttributeTimer = csapApis.metrics( ).startTimer( ) ;
boolean isCollectionSuccesful = false ;
try {
logger.debug( "serviceMeter: {}", serviceMeter ) ;
if ( serviceMeter.getMeterType( ).isMbean( ) ) {
attributeCollected = collectCustomMbean( serviceMeter,
collectionResults, mbeanConn ) ;
// } else if ( serviceMeter.getMeterType().isSimon() ) {
//
// attributeCollected = collectCustomSimon( serviceMeter, simonMgrMxBean,
// mbeanConn, collectionResults ) ;
} else {
logger.warn( "Unexpected meter type: {}", serviceMeter.toString( ) ) ;
throw new Exception( "Unknown metric type" ) ;
}
isCollectionSuccesful = true ;
} catch ( Throwable e ) {
if ( ! serviceMeter.isIgnoreErrors( ) ) {
// SLA will monitor counts
csapApis.metrics( ).incrementCounter( "csap.collect-jmx.service.failures" ) ;
csapApis.metrics( ).incrementCounter( "collect-jmx.service.failures."
+ collectionResults.getServiceInstance( ).getName( ) ) ;
csapApis.metrics( ).incrementCounter( "collect-jmx.service-failures." +
collectionResults.getServiceInstance( ).getName( )
+ "-" + serviceMeter.getCollectionId( ) ) ;
if ( serviceCollector.isShowWarnings( ) ) {
String reason = e.getMessage( ) ;
if ( reason != null && reason.length( ) > 60 ) {
reason = e
.getClass( )
.getName( ) ;
}
logger.warn( CsapApplication.header(
"Failed to collect {} for service {}\n Reason: {}, Cause: {}" ),
serviceMeter.getCollectionId( ), collectionResults.getServiceInstance( )
.getServiceName_Port( ), reason,
e.getCause( ) ) ;
logger.debug( "{}", CSAP.buildCsapStack( e ) ) ;
}
}
logger.debug( "{} Failed getting custom metrics for: {}, reason: {}",
collectionResults.getServiceInstance( ).getServiceName_Port( ),
serviceMeter.getCollectionId( ),
CSAP.buildCsapStack( e ) ) ;
} finally {
long resultLong = -1l ;
if ( attributeCollected instanceof Long ) {
resultLong = (Long) attributeCollected ;
} else if ( attributeCollected instanceof Integer ) {
resultLong = (Integer) attributeCollected ;
} else if ( attributeCollected instanceof Double ) {
Double d = (Double) attributeCollected ;
d = d * serviceMeter.getMultiplyBy( ) ;
if ( serviceMeter.getCollectionId( ).equals( "SystemCpuLoad" )
|| serviceMeter.getCollectionId( ).equals( "ProcessCpuLoad" ) ) {
logger.debug( "Adding multiple by for cpu values: {}", serviceMeter
.getCollectionId( ) ) ;
d = d * 100 ;
} else if ( d < 1 ) {
logger.debug( "{}: Multiplying {} by 1000 to store. Add divideBy 1000",
collectionResults.getServiceInstance( ).getServiceName_Port( ),
serviceMeter.getCollectionId( ) ) ;
d = d * 1000 ;
}
resultLong = Math.round( d ) ;
} else if ( attributeCollected instanceof Boolean ) {
logger.debug( "Got a boolean result" ) ;
Boolean b = (Boolean) attributeCollected ;
if ( b ) {
resultLong = 1 ;
} else {
resultLong = 0 ;
}
}
logger.debug( "{} metric: {} , jmxResultObject: {} , resultLong: {}",
collectionResults.getServiceInstance( ).getName( ),
serviceMeter.getCollectionId( ), attributeCollected, resultLong ) ;
if ( serviceMeter.getCollectionId( ).equalsIgnoreCase( ServiceAlertsEnum.JAVA_HEARTBEAT ) ) {
// for hearbeats, store the time IF it has passed
if ( resultLong == 1 ) {
var nanos = csapApis.metrics( ).stopTimer( jmxAttributeTimer,
"collect-jmx.service-attribute" ) ;
resultLong = TimeUnit.NANOSECONDS.toMillis( nanos ) ;
// some apps return very quickly due to not actually
// implementing. return 1 if that happens
if ( resultLong == 0 ) {
resultLong = 1 ; // minimum of 1 to indicate success
} // for checks.
}
collectionResults
.getServiceInstance( )
.getDefaultContainer( ).setJmxHeartbeatMs( resultLong ) ;
}
if ( ! ( attributeCollected instanceof Double ) ) {
resultLong = resultLong * serviceMeter.getMultiplyBy( ) ;
}
resultLong = Math.round( resultLong / serviceMeter.getDivideBy( serviceCollector
.getCollectionIntervalSeconds( ) ) ) ;
// simon delta is handled in simon collection
if ( serviceMeter.isDelta( ) ) {
long last = resultLong ;
String key = collectionResults.getServiceInstance( ).getServiceName_Port( ) + serviceMeter
.getCollectionId( ) ;
if ( deltaLastCollected.has( key ) && isCollectionSuccesful ) {
resultLong = resultLong - deltaLastCollected.get( key ).asLong( ) ;
if ( resultLong < 0 ) {
resultLong = 0 ;
}
} else {
resultLong = 0 ;
}
// Only update the delta when collection is successful;
// otherwise leave last collected in place
if ( isCollectionSuccesful ) {
deltaLastCollected.put( key, last ) ;
}
}
logger.debug( "\n\n{} ====> metricId: {}, resultLong: {} \n\n",
collectionResults.getServiceInstance( ).getName( ), serviceMeter.getCollectionId( ),
resultLong ) ;
collectionResults.addCustomResultLong( serviceMeter.getCollectionId( ), resultLong ) ;
}
} ) ;
}
private Object collectCustomMbean (
ServiceMeter serviceMeter ,
ServiceCollectionResults jmxResults ,
MBeanServerConnection mbeanConn )
throws Exception {
Object jmxResultObject = 0 ;
String mbeanNameCustom = serviceMeter.getMbeanName( ) ;
if ( mbeanNameCustom.contains( TOMCAT_SERVLET_CONTEXT_TOKEN ) ) {
// Some servlet metrics require version string in name
// logger.info("****** version: " +
// jmxResults.getInstanceConfig().getMavenVersion());
String version = jmxResults
.getServiceInstance( )
.getMavenVersion( ) ;
if ( jmxResults
.getServiceInstance( )
.isScmDeployed( ) ) {
version = jmxResults
.getServiceInstance( )
.getScmVersion( ) ;
version = version.split( " " )[0] ; // first word of
// scm
// scmVersion=3.5.6-SNAPSHOT
// Source build
// by ...
}
// WARNING: version must be updated when testing.
String serviceContext = "//localhost/" + jmxResults
.getServiceInstance( )
.getContext( ) ;
// if ( !jmxResults.getServiceInstance().is_springboot_server() ) {
// serviceContext += "##" + version ;
// }
mbeanNameCustom = mbeanNameCustom.replaceAll( TOMCAT_SERVLET_CONTEXT_TOKEN, serviceContext ) ;
logger.debug( "Using custom name: {} ", mbeanNameCustom ) ;
}
String mbeanAttributeName = serviceMeter.getMbeanAttribute( ) ;
if ( mbeanAttributeName.equals( "SystemCpuLoad" ) ) {
// Reuse already collected values (load is stateful)
jmxResultObject = Long.valueOf( serviceCollector.getCollected_HostCpu( ).get( 0 ).asLong( ) ) ;
} else if ( mbeanAttributeName.equals( "ProcessCpuLoad" ) ) {
// Reuse already collected values
jmxResultObject = Long.valueOf( jmxResults.getCpuPercent( ) ) ;
} else if ( serviceMeter.getCollectionId( ).equalsIgnoreCase( ServiceAlertsEnum.JAVA_HEARTBEAT )
&& ! serviceCollector.isPublishSummaryAndPerformHeartBeat( ) && ! serviceCollector
.isTestHeartBeat( ) ) {
// special case to avoid double heartbeats
// reUse collected value from earlier interval.
jmxResultObject = Long.valueOf( jmxResults.getServiceInstance( ).getDefaultContainer( )
.getJmxHeartbeatMs( ) ) ;
} else {
logger.debug( "Collecting mbean: {}, attribute: {}", mbeanNameCustom, mbeanAttributeName ) ;
jmxResultObject = mbeanConn.getAttribute( new ObjectName( mbeanNameCustom ),
mbeanAttributeName ) ;
}
logger.debug( "Result for {} is: {}", mbeanAttributeName, jmxResultObject ) ;
return jmxResultObject ;
}
}
| csap-platform/csap-core | csap-core-service/src/main/java/org/csap/agent/stats/service/JmxCustomCollector.java | Java | mit | 10,207 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* xxxx-xx-xx, author, first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# ifdef _WIN32
# define _WINSOCK_DEPRECATED_NO_WARNINGS 1
# include <Winsock2.h>
# include <ws2tcpip.h>
# include <Windows.h>
# pragma comment(lib, "ws2_32.lib")
# else
# include <sys/socket.h>
# include <netdb.h>
# include <ifaddrs.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# if defined(__FreeBSD__)
# include <netinet/in.h>
# endif
# endif
# include <dsn/internal/ports.h>
# include <dsn/service_api_c.h>
# include <dsn/cpp/address.h>
# include <dsn/internal/task.h>
# include "group_address.h"
# include "uri_address.h"
namespace dsn
{
const rpc_address rpc_group_address::_invalid;
}
#ifdef _WIN32
static void net_init()
{
static std::once_flag flag;
static bool flag_inited = false;
if (!flag_inited)
{
std::call_once(flag, [&]()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
flag_inited = true;
});
}
}
#endif
// name to ip etc.
DSN_API uint32_t dsn_ipv4_from_host(const char* name)
{
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
if ((addr.sin_addr.s_addr = inet_addr(name)) == (unsigned int)(-1))
{
hostent* hp = ::gethostbyname(name);
int err =
# ifdef _WIN32
(int)::WSAGetLastError()
# else
h_errno
# endif
;
if (hp == nullptr)
{
derror("gethostbyname failed, name = %s, err = %d.", name, err);
return 0;
}
else
{
memcpy(
(void*)&(addr.sin_addr.s_addr),
(const void*)hp->h_addr,
(size_t)hp->h_length
);
}
}
// converts from network byte order to host byte order
return (uint32_t)ntohl(addr.sin_addr.s_addr);
}
// if network_interface is "", then return the first "eth" prefixed non-loopback ipv4 address.
DSN_API uint32_t dsn_ipv4_local(const char* network_interface)
{
uint32_t ret = 0;
# ifndef _WIN32
static const char loopback[4] = { 127, 0, 0, 1 };
struct ifaddrs* ifa = nullptr;
if (getifaddrs(&ifa) == 0)
{
struct ifaddrs* i = ifa;
while (i != nullptr)
{
if (i->ifa_name != nullptr &&
i->ifa_addr != nullptr &&
i->ifa_addr->sa_family == AF_INET
)
{
if (strcmp(i->ifa_name, network_interface) == 0 ||
(network_interface[0] == '\0'
&& strncmp(i->ifa_name, "eth", 3) == 0
&& strncmp((const char*)&((struct sockaddr_in *)i->ifa_addr)->sin_addr.s_addr, loopback, 4) != 0)
)
ret = (uint32_t)ntohl(((struct sockaddr_in *)i->ifa_addr)->sin_addr.s_addr);
break;
}
i = i->ifa_next;
}
if (i == nullptr)
{
derror("get local ip from network interfaces failed, network_interface = %s\n", network_interface);
}
if (ifa != nullptr)
{
// remember to free it
freeifaddrs(ifa);
}
}
#endif
return ret;
}
DSN_API const char* dsn_address_to_string(dsn_address_t addr)
{
char* p = dsn::tls_dsn.scratch_next();
auto sz = sizeof(dsn::tls_dsn.scratch_buffer[0]);
struct in_addr net_addr;
# ifdef _WIN32
char* ip_str;
# else
int ip_len;
# endif
switch (addr.u.v4.type)
{
case HOST_TYPE_IPV4:
net_addr.s_addr = htonl((uint32_t)addr.u.v4.ip);
# ifdef _WIN32
ip_str = inet_ntoa(net_addr);
snprintf_p(p, sz, "%s:%hu", ip_str, (uint16_t)addr.u.v4.port);
# else
inet_ntop(AF_INET, &net_addr, p, sz);
ip_len = strlen(p);
snprintf_p(p + ip_len, sz - ip_len, ":%hu", (uint16_t)addr.u.v4.port);
# endif
break;
case HOST_TYPE_URI:
p = (char*)(uintptr_t)addr.u.uri.uri;
break;
case HOST_TYPE_GROUP:
p = (char*)(((dsn::rpc_group_address*)(uintptr_t)(addr.u.group.group))->name());
break;
default:
p = (char*)"invalid address";
break;
}
return (const char*)p;
}
DSN_API dsn_address_t dsn_address_build(
const char* host,
uint16_t port
)
{
dsn::rpc_address addr(host, port);
return addr.c_addr();
}
DSN_API dsn_address_t dsn_address_build_ipv4(
uint32_t ipv4,
uint16_t port
)
{
dsn::rpc_address addr(ipv4, port);
return addr.c_addr();
}
DSN_API dsn_address_t dsn_address_build_group(
dsn_group_t g
)
{
dsn::rpc_address addr;
addr.assign_group(g);
return addr.c_addr();
}
DSN_API dsn_address_t dsn_address_build_uri(
dsn_uri_t uri
)
{
dsn::rpc_address addr;
addr.assign_uri(uri);
return addr.c_addr();
}
DSN_API dsn_group_t dsn_group_build(const char* name) // must be paired with release later
{
auto g = new ::dsn::rpc_group_address(name);
return g;
}
DSN_API bool dsn_group_add(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
::dsn::rpc_address addr(ep);
return grp->add(addr);
}
DSN_API void dsn_group_set_leader(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
::dsn::rpc_address addr(ep);
grp->set_leader(addr);
}
DSN_API dsn_address_t dsn_group_get_leader(dsn_group_t g)
{
auto grp = (::dsn::rpc_group_address*)(g);
return grp->leader().c_addr();
}
DSN_API bool dsn_group_is_leader(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
return grp->leader() == ep;
}
DSN_API bool dsn_group_is_update_leader_on_rpc_forward(dsn_group_t g)
{
auto grp = (::dsn::rpc_group_address*)(g);
return grp->is_update_leader_on_rpc_forward();
}
DSN_API void dsn_group_set_update_leader_on_rpc_forward(dsn_group_t g, bool v)
{
auto grp = (::dsn::rpc_group_address*)(g);
grp->set_update_leader_on_rpc_forward(v);
}
DSN_API dsn_address_t dsn_group_next(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
::dsn::rpc_address addr(ep);
return grp->next(addr).c_addr();
}
DSN_API dsn_address_t dsn_group_forward_leader(dsn_group_t g)
{
auto grp = (::dsn::rpc_group_address*)(g);
grp->leader_forward();
return grp->leader().c_addr();
}
DSN_API bool dsn_group_remove(dsn_group_t g, dsn_address_t ep)
{
auto grp = (::dsn::rpc_group_address*)(g);
::dsn::rpc_address addr(ep);
return grp->remove(addr);
}
DSN_API void dsn_group_destroy(dsn_group_t g)
{
auto grp = (::dsn::rpc_group_address*)(g);
delete grp;
}
DSN_API dsn_uri_t dsn_uri_build(const char* url) // must be paired with destroy later
{
return (dsn_uri_t)new ::dsn::rpc_uri_address(url);
}
DSN_API void dsn_uri_destroy(dsn_uri_t uri)
{
delete (::dsn::rpc_uri_address*)(uri);
}
| ykwd/rDSN | src/core/core/address.cpp | C++ | mit | 8,222 |
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <stdio.h>
using namespace std;
//Proxy-class for [][] operation
template <typename T>
class Matrix_Row
{
private:
T *row;
size_t m;
public:
Matrix_Row<T>(T* a, size_t cnt) {
row = a;
m = cnt;
}
T& operator[](size_t i) {
if (i >= m) {
assert(!"index out of range");
exit(1);
}
return row[i];
}
};
template <typename T>
class Matrix
{
private:
size_t n; //rows count
size_t m; //columns count
T **arr;
public:
Matrix (int row, int col)
{
arr = (T **)malloc(row * sizeof(T*) + row * col * sizeof(T));
T *buf;
buf = (T*)(arr + row);
for (int i = 0; i < row; ++i) {
arr[i] = buf + i * col;
}
n = row;
m = col;
}
size_t columns()
{
return m;
}
size_t rows()
{
return n;
}
Matrix<T>(const Matrix& mt)
{
int row = mt.n, col = mt.m;
arr = (T **)malloc(row * sizeof(T*) + row * col * sizeof(T));
T *buf;
buf = (T*)(arr + row);
for (int i = 0; i < row; ++i) {
arr[i] = buf + i * col;
}
n = row;
m = col;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
arr[i][j] = mt.arr[i][j];
}
}
}
Matrix<T>& operator=(Matrix& mt)
{
if (this == &mt)
return *this;
int row = mt.n, col = mt.m;
free(arr);
arr = (T **)malloc(row * sizeof(T*) + row * col * sizeof(T));
T *buf;
buf = (T*)(arr + row);
for (int i = 0; i < row; ++i) {
arr[i] = buf + i * col;
}
n = row;
m = col;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
arr[i][j] = mt.arr[i][j];
}
}
return *this;
}
Matrix(Matrix&& mt)
{
n = mt.n;
m = mt.m;
arr = mt.arr;
mt.arr = nullptr;
}
Matrix& operator=(Matrix&& movied)
{
if (this == &movied)
return *this;
free(arr);
arr = movied.arr;
n = movied.n;
m = movied.m;
movied.arr = nullptr;
return *this;
}
Matrix_Row<T> operator[](size_t i)
{
if (i >= n) {
assert(!"index out of range");
exit(1);
}
return Matrix_Row<T>(arr[i], m); //m for check if column index our of range
}
Matrix& operator*=(vector <T> &v)
{
if (m != v.size()) {
assert(!"the vector has an unsuitable length"); //during matrix multiplication on vector from right, vector size must be equal to matrix colimn count
exit(1);
}
Matrix res = Matrix(n, 1);
for (size_t i = 0; i < n; ++i) {
res[i][0] = 0;
for (size_t j = 0; j < m; ++j){
res[i][0] += arr[i][j] * v[j];
}
}
int row = res.n, col = res.m;
free(arr);
arr = (T **)malloc(row * sizeof(T*) + row * col * sizeof(T));
T *buf;
buf = (T*)(arr + row);
for (int i = 0; i < row; ++i) {
arr[i] = buf + i * col;
}
n = row;
m = col;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
arr[i][j] = res.arr[i][j];
}
}
return *this;
}
Matrix& operator*=(T k)
{
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
arr[i][j] *= k;
}
}
return *this;
}
int operator==(Matrix& mt)
{
if (n != mt.rows() || m != mt.columns())
return 0;
int flag = 1;
for (size_t i = 0; i < n && flag; ++i) {
for (size_t j = 0; j < m && flag; ++j) {
flag = (arr[i][j] == mt[i][j]);
}
}
return flag;
}
int operator!=(Matrix& mt)
{
return !(*this == mt);
}
//with_size - flag of outputing matrix sizes
//format - format string for 1 element of matrix
void print(int with_size, char *format)
{
if (with_size) {
printf("%lu %lu\n", n, m);
}
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
printf(format, arr[i][j]);
}
printf("\n");
}
}
//print version with standart format of each element outputing
void print(int with_size)
{
char c[] = "%lf ";
print(with_size, c);
}
~Matrix() {
free(arr);
}
};
| mtrempoltsev/msu_cpp_autumn_2017 | homework/Zimnyukov/05/Matrix.cpp | C++ | mit | 4,826 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.spring.autoconfigure.cosmos;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.spring.autoconfigure.cosmos.domain.Person;
import com.azure.spring.autoconfigure.cosmos.domain.PersonRepository;
import com.azure.spring.data.cosmos.core.CosmosTemplate;
import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter;
import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext;
import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class CosmosRepositoriesAutoConfigurationUnitTest {
private AnnotationConfigApplicationContext context;
private CosmosTemplate cosmosTemplate;
@BeforeAll
public void beforeAll() {
cosmosTemplate = mock(CosmosTemplate.class);
CosmosMappingContext mappingContext = new CosmosMappingContext();
MappingCosmosConverter cosmosConverter = new MappingCosmosConverter(mappingContext, new ObjectMapper());
when(cosmosTemplate.getContainerProperties(any())).thenReturn(mock(CosmosContainerProperties.class));
when(cosmosTemplate.getConverter()).thenReturn(cosmosConverter);
}
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@AfterEach
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void testDefaultRepositoryConfiguration() throws Exception {
prepareApplicationContext(TestConfiguration.class);
assertNotNull(this.context.getBean(PersonRepository.class));
}
@Test
public void autoConfigNotKickInIfManualConfigDidNotCreateRepositories() throws Exception {
prepareApplicationContext(InvalidCustomConfiguration.class);
assertThrows(NoSuchBeanDefinitionException.class,
() -> this.context.getBean(PersonRepository.class));
}
private void prepareApplicationContext(Class<?>... configurationClasses) {
this.context = new AnnotationConfigApplicationContext();
this.context.register(configurationClasses);
this.context.register(CosmosRepositoriesAutoConfiguration.class);
this.context.getBeanFactory().registerSingleton("cosmosTemplate", cosmosTemplate);
this.context.refresh();
}
@Configuration
@TestAutoConfigurationPackage(Person.class)
protected static class TestConfiguration {
}
@Configuration
@EnableCosmosRepositories("foo.bar")
@TestAutoConfigurationPackage(CosmosRepositoriesAutoConfigurationUnitTest.class)
protected static class InvalidCustomConfiguration {
}
}
| Azure/azure-sdk-for-java | sdk/spring/azure-spring-boot/src/test/java/com/azure/spring/autoconfigure/cosmos/CosmosRepositoriesAutoConfigurationUnitTest.java | Java | mit | 3,673 |
<?php
include('class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Username = "Xarafire";
$mail->Password = "symwe!@#123";
$fromname = "Asiimwe Apollo Abraham";
$To = trim($email,"\r\n");
$tContent = '';
$abcd="Stuff is Hard";
$tContent .="<table width='550px' colspan='2' cellpadding='4'>
<tr><td align='center'><img src='imgpath' width='100' height='100'></td></tr>
<tr><td height='20'> </td></tr>
<tr>
<td>
<table cellspacing='1' cellpadding='1' width='100%' height='100%'>
<tr><td align='center'><h2>Hello World<h2></td></tr/>
<tr><td> </td></tr>
<tr><td align='center'>Name: ".trim(NAME,"\r\n")."</td></tr>
<tr><td align='center'>ABCD TEXT: ".$abcd."</td></tr>
<tr><td> </td></tr>
</table>
</td>
</tr>
</table>";
$mail->From = "aasiimwe@dcareug.com";
$mail->FromName = $fromname;
$mail->Subject = "John Doe";
$mail->Body = $tContent;
$mail->AddAddress($To);
$mail->set('X-Priority', '1'); //Priority 1 = High, 3 = Normal, 5 = low
$mail->Send(); | aasiimweDataCare/Dev_ftf | Dev_CPM/testMail.php | PHP | mit | 1,437 |
export namespace StorageUtils {
let hasLocalStorageCache: boolean;
export function hasLocalStorage(): boolean {
if (hasLocalStorageCache) {
return hasLocalStorageCache;
}
// hasLocalStorage is used to safely ensure we can use localStorage
// taken from https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Feature-detecting_localStorage
let storage: any = { length: 0 };
try {
storage = window['localStorage'];
let x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
hasLocalStorageCache = true;
}
catch (e) {
hasLocalStorageCache = e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0;
}
return hasLocalStorageCache;
}
/**
* Stores a string item into localStorage.
* @param key the item's key
* @param data the item's data
*/
export function setItem(key: string, data: string): void {
if (StorageUtils.hasLocalStorage()) {
window.localStorage.setItem(key, data);
}
}
/**
* Gets an item's string value from the localStorage.
* @param key the key to look up its associated value
* @return {string | null} Returns the string if found, null if there is no data stored for the key
*/
export function getItem(key: string): string | null {
if (StorageUtils.hasLocalStorage()) {
return window.localStorage.getItem(key);
} else {
return null;
}
}
/**
* Stores an object into localStorage. The object will be serialized to JSON. The following types are supported
* in addition to the default types:
* - ColorUtils.Color
*
* @param key the key to store the data to
* @param data the object to store
*/
export function setObject<T>(key: string, data: T): void {
if (StorageUtils.hasLocalStorage()) {
let json = JSON.stringify(data);
setItem(key, json);
}
}
/**
* Gets an object for the given key from localStorage. The object will be deserialized from JSON. Beside the
* default types, the following types are supported:
* - ColorUtils.Color
*
* @param key the key to look up its associated object
* @return {any} Returns the object if found, null otherwise
*/
export function getObject<T>(key: string): T {
if (StorageUtils.hasLocalStorage()) {
let json = getItem(key);
if (key) {
let object = JSON.parse(json);
return <T>object;
}
}
return null;
}
}
| bitmovin/bitmovin-player-ui | src/ts/storageutils.ts | TypeScript | mit | 2,905 |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Text;
namespace BrowserNatives {
class Maximize {
//Consts
const int SW_SHOWMAXIMIZED = 3;
//Imports
[DllImport("user32.dll")]
static extern bool IsZoomed (IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
//Methods
static void MaximizeWindow (IntPtr hWnd) {
using (new ForegroundWindowGuard())
ShowWindow(hWnd, SW_SHOWMAXIMIZED);
}
static void CheckIsWindowMaximized (IntPtr hWnd) {
Console.Out.WriteLine(IsZoomed(hWnd));
}
static void Main (string[] args) {
if (args.Length == 0 || args.Length > 2) {
Console.Error.Write("Incorrect arguments");
Environment.Exit(1);
}
IntPtr hWnd = (IntPtr)int.Parse(args[0]);
bool isStatusQuery = false;
if (args.Length == 2) {
if (args[1] == "status")
isStatusQuery = true;
else {
Console.Error.Write("Incorrect arguments");
Environment.Exit(1);
}
}
if (isStatusQuery)
CheckIsWindowMaximized(hWnd);
else
MaximizeWindow(hWnd);
}
}
}
| AndreyBelym/testcafe-browser-tools | src/natives/maximize/win/Maximize.cs | C# | mit | 1,625 |
package fr.rohichi.engine3d;
public class Pair {
public int x;
public int y;
}
| Rohichi/3DEngine | src/fr/rohichi/engine3d/Pair.java | Java | mit | 88 |
package info.pinlab.ttada.dbcache;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqliteConnectionWrapper {
private final String url;
Connection conn = null;
Statement statement = null;
private String tableName = "pinjson";
private SqliteConnectionWrapper(String url) throws SQLException{
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("DB can't be loaded!");
}
this.url = url;
conn = DriverManager.getConnection(this.url);
this.statement = conn.createStatement();
if(isTableExists()){
//-- great, do nothing --//
}else{
this.statement.executeUpdate("create table " + tableName +" (id integer, json string)");
}
}
private boolean isTableExists() throws SQLException{
DatabaseMetaData meta = conn.getMetaData();
ResultSet tables = meta.getTables(null, null, null, new String[] {"TABLE"});
while(tables.next()){
if(tableName.equals(tables.getString("TABLE_NAME"))){
return true;
}
}
return false;
}
public String readJsonString(String id){
return null;
}
/**
* Updates or creates json data with given id.
*
* @param id for json string
* @param json the json string (escaped)
* @return the id
*/
public String updateJsonString(String id, String json){
return null;
}
public boolean close(){
try{
if(!conn.isClosed()){
conn.close();
return true;
}
}catch(SQLException log){
//-- ignore --//
}
return false;
}
public static class SqliteConnectionBuilder{
String name = null;
String path = null; //-- DB save path - if exists
public SqliteConnectionBuilder setDbName(String name){
this.name = name;
return this;
}
public SqliteConnectionBuilder setDbPath(String path){
this.path = path;
return this;
}
public SqliteConnectionWrapper build(){
if (name == null){
throw new IllegalStateException("DB name can't be null!");
}
SqliteConnectionWrapper conn = null;
try{
conn = new SqliteConnectionWrapper("jdbc:sqlite:sample.db" + name);
}catch(SQLException e){
throw new IllegalStateException("DB error: '" + e.getMessage() + "'");
}
return conn;
}
}
}
| kinokocchi/Ttada | parent/dbcache/src/main/java/info/pinlab/ttada/dbcache/SqliteConnectionWrapper.java | Java | mit | 2,370 |
'use strict';
// 서비스 단위 테스트
describe('서비스 단위 테스트', function() {
beforeEach(module('myApp.services'));
describe('버전 서비스 테스트', function() {
it('현재 버전 반환', inject(function(version) {
expect(version).toEqual('0.1');
}));
});
});
| eu81273/angularjs-testing-example | test/unit/servicesSpec.js | JavaScript | mit | 313 |
<?php
namespace AMQPy;
use AMQPEnvelope;
use AMQPQueue;
use AMQPy\Client\Delivery;
use AMQPy\Serializers\Exceptions\SerializerException;
use AMQPy\Serializers\SerializersPool;
use AMQPy\Support\DeliveryBuilder;
use Exception;
abstract class AbstractListener
{
private $queue;
private $serializers;
private $builder;
private $read_timeout;
public function __construct(AMQPQueue $queue, SerializersPool $serializers_pool, DeliveryBuilder $delivery_builder)
{
$this->serializers = $serializers_pool;
$this->queue = $queue;
$this->builder = $delivery_builder;
}
public function getQueue()
{
return $this->queue;
}
public function getSerializers()
{
return $this->serializers;
}
public function getBuilder()
{
return $this->builder;
}
public function isEndless()
{
return !$this->queue->getConnection()->getReadTimeout();
}
public function setEndless($is_endless)
{
$is_endless = (bool)$is_endless;
if ($this->isEndless() === $is_endless) {
return $is_endless;
}
if ($is_endless) {
$this->read_timeout = $this->queue->getConnection()->getReadTimeout();
$this->queue->getConnection()->setReadTimeout(0);
} else {
if ($this->read_timeout) {
$this->queue->getConnection()->setReadTimeout($this->read_timeout);
$this->read_timeout = null;
}
}
return $is_endless;
}
public function get($auto_ack = false)
{
$envelope = $this->queue->get($auto_ack ? AMQP_AUTOACK : AMQP_NOPARAM);
if ($envelope) {
$delivery = $this->builder->build($envelope);
} else {
$delivery = null;
}
return $delivery;
}
/**
* Attach consumer to process payload from queue
*
* @param AbstractConsumer $consumer Consumer to process payload and handle possible errors
* @param bool $auto_ack Should message been acknowledged upon receive
*
* @return mixed
*
* @throws SerializerException
* @throws Exception Any exception from pre/post-consume handlers and from exception handler
*/
public function consume(AbstractConsumer $consumer, $auto_ack = false)
{
if (!$consumer->active()) {
// prevent dirty consumer been listening on queue
return;
}
$outside_error = null;
try {
$consumer->begin($this);
$this->queue->consume(
function (AMQPEnvelope $envelope /*, AMQPQueue $queue*/) use ($consumer) {
$delivery = $this->builder->build($envelope);
$this->feed($delivery, $consumer);
return $consumer->active();
}, $auto_ack ? AMQP_AUTOACK : AMQP_NOPARAM
);
} catch (Exception $e) {
$outside_error = $e;
}
try {
$this->queue->cancel();
} catch (Exception $e) {
}
$consumer->end($this, $outside_error);
if ($outside_error) {
throw $outside_error;
}
}
abstract public function feed(Delivery $delivery, AbstractConsumer $consumer);
public function accept(Delivery $delivery)
{
return $this->queue->ack($delivery->getEnvelope()->getDeliveryTag());
}
public function resend(Delivery $delivery)
{
$this->queue->nack($delivery->getEnvelope()->getDeliveryTag(), AMQP_REQUEUE);
}
public function drop(Delivery $delivery)
{
$this->queue->nack($delivery->getEnvelope()->getDeliveryTag());
}
}
| pinepain/amqpy | src/AMQPy/AbstractListener.php | PHP | mit | 3,816 |
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the marsExploration function below.
static int marsExploration(String s) {
int count = 0;
char[] c = s.toCharArray();
for(int i=0;i<c.length-2;i+=3) {
if(c[i]!='S') count++;
if(c[i+1]!='O') count++;
if(c[i+2]!='S') count++;
}
return count;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String s = scanner.nextLine();
int result = marsExploration(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
| dusadpiyush96/Competetive | HackerRank/Algorithm/Strings/MarsExploration.java | Java | mit | 1,004 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using Common;
namespace CustomControls
{
public partial class PasswordMeter : UserControl
{
private string password;
private LinearGradientBrush brush = null;
#region Color Array
private Color[] Colors = {
Color.FromArgb(255,255,0,0),
Color.FromArgb(255,255,1,0),
Color.FromArgb(255,255,2,0),
Color.FromArgb(255,255,4,0),
Color.FromArgb(255,255,5,0),
Color.FromArgb(255,255,6,0),
Color.FromArgb(255,255,7,0),
Color.FromArgb(255,255,8,0),
Color.FromArgb(255,255,10,0),
Color.FromArgb(255,255,11,0),
Color.FromArgb(255,255,12,0),
Color.FromArgb(255,255,13,0),
Color.FromArgb(255,255,15,0),
Color.FromArgb(255,255,16,0),
Color.FromArgb(255,255,17,0),
Color.FromArgb(255,255,19,0),
Color.FromArgb(255,255,20,0),
Color.FromArgb(255,255,21,0),
Color.FromArgb(255,255,22,0),
Color.FromArgb(255,255,23,0),
Color.FromArgb(255,255,25,0),
Color.FromArgb(255,255,26,0),
Color.FromArgb(255,255,27,0),
Color.FromArgb(255,255,28,0),
Color.FromArgb(255,255,30,0),
Color.FromArgb(255,255,31,0),
Color.FromArgb(255,255,32,0),
Color.FromArgb(255,255,34,0),
Color.FromArgb(255,255,35,0),
Color.FromArgb(255,255,36,0),
Color.FromArgb(255,255,37,0),
Color.FromArgb(255,255,38,0),
Color.FromArgb(255,255,40,0),
Color.FromArgb(255,255,41,0),
Color.FromArgb(255,255,42,0),
Color.FromArgb(255,255,43,0),
Color.FromArgb(255,255,44,0),
Color.FromArgb(255,255,46,0),
Color.FromArgb(255,255,47,0),
Color.FromArgb(255,255,48,0),
Color.FromArgb(255,255,49,0),
Color.FromArgb(255,255,51,0),
Color.FromArgb(255,255,52,0),
Color.FromArgb(255,255,53,0),
Color.FromArgb(255,255,55,0),
Color.FromArgb(255,255,56,0),
Color.FromArgb(255,255,57,0),
Color.FromArgb(255,255,58,0),
Color.FromArgb(255,255,59,0),
Color.FromArgb(255,255,61,0),
Color.FromArgb(255,255,62,0),
Color.FromArgb(255,255,63,0),
Color.FromArgb(255,255,64,0),
Color.FromArgb(255,255,66,0),
Color.FromArgb(255,255,67,0),
Color.FromArgb(255,255,68,0),
Color.FromArgb(255,255,70,0),
Color.FromArgb(255,255,71,0),
Color.FromArgb(255,255,72,0),
Color.FromArgb(255,255,73,0),
Color.FromArgb(255,255,74,0),
Color.FromArgb(255,255,76,0),
Color.FromArgb(255,255,77,0),
Color.FromArgb(255,255,78,0),
Color.FromArgb(255,255,80,0),
Color.FromArgb(255,255,81,0),
Color.FromArgb(255,255,82,0),
Color.FromArgb(255,255,83,0),
Color.FromArgb(255,255,85,0),
Color.FromArgb(255,255,86,0),
Color.FromArgb(255,255,87,0),
Color.FromArgb(255,255,88,0),
Color.FromArgb(255,255,89,0),
Color.FromArgb(255,255,91,0),
Color.FromArgb(255,255,92,0),
Color.FromArgb(255,255,93,0),
Color.FromArgb(255,255,95,0),
Color.FromArgb(255,255,96,0),
Color.FromArgb(255,255,97,0),
Color.FromArgb(255,255,98,0),
Color.FromArgb(255,255,100,0),
Color.FromArgb(255,255,101,0),
Color.FromArgb(255,255,102,0),
Color.FromArgb(255,255,103,0),
Color.FromArgb(255,255,104,0),
Color.FromArgb(255,255,106,0),
Color.FromArgb(255,255,107,0),
Color.FromArgb(255,255,108,0),
Color.FromArgb(255,255,110,0),
Color.FromArgb(255,255,111,0),
Color.FromArgb(255,255,112,0),
Color.FromArgb(255,255,113,0),
Color.FromArgb(255,255,115,0),
Color.FromArgb(255,255,116,0),
Color.FromArgb(255,255,117,0),
Color.FromArgb(255,255,118,0),
Color.FromArgb(255,255,119,0),
Color.FromArgb(255,255,121,0),
Color.FromArgb(255,255,122,0),
Color.FromArgb(255,255,123,0),
Color.FromArgb(255,255,124,0),
Color.FromArgb(255,255,125,0),
Color.FromArgb(255,255,127,0),
Color.FromArgb(255,255,128,0),
Color.FromArgb(255,255,129,0),
Color.FromArgb(255,255,131,0),
Color.FromArgb(255,255,132,0),
Color.FromArgb(255,255,133,0),
Color.FromArgb(255,255,134,0),
Color.FromArgb(255,255,136,0),
Color.FromArgb(255,255,137,0),
Color.FromArgb(255,255,138,0),
Color.FromArgb(255,255,139,0),
Color.FromArgb(255,255,140,0),
Color.FromArgb(255,255,142,0),
Color.FromArgb(255,255,143,0),
Color.FromArgb(255,255,144,0),
Color.FromArgb(255,255,146,0),
Color.FromArgb(255,255,147,0),
Color.FromArgb(255,255,148,0),
Color.FromArgb(255,255,149,0),
Color.FromArgb(255,255,151,0),
Color.FromArgb(255,255,152,0),
Color.FromArgb(255,255,153,0),
Color.FromArgb(255,255,154,0),
Color.FromArgb(255,255,155,0),
Color.FromArgb(255,255,155,0),
Color.FromArgb(255,255,156,0),
Color.FromArgb(255,255,157,0),
Color.FromArgb(255,255,158,0),
Color.FromArgb(255,255,159,0),
Color.FromArgb(255,255,159,0),
Color.FromArgb(255,255,160,0),
Color.FromArgb(255,255,161,0),
Color.FromArgb(255,255,162,0),
Color.FromArgb(255,255,163,0),
Color.FromArgb(255,255,163,0),
Color.FromArgb(255,255,164,0),
Color.FromArgb(255,255,165,0),
Color.FromArgb(255,255,166,0),
Color.FromArgb(255,255,167,0),
Color.FromArgb(255,255,167,0),
Color.FromArgb(255,255,168,0),
Color.FromArgb(255,255,169,0),
Color.FromArgb(255,255,170,0),
Color.FromArgb(255,255,171,0),
Color.FromArgb(255,255,171,0),
Color.FromArgb(255,255,172,0),
Color.FromArgb(255,255,173,0),
Color.FromArgb(255,255,174,0),
Color.FromArgb(255,255,175,0),
Color.FromArgb(255,255,175,0),
Color.FromArgb(255,255,176,0),
Color.FromArgb(255,255,177,0),
Color.FromArgb(255,255,178,0),
Color.FromArgb(255,255,179,0),
Color.FromArgb(255,255,179,0),
Color.FromArgb(255,255,180,0),
Color.FromArgb(255,255,181,0),
Color.FromArgb(255,255,181,0),
Color.FromArgb(255,255,182,0),
Color.FromArgb(255,255,183,0),
Color.FromArgb(255,255,184,0),
Color.FromArgb(255,255,185,0),
Color.FromArgb(255,255,185,0),
Color.FromArgb(255,255,186,0),
Color.FromArgb(255,255,187,0),
Color.FromArgb(255,255,188,0),
Color.FromArgb(255,255,189,0),
Color.FromArgb(255,255,189,0),
Color.FromArgb(255,255,190,0),
Color.FromArgb(255,255,191,0),
Color.FromArgb(255,255,192,0),
Color.FromArgb(255,255,193,0),
Color.FromArgb(255,255,193,0),
Color.FromArgb(255,255,194,0),
Color.FromArgb(255,255,195,0),
Color.FromArgb(255,255,196,0),
Color.FromArgb(255,255,197,0),
Color.FromArgb(255,255,197,0),
Color.FromArgb(255,255,198,0),
Color.FromArgb(255,255,199,0),
Color.FromArgb(255,255,200,0),
Color.FromArgb(255,255,201,0),
Color.FromArgb(255,255,201,0),
Color.FromArgb(255,255,202,0),
Color.FromArgb(255,255,203,0),
Color.FromArgb(255,255,204,0),
Color.FromArgb(255,255,205,0),
Color.FromArgb(255,255,205,0),
Color.FromArgb(255,255,206,0),
Color.FromArgb(255,255,207,0),
Color.FromArgb(255,255,208,0),
Color.FromArgb(255,255,209,0),
Color.FromArgb(255,255,209,0),
Color.FromArgb(255,255,210,0),
Color.FromArgb(255,255,211,0),
Color.FromArgb(255,255,212,0),
Color.FromArgb(255,255,213,0),
Color.FromArgb(255,255,213,0),
Color.FromArgb(255,255,214,0),
Color.FromArgb(255,255,215,0),
Color.FromArgb(255,255,216,0),
Color.FromArgb(255,255,217,0),
Color.FromArgb(255,255,217,0),
Color.FromArgb(255,255,218,0),
Color.FromArgb(255,255,219,0),
Color.FromArgb(255,255,220,0),
Color.FromArgb(255,255,221,0),
Color.FromArgb(255,255,221,0),
Color.FromArgb(255,255,222,0),
Color.FromArgb(255,255,223,0),
Color.FromArgb(255,255,224,0),
Color.FromArgb(255,255,225,0),
Color.FromArgb(255,255,225,0),
Color.FromArgb(255,255,226,0),
Color.FromArgb(255,255,227,0),
Color.FromArgb(255,255,228,0),
Color.FromArgb(255,255,229,0),
Color.FromArgb(255,255,229,0),
Color.FromArgb(255,255,230,0),
Color.FromArgb(255,255,231,0),
Color.FromArgb(255,255,232,0),
Color.FromArgb(255,255,233,0),
Color.FromArgb(255,255,233,0),
Color.FromArgb(255,255,234,0),
Color.FromArgb(255,255,235,0),
Color.FromArgb(255,255,236,0),
Color.FromArgb(255,255,237,0),
Color.FromArgb(255,255,237,0),
Color.FromArgb(255,255,238,0),
Color.FromArgb(255,255,239,0),
Color.FromArgb(255,255,240,0),
Color.FromArgb(255,255,241,0),
Color.FromArgb(255,255,241,0),
Color.FromArgb(255,255,242,0),
Color.FromArgb(255,255,243,0),
Color.FromArgb(255,255,244,0),
Color.FromArgb(255,255,245,0),
Color.FromArgb(255,255,245,0),
Color.FromArgb(255,255,246,0),
Color.FromArgb(255,255,247,0),
Color.FromArgb(255,255,248,0),
Color.FromArgb(255,255,249,0),
Color.FromArgb(255,255,249,0),
Color.FromArgb(255,255,250,0),
Color.FromArgb(255,255,251,0),
Color.FromArgb(255,255,252,0),
Color.FromArgb(255,255,253,0),
Color.FromArgb(255,255,253,0),
Color.FromArgb(255,255,254,0),
Color.FromArgb(255,255,255,0),
Color.FromArgb(255,255,255,0),
Color.FromArgb(255,254,254,1),
Color.FromArgb(255,253,254,1),
Color.FromArgb(255,252,254,1),
Color.FromArgb(255,251,253,2),
Color.FromArgb(255,251,253,2),
Color.FromArgb(255,250,252,3),
Color.FromArgb(255,249,252,3),
Color.FromArgb(255,248,252,3),
Color.FromArgb(255,247,251,4),
Color.FromArgb(255,247,251,4),
Color.FromArgb(255,246,250,5),
Color.FromArgb(255,245,250,5),
Color.FromArgb(255,244,250,5),
Color.FromArgb(255,243,249,6),
Color.FromArgb(255,243,249,6),
Color.FromArgb(255,242,248,7),
Color.FromArgb(255,241,248,7),
Color.FromArgb(255,240,248,7),
Color.FromArgb(255,239,247,8),
Color.FromArgb(255,239,247,8),
Color.FromArgb(255,238,247,8),
Color.FromArgb(255,237,246,9),
Color.FromArgb(255,237,246,9),
Color.FromArgb(255,236,245,10),
Color.FromArgb(255,235,245,10),
Color.FromArgb(255,234,245,10),
Color.FromArgb(255,233,244,11),
Color.FromArgb(255,233,244,11),
Color.FromArgb(255,232,243,12),
Color.FromArgb(255,231,243,12),
Color.FromArgb(255,230,243,12),
Color.FromArgb(255,230,242,13),
Color.FromArgb(255,229,242,13),
Color.FromArgb(255,228,242,13),
Color.FromArgb(255,227,241,14),
Color.FromArgb(255,227,241,14),
Color.FromArgb(255,226,240,15),
Color.FromArgb(255,225,240,15),
Color.FromArgb(255,224,240,15),
Color.FromArgb(255,223,239,16),
Color.FromArgb(255,223,239,16),
Color.FromArgb(255,222,238,17),
Color.FromArgb(255,221,238,17),
Color.FromArgb(255,220,238,17),
Color.FromArgb(255,219,237,18),
Color.FromArgb(255,219,237,18),
Color.FromArgb(255,218,236,19),
Color.FromArgb(255,217,236,19),
Color.FromArgb(255,216,236,19),
Color.FromArgb(255,215,235,20),
Color.FromArgb(255,215,235,20),
Color.FromArgb(255,214,234,21),
Color.FromArgb(255,213,234,21),
Color.FromArgb(255,213,234,21),
Color.FromArgb(255,212,233,22),
Color.FromArgb(255,211,233,22),
Color.FromArgb(255,210,233,22),
Color.FromArgb(255,209,232,23),
Color.FromArgb(255,209,232,23),
Color.FromArgb(255,208,231,24),
Color.FromArgb(255,207,231,24),
Color.FromArgb(255,206,231,24),
Color.FromArgb(255,205,230,25),
Color.FromArgb(255,205,230,25),
Color.FromArgb(255,204,229,26),
Color.FromArgb(255,203,229,26),
Color.FromArgb(255,202,229,26),
Color.FromArgb(255,201,228,27),
Color.FromArgb(255,201,228,27),
Color.FromArgb(255,200,227,28),
Color.FromArgb(255,199,227,28),
Color.FromArgb(255,198,227,28),
Color.FromArgb(255,197,226,29),
Color.FromArgb(255,197,226,29),
Color.FromArgb(255,196,226,29),
Color.FromArgb(255,195,225,30),
Color.FromArgb(255,195,225,30),
Color.FromArgb(255,194,224,31),
Color.FromArgb(255,193,224,31),
Color.FromArgb(255,192,224,31),
Color.FromArgb(255,191,223,32),
Color.FromArgb(255,191,223,32),
Color.FromArgb(255,190,222,33),
Color.FromArgb(255,189,222,33),
Color.FromArgb(255,188,222,33),
Color.FromArgb(255,187,221,34),
Color.FromArgb(255,187,221,34),
Color.FromArgb(255,186,220,35),
Color.FromArgb(255,185,220,35),
Color.FromArgb(255,184,220,35),
Color.FromArgb(255,183,219,36),
Color.FromArgb(255,183,219,36),
Color.FromArgb(255,182,219,36),
Color.FromArgb(255,181,218,37),
Color.FromArgb(255,181,218,37),
Color.FromArgb(255,180,217,38),
Color.FromArgb(255,179,217,38),
Color.FromArgb(255,178,217,38),
Color.FromArgb(255,177,216,39),
Color.FromArgb(255,177,216,39),
Color.FromArgb(255,176,215,40),
Color.FromArgb(255,175,215,40),
Color.FromArgb(255,174,215,40),
Color.FromArgb(255,173,214,41),
Color.FromArgb(255,173,214,41),
Color.FromArgb(255,172,213,42),
Color.FromArgb(255,171,213,42),
Color.FromArgb(255,171,213,42),
Color.FromArgb(255,170,212,43),
Color.FromArgb(255,169,212,43),
Color.FromArgb(255,168,212,43),
Color.FromArgb(255,167,211,44),
Color.FromArgb(255,167,211,44),
Color.FromArgb(255,166,210,45),
Color.FromArgb(255,165,210,45),
Color.FromArgb(255,164,210,45),
Color.FromArgb(255,163,209,46),
Color.FromArgb(255,163,209,46),
Color.FromArgb(255,162,208,47),
Color.FromArgb(255,161,208,47),
Color.FromArgb(255,160,208,47),
Color.FromArgb(255,159,207,48),
Color.FromArgb(255,159,207,48),
Color.FromArgb(255,158,206,49),
Color.FromArgb(255,157,206,49),
Color.FromArgb(255,156,206,49),
Color.FromArgb(255,155,205,50),
Color.FromArgb(255,155,205,50),
Color.FromArgb(255,154,205,50),
Color.FromArgb(255,153,204,51),
Color.FromArgb(255,152,203,51),
Color.FromArgb(255,151,202,50),
Color.FromArgb(255,149,202,50),
Color.FromArgb(255,148,201,49),
Color.FromArgb(255,146,200,49),
Color.FromArgb(255,145,199,48),
Color.FromArgb(255,144,198,48),
Color.FromArgb(255,143,197,48),
Color.FromArgb(255,141,196,47),
Color.FromArgb(255,140,195,47),
Color.FromArgb(255,139,194,46),
Color.FromArgb(255,137,194,46),
Color.FromArgb(255,136,193,45),
Color.FromArgb(255,134,192,45),
Color.FromArgb(255,133,191,44),
Color.FromArgb(255,132,190,44),
Color.FromArgb(255,131,189,44),
Color.FromArgb(255,129,188,43),
Color.FromArgb(255,128,187,43),
Color.FromArgb(255,127,186,42),
Color.FromArgb(255,125,186,42),
Color.FromArgb(255,124,184,41),
Color.FromArgb(255,122,184,41),
Color.FromArgb(255,121,183,40),
Color.FromArgb(255,120,182,40),
Color.FromArgb(255,119,181,40),
Color.FromArgb(255,118,180,39),
Color.FromArgb(255,116,179,39),
Color.FromArgb(255,115,178,38),
Color.FromArgb(255,113,178,38),
Color.FromArgb(255,112,177,37),
Color.FromArgb(255,111,176,37),
Color.FromArgb(255,109,175,36),
Color.FromArgb(255,108,174,36),
Color.FromArgb(255,107,173,36),
Color.FromArgb(255,106,172,35),
Color.FromArgb(255,104,171,35),
Color.FromArgb(255,103,170,34),
Color.FromArgb(255,101,170,34),
Color.FromArgb(255,100,169,33),
Color.FromArgb(255,98,168,33),
Color.FromArgb(255,97,167,32),
Color.FromArgb(255,96,166,32),
Color.FromArgb(255,95,165,32),
Color.FromArgb(255,93,164,31),
Color.FromArgb(255,92,163,31),
Color.FromArgb(255,91,162,30),
Color.FromArgb(255,89,162,30),
Color.FromArgb(255,88,160,29),
Color.FromArgb(255,86,160,29),
Color.FromArgb(255,85,159,28),
Color.FromArgb(255,84,158,28),
Color.FromArgb(255,83,157,28),
Color.FromArgb(255,81,156,27),
Color.FromArgb(255,80,155,27),
Color.FromArgb(255,79,154,26),
Color.FromArgb(255,77,154,26),
Color.FromArgb(255,76,152,25),
Color.FromArgb(255,74,152,25),
Color.FromArgb(255,73,151,24),
Color.FromArgb(255,72,150,24),
Color.FromArgb(255,70,149,23),
Color.FromArgb(255,69,148,23),
Color.FromArgb(255,68,147,23),
Color.FromArgb(255,67,146,22),
Color.FromArgb(255,65,145,22),
Color.FromArgb(255,64,144,21),
Color.FromArgb(255,62,144,21),
Color.FromArgb(255,61,143,20),
Color.FromArgb(255,59,142,20),
Color.FromArgb(255,58,141,19),
Color.FromArgb(255,57,140,19),
Color.FromArgb(255,56,139,19),
Color.FromArgb(255,54,138,18),
Color.FromArgb(255,53,137,18),
Color.FromArgb(255,52,136,17),
Color.FromArgb(255,50,136,17),
Color.FromArgb(255,49,135,16),
Color.FromArgb(255,47,134,16),
Color.FromArgb(255,46,133,15),
Color.FromArgb(255,45,132,15),
Color.FromArgb(255,44,131,15),
Color.FromArgb(255,42,130,14),
Color.FromArgb(255,41,129,14),
Color.FromArgb(255,40,128,13),
Color.FromArgb(255,38,128,13),
Color.FromArgb(255,37,126,12),
Color.FromArgb(255,35,126,12),
Color.FromArgb(255,34,125,11),
Color.FromArgb(255,33,124,11),
Color.FromArgb(255,32,123,11),
Color.FromArgb(255,31,122,10),
Color.FromArgb(255,29,122,10),
Color.FromArgb(255,28,120,9),
Color.FromArgb(255,26,120,9),
Color.FromArgb(255,25,119,8),
Color.FromArgb(255,24,118,8),
Color.FromArgb(255,22,117,7),
Color.FromArgb(255,21,116,7),
Color.FromArgb(255,20,115,7),
Color.FromArgb(255,19,114,6),
Color.FromArgb(255,17,113,6),
Color.FromArgb(255,16,112,5),
Color.FromArgb(255,14,112,5),
Color.FromArgb(255,13,111,4),
Color.FromArgb(255,11,110,4),
Color.FromArgb(255,10,109,3),
Color.FromArgb(255,9,108,3),
Color.FromArgb(255,8,107,3),
Color.FromArgb(255,6,106,2),
Color.FromArgb(255,5,105,2),
Color.FromArgb(255,4,104,1),
Color.FromArgb(255,2,104,1),
Color.FromArgb(255,1,102,0),
Color.FromArgb(255,0,102,0),
Color.FromArgb(255,0,102,0),
Color.FromArgb(255,0,102,0)};
#endregion
public PasswordMeter()
{
InitializeComponent();
password = "";
UpdateControl();
}
public void SetPassword(String pwd)
{
password = pwd;
UpdateControl();
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (brush != null)
e.Graphics.FillRectangle(brush, this.ClientRectangle);
}
private void UpdateControl()
{
int score = PasswordUtils.ComputePasswordScore(password);
lbText.Text = PasswordUtils.GetPasswordStrengthText(score);
int x1 = score * 4;
int x2 = x1 + 99;
if (x2 >= 500) x2 = 499;
Color clr1 = Colors[x1];
Color clr2 = Colors[x2];
if (brush != null)
{
brush.Dispose();
brush = null;
}
brush = new LinearGradientBrush(
new Point(0, 0),
new Point(this.Width, this.Height),
clr1,
clr2);
Refresh();
}
private void PasswordMeter_Load(object sender, EventArgs e)
{
// Needed to ensure control is drawn correctly at start up.
SetPassword("");
}
}
}
| sassy224/PasswordTextBox | CustomControls/PasswordMeter.cs | C# | mit | 33,534 |
try:
print 'Importing ....'
from base import * # noqa
from local import * # noqa
except ImportError:
import traceback
print traceback.format_exc()
print 'Unable to find moderation/settings/local.py'
try:
from post_env_commons import * # noqa
except ImportError:
pass
| CareerVillage/slack-moderation | src/moderation/settings/__init__.py | Python | mit | 305 |
class LockerController < ApplicationController
def index
@filenames = Dir.glob(File.join(APP_CONFIG[:locker], '*'))
end
end | jronallo/digitization-locker | app/controllers/locker_controller.rb | Ruby | mit | 131 |
using Autofac;
using AutoMapper;
using Miningcore.Blockchain.Ergo.Configuration;
using Miningcore.Configuration;
using Miningcore.Extensions;
using Miningcore.Messaging;
using Miningcore.Mining;
using Miningcore.Payments;
using Miningcore.Persistence;
using Miningcore.Persistence.Model;
using Miningcore.Persistence.Repositories;
using Miningcore.Time;
using Miningcore.Util;
using Block = Miningcore.Persistence.Model.Block;
using Contract = Miningcore.Contracts.Contract;
using static Miningcore.Util.ActionUtils;
namespace Miningcore.Blockchain.Ergo;
[CoinFamily(CoinFamily.Ergo)]
public class ErgoPayoutHandler : PayoutHandlerBase,
IPayoutHandler
{
public ErgoPayoutHandler(
IComponentContext ctx,
IConnectionFactory cf,
IMapper mapper,
IShareRepository shareRepo,
IBlockRepository blockRepo,
IBalanceRepository balanceRepo,
IPaymentRepository paymentRepo,
IMasterClock clock,
IMessageBus messageBus) :
base(cf, mapper, shareRepo, blockRepo, balanceRepo, paymentRepo, clock, messageBus)
{
Contract.RequiresNonNull(ctx, nameof(ctx));
Contract.RequiresNonNull(balanceRepo, nameof(balanceRepo));
Contract.RequiresNonNull(paymentRepo, nameof(paymentRepo));
this.ctx = ctx;
}
protected readonly IComponentContext ctx;
protected ErgoClient ergoClient;
private string network;
private ErgoPaymentProcessingConfigExtra extraPoolPaymentProcessingConfig;
protected override string LogCategory => "Ergo Payout Handler";
private class PaymentException : Exception
{
public PaymentException(string msg) : base(msg)
{
}
}
private void ReportAndRethrowApiError(string action, Exception ex, bool rethrow = true)
{
var error = ex.Message;
if(ex is ApiException<ApiError> apiException)
error = apiException.Result.Detail ?? apiException.Result.Reason;
logger.Warn(() => $"{action}: {error}");
if(rethrow)
throw ex;
}
private async Task UnlockWallet(CancellationToken ct)
{
logger.Info(() => $"[{LogCategory}] Unlocking wallet");
var walletPassword = extraPoolPaymentProcessingConfig.WalletPassword ?? string.Empty;
await Guard(() => ergoClient.WalletUnlockAsync(new Body4 {Pass = walletPassword}, ct), ex =>
{
if (ex is ApiException<ApiError> apiException)
{
var error = apiException.Result.Detail;
if (error != null && !error.ToLower().Contains("already unlocked"))
throw new PaymentException($"Failed to unlock wallet: {error}");
}
else
throw ex;
});
logger.Info(() => $"[{LogCategory}] Wallet unlocked");
}
private async Task LockWallet(CancellationToken ct)
{
logger.Info(() => $"[{LogCategory}] Locking wallet");
await Guard(() => ergoClient.WalletLockAsync(ct),
ex => ReportAndRethrowApiError("Failed to lock wallet", ex));
logger.Info(() => $"[{LogCategory}] Wallet locked");
}
#region IPayoutHandler
public virtual async Task ConfigureAsync(ClusterConfig clusterConfig, PoolConfig poolConfig, CancellationToken ct)
{
Contract.RequiresNonNull(poolConfig, nameof(poolConfig));
logger = LogUtil.GetPoolScopedLogger(typeof(ErgoPayoutHandler), poolConfig);
this.poolConfig = poolConfig;
this.clusterConfig = clusterConfig;
extraPoolPaymentProcessingConfig = poolConfig.PaymentProcessing.Extra.SafeExtensionDataAs<ErgoPaymentProcessingConfigExtra>();
ergoClient = ErgoClientFactory.CreateClient(poolConfig, clusterConfig, null);
// detect chain
var info = await ergoClient.GetNodeInfoAsync(ct);
network = ErgoConstants.RegexChain.Match(info.Name).Groups[1].Value.ToLower();
}
public virtual async Task<Block[]> ClassifyBlocksAsync(IMiningPool pool, Block[] blocks, CancellationToken ct)
{
Contract.RequiresNonNull(poolConfig, nameof(poolConfig));
Contract.RequiresNonNull(blocks, nameof(blocks));
if(blocks.Length == 0)
return blocks;
var coin = poolConfig.Template.As<ErgoCoinTemplate>();
var pageSize = 100;
var pageCount = (int) Math.Ceiling(blocks.Length / (double) pageSize);
var result = new List<Block>();
var minConfirmations = extraPoolPaymentProcessingConfig?.MinimumConfirmations ?? (network == "mainnet" ? 720 : 72);
var minerRewardsPubKey = await ergoClient.MiningReadMinerRewardPubkeyAsync(ct);
var minerRewardsAddress = await ergoClient.MiningReadMinerRewardAddressAsync(ct);
for(var i = 0; i < pageCount; i++)
{
// get a page full of blocks
var page = blocks
.Skip(i * pageSize)
.Take(pageSize)
.ToArray();
// fetch header ids for blocks in page
var headerBatch = page.Select(block => ergoClient.GetFullBlockAtAsync((int) block.BlockHeight, ct)).ToArray();
await Guard(()=> Task.WhenAll(headerBatch),
ex=> logger.Debug(ex));
for(var j = 0; j < page.Length; j++)
{
var block = page[j];
var headerTask = headerBatch[j];
if(!headerTask.IsCompletedSuccessfully)
{
if(headerTask.IsFaulted)
logger.Warn(()=> $"Failed to fetch block {block.BlockHeight}: {headerTask.Exception?.InnerException?.Message ?? headerTask.Exception?.Message}");
else
logger.Warn(()=> $"Failed to fetch block {block.BlockHeight}: {headerTask.Status.ToString().ToLower()}");
continue;
}
var headerIds = headerTask.Result;
// fetch blocks
var blockBatch = headerIds.Select(x=> ergoClient.GetFullBlockByIdAsync(x, ct)).ToArray();
await Guard(()=> Task.WhenAll(blockBatch),
ex=> logger.Debug(ex));
var blockHandled = false;
var pkMismatchCount = 0;
var nonceMismatchCount = 0;
var coinbaseNonWalletTxCount = 0;
foreach (var blockTask in blockBatch)
{
if(blockHandled)
break;
if(!blockTask.IsCompletedSuccessfully)
continue;
var fullBlock = blockTask.Result;
// only consider blocks with pow-solution pk matching ours
if(fullBlock.Header.PowSolutions.Pk != minerRewardsPubKey.RewardPubKey)
{
pkMismatchCount++;
continue;
}
// only consider blocks with pow-solution nonce matching what we have on file
if(fullBlock.Header.PowSolutions.N != block.TransactionConfirmationData)
{
nonceMismatchCount++;
continue;
}
var coinbaseWalletTxFound = false;
// reset block reward
block.Reward = 0;
foreach(var blockTx in fullBlock.BlockTransactions.Transactions)
{
var walletTx = await Guard(()=> ergoClient.WalletGetTransactionAsync(blockTx.Id, ct));
var coinbaseOutput = walletTx?.Outputs?.FirstOrDefault(x => x.Address == minerRewardsAddress.RewardAddress);
if(coinbaseOutput != null)
{
coinbaseWalletTxFound = true;
block.ConfirmationProgress = Math.Min(1.0d, (double) walletTx.NumConfirmations / minConfirmations);
block.Reward += coinbaseOutput.Value / ErgoConstants.SmallestUnit;
block.Hash = fullBlock.Header.Id;
if(walletTx.NumConfirmations >= minConfirmations)
{
// matured and spendable coinbase transaction
block.Status = BlockStatus.Confirmed;
block.ConfirmationProgress = 1;
}
}
}
blockHandled = coinbaseWalletTxFound;
if(blockHandled)
{
result.Add(block);
if(block.Status == BlockStatus.Confirmed)
{
logger.Info(() => $"[{LogCategory}] Unlocked block {block.BlockHeight} worth {FormatAmount(block.Reward)}");
messageBus.NotifyBlockUnlocked(poolConfig.Id, block, coin);
}
else
messageBus.NotifyBlockConfirmationProgress(poolConfig.Id, block, coin);
}
else
coinbaseNonWalletTxCount++;
}
if(!blockHandled)
{
string orphanReason = null;
if(pkMismatchCount == blockBatch.Length)
orphanReason = "pk mismatch";
else if(nonceMismatchCount == blockBatch.Length)
orphanReason = "nonce mismatch";
else if(coinbaseNonWalletTxCount == blockBatch.Length)
orphanReason = "no related coinbase tx found in wallet";
if(!string.IsNullOrEmpty(orphanReason))
{
block.Status = BlockStatus.Orphaned;
block.Reward = 0;
result.Add(block);
logger.Info(() => $"[{LogCategory}] Block {block.BlockHeight} classified as orphaned due to {orphanReason}");
messageBus.NotifyBlockUnlocked(poolConfig.Id, block, coin);
}
}
}
}
return result.ToArray();
}
public virtual Task CalculateBlockEffortAsync(IMiningPool pool, Block block, double accumulatedBlockShareDiff, CancellationToken ct)
{
block.Effort = accumulatedBlockShareDiff * ErgoConstants.ShareMultiplier / block.NetworkDifficulty;
return Task.FromResult(true);
}
public override double AdjustShareDifficulty(double difficulty)
{
return difficulty * ErgoConstants.ShareMultiplier;
}
public virtual async Task PayoutAsync(IMiningPool pool, Balance[] balances, CancellationToken ct)
{
Contract.RequiresNonNull(balances, nameof(balances));
// build args
var amounts = balances
.Where(x => x.Amount > 0)
.ToDictionary(x => x.Address, x => Math.Round(x.Amount, 4));
if(amounts.Count == 0)
return;
var balancesTotal = amounts.Sum(x => x.Value);
try
{
logger.Info(() => $"[{LogCategory}] Paying {FormatAmount(balances.Sum(x => x.Amount))} to {balances.Length} addresses");
// get wallet status
var status = await ergoClient.GetWalletStatusAsync(ct);
if(!status.IsInitialized)
throw new PaymentException($"Wallet is not initialized");
if(!status.IsUnlocked)
await UnlockWallet(ct);
// get balance
var walletBalances = await ergoClient.WalletBalancesAsync(ct);
var walletTotal = walletBalances.Balance / ErgoConstants.SmallestUnit;
logger.Info(() => $"[{LogCategory}] Current wallet balance is {FormatAmount(walletTotal)}");
// bail if balance does not satisfy payments
if(walletTotal < balancesTotal)
{
logger.Warn(() => $"[{LogCategory}] Wallet balance currently short of {FormatAmount(balancesTotal - walletTotal)}. Will try again.");
return;
}
// validate addresses
logger.Info("Validating addresses ...");
foreach(var pair in amounts)
{
var validity = await Guard(() => ergoClient.CheckAddressValidityAsync(pair.Key, ct));
if(validity == null || !validity.IsValid)
logger.Warn(()=> $"Address {pair.Key} is not valid!");
}
// Create request batch
var requests = amounts.Select(x => new PaymentRequest
{
Address = x.Key,
Value = (long) (x.Value * ErgoConstants.SmallestUnit),
}).ToArray();
var txId = await Guard(()=> ergoClient.WalletPaymentTransactionGenerateAndSendAsync(requests, ct), ex =>
{
if(ex is ApiException<ApiError> apiException)
{
var error = apiException.Result.Detail ?? apiException.Result.Reason;
if(error.Contains("reason:"))
error = error.Substring(error.IndexOf("reason:"));
throw new PaymentException($"Payment transaction failed: {error}");
}
else
throw ex;
});
if(string.IsNullOrEmpty(txId))
throw new PaymentException("Payment transaction failed to return a transaction id");
// payment successful
logger.Info(() => $"[{LogCategory}] Payment transaction id: {txId}");
await PersistPaymentsAsync(balances, txId);
NotifyPayoutSuccess(poolConfig.Id, balances, new[] {txId}, null);
}
catch(PaymentException ex)
{
logger.Error(() => $"[{LogCategory}] {ex.Message}");
NotifyPayoutFailure(poolConfig.Id, balances, ex.Message, null);
}
finally
{
await LockWallet(ct);
}
}
#endregion // IPayoutHandler
}
| coinfoundry/miningcore | src/Miningcore/Blockchain/Ergo/ErgoPayoutHandler.cs | C# | mit | 14,286 |
<?php
Breadcrumbs::for('admin.email-templates.index', function ($trail) {
$trail->push(__('labels.backend.access.email-templates.management'), route('admin.email-templates.index'));
});
Breadcrumbs::for('admin.email-templates.create', function ($trail) {
$trail->parent('admin.email-templates.index');
$trail->push(__('labels.backend.access.email-templates.management'), route('admin.email-templates.create'));
});
Breadcrumbs::for('admin.email-templates.edit', function ($trail, $id) {
$trail->parent('admin.email-templates.index');
$trail->push(__('labels.backend.access.email-templates.management'), route('admin.email-templates.edit', $id));
});
| viralsolani/laravel-adminpanel | routes/breadcrumbs/backend/email-templates/email-template.php | PHP | mit | 673 |
package gosquare
type Meta struct {
Code int `json:"code"`
ErrorType string `json:"errorType"`
ErrorDetails string `json:"errorDetails"`
}
type Notifications []Notification
type Notification struct {
Type string `json:"type"`
Item interface{} `json:"item"`
}
| aykutaras/gosquare | base.go | GO | mit | 286 |
package Mod.Items;
import java.util.List;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.item.EnumToolMaterial;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import Mod.Lib.Refrence;
import Mod.Main.Main;
import Mod.Misc.MiscDamage;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ModItemSilverSword extends ItemSword {
public ModItemSilverSword(int i, EnumToolMaterial enumToolMaterial){
super(i, enumToolMaterial);
setCreativeTab(Main.CreativeTab);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister)
{
this.itemIcon = par1IconRegister.registerIcon(Refrence.Mod_Id + ":" + "SilverSword");
}
public boolean hitEntity(ItemStack itemstack, EntityLivingBase EntityHit, EntityLivingBase EntityAttacker)
{
if(EntityHit instanceof EntityDragon || EntityHit instanceof EntityWither || EntityHit instanceof EntityPlayer){
}else{
EntityHit.attackEntityFrom(new MiscDamage("Silver Sword", StatCollector.translateToLocal("string.death.silversword").replace("%Killed", EntityHit.getTranslatedEntityName().replace("%Killer", EntityAttacker.getTranslatedEntityName()))), 80F);
EntityHit.attackEntityAsMob(EntityHit);
if (itemstack.stackTagCompound == null){
itemstack.setTagCompound(new NBTTagCompound());
}
if(itemstack.stackTagCompound.getInteger("Kills") == 0){
itemstack.stackTagCompound.setInteger("Kills", 1);
}else{
itemstack.stackTagCompound.setInteger("Kills", itemstack.stackTagCompound.getInteger("Kills") + 1);
}
itemstack.stackTagCompound.setString("LastMob", EntityHit.getTranslatedEntityName());
itemstack.attemptDamageItem(1, EntityHit.worldObj.rand);
}
return false;
}
public void onCreated(ItemStack item, World world, EntityPlayer player) {
if (item.stackTagCompound == null){
item.setTagCompound(new NBTTagCompound());
}
item.stackTagCompound.setString("MadeBy", player.username);
}
@Override
public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean par4)
{
list.add(StatCollector.translateToLocal("items.desc.silversword.1"));
if(itemstack.stackTagCompound != null){
list.add(StatCollector.translateToLocal("items.desc.silversword.2") + ": " + itemstack.stackTagCompound.getInteger("Kills"));
if(itemstack.stackTagCompound.getString("LastMob") == null)
list.add(StatCollector.translateToLocal("items.desc.silversword.4"));
else
list.add(StatCollector.translateToLocal("items.desc.silversword.3") + ": " + itemstack.stackTagCompound.getString("LastMob"));
if(itemstack.stackTagCompound.getString("MadeBy") == null)
list.add(StatCollector.translateToLocal("items.desc.silversword.6"));
else
list.add(StatCollector.translateToLocal("items.desc.silversword.5") + ": " + itemstack.stackTagCompound.getString("MadeBy"));
}else{
list.add(StatCollector.translateToLocal("items.desc.silversword.2") + ": 0");
list.add(StatCollector.translateToLocal("items.desc.silversword.4"));
list.add(StatCollector.translateToLocal("items.desc.silversword.6"));
}
}
public boolean getIsRepairable(ItemStack par1ItemStack, ItemStack par2ItemStack)
{
return false;
}
} | tm1990/MiscItemsAndBlocks | common/Mod/Items/ModItemSilverSword.java | Java | mit | 4,575 |
<?php
namespace Dflydev\EncryptedFigCookies\Encryption\Adapter;
use Dflydev\EncryptedFigCookies\Encryption\Encryption;
use Zend\Filter\Decrypt;
use Zend\Filter\Encrypt;
class ZendCryptEncryption implements Encryption
{
/**
* @var Decrypt
*/
private $decrypt;
/**
* @var Encrypt
*/
private $encrypt;
public function __construct(Decrypt $decrypt, Encrypt $encrypt)
{
$this->decrypt = $decrypt;
$this->encrypt = $encrypt;
}
public function decrypt($value)
{
return $this->decrypt->filter($value);
}
public function encrypt($value)
{
return $this->encrypt->filter($value);
}
}
| dflydev/dflydev-encrypted-fig-cookies | src/Dflydev/EncryptedFigCookies/Encryption/Adapter/ZendCryptEncryption.php | PHP | mit | 684 |
<?php
namespace Lyra;
use Lyra\Interfaces\Widget;
class WidgetRegistry implements \Lyra\Interfaces\WidgetRegistry
{
/**
* {@inheritdoc}
*/
protected $widgets;
public function __construct()
{
$this->widgets = [];
}
/**
* {@inheritdoc}
*/
public function addWidget(\Lyra\Interfaces\Widget $widget)
{
return $this->widgets[$widget->getName()] = $widget;
}
/**
* {@inheritdoc}
*/
public function getWidget($alias)
{
if (!isset($this->widgets[$alias])) {
throw new ServiceNotFoundException(sprintf('Widget %s is actually not load into the WidgetRegistry'),
$alias);
}
return $this->widgets[$alias];
}
}
| uaktags/lyraEngine | src/WidgetRegistry.php | PHP | mit | 754 |
package com.tactfactory.harmony.platform.android.updater;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import com.tactfactory.harmony.generator.BaseGenerator;
import com.tactfactory.harmony.platform.IAdapter;
import com.tactfactory.harmony.updater.IAddEntityField;
import com.tactfactory.harmony.utils.ConsoleUtils;
import com.tactfactory.harmony.utils.TactFileUtils;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class AddEntityFieldAndroid implements IAddEntityField{
private final String templatePath;
private final String sourceFile;
public AddEntityFieldAndroid(
String templatePath,
String sourceFile) {
this.templatePath = templatePath;
this.sourceFile = sourceFile;
}
@Override
public void execute(BaseGenerator<? extends IAdapter> generator) {
File file = new File(this.sourceFile);
if (file != null && file.isFile()) {
String strFile = TactFileUtils.fileToString(file);
try {
final Template tpl = generator.getCfg().getTemplate(this.templatePath);
StringWriter out = new StringWriter();
tpl.process(generator.getDatamodel(), out);
strFile = strFile.substring(0,
strFile.lastIndexOf('}'));
strFile = strFile.concat(out.toString() + "\n}");
TactFileUtils.writeStringToFile(file, strFile);
} catch (IOException | TemplateException e) {
ConsoleUtils.displayError(e);
}
}
}
}
| TACTfactory/harmony-core | src/com/tactfactory/harmony/platform/android/updater/AddEntityFieldAndroid.java | Java | mit | 1,647 |
<?php
namespace Sideclick\EntityHelperBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SideclickEntityHelperBundle extends Bundle
{
}
| Sideclick/EntityHelperBundle | src/SideclickEntityHelperBundle.php | PHP | mit | 150 |
#ifndef COMPONENT_HPP
#define COMPONENT_HPP
#include "messages/spa_subscription_reply.hpp"
#include "messages/spa_subscription_request.hpp"
#include "messages/spa_data.hpp"
#include "spa_communicator.hpp"
#include "spa_message.hpp"
#include <iostream>
#include <memory>
#include <vector>
struct Subscriber
{
Subscriber(LogicalAddress la, uint16_t d)
: subscriberAddress(la), deliveryRateDivisor(d) {}
LogicalAddress subscriberAddress;
uint16_t deliveryRateDivisor;
};
class Component
{
public:
typedef std::shared_ptr<SpaCommunicator> Com;
Component(Com communicator = nullptr, LogicalAddress address = LogicalAddress(0, 0))
: communicator(communicator),
address(address),
dialogId(0),
publishIter(1)
{
subscribers.reserve(8); // Default to 8 subscribers
}
virtual ~Component() {}
//virtual void appShutdown() = 0;
void publish();
virtual void sendSpaData(LogicalAddress) = 0;
virtual void handleSpaData(std::shared_ptr<SpaMessage>) = 0;
virtual void appInit() = 0;
void sendMsg(std::shared_ptr<SpaMessage> message)
{
if (message == nullptr || communicator == nullptr)
{
return;
}
communicator->send(message);
}
void receiveMessage(std::shared_ptr<SpaMessage>);
void handleSubscriptionReply(std::shared_ptr<SpaMessage>);
void registerSubscriptionRequest(std::shared_ptr<SpaMessage>);
void subscribe(
LogicalAddress producer,
uint8_t priority,
uint32_t leasePeriod,
uint16_t deliveryRateDivisor);
Com communicator;
protected:
LogicalAddress address;
uint8_t publishIter;
uint16_t dialogId;
std::vector<Subscriber> subscribers; // Should we make this a vector of pointers?
};
#endif
| SmallSatGasTeam/OpenSPA | lib/component.hpp | C++ | mit | 1,736 |
<!-- Replaced strings -->
<form class="form-signin form-horizontal" id="replaced_strings_form" role="form">
<div class="col-sm-10 col-sm-offset-4">
<h2 class="form-signin-heading"><?= $this->lang->line("replaced_string_settings"); ?></h2>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-6">
<input type="text" id="alert_word_count" name="alert_word_count" class="form-control" placeholder="<?= $this->lang->line("username"); ?>" required autofocus>
</div>
</div>
</div>
</form> | boh1996/TwitterAnalytics | v1/application/views/admin_strings_view.php | PHP | mit | 511 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.spring.data.gremlin.repository.config;
import org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport;
import org.springframework.data.repository.config.RepositoryConfigurationExtension;
import java.lang.annotation.Annotation;
public class GremlinRepositoryRegistrar extends RepositoryBeanDefinitionRegistrarSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {
return EnableGremlinRepositories.class;
}
@Override
protected RepositoryConfigurationExtension getExtension() {
return new GremlinRepositoryConfigurationExtension();
}
}
| selvasingh/azure-sdk-for-java | sdk/spring/azure-spring-data-gremlin/src/main/java/com/microsoft/spring/data/gremlin/repository/config/GremlinRepositoryRegistrar.java | Java | mit | 746 |
/*
* Message.cc
*
* Created on: Apr 13, 2014
* Author: wilfeli
*/
#include "Message.h"
Message::Message(std::string s_):type(s_){};
MessagePSSendPayment::MessagePSSendPayment(IPSAgent* a_, double q_, std::string type_):
Message(type_), getter(a_), q(q_){};
MessagePSSendPayment::MessagePSSendPayment(double q_, std::string type_):
Message(type_), q(q_){};
//MessageSellC::MessageSellC(Message* inf_, Contract<Agent, Agent>* c_): inf(inf_), contract(c_){
// type = "SellC";
//};
MessageMarketLSellC::MessageMarketLSellC
(MarketL* _sender, IBuyerL* _buyer, double _p, double _q):
sender(_sender), buyer(_buyer), p(_p), q(_q) {
type = "MarketLSellC";
};
MessageMarketCSellGoodC::MessageMarketCSellGoodC
(MarketC* _sender, IBuyerC* _buyer, double _p, double _q):
sender(_sender), buyer(_buyer), p(_p), q(_q) {
type = "MarketCSellGoodC";
};
MessageMarketLCheckAsk::MessageMarketLCheckAsk
(MarketL* _sender, double _p_eq): sender(_sender), p_eq(_p_eq){
type = "MarketLCheckAsk";
};
MessageMarketLCheckBid::MessageMarketLCheckBid
(MarketL* _sender, double _p_eq): sender(_sender), p_eq(_p_eq){
type = "MarketLCheckBid";
};
MessageMarketCCheckAsk::MessageMarketCCheckAsk
(MarketC* _sender, double _p_eq): sender(_sender), p_eq(_p_eq){
type = "MarketCCheckAsk";
};
MessageMarketCCheckBid::MessageMarketCCheckBid
(MarketC* _sender, double _p_eq): sender(_sender), p_eq(_p_eq){
type = "MarketCCheckBid";
};
MessageGoodC::MessageGoodC(double q_, double p_): q(q_), p(p_){
type = "asGC";
};
MessageBankruptcy::MessageBankruptcy(F* agent_): agent(agent_){
type = "Bankruptcy";
};
MessageBankruptcyH::MessageBankruptcyH(H* agent_): agent(agent_){
type = "Bankruptcy";
};
MessageMakeDec::MessageMakeDec(){
type = "MakeDec";
};
MessageStatus::MessageStatus(double status_): status(status_){
type = "Status";
};
| wilfeli/DMGameBasic | src/Message.cpp | C++ | mit | 1,845 |
import React, { PropTypes, Component } from 'react';
import cx from 'classnames';
import Modal from '../Modal';
import FontIcon from '../FontIcon';
import s from './AssignTo.scss';
class AssignTo extends Component {
state = {
nodeIdx: null,
treeData: [],
};
componentDidMount = () => this.setState({
nodeIdx: this.props.document.tags,
treeData: this.props.treeData.map(node =>
this.props.document.tags.indexOf(node.id) !== -1
? Object.assign({}, node, { isTarget: true })
: Object.assign({}, node, { isTarget: false })
),
});
/**
* Handles dismiss
*/
handleOnDismiss = () => this.props.onCancel();
/**
* Handles confirmation
*/
handleOnConfirm = () => {
this.props.onConfirm(this.props.document._id, this.state.nodeIdx);
this.handleOnDismiss();
};
/**
* Handles click on tree view's element
* @param {String} id - Current Tree Node
* @param {Event} event - Event
* @param isDisabled {Boolean}
*/
handleOnClickOnTreeItem = (id, event, isDisabled) => {
event.stopPropagation();
if (!isDisabled) {
const { nodeIdx } = this.state;
const newNodeIdx = nodeIdx.indexOf(id) !== -1
? nodeIdx.filter(node => node !== id) // remove if already added
: [...new Set([...this.state.nodeIdx, id])];
this.setState({
nodeIdx: newNodeIdx,
isRoot: false,
treeData: this.state.treeData.map(node =>
newNodeIdx.indexOf(node.id) !== -1
? Object.assign({}, node, { isTarget: true })
: Object.assign({}, node, { isTarget: false })
),
});
}
};
/**
* Handles key down on tree view's element
* @param {String} id - Current Tree Node ID
* @param {Event} event - Event
* @param isDisabled {Boolean}
*/
handleOnKeyDownOnTreeItem = (id, event, isDisabled) => {
if (!isDisabled) {
if (event.keyCode === 13 || event.keyCode === 32) {
this.handleOnClickOnTreeItem(id, event, isDisabled); // enter or space
}
}
};
/**
* Render tree item
* @param {Object} [node] Tree Node
* @param {number} [key]
* @return {XML} Tree Item.
*/
renderChild = (node) => {
const { treeData } = this.state;
const { canAssignSystemTags } = this.props;
const isDisabled = !canAssignSystemTags && node.isSystem;
const children = node
? treeData.map(child => child.parentId === node.id ? this.renderChild(child) : null)
: null;
return node.id === '0' ? null : (
<li
role="treeitem" key={node.id} tabIndex="0"
onClick={(event) => this.handleOnClickOnTreeItem(node.id, event, isDisabled)}
onKeyDown={(event) => this.handleOnKeyDownOnTreeItem(node.id, event)}
className={cx(s.child, {
[s.child_target]: node.isTarget,
[s.child_disabled]: isDisabled,
})}
>
<div className={s.item}>
<FontIcon
name={cx({
['folder']: node.isTarget,
['folder-o']: !node.isTarget,
})}
/>
<span>{node.name}</span>
</div>
<ul className={s.node} role="group">
{ children }
</ul>
</li>
);
};
render() {
const { strCancelLabel, strCaption, strSaveLabel } = this.props;
const { nodeIdx, treeData } = this.state;
return (
<Modal
caption={strCaption}
confirmText={strSaveLabel}
customBodyClassName={s.muted}
dismissText={strCancelLabel}
isConfirmDisabled={nodeIdx === null}
onConfirm={this.handleOnConfirm}
onDismiss={this.handleOnDismiss}
>
<div className={s.tree}>
<ul className={s.node} role="tree">
{ treeData.map(node =>
node.isRoot
? this.renderChild(node)
: null
)}
</ul>
</div>
</Modal>
);
}
}
AssignTo.propTypes = {
canAssignSystemTags: PropTypes.bool,
document: PropTypes.object,
message: PropTypes.string,
onCancel: PropTypes.func,
onConfirm: PropTypes.func,
onMount: PropTypes.func,
strCancelLabel: PropTypes.string,
strCaption: PropTypes.string,
strSaveLabel: PropTypes.string,
tagId: PropTypes.string,
tagName: PropTypes.string,
treeData: PropTypes.array,
};
AssignTo.defaultProps = {
canAssignSystemTags: false,
message: '',
treeData: [],
};
export default AssignTo;
| peinanshow/react-redux-samples | src/components/common/AssignTo/AssignTo.js | JavaScript | mit | 4,465 |
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AppConfig, AppRequest } from '../shared/index';
import { UserModel } from '../+users/user.interface';
import { TranslationComponent } from '../shared/translation/translation.component';
import { CacheComponent } from '../shared/cache/cache.component';
import { AlertComponent } from 'ng2-bootstrap/ng2-bootstrap';
@Component({
moduleId: module.id,
selector: 'sd-profile',
templateUrl: 'profile.component.html',
directives: [AlertComponent],
providers: [AppConfig, AppRequest]
})
export class ProfileComponent {
private _apiUrl = "user";
private _errorMessage: any;
hostUpload: string;
tr: any;
alerts: any = {};
model: UserModel;
userBack: any;
constructor(
private _tr: TranslationComponent,
private _cache: CacheComponent,
private _appRequest: AppRequest
) {
this.tr = _tr.getTranslation(_cache.getItem('lang'));
_cache.dataAdded$.subscribe((data: any) => {
if (data.hasOwnProperty('user')) this.model = data['user'];
this.model.chpassword = false;
this.model.password = "";
this.model.newpassword = "";
this.model.newrepassword = "";
this.userBack = this.model;
if (data.hasOwnProperty('lang')) {
this.tr = _tr.getTranslation(data['lang']);
}
});
}
isValid() {
let valid = true;
if (!this.model.email || !this.model.role) {
valid = false;
}
if (this.model.chpassword && (
!this.model.password || this.model.password.length < 5 ||
!this.model.newpassword || this.model.newpassword.length < 5 ||
!this.model.newrepassword || this.model.newrepassword.length < 5
)) {
valid = false;
}
return valid;
}
/**
* Send update request to API
*/
changeProfile() {
let sendData = [this.model];
this._appRequest.putAction(this._apiUrl, sendData)
.subscribe((res: any) => {
if (res.hasOwnProperty("warning")) {
this.alerts.warning = this.tr[res.warning];
}
if (res.hasOwnProperty("info")) {
if (res.info === 1) {
this.alerts.info = this.tr.profileChanged;
}
if (res.info === 0) {
this.alerts.warning = this.tr.profileNotChanged;
this.model = this.userBack;
}
}
},
(error: any) => this._errorMessage = error
);
}
/**
* Close profile info alert
*/
closeAlert(alert: string) {
this.alerts[alert] = null;
}
}
| martinsvb/Angular2_bootstrap_seed | src/client/app/+profile/profile.component.ts | TypeScript | mit | 2,850 |
/*
The MIT License (MIT)
Copyright (c) 2014 Harun Hasdal
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.
*/
package com.github.harunhasdal.livecycle.sftp;
public class SFTPParameterException extends RuntimeException {
public SFTPParameterException() {
super();
}
public SFTPParameterException(String s) {
super(s);
}
public SFTPParameterException(String s, Throwable throwable) {
super(s, throwable);
}
public SFTPParameterException(Throwable throwable) {
super(throwable);
}
}
| harunhasdal/sftp-connector | src/main/java/com/github/harunhasdal/livecycle/sftp/SFTPParameterException.java | Java | mit | 1,476 |
import test from 'tape';
import Validation from '../../src/validation';
import _ from 'lodash';
const v = new Validation();
test('isFalse: validates isFalse', t => {
let rule = {a: "isFalse"};
t.equal(v.validate({a: false}, rule), undefined);
t.deepEqual(v.validate({a: true}, rule), {a: ['must be false']});
rule = {a: {validate: "isFalse", message: '${$propertyPath}:${$value} is not false'}};
t.equal(v.validate({a: false}, rule), undefined);
t.deepEqual(v.validate({a: true}, rule), {a: ['a:true is not false']});
rule = {
a: {
validate: "isFalse",
value: "b < c",
message: "b:${$this.b} must be greater than c:${$this.c}"
}
};
t.equal(v.validate({a: true, b: 2, c: 1}, rule), undefined);
t.deepEqual(v.validate({a: false, b: 1, c: 2}, rule), {a: ['b:1 must be greater than c:2']});
rule = {
a: [{
validate: "isFalse",
value: "b < c",
message: "b:${$this.b} must be greater than c:${$this.c}"
}]
};
t.equal(v.validate({a: true, b: 2, c: 1}, rule), undefined);
t.deepEqual(v.validate({a: false, b: 1, c: 2}, rule), {a: ['b:1 must be greater than c:2']});
t.end();
});
| buttonwoodcx/bcx-validation | test/standard-transformers-and-validators/is-false.spec.js | JavaScript | mit | 1,160 |
/*
Copyright (c) 2007 Danny Chapman
http://www.rowlhouse.co.uk
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/**
* @author Muzer(muzerly@gmail.com)
* @link http://code.google.com/p/jiglibflash
*/
(function(jigLib){
var Vector3D=jigLib.Vector3D;
var JConfig=jigLib.JConfig;
var Vector3D=jigLib.Vector3D;
var Matrix3D=jigLib.Matrix3D;
var JMatrix3D=jigLib.JMatrix3D;
var JNumber3D=jigLib.JNumber3D;
var MaterialProperties=jigLib.MaterialProperties;
var PhysicsState=jigLib.PhysicsState;
var PhysicsSystem=jigLib.PhysicsSystem;
var JAABox=jigLib.JAABox;
var RigidBody=function(skin){
this._useDegrees = (JConfig.rotationType == "DEGREES") ? true : false;
this._id = RigidBody.idCounter++;
this._skin = skin;
this._material = new MaterialProperties();
this._bodyInertia = new Matrix3D();
this._bodyInvInertia = JMatrix3D.getInverseMatrix(this._bodyInertia);
this._currState = new PhysicsState();
this._oldState = new PhysicsState();
this._storeState = new PhysicsState();
this._invOrientation = JMatrix3D.getInverseMatrix(this._currState.get_orientation());
this._currLinVelocityAux = new Vector3D();
this._currRotVelocityAux = new Vector3D();
this._force = new Vector3D();
this._torque = new Vector3D();
this._linVelDamping = new Vector3D(0.995, 0.995, 0.995);
this._rotVelDamping = new Vector3D(0.5, 0.5, 0.5);
this._maxLinVelocities = 500;
this._maxRotVelocities = 50;
this._velChanged = false;
this._inactiveTime = 0;
this.isActive = this._activity = true;
this._movable = true;
this._origMovable = true;
this.collisions = [];
this._constraints = [];
this._nonCollidables = [];
this._storedPositionForActivation = new Vector3D();
this._bodiesToBeActivatedOnMovement = [];
this._lastPositionForDeactivation = this._currState.position.clone();
this._lastOrientationForDeactivation = this._currState.get_orientation().clone();
this._type = "Object3D";
this._boundingSphere = 0;
this._boundingBox = new JAABox(new Vector3D(), new Vector3D());
this._boundingBox.clear();
}
RigidBody.idCounter = 0;
RigidBody.prototype._id=null;
RigidBody.prototype._skin=null;
RigidBody.prototype._type=null;
RigidBody.prototype._boundingSphere=null;
RigidBody.prototype._boundingBox=null;
RigidBody.prototype._currState=null;
RigidBody.prototype._oldState=null;
RigidBody.prototype._storeState=null;
RigidBody.prototype._invOrientation=null;
RigidBody.prototype._currLinVelocityAux=null;
RigidBody.prototype._currRotVelocityAux=null;
RigidBody.prototype._mass=null;
RigidBody.prototype._invMass=null;
RigidBody.prototype._bodyInertia=null;
RigidBody.prototype._bodyInvInertia=null;
RigidBody.prototype._worldInertia=null;
RigidBody.prototype._worldInvInertia=null;
RigidBody.prototype._force=null;
RigidBody.prototype._torque=null;
RigidBody.prototype._linVelDamping=null;
RigidBody.prototype._rotVelDamping=null;
RigidBody.prototype._maxLinVelocities=null;
RigidBody.prototype._maxRotVelocities=null;
RigidBody.prototype._velChanged=null;
RigidBody.prototype._activity=null;
RigidBody.prototype._movable=null;
RigidBody.prototype._origMovable=null;
RigidBody.prototype._inactiveTime=null;
// The list of bodies that need to be activated when we move away from our stored position
RigidBody.prototype._bodiesToBeActivatedOnMovement=null;
RigidBody.prototype._storedPositionForActivation=null;// The position stored when we need to notify other bodies
RigidBody.prototype._lastPositionForDeactivation=null;// last position for when trying the deactivate
RigidBody.prototype._lastOrientationForDeactivation=null;// last orientation for when trying to deactivate
RigidBody.prototype._material=null;
RigidBody.prototype._rotationX = 0;
RigidBody.prototype._rotationY = 0;
RigidBody.prototype._rotationZ = 0;
RigidBody.prototype._useDegrees=null;
RigidBody.prototype._nonCollidables=null;
RigidBody.prototype._constraints=null;
RigidBody.prototype.collisions=null;
RigidBody.prototype.isActive=null;
RigidBody.prototype.radiansToDegrees=function(rad){
return rad * 180 / Math.PI;
}
RigidBody.prototype.degreesToRadians=function(deg){
return deg * Math.PI / 180;
}
RigidBody.prototype.get_rotationX=function(){
return this._rotationX;//(_useDegrees) ? radiansToDegrees(_rotationX) : _rotationX;
}
RigidBody.prototype.get_rotationY=function(){
return this._rotationY;//(_useDegrees) ? radiansToDegrees(_rotationY) : _rotationY;
}
RigidBody.prototype.get_rotationZ=function(){
return this._rotationZ;//(_useDegrees) ? radiansToDegrees(_rotationZ) : _rotationZ;
}
/**
* px - angle in Radians or Degrees
*/
RigidBody.prototype.set_rotationX=function(px){
//var rad:Number = (_useDegrees) ? degreesToRadians(px) : px;
this._rotationX = px;
this.setOrientation(this.createRotationMatrix());
}
/**
* py - angle in Radians or Degrees
*/
RigidBody.prototype.set_rotationY=function(py){
//var rad:Number = (_useDegrees) ? degreesToRadians(py) : py;
this._rotationY = py;
this.setOrientation(this.createRotationMatrix());
}
/**
* pz - angle in Radians or Degrees
*/
RigidBody.prototype.set_rotationZ=function(pz){
//var rad:Number = (_useDegrees) ? degreesToRadians(pz) : pz;
this._rotationZ = pz;
this.setOrientation(this.createRotationMatrix());
}
RigidBody.prototype.pitch=function(rot){
this.setOrientation(JMatrix3D.getAppendMatrix3D(this.get_currentState().orientation, JMatrix3D.getRotationMatrixAxis(rot, Vector3D.X_AXIS)));
}
RigidBody.prototype.yaw=function(rot){
this.setOrientation(JMatrix3D.getAppendMatrix3D(this.get_currentState().orientation, JMatrix3D.getRotationMatrixAxis(rot, Vector3D.Y_AXIS)));
}
RigidBody.prototype.roll=function(rot){
this.setOrientation(JMatrix3D.getAppendMatrix3D(this.get_currentState().orientation, JMatrix3D.getRotationMatrixAxis(rot, Vector3D.Z_AXIS)));
}
RigidBody.prototype.createRotationMatrix=function(){
var matrix3D = new Matrix3D();
matrix3D.appendRotation(this._rotationX, Vector3D.X_AXIS);
matrix3D.appendRotation(this._rotationY, Vector3D.Y_AXIS);
matrix3D.appendRotation(this._rotationZ, Vector3D.Z_AXIS);
return matrix3D;
}
RigidBody.prototype.setOrientation=function(orient){
//this._currState.get_orientation() = orient.clone();
this._currState.set_orientation(orient.clone());
this.updateInertia();
this.updateState();
}
RigidBody.prototype.get_x=function(){
return this._currState.position.x;
}
RigidBody.prototype.get_y=function(){
return this._currState.position.y;
}
RigidBody.prototype.get_z=function(){
return this._currState.position.z;
}
RigidBody.prototype.set_x=function(px){
this._currState.position.x = px;
this.updateState();
}
RigidBody.prototype.set_y=function(py){
this._currState.position.y = py;
this.updateState();
}
RigidBody.prototype.set_z=function(pz){
this._currState.position.z = pz;
this.updateState();
}
RigidBody.prototype.moveTo=function(pos){
this._currState.position = pos.clone();
this.updateState();
}
RigidBody.prototype.updateState=function(){
this._currState.linVelocity = new Vector3D();
this._currState.rotVelocity = new Vector3D();
this.copyCurrentStateToOld();
this.updateBoundingBox();
}
RigidBody.prototype.setVelocity=function(vel){
this._currState.linVelocity = vel.clone();
}
RigidBody.prototype.setAngVel=function(angVel){
this._currState.rotVelocity = angVel.clone();
}
RigidBody.prototype.setVelocityAux=function(vel){
this._currLinVelocityAux = vel.clone();
}
RigidBody.prototype.setAngVelAux=function(angVel){
this._currRotVelocityAux = angVel.clone();
}
RigidBody.prototype.addGravity=function(){
if (!this._movable){
return;
}
this._force = this._force.add(JNumber3D.getScaleVector(jigLib.PhysicsSystem.getInstance().get_gravity(), this._mass));
this._velChanged = true;
}
RigidBody.prototype.addExternalForces=function(dt){
this.addGravity();
}
RigidBody.prototype.addWorldTorque=function(t){
if (!this._movable){
return;
}
this._torque = this._torque.add(t);
this._velChanged = true;
this.setActive();
}
RigidBody.prototype.addBodyTorque=function(t){
if (!this._movable){
return;
}
JMatrix3D.multiplyVector(this._currState.get_orientation(), t);
this.addWorldTorque(t);
}
// functions to add forces in the world coordinate frame
RigidBody.prototype.addWorldForce=function(f, p){
if (!this._movable){
return;
}
this._force = this._force.add(f);
this.addWorldTorque(p.subtract(this._currState.position).crossProduct(f));
this._velChanged = true;
this.setActive();
}
// functions to add forces in the body coordinate frame
RigidBody.prototype.addBodyForce=function(f, p){
if (!this._movable){
return;
}
JMatrix3D.multiplyVector(this._currState.get_orientation(), f);
JMatrix3D.multiplyVector(this._currState.get_orientation(), p);
this.addWorldForce(f, this._currState.position.add(p));
}
// This just sets all forces etc to zero
RigidBody.prototype.clearForces=function(){
this._force = new Vector3D();
this._torque = new Vector3D();
}
// functions to add impulses in the world coordinate frame
RigidBody.prototype.applyWorldImpulse=function(impulse, pos){
if (!this._movable){
return;
}
this._currState.linVelocity = this._currState.linVelocity.add(JNumber3D.getScaleVector(impulse, this._invMass));
var rotImpulse = pos.subtract(this._currState.position).crossProduct(impulse);
JMatrix3D.multiplyVector(this._worldInvInertia, rotImpulse);
this._currState.rotVelocity = this._currState.rotVelocity.add(rotImpulse);
this._velChanged = true;
}
RigidBody.prototype.applyWorldImpulseAux=function(impulse, pos){
if (!this._movable){
return;
}
this._currLinVelocityAux = this._currLinVelocityAux.add(JNumber3D.getScaleVector(impulse, this._invMass));
var rotImpulse = pos.subtract(this._currState.position).crossProduct(impulse);
JMatrix3D.multiplyVector(this._worldInvInertia, rotImpulse);
this._currRotVelocityAux = this._currRotVelocityAux.add(rotImpulse);
this._velChanged = true;
}
// functions to add impulses in the body coordinate frame
RigidBody.prototype.applyBodyWorldImpulse=function(impulse, delta){
if (!this._movable){
return;
}
this._currState.linVelocity = this._currState.linVelocity.add(JNumber3D.getScaleVector(impulse, this._invMass));
var rotImpulse = delta.crossProduct(impulse);
JMatrix3D.multiplyVector(this._worldInvInertia, rotImpulse);
this._currState.rotVelocity = this._currState.rotVelocity.add(rotImpulse);
this._velChanged = true;
}
RigidBody.prototype.applyBodyWorldImpulseAux=function(impulse, delta){
if (!this._movable){
return;
}
this._currLinVelocityAux = this._currLinVelocityAux.add(JNumber3D.getScaleVector(impulse, this._invMass));
var rotImpulse = delta.crossProduct(impulse);
JMatrix3D.multiplyVector(this._worldInvInertia, rotImpulse);
this._currRotVelocityAux = this._currRotVelocityAux.add(rotImpulse);
this._velChanged = true;
}
RigidBody.prototype.addConstraint=function(constraint){
if (!this.findConstraint(constraint)){
this._constraints.push(constraint);
}
}
RigidBody.prototype.removeConstraint=function(constraint){
if (this.findConstraint(constraint)){
this._constraints.splice(this._constraints.indexOf(constraint), 1);
}
}
RigidBody.prototype.removeAllConstraints=function(){
this._constraints = [];
}
RigidBody.prototype.findConstraint=function(constraint){
for(var i=0; i<this._constraints.length;i++){
if (constraint == this._constraints[i]){
return true;
}
}
return false;
}
// implementation updates the velocity/angular rotation with the force/torque.
RigidBody.prototype.updateVelocity=function(dt){
if (!this._movable || !this._activity){
return;
}
this._currState.linVelocity = this._currState.linVelocity.add(JNumber3D.getScaleVector(this._force, this._invMass * dt));
var rac = JNumber3D.getScaleVector(this._torque, dt);
JMatrix3D.multiplyVector(this._worldInvInertia, rac);
this._currState.rotVelocity = this._currState.rotVelocity.add(rac);
}
// Updates the position with the auxiliary velocities, and zeros them
RigidBody.prototype.updatePositionWithAux=function(dt){
if (!this._movable || !this._activity){
this._currLinVelocityAux = new Vector3D();
this._currRotVelocityAux = new Vector3D();
return;
}
var ga = jigLib.PhysicsSystem.getInstance().get_gravityAxis();
if (ga != -1){
var arr = JNumber3D.toArray(this._currLinVelocityAux);
arr[(ga + 1) % 3] *= 0.1;
arr[(ga + 2) % 3] *= 0.1;
JNumber3D.copyFromArray(this._currLinVelocityAux, arr);
}
var angMomBefore = this._currState.rotVelocity.clone();
JMatrix3D.multiplyVector(this._worldInertia, angMomBefore);
this._currState.position = this._currState.position.add(JNumber3D.getScaleVector(this._currState.linVelocity.add(this._currLinVelocityAux), dt));
var dir = this._currState.rotVelocity.add(this._currRotVelocityAux);
var ang = dir.get_length() * 180 / Math.PI;
if (ang > 0){
dir.normalize();
ang *= dt;
var rot = JMatrix3D.getRotationMatrix(dir.x, dir.y, dir.z, ang);
this._currState.set_orientation(JMatrix3D.getAppendMatrix3D(this._currState.get_orientation(), rot));
this.updateInertia();
}
this._currLinVelocityAux = new Vector3D();
this._currRotVelocityAux = new Vector3D();
JMatrix3D.multiplyVector(this._worldInvInertia, angMomBefore);
this._currState.rotVelocity = angMomBefore.clone();
this.updateBoundingBox();
}
RigidBody.prototype.postPhysics=function(dt){
}
// function provided for the use of Physics system
RigidBody.prototype.tryToFreeze=function(dt){
if (!this._movable || !this._activity){
return;
}
if (this._currState.position.subtract(this._lastPositionForDeactivation).get_length() > JConfig.posThreshold){
this._lastPositionForDeactivation = this._currState.position.clone();
this._inactiveTime = 0;
return;
}
var ot = JConfig.orientThreshold;
var deltaMat = JMatrix3D.getSubMatrix(this._currState.get_orientation(), this._lastOrientationForDeactivation);
var cols = JMatrix3D.getCols(deltaMat);
if (cols[0].get_length() > ot || cols[1].get_length() > ot || cols[2].get_length() > ot){
this._lastOrientationForDeactivation = this._currState.get_orientation().clone();
this._inactiveTime = 0;
return;
}
if (this.getShouldBeActive()){
return;
}
this._inactiveTime += dt;
if (this._inactiveTime > JConfig.deactivationTime){
this._lastPositionForDeactivation = this._currState.position.clone();
this._lastOrientationForDeactivation = this._currState.get_orientation().clone();
this.setInactive();
}
}
RigidBody.prototype.set_mass=function(m){
this._mass = m;
this._invMass = 1 / m;
this.setInertia(this.getInertiaProperties(m));
}
RigidBody.prototype.setInertia=function(matrix3D){
this._bodyInertia = matrix3D.clone();
this._bodyInvInertia = JMatrix3D.getInverseMatrix(this._bodyInertia.clone());
this.updateInertia();
}
RigidBody.prototype.updateInertia=function(){
this._invOrientation = JMatrix3D.getTransposeMatrix(this._currState.get_orientation());
this._worldInertia = JMatrix3D.getAppendMatrix3D(
this._invOrientation,
JMatrix3D.getAppendMatrix3D(this._currState.get_orientation(), this._bodyInertia)
);
this._worldInvInertia = JMatrix3D.getAppendMatrix3D(
this._invOrientation,
JMatrix3D.getAppendMatrix3D(this._currState.get_orientation(), this._bodyInvInertia)
);
}
// prevent velocity updates etc
RigidBody.prototype.get_movable=function(){
return this._movable;
}
RigidBody.prototype.set_movable=function(mov){
if (this._type == "PLANE" || this._type == "TERRAIN") {
return;
}
this._movable = mov;
this.isActive = this._activity = mov;
this._origMovable = mov;
}
RigidBody.prototype.internalSetImmovable=function(){
this._origMovable = this._movable;
this._movable = false;
}
RigidBody.prototype.internalRestoreImmovable=function(){
this._movable = this._origMovable;
}
RigidBody.prototype.getVelChanged=function(){
return this._velChanged;
}
RigidBody.prototype.clearVelChanged=function(){
this._velChanged = false;
}
RigidBody.prototype.setActive=function(activityFactor){
if(!activityFactor) activityFactor=1;
if (this._movable){
this.isActive = this._activity = true;
this._inactiveTime = (1 - activityFactor) * JConfig.deactivationTime;
}
}
RigidBody.prototype.setInactive=function(){
if (this._movable){
this.isActive = this._activity = false;
}
}
// Returns the velocity of a point at body-relative position
RigidBody.prototype.getVelocity=function(relPos){
return this._currState.linVelocity.add(this._currState.rotVelocity.crossProduct(relPos));
}
// As GetVelocity but just uses the aux velocities
RigidBody.prototype.getVelocityAux=function(relPos){
return this._currLinVelocityAux.add(this._currRotVelocityAux.crossProduct(relPos));
}
// indicates if the velocity is above the threshold for freezing
RigidBody.prototype.getShouldBeActive=function(){
return ((this._currState.linVelocity.get_length() > JConfig.velThreshold) || (this._currState.rotVelocity.get_length() > JConfig.angVelThreshold));
}
RigidBody.prototype.getShouldBeActiveAux=function(){
return ((this._currLinVelocityAux.get_length() > JConfig.velThreshold) || (this._currRotVelocityAux.get_length() > JConfig.angVelThreshold));
}
// damp movement as the body approaches deactivation
RigidBody.prototype.dampForDeactivation=function(){
this._currState.linVelocity.x *= this._linVelDamping.x;
this._currState.linVelocity.y *= this._linVelDamping.y;
this._currState.linVelocity.z *= this._linVelDamping.z;
this._currState.rotVelocity.x *= this._rotVelDamping.x;
this._currState.rotVelocity.y *= this._rotVelDamping.y;
this._currState.rotVelocity.z *= this._rotVelDamping.z;
this._currLinVelocityAux.x *= this._linVelDamping.x;
this._currLinVelocityAux.y *= this._linVelDamping.y;
this._currLinVelocityAux.z *= this._linVelDamping.z;
this._currRotVelocityAux.x *= this._rotVelDamping.x;
this._currRotVelocityAux.y *= this._rotVelDamping.y;
this._currRotVelocityAux.z *= this._rotVelDamping.z;
var r = 0.5;
var frac = this._inactiveTime / JConfig.deactivationTime;
if (frac < r){
return;
}
var scale = 1 - ((frac - r) / (1 - r));
if (scale < 0){
scale = 0;
}else if (scale > 1){
scale = 1;
}
this._currState.linVelocity = JNumber3D.getScaleVector(this._currState.linVelocity, scale);
this._currState.rotVelocity = JNumber3D.getScaleVector(this._currState.rotVelocity, scale);
}
// function provided for use of physics system. Activates any
// body in its list if it's moved more than a certain distance,
// in which case it also clears its list.
RigidBody.prototype.doMovementActivations=function(){
if (this._bodiesToBeActivatedOnMovement.length == 0 || this._currState.position.subtract(this._storedPositionForActivation).get_length() < JConfig.posThreshold){
return;
}
for (var i = 0; i < this._bodiesToBeActivatedOnMovement.length; i++){
jigLib.PhysicsSystem.getInstance().activateObject(this._bodiesToBeActivatedOnMovement[i]);
}
this._bodiesToBeActivatedOnMovement = [];
}
// adds the other body to the list of bodies to be activated if
// this body moves more than a certain distance from either a
// previously stored position, or the position passed in.
RigidBody.prototype.addMovementActivation=function(pos, otherBody){
var len = this._bodiesToBeActivatedOnMovement.length;
for (var i = 0; i < len; i++){
if (this._bodiesToBeActivatedOnMovement[i] == otherBody){
return;
}
}
if (this._bodiesToBeActivatedOnMovement.length == 0){
this._storedPositionForActivation = pos;
}
this._bodiesToBeActivatedOnMovement.push(otherBody);
}
// Marks all constraints/collisions as being unsatisfied
RigidBody.prototype.setConstraintsAndCollisionsUnsatisfied=function(){
for(var i=0;i<this._constraints.length;i++){
this._constraints[i].set_satisfied(false);
}
for(var i=0;i<this.collisions.length;i++){
this.collisions[i].satisfied = false;
}
}
RigidBody.prototype.segmentIntersect=function(out, seg, state){
return false;
}
RigidBody.prototype.getInertiaProperties=function(m){
return new Matrix3D();
}
RigidBody.prototype.updateBoundingBox=function(){
}
RigidBody.prototype.hitTestObject3D=function(obj3D){
var num1 = this._currState.position.subtract(obj3D.get_currentState().position).get_length();
var num2 = this._boundingSphere + obj3D.get_boundingSphere();
if (num1 <= num2){
return true;
}
return false;
}
RigidBody.prototype.findNonCollidablesBody=function(body){
for(var i=0;i<this._nonCollidables.length;i++){
if (body == this._nonCollidables[i]){
return true;
}
}
return false;
}
RigidBody.prototype.disableCollisions=function(body){
if (!this.findNonCollidablesBody(body)){
this._nonCollidables.push(body);
}
}
RigidBody.prototype.enableCollisions=function(body){
if (this.findNonCollidablesBody(body)){
this._nonCollidables.splice(this._nonCollidables.indexOf(body), 1);
}
}
// copies the current position etc to old - normally called only by physicsSystem.
RigidBody.prototype.copyCurrentStateToOld=function(){
this._oldState.position = this._currState.position.clone();
this._oldState.set_orientation(this._currState.get_orientation().clone());
this._oldState.linVelocity = this._currState.linVelocity.clone();
this._oldState.rotVelocity = this._currState.rotVelocity.clone();
}
// Copy our current state into the stored state
RigidBody.prototype.storeState=function(){
this._storeState.position = this._currState.position.clone();
this._storeState.set_orientation(this._currState.get_orientation().clone());
this._storeState.linVelocity = this._currState.linVelocity.clone();
this._storeState.rotVelocity = this._currState.rotVelocity.clone();
}
// restore from the stored state into our current state.
RigidBody.prototype.restoreState=function(){
this._currState.position = this._storeState.position.clone();
this._currState.set_orientation(this._storeState.get_orientation().clone());
this._currState.linVelocity = this._storeState.linVelocity.clone();
this._currState.rotVelocity = this._storeState.rotVelocity.clone();
}
// the "working" state
RigidBody.prototype.get_currentState=function(){
return this._currState;
}
// the previous state - copied explicitly using copyCurrentStateToOld
RigidBody.prototype.get_oldState=function(){
return this._oldState;
}
RigidBody.prototype.get_id=function(){
return this._id;
}
RigidBody.prototype.get_type=function(){
return this._type;
}
RigidBody.prototype.get_skin=function(){
return this._skin;
}
RigidBody.prototype.get_boundingSphere=function(){
return this._boundingSphere;
}
RigidBody.prototype.get_boundingBox=function(){
return this._boundingBox;
}
// force in world frame
RigidBody.prototype.get_force=function(){
return this._force;
}
// torque in world frame
RigidBody.prototype.get_mass=function(){
return this._mass;
}
RigidBody.prototype.get_invMass=function(){
return this._invMass;
}
// inertia tensor in world space
RigidBody.prototype.get_worldInertia=function(){
return this._worldInertia;
}
// inverse inertia in world frame
RigidBody.prototype.get_worldInvInertia=function(){
return this._worldInvInertia;
}
RigidBody.prototype.get_nonCollidables=function(){
return this._nonCollidables;
}
//every dimension should be set to 0-1;
RigidBody.prototype.set_linVelocityDamping=function(vel){
this._linVelDamping.x = JNumber3D.getLimiteNumber(vel.x, 0, 1);
this._linVelDamping.y = JNumber3D.getLimiteNumber(vel.y, 0, 1);
this._linVelDamping.z = JNumber3D.getLimiteNumber(vel.z, 0, 1);
}
RigidBody.prototype.get_linVelocityDamping=function(){
return this._linVelDamping;
}
//every dimension should be set to 0-1;
RigidBody.prototype.set_rotVelocityDamping=function(vel){
this._rotVelDamping.x = JNumber3D.getLimiteNumber(vel.x, 0, 1);
this._rotVelDamping.y = JNumber3D.getLimiteNumber(vel.y, 0, 1);
this._rotVelDamping.z = JNumber3D.getLimiteNumber(vel.z, 0, 1);
}
RigidBody.prototype.get_rotVelocityDamping=function(){
return this._rotVelDamping;
}
//limit the max value of body's line velocity
RigidBody.prototype.set_maxLinVelocities=function(vel){
this._maxLinVelocities = JNumber3D.getLimiteNumber(Math.abs(vel), 0, 500);
}
RigidBody.prototype.get_maxLinVelocities=function(){
return this._maxLinVelocities;
}
//limit the max value of body's angle velocity
RigidBody.prototype.set_maxRotVelocities=function(vel){
this._maxRotVelocities = JNumber3D.getLimiteNumber(Math.abs(vel), JNumber3D.NUM_TINY, 50);
}
RigidBody.prototype.get_maxRotVelocities=function(){
return this._maxRotVelocities;
}
RigidBody.prototype.limitVel=function(){
this._currState.linVelocity.x = JNumber3D.getLimiteNumber(this._currState.linVelocity.x, -this._maxLinVelocities, this._maxLinVelocities);
this._currState.linVelocity.y = JNumber3D.getLimiteNumber(this._currState.linVelocity.y, -this._maxLinVelocities, this._maxLinVelocities);
this._currState.linVelocity.z = JNumber3D.getLimiteNumber(this._currState.linVelocity.z, -this._maxLinVelocities, this._maxLinVelocities);
}
RigidBody.prototype.limitAngVel=function(){
var fx = Math.abs(this._currState.rotVelocity.x) / this._maxRotVelocities;
var fy = Math.abs(this._currState.rotVelocity.y) / this._maxRotVelocities;
var fz = Math.abs(this._currState.rotVelocity.z) / this._maxRotVelocities;
var f = Math.max(fx, fy, fz);
if (f > 1){
this._currState.rotVelocity = JNumber3D.getDivideVector(this._currState.rotVelocity, f);
}
}
RigidBody.prototype.getTransform=function(){
if (this._skin != null){
return this._skin.get_transform();
}else{
return null;
}
}
//update skin
RigidBody.prototype.updateObject3D=function(){
if (this._skin != null){
this._skin.set_transform(JMatrix3D.getAppendMatrix3D(this._currState.get_orientation(), JMatrix3D.getTranslationMatrix(this._currState.position.x, this._currState.position.y, this._currState.position.z)));
}
}
RigidBody.prototype.get_material=function(){
return this._material;
}
//coefficient of elasticity
RigidBody.prototype.get_restitution=function(){
return this._material.get_restitution();
}
RigidBody.prototype.set_restitution=function(restitution){
this._material.set_restitution(JNumber3D.getLimiteNumber(restitution, 0, 1));
}
//coefficient of friction
RigidBody.prototype.get_friction=function(){
return this._material.get_friction();
}
RigidBody.prototype.set_friction=function(friction){
this._material.set_friction(JNumber3D.getLimiteNumber(friction, 0, 1));
}
jigLib.RigidBody=RigidBody;
})(jigLib)
| Pervasive/Lively3D | Dropbox/Lively3D/Resources/MiniGolf/scripts/rigid_body.js | JavaScript | mit | 29,886 |
<?php
namespace Admingenerator\GeneratorBundle\QueryFilter;
interface QueryFilterInterface
{
/**
* @param object $query the query object interface depend of the ORM
*
* @api
*/
function setQuery($query);
/**
* @return the query object interface depend of the ORM
*
* @api
*/
function getQuery();
/**
* Add filter for Default db types (types, not found
* by others add*Filter() methods
*
* @param string $field the db field
* @param string $value the search value
*
* @api
*/
function addDefaultFilter($field, $value);
}
| marius1092/test | vendor/bundles/Admingenerator/GeneratorBundle/QueryFilter/QueryFilterInterface.php | PHP | mit | 629 |
package model;
/**
* Тип дорожки.
*/
public enum LineType {
/**
* Верхняя. Проходит через левый нижний, левый верхний и правый верхний углы карты.
*/
TOP,
/**
* Центральная. Напрямую соединяет левый нижний и правый верхний углы карты.
*/
MIDDLE,
/**
* Нижняя. Проходит через левый нижний, правый нижний и правый верхний углы карты.
*/
BOTTOM
}
| spookiecookie/russianaicup | codewizards2016/java-cgdk/src/main/java/model/LineType.java | Java | mit | 606 |
app.factory('Pizza', ['$resource', 'LoginService', function ($resource, LoginService) {
const headers = {
token: getToken
};
return $resource('./api/pizzas/:id', { id: '@_id' },
{
query: {
method: 'GET',
isArray: true,
headers
},
save: {
method: 'POST',
headers
},
update: {
method: 'PUT',
headers
},
remove: {
method: 'DELETE',
headers,
params: {
id: '@id'
}
}
}
);
function getToken() {
return LoginService.getToken();
}
}]); | auromota/easy-pizza-api | src/public/js/factories/pizzaFactory.js | JavaScript | mit | 778 |
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Stephen Connolly, Tom Huybrechts, InfraDNA, Inc.
*
* 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.
*/
package hudson.model;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.BulkChange;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.XmlFile;
import hudson.init.Initializer;
import static hudson.init.InitMilestone.JOB_LOADED;
import static hudson.util.Iterators.reverse;
import hudson.cli.declarative.CLIResolver;
import hudson.model.labels.LabelAssignmentAction;
import hudson.model.queue.AbstractQueueTask;
import hudson.model.queue.Executables;
import hudson.model.queue.QueueListener;
import hudson.model.queue.QueueTaskFuture;
import hudson.model.queue.ScheduleResult;
import hudson.model.queue.ScheduleResult.Created;
import hudson.model.queue.SubTask;
import hudson.model.queue.FutureImpl;
import hudson.model.queue.MappingWorksheet;
import hudson.model.queue.MappingWorksheet.Mapping;
import hudson.model.queue.QueueSorter;
import hudson.model.queue.QueueTaskDispatcher;
import hudson.model.queue.Tasks;
import hudson.model.queue.WorkUnit;
import hudson.model.Node.Mode;
import hudson.model.listeners.SaveableListener;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.FoldableAction;
import hudson.model.queue.CauseOfBlockage.BecauseLabelIsBusy;
import hudson.model.queue.CauseOfBlockage.BecauseNodeIsOffline;
import hudson.model.queue.CauseOfBlockage.BecauseLabelIsOffline;
import hudson.model.queue.CauseOfBlockage.BecauseNodeIsBusy;
import hudson.model.queue.WorkUnitContext;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import jenkins.security.QueueItemAuthenticatorProvider;
import jenkins.util.Timer;
import hudson.triggers.SafeTimerTask;
import java.util.concurrent.TimeUnit;
import hudson.util.XStream2;
import hudson.util.ConsistentHash;
import hudson.util.ConsistentHash.Hash;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import jenkins.security.QueueItemAuthenticator;
import jenkins.util.AtmostOneTaskExecutor;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
import org.jenkinsci.bytecode.AdaptField;
import org.jenkinsci.remoting.RoleChecker;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnegative;
import jenkins.model.queue.AsynchronousExecution;
import jenkins.model.queue.CompositeCauseOfBlockage;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Build queue.
*
* <p>
* This class implements the core scheduling logic. {@link Task} represents the executable
* task that are placed in the queue. While in the queue, it's wrapped into {@link Item}
* so that we can keep track of additional data used for deciding what to execute when.
*
* <p>
* Items in queue goes through several stages, as depicted below:
* <pre>{@code
* (enter) --> waitingList --+--> blockedProjects
* | ^
* | |
* | v
* +--> buildables ---> pending ---> left
* ^ |
* | |
* +---(rarely)---+
* }</pre>
*
* <p>
* Note: In the normal case of events pending items only move to left. However they can move back
* if the node they are assigned to execute on disappears before their {@link Executor} thread
* starts, where the node is removed before the {@link Executable} has been instantiated it
* is safe to move the pending item back to buildable. Once the {@link Executable} has been
* instantiated the only option is to let the {@link Executable} bomb out as soon as it starts
* to try an execute on the node that no longer exists.
*
* <p>
* In addition, at any stage, an item can be removed from the queue (for example, when the user
* cancels a job in the queue.) See the corresponding field for their exact meanings.
*
* @author Kohsuke Kawaguchi
* @see QueueListener
* @see QueueTaskDispatcher
*/
@ExportedBean
public class Queue extends ResourceController implements Saveable {
/**
* Items that are waiting for its quiet period to pass.
*
* <p>
* This consists of {@link Item}s that cannot be run yet
* because its time has not yet come.
*/
private final Set<WaitingItem> waitingList = new TreeSet<WaitingItem>();
/**
* {@link Task}s that can be built immediately
* but blocked because another build is in progress,
* required {@link Resource}s are not available,
* blocked via {@link QueueTaskDispatcher#canRun(Item)},
* or otherwise blocked by {@link Task#isBuildBlocked()}.
*/
private final ItemList<BlockedItem> blockedProjects = new ItemList<BlockedItem>();
/**
* {@link Task}s that can be built immediately
* that are waiting for available {@link Executor}.
* This list is sorted in such a way that earlier items are built earlier.
*/
private final ItemList<BuildableItem> buildables = new ItemList<BuildableItem>();
/**
* {@link Task}s that are being handed over to the executor, but execution
* has not started yet.
*/
private final ItemList<BuildableItem> pendings = new ItemList<BuildableItem>();
private transient volatile Snapshot snapshot = new Snapshot(waitingList, blockedProjects, buildables, pendings);
/**
* Items that left queue would stay here for a while to enable tracking via {@link Item#getId()}.
*
* This map is forgetful, since we can't remember everything that executed in the past.
*/
private final Cache<Long,LeftItem> leftItems = CacheBuilder.newBuilder().expireAfterWrite(5*60, TimeUnit.SECONDS).build();
/**
* Data structure created for each idle {@link Executor}.
* This is a job offer from the queue to an executor.
*
* <p>
* For each idle executor, this gets created to allow the scheduling logic
* to assign a work. Once a work is assigned, the executor actually gets
* started to carry out the task in question.
*/
public static class JobOffer extends MappingWorksheet.ExecutorSlot {
public final Executor executor;
/**
* The work unit that this {@link Executor} is going to handle.
*/
private WorkUnit workUnit;
private JobOffer(Executor executor) {
this.executor = executor;
}
@Override
protected void set(WorkUnit p) {
assert this.workUnit == null;
this.workUnit = p;
assert executor.isParking();
executor.start(workUnit);
// LOGGER.info("Starting "+executor.getName());
}
@Override
public Executor getExecutor() {
return executor;
}
/**
* @deprecated discards information; prefer {@link #getCauseOfBlockage}
*/
@Deprecated
public boolean canTake(BuildableItem item) {
return getCauseOfBlockage(item) == null;
}
/**
* Checks whether the {@link Executor} represented by this object is capable of executing the given task.
* @return a reason why it cannot, or null if it could
* @since 2.37
*/
public @CheckForNull CauseOfBlockage getCauseOfBlockage(BuildableItem item) {
Node node = getNode();
if (node == null) {
return CauseOfBlockage.fromMessage(Messages._Queue_node_has_been_removed_from_configuration(executor.getOwner().getDisplayName()));
}
CauseOfBlockage reason = node.canTake(item);
if (reason != null) {
return reason;
}
for (QueueTaskDispatcher d : QueueTaskDispatcher.all()) {
reason = d.canTake(node, item);
if (reason != null) {
return reason;
}
}
// inlining isAvailable:
if (workUnit != null) { // unlikely in practice (should not have even found this executor if so)
return CauseOfBlockage.fromMessage(Messages._Queue_executor_slot_already_in_use());
}
if (executor.getOwner().isOffline()) {
return new CauseOfBlockage.BecauseNodeIsOffline(node);
}
if (!executor.getOwner().isAcceptingTasks()) { // Node.canTake (above) does not consider RetentionStrategy.isAcceptingTasks
return new CauseOfBlockage.BecauseNodeIsNotAcceptingTasks(node);
}
return null;
}
/**
* Is this executor ready to accept some tasks?
*/
public boolean isAvailable() {
return workUnit == null && !executor.getOwner().isOffline() && executor.getOwner().isAcceptingTasks();
}
@CheckForNull
public Node getNode() {
return executor.getOwner().getNode();
}
public boolean isNotExclusive() {
return getNode().getMode() == Mode.NORMAL;
}
@Override
public String toString() {
return String.format("JobOffer[%s #%d]",executor.getOwner().getName(), executor.getNumber());
}
}
private volatile transient LoadBalancer loadBalancer;
private volatile transient QueueSorter sorter;
private transient final AtmostOneTaskExecutor<Void> maintainerThread = new AtmostOneTaskExecutor<Void>(new Callable<Void>() {
@Override
public Void call() throws Exception {
maintain();
return null;
}
@Override
public String toString() {
return "Periodic Jenkins queue maintenance";
}
});
private transient final ReentrantLock lock = new ReentrantLock();
private transient final Condition condition = lock.newCondition();
public Queue(@Nonnull LoadBalancer loadBalancer) {
this.loadBalancer = loadBalancer.sanitize();
// if all the executors are busy doing something, then the queue won't be maintained in
// timely fashion, so use another thread to make sure it happens.
new MaintainTask(this).periodic();
}
public LoadBalancer getLoadBalancer() {
return loadBalancer;
}
public void setLoadBalancer(@Nonnull LoadBalancer loadBalancer) {
if(loadBalancer==null) throw new IllegalArgumentException();
this.loadBalancer = loadBalancer.sanitize();
}
public QueueSorter getSorter() {
return sorter;
}
public void setSorter(QueueSorter sorter) {
this.sorter = sorter;
}
/**
* Simple queue state persistence object.
*/
static class State {
public long counter;
public List<Item> items = new ArrayList<Item>();
}
/**
* Loads the queue contents that was {@link #save() saved}.
*/
public void load() {
lock.lock();
try { try {
// Clear items, for the benefit of reloading.
waitingList.clear();
blockedProjects.clear();
buildables.clear();
pendings.clear();
// first try the old format
File queueFile = getQueueFile();
if (queueFile.exists()) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(Files.newInputStream(queueFile.toPath())))) {
String line;
while ((line = in.readLine()) != null) {
AbstractProject j = Jenkins.getInstance().getItemByFullName(line, AbstractProject.class);
if (j != null)
j.scheduleBuild();
}
} catch (InvalidPathException e) {
throw new IOException(e);
}
// discard the queue file now that we are done
queueFile.delete();
} else {
queueFile = getXMLQueueFile();
if (queueFile.exists()) {
Object unmarshaledObj = new XmlFile(XSTREAM, queueFile).read();
List items;
if (unmarshaledObj instanceof State) {
State state = (State) unmarshaledObj;
items = state.items;
WaitingItem.COUNTER.set(state.counter);
} else {
// backward compatibility - it's an old List queue.xml
items = (List) unmarshaledObj;
long maxId = 0;
for (Object o : items) {
if (o instanceof Item) {
maxId = Math.max(maxId, ((Item)o).id);
}
}
WaitingItem.COUNTER.set(maxId);
}
for (Object o : items) {
if (o instanceof Task) {
// backward compatibility
schedule((Task)o, 0);
} else if (o instanceof Item) {
Item item = (Item)o;
if (item.task == null) {
continue; // botched persistence. throw this one away
}
if (item instanceof WaitingItem) {
item.enter(this);
} else if (item instanceof BlockedItem) {
item.enter(this);
} else if (item instanceof BuildableItem) {
item.enter(this);
} else {
throw new IllegalStateException("Unknown item type! " + item);
}
}
}
// I just had an incident where all the executors are dead at AbstractProject._getRuns()
// because runs is null. Debugger revealed that this is caused by a MatrixConfiguration
// object that doesn't appear to be de-serialized properly.
// I don't know how this problem happened, but to diagnose this problem better
// when it happens again, save the old queue file for introspection.
File bk = new File(queueFile.getPath() + ".bak");
bk.delete();
queueFile.renameTo(bk);
queueFile.delete();
}
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load the queue file " + getXMLQueueFile(), e);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Persists the queue contents to the disk.
*/
public void save() {
if(BulkChange.contains(this)) return;
XmlFile queueFile = new XmlFile(XSTREAM, getXMLQueueFile());
lock.lock();
try {
// write out the queue state we want to save
State state = new State();
state.counter = WaitingItem.COUNTER.longValue();
// write out the tasks on the queue
for (Item item: getItems()) {
if(item.task instanceof TransientTask) continue;
state.items.add(item);
}
try {
queueFile.write(state);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to write out the queue file " + getXMLQueueFile(), e);
}
} finally {
lock.unlock();
}
SaveableListener.fireOnChange(this, queueFile);
}
/**
* Wipes out all the items currently in the queue, as if all of them are cancelled at once.
*/
public void clear() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
lock.lock();
try { try {
for (WaitingItem i : new ArrayList<WaitingItem>(
waitingList)) // copy the list as we'll modify it in the loop
i.cancel(this);
blockedProjects.cancelAll();
pendings.cancelAll();
buildables.cancelAll();
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
scheduleMaintenance();
}
private File getQueueFile() {
return new File(Jenkins.getInstance().getRootDir(), "queue.txt");
}
/*package*/ File getXMLQueueFile() {
return new File(Jenkins.getInstance().getRootDir(), "queue.xml");
}
/**
* @deprecated as of 1.311
* Use {@link #schedule(AbstractProject)}
*/
@Deprecated
public boolean add(AbstractProject p) {
return schedule(p)!=null;
}
/**
* Schedule a new build for this project.
* @see #schedule(Task, int)
*/
public @CheckForNull WaitingItem schedule(AbstractProject p) {
return schedule(p, p.getQuietPeriod());
}
/**
* Schedules a new build with a custom quiet period.
*
* <p>
* Left for backward compatibility with <1.114.
*
* @since 1.105
* @deprecated as of 1.311
* Use {@link #schedule(Task, int)}
*/
@Deprecated
public boolean add(AbstractProject p, int quietPeriod) {
return schedule(p, quietPeriod)!=null;
}
/**
* @deprecated as of 1.521
* Use {@link #schedule2(Task, int, List)}
*/
@Deprecated
public WaitingItem schedule(Task p, int quietPeriod, List<Action> actions) {
return schedule2(p, quietPeriod, actions).getCreateItem();
}
/**
* Schedules an execution of a task.
*
* @param actions
* These actions can be used for associating information scoped to a particular build, to
* the task being queued. Upon the start of the build, these {@link Action}s will be automatically
* added to the {@link Run} object, and hence available to everyone.
* For the convenience of the caller, this list can contain null, and those will be silently ignored.
* @since 1.311
* @return
* {@link hudson.model.queue.ScheduleResult.Refused} if Jenkins refused to add this task into the queue (for example because the system
* is about to shutdown.) Otherwise the task is either merged into existing items in the queue
* (in which case you get {@link hudson.model.queue.ScheduleResult.Existing} instance back), or a new item
* gets created in the queue (in which case you get {@link Created}.
*
* Note the nature of the queue
* is that such {@link Item} only captures the state of the item at a particular moment,
* and by the time you inspect the object, some of its information can be already stale.
*
* That said, one can still look at {@link Queue.Item#future}, {@link Queue.Item#getId()}, etc.
*/
public @Nonnull ScheduleResult schedule2(Task p, int quietPeriod, List<Action> actions) {
// remove nulls
actions = new ArrayList<Action>(actions);
for (Iterator<Action> itr = actions.iterator(); itr.hasNext();) {
Action a = itr.next();
if (a==null) itr.remove();
}
lock.lock();
try { try {
for (QueueDecisionHandler h : QueueDecisionHandler.all())
if (!h.shouldSchedule(p, actions))
return ScheduleResult.refused(); // veto
return scheduleInternal(p, quietPeriod, actions);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Schedules an execution of a task.
*
* @since 1.311
* @return
* {@link hudson.model.queue.ScheduleResult.Existing} if this task is already in the queue and
* therefore the add operation was no-op. Otherwise {@link hudson.model.queue.ScheduleResult.Created}
* indicates the {@link WaitingItem} object added, although the nature of the queue
* is that such {@link Item} only captures the state of the item at a particular moment,
* and by the time you inspect the object, some of its information can be already stale.
*
* That said, one can still look at {@link WaitingItem#future}, {@link WaitingItem#getId()}, etc.
*/
private @Nonnull ScheduleResult scheduleInternal(Task p, int quietPeriod, List<Action> actions) {
lock.lock();
try { try {
Calendar due = new GregorianCalendar();
due.add(Calendar.SECOND, quietPeriod);
// Do we already have this task in the queue? Because if so, we won't schedule a new one.
List<Item> duplicatesInQueue = new ArrayList<Item>();
for (Item item : liveGetItems(p)) {
boolean shouldScheduleItem = false;
for (QueueAction action : item.getActions(QueueAction.class)) {
shouldScheduleItem |= action.shouldSchedule(actions);
}
for (QueueAction action : Util.filter(actions, QueueAction.class)) {
shouldScheduleItem |= action.shouldSchedule((new ArrayList<Action>(item.getAllActions())));
}
if (!shouldScheduleItem) {
duplicatesInQueue.add(item);
}
}
if (duplicatesInQueue.isEmpty()) {
LOGGER.log(Level.FINE, "{0} added to queue", p);
// put the item in the queue
WaitingItem added = new WaitingItem(due, p, actions);
added.enter(this);
scheduleMaintenance(); // let an executor know that a new item is in the queue.
return ScheduleResult.created(added);
}
LOGGER.log(Level.FINE, "{0} is already in the queue", p);
// but let the actions affect the existing stuff.
for (Item item : duplicatesInQueue) {
for (FoldableAction a : Util.filter(actions, FoldableAction.class)) {
a.foldIntoExisting(item, p, actions);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "after folding {0}, {1} includes {2}", new Object[] {a, item, item.getAllActions()});
}
}
}
boolean queueUpdated = false;
for (WaitingItem wi : Util.filter(duplicatesInQueue, WaitingItem.class)) {
// make sure to always use the shorter of the available due times
if (wi.timestamp.before(due))
continue;
// waitingList is sorted, so when we change a timestamp we need to maintain order
wi.leave(this);
wi.timestamp = due;
wi.enter(this);
queueUpdated = true;
}
if (queueUpdated) scheduleMaintenance();
// REVISIT: when there are multiple existing items in the queue that matches the incoming one,
// whether the new one should affect all existing ones or not is debatable. I for myself
// thought this would only affect one, so the code was bit of surprise, but I'm keeping the current
// behaviour.
return ScheduleResult.existing(duplicatesInQueue.get(0));
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* @deprecated as of 1.311
* Use {@link #schedule(Task, int)}
*/
@Deprecated
public boolean add(Task p, int quietPeriod) {
return schedule(p, quietPeriod)!=null;
}
public @CheckForNull WaitingItem schedule(Task p, int quietPeriod) {
return schedule(p, quietPeriod, new Action[0]);
}
/**
* @deprecated as of 1.311
* Use {@link #schedule(Task, int, Action...)}
*/
@Deprecated
public boolean add(Task p, int quietPeriod, Action... actions) {
return schedule(p, quietPeriod, actions)!=null;
}
/**
* Convenience wrapper method around {@link #schedule(Task, int, List)}
*/
public @CheckForNull WaitingItem schedule(Task p, int quietPeriod, Action... actions) {
return schedule2(p, quietPeriod, actions).getCreateItem();
}
/**
* Convenience wrapper method around {@link #schedule2(Task, int, List)}
*/
public @Nonnull ScheduleResult schedule2(Task p, int quietPeriod, Action... actions) {
return schedule2(p, quietPeriod, Arrays.asList(actions));
}
/**
* Cancels the item in the queue. If the item is scheduled more than once, cancels the first occurrence.
*
* @return true if the project was indeed in the queue and was removed.
* false if this was no-op.
*/
public boolean cancel(Task p) {
lock.lock();
try { try {
LOGGER.log(Level.FINE, "Cancelling {0}", p);
for (WaitingItem item : waitingList) {
if (item.task.equals(p)) {
return item.cancel(this);
}
}
// use bitwise-OR to make sure that both branches get evaluated all the time
return blockedProjects.cancel(p) != null | buildables.cancel(p) != null;
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
private void updateSnapshot() {
Snapshot revised = new Snapshot(waitingList, blockedProjects, buildables, pendings);
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "{0} → {1}; leftItems={2}", new Object[] {snapshot, revised, leftItems.asMap()});
}
snapshot = revised;
}
public boolean cancel(Item item) {
LOGGER.log(Level.FINE, "Cancelling {0} item#{1}", new Object[] {item.task, item.id});
lock.lock();
try { try {
return item.cancel(this);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Called from {@code queue.jelly} and {@code entries.jelly}.
*/
@RequirePOST
public HttpResponse doCancelItem(@QueryParameter long id) throws IOException, ServletException {
Item item = getItem(id);
if (item != null) {
cancel(item);
} // else too late, ignore (JENKINS-14813)
return HttpResponses.forwardToPreviousPage();
}
public boolean isEmpty() {
Snapshot snapshot = this.snapshot;
return snapshot.waitingList.isEmpty() && snapshot.blockedProjects.isEmpty() && snapshot.buildables.isEmpty()
&& snapshot.pendings.isEmpty();
}
private WaitingItem peek() {
return waitingList.iterator().next();
}
/**
* Gets a snapshot of items in the queue.
*
* Generally speaking the array is sorted such that the items that are most likely built sooner are
* at the end.
*/
@Exported(inline=true)
public Item[] getItems() {
Snapshot s = this.snapshot;
List<Item> r = new ArrayList<Item>();
for(WaitingItem p : s.waitingList) {
r = checkPermissionsAndAddToList(r, p);
}
for (BlockedItem p : s.blockedProjects){
r = checkPermissionsAndAddToList(r, p);
}
for (BuildableItem p : reverse(s.buildables)) {
r = checkPermissionsAndAddToList(r, p);
}
for (BuildableItem p : reverse(s.pendings)) {
r= checkPermissionsAndAddToList(r, p);
}
Item[] items = new Item[r.size()];
r.toArray(items);
return items;
}
private List<Item> checkPermissionsAndAddToList(List<Item> r, Item t) {
if (t.task instanceof hudson.security.AccessControlled) {
if (((hudson.security.AccessControlled)t.task).hasPermission(hudson.model.Item.READ)
|| ((hudson.security.AccessControlled) t.task).hasPermission(hudson.security.Permission.READ)) {
r.add(t);
}
}
return r;
}
/**
* Returns an array of Item for which it is only visible the name of the task.
*
* Generally speaking the array is sorted such that the items that are most likely built sooner are
* at the end.
*/
@Restricted(NoExternalUse.class)
@Exported(inline=true)
public StubItem[] getDiscoverableItems() {
Snapshot s = this.snapshot;
List<StubItem> r = new ArrayList<StubItem>();
for(WaitingItem p : s.waitingList) {
r = filterDiscoverableItemListBasedOnPermissions(r, p);
}
for (BlockedItem p : s.blockedProjects){
r = filterDiscoverableItemListBasedOnPermissions(r, p);
}
for (BuildableItem p : reverse(s.buildables)) {
r = filterDiscoverableItemListBasedOnPermissions(r, p);
}
for (BuildableItem p : reverse(s.pendings)) {
r= filterDiscoverableItemListBasedOnPermissions(r, p);
}
StubItem[] items = new StubItem[r.size()];
r.toArray(items);
return items;
}
private List<StubItem> filterDiscoverableItemListBasedOnPermissions(List<StubItem> r, Item t) {
if (t.task instanceof hudson.model.Item) {
if (!((hudson.model.Item)t.task).hasPermission(hudson.model.Item.READ) && ((hudson.model.Item)t.task).hasPermission(hudson.model.Item.DISCOVER)) {
r.add(new StubItem(new StubTask(t.task)));
}
}
return r;
}
/**
* Like {@link #getItems()}, but returns an approximation that might not be completely up-to-date.
*
* <p>
* At the expense of accuracy, this method does not usually lock {@link Queue} and therefore is faster
* in a highly concurrent situation.
*
* <p>
* The list obtained is an accurate snapshot of the queue at some point in the past. The snapshot
* is updated and normally no more than one second old, but this is a soft commitment that might
* get violated when the lock on {@link Queue} is highly contended.
*
* <p>
* This method is primarily added to make UI threads run faster.
*
* @since 1.483
* @deprecated Use {@link #getItems()} directly. As of 1.607 the approximation is no longer needed.
*/
@Deprecated
public List<Item> getApproximateItemsQuickly() {
return Arrays.asList(getItems());
}
public Item getItem(long id) {
Snapshot snapshot = this.snapshot;
for (Item item : snapshot.blockedProjects) {
if (item.id == id)
return item;
}
for (Item item : snapshot.buildables) {
if (item.id == id)
return item;
}
for (Item item : snapshot.pendings) {
if (item.id == id)
return item;
}
for (Item item : snapshot.waitingList) {
if (item.id == id) {
return item;
}
}
return leftItems.getIfPresent(id);
}
/**
* Gets all the {@link BuildableItem}s that are waiting for an executor in the given {@link Computer}.
*/
public List<BuildableItem> getBuildableItems(Computer c) {
Snapshot snapshot = this.snapshot;
List<BuildableItem> result = new ArrayList<BuildableItem>();
_getBuildableItems(c, snapshot.buildables, result);
_getBuildableItems(c, snapshot.pendings, result);
return result;
}
private void _getBuildableItems(Computer c, List<BuildableItem> col, List<BuildableItem> result) {
Node node = c.getNode();
if (node == null) // Deleted computers cannot take build items...
return;
for (BuildableItem p : col) {
if (node.canTake(p) == null)
result.add(p);
}
}
/**
* Gets the snapshot of all {@link BuildableItem}s.
*/
public List<BuildableItem> getBuildableItems() {
Snapshot snapshot = this.snapshot;
ArrayList<BuildableItem> r = new ArrayList<BuildableItem>(snapshot.buildables);
r.addAll(snapshot.pendings);
return r;
}
/**
* Gets the snapshot of all {@link BuildableItem}s.
*/
public List<BuildableItem> getPendingItems() {
return new ArrayList<BuildableItem>(snapshot.pendings);
}
/**
* Gets the snapshot of all {@link BlockedItem}s.
*/
protected List<BlockedItem> getBlockedItems() {
return new ArrayList<BlockedItem>(snapshot.blockedProjects);
}
/**
* Returns the snapshot of all {@link LeftItem}s.
*
* @since 1.519
*/
public Collection<LeftItem> getLeftItems() {
return Collections.unmodifiableCollection(leftItems.asMap().values());
}
/**
* Immediately clear the {@link #getLeftItems} cache.
* Useful for tests which need to verify that no links to a build remain.
* @since 1.519
*/
public void clearLeftItems() {
leftItems.invalidateAll();
}
/**
* Gets all items that are in the queue but not blocked
*
* @since 1.402
*/
public List<Item> getUnblockedItems() {
Snapshot snapshot = this.snapshot;
List<Item> queuedNotBlocked = new ArrayList<Item>();
queuedNotBlocked.addAll(snapshot.waitingList);
queuedNotBlocked.addAll(snapshot.buildables);
queuedNotBlocked.addAll(snapshot.pendings);
// but not 'blockedProjects'
return queuedNotBlocked;
}
/**
* Works just like {@link #getUnblockedItems()} but return tasks.
*
* @since 1.402
*/
public Set<Task> getUnblockedTasks() {
List<Item> items = getUnblockedItems();
Set<Task> unblockedTasks = new HashSet<Task>(items.size());
for (Queue.Item t : items)
unblockedTasks.add(t.task);
return unblockedTasks;
}
/**
* Is the given task currently pending execution?
*/
public boolean isPending(Task t) {
Snapshot snapshot = this.snapshot;
for (BuildableItem i : snapshot.pendings)
if (i.task.equals(t))
return true;
return false;
}
/**
* How many {@link BuildableItem}s are assigned for the given label?
* @param l Label to be checked. If null, any label will be accepted.
* If you want to count {@link BuildableItem}s without assigned labels,
* use {@link #strictCountBuildableItemsFor(hudson.model.Label)}.
* @return Number of {@link BuildableItem}s for the specified label.
*/
public @Nonnegative int countBuildableItemsFor(@CheckForNull Label l) {
Snapshot snapshot = this.snapshot;
int r = 0;
for (BuildableItem bi : snapshot.buildables)
for (SubTask st : bi.task.getSubTasks())
if (null == l || bi.getAssignedLabelFor(st) == l)
r++;
for (BuildableItem bi : snapshot.pendings)
for (SubTask st : bi.task.getSubTasks())
if (null == l || bi.getAssignedLabelFor(st) == l)
r++;
return r;
}
/**
* How many {@link BuildableItem}s are assigned for the given label?
* <p>
* The implementation is quite similar to {@link #countBuildableItemsFor(hudson.model.Label)},
* but it has another behavior for null parameters.
* @param l Label to be checked. If null, only jobs without assigned labels
* will be taken into the account.
* @return Number of {@link BuildableItem}s for the specified label.
* @since 1.615
*/
public @Nonnegative int strictCountBuildableItemsFor(@CheckForNull Label l) {
Snapshot _snapshot = this.snapshot;
int r = 0;
for (BuildableItem bi : _snapshot.buildables)
for (SubTask st : bi.task.getSubTasks())
if (bi.getAssignedLabelFor(st) == l)
r++;
for (BuildableItem bi : _snapshot.pendings)
for (SubTask st : bi.task.getSubTasks())
if (bi.getAssignedLabelFor(st) == l)
r++;
return r;
}
/**
* Counts all the {@link BuildableItem}s currently in the queue.
*/
public int countBuildableItems() {
return countBuildableItemsFor(null);
}
/**
* Gets the information about the queue item for the given project.
*
* @return null if the project is not in the queue.
*/
public Item getItem(Task t) {
Snapshot snapshot = this.snapshot;
for (Item item : snapshot.blockedProjects) {
if (item.task.equals(t))
return item;
}
for (Item item : snapshot.buildables) {
if (item.task.equals(t))
return item;
}
for (Item item : snapshot.pendings) {
if (item.task.equals(t))
return item;
}
for (Item item : snapshot.waitingList) {
if (item.task.equals(t)) {
return item;
}
}
return null;
}
/**
* Gets the information about the queue item for the given project.
*
* @return null if the project is not in the queue.
* @since 1.607
*/
private List<Item> liveGetItems(Task t) {
lock.lock();
try {
List<Item> result = new ArrayList<Item>();
result.addAll(blockedProjects.getAll(t));
result.addAll(buildables.getAll(t));
// Do not include pendings—we have already finalized WorkUnitContext.actions.
if (LOGGER.isLoggable(Level.FINE)) {
List<BuildableItem> thePendings = pendings.getAll(t);
if (!thePendings.isEmpty()) {
LOGGER.log(Level.FINE, "ignoring {0} during scheduleInternal", thePendings);
}
}
for (Item item : waitingList) {
if (item.task.equals(t)) {
result.add(item);
}
}
return result;
} finally {
lock.unlock();
}
}
/**
* Gets the information about the queue item for the given project.
*
* @return null if the project is not in the queue.
*/
public List<Item> getItems(Task t) {
Snapshot snapshot = this.snapshot;
List<Item> result = new ArrayList<Item>();
for (Item item : snapshot.blockedProjects) {
if (item.task.equals(t)) {
result.add(item);
}
}
for (Item item : snapshot.buildables) {
if (item.task.equals(t)) {
result.add(item);
}
}
for (Item item : snapshot.pendings) {
if (item.task.equals(t)) {
result.add(item);
}
}
for (Item item : snapshot.waitingList) {
if (item.task.equals(t)) {
result.add(item);
}
}
return result;
}
/**
* Returns true if this queue contains the said project.
*/
public boolean contains(Task t) {
return getItem(t)!=null;
}
/**
* Called when the executor actually starts executing the assigned work unit.
*
* This moves the task from the pending state to the "left the queue" state.
*/
/*package*/ void onStartExecuting(Executor exec) throws InterruptedException {
lock.lock();
try { try {
final WorkUnit wu = exec.getCurrentWorkUnit();
pendings.remove(wu.context.item);
LeftItem li = new LeftItem(wu.context);
li.enter(this);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Checks the queue and runs anything that can be run.
*
* <p>
* When conditions are changed, this method should be invoked.
* <p>
* This wakes up one {@link Executor} so that it will maintain a queue.
*/
@WithBridgeMethods(void.class)
public Future<?> scheduleMaintenance() {
// LOGGER.info("Scheduling maintenance");
return maintainerThread.submit();
}
/**
* Checks if the given item should be prevented from entering into the {@link #buildables} state
* and instead stay in the {@link #blockedProjects} state.
*/
private boolean isBuildBlocked(Item i) {
if (i.task.isBuildBlocked() || !canRun(i.task.getResourceList()))
return true;
for (QueueTaskDispatcher d : QueueTaskDispatcher.all()) {
if (d.canRun(i)!=null)
return true;
}
return false;
}
/**
* Make sure we don't queue two tasks of the same project to be built
* unless that project allows concurrent builds.
*/
private boolean allowNewBuildableTask(Task t) {
if (t.isConcurrentBuild()) {
return true;
}
return !buildables.containsKey(t) && !pendings.containsKey(t);
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
* @param runnable the operation to perform.
* @since 1.592
*/
public static void withLock(Runnable runnable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
runnable.run();
} else {
queue._withLock(runnable);
}
}
/**
* Some operations require the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
*
* @param callable the operation to perform.
* @param <V> the type of return value
* @param <T> the type of exception.
* @return the result of the callable.
* @throws T the exception of the callable
* @since 1.592
*/
public static <V, T extends Throwable> V withLock(hudson.remoting.Callable<V, T> callable) throws T {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
return callable.call();
} else {
return queue._withLock(callable);
}
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
*
* @param callable the operation to perform.
* @param <V> the type of return value
* @return the result of the callable.
* @throws Exception if the callable throws an exception.
* @since 1.592
*/
public static <V> V withLock(java.util.concurrent.Callable<V> callable) throws Exception {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
return callable.call();
} else {
return queue._withLock(callable);
}
}
/**
* Invokes the supplied {@link Runnable} if the {@link Queue} lock was obtained without blocking.
*
* @param runnable the operation to perform.
* @return {@code true} if the lock was available and the operation was performed.
* @since 1.618
*/
public static boolean tryWithLock(Runnable runnable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
runnable.run();
return true;
} else {
return queue._tryWithLock(runnable);
}
}
/**
* Wraps a {@link Runnable} with the {@link Queue} lock held.
*
* @param runnable the operation to wrap.
* @since 1.618
*/
public static Runnable wrapWithLock(Runnable runnable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? runnable : new LockedRunnable(runnable);
}
/**
* Wraps a {@link hudson.remoting.Callable} with the {@link Queue} lock held.
*
* @param callable the operation to wrap.
* @since 1.618
*/
public static <V, T extends Throwable> hudson.remoting.Callable<V, T> wrapWithLock(hudson.remoting.Callable<V, T> callable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? callable : new LockedHRCallable<>(callable);
}
/**
* Wraps a {@link java.util.concurrent.Callable} with the {@link Queue} lock held.
*
* @param callable the operation to wrap.
* @since 1.618
*/
public static <V> java.util.concurrent.Callable<V> wrapWithLock(java.util.concurrent.Callable<V> callable) {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? callable : new LockedJUCCallable<V>(callable);
}
@Override
protected void _await() throws InterruptedException {
condition.await();
}
@Override
protected void _signalAll() {
condition.signalAll();
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
* @param runnable the operation to perform.
* @since 1.592
*/
protected void _withLock(Runnable runnable) {
lock.lock();
try {
runnable.run();
} finally {
lock.unlock();
}
}
/**
* Invokes the supplied {@link Runnable} if the {@link Queue} lock was obtained without blocking.
*
* @param runnable the operation to perform.
* @return {@code true} if the lock was available and the operation was performed.
* @since 1.618
*/
protected boolean _tryWithLock(Runnable runnable) {
if (lock.tryLock()) {
try {
runnable.run();
} finally {
lock.unlock();
}
return true;
} else {
return false;
}
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
*
* @param callable the operation to perform.
* @param <V> the type of return value
* @param <T> the type of exception.
* @return the result of the callable.
* @throws T the exception of the callable
* @since 1.592
*/
protected <V, T extends Throwable> V _withLock(hudson.remoting.Callable<V, T> callable) throws T {
lock.lock();
try {
return callable.call();
} finally {
lock.unlock();
}
}
/**
* Some operations require to be performed with the {@link Queue} lock held. Use one of these methods rather
* than locking directly on Queue in order to allow for future refactoring.
*
* @param callable the operation to perform.
* @param <V> the type of return value
* @return the result of the callable.
* @throws Exception if the callable throws an exception.
* @since 1.592
*/
protected <V> V _withLock(java.util.concurrent.Callable<V> callable) throws Exception {
lock.lock();
try {
return callable.call();
} finally {
lock.unlock();
}
}
/**
* Queue maintenance.
*
* <p>
* Move projects between {@link #waitingList}, {@link #blockedProjects}, {@link #buildables}, and {@link #pendings}
* appropriately.
*
* <p>
* Jenkins internally invokes this method by itself whenever there's a change that can affect
* the scheduling (such as new node becoming online, # of executors change, a task completes execution, etc.),
* and it also gets invoked periodically (see {@link Queue.MaintainTask}.)
*/
public void maintain() {
lock.lock();
try { try {
LOGGER.log(Level.FINE, "Queue maintenance started on {0} with {1}", new Object[] {this, snapshot});
// The executors that are currently waiting for a job to run.
Map<Executor, JobOffer> parked = new HashMap<Executor, JobOffer>();
{// update parked (and identify any pending items whose executor has disappeared)
List<BuildableItem> lostPendings = new ArrayList<BuildableItem>(pendings);
for (Computer c : Jenkins.getInstance().getComputers()) {
for (Executor e : c.getExecutors()) {
if (e.isInterrupted()) {
// JENKINS-28840 we will deadlock if we try to touch this executor while interrupt flag set
// we need to clear lost pendings as we cannot know what work unit was on this executor
// while it is interrupted. (All this dancing is a result of Executor extending Thread)
lostPendings.clear(); // we'll get them next time around when the flag is cleared.
LOGGER.log(Level.FINEST,
"Interrupt thread for executor {0} is set and we do not know what work unit was on the executor.",
e.getDisplayName());
continue;
}
if (e.isParking()) {
LOGGER.log(Level.FINEST, "{0} is parking and is waiting for a job to execute.", e.getDisplayName());
parked.put(e, new JobOffer(e));
}
final WorkUnit workUnit = e.getCurrentWorkUnit();
if (workUnit != null) {
lostPendings.remove(workUnit.context.item);
}
}
}
// pending -> buildable
for (BuildableItem p: lostPendings) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"BuildableItem {0}: pending -> buildable as the assigned executor disappeared",
p.task.getFullDisplayName());
}
p.isPending = false;
pendings.remove(p);
makeBuildable(p); // TODO whatever this is for, the return value is being ignored, so this does nothing at all
}
}
final QueueSorter s = sorter;
{// blocked -> buildable
// copy as we'll mutate the list and we want to process in a potentially different order
List<BlockedItem> blockedItems = new ArrayList<>(blockedProjects.values());
// if facing a cycle of blocked tasks, ensure we process in the desired sort order
if (s != null) {
s.sortBlockedItems(blockedItems);
} else {
Collections.sort(blockedItems, QueueSorter.DEFAULT_BLOCKED_ITEM_COMPARATOR);
}
for (BlockedItem p : blockedItems) {
String taskDisplayName = LOGGER.isLoggable(Level.FINEST) ? p.task.getFullDisplayName() : null;
LOGGER.log(Level.FINEST, "Current blocked item: {0}", taskDisplayName);
if (!isBuildBlocked(p) && allowNewBuildableTask(p.task)) {
LOGGER.log(Level.FINEST,
"BlockedItem {0}: blocked -> buildable as the build is not blocked and new tasks are allowed",
taskDisplayName);
// ready to be executed
Runnable r = makeBuildable(new BuildableItem(p));
if (r != null) {
p.leave(this);
r.run();
// JENKINS-28926 we have removed a task from the blocked projects and added to building
// thus we should update the snapshot so that subsequent blocked projects can correctly
// determine if they are blocked by the lucky winner
updateSnapshot();
}
}
}
}
// waitingList -> buildable/blocked
while (!waitingList.isEmpty()) {
WaitingItem top = peek();
if (top.timestamp.compareTo(new GregorianCalendar()) > 0) {
LOGGER.log(Level.FINEST, "Finished moving all ready items from queue.");
break; // finished moving all ready items from queue
}
top.leave(this);
Task p = top.task;
if (!isBuildBlocked(top) && allowNewBuildableTask(p)) {
// ready to be executed immediately
Runnable r = makeBuildable(new BuildableItem(top));
String topTaskDisplayName = LOGGER.isLoggable(Level.FINEST) ? top.task.getFullDisplayName() : null;
if (r != null) {
LOGGER.log(Level.FINEST, "Executing runnable {0}", topTaskDisplayName);
r.run();
} else {
LOGGER.log(Level.FINEST, "Item {0} was unable to be made a buildable and is now a blocked item.", topTaskDisplayName);
new BlockedItem(top).enter(this);
}
} else {
// this can't be built now because another build is in progress
// set this project aside.
new BlockedItem(top).enter(this);
}
}
if (s != null)
s.sortBuildableItems(buildables);
// Ensure that identification of blocked tasks is using the live state: JENKINS-27708 & JENKINS-27871
updateSnapshot();
// allocate buildable jobs to executors
for (BuildableItem p : new ArrayList<BuildableItem>(
buildables)) {// copy as we'll mutate the list in the loop
// one last check to make sure this build is not blocked.
if (isBuildBlocked(p)) {
p.leave(this);
new BlockedItem(p).enter(this);
LOGGER.log(Level.FINE, "Catching that {0} is blocked in the last minute", p);
// JENKINS-28926 we have moved an unblocked task into the blocked state, update snapshot
// so that other buildables which might have been blocked by this can see the state change
updateSnapshot();
continue;
}
String taskDisplayName = LOGGER.isLoggable(Level.FINEST) ? p.task.getFullDisplayName() : null;
if (p.task instanceof FlyweightTask) {
Runnable r = makeFlyWeightTaskBuildable(new BuildableItem(p));
if (r != null) {
p.leave(this);
LOGGER.log(Level.FINEST, "Executing flyweight task {0}", taskDisplayName);
r.run();
updateSnapshot();
}
} else {
List<JobOffer> candidates = new ArrayList<>(parked.size());
List<CauseOfBlockage> reasons = new ArrayList<>(parked.size());
for (JobOffer j : parked.values()) {
CauseOfBlockage reason = j.getCauseOfBlockage(p);
if (reason == null) {
LOGGER.log(Level.FINEST,
"{0} is a potential candidate for task {1}",
new Object[]{j, taskDisplayName});
candidates.add(j);
} else {
LOGGER.log(Level.FINEST, "{0} rejected {1}: {2}", new Object[] {j, taskDisplayName, reason});
reasons.add(reason);
}
}
MappingWorksheet ws = new MappingWorksheet(p, candidates);
Mapping m = loadBalancer.map(p.task, ws);
if (m == null) {
// if we couldn't find the executor that fits,
// just leave it in the buildables list and
// check if we can execute other projects
LOGGER.log(Level.FINER, "Failed to map {0} to executors. candidates={1} parked={2}",
new Object[]{p, candidates, parked.values()});
p.transientCausesOfBlockage = reasons.isEmpty() ? null : reasons;
continue;
}
// found a matching executor. use it.
WorkUnitContext wuc = new WorkUnitContext(p);
LOGGER.log(Level.FINEST, "Found a matching executor for {0}. Using it.", taskDisplayName);
m.execute(wuc);
p.leave(this);
if (!wuc.getWorkUnits().isEmpty()) {
LOGGER.log(Level.FINEST, "BuildableItem {0} marked as pending.", taskDisplayName);
makePending(p);
}
else
LOGGER.log(Level.FINEST, "BuildableItem {0} with empty work units!?", p);
// Ensure that identification of blocked tasks is using the live state: JENKINS-27708 & JENKINS-27871
// The creation of a snapshot itself should be relatively cheap given the expected rate of
// job execution. You probably would need 100's of jobs starting execution every iteration
// of maintain() before this could even start to become an issue and likely the calculation
// of isBuildBlocked(p) will become a bottleneck before updateSnapshot() will. Additionally
// since the snapshot itself only ever has at most one reference originating outside of the stack
// it should remain in the eden space and thus be cheap to GC.
// See https://jenkins-ci.org/issue/27708?focusedCommentId=225819&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-225819
// or https://jenkins-ci.org/issue/27708?focusedCommentId=225906&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-225906
// for alternative fixes of this issue.
updateSnapshot();
}
}
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Tries to make an item ready to build.
* @param p a proposed buildable item
* @return a thunk to actually prepare it (after leaving an earlier list), or null if it cannot be run now
*/
private @CheckForNull Runnable makeBuildable(final BuildableItem p) {
if (p.task instanceof FlyweightTask) {
String taskDisplayName = LOGGER.isLoggable(Level.FINEST) ? p.task.getFullDisplayName() : null;
if (!isBlockedByShutdown(p.task)) {
Runnable runnable = makeFlyWeightTaskBuildable(p);
LOGGER.log(Level.FINEST, "Converting flyweight task: {0} into a BuildableRunnable", taskDisplayName);
if(runnable != null){
return runnable;
}
//this is to solve JENKINS-30084: the task has to be buildable to force the provisioning of nodes.
//if the execution gets here, it means the task could not be scheduled since the node
//the task is supposed to run on is offline or not available.
//Thus, the flyweighttask enters the buildables queue and will ask Jenkins to provision a node
LOGGER.log(Level.FINEST, "Flyweight task {0} is entering as buildable to provision a node.", taskDisplayName);
return new BuildableRunnable(p);
}
// if the execution gets here, it means the task is blocked by shutdown and null is returned.
LOGGER.log(Level.FINEST, "Task {0} is blocked by shutdown.", taskDisplayName);
return null;
} else {
// regular heavyweight task
return new BuildableRunnable(p);
}
}
/**
* This method checks if the flyweight task can be run on any of the available executors
* @param p - the flyweight task to be scheduled
* @return a Runnable if there is an executor that can take the task, null otherwise
*/
@CheckForNull
private Runnable makeFlyWeightTaskBuildable(final BuildableItem p){
//we double check if this is a flyweight task
if (p.task instanceof FlyweightTask) {
Jenkins h = Jenkins.getInstance();
Map<Node, Integer> hashSource = new HashMap<Node, Integer>(h.getNodes().size());
// Even if master is configured with zero executors, we may need to run a flyweight task like MatrixProject on it.
hashSource.put(h, Math.max(h.getNumExecutors() * 100, 1));
for (Node n : h.getNodes()) {
hashSource.put(n, n.getNumExecutors() * 100);
}
ConsistentHash<Node> hash = new ConsistentHash<Node>(NODE_HASH);
hash.addAll(hashSource);
Label lbl = p.getAssignedLabel();
String fullDisplayName = p.task.getFullDisplayName();
for (Node n : hash.list(fullDisplayName)) {
final Computer c = n.toComputer();
if (c == null || c.isOffline()) {
continue;
}
if (lbl!=null && !lbl.contains(n)) {
continue;
}
if (n.canTake(p) != null) {
continue;
}
LOGGER.log(Level.FINEST, "Creating flyweight task {0} for computer {1}", new Object[]{fullDisplayName, c.getName()});
return new Runnable() {
@Override public void run() {
c.startFlyWeightTask(new WorkUnitContext(p).createWorkUnit(p.task));
makePending(p);
}
};
}
}
return null;
}
private static Hash<Node> NODE_HASH = new Hash<Node>() {
public String hash(Node node) {
return node.getNodeName();
}
};
private boolean makePending(BuildableItem p) {
// LOGGER.info("Making "+p.task+" pending"); // REMOVE
p.isPending = true;
return pendings.add(p);
}
/** @deprecated Use {@link #isBlockedByShutdown} instead. */
@Deprecated
public static boolean ifBlockedByHudsonShutdown(Task task) {
return isBlockedByShutdown(task);
}
/**
* Checks whether a task should not be scheduled because {@link Jenkins#isQuietingDown()}.
* @param task some queue task
* @return true if {@link Jenkins#isQuietingDown()} unless this is a {@link NonBlockingTask}
* @since 1.598
*/
public static boolean isBlockedByShutdown(Task task) {
return Jenkins.getInstance().isQuietingDown() && !(task instanceof NonBlockingTask);
}
public Api getApi() {
return new Api(this);
}
/**
* Marks {@link Task}s that are not persisted.
* @since 1.311
*/
public interface TransientTask extends Task {}
/**
* Marks {@link Task}s that do not consume {@link Executor}.
* @see OneOffExecutor
* @since 1.318
*/
public interface FlyweightTask extends Task {}
/**
* Marks {@link Task}s that are not affected by the {@linkplain Jenkins#isQuietingDown()} quieting down},
* because these tasks keep other tasks executing.
* @see #isBlockedByShutdown
* @since 1.336
*/
public interface NonBlockingTask extends Task {}
/**
* Task whose execution is controlled by the queue.
*
* <p>
* {@link #equals(Object) Value equality} of {@link Task}s is used
* to collapse two tasks into one. This is used to avoid infinite
* queue backlog.
*
* <p>
* Pending {@link Task}s are persisted when Hudson shuts down, so
* it needs to be persistable via XStream. To create a non-persisted
* transient Task, extend {@link TransientTask} marker interface.
*
* <p>
* Plugins are encouraged to extend from {@link AbstractQueueTask}
* instead of implementing this interface directly, to maintain
* compatibility with future changes to this interface.
*
* <p>
* Plugins are encouraged to implement {@link AccessControlled} otherwise
* the tasks will be hidden from display in the queue.
*
* <p>
* For historical reasons, {@link Task} object by itself
* also represents the "primary" sub-task (and as implied by this
* design, a {@link Task} must have at least one sub-task.)
* Most of the time, the primary subtask is the only sub task.
*/
public interface Task extends ModelObject, SubTask {
/**
* Returns true if the execution should be blocked
* for temporary reasons.
*
* <p>
* Short-hand for {@code getCauseOfBlockage()!=null}.
*/
boolean isBuildBlocked();
/**
* @deprecated as of 1.330
* Use {@link CauseOfBlockage#getShortDescription()} instead.
*/
@Deprecated
String getWhyBlocked();
/**
* If the execution of this task should be blocked for temporary reasons,
* this method returns a non-null object explaining why.
*
* <p>
* Otherwise this method returns null, indicating that the build can proceed right away.
*
* <p>
* This can be used to define mutual exclusion that goes beyond
* {@link #getResourceList()}.
* @return by default, null
*/
@CheckForNull
default CauseOfBlockage getCauseOfBlockage() {
return null;
}
/**
* Unique name of this task.
*
* <p>
* This method is no longer used, left here for compatibility. Just return {@link #getDisplayName()}.
*/
String getName();
/**
* @see hudson.model.Item#getFullDisplayName()
*/
String getFullDisplayName();
/**
* Checks the permission to see if the current user can abort this executable.
* Returns normally from this method if it's OK.
* <p>
* NOTE: If you have implemented {@link AccessControlled} this should just be
* {@code checkPermission(hudson.model.Item.CANCEL);}
*
* @throws AccessDeniedException if the permission is not granted.
*/
void checkAbortPermission();
/**
* Works just like {@link #checkAbortPermission()} except it indicates the status by a return value,
* instead of exception.
* Also used by default for {@link hudson.model.Queue.Item#hasCancelPermission}.
* <p>
* NOTE: If you have implemented {@link AccessControlled} this should just be
* {@code return hasPermission(hudson.model.Item.CANCEL);}
*
* @return false
* if the user doesn't have the permission.
*/
boolean hasAbortPermission();
/**
* Returns the URL of this task relative to the context root of the application.
*
* <p>
* When the user clicks an item in the queue, this is the page where the user is taken to.
* Hudson expects the current instance to be bound to the URL returned by this method.
*
* @return
* URL that ends with '/'.
*/
String getUrl();
/**
* True if the task allows concurrent builds, where the same {@link Task} is executed
* by multiple executors concurrently on the same or different nodes.
* @return by default, false
* @since 1.338
*/
default boolean isConcurrentBuild() {
return false;
}
/**
* Obtains the {@link SubTask}s that constitute this task.
*
* <p>
* The collection returned by this method must also contain the primary {@link SubTask}
* represented by this {@link Task} object itself as the first element.
* The returned value is read-only.
*
* <p>
* At least size 1.
*
* @return by default, {@code this}
* @since 1.377
*/
default Collection<? extends SubTask> getSubTasks() {
return Collections.singleton(this);
}
/**
* This method allows the task to provide the default fallback authentication object to be used
* when {@link QueueItemAuthenticator} fails to authenticate the build.
*
* <p>
* When the task execution touches other objects inside Jenkins, the access control is performed
* based on whether this {@link Authentication} is allowed to use them.
*
* @return by default, {@link ACL#SYSTEM}
* @since 1.520
* @see QueueItemAuthenticator
* @see Tasks#getDefaultAuthenticationOf(Queue.Task)
*/
default @Nonnull Authentication getDefaultAuthentication() {
return ACL.SYSTEM;
}
/**
* This method allows the task to provide the default fallback authentication object to be used
* when {@link QueueItemAuthenticator} fails to authenticate the build.
*
* <p>
* When the task execution touches other objects inside Jenkins, the access control is performed
* based on whether this {@link Authentication} is allowed to use them.
*
* <p>
* This method was added to an interface after it was created, so plugins built against
* older versions of Jenkins may not have this method implemented. Called private method _getDefaultAuthenticationOf(Task) on {@link Tasks}
* to avoid {@link AbstractMethodError}.
*
* @since 1.592
* @see QueueItemAuthenticator
* @see Tasks#getDefaultAuthenticationOf(Queue.Task, Queue.Item)
*/
default @Nonnull Authentication getDefaultAuthentication(Queue.Item item) {
return getDefaultAuthentication();
}
}
/**
* Represents the real meat of the computation run by {@link Executor}.
*
* <h2>Views</h2>
* <p>
* Implementation must have <tt>executorCell.jelly</tt>, which is
* used to render the HTML that indicates this executable is executing.
*/
public interface Executable extends Runnable {
/**
* Task from which this executable was created.
*
* <p>
* Since this method went through a signature change in 1.377, the invocation may results in
* {@link AbstractMethodError}.
* Use {@link Executables#getParentOf(Queue.Executable)} that avoids this.
*/
@Nonnull SubTask getParent();
/**
* Called by {@link Executor} to perform the task.
* @throws AsynchronousExecution if you would like to continue without consuming a thread
*/
@Override void run() throws AsynchronousExecution;
/**
* Estimate of how long will it take to execute this executable.
* Measured in milliseconds.
*
* @return -1 if it's impossible to estimate; default, {@link SubTask#getEstimatedDuration}
* @since 1.383
*/
default long getEstimatedDuration() {
return Executables.getParentOf(this).getEstimatedDuration();
}
/**
* Used to render the HTML. Should be a human readable text of what this executable is.
*/
@Override String toString();
}
/**
* Item in a queue.
*/
@ExportedBean(defaultVisibility = 999)
public static abstract class Item extends Actionable {
private final long id;
/**
* Unique ID (per master) that tracks the {@link Task} as it moves through different stages
* in the queue (each represented by different subtypes of {@link Item} and into any subsequent
* {@link Run} instance (see {@link Run#getQueueId()}).
* @return
* @since 1.601
*/
@Exported
public long getId() {
return id;
}
@AdaptField(was=int.class, name="id")
@Deprecated
public int getIdLegacy() {
if (id > Integer.MAX_VALUE) {
throw new IllegalStateException("Sorry, you need to update any Plugins attempting to " +
"assign 'Queue.Item.id' to an int value. 'Queue.Item.id' is now a long value and " +
"has incremented to a value greater than Integer.MAX_VALUE (2^31 - 1).");
}
return (int) id;
}
/**
* Project to be built.
*/
@Exported
public final Task task;
private /*almost final*/ transient FutureImpl future;
private final long inQueueSince;
/**
* Build is blocked because another build is in progress,
* required {@link Resource}s are not available, or otherwise blocked
* by {@link Task#isBuildBlocked()}.
*/
@Exported
public boolean isBlocked() { return this instanceof BlockedItem; }
/**
* Build is waiting the executor to become available.
* This flag is only used in {@link Queue#getItems()} for
* 'pseudo' items that are actually not really in the queue.
*/
@Exported
public boolean isBuildable() { return this instanceof BuildableItem; }
/**
* True if the item is starving for an executor for too long.
*/
@Exported
public boolean isStuck() { return false; }
/**
* Since when is this item in the queue.
* @return Unix timestamp
*/
@Exported
public long getInQueueSince() {
return this.inQueueSince;
}
/**
* Returns a human readable presentation of how long this item is already in the queue.
* E.g. something like '3 minutes 40 seconds'
*/
public String getInQueueForString() {
long duration = System.currentTimeMillis() - this.inQueueSince;
return Util.getTimeSpanString(duration);
}
/**
* Can be used to wait for the completion (either normal, abnormal, or cancellation) of the {@link Task}.
* <p>
* Just like {@link #getId()}, the same object tracks various stages of the queue.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<Executable> getFuture() { return future; }
/**
* If this task needs to be run on a node with a particular label,
* return that {@link Label}. Otherwise null, indicating
* it can run on anywhere.
*
* <p>
* This code takes {@link LabelAssignmentAction} into account, then fall back to {@link SubTask#getAssignedLabel()}
*/
public Label getAssignedLabel() {
for (LabelAssignmentAction laa : getActions(LabelAssignmentAction.class)) {
Label l = laa.getAssignedLabel(task);
if (l!=null) return l;
}
return task.getAssignedLabel();
}
/**
* Test if the specified {@link SubTask} needs to be run on a node with a particular label.
* <p>
* This method takes {@link LabelAssignmentAction} into account, the first
* non-null assignment will be returned.
* Otherwise falls back to {@link SubTask#getAssignedLabel()}
* @param st {@link SubTask} to be checked.
* @return Required {@link Label}. Otherwise null, indicating it can run on anywhere.
*/
public @CheckForNull Label getAssignedLabelFor(@Nonnull SubTask st) {
for (LabelAssignmentAction laa : getActions(LabelAssignmentAction.class)) {
Label l = laa.getAssignedLabel(st);
if (l!=null) return l;
}
return st.getAssignedLabel();
}
/**
* Convenience method that returns a read only view of the {@link Cause}s associated with this item in the queue.
*
* @return can be empty but never null
* @since 1.343
*/
public final List<Cause> getCauses() {
CauseAction ca = getAction(CauseAction.class);
if (ca!=null)
return Collections.unmodifiableList(ca.getCauses());
return Collections.emptyList();
}
@Restricted(DoNotUse.class) // used from Jelly
public String getCausesDescription() {
List<Cause> causes = getCauses();
StringBuilder s = new StringBuilder();
for (Cause c : causes) {
s.append(c.getShortDescription()).append('\n');
}
return s.toString();
}
protected Item(Task task, List<Action> actions, long id, FutureImpl future) {
this.task = task;
this.id = id;
this.future = future;
this.inQueueSince = System.currentTimeMillis();
for (Action action: actions) addAction(action);
}
protected Item(Task task, List<Action> actions, long id, FutureImpl future, long inQueueSince) {
this.task = task;
this.id = id;
this.future = future;
this.inQueueSince = inQueueSince;
for (Action action: actions) addAction(action);
}
protected Item(Item item) {
this(item.task, new ArrayList<Action>(item.getAllActions()), item.id, item.future, item.inQueueSince);
}
/**
* Returns the URL of this {@link Item} relative to the context path of Jenkins
*
* @return
* URL that ends with '/'.
* @since 1.519
*/
@Exported
public String getUrl() {
return "queue/item/"+id+'/';
}
/**
* Gets a human-readable status message describing why it's in the queue.
*/
@Exported
public final String getWhy() {
CauseOfBlockage cob = getCauseOfBlockage();
return cob!=null ? cob.getShortDescription() : null;
}
/**
* Gets an object that describes why this item is in the queue.
*/
public abstract CauseOfBlockage getCauseOfBlockage();
/**
* Gets a human-readable message about the parameters of this item
* @return String
*/
@Exported
public String getParams() {
StringBuilder s = new StringBuilder();
for (ParametersAction pa : getActions(ParametersAction.class)) {
for (ParameterValue p : pa.getParameters()) {
s.append('\n').append(p.getShortDescription());
}
}
return s.toString();
}
/**
* Checks whether a scheduled item may be canceled.
* @return by default, the same as {@link hudson.model.Queue.Task#hasAbortPermission}
*/
public boolean hasCancelPermission() {
return task.hasAbortPermission();
}
public String getDisplayName() {
// TODO Auto-generated method stub
return null;
}
public String getSearchUrl() {
// TODO Auto-generated method stub
return null;
}
/** @deprecated Use {@link #doCancelItem} instead. */
@Deprecated
@RequirePOST
public HttpResponse doCancelQueue() throws IOException, ServletException {
Jenkins.getInstance().getQueue().cancel(this);
return HttpResponses.forwardToPreviousPage();
}
/**
* Returns the identity that this task carries when it runs, for the purpose of access control.
*
* When the task execution touches other objects inside Jenkins, the access control is performed
* based on whether this {@link Authentication} is allowed to use them. Implementers, if you are unsure,
* return the identity of the user who queued the task, or {@link ACL#SYSTEM} to bypass the access control
* and run as the super user.
*
* @since 1.520
*/
@Nonnull
public Authentication authenticate() {
for (QueueItemAuthenticator auth : QueueItemAuthenticatorProvider.authenticators()) {
Authentication a = auth.authenticate(this);
if (a!=null)
return a;
}
return task.getDefaultAuthentication(this);
}
public Api getApi() {
return new Api(this);
}
private Object readResolve() {
this.future = new FutureImpl(task);
return this;
}
@Override
public String toString() {
return getClass().getName() + ':' + task + ':' + id;
}
/**
* Enters the appropriate queue for this type of item.
*/
/*package*/ abstract void enter(Queue q);
/**
* Leaves the appropriate queue for this type of item.
*/
/*package*/ abstract boolean leave(Queue q);
/**
* Cancels this item, which updates {@link #future} to notify the listener, and
* also leaves the queue.
*
* @return true
* if the item was successfully cancelled.
*/
/*package*/ boolean cancel(Queue q) {
boolean r = leave(q);
if (r) {
future.setAsCancelled();
LeftItem li = new LeftItem(this);
li.enter(q);
}
return r;
}
}
/**
* A Stub class for {@link Task} which exposes only the name of the Task to be displayed when the user
* has DISCOVERY permissions only.
*/
@Restricted(NoExternalUse.class)
@ExportedBean(defaultVisibility = 999)
public static class StubTask {
private String name;
public StubTask(@Nonnull Queue.Task base) {
this.name = base.getName();
}
@Exported
public String getName() {
return name;
}
}
/**
* A Stub class for {@link Item} which exposes only the name of the Task to be displayed when the user
* has DISCOVERY permissions only.
*/
@Restricted(NoExternalUse.class)
@ExportedBean(defaultVisibility = 999)
public class StubItem {
@Exported public StubTask task;
public StubItem(StubTask task) {
this.task = task;
}
}
/**
* An optional interface for actions on Queue.Item.
* Lets the action cooperate in queue management.
*
* @since 1.300-ish.
*/
public interface QueueAction extends Action {
/**
* Returns whether the new item should be scheduled.
* An action should return true if the associated task is 'different enough' to warrant a separate execution.
*/
boolean shouldSchedule(List<Action> actions);
}
/**
* Extension point for deciding if particular job should be scheduled or not.
*
* <p>
* This handler is consulted every time someone tries to submit a task to the queue.
* If any of the registered handlers returns false, the task will not be added
* to the queue, and the task will never get executed.
*
* <p>
* The other use case is to add additional {@link Action}s to the task
* (for example {@link LabelAssignmentAction}) to tasks that are submitted to the queue.
*
* @since 1.316
*/
public static abstract class QueueDecisionHandler implements ExtensionPoint {
/**
* Returns whether the new item should be scheduled.
*
* @param actions
* List of actions that are to be made available as {@link AbstractBuild#getActions()}
* upon the start of the build. This list is live, and can be mutated.
*/
public abstract boolean shouldSchedule(Task p, List<Action> actions);
/**
* All registered {@link QueueDecisionHandler}s
*/
public static ExtensionList<QueueDecisionHandler> all() {
return ExtensionList.lookup(QueueDecisionHandler.class);
}
}
/**
* {@link Item} in the {@link Queue#waitingList} stage.
*/
public static final class WaitingItem extends Item implements Comparable<WaitingItem> {
private static final AtomicLong COUNTER = new AtomicLong(0);
/**
* This item can be run after this time.
*/
@Exported
public Calendar timestamp;
public WaitingItem(Calendar timestamp, Task project, List<Action> actions) {
super(project, actions, COUNTER.incrementAndGet(), new FutureImpl(project));
this.timestamp = timestamp;
}
static int getCurrentCounterValue() {
return COUNTER.intValue();
}
public int compareTo(WaitingItem that) {
int r = this.timestamp.getTime().compareTo(that.timestamp.getTime());
if (r != 0) return r;
if (this.getId() < that.getId()) {
return -1;
} else if (this.getId() == that.getId()) {
return 0;
} else {
return 1;
}
}
public CauseOfBlockage getCauseOfBlockage() {
long diff = timestamp.getTimeInMillis() - System.currentTimeMillis();
if (diff > 0)
return CauseOfBlockage.fromMessage(Messages._Queue_InQuietPeriod(Util.getTimeSpanString(diff)));
else
return CauseOfBlockage.fromMessage(Messages._Queue_Unknown());
}
@Override
/*package*/ void enter(Queue q) {
if (q.waitingList.add(this)) {
for (QueueListener ql : QueueListener.all()) {
try {
ql.onEnterWaiting(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
}
@Override
/*package*/ boolean leave(Queue q) {
boolean r = q.waitingList.remove(this);
if (r) {
for (QueueListener ql : QueueListener.all()) {
try {
ql.onLeaveWaiting(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
return r;
}
}
/**
* Common part between {@link BlockedItem} and {@link BuildableItem}.
*/
public static abstract class NotWaitingItem extends Item {
/**
* When did this job exit the {@link Queue#waitingList} phase?
*/
@Exported
public final long buildableStartMilliseconds;
protected NotWaitingItem(WaitingItem wi) {
super(wi);
buildableStartMilliseconds = System.currentTimeMillis();
}
protected NotWaitingItem(NotWaitingItem ni) {
super(ni);
buildableStartMilliseconds = ni.buildableStartMilliseconds;
}
}
/**
* {@link Item} in the {@link Queue#blockedProjects} stage.
*/
public final class BlockedItem extends NotWaitingItem {
public BlockedItem(WaitingItem wi) {
super(wi);
}
public BlockedItem(NotWaitingItem ni) {
super(ni);
}
public CauseOfBlockage getCauseOfBlockage() {
ResourceActivity r = getBlockingActivity(task);
if (r != null) {
if (r == task) // blocked by itself, meaning another build is in progress
return CauseOfBlockage.fromMessage(Messages._Queue_InProgress());
return CauseOfBlockage.fromMessage(Messages._Queue_BlockedBy(r.getDisplayName()));
}
for (QueueTaskDispatcher d : QueueTaskDispatcher.all()) {
CauseOfBlockage cause = d.canRun(this);
if (cause != null)
return cause;
}
return task.getCauseOfBlockage();
}
/*package*/ void enter(Queue q) {
LOGGER.log(Level.FINE, "{0} is blocked", this);
blockedProjects.add(this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onEnterBlocked(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
/*package*/ boolean leave(Queue q) {
boolean r = blockedProjects.remove(this);
if (r) {
LOGGER.log(Level.FINE, "{0} no longer blocked", this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onLeaveBlocked(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
return r;
}
}
/**
* {@link Item} in the {@link Queue#buildables} stage.
*/
public final static class BuildableItem extends NotWaitingItem {
/**
* Set to true when this is added to the {@link Queue#pendings} list.
*/
private boolean isPending;
/**
* Reasons why the last call to {@link #maintain} left this buildable (but not blocked or executing).
* May be null but not empty.
*/
private transient volatile @CheckForNull List<CauseOfBlockage> transientCausesOfBlockage;
public BuildableItem(WaitingItem wi) {
super(wi);
}
public BuildableItem(NotWaitingItem ni) {
super(ni);
}
public CauseOfBlockage getCauseOfBlockage() {
Jenkins jenkins = Jenkins.getInstance();
if(isBlockedByShutdown(task))
return CauseOfBlockage.fromMessage(Messages._Queue_HudsonIsAboutToShutDown());
List<CauseOfBlockage> causesOfBlockage = transientCausesOfBlockage;
Label label = getAssignedLabel();
List<Node> allNodes = jenkins.getNodes();
if (allNodes.isEmpty())
label = null; // no master/agent. pointless to talk about nodes
if (label != null) {
Set<Node> nodes = label.getNodes();
if (label.isOffline()) {
if (nodes.size() != 1) return new BecauseLabelIsOffline(label);
else return new BecauseNodeIsOffline(nodes.iterator().next());
} else {
if (causesOfBlockage != null && label.getIdleExecutors() > 0) {
return new CompositeCauseOfBlockage(causesOfBlockage);
}
if (nodes.size() != 1) return new BecauseLabelIsBusy(label);
else return new BecauseNodeIsBusy(nodes.iterator().next());
}
} else if (causesOfBlockage != null && new ComputerSet().getIdleExecutors() > 0) {
return new CompositeCauseOfBlockage(causesOfBlockage);
} else {
return CauseOfBlockage.createNeedsMoreExecutor(Messages._Queue_WaitingForNextAvailableExecutor());
}
}
@Override
public boolean isStuck() {
Label label = getAssignedLabel();
if(label!=null && label.isOffline())
// no executor online to process this job. definitely stuck.
return true;
long d = task.getEstimatedDuration();
long elapsed = System.currentTimeMillis()-buildableStartMilliseconds;
if(d>=0) {
// if we were running elsewhere, we would have done this build ten times.
return elapsed > Math.max(d,60000L)*10;
} else {
// more than a day in the queue
return TimeUnit.MILLISECONDS.toHours(elapsed)>24;
}
}
@Exported
public boolean isPending() {
return isPending;
}
@Override
/*package*/ void enter(Queue q) {
q.buildables.add(this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onEnterBuildable(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
@Override
/*package*/ boolean leave(Queue q) {
boolean r = q.buildables.remove(this);
if (r) {
LOGGER.log(Level.FINE, "{0} no longer blocked", this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onLeaveBuildable(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
return r;
}
}
/**
* {@link Item} in the {@link Queue#leftItems} stage. These are items that had left the queue
* by either began executing or by getting cancelled.
*
* @since 1.519
*/
public final static class LeftItem extends Item {
public final WorkUnitContext outcome;
/**
* When item has left the queue and begin executing.
*/
public LeftItem(WorkUnitContext wuc) {
super(wuc.item);
this.outcome = wuc;
}
/**
* When item is cancelled.
*/
public LeftItem(Item cancelled) {
super(cancelled);
this.outcome = null;
}
@Override
public CauseOfBlockage getCauseOfBlockage() {
return null;
}
/**
* If this is representing an item that started executing, this property returns
* the primary executable (such as {@link AbstractBuild}) that created out of it.
*/
@Exported
public @CheckForNull Executable getExecutable() {
return outcome!=null ? outcome.getPrimaryWorkUnit().getExecutable() : null;
}
/**
* Is this representing a cancelled item?
*/
@Exported
public boolean isCancelled() {
return outcome==null;
}
@Override
void enter(Queue q) {
q.leftItems.put(getId(),this);
for (QueueListener ql : QueueListener.all()) {
try {
ql.onLeft(this);
} catch (Throwable e) {
// don't let this kill the queue
LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
}
}
}
@Override
boolean leave(Queue q) {
// there's no leave operation
return false;
}
}
private static final Logger LOGGER = Logger.getLogger(Queue.class.getName());
/**
* This {@link XStream} instance is used to persist {@link Task}s.
*/
public static final XStream XSTREAM = new XStream2();
static {
XSTREAM.registerConverter(new AbstractSingleValueConverter() {
@Override
@SuppressWarnings("unchecked")
public boolean canConvert(Class klazz) {
return hudson.model.Item.class.isAssignableFrom(klazz);
}
@Override
public Object fromString(String string) {
Object item = Jenkins.getInstance().getItemByFullName(string);
if(item==null) throw new NoSuchElementException("No such job exists: "+string);
return item;
}
@Override
public String toString(Object item) {
return ((hudson.model.Item) item).getFullName();
}
});
XSTREAM.registerConverter(new AbstractSingleValueConverter() {
@SuppressWarnings("unchecked")
@Override
public boolean canConvert(Class klazz) {
return Run.class.isAssignableFrom(klazz);
}
@Override
public Object fromString(String string) {
String[] split = string.split("#");
String projectName = split[0];
int buildNumber = Integer.parseInt(split[1]);
Job<?,?> job = (Job<?,?>) Jenkins.getInstance().getItemByFullName(projectName);
if(job==null) throw new NoSuchElementException("No such job exists: "+projectName);
Run<?,?> run = job.getBuildByNumber(buildNumber);
if(run==null) throw new NoSuchElementException("No such build: "+string);
return run;
}
@Override
public String toString(Object object) {
Run<?,?> run = (Run<?,?>) object;
return run.getParent().getFullName() + "#" + run.getNumber();
}
});
/**
* Reconnect every reference to {@link Queue} by the singleton.
*/
XSTREAM.registerConverter(new AbstractSingleValueConverter() {
@Override
public boolean canConvert(Class klazz) {
return Queue.class.isAssignableFrom(klazz);
}
@Override
public Object fromString(String string) {
return Jenkins.getInstance().getQueue();
}
@Override
public String toString(Object item) {
return "queue";
}
});
}
/**
* Regularly invokes {@link Queue#maintain()} and clean itself up when
* {@link Queue} gets GC-ed.
*/
private static class MaintainTask extends SafeTimerTask {
private final WeakReference<Queue> queue;
MaintainTask(Queue queue) {
this.queue = new WeakReference<Queue>(queue);
}
private void periodic() {
long interval = 5000;
Timer.get().scheduleWithFixedDelay(this, interval, interval, TimeUnit.MILLISECONDS);
}
protected void doRun() {
Queue q = queue.get();
if (q != null)
q.maintain();
else
cancel();
}
}
/**
* {@link ArrayList} of {@link Item} with more convenience methods.
*/
private class ItemList<T extends Item> extends ArrayList<T> {
public T get(Task task) {
for (T item: this) {
if (item.task.equals(task)) {
return item;
}
}
return null;
}
public List<T> getAll(Task task) {
List<T> result = new ArrayList<T>();
for (T item: this) {
if (item.task.equals(task)) {
result.add(item);
}
}
return result;
}
public boolean containsKey(Task task) {
return get(task) != null;
}
public T remove(Task task) {
Iterator<T> it = iterator();
while (it.hasNext()) {
T t = it.next();
if (t.task.equals(task)) {
it.remove();
return t;
}
}
return null;
}
public void put(Task task, T item) {
assert item.task.equals(task);
add(item);
}
public ItemList<T> values() {
return this;
}
/**
* Works like {@link #remove(Task)} but also marks the {@link Item} as cancelled.
*/
public T cancel(Task p) {
T x = get(p);
if(x!=null) x.cancel(Queue.this);
return x;
}
@SuppressFBWarnings(value = "IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD",
justification = "It will invoke the inherited clear() method according to Java semantics. "
+ "FindBugs recommends suppressing warnings in such case")
public void cancelAll() {
for (T t : new ArrayList<T>(this))
t.cancel(Queue.this);
clear();
}
}
private static class Snapshot {
private final Set<WaitingItem> waitingList;
private final List<BlockedItem> blockedProjects;
private final List<BuildableItem> buildables;
private final List<BuildableItem> pendings;
public Snapshot(Set<WaitingItem> waitingList, List<BlockedItem> blockedProjects, List<BuildableItem> buildables,
List<BuildableItem> pendings) {
this.waitingList = new LinkedHashSet<WaitingItem>(waitingList);
this.blockedProjects = new ArrayList<BlockedItem>(blockedProjects);
this.buildables = new ArrayList<BuildableItem>(buildables);
this.pendings = new ArrayList<BuildableItem>(pendings);
}
@Override
public String toString() {
return "Queue.Snapshot{waitingList=" + waitingList + ";blockedProjects=" + blockedProjects + ";buildables=" + buildables + ";pendings=" + pendings + "}";
}
}
private static class LockedRunnable implements Runnable {
private final Runnable delegate;
private LockedRunnable(Runnable delegate) {
this.delegate = delegate;
}
@Override
public void run() {
withLock(delegate);
}
}
private class BuildableRunnable implements Runnable {
private final BuildableItem buildableItem;
private BuildableRunnable(BuildableItem p) {
this.buildableItem = p;
}
@Override
public void run() {
//the flyweighttask enters the buildables queue and will ask Jenkins to provision a node
buildableItem.enter(Queue.this);
}
}
private static class LockedJUCCallable<V> implements java.util.concurrent.Callable<V> {
private final java.util.concurrent.Callable<V> delegate;
private LockedJUCCallable(java.util.concurrent.Callable<V> delegate) {
this.delegate = delegate;
}
@Override
public V call() throws Exception {
return withLock(delegate);
}
}
private static class LockedHRCallable<V,T extends Throwable> implements hudson.remoting.Callable<V,T> {
private static final long serialVersionUID = 1L;
private final hudson.remoting.Callable<V,T> delegate;
private LockedHRCallable(hudson.remoting.Callable<V,T> delegate) {
this.delegate = delegate;
}
@Override
public V call() throws T {
return withLock(delegate);
}
@Override
public void checkRoles(RoleChecker checker) throws SecurityException {
delegate.checkRoles(checker);
}
}
@CLIResolver
public static Queue getInstance() {
return Jenkins.getInstance().getQueue();
}
/**
* Restores the queue content during the start up.
*/
@Initializer(after=JOB_LOADED)
public static void init(Jenkins h) {
h.getQueue().load();
}
}
| tfennelly/jenkins | core/src/main/java/hudson/model/Queue.java | Java | mit | 108,599 |
require "action_controller"
Mime::Type.register "application/pdf", :pdf
require "prawn"
ActionController::Renderers.add :pdf do |filename, options|
pdf = Prawn::Document.new
pdf.text render_to_string options
send_data pdf.render, :filename => "#{filename}.pdf",
:type => "application/pdf", :disposition => "attachment"
end
module PdfRenderer
end
| travisjeffery/pdf_renderer | lib/pdf_renderer.rb | Ruby | mit | 361 |
describe('modelAndOptionMapping', function() {
var utHelper = window.utHelper;
var testCase = utHelper.prepare([
'echarts/src/component/grid',
'echarts/src/chart/line',
'echarts/src/chart/pie',
'echarts/src/chart/bar',
'echarts/src/component/toolbox',
'echarts/src/component/dataZoom'
]);
function getData0(chart, seriesIndex) {
return getSeries(chart, seriesIndex).getData().get('y', 0);
}
function getSeries(chart, seriesIndex) {
return chart.getModel().getComponent('series', seriesIndex);
}
function getModel(chart, type, index) {
return chart.getModel().getComponent(type, index);
}
function countSeries(chart) {
return countModel(chart, 'series');
}
function countModel(chart, type) {
// FIXME
// access private
return chart.getModel()._componentsMap.get(type).length;
}
function getChartView(chart, series) {
return chart._chartsMap[series.__viewId];
}
function countChartViews(chart) {
return chart._chartsViews.length;
}
function saveOrigins(chart) {
var count = countSeries(chart);
var origins = [];
for (var i = 0; i < count; i++) {
var series = getSeries(chart, i);
origins.push({
model: series,
view: getChartView(chart, series)
});
}
return origins;
}
function modelEqualsToOrigin(chart, idxList, origins, boolResult) {
for (var i = 0; i < idxList.length; i++) {
var idx = idxList[i];
expect(origins[idx].model === getSeries(chart, idx)).toEqual(boolResult);
}
}
function viewEqualsToOrigin(chart, idxList, origins, boolResult) {
for (var i = 0; i < idxList.length; i++) {
var idx = idxList[i];
expect(
origins[idx].view === getChartView(chart, getSeries(chart, idx))
).toEqual(boolResult);
}
}
describe('idNoNameNo', function () {
testCase.createChart()('sameTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
// Not merge
var origins = saveOrigins(chart);
chart.setOption(option, true);
expect(countChartViews(chart)).toEqual(3);
expect(countSeries(chart)).toEqual(3);
modelEqualsToOrigin(chart, [0, 1, 2], origins, false);
viewEqualsToOrigin(chart, [0, 1, 2], origins, true);
});
testCase.createChart()('sameTypeMergeFull', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
// Merge
var origins = saveOrigins(chart);
chart.setOption({
series: [
{type: 'line', data: [111]},
{type: 'line', data: [222]},
{type: 'line', data: [333]}
]
});
expect(countSeries(chart)).toEqual(3);
expect(countChartViews(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(111);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(333);
viewEqualsToOrigin(chart, [0, 1, 2], origins, true);
modelEqualsToOrigin(chart, [0, 1, 2], origins, true);
});
testCase.createChart()('sameTypeMergePartial', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
// Merge
var origins = saveOrigins(chart);
chart.setOption({
series: [
{data: [22222]}
]
});
expect(countSeries(chart)).toEqual(3);
expect(countChartViews(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(22222);
expect(getData0(chart, 1)).toEqual(22);
expect(getData0(chart, 2)).toEqual(33);
viewEqualsToOrigin(chart, [0, 1, 2], origins, true);
modelEqualsToOrigin(chart, [0, 1, 2], origins, true);
});
testCase.createChart()('differentTypeMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
// Merge
var origins = saveOrigins(chart);
chart.setOption({
series: [
{type: 'line', data: [111]},
{type: 'bar', data: [222]},
{type: 'line', data: [333]}
]
});
expect(countSeries(chart)).toEqual(3);
expect(countChartViews(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(111);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(333);
expect(getSeries(chart, 1).type === 'series.bar').toEqual(true);
modelEqualsToOrigin(chart, [0, 2], origins, true);
modelEqualsToOrigin(chart, [1], origins, false);
viewEqualsToOrigin(chart, [0, 2], origins, true);
viewEqualsToOrigin(chart, [1], origins, false);
});
});
describe('idSpecified', function () {
testCase.createChart()('sameTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33], id: 30},
{type: 'line', data: [44]},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
expect(countSeries(chart)).toEqual(5);
expect(countChartViews(chart)).toEqual(5);
expect(getData0(chart, 0)).toEqual(11);
expect(getData0(chart, 1)).toEqual(22);
expect(getData0(chart, 2)).toEqual(33);
expect(getData0(chart, 3)).toEqual(44);
expect(getData0(chart, 4)).toEqual(55);
var origins = saveOrigins(chart);
chart.setOption(option, true);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, false);
viewEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
});
testCase.createChart()('sameTypeMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33], id: 30},
{type: 'line', data: [44]},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
chart.setOption(option);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
viewEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
});
testCase.createChart()('differentTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33], id: 30},
{type: 'line', data: [44]},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'bar', data: [22], id: 20},
{type: 'line', data: [33], id: 30},
{type: 'bar', data: [44]},
{type: 'line', data: [55]}
]
};
chart.setOption(option2, true);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, false);
viewEqualsToOrigin(chart, [0, 2, 4], origins, true);
viewEqualsToOrigin(chart, [1, 3], origins, false);
});
testCase.createChart()('differentTypeMergeFull', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33], id: 30, name: 'a'},
{type: 'line', data: [44]},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
series: [
{type: 'line', data: [11]},
{type: 'bar', data: [22], id: 20, name: 'a'},
{type: 'line', data: [33], id: 30},
{type: 'bar', data: [44]},
{type: 'line', data: [55]}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 2, 4], origins, true);
modelEqualsToOrigin(chart, [1, 3], origins, false);
viewEqualsToOrigin(chart, [0, 2, 4], origins, true);
viewEqualsToOrigin(chart, [1, 3], origins, false);
});
testCase.createChart()('differentTypeMergePartial1', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20},
{type: 'line', data: [33]},
{type: 'line', data: [44], id: 40},
{type: 'line', data: [55]}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
series: [
{type: 'bar', data: [444], id: 40},
{type: 'line', data: [333]},
{type: 'line', data: [222], id: 20}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
expect(getData0(chart, 0)).toEqual(333);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(33);
expect(getData0(chart, 3)).toEqual(444);
expect(getData0(chart, 4)).toEqual(55);
modelEqualsToOrigin(chart, [0, 1, 2, 4], origins, true);
modelEqualsToOrigin(chart, [3], origins, false);
viewEqualsToOrigin(chart, [0, 1, 2, 4], origins, true);
viewEqualsToOrigin(chart, [3], origins, false);
});
testCase.createChart()('differentTypeMergePartial2', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], id: 20}
]
};
var chart = this.chart;
chart.setOption(option);
var option2 = {
series: [
{type: 'bar', data: [444], id: 40},
{type: 'line', data: [333]},
{type: 'line', data: [222], id: 20},
{type: 'line', data: [111]}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(4);
expect(countSeries(chart)).toEqual(4);
expect(getData0(chart, 0)).toEqual(333);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(444);
expect(getData0(chart, 3)).toEqual(111);
});
testCase.createChart()('mergePartialDoNotMapToOtherId', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11], id: 10},
{type: 'line', data: [22], id: 20}
]
};
var chart = this.chart;
chart.setOption(option);
var option2 = {
series: [
{type: 'bar', data: [444], id: 40}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(3);
expect(countSeries(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(11);
expect(getData0(chart, 1)).toEqual(22);
expect(getData0(chart, 2)).toEqual(444);
});
testCase.createChart()('idDuplicate', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11], id: 10},
{type: 'line', data: [22], id: 10}
]
};
var chart = this.chart;
expect(function () {
chart.setOption(option);
}).toThrowError(/duplicate/);
});
testCase.createChart()('nameTheSameButIdNotTheSame', function () {
var chart = this.chart;
var option = {
grid: {},
xAxis: [
{id: 'x1', name: 'a', xxxx: 'x1_a'},
{id: 'x2', name: 'b', xxxx: 'x2_b'}
],
yAxis: {}
};
chart.setOption(option);
var xAxisModel0 = getModel(chart, 'xAxis', 0);
var xAxisModel1 = getModel(chart, 'xAxis', 1);
expect(xAxisModel0.option.xxxx).toEqual('x1_a');
expect(xAxisModel1.option.xxxx).toEqual('x2_b');
expect(xAxisModel1.option.name).toEqual('b');
var option2 = {
xAxis: [
{id: 'k1', name: 'a', xxxx: 'k1_a'},
{id: 'x2', name: 'a', xxxx: 'x2_a'}
]
};
chart.setOption(option2);
var xAxisModel0 = getModel(chart, 'xAxis', 0);
var xAxisModel1 = getModel(chart, 'xAxis', 1);
var xAxisModel2 = getModel(chart, 'xAxis', 2);
expect(xAxisModel0.option.xxxx).toEqual('x1_a');
expect(xAxisModel1.option.xxxx).toEqual('x2_a');
expect(xAxisModel1.option.name).toEqual('a');
expect(xAxisModel2.option.xxxx).toEqual('k1_a');
});
});
describe('noIdButNameExists', function () {
testCase.createChart()('sameTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'},
{type: 'line', data: [33], name: 'b'},
{type: 'line', data: [44]},
{type: 'line', data: [55], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
expect(getSeries(chart, 1)).not.toEqual(getSeries(chart, 4));
expect(countSeries(chart)).toEqual(5);
expect(countChartViews(chart)).toEqual(5);
expect(getData0(chart, 0)).toEqual(11);
expect(getData0(chart, 1)).toEqual(22);
expect(getData0(chart, 2)).toEqual(33);
expect(getData0(chart, 3)).toEqual(44);
expect(getData0(chart, 4)).toEqual(55);
var origins = saveOrigins(chart);
chart.setOption(option, true);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, false);
viewEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
});
testCase.createChart()('sameTypeMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'},
{type: 'line', data: [33], name: 'b'},
{type: 'line', data: [44]},
{type: 'line', data: [55], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
chart.setOption(option);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
viewEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, true);
});
testCase.createChart()('differentTypeNotMerge', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'},
{type: 'line', data: [33], name: 'b'},
{type: 'line', data: [44]},
{type: 'line', data: [55], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'bar', data: [22], name: 'a'},
{type: 'line', data: [33], name: 'b'},
{type: 'bar', data: [44]},
{type: 'line', data: [55], name: 'a'}
]
};
chart.setOption(option2, true);
expect(countChartViews(chart)).toEqual(5);
expect(countSeries(chart)).toEqual(5);
modelEqualsToOrigin(chart, [0, 1, 2, 3, 4], origins, false);
viewEqualsToOrigin(chart, [0, 2, 4], origins, true);
viewEqualsToOrigin(chart, [1, 3], origins, false);
});
testCase.createChart()('differentTypeMergePartialOneMapTwo', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'},
{type: 'line', data: [33]},
{type: 'line', data: [44], name: 'b'},
{type: 'line', data: [55], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
var origins = saveOrigins(chart);
var option2 = {
series: [
{type: 'bar', data: [444], id: 40},
{type: 'line', data: [333]},
{type: 'bar', data: [222], name: 'a'}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(6);
expect(countSeries(chart)).toEqual(6);
expect(getData0(chart, 0)).toEqual(333);
expect(getData0(chart, 1)).toEqual(222);
expect(getData0(chart, 2)).toEqual(33);
expect(getData0(chart, 3)).toEqual(44);
expect(getData0(chart, 4)).toEqual(55);
expect(getData0(chart, 5)).toEqual(444);
modelEqualsToOrigin(chart, [0, 2, 3, 4], origins, true);
modelEqualsToOrigin(chart, [1], origins, false);
viewEqualsToOrigin(chart, [0, 2, 3, 4], origins, true);
viewEqualsToOrigin(chart, [1], origins, false);
});
testCase.createChart()('differentTypeMergePartialTwoMapOne', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22], name: 'a'}
]
};
var chart = this.chart;
chart.setOption(option);
var option2 = {
series: [
{type: 'bar', data: [444], name: 'a'},
{type: 'line', data: [333]},
{type: 'line', data: [222], name: 'a'},
{type: 'line', data: [111]}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(4);
expect(countSeries(chart)).toEqual(4);
expect(getData0(chart, 0)).toEqual(333);
expect(getData0(chart, 1)).toEqual(444);
expect(getData0(chart, 2)).toEqual(222);
expect(getData0(chart, 3)).toEqual(111);
});
testCase.createChart()('mergePartialCanMapToOtherName', function () {
// Consider case: axis.name = 'some label', which can be overwritten.
var option = {
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11], name: 10},
{type: 'line', data: [22], name: 20}
]
};
var chart = this.chart;
chart.setOption(option);
var option2 = {
series: [
{type: 'bar', data: [444], name: 40},
{type: 'bar', data: [999], name: 40},
{type: 'bar', data: [777], id: 70}
]
};
chart.setOption(option2);
expect(countChartViews(chart)).toEqual(3);
expect(countSeries(chart)).toEqual(3);
expect(getData0(chart, 0)).toEqual(444);
expect(getData0(chart, 1)).toEqual(999);
expect(getData0(chart, 2)).toEqual(777);
});
});
describe('ohters', function () {
testCase.createChart()('aBugCase', function () {
var option = {
series: [
{
type:'pie',
radius: ['20%', '25%'],
center:['20%', '20%'],
avoidLabelOverlap: true,
hoverAnimation :false,
label: {
normal: {
show: true,
position: 'center',
textStyle: {
fontSize: '30',
fontWeight: 'bold'
}
},
emphasis: {
show: true
}
},
data:[
{value:135, name:'视频广告'},
{value:1548}
]
}
]
};
var chart = this.chart;
chart.setOption(option);
chart.setOption({
series: [
{
type:'pie',
radius: ['20%', '25%'],
center: ['20%', '20%'],
avoidLabelOverlap: true,
hoverAnimation: false,
label: {
normal: {
show: true,
position: 'center',
textStyle: {
fontSize: '30',
fontWeight: 'bold'
}
}
},
data: [
{value:135, name:'视频广告'},
{value:1548}
]
},
{
type:'pie',
radius: ['20%', '25%'],
center: ['60%', '20%'],
avoidLabelOverlap: true,
hoverAnimation: false,
label: {
normal: {
show: true,
position: 'center',
textStyle: {
fontSize: '30',
fontWeight: 'bold'
}
}
},
data: [
{value:135, name:'视频广告'},
{value:1548}
]
}
]
}, true);
expect(countChartViews(chart)).toEqual(2);
expect(countSeries(chart)).toEqual(2);
});
testCase.createChart()('color', function () {
var option = {
backgroundColor: 'rgba(1,1,1,1)',
xAxis: {data: ['a']},
yAxis: {},
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]},
{type: 'line', data: [33]}
]
};
var chart = this.chart;
chart.setOption(option);
expect(chart._model.option.backgroundColor).toEqual('rgba(1,1,1,1)');
// Not merge
chart.setOption({
backgroundColor: '#fff'
}, true);
expect(chart._model.option.backgroundColor).toEqual('#fff');
});
testCase.createChart()('innerId', function () {
var option = {
xAxis: {data: ['a']},
yAxis: {},
toolbox: {
feature: {
dataZoom: {}
}
},
dataZoom: [
{type: 'inside', id: 'a'},
{type: 'slider', id: 'b'}
],
series: [
{type: 'line', data: [11]},
{type: 'line', data: [22]}
]
};
var chart = this.chart;
chart.setOption(option);
expect(countModel(chart, 'dataZoom')).toEqual(4);
expect(getModel(chart, 'dataZoom', 0).id).toEqual('a');
expect(getModel(chart, 'dataZoom', 1).id).toEqual('b');
// Merge
chart.setOption({
dataZoom: [
{type: 'slider', id: 'c'},
{type: 'slider', name: 'x'}
]
});
expect(countModel(chart, 'dataZoom')).toEqual(5);
expect(getModel(chart, 'dataZoom', 0).id).toEqual('a');
expect(getModel(chart, 'dataZoom', 1).id).toEqual('b');
expect(getModel(chart, 'dataZoom', 4).id).toEqual('c');
});
});
});
| ka215/WP-Gentelella | vendors/echarts/test/ut/spec/model/Global.js | JavaScript | mit | 29,436 |