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 |
|---|---|---|---|---|---|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SimpleUse.Net46WithSimpleInjector")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a49e5d94-8929-4134-837b-443b89698229")]
| solr-express/solr-express | sample/SimpleUse.Net46WithSimpleInjector/Properties/AssemblyInfo.cs | C# | mit | 806 |
package org.lff.plugin.dupfinder;
import org.lff.plugin.dupfinder.vo.SourceVO;
import javax.swing.table.AbstractTableModel;
import java.util.*;
/**
* @author Feifei Liu
* @datetime Jul 10 2017 13:54
*/
public class DuplicatesTableModel extends AbstractTableModel {
static final String[] NAMES = new String[]{"Type", "Module", "Library"};
private static final long serialVersionUID = 2834765790738917135L;
private List<Map<Integer, String>> data = new LinkedList<>();
private Map<String, Set<SourceVO>> duplicates = new HashMap<>();
@Override
public String getColumnName(int column) {
return NAMES[column];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Map<Integer, String> rowData = data.get(rowIndex);
return rowData.get(columnIndex);
}
public void add(SourceVO vo) {
Map<Integer, String> rowData = new HashMap<>();
rowData.put(0, vo.getLibrary());
rowData.put(1, vo.getModule());
rowData.put(2, vo.getUrl());
data.add(rowData);
int index0 = data.size() - 1;
int index1 = index0;
this.fireTableRowsInserted(index0, index1);
}
public void setDependents(String fullName, Set<SourceVO> dependents) {
duplicates.put(fullName, dependents);
}
public void clear() {
int index1 = data.size()-1;
data.clear();
if (index1 >= 0) {
fireTableRowsDeleted(0, index1);
}
}
public void show(String fullname) {
Set<SourceVO> list = duplicates.get(fullname);
for (SourceVO vo : list) {
this.add(vo);
}
}
}
| lff0305/duplicateClassFinder | src/org/lff/plugin/dupfinder/DuplicatesTableModel.java | Java | mit | 1,932 |
using OmniConf.Core.Interfaces;
namespace OmniConf.Web
{
public class SiteSettings : ISiteSettings
{
public int SiteConferenceId { get; set; }
}
}
| ardalis/OmniConf | src/OmniConf.Web/SiteSettings.cs | C# | mit | 171 |
// Simple JavaScript Templating
// Heavily based on: John Resig - http://ejohn.org/blog/javascript-micro-templating/
var argName = 'data';
function getFuncBody(str) {
return argName+"="+argName+"||{};var p=[];p.push('"
+ str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');return p.join('');";
}
function mtmpl(str,data) {
var fn = new Function(argName,getFuncBody(str));
return data ? fn(data) : fn;
}
function precompile(str) {
return "function("+argName+"){"+getFuncBody(str)+"}";
}
module.exports = {
mtmpl:mtmpl,
precompile:precompile
}; | theakman2/node-modules-mtmpl | lib/index.js | JavaScript | mit | 756 |
<?php
/**
* Created by PhpStorm.
* Author: Misha Serenkov
* Email: mi.serenkov@gmail.com
* Date: 30.11.2016 11:39
*/
namespace miserenkov\sms\client;
use miserenkov\sms\exceptions\BalanceException;
use miserenkov\sms\exceptions\Exception;
use miserenkov\sms\exceptions\SendException;
use miserenkov\sms\exceptions\StatusException;
use yii\base\InvalidConfigException;
class SoapClient extends \SoapClient implements ClientInterface
{
/**
* @var string
*/
private $_login = null;
/**
* @var string
*/
private $_password = null;
/**
* @var null|string
*/
private $_senderName = null;
/**
* @var bool
*/
private $_throwExceptions = false;
/**
* @inheritdoc
*/
public function __construct($gateway, $login, $password, $senderName, $options = [])
{
$https = true;
$this->_login = $login;
$this->_password = $password;
$this->_senderName = $senderName;
if (isset($options['throwExceptions'])) {
$this->_throwExceptions = $options['throwExceptions'];
}
if (isset($options['useHttps']) && is_bool($options['useHttps'])) {
$https = $options['useHttps'];
}
parent::__construct($this->getWsdl($gateway, $https), []);
}
private function getWsdl($gateway, $useHttps = true)
{
$httpsWsdl = 'https://' . $gateway . '/sys/soap.php?wsdl';
$httpWsdl = 'http://' . $gateway . '/sys/soap.php?wsdl';
if ($useHttps) {
$ch = curl_init($httpsWsdl);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$errorCode = curl_errno($ch);
curl_close($ch);
if ($errorCode === CURLE_OK && $httpCode === 200) {
return $httpsWsdl;
}
\Yii::warning("Gateway \"$gateway\" doesn't support https connections. Will use http", self::class);
if ($this->_throwExceptions) {
throw new InvalidConfigException("Gateway \"$gateway\" doesn't support https connections. Will use http");
}
}
return $httpWsdl;
}
/**
* @inheritdoc
*/
public function getBalance()
{
$response = $this->get_balance([
'login' => $this->_login,
'psw' => $this->_password,
]);
if ($response->balanceresult->error == BalanceException::NO_ERROR) {
$balance = (double)$response->balanceresult->balance;
if (round($balance) == 0) {
\Yii::warning(BalanceException::getErrorString(BalanceException::ERROR_NOT_MONEY), self::class);
if ($this->_throwExceptions) {
throw new BalanceException(BalanceException::ERROR_NOT_MONEY);
}
}
return $balance;
} else {
\Yii::error(BalanceException::getErrorString((int) $response->balanceresult->error), self::class);
if ($this->_throwExceptions) {
throw new BalanceException((int) $response->balanceresult->error);
}
return false;
}
}
/**
* @inheritdoc
*/
public function sendMessage(array $params)
{
$query = [
'login' => $this->_login,
'psw' => $this->_password,
'sender' => $this->_senderName,
];
if (isset($params['phones']) && isset($params['message'])) {
if (!isset($params['tinyurl']) || ($params['tinyurl'] != 0 && $params['tinyurl'] != 1)) {
$query['tinyurl'] = 1;
} else {
$query['tinyurl'] = $params['tinyurl'];
}
if (is_array($params['phones'])) {
$query['phones'] = implode(';', $params['phones']);
} else {
$query['phones'] = $params['phones'];
}
$query['mes'] = $params['message'];
$query['id'] = $params['id'];
$response = $this->send_sms($query);
$response = (array) $response->sendresult;
if (!isset($response['error']) || $response['error'] === '0') {
return ['id' => $response['id']];
} else {
\Yii::error(SendException::getErrorString((int) $response['error']), self::class);
if ($this->_throwExceptions) {
throw new SendException((int) $response['error']);
}
return ['error' => $response['error']];
}
}
return false;
}
/**
* @inheritdoc
*/
public function getMessageStatus($id, $phone, $all = 2)
{
$response = $this->get_status([
'login' => $this->_login,
'psw' => $this->_password,
'phone' => $phone,
'id' => $id,
'all' => $all,
]);
$response = (array) $response->statusresult;
if (count($response) > 0) {
if ((int) $response['error'] !== StatusException::NO_ERROR) {
\Yii::error(SendException::getErrorString((int) $response['error']), self::class);
if ($this->_throwExceptions) {
throw new StatusException((int) $response['error']);
}
return false;
}
return [
'status' => (int) $response['status'],
'status_message' => $this->getSendStatus((int) $response['status']),
'err' => (int) $response['err'],
'err_message' => $this->getSendStatusError((int) $response['err']),
'send_time' => (int) $response['send_timestamp'],
'cost' => (float) $response['cost'],
'operator' => $response['operator'],
'region' => $response['region'],
];
} else {
\Yii::error(Exception::getErrorString(Exception::EMPTY_RESPONSE), self::class);
if ($this->_throwExceptions) {
throw new Exception(Exception::EMPTY_RESPONSE);
}
return false;
}
}
private function getSendStatus($code)
{
$codes = [
-3 => 'The message is not found',
-1 => 'Waiting to be sent',
0 => 'Transferred to the operator',
1 => 'Delivered',
3 => 'Expired',
20 => 'It is impossible to deliver',
22 => 'Wrong number',
23 => 'Prohibited',
24 => 'Insufficient funds',
25 => 'Unavailable number',
];
if (isset($codes[$code])) {
return $codes[$code];
} else {
return 'Unknown status';
}
}
private function getSendStatusError($error)
{
$errors = [
0 => 'There are no errors',
1 => 'The subscriber does not exist',
6 => 'The subscriber is not online',
11 => 'No SMS',
13 => 'The subscriber is blocked',
21 => 'There is no support for SMS',
200 => 'Virtual dispatch',
220 => 'Queue overflowed from the operator',
240 => 'Subscriber is busy',
241 => 'Error converting audio',
242 => 'Recorded answering machine',
243 => 'Not a contract',
244 => 'Distribution is prohibited',
245 => 'Status is not received',
246 => 'A time limit',
247 => 'Limit exceeded messages',
248 => 'There is no route',
249 => 'Invalid number format',
250 => 'The phone number of prohibited settings',
251 => 'Limit is exceeded on a single number',
252 => 'Phone number is prohibited',
253 => 'Prohibited spam filter',
254 => 'Unregistered sender id',
255 => 'Rejected by the operator',
];
if (isset($errors[$error])) {
return $errors[$error];
} else {
return 'Unknown error';
}
}
}
| miserenkov/yii2-sms | src/client/SoapClient.php | PHP | mit | 8,357 |
/*
Edison is designed to be simpler and more performant unit/integration testing framework.
Copyright (c) 2015, Matthew Kelly (Badgerati)
Company: Cadaeic Studios
License: MIT (see LICENSE for details)
*/
using System;
namespace Edison.Engine.Core.Exceptions
{
public class ParseException : Exception
{
public ParseException(string message)
: base(message) { }
}
}
| Badgerati/Edison | Edison.Engine/Core/Exceptions/ParseException.cs | C# | mit | 406 |
module Bondora
VERSION = "0.2.0"
end
| cschritt/bondora | lib/bondora/version.rb | Ruby | mit | 39 |
<?php
namespace MN\PlayerBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('mn_player');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| mark-newman/footy | src/MN/PlayerBundle/DependencyInjection/Configuration.php | PHP | mit | 873 |
#ifndef __tcode_byte_buffer_h__
#define __tcode_byte_buffer_h__
#include <tcode/block.hpp>
namespace tcode {
/*!
@class byte_buffer
@brief memory block Á¶ÀÛ °ü·Ã ÀÎÅÍÆäÀ̽º
@author tk
@detail ¸î¸î ÀÎÅÍÆäÀ̽º ( rd_ptr / wr_ptr / etc ) µîÀº ACE message_block µî¿¡¼ ÂüÁ¶\n
³»°¡ »ç¿ëÇÏ±â ÆíÇϵµ·Ï Á¤¸®ÇÑ class\n
³»ºÎ ¹öÆÛ´Â block ÇÒ´çÀÚ ±¸ÇöÀ» ÀÌ¿ë\n
µû¶ó¼ refrenceCounting À¸·Î µ¿ÀÛÇÑ´Ù.
*/
class byte_buffer {
public:
//! buffer ÀÇ ÇöÀç Á¶ÀÛ À§Ä¡ Á¤º¸ tell / seek À¸·Î Á¶ÀÛ
struct position {
public:
position( void );
position( const position& rhs );
position operator=( const position& rhs );
void set( std::size_t r , std::size_t w);
void swap( position& pos );
public:
std::size_t read;
std::size_t write;
};
byte_buffer( void );
//! sz ¸¸ÅÀÇ ¹öÆÛ ÇÒ´ç
explicit byte_buffer( const std::size_t sz );
//! len ¸¸ÅÀÇ ¹öÆÛ ÇÒ´çÈÄ buf ÀÇ ³»¿ëÀ» internal buffer·Î º¹»ç ó¸®
byte_buffer( uint8_t* buf , const std::size_t len );
byte_buffer( const byte_buffer& rhs );
byte_buffer( byte_buffer&& rhs );
byte_buffer& operator=( const byte_buffer& rhs );
byte_buffer& operator=( byte_buffer&& rhs );
~byte_buffer( void );
void swap( byte_buffer& rhs );
// buffer size
std::size_t capacity( void ) const;
// writable pointer
uint8_t* wr_ptr( void );
int wr_ptr( const int move );
// readable pointer
uint8_t* rd_ptr( void );
int rd_ptr( const int move );
//! fit data
int fit( void );
//! fit data & fit buffer
int shrink_to_fit( void );
//! data size
std::size_t length( void );
//! writable size
std::size_t space( void );
//! data clear
void clear( void );
//! capacity reserve
void reserve( const int sz ) ;
std::size_t read(void* dst , const std::size_t sz );
std::size_t peak(void* dst , const std::size_t sz );
std::size_t write( void* src , const std::size_t sz );
position tell( void ) const;
void seek( const position& p );
std::size_t write_msg( const char* msg );
std::size_t write_msg( const wchar_t* msg );
std::size_t write_fmt( const char* msg , ... );
tcode::byte_buffer sub_buffer( const std::size_t start , const std::size_t len );
//! shallow copy
tcode::byte_buffer duplicate(void);
//! deep copy
tcode::byte_buffer copy(void);
private:
byte_buffer( block::handle handle , const position& pos );
private:
block::handle _block;
position _pos;
};
/*!
@brief POD serialization
*/
template < typename Object >
byte_buffer& operator<<( byte_buffer& buf , const Object& obj ) {
buf.write( const_cast<Object*>( &obj ), sizeof( obj ));
return buf;
}
/*!
@brief POD data deserialization
*/
template < typename Object >
byte_buffer& operator>>( byte_buffer& buf , Object& obj ) {
buf.read( &obj , sizeof( obj ));
return buf;
}
}
#endif
| aoziczero/tcode | include/tcode/byte_buffer.hpp | C++ | mit | 2,754 |
<?php
namespace FromSelect\ServiceProvider;
use FromSelect\Controller\ControllerDecorator;
use FromSelect\DecoratingCallableResolver;
use FromSelect\FromSelect;
class RouteServiceProvider implements ServiceProviderInterface
{
/**
* Provides routes for application.
*
* @param FromSelect $app
*/
public function provide(FromSelect $app)
{
require dirname(dirname(__DIR__)).'/resources/routes.php';
$app->getContainer()['callableResolver'] = function ($c) {
$decorator = new ControllerDecorator($c['view'], $c['router']);
return new DecoratingCallableResolver($c, $decorator);
};
}
}
| Albert221/FromSelect | src/ServiceProvider/RouteServiceProvider.php | PHP | mit | 671 |
<main>
<div class="container1">
<div id="liste" class="row z-depth-1" style="margin-bottom: 80px">
<div class="col s12">
<h2 class="header">Liste des OPR <a href="#importer" class="modal-trigger waves-effect waves-light btn blue">Importer</a> </h2>
<div class="row input-field">
<label for="recherche" class="grey-text">Recherche</label>
<input id="recherche" type="text" class="search col s3" style="margin: 0">
<a href="<?php echo base_url()?>c_parametre/rechercher/opr" style="font-size: 13px;"> <i class="material-icons left" style="margin-right: 3px;font-size: 20px">search</i> Recherche avancée</a>
</div>
<table class="bordered striped">
<thead>
<tr>
<th>Code</th>
<th>Nom</th>
<th>Filières développées</th>
<th>Statut juridique</th>
<th>Formelle</th>
<th>Representant</th>
<th width="10%">Option</th>
</tr>
</thead>
<tbody class="list">
<?php foreach($oprListe as $opr) { ?>
<tr>
<td class="codeOpr"><a href="<?php echo base_url()?>c_parametre/fiche_op/opr/<?php echo $opr->ID_OPR ?>"><?php echo $opr->CODE_OPR ?></a></td>
<td class="nomOpr"><?php echo $opr->NOM_OPR ?></td>
<td class="filiere"><?php echo $opr->FILIERES ?></td>
<td><?php echo $opr->STATUT ?></td>
<td><?php if($opr->FORMELLE == 1) echo 'OUI'; else echo 'NON' ?></td>
<td class="representant"><?php echo $opr->REPRESENTANT ?></td>
<td>
<a href="<?php echo base_url()?>c_parametre/edit_op/opr/<?php echo $opr->ID_OPR ?>" class="waves-effect waves-light green btn edit" data-id="<?php echo $opr->ID_OPR ?>"><i class="material-icons">edit</i></a>
<a href="#delete_opr" class="modal-trigger waves-effect waves-light red btn delete" data-id="<?php echo $opr->ID_OPR ?>"><i class="material-icons">delete</i></a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<div id="pagination">
<p class="left"><b>Total: <?php echo $oprTotal?></b></p>
</div>
<div class="fixed-action-btn">
<a href="<?php echo base_url(); ?>c_parametre/ajout_opr" class="btn-floating btn-large red">
<i class="large material-icons">add</i>
</a>
</div>
</div>
</div>
</div>
<!-- Modal import opr -->
<div id="importer" class="modal" style="width: 50%">
<form method="post" action="<?php echo base_url(); ?>c_parametre/importer_opr" enctype="multipart/form-data">
<div class="modal-content center-align">
<h5 class="green-text"> Importer OPR (CSV)</h5>
<div class="divider"></div>
<div class="file-field input-field">
<div class="btn blue">
<span>File</span>
<input type="file" name="csv">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</div>
<div class="modal-footer" style="width: 100% !important;">
<button type="button" class="modal-action modal-close red waves-effect waves-light btn">Fermer</button>
<button type="submit" class="waves-effect green waves-light btn">Importer</button>
</div>
</form>
</div>
<!-- Modal delete opr -->
<div id="delete_opr" class="modal" style="width: 25%">
<form method="post" action="<?php echo base_url(); ?>c_parametre/delete_opr" >
<div class="modal-content center-align">
<h5 class="red-text"> Supprimer OPR ?</h5>
<div class="divider"></div>
<input id="id_opr" type="hidden" name="id_opr">
</div>
<div class="modal-footer center-align" style="width: 100%!important;">
<button type="submit" class="waves-effect green waves-light btn" style="float: none">Supprimer</button>
<button type="button" class="modal-action modal-close red waves-effect waves-light btn" style="float: none">Fermer</button>
</div>
</form>
</div>
</main>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/init.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/list.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize-pagination.js"></script>
<script type="text/javascript">
var li = $('a[href="http://localhost/aropa/c_parametre/liste_opr"]').parent();
li.addClass("active");
console.log(window.location.href);
var parentLi = li.parents("li");
parentLi.addClass("active");
$(parentLi).children().first().addClass("active");
$(document).ready(function(){
var options = {
valueNames: [ 'codeOpr', 'nomOpr', 'filiere', 'representant' ]
};
var opbListe = new List('liste', options);
$('#pagination').materializePagination({
align: 'right',
lastPage: <?php echo $oprTotal/20 +1 ?>,
firstPage: 1,
urlParameter: 'page',
useUrlParameter: true,
onClickCallback: function(requestedPage){
window.location.replace('<?php echo base_url() ?>c_parametre/liste_opr?page='+requestedPage);
}
});
$('.pagination').removeClass('right-align');
$('.pagination').addClass('right');
});
$(document).on('click', '.delete', function () {
var id_opr = $(this).attr('data-id');
$('#id_opr').val(id_opr);
});
</script> | raoultahin/aropa | application/views/liste_opr.php | PHP | mit | 6,593 |
using Medallion.Threading.Internal;
using Medallion.Threading.Redis.RedLock;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Medallion.Threading.Redis.Primitives
{
internal class RedisMutexPrimitive : IRedLockAcquirableSynchronizationPrimitive, IRedLockExtensibleSynchronizationPrimitive
{
private readonly RedisKey _key;
private readonly RedisValue _lockId;
private readonly RedLockTimeouts _timeouts;
public RedisMutexPrimitive(RedisKey key, RedisValue lockId, RedLockTimeouts timeouts)
{
this._key = key;
this._lockId = lockId;
this._timeouts = timeouts;
}
public TimeoutValue AcquireTimeout => this._timeouts.AcquireTimeout;
private static readonly RedisScript<RedisMutexPrimitive> ReleaseScript = new RedisScript<RedisMutexPrimitive>(@"
if redis.call('get', @key) == @lockId then
return redis.call('del', @key)
end
return 0",
p => new { key = p._key, lockId = p._lockId }
);
public void Release(IDatabase database, bool fireAndForget) => ReleaseScript.Execute(database, this, fireAndForget);
public Task ReleaseAsync(IDatabaseAsync database, bool fireAndForget) => ReleaseScript.ExecuteAsync(database, this, fireAndForget);
public bool TryAcquire(IDatabase database) =>
database.StringSet(this._key, this._lockId, this._timeouts.Expiry.TimeSpan, When.NotExists, CommandFlags.DemandMaster);
public Task<bool> TryAcquireAsync(IDatabaseAsync database) =>
database.StringSetAsync(this._key, this._lockId, this._timeouts.Expiry.TimeSpan, When.NotExists, CommandFlags.DemandMaster);
private static readonly RedisScript<RedisMutexPrimitive> ExtendScript = new RedisScript<RedisMutexPrimitive>(@"
if redis.call('get', @key) == @lockId then
return redis.call('pexpire', @key, @expiryMillis)
end
return 0",
p => new { key = p._key, lockId = p._lockId, expiryMillis = p._timeouts.Expiry.InMilliseconds }
);
public Task<bool> TryExtendAsync(IDatabaseAsync database) => ExtendScript.ExecuteAsync(database, this).AsBooleanTask();
}
}
| madelson/DistributedLock | DistributedLock.Redis/Primitives/RedisMutexPrimitive.cs | C# | mit | 2,369 |
<?php
/*
* This file is part of the Behat Gherkin.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\Gherkin\Node;
/**
* Represents Gherkin Scenario.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class ScenarioNode implements ScenarioInterface
{
/**
* @var string
*/
private $title;
/**
* @var array
*/
private $tags = array();
/**
* @var StepNode[]
*/
private $steps = array();
/**
* @var string
*/
private $keyword;
/**
* @var integer
*/
private $line;
/**
* Initializes scenario.
*
* @param null|string $title
* @param array $tags
* @param StepNode[] $steps
* @param string $keyword
* @param integer $line
*/
public function __construct($title, array $tags, array $steps, $keyword, $line)
{
$this->title = $title;
$this->tags = $tags;
$this->steps = $steps;
$this->keyword = $keyword;
$this->line = $line;
}
/**
* Returns node type string
*
* @return string
*/
public function getNodeType()
{
return 'Scenario';
}
/**
* Returns scenario title.
*
* @return null|string
*/
public function getTitle()
{
return $this->title;
}
/**
* Checks if scenario is tagged with tag.
*
* @param string $tag
*
* @return bool
*/
public function hasTag($tag)
{
return in_array($tag, $this->getTags());
}
/**
* Checks if scenario has tags (both inherited from feature and own).
*
* @return bool
*/
public function hasTags()
{
return 0 < count($this->getTags());
}
/**
* Returns scenario tags (including inherited from feature).
*
* @return array
*/
public function getTags()
{
return $this->tags;
}
/**
* Checks if scenario has steps.
*
* @return bool
*/
public function hasSteps()
{
return 0 < count($this->steps);
}
/**
* Returns scenario steps.
*
* @return StepNode[]
*/
public function getSteps()
{
return $this->steps;
}
/**
* Returns scenario keyword.
*
* @return string
*/
public function getKeyword()
{
return $this->keyword;
}
/**
* Returns scenario declaration line number.
*
* @return integer
*/
public function getLine()
{
return $this->line;
}
}
| Behat/Gherkin | src/Behat/Gherkin/Node/ScenarioNode.php | PHP | mit | 2,730 |
#include "../gc/GC.h"
#include "../misc/Debug.h"
#include "../misc/NativeMethod.h"
#include "../misc/Option.h"
#include "../misc/Utils.h"
#include "../runtime/JavaClass.h"
#include "../runtime/JavaHeap.hpp"
#include "../runtime/MethodArea.h"
#include "../runtime/RuntimeEnv.h"
#include "YVM.h"
YVM::ExecutorThreadPool YVM::executor;
#define FORCE(x) (reinterpret_cast<char*>(x))
// registered java native methods table, it conforms to following rule:
// {class_name,method_name,descriptor_name,function_pointer}
static const char*((nativeFunctionTable[])[4]) = {
{"ydk/lang/IO", "print", "(Ljava/lang/String;)V",
FORCE(ydk_lang_IO_print_str)},
{"ydk/lang/IO", "print", "(I)V", FORCE(ydk_lang_IO_print_I)},
{"ydk/lang/IO", "print", "(C)V", FORCE(ydk_lang_IO_print_C)},
{"java/lang/Math", "random", "()D", FORCE(java_lang_Math_random)},
{"java/lang/StringBuilder", "append", "(I)Ljava/lang/StringBuilder;",
FORCE(java_lang_stringbuilder_append_I)},
{"java/lang/StringBuilder", "append", "(C)Ljava/lang/StringBuilder;",
FORCE(java_lang_stringbuilder_append_C)},
{"java/lang/StringBuilder", "append", "(D)Ljava/lang/StringBuilder;",
FORCE(java_lang_stringbuilder_append_D)},
{"java/lang/StringBuilder", "append",
"(Ljava/lang/String;)Ljava/lang/StringBuilder;",
FORCE(java_lang_stringbuilder_append_str)},
{"java/lang/StringBuilder", "toString", "()Ljava/lang/String;",
FORCE(java_lang_stringbuilder_tostring)},
{"java/lang/Thread", "start", "()V", FORCE(java_lang_thread_start)}
};
YVM::YVM() {
#ifdef YVM_DEBUG_SHOW_SIZEOF_ALL_TYPE
Inspector::printSizeofInternalTypes();
#endif
}
// Load given class into jvm
bool YVM::loadClass(const std::string& name) {
return yrt.ma->loadJavaClass(name);
}
// link given class into jvm. A linkage exception would be occurred if given
// class not existed before linking
bool YVM::linkClass(const std::string& name) {
if (!yrt.ma->findJavaClass(name)) {
// It's not an logical endurable error, so we throw and linkage
// exception to denote it;
throw std::runtime_error(
"LinkageException: Class haven't been loaded into YVM yet!");
}
yrt.ma->linkJavaClass(name);
return true;
}
// Initialize given class.
bool YVM::initClass(Interpreter& exec, const std::string& name) {
if (!yrt.ma->findJavaClass(name)) {
// It's not an logical endurable error, so we throw and linkage
// exception to denote it;
throw std::runtime_error(
"InitializationException: Class haven't been loaded into YVM yet!");
}
yrt.ma->initClassIfAbsent(exec, name);
return true;
}
// Call java's "public static void main(String...)" method in the newly created
// main thread. It also responsible for releasing reousrces and terminating
// virtual machine after main method executing accomplished
void YVM::callMain(const std::string& name) {
executor.initialize(1);
std::future<void> mainFuture = executor.submit([=]() -> void {
#ifdef YVM_DEBUG_SHOW_THREAD_NAME
std::cout << "[Main Executing Thread] ID:" << std::this_thread::get_id()
<< "\n";
#endif
auto* jc = yrt.ma->loadClassIfAbsent(name);
yrt.ma->linkClassIfAbsent(name);
// For each execution thread, we have a code execution engine
Interpreter exec;
yrt.ma->initClassIfAbsent(exec, name);
exec.invokeByName(jc, "main", "([Ljava/lang/String;)V");
});
// Block until all sub threads accomplished its task
for (const auto& start : executor.getTaskFutures()) {
start.get();
}
// Block until main thread accomplished;
mainFuture.get();
// Close garbage collection. This is optional since operation system would
// release all resources when process exited
yrt.gc->terminateGC();
// Terminate virtual machine normally
return;
}
// Warm up yvm. This function would register native methods into jvm before
// actual code execution, and also initialize MethodArea with given java runtime
// paths, which is the core component of this jvm
void YVM::warmUp(const std::vector<std::string>& libPaths) {
int p = sizeof nativeFunctionTable / sizeof nativeFunctionTable[0];
for (int i = 0; i < p; i++) {
registerNativeMethod(
nativeFunctionTable[i][0], nativeFunctionTable[i][1],
nativeFunctionTable[i][2],
reinterpret_cast<JType* (*)(RuntimeEnv*, JType**, int)>(
const_cast<char*>(nativeFunctionTable[i][3])));
}
yrt.ma = new MethodArea(libPaths);
}
| racaljk/yvm | src/vm/YVM.cpp | C++ | mit | 4,611 |
'use strict';
var nodeSassImport = require('../');
var test = require('tape');
var sass = require('node-sass');
test('base:function:test', function (t) {
t.ok(typeof nodeSassImport === 'function');
t.end();
});
test('base:importer:test', function (t) {
sass.render({
file: 'test/fixtures/main.scss',
importer: nodeSassImport
}, function (err, result) {
t.error(err, 'should render SASS without errors');
t.end();
});
});
test('base:importer:globs:test', function (t) {
sass.render({
file: 'test/fixtures/glob.scss',
importer: nodeSassImport
}, function (err, result) {
var css = result.css.toString();
t.error(err, 'should render SASS without errors');
t.ok(/div\.one/.test(css), 'renders one.scss');
t.ok(/div\.two/.test(css), 'renders two.scss');
t.end();
});
});
| anarh/node-sass-import | test/index.js | JavaScript | mit | 830 |
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using PholioVisualisation.DataConstruction;
using PholioVisualisation.DataSorting;
using PholioVisualisation.PholioObjects;
namespace PholioVisualisation.DataConstructionTest
{
[TestClass]
public class ParentChildAreaRelationshipBuilderTest
{
private string parentAreaCode = "Parent";
private int childAreaId = AreaTypeIds.Pct;
private List<IArea> filteredAreas;
private List<IArea> unfilteredAreas;
[TestInitialize]
public void RunBeforeEachTest()
{
filteredAreas = new List<IArea> {
new Area { Code = "z" },
new Area { Code = "y" }
};
unfilteredAreas = new List<IArea>(filteredAreas);
unfilteredAreas.Add(new Area { Code = "a" });
}
[TestMethod]
public void TestBuild()
{
var areaListBuilder = new Mock<AreaListProvider>(MockBehavior.Strict);
areaListBuilder.Setup(x => x.CreateChildAreaList(parentAreaCode, childAreaId));
areaListBuilder.Setup(x => x.SortByOrderOrName());
areaListBuilder.SetupGet(x => x.Areas)
.Returns(unfilteredAreas);
var ignoredAreasFilter = new Mock<IgnoredAreasFilter>(MockBehavior.Strict);
// Get areas
ParentAreaWithChildAreas relationship =
new ParentChildAreaRelationshipBuilder(ignoredAreasFilter.Object, areaListBuilder.Object)
.GetParentAreaWithChildAreas(new Area { Code = parentAreaCode }, childAreaId, true);
// Verify
Assert.AreEqual(3, relationship.Children.Count());
Assert.AreEqual(parentAreaCode, relationship.Parent.Code);
areaListBuilder.VerifyAll();
}
[TestMethod]
public void TestBuild_IgnoredAreasMayBeRemoved()
{
var areaListBuilder = new Mock<AreaListProvider>();
areaListBuilder.SetupGet(x => x.Areas)
.Returns(filteredAreas);
var ignoredAreasFilter = new Mock<IgnoredAreasFilter>(MockBehavior.Strict);
ignoredAreasFilter.Setup(x => x.RemoveAreasIgnoredEverywhere(unfilteredAreas));
// Get areas
ParentAreaWithChildAreas relationship =
new ParentChildAreaRelationshipBuilder(ignoredAreasFilter.Object, areaListBuilder.Object)
.GetParentAreaWithChildAreas(new Area { Code = parentAreaCode }, childAreaId, false);
// Verify
Assert.AreEqual(2, relationship.Children.Count());
areaListBuilder.VerifyAll();
}
}
} | PublicHealthEngland/fingertips-open | PholioVisualisationWS/DataConstructionTest/ParentChildAreaRelationshipBuilderTest.cs | C# | mit | 2,757 |
package rbfs.server;
import java.net.Socket;
import java.util.List;
import com.google.gson.*;
/**
* A thread that handles an incoming connection and responds to the embedded request.
* @author James Hoak
* @version 1.0
*/
final class ConnectionHandler implements Runnable {
// TODO null check, idiot
// TODO put a protocol package with JSON parsing, validation of each message
private Socket connection;
private ConnectionHandler(Socket connection) {
this.connection = connection;
}
static ConnectionHandler make(Socket connection) {
return new ConnectionHandler(connection);
}
public void run() {
try {
// TODO
}
// TODO catch other exceptions
catch (Exception x) {
// TODO
}
}
private void handle(String requestMessage) {
JsonObject convertedMessage = (JsonObject)(new Gson().toJsonTree(requestMessage));
String req = convertedMessage.get("request").getAsString();
if (req.equals("login") || req.equals("register"))
handleLoginRequest(convertedMessage);
else
handleSessionRequest(convertedMessage);
// TODO close connection if not done?
}
private void handleLoginRequest(JsonObject msg) {
String name = msg.get("name").getAsString(),
pwd = msg.get("pwd").getAsString();
if (msg.get("request").getAsString().equals("login")) {
String validUserQuery = String.format(
"select uid from User where name = %s && pwd = %s;",
name,
pwd
);
try {
List<Object[]> userResults = DBUtils.runQuery(validUserQuery, false);
if (userResults.size() != 0) {
int uid = (Integer)(userResults.get(0)[0]);
String existingSessionQuery = String.format(
"select * from Session where uid = %d;",
uid
);
List<Object[]> sessionResults = DBUtils.runQuery(existingSessionQuery, false);
if (sessionResults.size() == 0) {
login(uid);
}
else {
// TODO send message that login failed - user already logged in
}
}
else {
// TODO send message that login failed - bad name/pwd combination
}
}
catch (DBUtils.DBException x) {
// TODO send message that we failed to login, try again later
}
}
else {
// TODO handle registration (don't login yet)
// TODO get email: String email = msg.get("email").getAsString();
}
}
private void login(int uid) throws DBUtils.DBException {
// insert the session record into the db
int[] results = DBUtils.runUpdate(String.format(
"insert into Session (uid, skey) values (%d, %x);",
uid,
DBUtils.generateSessionKey()
));
if (results[0] == 1) {
// TODO send success message with sesh key
}
else {
// TODO send failure message - user already logged in
}
}
private void handleSessionRequest(JsonObject msg) {
}
}
| jhoak/RBFS | src/rbfs/server/ConnectionHandler.java | Java | mit | 3,453 |
"use strict";
const assert = require("assert");
const Message = require("../lib/vehicle-message");
describe("vehicle-message", () => {
it("get MQTT packet and return VehicleMessage data model", () => {
const msg = Message.from({
topic: "vehicle/foo",
payload: new Buffer(JSON.stringify({
timestamp: "2016-04-30T05:41:08.915Z",
longitude: 37.481200,
latitude: 126.948004
}))
});
assert.strictEqual(msg.vehicleId, "foo");
assert.strictEqual(msg.timestamp, "2016-04-30T05:41:08.915Z");
assert.strictEqual(msg.longitude, 37.481200);
assert.strictEqual(msg.latitude, 126.948004);
});
it("validate MQTT packet to create VehicleMessage data model", () => {
const bool = Message.validate({
topic: "vehicle/foo",
payload: new Buffer(JSON.stringify({
timestamp: "invalid date",
longitude: 37.481200,
latitude: 126.948004
}))
});
assert.strictEqual(bool, false);
});
it("get MQTT packet and return null if it can't be compatible to VehicleMessage", () => {
const msg = Message.from({
topic: "vehicle/foo",
payload: new Buffer(JSON.stringify({
timestamp: "invalid date",
longitude: 37.481200,
latitude: 126.948004
}))
});
assert.strictEqual(msg, null);
});
it("JSON.stringify and parse", () => {
const msg = Message.from({
topic: "vehicle/foo",
payload: new Buffer(JSON.stringify({
timestamp: "2016-04-30T05:41:08.915Z",
longitude: 37.481200,
latitude: 126.948004
}))
});
assert.deepEqual(JSON.parse(JSON.stringify(msg)), {
vehicleId: "foo",
timestamp: "2016-04-30T05:41:08.915Z",
longitude: 37.481200,
latitude: 126.948004
});
});
}); | esmusssein/SNU-grad-proj | broker/test/vehicle-message.js | JavaScript | mit | 1,804 |
'use strict';
// http://stackoverflow.com/a/365853
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.toRad = toRad;
exports.getShortestDistance = getShortestDistance;
exports.getLonguestDistance = getLonguestDistance;
exports.getLonguestDistanceFromCoordinates = getLonguestDistanceFromCoordinates;
exports.getAverageETA = getAverageETA;
function toRad(deg) {
return deg * (Math.PI / 180);
}
function getShortestDistance(lat1, lon1, lat2, lon2) {
var R = 6371000; // m
var dLat = toRad(lat2 - lat1);
var dLon = toRad(lon2 - lon1);
var rLat1 = toRad(lat1);
var rLat2 = toRad(lat2);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(rLat1) * Math.cos(rLat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
function getLonguestDistance(lat1, lon1, lat2, lon2) {
// Just the sum of two special cases of getShortestDistance
var R = 6371000; // m
var dLon = toRad(lon2 - lon1);
var dLat = toRad(lat2 - lat1);
var rLat1 = toRad(lat1);
var rLat2 = toRad(lat1);
var a = Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(rLat1) * Math.cos(rLat2);
var distA = R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var b = Math.sin(dLat / 2) * Math.sin(dLat / 2);
var distB = R * 2 * Math.atan2(Math.sqrt(b), Math.sqrt(1 - b));
return distA + distB;
}
function getLonguestDistanceFromCoordinates(from, to, waypoints) {
var points = [];
points.push(from);
points.push.apply(points, waypoints);
points.push(to);
var distance = 0;
points.forEach(function (point, i) {
if (!i) return;
distance += getLonguestDistance(points[i - 1][0], points[i - 1][1], point[0], point[1]);
});
return distance;
}
function getAverageETA(distance, speed) {
return Math.round(distance / speed);
} | alexjab/node-simple-eta | lib/distances.js | JavaScript | mit | 1,850 |
namespace NwaDg.Web.Areas.HelpPage.ModelDescriptions
{
public class CollectionModelDescription : ModelDescription
{
public ModelDescription ElementDescription { get; set; }
}
} | nwadg/nwadg-website | NwaDg.Web/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs | C# | mit | 196 |
module Memorandom
module Plugins
class URLParams < PluginTemplate
@description = "This plugin looks for interesting URL parameters and POST data"
@confidence = 0.50
# Scan takes a buffer and an offset of where this buffer starts in the source
def scan(buffer, source_offset)
buffer.scan(
/[%a-z0-9_\-=\&]*(?:sid|session|sess|user|usr|login|pass|secret|token)[%a-z0-9_\-=\&]*=[%a-z0-9_\-=&]+/mi
).each do |m|
# This may hit an earlier identical match, but thats ok
last_offset = buffer.index(m)
report_hit(:type => 'URLParams', :data => m, :offset => source_offset + last_offset)
last_offset += m.length
end
end
end
end
end
| kn0/memorandom | lib/memorandom/plugins/url_params.rb | Ruby | mit | 679 |
import re
import struct
from traitlets import Bytes, Unicode, TraitError
# reference to https://stackoverflow.com/a/385597/1338797
float_re = r'''
(?:
[-+]? # optional sign
(?:
(?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc.
|
(?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc.
)
# followed by optional exponent part if desired
(?: [Ee] [+-]? \d+ ) ?
)
'''
stl_re = r'''
solid .* \n # header
(?:
\s* facet \s normal (?: \s ''' + float_re + r''' ){3}
\s* outer \s loop
(?:
\s* vertex (?: \s ''' + float_re + r''' ){3}
){3}
\s* endloop
\s* endfacet
) + # at least 1 facet.
\s* endsolid (?: .*)?
\s* $ # allow trailing WS
'''
ascii_stl = re.compile(stl_re, re.VERBOSE)
class AsciiStlData(Unicode):
def validate(self, owner, stl):
stl = super(AsciiStlData, self).validate(owner, stl)
if ascii_stl.match(stl) is None:
raise TraitError('Given string is not valid ASCII STL data.')
return stl
class BinaryStlData(Bytes):
HEADER = 80
COUNT_SIZE = 4
FACET_SIZE = 50
def validate(self, owner, stl):
stl = super(BinaryStlData, self).validate(owner, stl)
if len(stl) < self.HEADER + self.COUNT_SIZE:
raise TraitError(
'Given bytestring is too short ({}) for Binary STL data.'
.format(len(stl))
)
(num_facets,) = struct.unpack('<I', stl[self.HEADER : self.HEADER + self.COUNT_SIZE])
expected_size = self.HEADER + self.COUNT_SIZE + num_facets * self.FACET_SIZE
if len(stl) != expected_size:
raise TraitError(
'Given bytestring has wrong length ({}) for Binary STL data. '
'For {} facets {} bytes were expected.'
.format(len(stl), num_facets, expected_size)
)
return stl
| K3D-tools/K3D-jupyter | k3d/validation/stl.py | Python | mit | 1,932 |
<?php
/**
* This file is part of Gush package.
*
* (c) 2013-2014 Luis Cordova <cordoval@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Gush\Tests\Helper;
use Gush\Helper\EditorHelper;
/**
* @author Luis Cordova <cordoval@gmail.com>
* @author Daniel Leech <daniel@dantleech.com>
*/
class EditorHelperTest extends \PHPUnit_Framework_TestCase
{
protected $helper;
public function setUp()
{
$this->helper = new EditorHelper();
putenv('EDITOR=cat');
}
/**
* @test
*/
public function itOutputsFromAString()
{
$oneTwoThree = <<<EOT
One
Two
Three
EOT;
$res = $this->helper->fromString($oneTwoThree);
$this->assertEquals($oneTwoThree, $res);
}
/**
* @test
* @expectedException \RuntimeException
*/
public function itFailsToOutputWhenEditorEnvironmentalVariableIsNotSet()
{
putenv('EDITOR');
$this->helper->fromString('asd');
}
/**
* @test
* @dataProvider provideFromStringWithMessage
*/
public function itOutputsFromAStringWithMessage($source, $message)
{
$res = $this->helper->fromStringWithMessage($source, $message);
$this->assertSame($source, $res);
}
public function provideFromStringWithMessage()
{
return [
[
<<<EOT
This is some text that I want to edit
EOT
,
<<<EOT
This is some text that I want the user to see in a command
OK
EOT
],
];
}
}
| cordoval/gush-core | tests/Helper/EditorHelperTest.php | PHP | mit | 1,623 |
#ifndef LOCI_CollectionLocus
#define LOCI_CollectionLocus
#include "../core/Locus.hpp"
#include <vector>
class CollectionLocus : public Locus {
private:
protected:
std::vector<boost::any> population;
CollectionLocus();
CollectionLocus(std::vector<boost::any> population);
void setPopulation(std::vector<boost::any> population);
virtual boost::any getIndex(double index);
public:
virtual ~CollectionLocus();
virtual Gene* getGene();
virtual Gene* getGene(double index);
virtual double randomIndex();
virtual double topIndex();
virtual double bottomIndex();
virtual double closestIndex(double index);
virtual bool outOfRange(double index);
virtual bool outOfRange(Gene* index);
virtual std::string toString()=0;
virtual std::string flatten(Gene* index)=0;
virtual boost::any getIndex(Gene* index);
};
#endif
| NGTOne/libHierGA | include/loci/CollectionLocus.hpp | C++ | mit | 833 |
$(function() {
var background = chrome.extension.getBackgroundPage();
var defaultOptions = background.defaultOptions;
var options = {};
function createFrames() {
var frames = options.frames.split('\n');
$('.js-frame').remove();
for (var i = 0; i < frames.length; i++) {
var src = frames[i];
if (!src) {
continue;
}
var $frame = $(
'<div class="frame js-frame">' +
'<div class="frame-iframe-wrapper js-iframe-wrapper">' +
'<iframe frameborder="0" scrolling="no"></iframe>' +
'</div>' +
'<div class="frame-title-container">' +
'<a class="frame-title js-title" ' +
'href="' + src + '" target="_blank">' + src + '</a>' +
'</div>' +
'</div>'
);
$('.js-frames').append($frame);
src += src.indexOf('?') !== -1 ? '&' : '?';
src += 'timestamp=' + (new Date()).getTime();
$frame.find('iframe').attr('src', src);
}
resizeFrames();
}
function resizeFrames() {
var resolutionX = options.resolutionX;
var resolutionY = options.resolutionY;
var gutterWidth = 10;
var frameWidth = (
($(document).width() - options.columns * gutterWidth - gutterWidth) /
options.columns
);
var scale = frameWidth / resolutionX;
$('.js-frame').each(function() {
var $frame = $(this);
var $wrapper = $frame.find('.js-iframe-wrapper');
var $iframe = $wrapper.find('iframe');
$frame.width(frameWidth);
$wrapper.height(frameWidth * (resolutionY / resolutionX));
$iframe.css({
transform: 'scale(' + scale + ')',
});
});
}
$(window).on('resize', resizeFrames);
chrome.storage.sync.get('options', function(result) {
options = result.options || defaultOptions;
createFrames();
});
});
| laurentguilbert/overseer | js/frames.js | JavaScript | mit | 1,827 |
<div class="white-area-content">
<div class="db-header clearfix">
<div class="page-header-title"> <span class="glyphicon glyphicon-user"></span> <?php echo lang("ctn_1") ?></div>
<div class="db-header-extra">
</div>
</div>
<ol class="breadcrumb">
<li><a href="<?php echo site_url("backend/admin") ?>"><?php echo lang("ctn_2") ?></a></li>
<li><a href="<?php echo site_url("backend/admin") ?>"><?php echo lang("ctn_1") ?></a></li>
<li class="active"><?php echo lang("ctn_62") ?></li>
</ol>
<p><?php echo lang("ctn_63") ?></p>
<hr>
<table class="table table-bordered tbl">
<tr class='table-header'><td><?php echo lang("ctn_11") ?></td><td><?php echo lang("ctn_52") ?></td></tr>
<?php foreach($email_templates->result() as $r) : ?>
<tr><td><?php echo $r->title ?></td><td><a href="<?php echo site_url("backend/admin/edit_email_template/" . $r->ID) ?>" class="btn btn-warning btn-xs" title="<?php echo lang("ctn_55") ?>"><span class="glyphicon glyphicon-cog"></span></a></td></tr>
<?php endforeach; ?>
</table>
</div> | dodeagung/KLGH | application/views/admin/email_templates.php | PHP | mit | 1,032 |
class AddInfoFieldsToPhoto < ActiveRecord::Migration
def change
add_column :photos, :year, :string
add_column :photos, :place, :string
add_column :photos, :people, :text
end
end
| macool/antano | db/migrate/20140530001952_add_info_fields_to_photo.rb | Ruby | mit | 194 |
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: '12',
},
},
],
'@babel/preset-react',
],
};
| dannegm/danielgarcia | .babelrc.js | JavaScript | mit | 236 |
/*
* Module dependencies
*/
var conf = module.exports = require('nconf');
/* Last fallback : environment variables */
conf.env().argv();
/* Dev fallback : config.json */
conf.file(__dirname + '/../config.json');
/* Default values */
conf.defaults({
title: 'Meishengo',
debug: false,
port: 8000,
host: 'localhost',
gameTTL: 24 * 3600,
nickTTL: 60
});
| dawicorti/meishengo | lib/conf.js | JavaScript | mit | 372 |
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.api.item.inventory.entity;
import org.spongepowered.api.entity.living.Human;
import org.spongepowered.api.item.inventory.types.CarriedInventory;
/**
* Represents the inventory of a Human or Player. Implementors of this interface
* guarantee that (at a minimum) the following subinventory types can be queried
* for:
*
* <ul><li>
* {@link org.spongepowered.api.item.inventory.crafting.CraftingInventory}
* </li></ul>
*/
public interface HumanInventory extends CarriedInventory<Human> {
/**
* Get the hotbar inventory.
*
* @return the hotbar
*/
Hotbar getHotbar();
}
| frogocomics/SpongeAPI | src/main/java/org/spongepowered/api/item/inventory/entity/HumanInventory.java | Java | mit | 1,889 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Sphinx configuration."""
from __future__ import print_function
import os
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Do not warn on external images.
suppress_warnings = ['image.nonlocal_uri']
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.doctest',
'sphinx.ext.extlinks',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
]
extlinks = {
'source': ('https://github.com/inveniosoftware/invenio-search-ui/tree/master/%s', 'source')
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Invenio-Search-UI'
copyright = u'2015, CERN'
author = u'CERN'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
# Get the version string. Cannot be done with import!
g = {}
with open(os.path.join(os.path.dirname(__file__), '..',
'invenio_search_ui', 'version.py'),
'rt') as fp:
exec(fp.read(), g)
version = g['__version__']
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
html_theme = 'alabaster'
html_theme_options = {
'description': 'UI for Invenio-Search.',
'github_user': 'inveniosoftware',
'github_repo': 'invenio-search-ui',
'github_button': False,
'github_banner': True,
'show_powered_by': False,
'extra_nav_links': {
'invenio-search-ui@GitHub': 'https://github.com/inveniosoftware/invenio-search-ui',
'invenio-search-ui@PyPI': 'https://pypi.python.org/pypi/invenio-search-ui/',
}
}
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'relations.html',
'searchbox.html',
'donate.html',
]
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'invenio-search-ui_namedoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'invenio-search-ui.tex', u'invenio-search-ui Documentation',
u'CERN', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'invenio-search-ui', u'invenio-search-ui Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'invenio-search-ui', u'Invenio-Search-UI Documentation',
author, 'invenio-search-ui', 'UI for Invenio-Search.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
# Autodoc configuraton.
autoclass_content = 'both'
| inveniosoftware/invenio-search-ui | docs/conf.py | Python | mit | 10,173 |
#!/usr/bin/ruby
# file: xml-to-haml.rb
require 'rexml/document'
class XMLtoHAML
include REXML
def initialize(s)
doc = Document.new(s)
@haml = xml_to_haml(doc)
end
def to_s
@haml
end
def xml_to_haml(nodex, indent ='')
buffer = nodex.elements.map do |node|
attributex = ' '
buffer = "%s" % [indent + '%' + node.name]
if node.attributes.size > 0 then
alist = Array.new(node.attributes.size)
i = 0
node.attributes.each { |x, y|
alist[i] = " :#{x} => '#{y}'"
i += 1
}
attributex = '{' + alist.join(",") + '} '
end
buffer += "%s" % [attributex + node.text] if not node.text.nil?
buffer += "\n"
buffer += xml_to_haml(node, indent + ' ')
buffer
end
buffer.join
end
end
| jrobertson/xml-to-haml | lib/xml-to-haml.rb | Ruby | mit | 832 |
<?php
namespace AppBundle\Service\Crud;
use AppBundle\Service\Crud\Exception\EntityNotFound;
/**
* @author Alexandr Sibov<cyberdelia1987@gmail.com>
*/
interface DeleteInterface
{
/**
* Remove an entity
*
* @param mixed $identity
*
* @throws EntityNotFound
*/
public function delete($identity);
} | Cyberdelia1987/symfony-test | src/AppBundle/Service/Crud/DeleteInterface.php | PHP | mit | 337 |
<?php
namespace CarBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class DefaultController extends Controller
{
/**
* @Route("/our-cars", name="offer")
*/
public function indexAction(Request $request)
{
$carRepository = $this->getDoctrine()->getRepository('CarBundle:Car');
$cars = $carRepository->findCarsWithDetails();
$form = $this->createFormBuilder()
->setMethod('GET')
->add('search', TextType::class, [
'constraints' => [
new NotBlank(),
new Length(['min' => 2])
]
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
die('form submitted');
}
return $this->render('CarBundle:Default:index.html.twig',
[
'cars' => $cars,
'form' => $form->createView()
]
);
}
/**
* @Route("/car/{id}", name="show_car")
* @param $id
* @return \Symfony\Component\HttpFoundation\Response
*/
public function showAction($id)
{
$carRepository = $this->getDoctrine()->getRepository('CarBundle:Car');
$car = $carRepository->findCarWithDetailsById($id);
return $this->render('CarBundle:Default:show.html.twig', ['car' => $car]);
}
}
| aRastini/symfonyExample | src/CarBundle/Controller/DefaultController.php | PHP | mit | 1,759 |
/**
* Author: Carter
*/
#include <iostream>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
using namespace std;
int main(int argc, char** argv) {
if (argc != 2) {
cout << "Incorrect number of arguments\nUsage: run.out output_file.png" << endl;
return 1;
}
const int width = 1920;
const int height = 1080;
const char channels = 3;
int index;
unsigned char* data = new unsigned char[width * height * 3];
for (int y = height - 1; y >= 0; y--) {
for (int x = 0; x < width; x++) {
index = ((height - 1 - y) * width * channels) + (x * channels);
data[index] = ((float) y / (float) height) * 255; // Red channel
data[index + 1] = ((float) x / (float) width) * 255; // Green channel
data[index + 2] = 0; // Blue channel
}
}
stbi_write_png(argv[1], width, height, channels, data, width * channels);
delete[] data;
return 0;
}
| clccmh/RayTracingInOneWeekend | Ch1/src/create.cpp | C++ | mit | 921 |
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'image_zoomer'
| vdtejeda/Image_Zoomer | spec/spec_helper.rb | Ruby | mit | 82 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Closest Two Points")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Closest Two Points")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0cd3692f-8de8-4cff-ac89-9111c124369a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mkpetrov/Programming-Fundamentals-SoftUni-Jan2017 | Objects and Simple Classes/Closest Two Points/Properties/AssemblyInfo.cs | C# | mit | 1,412 |
module.exports = {
mixins: [__dirname],
fragmentsFile: '<rootDir>/fragmentTypes.json',
graphqlMockServerPath: '/graphql',
configSchema: {
fragmentsFile: {
type: 'string',
absolutePath: true,
},
graphqlSchemaFile: {
type: 'string',
absolutePath: true,
},
graphqlMockSchemaFile: {
type: 'string',
},
graphqlMockServerPath: {
type: 'string',
},
graphqlMockContextExtenderFile: {
type: 'string',
},
},
};
| xing/hops | packages/apollo-mock-server/preset.js | JavaScript | mit | 493 |
package org.jinstagram.auth.model;
public class Constants {
public static final String INSTAGRAM_OAUTH_URL_BASE = "https://api.instagram.com/oauth";
public static final String ACCESS_TOKEN_ENDPOINT = INSTAGRAM_OAUTH_URL_BASE + "/access_token";
public static final String AUTHORIZE_URL = INSTAGRAM_OAUTH_URL_BASE + "/authorize/?client_id=%s&redirect_uri=%s&response_type=code";
public static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s";
}
| thesocialstation/jInstagram | src/main/java/org/jinstagram/auth/model/Constants.java | Java | mit | 470 |
# -*- coding: utf-8 -*-
"""
Send many mails
===============
Send mail to students. The script consider two columns from
one spreadsheets. The first one is about the receivers,
the second one about the customized message for each of them.
"""
#########################################
# logging et import
import os
import warnings
from pyquickhelper.loghelper import fLOG
fLOG(OutputPrint=True)
from ensae_teaching_cs.automation_students import enumerate_feedback, enumerate_send_email
import pymmails
#########################################
# On définit le contenu du mail.
cc = []
sujet = "Question de code - ENSAE 1A - projet de programmation"
col_name = None # "mail"
col_mail = "mail"
columns = ["sujet", "Question de code"]
col_group = "groupe"
delay_sending = False
test_first_mail = False # regarder le premier mail avant de les envoyer
skip = 0 # to start again after a failure
only = None
skiprows = 1
folder = os.path.normpath(os.path.abspath(os.path.join(
*([os.path.dirname(__file__)] + ([".."] * 5) + ["_data", "ecole", "ENSAE", "2017-2018", "1A_projet"]))))
student = os.path.join(folder, "ENSAE 1A - projet python.xlsx")
if not os.path.exists(student):
raise FileNotFoundError(student)
##############################
# début commun
begin = """
Bonjour,
""" + \
"""
Bonjour,
Voici les questions de code. Celles-ci sont
extraites des programmes que vous m'avez transmis.
Les noms de fonctions que j'utilise y font référence
quand je ne recopie pas le code. La réponse est souvent
liée à la performance.
""".replace("\n", " ")
#####################
# fin commune
end = """
""".replace("\n", " ") + \
"""
Xavier
"""
###################################
# Lecture des de la feuille Excel
import pandas
df = pandas.read_excel(student, sheet_name=0,
skiprows=skiprows, engine='openpyxl')
if len(df.columns) < 4:
raise ValueError("Probably an issue while reading the spreadsheet:\n{0}\n{1}".format(
df.columns, df.head()))
if len(" ".join(df.columns).split("Unnamed")) > 4:
raise ValueError("Probably an issue while reading the spreadsheet:\n{0}\n{1}".format(
df.columns, df.head()))
fLOG("shape", df.shape)
fLOG("columns", df.columns)
###################################
# mot de passe
from pyquickhelper.loghelper import get_keyword
user = get_password("gmail", "ensae_teaching_cs,user")
pwd = get_password("gmail", "ensae_teaching_cs,pwd")
###################################
# On envoie les mails.
# Le paramètre delay_sending retourne une fonction qu'il suffit d'exécuter
# pour envoyer le mail.
# Si mailbox est None, la fonction affiche les résultats mais ne fait rien.
fLOG("connect", user)
mailbox = pymmails.sender.create_smtp_server("gmail", user, pwd)
fLOG("send")
# remplacer mailbox par None pour voir le premier mail sans l'envoyer
mails = enumerate_send_email(mailbox if not test_first_mail else None,
sujet, user + "@gmail.com",
df, exc=True, fLOG=fLOG, delay_sending=delay_sending,
begin=begin, end=end, skip=skip,
cc=cc, only=only, col_group=col_group,
col_name=col_name, col_mail=col_mail,
cols=columns)
for i, m in enumerate(mails):
fLOG("------------", m)
###################################
# fin
mailbox.close()
fLOG("Done")
| sdpython/ensae_teaching_cs | _doc/examples/automation/send_mails.py | Python | mit | 3,434 |
package org.mce.teknoservice.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Spring Security success handler, specialized for Ajax requests.
*/
@Component
public class AjaxAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication)
throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK);
}
}
| MarcoCeccarini/teknoservice | src/main/java/org/mce/teknoservice/security/AjaxAuthenticationSuccessHandler.java | Java | mit | 881 |
from __future__ import unicode_literals
from django import template
from django.utils.html import mark_safe
from .. import conf
from ..models import Icon
register = template.Library()
@register.simple_tag
def svg_icons_icon(name, **kwargs):
filters = {'name__iexact': name}
value = ''
if kwargs.get('group'):
filters['group__name__iexact'] = kwargs.get('group')
try:
icon = Icon.objects.get(**filters)
value = icon.source
except Icon.DoesNotExist:
if conf.settings.DEBUG is True:
value = ('<span class="svg-icon-error">'
'<b>template tag svg_icons_icon: </b>'
'no icon by the name "{0}"</span>').format(name)
else:
value = ''
except Icon.MultipleObjectsReturned:
if conf.settings.DEBUG is True:
value = ('<span class="svg-icon-error">'
'<b>template tag svg_icons_icon: </b>'
'there are more than one '
'icon by the name "{0}" '
'try to use the "group" parameter</span>').format(name)
else:
icon = Icon.objects.filter(**filters)[:1].get()
value = icon.source
return mark_safe(value)
| rouxcode/django-svg-icons | svg_icons/templatetags/svg_icons_tags.py | Python | mit | 1,258 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace SoftJail.Data.Models
{
public class Mail
{
[Key]
[Required]
public int Id { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string Sender { get; set; }
[Required]
[RegularExpression(@"^[A-Za-z0-9 ]+ str.$")]
public string Address { get; set; }
public int PrisonerId { get; set; }
[Required]
public Prisoner Prisoner { get; set; }
}
}
| Steffkn/SoftUni | 04.CSharpDB/02.EntityFrameworkCore/00.Exams/SoftJail/SoftJail/Data/Models/Mail.cs | C# | mit | 614 |
package com.passwordLib;
import android.content.Context;
import android.os.AsyncTask;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class SendPasswordTask extends AsyncTask<Object, Void, Boolean> {
Context context;
String username;
String password;
@Override
protected Boolean doInBackground(Object... params) {
System.out.println("get args " + params[0]);
context = (Context) (params[0]);
System.out.println("get args " + params[1]);
username = (String) (params[1]);
System.out.println("get args " + params[2]);
password = (String) (params[2]);
JSch jsch = new JSch();
Session session = null;
final String SERVER = "app.smartfile.com";
final String USERNAME = PasswordFile.username;
final String PASSWORD = PasswordFile.password;
PasswordFile.saveFile();
String fileName = PasswordFile.fileName;
try {
session = jsch.getSession(USERNAME, SERVER, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(PASSWORD);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.put(context.getFilesDir() + "/" + fileName, fileName);
sftpChannel.exit();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
// do nothing
}
}
| aarongolliver/SmartPass | src/com/passwordLib/SendPasswordTask.java | Java | mit | 1,660 |
class ValidateAddReminderDayOfMonthAndDeadlineDayOfMonth < ActiveRecord::Migration[6.1]
def change
validate_check_constraint :partner_groups, name: "deadline_day_of_month_check"
validate_check_constraint :partner_groups, name: "reminder_day_of_month_check"
validate_check_constraint :partner_groups, name: "reminder_day_of_month_and_deadline_day_of_month_check"
end
end
| rubyforgood/diaper | db/migrate/20220103232639_validate_add_reminder_day_of_month_and_deadline_day_of_month.rb | Ruby | mit | 386 |
import {
CHOOSE_MEMORY,
LOAD_PHOTO_ERROR,
LOAD_PHOTO_SUCCESS,
} from './constants';
export function chooseMemory({ id, index }) {
return {
type: CHOOSE_MEMORY,
id,
index,
};
}
export function photoLoadSuccess({
host,
gallery,
setCurrentMemory,
album,
id,
photoLink,
}) {
return {
type: LOAD_PHOTO_SUCCESS,
id,
photoLink,
setCurrentMemory,
host,
gallery,
album,
};
}
export function photoLoadError(error, filename) {
return {
type: LOAD_PHOTO_ERROR,
filename,
error,
};
}
| danactive/history | ui/app/containers/App/actions.js | JavaScript | mit | 556 |
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0xa4d6fc138e2ab2fa649e97472c481009f6761548cbf7d86a14ca0ddc1e74203c"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1479129701, // * UNIX timestamp of last checkpoint block
1, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
120.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0xe900c15110857ca650625825761b00381699ef41451915468b1488644295671a"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1398863062,
1,
960.0
};
const CCheckpointData &Checkpoints() {
if (fTestNet)
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!GetBoolArg("-checkpoints", true))
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!GetBoolArg("-checkpoints", true))
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!GetBoolArg("-checkpoints", true))
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
| wrapperproject/wrapper | src/checkpoints.cpp | C++ | mit | 5,010 |
function saveUser({state, input}) {
state.set(['user', 'user'], input.user);
state.set(['session', 'jwt'], input.jwt);
}
export default saveUser;
| testpackbin/testpackbin | app/modules/home/actions/saveUser.js | JavaScript | mit | 151 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zm-2 5.79V18h-3.52L12 20.48 9.52 18H6v-3.52L3.52 12 6 9.52V6h3.52L12 3.52 14.48 6H18v3.52L20.48 12 18 14.48zM12 6.5c-3.03 0-5.5 2.47-5.5 5.5s2.47 5.5 5.5 5.5 5.5-2.47 5.5-5.5-2.47-5.5-5.5-5.5zm0 9c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z" /><circle cx="12" cy="12" r="2" /></React.Fragment>
, 'Brightness7Outlined');
| kybarg/material-ui | packages/material-ui-icons/src/Brightness7Outlined.js | JavaScript | mit | 593 |
'use strict';
// Listens for the app launching then creates the window
chrome.app.runtime.onLaunched.addListener(function() {
var width = 600;
var height = 400;
chrome.app.window.create('index.html', {
id: 'main',
bounds: {
width: width,
height: height,
left: Math.round((screen.availWidth - width) / 2),
top: Math.round((screen.availHeight - height)/2)
}
});
});
| yogiekurniawan/JayaMekar-ChromeApp | app/scripts/main.js | JavaScript | mit | 454 |
var lint = require('mocha-eslint');
var paths = [
'src',
];
var options = {
// Note: we saw timeouts with the 2000ms mocha timeout setting,
// thus raised to 5000ms for eslint
timeout: 5000, // Defaults to the global mocha `timeout` option
};
// Run the tests
lint(paths, options); | iulia0103/taste-of-code | linter.js | JavaScript | mit | 293 |
<?php
/**
* @package dynamic-parameter-bundle
*/
namespace Jihel\Plugin\DynamicParameterBundle\HttpKernel;
use Jihel\Plugin\DynamicParameterBundle\DependencyInjection\Dumper\CustomContainerDumper;
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper;
/**
* Class Kernel
*
* @author Joseph LEMOINE <lemoine.joseph@gmail.com>
* @link http://www.joseph-lemoine.fr
*/
abstract class Kernel extends BaseKernel
{
const customContainerOverloadClassPrefix = 'Jihel';
/**
* Initializes the service container.
*
* The cached version of the service container is used when fresh, otherwise the
* container is built.
*/
protected function initializeContainer()
{
$customClass = $this->getCustomContainerClass();
$baseClass = $this->getContainerClass();
$customCache = new ConfigCache($this->getCacheDir().'/'.$customClass.'.php', $this->debug);
$baseCache = new ConfigCache($this->getCacheDir().'/'.$baseClass.'.php', $this->debug);
$fresh = true;
if (!$baseCache->isFresh() || !$customCache->isFresh()) {
$container = $this->buildContainer();
if (!$container->hasParameter('jihel.plugin.dynamic_parameter.table_prefix')) {
$container->setParameter('jihel.plugin.dynamic_parameter.table_prefix', 'jihel_');
}
$container->compile();
$this->dumpContainer($baseCache, $container, $baseClass, $this->getContainerBaseClass());
$this->dumpCustomContainer($customCache, $container, $baseClass);
$fresh = false;
}
require_once $baseCache;
require_once $customCache;
$this->container = new $customClass();
$this->container->set('kernel', $this);
if (!$fresh && $this->container->has('cache_warmer')) {
$this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
}
}
/**
* @return string
*/
protected function getCustomContainerClass()
{
return static::customContainerOverloadClassPrefix.$this->getContainerClass();
}
/**
* Dumps the service container to PHP code in the cache.
*
* @param ConfigCache $cache The config cache
* @param ContainerBuilder $container The service container
* @param string $class The name of the class to generate
* @param string $baseClass The name of the container's base class
*/
protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
{
// cache the container
$dumper = new PhpDumper($container);
if (class_exists('ProxyManager\Configuration')) {
$dumper->setProxyDumper(new ProxyDumper());
}
$content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass));
if (!$this->debug) {
$content = static::stripComments($content);
}
$cache->write($content, $container->getResources());
}
/**
* Dumps the service container to PHP code in the cache.
*
* @param ConfigCache $cache The config cache
* @param ContainerBuilder $container The service container
* @param string $baseClass The name of the parent class
*/
protected function dumpCustomContainer(ConfigCache $cache, ContainerBuilder $container, $baseClass)
{
$dumper = new CustomContainerDumper();
$content = $dumper->dump(array('base_class' => $baseClass, 'prefix' => static::customContainerOverloadClassPrefix));
if (!$this->debug) {
$content = static::stripComments($content);
}
$cache->write($content, $container->getResources());
}
}
| Jihell/dynamic-parameter-bundle | src/HttpKernel/Kernel.php | PHP | mit | 4,046 |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk
{
/// <summary>
/// Structure containing callback function pointers for memory allocation.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct AllocationCallbacks
{
/// <summary>
/// A value to be interpreted by the implementation of the callbacks.
/// When any of the callbacks in AllocationCallbacks are called, the
/// Vulkan implementation will pass this value as the first parameter
/// to the callback. This value can vary each time an allocator is
/// passed into a command, even when the same object takes an allocator
/// in multiple commands.
/// </summary>
public IntPtr? UserData
{
get;
set;
}
/// <summary>
/// An application-defined memory allocation function of type
/// AllocationFunction.
/// </summary>
public SharpVk.AllocationFunctionDelegate Allocation
{
get;
set;
}
/// <summary>
/// An application-defined memory reallocation function of type
/// ReallocationFunction.
/// </summary>
public SharpVk.ReallocationFunctionDelegate Reallocation
{
get;
set;
}
/// <summary>
/// An application-defined memory free function of type FreeFunction.
/// </summary>
public SharpVk.FreeFunctionDelegate Free
{
get;
set;
}
/// <summary>
/// An application-defined function that is called by the
/// implementation when the implementation makes internal allocations,
/// and it is of type InternalAllocationNotification.
/// </summary>
public SharpVk.InternalAllocationNotificationDelegate InternalAllocation
{
get;
set;
}
/// <summary>
/// An application-defined function that is called by the
/// implementation when the implementation frees internal allocations,
/// and it is of type InternalFreeNotification.
/// </summary>
public SharpVk.InternalFreeNotificationDelegate InternalFree
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="pointer">
/// </param>
internal unsafe void MarshalTo(SharpVk.Interop.AllocationCallbacks* pointer)
{
if (this.UserData != null)
{
pointer->UserData = this.UserData.Value.ToPointer();
}
else
{
pointer->UserData = default(void*);
}
pointer->Allocation = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.Allocation);
pointer->Reallocation = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.Reallocation);
pointer->Free = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.Free);
pointer->InternalAllocation = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.InternalAllocation);
pointer->InternalFree = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.InternalFree);
}
}
}
| FacticiusVir/SharpVk | src/SharpVk/AllocationCallbacks.gen.cs | C# | mit | 4,718 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Urals Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet_ismine.h"
#include "key.h"
#include "keystore.h"
#include "script/script.h"
#include "script/standard.h"
#include "script/sign.h"
#include <boost/foreach.hpp>
using namespace std;
typedef vector<unsigned char> valtype;
unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
{
unsigned int nResult = 0;
BOOST_FOREACH(const valtype& pubkey, pubkeys)
{
CKeyID keyID = CPubKey(pubkey).GetID();
if (keystore.HaveKey(keyID))
++nResult;
}
return nResult;
}
isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
{
CScript script = GetScriptForDestination(dest);
return IsMine(keystore, script);
}
isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
{
vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions)) {
if (keystore.HaveWatchOnly(scriptPubKey))
return ISMINE_WATCH_UNSOLVABLE;
return ISMINE_NO;
}
CKeyID keyID;
switch (whichType)
{
case TX_NONSTANDARD:
case TX_NULL_DATA:
break;
case TX_PUBKEY:
keyID = CPubKey(vSolutions[0]).GetID();
if (keystore.HaveKey(keyID))
return ISMINE_SPENDABLE;
break;
case TX_PUBKEYHASH:
keyID = CKeyID(uint160(vSolutions[0]));
if (keystore.HaveKey(keyID))
return ISMINE_SPENDABLE;
break;
case TX_SCRIPTHASH:
{
CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
CScript subscript;
if (keystore.GetCScript(scriptID, subscript)) {
isminetype ret = IsMine(keystore, subscript);
if (ret == ISMINE_SPENDABLE)
return ret;
}
break;
}
case TX_MULTISIG:
{
// Only consider transactions "mine" if we own ALL the
// keys involved. Multi-signature transactions that are
// partially owned (somebody else has a key that can spend
// them) enable spend-out-from-under-you attacks, especially
// in shared-wallet situations.
vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
if (HaveKeys(keys, keystore) == keys.size())
return ISMINE_SPENDABLE;
break;
}
}
if (keystore.HaveWatchOnly(scriptPubKey)) {
// TODO: This could be optimized some by doing some work after the above solver
CScript scriptSig;
return ProduceSignature(DummySignatureCreator(&keystore), scriptPubKey, scriptSig) ? ISMINE_WATCH_SOLVABLE : ISMINE_WATCH_UNSOLVABLE;
}
return ISMINE_NO;
}
| JohnMnemonick/UralsCoin | src/wallet/wallet_ismine.cpp | C++ | mit | 2,907 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Identity_service {
private $ci;
public function __construct()
{
// to load ci instance
$this->ci =& get_instance();
}
public function set($User)
{
if(isset($User['id']) && isset($User['role']))
{
$this->ci->session->set_userdata('id', $User['id']);
$this->ci->session->set_userdata('role', $User['role']);
}
}
public function get()
{
}
public function destroy()
{
}
public function get_id()
{
return $this->ci->session->userdata('id');
}
public function get_role()
{
return $this->ci->session->userdata('role');
}
public function validate_role($type)
{
if($this->ci->session->userdata('role') === $type)
{
return true;
}
else
{
redirect('login');
}
}
} | trisetiobr/labscheduler | application/libraries/services/Identity_service.php | PHP | mit | 799 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2016, British Columbia Institute of Technology
*
* 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 CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
* @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
/*
*---------------------------------------------------------------
* APPLICATION ENVIRONMENT
*---------------------------------------------------------------
*
* You can load different configurations depending on your
* current environment. Setting the environment also influences
* things like logging and error reporting.
*
* This can be set to anything, but default usage is:
*
* development
* testing
* production
*
* NOTE: If you change these, also change the error_reporting() code below
*/
define('ENVIRONMENT', 'development');
//define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
switch (ENVIRONMENT)
{
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
case 'testing':
case 'production':
ini_set('display_errors', 0);
if (version_compare(PHP_VERSION, '5.3', '>='))
{
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
}
else
{
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
}
break;
default:
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'The application environment is not set correctly.';
exit(1); // EXIT_ERROR
}
/*
*---------------------------------------------------------------
* SYSTEM DIRECTORY NAME
*---------------------------------------------------------------
*
* This variable must contain the name of your "system" directory.
* Set the path if it is not in the same directory as this file.
*/
$system_path = 'system';
/*
*---------------------------------------------------------------
* APPLICATION DIRECTORY NAME
*---------------------------------------------------------------
*
* If you want this front controller to use a different "application"
* directory than the default one you can set its name here. The directory
* can also be renamed or relocated anywhere on your server. If you do,
* use an absolute (full) server path.
* For more info please see the user guide:
*
* https://codeigniter.com/user_guide/general/managing_apps.html
*
* NO TRAILING SLASH!
*/
$application_folder = 'application';
/*
*---------------------------------------------------------------
* VIEW DIRECTORY NAME
*---------------------------------------------------------------
*
* If you want to move the view directory out of the application
* directory, set the path to it here. The directory can be renamed
* and relocated anywhere on your server. If blank, it will default
* to the standard location inside your application directory.
* If you do move this, use an absolute (full) server path.
*
* NO TRAILING SLASH!
*/
$view_folder = '';
/*
* --------------------------------------------------------------------
* DEFAULT CONTROLLER
* --------------------------------------------------------------------
*
* Normally you will set your default controller in the routes.php file.
* You can, however, force a custom routing by hard-coding a
* specific controller class/function here. For most applications, you
* WILL NOT set your routing here, but it's an option for those
* special instances where you might want to override the standard
* routing in a specific front controller that shares a common CI installation.
*
* IMPORTANT: If you set the routing here, NO OTHER controller will be
* callable. In essence, this preference limits your application to ONE
* specific controller. Leave the function name blank if you need
* to call functions dynamically via the URI.
*
* Un-comment the $routing array below to use this feature
*/
// The directory name, relative to the "controllers" directory. Leave blank
// if your controller is not in a sub-directory within the "controllers" one
// $routing['directory'] = '';
// The controller class file name. Example: mycontroller
// $routing['controller'] = '';
// The controller function you wish to be called.
// $routing['function'] = '';
/*
* -------------------------------------------------------------------
* CUSTOM CONFIG VALUES
* -------------------------------------------------------------------
*
* The $assign_to_config array below will be passed dynamically to the
* config class when initialized. This allows you to set custom config
* items or override any default config values found in the config.php file.
* This can be handy as it permits you to share one application between
* multiple front controller files, with each file containing different
* config values.
*
* Un-comment the $assign_to_config array below to use this feature
*/
// $assign_to_config['name_of_config_item'] = 'value of config item';
// --------------------------------------------------------------------
// END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE
// --------------------------------------------------------------------
/*
* ---------------------------------------------------------------
* Resolve the system path for increased reliability
* ---------------------------------------------------------------
*/
// Set the current directory correctly for CLI requests
if (defined('STDIN'))
{
chdir(dirname(__FILE__));
}
if (($_temp = realpath($system_path)) !== FALSE)
{
$system_path = $_temp.DIRECTORY_SEPARATOR;
}
else
{
// Ensure there's a trailing slash
$system_path = strtr(
rtrim($system_path, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
).DIRECTORY_SEPARATOR;
}
// Is the system path correct?
if ( ! is_dir($system_path))
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME);
exit(3); // EXIT_CONFIG
}
/*
* -------------------------------------------------------------------
* Now that we know the path, set the main path constants
* -------------------------------------------------------------------
*/
// The name of THIS file
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
// Path to the system directory
define('BASEPATH', $system_path);
// Path to the front controller (this file) directory
define('FCPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
// Name of the "system" directory
define('SYSDIR', basename(BASEPATH));
// The path to the "application" directory
if (is_dir($application_folder))
{
if (($_temp = realpath($application_folder)) !== FALSE)
{
$application_folder = $_temp;
}
else
{
$application_folder = strtr(
rtrim($application_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
}
elseif (is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR))
{
$application_folder = BASEPATH.strtr(
trim($application_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
else
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
exit(3); // EXIT_CONFIG
}
define('APPPATH', $application_folder.DIRECTORY_SEPARATOR);
// The path to the "views" directory
if ( ! isset($view_folder[0]) && is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR))
{
$view_folder = APPPATH.'views';
}
elseif (is_dir($view_folder))
{
if (($_temp = realpath($view_folder)) !== FALSE)
{
$view_folder = $_temp;
}
else
{
$view_folder = strtr(
rtrim($view_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
}
elseif (is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR))
{
$view_folder = APPPATH.strtr(
trim($view_folder, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
);
}
else
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
exit(3); // EXIT_CONFIG
}
define('VIEWPATH', $view_folder.DIRECTORY_SEPARATOR);
/*
* --------------------------------------------------------------------
* LOAD THE BOOTSTRAP FILE
* --------------------------------------------------------------------
*
* And away we go...
*/
require_once BASEPATH.'core/CodeIgniter.php';
| zirajmohammed/ICHESS | index.php | PHP | mit | 10,294 |
using System;
namespace Agiil.Domain
{
public interface IIndictesSuccess
{
bool IsSuccess { get; }
}
}
| csf-dev/agiil | Agiil.Domain/IIndictesSuccess.cs | C# | mit | 116 |
var express = require('express');
var router = express.Router();
var fs = require('fs');
var instasync = require('instasync');
var helpers = instasync.helpers;
var queries = helpers.queries;
//set Content type
router.use(function(req,res,next){
res.header("Content-Type", "text/html");
res.header("X-Frame-Options","DENY");
next();
});
router.param('room_name', function(req,res, next, room_name){
queries.getRoom(room_name).then(function(room){
if (!room){
var error = new Error("Room not found.");
error.status = 404;
throw error;
}
req.room = room;
return req.db("rooms").where("room_id",'=',room.room_id).increment("visits", 1);
}).then(function(){
next();
}).catch(function(err){
return next(err);
});
});
router.get('/:room_name', function(req, res, next) {
res.render('rooms/index', {
title: 'InstaSync - '+req.room.room_name+"'s room!",
room: req.room
}, function(err,html){ //not sure this is needed
if(err) {
next(err);
} else {
res.end(html);
}
});
});
module.exports = router;
| Mewte/InstaSync | web/routes/rooms.js | JavaScript | mit | 1,039 |
<?php
namespace ORM\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* GdConfigurations
*
* @ORM\Table(name="gd_configurations")
* @ORM\Entity
*/
class GdConfigurations
{
/**
* @var integer
*
* @ORM\Column(name="configuration_id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $configurationId;
/**
* @var string
*
* @ORM\Column(name="status", type="string", nullable=false)
*/
private $status;
/**
* @var \DateTime
*
* @ORM\Column(name="date_created", type="datetime", nullable=false)
*/
private $dateCreated;
/**
* @var \DateTime
*
* @ORM\Column(name="last_updated", type="datetime", nullable=false)
*/
private $lastUpdated;
/**
* @var integer
*
* @ORM\Column(name="account_id", type="integer", nullable=false)
*/
private $accountId;
/**
* @var string
*
* @ORM\Column(name="configuration_name", type="string", length=100, nullable=false)
*/
private $configurationName;
/**
* @var string
*
* @ORM\Column(name="content", type="text", nullable=false)
*/
private $content;
/**
* @var integer
*
* @ORM\Column(name="num_rows_generated", type="integer", nullable=true)
*/
private $numRowsGenerated = '0';
/**
* Get configurationId
*
* @return integer
*/
public function getConfigurationId()
{
return $this->configurationId;
}
/**
* Set status
*
* @param string $status
* @return GdConfigurations
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set dateCreated
*
* @param \DateTime $dateCreated
* @return GdConfigurations
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* @return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* Set lastUpdated
*
* @param \DateTime $lastUpdated
* @return GdConfigurations
*/
public function setLastUpdated($lastUpdated)
{
$this->lastUpdated = $lastUpdated;
return $this;
}
/**
* Get lastUpdated
*
* @return \DateTime
*/
public function getLastUpdated()
{
return $this->lastUpdated;
}
/**
* Set accountId
*
* @param integer $accountId
* @return GdConfigurations
*/
public function setAccountId($accountId)
{
$this->accountId = $accountId;
return $this;
}
/**
* Get accountId
*
* @return integer
*/
public function getAccountId()
{
return $this->accountId;
}
/**
* Set configurationName
*
* @param string $configurationName
* @return GdConfigurations
*/
public function setConfigurationName($configurationName)
{
$this->configurationName = $configurationName;
return $this;
}
/**
* Get configurationName
*
* @return string
*/
public function getConfigurationName()
{
return $this->configurationName;
}
/**
* Set content
*
* @param string $content
* @return GdConfigurations
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set numRowsGenerated
*
* @param integer $numRowsGenerated
* @return GdConfigurations
*/
public function setNumRowsGenerated($numRowsGenerated)
{
$this->numRowsGenerated = $numRowsGenerated;
return $this;
}
/**
* Get numRowsGenerated
*
* @return integer
*/
public function getNumRowsGenerated()
{
return $this->numRowsGenerated;
}
}
| Barbar76/ExpTech-PHP | src/ORM/MainBundle/Entity/GdConfigurations.php | PHP | mit | 4,351 |
#ifndef AWTIMETABLE_HPP
#define AWTIMETABLE_HPP
#include <string>
#include <vector>
#include <SFML/Graphics/Font.hpp>
namespace sf
{
class RenderWindow;
}
namespace aw
{
namespace priv
{
struct Player
{
std::string name;
float time;
sf::Color color;
Player() : Player("", 0, sf::Color::White)
{}
Player(const std::string &pName, float pTime, const sf::Color &pColor):
name(pName), time(pTime), color(pColor)
{
}
};
}
class TimeTable
{
public:
TimeTable();
void addPlayer(const std::string &name, float time, const sf::Color &color);
void removePlayer(const std::string &name);
void removePlayer(std::size_t index);
void addTime(const std::string &name, float time);
void addTime(std::size_t index, float time);
void addLadderTime(const std::string &name, float time);
void clearLadder();
void resetTimes();
void render(sf::RenderWindow &window);
void clear();
std::size_t getPlayerIndex(const std::string &name);
float getTime(std::size_t index);
private:
void orderTimeTable();
private:
std::vector<priv::Player> m_currentHighscore;
std::vector<priv::Player> m_ladder;
sf::Font m_font;
};
}
#endif | AlexAUT/Kroniax_Cpp | include/modules/game/timeTable.hpp | C++ | mit | 1,196 |
package ordering;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class OrderingExamples {
private CidadeByPopulacao cidadeByPopulacao;
private CidadeByImpostos cidadeByImpostos;
@Before
public void setUp() throws Exception {
cidadeByPopulacao = new CidadeByPopulacao();
cidadeByImpostos = new CidadeByImpostos();
}
@Test
public void ordena_pela_populacao_reverse() throws Exception {
Cidade cidade1 = new Cidade(11000, 55.0);
Cidade cidade2 = new Cidade(8000, 45.0);
Cidade cidade3 = new Cidade(10000, 33.8);
List<Cidade> cidades = Lists.newArrayList(cidade1, cidade2, cidade3);
Ordering<Cidade> reverse = Ordering.from(cidadeByPopulacao).reverse();
Collections.sort(cidades, reverse);
assertThat(cidades.get(0), is(cidade1));
}
@Test
public void oredenacao_composta() {
Cidade cidade1 = new Cidade(10000, 55.0);
Cidade cidade2 = new Cidade(10000, 45.0);
Cidade cidade3 = new Cidade(10000, 33.8);
List<Cidade> cidades = Lists.newArrayList(cidade1, cidade2, cidade3);
Ordering<Cidade> composto = Ordering.from(cidadeByPopulacao).compound(cidadeByImpostos);
Collections.sort(cidades, composto);
assertThat(cidades.get(0), is(cidade3));
}
@Test
public void greatestOf() {
Cidade cidade1 = new Cidade(10000, 55.0);
Cidade cidade2 = new Cidade(9000, 45.0);
Cidade cidade3 = new Cidade(8000, 33.8);
List<Cidade> cidades = Lists.newArrayList(cidade1, cidade2, cidade3);
Ordering<Cidade> byPopulation = Ordering.from(cidadeByPopulacao);
List<Cidade> greatestPopulations = byPopulation.greatestOf(cidades, 2);
assertThat(greatestPopulations.size(), is(2));
assertThat(greatestPopulations.get(0), is(cidade1));
assertThat(greatestPopulations.get(1), is(cidade2));
}
@Test
public void leastOf() {
Cidade cidade1 = new Cidade(10000, 55.0);
Cidade cidade2 = new Cidade(9000, 45.0);
Cidade cidade3 = new Cidade(8000, 33.8);
List<Cidade> cidades = Lists.newArrayList(cidade1, cidade2, cidade3);
Ordering<Cidade> byPopulation = Ordering.from(cidadeByPopulacao);
List<Cidade> greatestPopulations = byPopulation.leastOf(cidades, 2);
assertThat(greatestPopulations.size(), is(2));
assertThat(greatestPopulations.get(0), is(cidade3));
assertThat(greatestPopulations.get(1), is(cidade2));
}
}
| alexrios/guava-labs | src/test/java/ordering/OrderingExamples.java | Java | mit | 2,760 |
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '2=ejgw$ytij5oh#i$eeg237okk8m3nkm@5a!j%&1(s2j7yl2xm'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'auth_functional.RequestFixtureMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = ''
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'tests/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'django_paginator_ext',
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| anler/django-paginator-ext | tests/settings.py | Python | mit | 5,356 |
/**
* body-checker
* A simple tool to protect your API against bad request parameters
*
* @param {Object} body request body
* @param {Object} options configuration parmaters
* @param {Function} cb callback function
*
*/
var check = require('check-types');
module.exports = function(body, options, cb) {
var valid_keys = Object.keys(options);
// Ensure all passed params are legal
for(var p in body) {
if(valid_keys.indexOf(p) === -1) {
return cb(new Error('Illegal parameter "' + p + '" provided'));
}
}
for(var key in options) {
// Check for Required
if(options[key].required && !body[key]) {
switch(options[key].type) {
case 'number':
case 'integer':
if(check.zero(body[key])) break;
default:
return cb(new Error('Missing required parameter ' + key));
}
}
// Optional default handler
if(!options[key].required && !body[key] && options[key].default) {
body[key] = options[key].default;
}
if (check[options[key].type](body[key]) === false) {
// Check types for all but "any" allow undefined properties when not required
if (body[key] === undefined && !options[key].required) {
// skip when key is not present and is not required
} else {
if(options[key].type !== 'any') {
return cb(new Error('Expected "' + key + '" to be type ' + options[key].type + ', instead found ' + typeof body[key]));
}
}
}
}
// All is good
return cb(null, body);
};
| luceracloud/body-checker | index.js | JavaScript | mit | 1,461 |
using System.Linq;
namespace Powercards.Core.Cards
{
[CardInfo(CardSet.Intrigue, 5, true)]
public class Upgrade : CardBase, IActionCard
{
#region methods
public void Play(TurnContext context)
{
context.ActivePlayer.DrawCards(1, context);
context.RemainingActions += 1;
if (!context.ActivePlayer.Hand.IsEmpty)
{
var trashCard = context.Game.Dialog.Select(context, context.ActivePlayer, context.ActivePlayer.Hand,
new CountValidator<ICard>(1), "Select a card to Upgrade.").Single();
if (trashCard.MoveTo(context.ActivePlayer.Hand, context.Game.TrashZone, CardMovementVerb.Trash, context))
context.Game.Log.LogTrash(context.ActivePlayer, trashCard);
var costOfCardToGain = trashCard.GetCost(context, context.ActivePlayer) + 1;
var pilesToGain = context.Game.Supply.AllPiles.Where(new NonEmptyPileValidator().Then(new CardCostValidator(context, context.ActivePlayer, costOfCardToGain)).Validate).ToArray();
if (pilesToGain.Length > 0)
{
var gainPile = context.Game.Dialog.Select(context, context.ActivePlayer, pilesToGain,
new CountValidator<CardSupplyPile>(1),
string.Format("Select a card to gain of exact cost of {0}", costOfCardToGain)).Single();
if (gainPile.TopCard.MoveTo(gainPile, context.ActivePlayer.DiscardArea, CardMovementVerb.Gain, context))
context.Game.Log.LogGain(context.ActivePlayer, gainPile);
}
else
{
context.Game.Log.LogMessage("{0} could gain no card of appropriate cost", context.ActivePlayer);
}
}
else
{
context.Game.Log.LogMessage(context.ActivePlayer.Name + " did not have any cards to upgrade.");
}
}
#endregion
}
}
| whence/powerlife | csharp/Core/Cards/Upgrade.cs | C# | mit | 2,052 |
require 'spec_helper'
describe Chouette::Exporter, :type => :model do
subject { Chouette::Exporter.new("test") }
describe "#export" do
let(:chouette_command) { double :run! => true }
before(:each) do
allow(subject).to receive_messages :chouette_command => chouette_command
end
it "should use specified file in -outputFile option" do
expect(chouette_command).to receive(:run!).with(hash_including(:output_file => File.expand_path('file')))
subject.export "file"
end
it "should use specified format in -format option" do
expect(chouette_command).to receive(:run!).with(hash_including(:format => 'DUMMY'))
subject.export "file", :format => "dummy"
end
end
end
| afimb/ninoxe | spec/models/chouette/exporter_spec.rb | Ruby | mit | 739 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ServiceFabric::V6_2_0_9
module Models
#
# Describes how the scaling should be performed
#
class ScalingPolicyDescription
include MsRestAzure
# @return [ScalingTriggerDescription] Specifies the trigger associated
# with this scaling policy
attr_accessor :scaling_trigger
# @return [ScalingMechanismDescription] Specifies the mechanism
# associated with this scaling policy
attr_accessor :scaling_mechanism
#
# Mapper for ScalingPolicyDescription class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ScalingPolicyDescription',
type: {
name: 'Composite',
class_name: 'ScalingPolicyDescription',
model_properties: {
scaling_trigger: {
client_side_validation: true,
required: true,
serialized_name: 'ScalingTrigger',
type: {
name: 'Composite',
polymorphic_discriminator: 'Kind',
uber_parent: 'ScalingTriggerDescription',
class_name: 'ScalingTriggerDescription'
}
},
scaling_mechanism: {
client_side_validation: true,
required: true,
serialized_name: 'ScalingMechanism',
type: {
name: 'Composite',
polymorphic_discriminator: 'Kind',
uber_parent: 'ScalingMechanismDescription',
class_name: 'ScalingMechanismDescription'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | data/azure_service_fabric/lib/6.2.0.9/generated/azure_service_fabric/models/scaling_policy_description.rb | Ruby | mit | 2,007 |
/// <reference path="0-bosun.ts" />
bosunApp.directive('tsResults', function() {
return {
templateUrl: '/partials/results.html',
link: (scope: any, elem, attrs) => {
scope.isSeries = v => {
return typeof (v) === 'object';
};
},
};
});
bosunApp.directive('tsComputations', () => {
return {
scope: {
computations: '=tsComputations',
time: '=',
header: '=',
},
templateUrl: '/partials/computations.html',
link: (scope: any, elem: any, attrs: any) => {
if (scope.time) {
var m = moment.utc(scope.time);
scope.timeParam = "&date=" + encodeURIComponent(m.format("YYYY-MM-DD")) + "&time=" + encodeURIComponent(m.format("HH:mm"));
}
scope.btoa = (v: any) => {
return encodeURIComponent(btoa(v));
};
},
};
});
function fmtDuration(v: any) {
var diff = moment.duration(v, 'milliseconds');
var f;
if (Math.abs(v) < 60000) {
return diff.format('ss[s]');
}
return diff.format('d[d]hh[h]mm[m]ss[s]');
}
function fmtTime(v: any) {
var m = moment(v).utc();
var now = moment().utc();
var msdiff = now.diff(m);
var ago = '';
var inn = '';
if (msdiff >= 0) {
ago = ' ago';
} else {
inn = 'in ';
}
return m.format() + ' (' + inn + fmtDuration(msdiff) + ago + ')';
}
function parseDuration(v: string) {
var pattern = /(\d+)(d|y|n|h|m|s)-ago/;
var m = pattern.exec(v);
return moment.duration(parseInt(m[1]), m[2].replace('n', 'M'))
}
interface ITimeScope extends IBosunScope {
noLink: string;
}
bosunApp.directive("tsTime", function() {
return {
link: function(scope: ITimeScope, elem: any, attrs: any) {
scope.$watch(attrs.tsTime, (v: any) => {
var m = moment(v).utc();
var text = fmtTime(v);
if (attrs.tsEndTime) {
var diff = moment(scope.$eval(attrs.tsEndTime)).diff(m);
var duration = fmtDuration(diff);
text += " for " + duration;
}
if (attrs.noLink) {
elem.text(text);
} else {
var el = document.createElement('a');
el.text = text;
el.href = 'http://www.timeanddate.com/worldclock/converted.html?iso=';
el.href += m.format('YYYYMMDDTHHmm');
el.href += '&p1=0';
angular.forEach(scope.timeanddate, (v, k) => {
el.href += '&p' + (k + 2) + '=' + v;
});
elem.html(el);
}
});
},
};
});
bosunApp.directive("tsTimeUnix", function() {
return {
link: function(scope: ITimeScope, elem: any, attrs: any) {
scope.$watch(attrs.tsTimeUnix, (v: any) => {
var m = moment(v * 1000).utc();
var text = fmtTime(m);
if (attrs.tsEndTime) {
var diff = moment(scope.$eval(attrs.tsEndTime)).diff(m);
var duration = fmtDuration(diff);
text += " for " + duration;
}
if (attrs.noLink) {
elem.text(text);
} else {
var el = document.createElement('a');
el.text = text;
el.href = 'http://www.timeanddate.com/worldclock/converted.html?iso=';
el.href += m.format('YYYYMMDDTHHmm');
el.href += '&p1=0';
angular.forEach(scope.timeanddate, (v, k) => {
el.href += '&p' + (k + 2) + '=' + v;
});
elem.html(el);
}
});
},
};
});
bosunApp.directive("tsSince", function() {
return {
link: function(scope: IBosunScope, elem: any, attrs: any) {
scope.$watch(attrs.tsSince, (v: any) => {
var m = moment(v).utc();
elem.text(m.fromNow());
});
},
};
});
bosunApp.directive("tooltip", function() {
return {
link: function(scope: IGraphScope, elem: any, attrs: any) {
angular.element(elem[0]).tooltip({ placement: "bottom" });
},
};
});
bosunApp.directive('tsTab', () => {
return {
link: (scope: any, elem: any, attrs: any) => {
var ta = elem[0];
elem.keydown(evt => {
if (evt.ctrlKey) {
return;
}
// This is so shift-enter can be caught to run a rule when tsTab is called from
// the rule page
if (evt.keyCode == 13 && evt.shiftKey) {
return;
}
switch (evt.keyCode) {
case 9: // tab
evt.preventDefault();
var v = ta.value;
var start = ta.selectionStart;
ta.value = v.substr(0, start) + "\t" + v.substr(start);
ta.selectionStart = ta.selectionEnd = start + 1;
return;
case 13: // enter
if (ta.selectionStart != ta.selectionEnd) {
return;
}
evt.preventDefault();
var v = ta.value;
var start = ta.selectionStart;
var sub = v.substr(0, start);
var last = sub.lastIndexOf("\n") + 1
for (var i = last; i < sub.length && /[ \t]/.test(sub[i]); i++)
;
var ws = sub.substr(last, i - last);
ta.value = v.substr(0, start) + "\n" + ws + v.substr(start);
ta.selectionStart = ta.selectionEnd = start + 1 + ws.length;
}
});
},
};
});
interface JQuery {
tablesorter(v: any): JQuery;
linedtextarea(): void;
}
bosunApp.directive('tsresizable', () => {
return {
restrict: 'A',
scope: {
callback: '&onResize'
},
link: function postLink(scope: any, elem: any, attrs) {
elem.resizable();
elem.on('resizestop', function(evt, ui) {
if (scope.callback) { scope.callback(); }
});
}
};
});
bosunApp.directive('tsTableSort', ['$timeout', ($timeout: ng.ITimeoutService) => {
return {
link: (scope: ng.IScope, elem: any, attrs: any) => {
$timeout(() => {
$(elem).tablesorter({
sortList: scope.$eval(attrs.tsTableSort),
});
});
},
};
}]);
// https://gist.github.com/mlynch/dd407b93ed288d499778
bosunApp.directive('autofocus', ['$timeout', function($timeout) {
return {
restrict: 'A',
link : function($scope, $element) {
$timeout(function() {
$element[0].focus();
});
}
}
}]);
bosunApp.directive('tsTimeLine', () => {
var tsdbFormat = d3.time.format.utc("%Y/%m/%d-%X");
function parseDate(s: any) {
return moment.utc(s).toDate();
}
var margin = {
top: 10,
right: 10,
bottom: 30,
left: 250,
};
return {
link: (scope: any, elem: any, attrs: any) => {
scope.shown = {};
scope.collapse = (i: any, entry: any, v: any) => {
scope.shown[i] = !scope.shown[i];
if (scope.loadTimelinePanel && entry && scope.shown[i]) {
scope.loadTimelinePanel(entry, v);
}
};
scope.$watch('alert_history', update);
function update(history: any) {
if (!history) {
return;
}
var entries = d3.entries(history);
if (!entries.length) {
return;
}
entries.sort((a, b) => {
return a.key.localeCompare(b.key);
});
scope.entries = entries;
var values = entries.map(v => { return v.value });
var keys = entries.map(v => { return v.key });
var barheight = 500 / values.length;
barheight = Math.min(barheight, 45);
barheight = Math.max(barheight, 15);
var svgHeight = values.length * barheight + margin.top + margin.bottom;
var height = svgHeight - margin.top - margin.bottom;
var svgWidth = elem.width();
var width = svgWidth - margin.left - margin.right;
var xScale = d3.time.scale.utc().range([0, width]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom');
elem.empty();
var svg = d3.select(elem[0])
.append('svg')
.attr('width', svgWidth)
.attr('height', svgHeight)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
svg.append('g')
.attr('class', 'x axis tl-axis')
.attr('transform', 'translate(0,' + height + ')');
xScale.domain([
d3.min(values, (d: any) => { return d3.min(d.History, (c: any) => { return parseDate(c.Time); }); }),
d3.max(values, (d: any) => { return d3.max(d.History, (c: any) => { return parseDate(c.EndTime); }); }),
]);
var legend = d3.select(elem[0])
.append('div')
.attr('class', 'tl-legend');
var time_legend = legend
.append('div')
.text(values[0].History[0].Time);
var alert_legend = legend
.append('div')
.text(keys[0]);
svg.select('.x.axis')
.transition()
.call(xAxis);
var chart = svg.append('g');
angular.forEach(entries, function(entry: any, i: number) {
chart.selectAll('.bars')
.data(entry.value.History)
.enter()
.append('rect')
.attr('class', (d: any) => { return 'tl-' + d.Status; })
.attr('x', (d: any) => { return xScale(parseDate(d.Time)); })
.attr('y', i * barheight)
.attr('height', barheight)
.attr('width', (d: any) => {
return xScale(parseDate(d.EndTime)) - xScale(parseDate(d.Time));
})
.on('mousemove.x', mousemove_x)
.on('mousemove.y', function(d) {
alert_legend.text(entry.key);
})
.on('click', function(d, j) {
var id = 'panel' + i + '-' + j;
scope.shown['group' + i] = true;
scope.shown[id] = true;
if (scope.loadTimelinePanel) {
scope.loadTimelinePanel(entry, d);
}
scope.$apply();
setTimeout(() => {
var e = $("#" + id);
if (!e) {
console.log('no', id, e);
return;
}
$('html, body').scrollTop(e.offset().top);
});
});
});
chart.selectAll('.labels')
.data(keys)
.enter()
.append('text')
.attr('text-anchor', 'end')
.attr('x', 0)
.attr('dx', '-.5em')
.attr('dy', '.25em')
.attr('y', function(d: any, i: number) { return (i + .5) * barheight; })
.text(function(d: any) { return d; });
chart.selectAll('.sep')
.data(values)
.enter()
.append('rect')
.attr('y', function(d: any, i: number) { return (i + 1) * barheight })
.attr('height', 1)
.attr('x', 0)
.attr('width', width)
.on('mousemove.x', mousemove_x);
function mousemove_x() {
var x = xScale.invert(d3.mouse(this)[0]);
time_legend
.text(tsdbFormat(x));
}
};
},
};
});
var fmtUnits = ['', 'k', 'M', 'G', 'T', 'P', 'E'];
function nfmt(s: any, mult: number, suffix: string, opts: any) {
opts = opts || {};
var n = parseFloat(s);
if (isNaN(n) && typeof s === 'string') {
return s;
}
if (opts.round) n = Math.round(n);
if (!n) return suffix ? '0 ' + suffix : '0';
if (isNaN(n) || !isFinite(n)) return '-';
var a = Math.abs(n);
if (a >= 1) {
var number = Math.floor(Math.log(a) / Math.log(mult));
a /= Math.pow(mult, Math.floor(number));
if (fmtUnits[number]) {
suffix = fmtUnits[number] + suffix;
}
}
var r = a.toFixed(5);
if (a < 1e-5) {
r = a.toString();
}
var neg = n < 0 ? '-' : '';
return neg + (+r) + suffix;
}
bosunApp.filter('nfmt', function() {
return function(s: any) {
return nfmt(s, 1000, '', {});
}
});
bosunApp.filter('bytes', function() {
return function(s: any) {
return nfmt(s, 1024, 'B', { round: true });
}
});
bosunApp.filter('bits', function() {
return function(s: any) {
return nfmt(s, 1024, 'b', { round: true });
}
});
bosunApp.directive('elastic', [
'$timeout',
function($timeout) {
return {
restrict: 'A',
link: function($scope, element) {
$scope.initialHeight = $scope.initialHeight || element[0].style.height;
var resize = function() {
element[0].style.height = $scope.initialHeight;
element[0].style.height = "" + element[0].scrollHeight + "px";
};
element.on("input change", resize);
$timeout(resize, 0);
}
};
}
]);
bosunApp.directive('tsBar', ['$window', 'nfmtFilter', function($window: ng.IWindowService, fmtfilter: any) {
var margin = {
top: 20,
right: 20,
bottom: 0,
left: 200,
};
return {
scope: {
data: '=',
height: '=',
},
link: (scope: any, elem: any, attrs: any) => {
var svgHeight = +scope.height || 150;
var height = svgHeight - margin.top - margin.bottom;
var svgWidth: number;
var width: number;
var xScale = d3.scale.linear();
var yScale = d3.scale.ordinal()
var top = d3.select(elem[0])
.append('svg')
.attr('height', svgHeight)
.attr('width', '100%');
var svg = top
.append('g')
//.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("top")
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
scope.$watch('data', update);
var w = angular.element($window);
scope.$watch(() => {
return w.width();
}, resize, true);
w.bind('resize', () => {
scope.$apply();
});
function resize() {
if (!scope.data) {
return;
}
svgWidth = elem.width();
if (svgWidth <= 0) {
return;
}
margin.left = d3.max(scope.data, (d: any) => { return d.name.length * 8 })
width = svgWidth - margin.left - margin.right;
svgHeight = scope.data.length * 15;
height = svgHeight - margin.top - margin.bottom;
xScale.range([0, width]);
yScale.rangeRoundBands([0, height], .1);
yAxis.scale(yScale);
svg.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
svg.attr('width', svgWidth);
svg.attr('height', height);
top.attr('height', svgHeight);
xAxis.ticks(width / 60);
draw();
}
function update(v: any) {
if (!angular.isArray(v) || v.length == 0) {
return;
}
resize();
}
function draw() {
if (!scope.data) {
return;
}
yScale.domain(scope.data.map((d: any) => { return d.name }));
xScale.domain([0, d3.max(scope.data, (d: any) => { return d.Value })]);
svg.selectAll('g.axis').remove();
//X axis
svg.append("g")
.attr("class", "x axis")
.call(xAxis)
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.selectAll("text")
.style("text-anchor", "end")
var bars = svg.selectAll(".bar").data(scope.data);
bars.enter()
.append("rect")
.attr("class", "bar")
.attr("y", function(d) { return yScale(d.name); })
.attr("height", yScale.rangeBand())
.attr('width', (d: any) => { return xScale(d.Value); })
};
},
};
}]);
bosunApp.directive('tsGraph', ['$window', 'nfmtFilter', function($window: ng.IWindowService, fmtfilter: any) {
var margin = {
top: 10,
right: 10,
bottom: 30,
left: 80,
};
return {
scope: {
data: '=',
annotations: '=',
height: '=',
generator: '=',
brushStart: '=bstart',
brushEnd: '=bend',
enableBrush: '@',
max: '=',
min: '=',
normalize: '=',
annotation: '=',
annotateEnabled: '=',
showAnnotations: '=',
},
template: '<div class="row"></div>' + // chartElemt
'<div class="row col-lg-12"></div>' + // timeElem
'<div class"row">' + // legendAnnContainer
'<div class="col-lg-6"></div>' + // legendElem
'<div class="col-lg-6"></div>' + // annElem
'</div>',
link: (scope: any, elem: any, attrs: any, $compile: any) => {
var chartElem = d3.select(elem.children()[0]);
var timeElem = d3.select(elem.children()[1]);
var legendAnnContainer = angular.element(elem.children()[2]);
var legendElem = d3.select(legendAnnContainer.children()[0]);
if (scope.annotateEnabled) {
var annElem = d3.select(legendAnnContainer.children()[1]);
}
var valueIdx = 1;
if (scope.normalize) {
valueIdx = 2;
}
var svgHeight = +scope.height || 150;
var height = svgHeight - margin.top - margin.bottom;
var svgWidth: number;
var width: number;
var yScale = d3.scale.linear().range([height, 0]);
var xScale = d3.time.scale.utc();
var xAxis = d3.svg.axis()
.orient('bottom');
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.ticks(Math.min(10, height / 20))
.tickFormat(fmtfilter);
var line: any;
switch (scope.generator) {
case 'area':
line = d3.svg.area();
break;
default:
line = d3.svg.line();
}
var brush = d3.svg.brush()
.x(xScale)
.on('brush', brushed)
.on('brushend', annotateBrushed);
var top = chartElem
.append('svg')
.attr('height', svgHeight)
.attr('width', '100%');
var svg = top
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var defs = svg.append('defs')
.append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('height', height);
var chart = svg.append('g')
.attr('pointer-events', 'all')
.attr('clip-path', 'url(#clip)');
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')');
svg.append('g')
.attr('class', 'y axis');
var paths = chart.append('g');
chart.append('g')
.attr('class', 'x brush');
if (scope.annotateEnabled) {
var ann = chart.append('g');
}
top.append('rect')
.style('opacity', 0)
.attr('x', 0)
.attr('y', 0)
.attr('height', height)
.attr('width', margin.left)
.style('cursor', 'pointer')
.on('click', yaxisToggle);
var xloc = timeElem.append('div').attr("class", "col-lg-6");
xloc.style('float', 'left');
var brushText = timeElem.append('div').attr("class", "col-lg-6").append('p').attr("class", "text-right")
var legend = legendElem;
var aLegend = annElem;
var color = d3.scale.ordinal().range([
'#e41a1c',
'#377eb8',
'#4daf4a',
'#984ea3',
'#ff7f00',
'#a65628',
'#f781bf',
'#999999',
]);
var annColor = d3.scale.ordinal().range([
'#e41a1c',
'#377eb8',
'#4daf4a',
'#984ea3',
'#ff7f00',
'#a65628',
'#f781bf',
'#999999',
]);
var mousex = 0;
var mousey = 0;
var oldx = 0;
var hover = svg.append('g')
.attr('class', 'hover')
.style('pointer-events', 'none')
.style('display', 'none');
var hoverPoint = hover.append('svg:circle')
.attr('r', 5);
var hoverRect = hover.append('svg:rect')
.attr('fill', 'white');
var hoverText = hover.append('svg:text')
.style('font-size', '12px');
var focus = svg.append('g')
.attr('class', 'focus')
.style('pointer-events', 'none');
focus.append('line');
var yaxisZero = false;
function yaxisToggle() {
yaxisZero = !yaxisZero;
draw();
}
var drawAnnLegend = () => {
if (scope.annotation) {
aLegend.html('')
var a = scope.annotation;
//var table = aLegend.append('table').attr("class", "table table-condensed")
var table = aLegend.append("div")
var row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("CreationUser")
row.append("div").attr("class", "col-lg-10").text(a.CreationUser)
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Owner")
row.append("div").attr("class", "col-lg-10").text(a.Owner)
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Url")
row.append("div").attr("class", "col-lg-10").append('a')
.attr("xlink:href", a.Url).text(a.Url).on("click", (d) => {
window.open(a.Url, "_blank");
});
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Category")
row.append("div").attr("class", "col-lg-10").text(a.Category)
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Host")
row.append("div").attr("class", "col-lg-10").text(a.Host)
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Message")
row.append("div").attr("class", "col-lg-10").text(a.Message)
}//
};
var drawLegend = _.throttle((normalizeIdx: any) => {
var names = legend.selectAll('.series')
.data(scope.data, (d) => { return d.Name; });
names.enter()
.append('div')
.attr('class', 'series');
names.exit()
.remove();
var xi = xScale.invert(mousex);
xloc.text('Time: ' + fmtTime(xi));
var t = xi.getTime() / 1000;
var minDist = width + height;
var minName: string, minColor: string;
var minX: number, minY: number;
names
.each(function(d: any) {
var idx = bisect(d.Data, t);
if (idx >= d.Data.length) {
idx = d.Data.length - 1;
}
var e = d3.select(this);
var pt = d.Data[idx];
if (pt) {
e.attr('title', pt[normalizeIdx]);
e.text(d.Name + ': ' + fmtfilter(pt[1]));
var ptx = xScale(pt[0] * 1000);
var pty = yScale(pt[normalizeIdx]);
var ptd = Math.sqrt(
Math.pow(ptx - mousex, 2) +
Math.pow(pty - mousey, 2)
);
if (ptd < minDist) {
minDist = ptd;
minX = ptx;
minY = pty;
minName = d.Name + ': ' + pt[1];
minColor = color(d.Name);
}
}
})
.style('color', (d: any) => { return color(d.Name); });
hover
.attr('transform', 'translate(' + minX + ',' + minY + ')');
hoverPoint.style('fill', minColor);
hoverText
.text(minName)
.style('fill', minColor);
var isRight = minX > width / 2;
var isBottom = minY > height / 2;
hoverText
.attr('x', isRight ? -5 : 5)
.attr('y', isBottom ? -8 : 15)
.attr('text-anchor', isRight ? 'end' : 'start');
var node: any = hoverText.node();
var bb = node.getBBox();
hoverRect
.attr('x', bb.x - 1)
.attr('y', bb.y - 1)
.attr('height', bb.height + 2)
.attr('width', bb.width + 2);
var x = mousex;
if (x > width) {
x = 0;
}
focus.select('line')
.attr('x1', x)
.attr('x2', x)
.attr('y1', 0)
.attr('y2', height);
if (extentStart) {
var s = extentStart;
if (extentEnd != extentStart) {
s += ' - ' + extentEnd;
s += ' (' + extentDiff + ')'
}
brushText.text(s);
}
}, 50);
scope.$watchCollection('[data, annotations, showAnnotations]', update);
var showAnnotations = (show: boolean) => {
if (show) {
ann.attr("visibility", "visible");
return;
}
ann.attr("visibility", "hidden");
aLegend.html('');
}
var w = angular.element($window);
scope.$watch(() => {
return w.width();
}, resize, true);
w.bind('resize', () => {
scope.$apply();
});
function resize() {
svgWidth = elem.width();
if (svgWidth <= 0) {
return;
}
width = svgWidth - margin.left - margin.right;
xScale.range([0, width]);
xAxis.scale(xScale);
if (!mousex) {
mousex = width + 1;
}
svg.attr('width', svgWidth);
defs.attr('width', width);
xAxis.ticks(width / 60);
draw();
}
var oldx = 0;
var bisect = d3.bisector((d) => { return d[0]; }).left;
var bisectA = d3.bisector((d) => { return moment(d.StartDate).unix(); }).left;
function update(v: any) {
if (!angular.isArray(v) || v.length == 0) {
return;
}
d3.selectAll(".x.brush").call(brush.clear());
if (scope.annotateEnabled) {
showAnnotations(scope.showAnnotations);
}
resize();
}
function draw() {
if (!scope.data) {
return;
}
if (scope.normalize) {
valueIdx = 2;
}
function mousemove() {
var pt = d3.mouse(this);
mousex = pt[0];
mousey = pt[1];
drawLegend(valueIdx);
}
scope.data.map((data: any, i: any) => {
var max = d3.max(data.Data, (d: any) => { return d[1]; });
data.Data.map((d: any, j: any) => {
d.push(d[1] / max * 100 || 0)
});
});
line.y((d: any) => { return yScale(d[valueIdx]); });
line.x((d: any) => { return xScale(d[0] * 1000); });
var xdomain = [
d3.min(scope.data, (d: any) => { return d3.min(d.Data, (c: any) => { return c[0]; }); }) * 1000,
d3.max(scope.data, (d: any) => { return d3.max(d.Data, (c: any) => { return c[0]; }); }) * 1000,
];
if (!oldx) {
oldx = xdomain[1];
}
xScale.domain(xdomain);
var ymin = d3.min(scope.data, (d: any) => { return d3.min(d.Data, (c: any) => { return c[1]; }); });
var ymax = d3.max(scope.data, (d: any) => { return d3.max(d.Data, (c: any) => { return c[valueIdx]; }); });
var diff = (ymax - ymin) / 50;
if (!diff) {
diff = 1;
}
ymin -= diff;
ymax += diff;
if (yaxisZero) {
if (ymin > 0) {
ymin = 0;
} else if (ymax < 0) {
ymax = 0;
}
}
var ydomain = [ymin, ymax];
if (angular.isNumber(scope.min)) {
ydomain[0] = +scope.min;
}
if (angular.isNumber(scope.max)) {
ydomain[valueIdx] = +scope.max;
}
yScale.domain(ydomain);
if (scope.generator == 'area') {
line.y0(yScale(0));
}
svg.select('.x.axis')
.transition()
.call(xAxis);
svg.select('.y.axis')
.transition()
.call(yAxis);
svg.append('text')
.attr("class", "ylabel")
.attr("transform", "rotate(-90)")
.attr("y", -margin.left)
.attr("x", - (height / 2))
.attr("dy", "1em")
.text(_.uniq(scope.data.map(v => { return v.Unit })).join("; "));
if (scope.annotateEnabled) {
var rowId = {}; // annotation Id -> rowId
var rowEndDate = {}; // rowId -> EndDate
var maxRow = 0;
for (var i = 0; i < scope.annotations.length; i++) {
if (i == 0) {
rowId[scope.annotations[i].Id] = 0;
rowEndDate[0] = scope.annotations[0].EndDate;
continue;
}
for (var row = 0; row <= maxRow + 1; row++) {
if (row == maxRow + 1) {
rowId[scope.annotations[i].Id] = row;
rowEndDate[row] = scope.annotations[i].EndDate;
maxRow += 1
break;
}
if (rowEndDate[row] < scope.annotations[i].StartDate) {
rowId[scope.annotations[i].Id] = row;
rowEndDate[row] = scope.annotations[i].EndDate;
break;
}
}
}
var annotations = ann.selectAll('.annotation')
.data(scope.annotations, (d) => { return d.Id; });
annotations.enter()
.append("svg:a")
.append('rect')
.attr('visilibity', () => {
if (scope.showAnnotations) {
return "visible";
}
return "hidden";
})
.attr("y", (d) => { return rowId[d.Id] * ((height * .05) + 2) })
.attr("height", height * .05)
.attr("class", "annotation")
.attr("stroke", (d) => { return annColor(d.Id) })
.attr("stroke-opacity", .5)
.attr("fill", (d) => { return annColor(d.Id) })
.attr("fill-opacity", 0.1)
.attr("stroke-width", 1)
.attr("x", (d: any) => { return xScale(moment(d.StartDate).utc().unix() * 1000); })
.attr("width", (d: any) => {
var startT = moment(d.StartDate).utc().unix() * 1000
var endT = moment(d.EndDate).utc().unix() * 1000
if (startT == endT) {
return 3
}
return xScale(endT) - xScale(startT)
})
.on("mouseenter", (ann) => {
if (!scope.showAnnotations) {
return;
}
if (ann) {
scope.annotation = ann;
drawAnnLegend();
}
scope.$apply();
})
.on("click", () => {
if (!scope.showAnnotations) {
return;
}
angular.element('#modalShower').trigger('click');
});
annotations.exit().remove();
}
var queries = paths.selectAll('.line')
.data(scope.data, (d) => { return d.Name; });
switch (scope.generator) {
case 'area':
queries.enter()
.append('path')
.attr('stroke', (d: any) => { return color(d.Name); })
.attr('class', 'line')
.style('fill', (d: any) => { return color(d.Name); });
break;
default:
queries.enter()
.append('path')
.attr('stroke', (d: any) => { return color(d.Name); })
.attr('class', 'line');
}
queries.exit()
.remove();
queries
.attr('d', (d: any) => { return line(d.Data); })
.attr('transform', null)
.transition()
.ease('linear')
.attr('transform', 'translate(' + (xScale(oldx) - xScale(xdomain[1])) + ')');
chart.select('.x.brush')
.call(brush)
.selectAll('rect')
.attr('height', height)
.on('mouseover', () => {
hover.style('display', 'block');
})
.on('mouseout', () => {
hover.style('display', 'none');
})
.on('mousemove', mousemove);
chart.select('.x.brush .extent')
.style('stroke', '#fff')
.style('fill-opacity', '.125')
.style('shape-rendering', 'crispEdges');
oldx = xdomain[1];
drawLegend(valueIdx);
};
var extentStart: string;
var extentEnd: string;
var extentDiff: string;
function brushed() {
var e: any;
e = d3.event.sourceEvent;
if (e.shiftKey) {
return;
}
var extent = brush.extent();
extentStart = datefmt(extent[0]);
extentEnd = datefmt(extent[1]);
extentDiff = fmtDuration(moment(extent[1]).diff(moment(extent[0])));
drawLegend(valueIdx);
if (scope.enableBrush && extentEnd != extentStart) {
scope.brushStart = extentStart;
scope.brushEnd = extentEnd;
scope.$apply();
}
}
function annotateBrushed() {
if (!scope.annotateEnabled) {
return;
}
var e: any
e = d3.event.sourceEvent;
if (!e.shiftKey) {
return;
}
var extent = brush.extent();
scope.annotation = new Annotation();
scope.annotation.StartDate = moment(extent[0]).utc().format(timeFormat);
scope.annotation.EndDate = moment(extent[1]).utc().format(timeFormat);
scope.$apply(); // This logs a console type error, but also works .. odd.
angular.element('#modalShower').trigger('click');
}
var mfmt = 'YYYY/MM/DD-HH:mm:ss';
function datefmt(d: any) {
return moment(d).utc().format(mfmt);
}
},
};
}]);
| seekingalpha/bosun | cmd/bosun/web/static/js/directives.ts | TypeScript | mit | 41,222 |
require "rdg/analysis/propagater"
module RDG
module Control
class Case < Analysis::Propagater
register_analyser :case
def prepare
@expression, *@consequences = nodes
end
def internal_flow_edges
nodes.each_cons(2).to_a
end
def start_node
@expression
end
def end_nodes
@consequences
end
end
end
end
| mutiny/rdg | lib/rdg/control/case.rb | Ruby | mit | 400 |
import * as React from "react";
import * as ReactDOM from "react-dom";
import Start from "./awesome-sec-audit.tsx";
// Dedicating a file to this basic call allows us to import all major modules
// into test suites.
const item = document.getElementById("content");
if (item == null) {
console.log("Render container missing");
}
else {
ReactDOM.render(
<Start />,
item
);
}
| technion/awesome-sec-audit | assets/awesome-sec-audit-run.tsx | TypeScript | mit | 402 |
'use strict';
/* Services */
angular.module('nhsApp.services', [])
.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
})
.factory('nhsApiService', function($http) {
var nhsAPI = {};
nhsAPI.getLetters = function() {
return $http({
method: 'POST',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/atoz.json"
});
};
nhsAPI.getLetter = function(letter) {
return $http({
method: 'POST',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/atoz/"+ letter + ".json"
});
};
nhsAPI.getCondition = function(condition) {
return $http({
method: 'GET',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/articles/"+ condition + ".json"
});
};
nhsAPI.getDetail = function(condition, detail) {
return $http({
method: 'GET',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/articles/" + condition + "/" + detail + ".html"
});
};
/* Useful to avoid all the extra mark-up in the Html version */
nhsAPI.getXmlDetail = function(condition, detail) {
return $http({
method: 'GET',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/articles/" + condition + "/" + detail + ".xml"
});
};
return nhsAPI;
}); | denniskenny/Nhs-Choices-Angular | app/js/services.js | JavaScript | mit | 1,529 |
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
def setup
@user = users(:dave)
end
test 'should get new' do
get :new
assert_response :success
end
test 'should redirect update_user_filters when not logged in' do
patch :update_user_filters, params: { play_types: ['tenth'] }, xhr: true
assert_not flash.empty?
assert_redirected_to login_url
end
test 'should overwrite play types on a valid update_user_filters request' do
log_in_here(@user)
assert_equal ['regular'], @user.play_types
patch :update_user_filters, params: { play_types: ['tenth'] }, xhr: true
assert_response :success
assert_equal ['tenth'], @user.reload.play_types
end
test 'should filter out invalid play types' do
log_in_here(@user)
assert_equal ['regular'], @user.play_types
# rubocop:disable WordArray
patch :update_user_filters, params: { play_types: ['not_a_type', 'kids'] },
xhr: true
# rubocop:enable WordArray
assert_response :success
assert_equal ['kids'], @user.reload.play_types
end
test 'should fail gracefully when update_user_filters given invalid types' do
log_in_here(@user)
assert_equal ['regular'], @user.play_types
patch :update_user_filters, params: { play_types: 'not-an-array' },
xhr: true
assert_response :bad_request
assert_equal ['regular'], @user.reload.play_types
end
end
| steve-mcclellan/j-scorer | test/controllers/users_controller_test.rb | Ruby | mit | 1,478 |
<?php
namespace Analatica\ForfaitBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('AnalaticaForfaitBundle:Default:index.html.twig', array('name' => $name));
}
}
| portalsway2/AnalaticaV2 | src/Analatica/ForfaitBundle/Controller/DefaultController.php | PHP | mit | 317 |
import * as decimal from 'break_infinity.js';
declare global {
interface Decimal {
cos(): Decimal
lessThanOrEqualTo(other: decimal.Decimal): boolean
lessThan(other: decimal.Decimal): boolean
greaterThan(other: decimal.Decimal): boolean
greaterThanOrEqualTo(other: decimal.Decimal): boolean
}
}
| scorzy/IdleAnt | src/index.d.ts | TypeScript | mit | 321 |
export { default } from 'ember-disqus/components/disqus-comment-count'; | sir-dunxalot/ember-disqus | app/components/disqus-comment-count.js | JavaScript | mit | 71 |
import re, sys, os
from gunicorn.app.wsgiapp import run
if __name__ == '__main__':
sys.argv[0] = __file__
sys.exit(run())
| commitmachine/pg-hoffserver | pghoffserver/gunicorn_python.py | Python | mit | 131 |
package org.nkjmlab.twitter.util;
import java.io.File;
import java.io.FileReader;
import java.util.List;
import org.nkjmlab.twitter.conf.TwitterConfig;
import org.nkjmlab.util.io.FileUtils;
import org.nkjmlab.util.json.JsonUtils;
import net.arnx.jsonic.JSON;
import net.arnx.jsonic.JSONException;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.NullAuthorization;
public class TwitterFactory {
public static void main(String[] args) throws Exception {
TwitterConfig conf = JSON.decode(
new FileReader(new File("conf/twitter.conf")), TwitterConfig.class);
Twitter twitter = TwitterFactory.create(conf);
User user = twitter.verifyCredentials();
System.out.println(user);
List<Status> statuses = twitter.getHomeTimeline();
System.out.println("Showing home timeline.");
for (Status status : statuses) {
System.out.println(
status.getUser().getName() + ":" + status.getText());
}
}
public static Twitter create(TwitterConfig conf) {
Twitter twitter = new twitter4j.TwitterFactory().getInstance();
if (!(twitter.getAuthorization() instanceof NullAuthorization)) {
return twitter;
}
AccessToken accessToken = new AccessToken(conf.getAccessToken(),
conf.getAccessTokenSecret());
twitter.setOAuthConsumer(conf.getConsumerKey(),
conf.getConsumerSecret());
twitter.setOAuthAccessToken(accessToken);
return twitter;
}
public static Twitter create(String fileName) {
try {
return create(JsonUtils.decode(FileUtils.getFileReader(fileName), TwitterConfig.class));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public static Twitter getSingleton() {
return twitter4j.TwitterFactory.getSingleton();
}
}
| nkjmlab/TweetAnalyzerCore | src/main/java/org/nkjmlab/twitter/util/TwitterFactory.java | Java | mit | 1,771 |
/* @flow */
require('./sharedMocks');
jest.mock('glob', () => ({
sync: jest.fn(() => ['path/to/main/entry.js']),
}));
jest.mock('fs-extra');
// $FlowIgnore
const entries = require('entries.json');
const buildEntries = require('../buildEntries');
const defaultGSConfig = require('../../defaults/glueStickConfig');
const generate = require('gluestick-generators').default;
describe('config/webpack/buildEntries', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should build all client entries', () => {
// $FlowIgnore
expect(buildEntries(defaultGSConfig, {}, entries, [])).toEqual({
main: `./${defaultGSConfig.clientEntryInitPath}/main`,
home: `./${defaultGSConfig.clientEntryInitPath}/home`,
});
// $FlowIgnore
expect(generate.mock.calls[0][0]).toEqual({
generatorName: 'clientEntryInit',
entityName: 'main',
options: {
component: 'path/to/main/component',
routes: 'path/to/main/routes',
reducers: 'path/to/main/reducers',
config: `${defaultGSConfig.configPath}/${defaultGSConfig.applicationConfigPath}`,
clientEntryInitPath: defaultGSConfig.clientEntryInitPath,
plugins: [],
enableErrorOverlay: true,
},
});
// $FlowIgnore
expect(generate.mock.calls[1][0]).toEqual({
generatorName: 'clientEntryInit',
entityName: 'home',
options: {
component: 'path/to/home/component',
routes: 'path/to/home/routes',
reducers: 'path/to/home/reducers',
config: 'path/to/home/config',
clientEntryInitPath: defaultGSConfig.clientEntryInitPath,
plugins: [],
enableErrorOverlay: true,
},
});
});
it('should build only a signle client entry', () => {
const homeEntry = Object.keys(entries)
.filter(k => k === '/home')
.reduce((acc, key) => ({ ...acc, [key]: entries[key] }), {});
// $FlowIgnore
expect(buildEntries(defaultGSConfig, {}, homeEntry, [])).toEqual({
home: `./${defaultGSConfig.clientEntryInitPath}/home`,
});
// $FlowIgnore
expect(generate.mock.calls[0][0]).toEqual({
generatorName: 'clientEntryInit',
entityName: 'home',
options: {
component: 'path/to/home/component',
routes: 'path/to/home/routes',
reducers: 'path/to/home/reducers',
config: 'path/to/home/config',
clientEntryInitPath: defaultGSConfig.clientEntryInitPath,
plugins: [],
enableErrorOverlay: true,
},
});
});
});
| TrueCar/gluestick | packages/gluestick/src/config/webpack/__tests__/buildEntries.test.js | JavaScript | mit | 2,533 |
/**
* Created by peter on 9/19/16.
*/
// ==UserScript==
// @name Super Rookie
// @namespace http://v.numag.net/grease/
// @description locate new posts on piratebay
// @include https://thepiratebay.org/top/*
// ==/UserScript==
(function () {
function $x() {
var x='';
var node=document;
var type=0;
var fix=true;
var i=0;
var cur;
function toArray(xp) {
var final=[], next;
while (next=xp.iterateNext()) {
final.push(next);
}
return final;
}
while (cur=arguments[i++]) {
switch (typeof cur) {
case "string": x+=(x=='') ? cur : " | " + cur; continue;
case "number": type=cur; continue;
case "object": node=cur; continue;
case "boolean": fix=cur; continue;
}
}
if (fix) {
if (type==6) type=4;
if (type==7) type=5;
}
// selection mistake helper
if (!/^\//.test(x)) x="//"+x;
// context mistake helper
if (node!=document && !/^\./.test(x)) x="."+x;
var result=document.evaluate(x, node, null, type, null);
if (fix) {
// automatically return special type
switch (type) {
case 1: return result.numberValue;
case 2: return result.stringValue;
case 3: return result.booleanValue;
case 8:
case 9: return result.singleNodeValue;
}
}
return fix ? toArray(result) : result;
};
$x("/html/body/div[@id='main-content']/table[@id='searchResult']/tbody/tr/td[2]/a").map(function (element) {
if (localStorage.getItem(element.href) == undefined){
localStorage.setItem(element.href,1);
element.parentNode.style= 'background: darkorange;';
}
else {
localStorage.setItem(element.href,parseInt(localStorage.getItem(element.href))+1);
};
});
})();
| motord/elbowgrease | grease/superrookie.user.js | JavaScript | mit | 2,103 |
/* @flow */
const babelJest = require('babel-jest');
module.exports = babelJest.createTransformer({
presets: [
[
'env',
{
targets: {
ie: 11,
edge: 14,
firefox: 45,
chrome: 49,
safari: 10,
node: '6.11',
},
modules: 'commonjs',
},
],
'react',
],
plugins: [
'transform-flow-strip-types',
'transform-class-properties',
'transform-object-rest-spread',
],
});
| boldr/boldr-ui | internal/jest/transform.js | JavaScript | mit | 489 |
import { name, autoService } from 'knifecycle';
import type { LogService } from 'common-services';
import type { JsonValue } from 'type-fest';
export type APMService<T = string> = (type: T, data: JsonValue) => void;
export default name('apm', autoService(initAPM));
const noop = () => undefined;
/**
* Application monitoring service that simply log stringified contents.
* @function
* @param {Object} services
* The services to inject
* @param {Function} [services.log]
* A logging function
* @return {Promise<Object>}
* A promise of the apm service.
*/
async function initAPM<T = string>({
log = noop,
}: {
log: LogService;
}): Promise<APMService<T>> {
log('debug', '❤️ - Initializing the APM service.');
return (type, data) => log('info', type, JSON.stringify(data));
}
| nfroidure/whook | packages/whook-http-transaction/src/services/apm.ts | TypeScript | mit | 806 |
//******************************************************************************************************
// Serialization.cs - Gbtc
//
// Copyright © 2012, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 06/08/2006 - Pinal C. Patel
// Original version of source code generated.
// 09/09/2008 - J. Ritchie Carroll
// Converted to C#.
// 09/09/2008 - J. Ritchie Carroll
// Added TryGetObject overloads.
// 02/16/2009 - Josh L. Patterson
// Edited Code Comments.
// 08/4/2009 - Josh L. Patterson
// Edited Code Comments.
// 09/14/2009 - Stephen C. Wills
// Added new header and license agreement.
// 04/06/2011 - Pinal C. Patel
// Modified GetString() method to not check for the presence of Serializable attribute on the
// object being serialized since this is not required by the XmlSerializer.
// 04/08/2011 - Pinal C. Patel
// Moved Serialize() and Deserialize() methods from GSF.Services.ServiceModel.Serialization class
// in GSF.Services.dll to consolidate serialization methods.
// 12/14/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.Xml.Serialization;
using GSF.IO;
using GSF.Reflection;
namespace GSF
{
#region [ Enumerations ]
/// <summary>
/// Indicates the format of <see cref="object"/> serialization or deserialization.
/// </summary>
public enum SerializationFormat
{
/// <summary>
/// <see cref="object"/> is serialized or deserialized using <see cref="DataContractSerializer"/> to XML (eXtensible Markup Language) format.
/// </summary>
/// <remarks>
/// <see cref="object"/> can be serialized or deserialized using <see cref="XmlSerializer"/> by adding the <see cref="XmlSerializerFormatAttribute"/> to the <see cref="object"/>.
/// </remarks>
Xml,
/// <summary>
/// <see cref="object"/> is serialized or deserialized using <see cref="DataContractJsonSerializer"/> to JSON (JavaScript Object Notation) format.
/// </summary>
Json,
/// <summary>
/// <see cref="object"/> is serialized or deserialized using <see cref="BinaryFormatter"/> to binary format.
/// </summary>
Binary
}
#endregion
/// <summary>
/// Common serialization related functions.
/// </summary>
public static class Serialization
{
#region [ Obsolete ]
/// <summary>
/// Creates a clone of a serializable object.
/// </summary>
/// <typeparam name="T">The type of the cloned object.</typeparam>
/// <param name="sourceObject">The type source to be cloned.</param>
/// <returns>A clone of <paramref name="sourceObject"/>.</returns>
[Obsolete("This method will be removed in future builds.")]
public static T CloneObject<T>(T sourceObject)
{
return Deserialize<T>(Serialize(sourceObject, SerializationFormat.Binary), SerializationFormat.Binary);
}
/// <summary>
/// Performs XML deserialization on the XML string and returns the typed object for it.
/// </summary>
/// <remarks>
/// This function will throw an error during deserialization if the input data is invalid,
/// consider using TryGetObject to prevent needing to implement exception handling.
/// </remarks>
/// <exception cref="System.InvalidOperationException">
/// An error occurred during deserialization. The original exception is available using
/// the InnerException property.
/// </exception>
/// <typeparam name="T">The type of the object to create from the serialized string <paramref name="serializedObject"/>.</typeparam>
/// <param name="serializedObject">A <see cref="string"/> representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <returns>A type T based on <paramref name="serializedObject"/>.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static T GetObject<T>(string serializedObject)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(serializedObject));
}
/// <summary>
/// Attempts XML deserialization on the XML string and returns the typed object for it.
/// </summary>
/// <typeparam name="T">The generic type T that is to be deserialized.</typeparam>
/// <param name="serializedObject"><see cref="string"/> that contains the serialized representation of the object.</param>
/// <param name="deserializedObject">An object of type T that is passed in as the container to hold the deserialized object from the string <paramref name="serializedObject"/>.</param>
/// <returns><see cref="bool"/> value indicating if the deserialization was successful.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static bool TryGetObject<T>(string serializedObject, out T deserializedObject)
{
try
{
deserializedObject = GetObject<T>(serializedObject);
return true;
}
catch
{
deserializedObject = default(T);
return false;
}
}
/// <summary>
/// Performs binary deserialization on the byte array and returns the typed object for it.
/// </summary>
/// <remarks>
/// This function will throw an error during deserialization if the input data is invalid,
/// consider using TryGetObject to prevent needing to implement exception handling.
/// </remarks>
/// <exception cref="System.Runtime.Serialization.SerializationException">Serialized object data is invalid or length is 0.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission. </exception>
/// <typeparam name="T">The type of the object to create from the serialized byte array <paramref name="serializedObject"/>.</typeparam>
/// <param name="serializedObject">A <see cref="byte"/> array representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <returns>A type T based on <paramref name="serializedObject"/>.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static T GetObject<T>(byte[] serializedObject)
{
BinaryFormatter serializer = new BinaryFormatter();
return (T)serializer.Deserialize(new MemoryStream(serializedObject));
}
/// <summary>
/// Attempts binary deserialization on the byte array and returns the typed object for it.
/// </summary>
/// <param name="serializedObject">A <see cref="byte"/> array representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <param name="deserializedObject">A type T object, passed by reference, that is used to be hold the deserialized object.</param>
/// <typeparam name="T">The generic type T that is to be deserialized.</typeparam>
/// <returns>A <see cref="bool"/> which indicates whether the deserialization process was successful.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static bool TryGetObject<T>(byte[] serializedObject, out T deserializedObject)
{
try
{
deserializedObject = GetObject<T>(serializedObject);
return true;
}
catch
{
deserializedObject = default(T);
return false;
}
}
/// <summary>
/// Performs binary deserialization on the byte array and returns the object for it.
/// </summary>
/// <remarks>
/// This function will throw an error during deserialization if the input data is invalid,
/// consider using TryGetObject to prevent needing to implement exception handling.
/// </remarks>
/// <exception cref="System.Runtime.Serialization.SerializationException">Serialized object data is invalid or length is 0.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission. </exception>
/// <param name="serializedObject">A <see cref="byte"/> array representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <returns>An <see cref="object"/> based on <paramref name="serializedObject"/>.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static object GetObject(byte[] serializedObject)
{
BinaryFormatter serializer = new BinaryFormatter();
return serializer.Deserialize(new MemoryStream(serializedObject));
}
/// <summary>
/// Attempts binary deserialization on the byte array and returns the typed object for it.
/// </summary>
/// <param name="serializedObject">A <see cref="byte"/> array representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <param name="deserializedObject">An <see cref="object"/>, passed by reference, that is used to be hold the deserialized object.</param>
/// <returns>A <see cref="bool"/> which indicates whether the deserialization process was successful.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static bool TryGetObject(byte[] serializedObject, out object deserializedObject)
{
try
{
deserializedObject = GetObject(serializedObject);
return true;
}
catch
{
deserializedObject = null;
return false;
}
}
/// <summary>
/// Performs XML serialization on the serializable object and returns the output as string.
/// </summary>
/// <param name="serializableObject">The serializable object.</param>
/// <returns>An XML representation of the object if the specified object can be serialized; otherwise an empty string.</returns>
[Obsolete("This method will be removed in future builds, use the Serialize() method instead.")]
public static string GetString(object serializableObject)
{
StringWriter serializedObject = new StringWriter();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
serializer.Serialize(serializedObject, serializableObject);
return serializedObject.ToString();
}
/// <summary>
/// Performs binary serialization on the serializable object and returns the output as byte array.
/// </summary>
/// <param name="serializableObject">The serializable object.</param>
/// <returns>A byte array representation of the object if the specified object can be serialized; otherwise an empty array.</returns>
[Obsolete("This method will be removed in future builds, use the Serialize() method instead.")]
public static byte[] GetBytes(object serializableObject)
{
return GetStream(serializableObject).ToArray();
}
/// <summary>
/// Performs binary serialization on the serializable object and returns the serialized object as a stream.
/// </summary>
/// <param name="serializableObject">The serializable object.</param>
/// <returns>A memory stream representation of the object if the specified object can be serialized; otherwise an empty stream.</returns>
[Obsolete("This method will be removed in future builds, use the Serialize() method instead.")]
public static MemoryStream GetStream(object serializableObject)
{
MemoryStream dataStream = new MemoryStream();
if (serializableObject.GetType().IsSerializable)
{
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(dataStream, serializableObject);
}
return dataStream;
}
#endregion
#region [ Legacy ]
/// <summary>
/// Serialization binder used to deserialize files that were serialized using the old library frameworks
/// (TVA Code Library, Time Series Framework, TVA.PhasorProtocols, and PMU Connection Tester) into classes
/// in the Grid Solutions Framework.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly SerializationBinder LegacyBinder = new LegacySerializationBinder();
// Serialization binder used to deserialize files that were serialized using the old library frameworks.
private class LegacySerializationBinder : SerializationBinder
{
/// <summary>
/// Controls the binding of a serialized object to a type.
/// </summary>
/// <param name="assemblyName">Specifies the <see cref="Assembly"/> name of the serialized object.</param>
/// <param name="typeName">Specifies the <see cref="Type"/> name of the serialized object.</param>
/// <returns>The type of the object the formatter creates a new instance of.</returns>
public override Type BindToType(string assemblyName, string typeName)
{
Type newType;
string newTypeName;
// Perform namespace transformations that occurred when migrating to the Grid Solutions Framework
// from various older versions of code with different namespaces
newTypeName = typeName
.Replace("TVA.", "GSF.")
.Replace("TimeSeriesFramework.", "GSF.TimeSeries.")
.Replace("ConnectionTester.", "GSF.PhasorProtocols.") // PMU Connection Tester namespace
.Replace("TVA.Phasors.", "GSF.PhasorProtocols.") // 2007 TVA Code Library namespace
.Replace("Tva.Phasors.", "GSF.PhasorProtocols.") // 2008 TVA Code Library namespace
.Replace("BpaPdcStream", "BPAPDCstream") // 2013 GSF uppercase phasor protocol namespace
.Replace("FNet", "FNET") // 2013 GSF uppercase phasor protocol namespace
.Replace("Iec61850_90_5", "IEC61850_90_5") // 2013 GSF uppercase phasor protocol namespace
.Replace("Ieee1344", "IEEE1344") // 2013 GSF uppercase phasor protocol namespace
.Replace("IeeeC37_118", "IEEEC37_118"); // 2013 GSF uppercase phasor protocol namespace
// Check for 2009 TVA Code Library namespace
if (newTypeName.StartsWith("PhasorProtocols", StringComparison.Ordinal))
newTypeName = "GSF." + newTypeName;
// Check for 2014 LineFrequency type in the GSF phasor protocol namespace
if (newTypeName.Equals("GSF.PhasorProtocols.LineFrequency", StringComparison.Ordinal))
newTypeName = "GSF.Units.EE.LineFrequency";
try
{
// Search each assembly in the current application domain for the type with the transformed name
return AssemblyInfo.FindType(newTypeName);
}
catch
{
// Fall back on more brute force search when simple search fails
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
newType = assembly.GetType(newTypeName);
if ((object)newType != null)
return newType;
}
catch
{
// Ignore errors that occur when attempting to load
// types from assemblies as we may still be able to
// load the type from a different assembly
}
}
}
// No type found; return null
return null;
}
}
#endregion
/// <summary>
/// Serializes an <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the <paramref name="serializableObject"/>.</typeparam>
/// <param name="serializableObject"><see cref="Object"/> to be serialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializableObject"/> is to be serialized.</param>
/// <returns>An <see cref="Array"/> of <see cref="Byte"/> of the serialized <see cref="Object"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="serializableObject"/> is null.</exception>
/// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
public static byte[] Serialize<T>(T serializableObject, SerializationFormat serializationFormat)
{
// FYI, using statement will not work here as this creates a read-only variable that cannot be passed by reference
Stream stream = null;
try
{
stream = new BlockAllocatedMemoryStream();
Serialize(serializableObject, serializationFormat, stream);
return ((BlockAllocatedMemoryStream)stream).ToArray();
}
finally
{
if ((object)stream != null)
stream.Dispose();
}
}
/// <summary>
/// Serializes an <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the <paramref name="serializableObject"/>.</typeparam>
/// <param name="serializableObject"><see cref="Object"/> to be serialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializableObject"/> is to be serialized.</param>
/// <param name="serializedOutput"><see cref="Stream"/> where the <paramref name="serializableObject"/> is to be serialized.</param>
/// <exception cref="ArgumentNullException"><paramref name="serializedOutput"/> or <paramref name="serializableObject"/> is null.</exception>
/// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
public static void Serialize<T>(T serializableObject, SerializationFormat serializationFormat, Stream serializedOutput)
{
if ((object)serializedOutput == null)
throw new ArgumentNullException(nameof(serializedOutput));
if ((object)serializableObject == null)
throw new ArgumentNullException(nameof(serializableObject));
// Serialize object to the provided stream.
if (serializationFormat == SerializationFormat.Xml)
{
if (typeof(T).GetCustomAttributes(typeof(XmlSerializerFormatAttribute), false).Length > 0)
{
// Serialize to XML format using XmlSerializer.
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(serializedOutput, serializableObject);
}
else
{
// Serialize to XML format using DataContractSerializer.
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(serializedOutput, serializableObject);
}
}
else if (serializationFormat == SerializationFormat.Json)
{
// Serialize to JSON format.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(serializedOutput, serializableObject);
}
else if (serializationFormat == SerializationFormat.Binary)
{
// Serialize to binary format.
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(serializedOutput, serializableObject);
}
else
{
// Serialization format is not supported.
throw new NotSupportedException(string.Format("{0} serialization is not supported", serializationFormat));
}
// Seek to the beginning of the serialized output stream.
serializedOutput.Position = 0;
}
/// <summary>
/// Deserializes a serialized <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the deserialized <see cref="Object"/> to be returned.</typeparam>
/// <param name="serializedObject"><see cref="Array"/> of <see cref="Byte"/>s containing the serialized <see cref="Object"/> that is to be deserialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializedObject"/> was serialized.</param>
/// <returns>The deserialized <see cref="Object"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="serializedObject"/> is null.</exception>
/// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
public static T Deserialize<T>(byte[] serializedObject, SerializationFormat serializationFormat)
{
if ((object)serializedObject == null)
throw new ArgumentNullException(nameof(serializedObject));
using (MemoryStream stream = new MemoryStream(serializedObject))
{
return Deserialize<T>(stream, serializationFormat);
}
}
/// <summary>
/// Deserializes a serialized <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the deserialized <see cref="Object"/> to be returned.</typeparam>
/// <param name="serializedObject"><see cref="Stream"/> containing the serialized <see cref="Object"/> that is to be deserialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializedObject"/> was serialized.</param>
/// <returns>The deserialized <see cref="Object"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="serializedObject"/> is null.</exception>
/// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
public static T Deserialize<T>(Stream serializedObject, SerializationFormat serializationFormat)
{
if ((object)serializedObject == null)
throw new ArgumentNullException(nameof(serializedObject));
// Deserialize the serialized object.
T deserializedObject;
if (serializationFormat == SerializationFormat.Xml)
{
if (typeof(T).GetCustomAttributes(typeof(XmlSerializerFormatAttribute), false).Length > 0)
{
// Deserialize from XML format using XmlSerializer.
XmlSerializer serializer = new XmlSerializer(typeof(T));
deserializedObject = (T)serializer.Deserialize(serializedObject);
}
else
{
// Deserialize from XML format using DataContractSerializer.
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
deserializedObject = (T)serializer.ReadObject(serializedObject);
}
}
else if (serializationFormat == SerializationFormat.Json)
{
// Deserialize from JSON format.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
deserializedObject = (T)serializer.ReadObject(serializedObject);
}
else if (serializationFormat == SerializationFormat.Binary)
{
// Deserialize from binary format.
BinaryFormatter serializer = new BinaryFormatter();
serializer.Binder = LegacyBinder;
deserializedObject = (T)serializer.Deserialize(serializedObject);
}
else
{
// Serialization format is not supported.
throw new NotSupportedException(string.Format("{0} serialization is not supported", serializationFormat));
}
return deserializedObject;
}
/// <summary>
/// Attempts to deserialize a serialized <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the deserialized <see cref="Object"/> to be returned.</typeparam>
/// <param name="serializedObject"><see cref="Array"/> of <see cref="Byte"/>s containing the serialized <see cref="Object"/> that is to be deserialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializedObject"/> was serialized.</param>
/// <param name="deserializedObject">Deserialized <see cref="Object"/>.</param>
/// <returns><c>true</c>if deserialization succeeded; otherwise <c>false</c>.</returns>
public static bool TryDeserialize<T>(byte[] serializedObject, SerializationFormat serializationFormat, out T deserializedObject)
{
deserializedObject = default(T);
try
{
deserializedObject = Deserialize<T>(serializedObject, serializationFormat);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Attempts to deserialize a serialized <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the deserialized <see cref="Object"/> to be returned.</typeparam>
/// <param name="serializedObject"><see cref="Stream"/> containing the serialized <see cref="Object"/> that is to be deserialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializedObject"/> was serialized.</param>
/// <param name="deserializedObject">Deserialized <see cref="Object"/>.</param>
/// <returns><c>true</c>if deserialization succeeded; otherwise <c>false</c>.</returns>
public static bool TryDeserialize<T>(Stream serializedObject, SerializationFormat serializationFormat, out T deserializedObject)
{
deserializedObject = default(T);
try
{
deserializedObject = Deserialize<T>(serializedObject, serializationFormat);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Gets <see cref="SerializationInfo"/> value for specified <paramref name="name"/>; otherwise <paramref name="defaultValue"/>.
/// </summary>
/// <typeparam name="T">Type of parameter to get from <see cref="SerializationInfo"/>.</typeparam>
/// <param name="info"><see cref="SerializationInfo"/> object that contains deserialized values.</param>
/// <param name="name">Name of deserialized parameter to retrieve.</param>
/// <param name="defaultValue">Default value to return if <paramref name="name"/> does not exist or cannot be deserialized.</param>
/// <returns>Value for specified <paramref name="name"/>; otherwise <paramref name="defaultValue"/></returns>
/// <remarks>
/// <see cref="SerializationInfo"/> do not have a direct way of determining if an item with a specified name exists, so when calling
/// one of the Get(n) functions you will simply get a <see cref="SerializationException"/> if the parameter does not exist; similarly
/// you will receive this exception if the parameter fails to properly deserialize. This extension method protects against both of
/// these failures and returns a default value if the named parameter does not exist or cannot be deserialized.
/// </remarks>
public static T GetOrDefault<T>(this SerializationInfo info, string name, T defaultValue)
{
try
{
return (T)info.GetValue(name, typeof(T));
}
catch (SerializationException)
{
return defaultValue;
}
}
}
} | rmc00/gsf | Source/Libraries/GSF.Core/Serialization.cs | C# | mit | 30,963 |
/**
* Created by gkarak on 28/7/2016.
*/
'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var lodash = require('lodash');
var prompts = require('../../services/prompts');
var buildContext = require('../../services/build-context');
var pathNames = require('../../services/path-names');
var append = require('../../services/append');
module.exports = yeoman.Base.extend({
prompting: function () {
this.log('Generating ' + chalk.red('model') + ' for mongoose and api endpoints');
return this.prompt(this.options.objectName ? [] : prompts.angularObjectPrompts(this))
.then(function (props) {
this.props = props;
}.bind(this));
},
saveConfig: function () {
this.config.set('objectName', this.props.objectName);
this.config.set('objectTitle', this.props.objectTitle);
this.config.set('objectUrl', this.props.objectUrl);
},
writing: function () {
var templatePaths = [
'models/_object-name_.js.ejs',
'routes/api/_object-name_s.js.ejs'
];
if (this.options.objectName) lodash.extend(this.props, this.options);
var context = buildContext({
objectName: this.props.objectName,
objectTitle: this.props.objectTitle
});
var $this = this;
templatePaths.forEach(function (templatePath) {
$this.fs.copyTpl(
$this.templatePath(templatePath),
$this.destinationPath(pathNames(templatePath, $this.props)),
context
);
});
// Modify files: append model route to express app
var templatePath = 'app.js';
this.fs.copy(
this.destinationPath(templatePath), this.destinationPath(templatePath), {
process: function (content) {
return append.expressRoute(content, $this.props.objectName, $this.props.objectTitle, $this.props.objectUrl);
}
});
// Modify files: append model require to mongoose service
templatePath = this.destinationPath('services', 'mongoose.js');
this.fs.copy(templatePath, templatePath, {
process: function (content) {
return append.mongoose(content, $this.props.objectUrl);
}
});
}
});
| Wtower/generator-makrina | generators/model/index.js | JavaScript | mit | 2,151 |
<?php
$color = strip_tags(htmlspecialchars($_POST['color']));
$age = strip_tags(htmlspecialchars($_POST['age']));
$industry = strip_tags(htmlspecialchars($_POST['industry']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$to = 'christina.ccicolor@gmail.com';
$email_subject = "Feedback From Fundamental Color Tools Form";
$email_body = "You have received a new message from your Fundamental Color Tools feedback form.\n\n"."Here are the details:\n\nWhat is your favourite way to choose colors?: $color\n\nIf Other please specify:\n $message\n\nWhat is your age?: $age\n\nDo you work in the color industry or do you represent the consumer market?: $industry";
$headers = "From: ccicolor@ccirewrite.site\n";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
| KarismaSoni/CCI-Rewrite | app/bin/fundamental_contact.php | PHP | mit | 785 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Name: Ion Auth
*
* Version: 2.5.2
*
* Author: Ben Edmunds
* ben.edmunds@gmail.com
* @benedmunds
*
* Added Awesomeness: Phil Sturgeon
*
* Location: http://github.com/benedmunds/CodeIgniter-Ion-Auth
*
* Created: 10.01.2009
*
* Description: Modified auth system based on redux_auth with extensive customization. This is basically what Redux Auth 2 should be.
* Original Author name has been kept but that does not mean that the method has not been modified.
*
* Requirements: PHP5 or above
*
*/
/*
| -------------------------------------------------------------------------
| Tables.
| -------------------------------------------------------------------------
| Database table names.
*/
$config['tables']['users'] = 'users';
$config['tables']['groups'] = 'groups';
$config['tables']['users_groups'] = 'users_groups';
$config['tables']['login_attempts'] = 'login_attempts';
/*
| Users table column and Group table column you want to join WITH.
|
| Joins from users.id
| Joins from groups.id
*/
$config['join']['users'] = 'user_id';
$config['join']['groups'] = 'group_id';
/*
| -------------------------------------------------------------------------
| Hash Method (sha1 or bcrypt)
| -------------------------------------------------------------------------
| Bcrypt is available in PHP 5.3+
|
| IMPORTANT: Based on the recommendation by many professionals, it is highly recommended to use
| bcrypt instead of sha1.
|
| NOTE: If you use bcrypt you will need to increase your password column character limit to (80)
|
| Below there is "default_rounds" setting. This defines how strong the encryption will be,
| but remember the more rounds you set the longer it will take to hash (CPU usage) So adjust
| this based on your server hardware.
|
| If you are using Bcrypt the Admin password field also needs to be changed in order to login as admin:
| $2y$: $2y$08$200Z6ZZbp3RAEXoaWcMA6uJOFicwNZaqk4oDhqTUiFXFe63MG.Daa
| $2a$: $2a$08$6TTcWD1CJ8pzDy.2U3mdi.tpl.nYOR1pwYXwblZdyQd9SL16B7Cqa
|
| Be careful how high you set max_rounds, I would do your own testing on how long it takes
| to encrypt with x rounds.
|
| salt_prefix: Used for bcrypt. Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix
| Versions 5.3.7 or greater should use the default of "$2y$".
*/
$config['hash_method'] = 'bcrypt'; // sha1 or bcrypt, bcrypt is STRONGLY recommended
$config['default_rounds'] = 8; // This does not apply if random_rounds is set to true
$config['random_rounds'] = FALSE;
$config['min_rounds'] = 5;
$config['max_rounds'] = 9;
$config['salt_prefix'] = version_compare(PHP_VERSION, '5.3.7', '<') ? '$2a$' : '$2y$';
/*
| -------------------------------------------------------------------------
| Authentication options.
| -------------------------------------------------------------------------
| maximum_login_attempts: This maximum is not enforced by the library, but is
| used by $this->ion_auth->is_max_login_attempts_exceeded().
| The controller should check this function and act
| appropriately. If this variable set to 0, there is no maximum.
*/
$config['site_title'] = "Example.com"; // Site Title, example.com
$config['admin_email'] = "admin@example.com"; // Admin Email, admin@example.com
$config['default_group'] = 'members'; // Default group, use name
$config['admin_group'] = 'admin'; // Default administrators group, use name
$config['identity'] = 'email'; // A database column which is used to login with
$config['min_password_length'] = 8; // Minimum Required Length of Password
$config['max_password_length'] = 20; // Maximum Allowed Length of Password
$config['email_activation'] = FALSE; // Email Activation for registration
$config['manual_activation'] = FALSE; // Manual Activation for registration
$config['remember_users'] = TRUE; // Allow users to be remembered and enable auto-login
$config['user_expire'] = 86500; // How long to remember the user (seconds). Set to zero for no expiration
$config['user_extend_on_login'] = FALSE; // Extend the users cookies every time they auto-login
$config['track_login_attempts'] = FALSE; // Track the number of failed login attempts for each user or ip.
$config['track_login_ip_address'] = TRUE; // Track login attempts by IP Address, if FALSE will track based on identity. (Default: TRUE)
$config['maximum_login_attempts'] = 3; // The maximum number of failed login attempts.
$config['lockout_time'] = 600; // The number of seconds to lockout an account due to exceeded attempts
$config['forgot_password_expiration'] = 0; // The number of milliseconds after which a forgot password request will expire. If set to 0, forgot password requests will not expire.
/*
| -------------------------------------------------------------------------
| Cookie options.
| -------------------------------------------------------------------------
| remember_cookie_name Default: remember_code
| identity_cookie_name Default: identity
*/
$config['remember_cookie_name'] = 'remember_code';
$config['identity_cookie_name'] = 'identity';
/*
| -------------------------------------------------------------------------
| Email options.
| -------------------------------------------------------------------------
| email_config:
| 'file' = Use the default CI config or use from a config file
| array = Manually set your email config settings
*/
$config['use_ci_email'] = TRUE; // Send Email using the builtin CI email class, if false it will return the code and the identity
$config['email_config'] = array(
'protocol' => 'mail',
'mailtype' => 'html'
);
/*
| -------------------------------------------------------------------------
| Email templates.
| -------------------------------------------------------------------------
| Folder where email templates are stored.
| Default: auth/
*/
$config['email_templates'] = 'auth/email/';
/*
| -------------------------------------------------------------------------
| Activate Account Email Template
| -------------------------------------------------------------------------
| Default: activate.tpl.php
*/
$config['email_activate'] = 'activate.tpl.php';
/*
| -------------------------------------------------------------------------
| Forgot Password Email Template
| -------------------------------------------------------------------------
| Default: forgot_password.tpl.php
*/
$config['email_forgot_password'] = 'forgot_password.tpl.php';
/*
| -------------------------------------------------------------------------
| Forgot Password Complete Email Template
| -------------------------------------------------------------------------
| Default: new_password.tpl.php
*/
$config['email_forgot_password_complete'] = 'new_password.tpl.php';
/*
| -------------------------------------------------------------------------
| Salt options
| -------------------------------------------------------------------------
| salt_length Default: 22
|
| store_salt: Should the salt be stored in the database?
| This will change your password encryption algorithm,
| default password, 'password', changes to
| fbaa5e216d163a02ae630ab1a43372635dd374c0 with default salt.
*/
$config['salt_length'] = 22;
$config['store_salt'] = FALSE;
/*
| -------------------------------------------------------------------------
| Message Delimiters.
| -------------------------------------------------------------------------
*/
$config['delimiters_source'] = 'config'; // "config" = use the settings defined here, "form_validation" = use the settings defined in CI's form validation library
$config['message_start_delimiter'] = '<p>'; // Message start delimiter
$config['message_end_delimiter'] = '</p>'; // Message end delimiter
$config['error_start_delimiter'] = '<p>'; // Error message start delimiter
$config['error_end_delimiter'] = '</p>'; // Error message end delimiter
/* End of file ion_auth.php */
/* Location: ./application/config/ion_auth.php */
| dbmeister/codeigniter3_hmvc_ion_auth | application/modules/auth/config/ion_auth.php | PHP | mit | 8,490 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using PlaylistSharpLib;
namespace PlaylistSharpTest.Unit
{
[TestFixture]
public class SerialTest
{
[Test]
public void Playlist_Avec3Elem_XPSF()
{
var playlist = new Playlist
{
Tracks = new List<PlaylistTrack>
{
new PlaylistTrack {Title = "title1", Location = "location1"},
new PlaylistTrack {Title = string.Empty, Location = "location2"},
new PlaylistTrack {Title = null, Location = "location3"}
},
Type = PlaylistType.XPSF
};
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
Assert.AreEqual(list, list2);
Assert.AreEqual(3, playlist2.Tracks.ToList().Count);
}
[Test]
public void Playlist_Avec3Elem_M3U()
{
var playlist = new Playlist
{
Tracks = new List<PlaylistTrack>
{
new PlaylistTrack {Title = "title1", Location = "location1"},
new PlaylistTrack {Title = string.Empty, Location = "location2"},
new PlaylistTrack {Title = null, Location = "location3"}
},
Type = PlaylistType.M3U
};
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
Assert.AreEqual(list, list2);
Assert.AreEqual(3, playlist2.Tracks.ToList().Count);
}
[Test]
[ExpectedException]
public void Playlist_AvecNullElem_XPSF()
{
var playlist = new Playlist
{
Tracks = null,
Type = PlaylistType.XPSF
};
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
}
[Test]
[ExpectedException]
public void Playlist_AvecNullElem_M3U()
{
var playlist = new Playlist
{
Tracks = null,
Type = PlaylistType.M3U
};
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
}
[Test]
[ExpectedException]
public void Playlist_Avec0ElemValide_XPSF()
{
var playlist = new Playlist
{
Tracks = new List<PlaylistTrack>
{
new PlaylistTrack {Title = string.Empty, Location = null},
new PlaylistTrack {Title = string.Empty, Location = string.Empty},
new PlaylistTrack {Title = null, Location = null},
new PlaylistTrack {Title = null, Location = string.Empty}
},
Type = PlaylistType.XPSF
};
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
}
[Test]
[ExpectedException]
public void Playlist_Avec0ElemValide_M3U()
{
var playlist = new Playlist
{
Tracks = new List<PlaylistTrack>
{
new PlaylistTrack {Title = string.Empty, Location = null},
new PlaylistTrack {Title = string.Empty, Location = string.Empty},
new PlaylistTrack {Title = null, Location = null},
new PlaylistTrack {Title = null, Location = string.Empty}
},
Type = PlaylistType.M3U
};
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
}
[Test]
public void Playlist_Avec10Elem_XPSF()
{
var playlist = new Playlist
{
Tracks = new List<PlaylistTrack>
{
new PlaylistTrack {Title = "title1", Location = "location1"},
new PlaylistTrack {Title = string.Empty, Location = "location2"},
new PlaylistTrack {Title = null, Location = "location3"},
new PlaylistTrack {Title = "title2", Location = "location4"},
new PlaylistTrack {Title = "title3", Location = null},
new PlaylistTrack {Title = "title4", Location = "location5"},
new PlaylistTrack {Title = "title5", Location = "location6"},
new PlaylistTrack {Title = "title6", Location = string.Empty},
new PlaylistTrack {Title = null, Location = "location7"},
new PlaylistTrack {Title = "", Location = "location8"},
new PlaylistTrack {Title = string.Empty, Location = "location9"},
new PlaylistTrack {Title = "title7", Location = ""},
new PlaylistTrack {Title = null, Location = "location10"}
},
Type = PlaylistType.XPSF
};
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
Assert.AreEqual(list, list2);
Assert.AreEqual(10, playlist2.Tracks.ToList().Count);
}
[Test]
public void Playlist_Avec10Elem_M3U()
{
var playlist = new Playlist
{
Tracks = new List<PlaylistTrack>
{
new PlaylistTrack {Title = "title1", Location = "location1"},
new PlaylistTrack {Title = string.Empty, Location = "location2"},
new PlaylistTrack {Title = null, Location = "location3"},
new PlaylistTrack {Title = "title2", Location = "location4"},
new PlaylistTrack {Title = "title3", Location = null},
new PlaylistTrack {Title = "title4", Location = "location5"},
new PlaylistTrack {Title = "title5", Location = "location6"},
new PlaylistTrack {Title = "title6", Location = string.Empty},
new PlaylistTrack {Title = null, Location = "location7"},
new PlaylistTrack {Title = "", Location = "location8"},
new PlaylistTrack {Title = string.Empty, Location = "location9"},
new PlaylistTrack {Title = "title7", Location = ""},
new PlaylistTrack {Title = null, Location = "location10"} },
Type = PlaylistType.M3U
};
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
Assert.AreEqual(list, list2);
Assert.AreEqual(10, playlist2.Tracks.ToList().Count);
}
[Test]
public void Playlist_Avec460Elem_XPSF()
{
const int nbTrack = 460;
var playlist = new Playlist
{
Tracks = new List<PlaylistTrack>() ,
Type = PlaylistType.XPSF
};
var listTrack = playlist.Tracks.ToList();
for (int i = 0; i < nbTrack; i++)
listTrack.Add(new PlaylistTrack {Title = "Title" + i, Location = "location" + i });
playlist.Tracks = listTrack;
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
Assert.AreEqual(list, list2);
Assert.AreEqual(nbTrack, playlist2.Tracks.ToList().Count);
}
[Test]
public void Playlist_Avec460Elem_M3U()
{
const int nbTrack = 460;
var playlist = new Playlist
{
Tracks = new List<PlaylistTrack> (),
Type = PlaylistType.M3U
};
var listTrack = playlist.Tracks.ToList();
for (int i = 0; i < nbTrack; i++)
listTrack.Add(new PlaylistTrack { Title = "Title" + i, Location = "location" + i });
playlist.Tracks = listTrack;
string list = playlist.ToString(playlist.Type);
var playlist2 = new Playlist(playlist.Type, list);
string list2 = playlist2.ToString(playlist2.Type);
Assert.AreEqual(list, list2);
Assert.AreEqual(nbTrack, playlist2.Tracks.ToList().Count);
}
}
} | aloisdg/PlaylistSharp | PlaylistSharpTest.Unit/SerialTest.cs | C# | mit | 9,302 |
package com.maxifier.guice.mbean;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Module;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.annotations.Test;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
/**
* Project: Maxifier
* Date: 08.11.2009
* Time: 14:55:33
* <p/>
* Copyright (c) 1999-2009 Magenta Corporation Ltd. All Rights Reserved.
* Magenta Technology proprietary and confidential.
* Use is subject to license terms.
*
* @author Aleksey Didik
*/
public class DoubleStartTest {
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
@Test
public void testDoubleStart() throws InterruptedException, MBeanRegistrationException, InstanceAlreadyExistsException, NotCompliantMBeanException, InstanceNotFoundException {
MBeanServer server = Mockito.mock(MBeanServer.class);
Mockito.when(server.registerMBean(Mockito.any(), Mockito.any(ObjectName.class))).thenAnswer(new Answer<Object>() {
int count = 0;
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
if (++count != 2) {
return null;
} else {
throw new InstanceAlreadyExistsException();
}
}
});
Module module = new AbstractModule() {
@Override
protected void configure() {
bind(Foo.class).asEagerSingleton();
}
};
Guice.createInjector(new MBeanModule("test", server), module);
Guice.createInjector(new MBeanModule("test", server), module);
Mockito.verify(server, Mockito.times(3)).registerMBean(Mockito.any(), Mockito.any(ObjectName.class));
Mockito.verify(server).unregisterMBean(Mockito.any(ObjectName.class));
}
@MBean(name = "service=Foo")
static class Foo implements FooMBean {
}
static interface FooMBean {
}
}
| maxifier/x-guice | guice-mbean/src/test/java/com/maxifier/guice/mbean/DoubleStartTest.java | Java | mit | 2,347 |
using System;
using System.Collections.Generic;
using System.IO;
namespace Yu_Gi_Oh.Save_File
{
public class Stat_Save : Save_Data_Chunk
{
private const int NumberOfSaveStats = 43;
public Stat_Save()
{
Stats = new Dictionary<StatSaveType, long>();
}
/// <summary>
/// Public dictionary of SaveStats and their values.
/// </summary>
public Dictionary<StatSaveType, long> Stats { get; }
/// <summary>
/// Clear all SaveStat values back to 0.
/// </summary>
public override void Clear()
{
foreach (StatSaveType Stat in Enum.GetValues(typeof(StatSaveType))) Stats[Stat] = 0;
}
/// <summary>
/// Loads SaveStat values into the Stats Dictionary
/// </summary>
/// <seealso cref="Stats" />
/// <param name="Reader">An instance of BinaryReader used for loading the save file.</param>
public override void Load(BinaryReader Reader)
{
for (var Count = 0; Count < NumberOfSaveStats; Count++) Stats[(StatSaveType) Count] = Reader.ReadInt64();
}
/// <summary>
/// Saves SaveStat values from the Stats Dictionary back to the Save File
/// </summary>
/// <seealso cref="Stats" />
/// <param name="Writer">An instance of BinaryWriter for saving to the save file.</param>
public override void Save(BinaryWriter Writer)
{
for (var Count = 0; Count < NumberOfSaveStats; Count++)
{
Stats.TryGetValue((StatSaveType) Count, out var Value);
Writer.Write(Value);
}
}
}
} | Arefu/Wolf | Yu-Gi-Oh/Save File/Stat_Save.cs | C# | mit | 1,779 |
using System.Reflection;
[assembly: AssemblyVersion("1.3.6")]
[assembly: AssemblyFileVersion("1.3.6")]
[assembly: AssemblyInformationalVersion("1.3.6")]
| rbouallou/Zebus | src/SharedVersionInfo.cs | C# | mit | 157 |
module ApiHelper
private
def authenticate!(client = @client || :spy)
client = shipit_api_clients(client) if client.is_a?(Symbol)
@client ||= client
request.headers['Authorization'] = "Basic #{Base64.encode64(client.authentication_token)}"
end
end
| perobertson/shipit-engine | test/helpers/api_helper.rb | Ruby | mit | 266 |
<?php
/* @WebProfiler/Profiler/toolbar_js.html.twig */
class __TwigTemplate_6fb18f7e22ead7a1441adb0d4a6862fe4242ea7db82b2678bdfd08825c836861 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())
{
$__internal_85288cbee958591352262e4b6e95eed2f7be7559015c08587f28af26a173995f = $this->env->getExtension("native_profiler");
$__internal_85288cbee958591352262e4b6e95eed2f7be7559015c08587f28af26a173995f->enter($__internal_85288cbee958591352262e4b6e95eed2f7be7559015c08587f28af26a173995f_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@WebProfiler/Profiler/toolbar_js.html.twig"));
// line 1
echo "<div id=\"sfwdt";
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "\" class=\"sf-toolbar\" style=\"display: none\"></div>
";
// line 2
$this->loadTemplate("@WebProfiler/Profiler/base_js.html.twig", "@WebProfiler/Profiler/toolbar_js.html.twig", 2)->display($context);
// line 3
echo "<script>/*<![CDATA[*/
(function () {
";
// line 5
if (("top" == (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")))) {
// line 6
echo " var sfwdt = document.getElementById('sfwdt";
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "');
document.body.insertBefore(
document.body.removeChild(sfwdt),
document.body.firstChild
);
";
}
// line 12
echo "
Sfjs.load(
'sfwdt";
// line 14
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "',
'";
// line 15
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_wdt", array("token" => (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")))), "html", null, true);
echo "',
function(xhr, el) {
el.style.display = -1 !== xhr.responseText.indexOf('sf-toolbarreset') ? 'block' : 'none';
if (el.style.display == 'none') {
return;
}
if (Sfjs.getPreference('toolbar/displayState') == 'none') {
document.getElementById('sfToolbarMainContent-";
// line 24
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'none';
document.getElementById('sfToolbarClearer-";
// line 25
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'none';
document.getElementById('sfMiniToolbar-";
// line 26
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'block';
} else {
document.getElementById('sfToolbarMainContent-";
// line 28
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'block';
document.getElementById('sfToolbarClearer-";
// line 29
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'block';
document.getElementById('sfMiniToolbar-";
// line 30
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'none';
}
Sfjs.renderAjaxRequests();
/* Handle toolbar-info position */
var toolbarBlocks = document.querySelectorAll('.sf-toolbar-block');
for (var i = 0; i < toolbarBlocks.length; i += 1) {
toolbarBlocks[i].onmouseover = function () {
var toolbarInfo = this.querySelectorAll('.sf-toolbar-info')[0];
var pageWidth = document.body.clientWidth;
var elementWidth = toolbarInfo.offsetWidth;
var leftValue = (elementWidth + this.offsetLeft) - pageWidth;
var rightValue = (elementWidth + (pageWidth - this.offsetLeft)) - pageWidth;
/* Reset right and left value, useful on window resize */
toolbarInfo.style.right = '';
toolbarInfo.style.left = '';
if (leftValue > 0 && rightValue > 0) {
toolbarInfo.style.right = (rightValue * -1) + 'px';
} else if (leftValue < 0) {
toolbarInfo.style.left = 0;
} else {
toolbarInfo.style.right = '-1px';
}
};
}
},
function(xhr) {
if (xhr.status !== 0) {
confirm('An error occurred while loading the web debug toolbar (' + xhr.status + ': ' + xhr.statusText + ').\\n\\nDo you want to open the profiler?') && (window.location = '";
// line 61
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_profiler", array("token" => (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")))), "html", null, true);
echo "');
}
},
{'maxTries': 5}
);
})();
/*]]>*/</script>
";
$__internal_85288cbee958591352262e4b6e95eed2f7be7559015c08587f28af26a173995f->leave($__internal_85288cbee958591352262e4b6e95eed2f7be7559015c08587f28af26a173995f_prof);
}
public function getTemplateName()
{
return "@WebProfiler/Profiler/toolbar_js.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 120 => 61, 86 => 30, 82 => 29, 78 => 28, 73 => 26, 69 => 25, 65 => 24, 53 => 15, 49 => 14, 45 => 12, 35 => 6, 33 => 5, 29 => 3, 27 => 2, 22 => 1,);
}
}
/* <div id="sfwdt{{ token }}" class="sf-toolbar" style="display: none"></div>*/
/* {% include '@WebProfiler/Profiler/base_js.html.twig' %}*/
/* <script>/*<![CDATA[*//* */
/* (function () {*/
/* {% if 'top' == position %}*/
/* var sfwdt = document.getElementById('sfwdt{{ token }}');*/
/* document.body.insertBefore(*/
/* document.body.removeChild(sfwdt),*/
/* document.body.firstChild*/
/* );*/
/* {% endif %}*/
/* */
/* Sfjs.load(*/
/* 'sfwdt{{ token }}',*/
/* '{{ path("_wdt", { "token": token }) }}',*/
/* function(xhr, el) {*/
/* el.style.display = -1 !== xhr.responseText.indexOf('sf-toolbarreset') ? 'block' : 'none';*/
/* */
/* if (el.style.display == 'none') {*/
/* return;*/
/* }*/
/* */
/* if (Sfjs.getPreference('toolbar/displayState') == 'none') {*/
/* document.getElementById('sfToolbarMainContent-{{ token }}').style.display = 'none';*/
/* document.getElementById('sfToolbarClearer-{{ token }}').style.display = 'none';*/
/* document.getElementById('sfMiniToolbar-{{ token }}').style.display = 'block';*/
/* } else {*/
/* document.getElementById('sfToolbarMainContent-{{ token }}').style.display = 'block';*/
/* document.getElementById('sfToolbarClearer-{{ token }}').style.display = 'block';*/
/* document.getElementById('sfMiniToolbar-{{ token }}').style.display = 'none';*/
/* }*/
/* */
/* Sfjs.renderAjaxRequests();*/
/* */
/* /* Handle toolbar-info position *//* */
/* var toolbarBlocks = document.querySelectorAll('.sf-toolbar-block');*/
/* for (var i = 0; i < toolbarBlocks.length; i += 1) {*/
/* toolbarBlocks[i].onmouseover = function () {*/
/* var toolbarInfo = this.querySelectorAll('.sf-toolbar-info')[0];*/
/* var pageWidth = document.body.clientWidth;*/
/* var elementWidth = toolbarInfo.offsetWidth;*/
/* var leftValue = (elementWidth + this.offsetLeft) - pageWidth;*/
/* var rightValue = (elementWidth + (pageWidth - this.offsetLeft)) - pageWidth;*/
/* */
/* /* Reset right and left value, useful on window resize *//* */
/* toolbarInfo.style.right = '';*/
/* toolbarInfo.style.left = '';*/
/* */
/* if (leftValue > 0 && rightValue > 0) {*/
/* toolbarInfo.style.right = (rightValue * -1) + 'px';*/
/* } else if (leftValue < 0) {*/
/* toolbarInfo.style.left = 0;*/
/* } else {*/
/* toolbarInfo.style.right = '-1px';*/
/* }*/
/* };*/
/* }*/
/* },*/
/* function(xhr) {*/
/* if (xhr.status !== 0) {*/
/* confirm('An error occurred while loading the web debug toolbar (' + xhr.status + ': ' + xhr.statusText + ').\n\nDo you want to open the profiler?') && (window.location = '{{ path("_profiler", { "token": token }) }}');*/
/* }*/
/* },*/
/* {'maxTries': 5}*/
/* );*/
/* })();*/
/* /*]]>*//* </script>*/
/* */
| ProgrammeurAlpha/symfonyDemo | app/cache/dev/twig/7/f/7f05cc4652ffdaba5085bcba2a5647af8ca31a7b143c0d2fc3447f282b11e28f.php | PHP | mit | 10,693 |
# coding: utf-8
module Contentr
class HeadlineParagraph < Paragraph
COLORS = { 'Schwarz' => :black, 'Grau' => :grey, 'Blau' => :blue}
LEVELS = {
'Hauptüberschrift' => 1,
'Unterüberschrift Ebene 2' => 2,
'Unterüberschrift Ebene 3' => 3
}
field :headline, type: :string
field :color, type: :string
field :level, type: :string
def summary()
lvl = LEVELS.find{|l,i| i.to_s == level.to_s}.try(:first)
"#{lvl}: #{headline.presence || '—'} (#{color.presence || '—'})"
end
end
end
| metaminded/contentr-default-paragraphs | app/models/contentr/headline_paragraph.rb | Ruby | mit | 548 |
<?php
$config['google_api'] = array(
'url'=>'https://maps.googleapis.com/maps/api/place/nearbysearch/json',
'key'=>'AIzaSyCvWvb2h-QdQJJrUd8n7gIrpEDWmv-TCxk',
'zillow_building_lat_lon'=>'47.607849,-122.338108',
'default_search_radius'=>1610
); | jcow/lunch-recommender | application/config/google_api.php | PHP | mit | 248 |
require_relative 'spec_helper'
describe "Spring" do
before(:each) do
set_java_version(app.directory, jdk_version)
end
["1.6", "1.7", "1.8"].each do |version|
context "on jdk-#{version}" do
let(:jdk_version) { version }
context "spring-boot-webapp-runner" do
let(:app) { Hatchet::Runner.new("spring-boot-webapp-runner") }
it "builds a war" do
app.deploy do |app|
expect(app).to be_deployed
expect(app.output).to include("Installing OpenJDK #{jdk_version}")
expect(app.output).to include("Installing Maven 3.0.5")
expect(app.output).to match(%r{Building war: /tmp/.*/target/spring-boot-example-1.0-SNAPSHOT.war})
expect(app.output).not_to match(%r{Building jar: /tmp/.*/target/spring-boot-example-1.0-SNAPSHOT.jar})
expect(app.output).not_to include("Installing settings.xml")
expect(app.output).not_to include("BUILD FAILURE")
expect(successful_body(app)).to include("Create a New Appointment")
end
end
end
context "spring-boot-executable" do
let(:app) { Hatchet::Runner.new("spring-boot-executable") }
it "builds an executable jar" do
app.deploy do |app|
expect(app).to be_deployed
expect(app.output).to include("Installing OpenJDK #{jdk_version}")
expect(app.output).to include("Installing Maven 3.0.5")
expect(app.output).not_to match(%r{Building war: /tmp/.*/target/spring-boot-example-1.0-SNAPSHOT.war})
expect(app.output).to match(%r{Building jar: /tmp/.*/target/spring-boot-example-1.0-SNAPSHOT.jar})
expect(app.output).not_to include("Installing settings.xml")
expect(app.output).not_to include("BUILD FAILURE")
expect(successful_body(app)).to include("Create a New Appointment")
end
end
end
end
end
end
| vbansal22/paas_devbox | spec/spring_spec.rb | Ruby | mit | 1,948 |
package com.jakub.ajamarks.controllers;
import com.jakub.ajamarks.entities.Classroom;
import com.jakub.ajamarks.entities.Mark;
import com.jakub.ajamarks.entities.Student;
import com.jakub.ajamarks.services.showdataservices.StudentService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.ResponseEntity;
import java.util.*;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Created by ja on 03.02.17.
*/
public class StudentControllerTest {
StudentController studentController;
private Mark mark;
private List<Mark> markList;
private Student student;
private Classroom classroom;
private List<Classroom> classroomList;
private Set<Student> studentSetInClassroom;
private Set<Student> studentSetWithBDBMark;
private List<Student> studentList;
@Before
public void setUp() {
studentController = new StudentController();
studentController.studentService = mock(StudentService.class);
mark = new Mark();
mark.setIdMark(1);
mark.setMarkName("BDB");
mark.setMarkValue(5);
student = new Student();
student.setIdStudent(1);
student.setUserName("JA");
student.setFirstName("Jak");
student.setLastName("Ani");
studentList = new ArrayList<>();
studentList.add(student);
studentSetInClassroom = new TreeSet<>();
studentSetInClassroom.add(student);
studentSetWithBDBMark = new TreeSet<>();
studentSetWithBDBMark.add(student);
classroom = new Classroom();
classroom.setIdClassroom(1);
classroom.setClassroomNumber(1);
classroom.setClassroomName("Pierwsza");
classroom.setStudentsInClassroom(studentSetInClassroom);
classroomList = new ArrayList<>();
classroomList.add(classroom);
student.setClassroom(classroom);
mark.setStudentsWithMark(studentSetWithBDBMark);
markList = new ArrayList<>();
markList.add(mark);
}
@Test
public void addStudent() throws Exception {
Student student = new Student();
student.setUserName("JA");
student.setFirstName("Jak");
student.setLastName("Ani");
when(studentController.studentService.saveStudent(student)).thenReturn(student);
//when
ResponseEntity responseEntity = studentController.addStudent("JA", "Jak", "Ani");
//then
verify(studentController.studentService).saveStudent(student);
assertThat(responseEntity.getBody(), is(student));
assertThat(responseEntity.getStatusCodeValue(), is(201));
}
@Test
public void addStudentThrowException() throws Exception {
Student student = new Student();
student.setUserName("JA");
student.setFirstName("Jak");
student.setLastName("Ani");
when(studentController.studentService.saveStudent(student)).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.addStudent("JA", "Jak", "Ani");
//then
verify(studentController.studentService).saveStudent(student);
assertThat(responseEntity.getStatusCodeValue(), is(406));
}
@Test
public void createStudent() {
//given
when(studentController.studentService.saveStudent(student)).thenReturn(student);
//when
ResponseEntity responseEntity = studentController.createStudent(this.student);
//then
verify(studentController.studentService).saveStudent(student);
assertThat(responseEntity.getBody(), is(student));
assertThat(responseEntity.getStatusCodeValue(), is(201));
}
@Test
public void createStudentThrowException() {
//given
when(studentController.studentService.saveStudent(student)).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.createStudent(this.student);
//then
verify(studentController.studentService).saveStudent(student);
assertThat(responseEntity.getStatusCodeValue(), is(406));
}
@Test
public void updateStudent() {
//given
when(studentController.studentService.updateStudent(1, student)).thenReturn(student);
//when
ResponseEntity responseEntity = studentController.updateStudent(1, student);
//then
verify(studentController.studentService).updateStudent(1, student);
assertThat(responseEntity.getBody(), is(student));
assertThat(responseEntity.getStatusCodeValue(), is(200));
}
@Test
public void updateStudentThrowException() {
//given
when(studentController.studentService.updateStudent(1, student)).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.updateStudent(1, student);
//then
verify(studentController.studentService).updateStudent(1, student);
assertThat(responseEntity.getStatusCodeValue(), is(406));
}
@Test
public void deleteStudent() {
//given
when(studentController.studentService.getStudentByUserName("JA")).thenReturn(student);
//when
ResponseEntity responseEntity = studentController.deleteStudent("JA");
//then
verify(studentController.studentService).getStudentByUserName("JA");
verify(studentController.studentService).delete(student);
assertThat(responseEntity.getStatusCodeValue(), is(204));
}
@Test
public void deleteStudentThrowException() {
//given
when(studentController.studentService.getStudentByUserName("JA")).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.deleteStudent("JA");
//then
verify(studentController.studentService).getStudentByUserName("JA");
assertThat(responseEntity.getStatusCodeValue(), is(404));
}
@Test
public void showAllStudents() {
//given
when(studentController.studentService.getAll()).thenReturn(studentList);
//when
ResponseEntity responseEntity = studentController.showAllStudents();
//then
verify(studentController.studentService).getAll();
assertThat(responseEntity.getBody(), is(studentList));
assertThat(responseEntity.getStatusCodeValue(), is(200));
}
@Test
public void showAllStudentsThrowException() {
//given
when(studentController.studentService.getAll()).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.showAllStudents();
//then
verify(studentController.studentService).getAll();
assertThat(responseEntity.getStatusCodeValue(), is(404));
}
@Test
public void showStudentByUserId() {
//given
when(studentController.studentService.getStudentById(1L)).thenReturn(student);
//when
ResponseEntity responseEntity = studentController.showStudentByUserId(1L);
//then
verify(studentController.studentService).getStudentById(1L);
assertThat(responseEntity.getBody(), is(student));
assertThat(responseEntity.getStatusCodeValue(), is(200));
}
@Test
public void showStudentByUserIdThrowException() {
//given
when(studentController.studentService.getStudentById(1L)).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.showStudentByUserId(1L);
//then
verify(studentController.studentService).getStudentById(1L);
assertThat(responseEntity.getStatusCodeValue(), is(404));
}
@Test
public void showStudentByUserName() {
//given
when(studentController.studentService.getStudentByUserName("JA")).thenReturn(student);
//when
ResponseEntity responseEntity = studentController.showStudentByUserName("JA");
//then
verify(studentController.studentService).getStudentByUserName("JA");
assertThat(responseEntity.getBody(), is(student));
assertThat(responseEntity.getStatusCodeValue(), is(200));
}
@Test
public void showStudentByUserNameThrowException() {
//given
when(studentController.studentService.getStudentByUserName("JA")).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.showStudentByUserName("JA");
//then
verify(studentController.studentService).getStudentByUserName("JA");
assertThat(responseEntity.getStatusCodeValue(), is(404));
}
@Test
public void showStudentsWithGivenMarkValue() {
//given
when(studentController.studentService.getStudentsWithGivenMarkValue(5)).thenReturn(studentList);
//when
ResponseEntity responseEntity = studentController.showStudentsWithGivenMarkValue(5);
//then
verify(studentController.studentService).getStudentsWithGivenMarkValue(5);
assertThat(responseEntity.getBody(), is(studentList));
assertThat(responseEntity.getStatusCodeValue(), is(200));
}
@Test
public void showStudentsWithGivenMarkValueThrowEsception() {
//given
when(studentController.studentService.getStudentsWithGivenMarkValue(5)).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.showStudentsWithGivenMarkValue(5);
//then
verify(studentController.studentService).getStudentsWithGivenMarkValue(5);
assertThat(responseEntity.getStatusCodeValue(), is(404));
}
@Test
public void showStudentsWithoutGivenMarkValue() {
//given
Student student = new Student();
student.setUserName("nowy");
student.setFirstName("nowy");
student.setLastName("nowy");
student.setStudentMarks(Collections.emptyList());
List<Student> studentList = new ArrayList<>();
studentList.add(student);
when(studentController.studentService.getStudentsWithoutGivenMarkValue(5)).thenReturn(studentList);
//when
ResponseEntity responseEntity = studentController.showStudentsWithoutGivenMarkValue(5);
//then
verify(studentController.studentService).getStudentsWithoutGivenMarkValue(5);
assertThat(responseEntity.getBody(), is(studentList));
assertThat(responseEntity.getStatusCodeValue(), is(200));
}
@Test
public void showStudentsWithoutGivenMarkValueThrowException() {
//given
when(studentController.studentService.getStudentsWithoutGivenMarkValue(5)).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.showStudentsWithoutGivenMarkValue(5);
//then
verify(studentController.studentService).getStudentsWithoutGivenMarkValue(5);
assertThat(responseEntity.getStatusCodeValue(), is(404));
}
@Test
public void showStudentsByClassroomNumber() {
//given
when(studentController.studentService.getClassroomStudentsByClassroomNumberDescLastName(1)).thenReturn(studentList);
//when
ResponseEntity responseEntity = studentController.showStudentsByClassroomNumber(1);
//then
verify(studentController.studentService).getClassroomStudentsByClassroomNumberDescLastName(1);
assertThat(responseEntity.getBody(), is(studentList));
assertThat(responseEntity.getStatusCodeValue(), is(200));
}
@Test
public void showStudentsByClassroomNumberThrowException() {
//given
when(studentController.studentService.getClassroomStudentsByClassroomNumberDescLastName(1)).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.showStudentsByClassroomNumber(1);
//then
verify(studentController.studentService).getClassroomStudentsByClassroomNumberDescLastName(1);
assertThat(responseEntity.getStatusCodeValue(), is(404));
}
@Test
public void showStudentsByClassroomName() {
//given
when(studentController.studentService.getClassroomStudentsByClassroomNameDescLastName("Pierwsza")).thenReturn(studentList);
//when
ResponseEntity responseEntity = studentController.showStudentsByClassroomName("Pierwsza");
//then
verify(studentController.studentService).getClassroomStudentsByClassroomNameDescLastName("Pierwsza");
assertThat(responseEntity.getBody(), is(studentList));
assertThat(responseEntity.getStatusCodeValue(), is(200));
}
@Test
public void showStudentsByClassroomNameThrowException() {
//given
when(studentController.studentService.getClassroomStudentsByClassroomNameDescLastName("Pierwsza")).thenThrow(new RuntimeException());
//when
ResponseEntity responseEntity = studentController.showStudentsByClassroomName("Pierwsza");
//then
verify(studentController.studentService).getClassroomStudentsByClassroomNameDescLastName("Pierwsza");
assertThat(responseEntity.getStatusCodeValue(), is(404));
}
} | ajakuba/AJAmarks | AJAmarksWeb/src/test/java/com/jakub/ajamarks/controllers/StudentControllerTest.java | Java | mit | 13,384 |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;
namespace Peace.Message_Queue
{
public interface IMessageQueue
{
void Load(IEnumerable<QueueMessage> messages);
void Enqueue(QueueMessage message);
QueueMessage Dequeue();
void Purge(string token);
void PurgeAll();
}
public class MessageQueues : IMessageQueue, IDisposable
{
private readonly Dictionary<string, QueueMessage> messageDic;
private readonly ReaderWriterLockSlim locker = new ReaderWriterLockSlim();
private int current = 1, count = 0;
public int Count
{
get { return count; }
}
public MessageQueues()
{
messageDic = new Dictionary<string, QueueMessage>();
}
public void Dispose()
{
throw new NotImplementedException();
}
public void Load(IEnumerable<QueueMessage> messages)
{
locker.EnterWriteLock();
try
{
foreach (QueueMessage queueMessage in messages)
{
Put(queueMessage);
}
}
finally
{
locker.ExitWriteLock();
}
}
/// <summary>
/// 入队
/// </summary>
/// <param name="message"></param>
public void Enqueue(QueueMessage message)
{
locker.EnterWriteLock();
try
{
Put(message);
}
finally
{
locker.ExitWriteLock();
}
}
/// <summary>
/// 出队
/// </summary>
public QueueMessage Dequeue()
{
QueueMessage result = null;
if (messageDic.Count > 0)
{
locker.EnterReadLock();
try
{
var enumerator = messageDic.Values.GetEnumerator();
int index = 1;
while (enumerator.MoveNext())
{
if (index == current)
{
result = enumerator.Current;
result.State = State.Processing;
current++;
break;
}
else
{
index++;
}
}
}
finally
{
locker.ExitReadLock();
}
}
return result;
}
public void Purge(string token)
{
locker.EnterWriteLock();
try
{
Console.WriteLine("删除 {0}", token);
count--;
var cur = messageDic[token];
cur.State = State.Completed;
Console.Write(" 剩余{0}\n", count);
if (current == messageDic.Count)
{
PurgeAll();
}
}
finally
{
locker.ExitWriteLock();
}
}
public void PurgeAll()
{
messageDic.Clear();
Console.WriteLine("最后剩余:{0}", messageDic.Count);
}
private void Put(QueueMessage message)
{
var key = message.Token();
if (!messageDic.ContainsKey(key))
{
message.CompletedEvent += Purge;
messageDic.Add(key, message);
count++;
}
}
}
public delegate void MessageQueueNotifyEventHandler(QueueMessage message);
public class MessageQueueManager
{
private readonly MessageQueues _queue;
private readonly Timer _timer;
private static readonly object Locker = new object();
public static readonly MessageQueueManager Manager = new MessageQueueManager();
/// <summary>
/// 处理速度(单位毫秒)
/// </summary>
public double ProcessSpeed { get; set; }
public int Count
{
get { return _queue.Count; }
}
private MessageQueueManager()
{
_queue = new MessageQueues();
_timer = new Timer();
ProcessSpeed = 1000;
this._timer.Interval = 500;
this._timer.Elapsed += Notify;
}
public void Start()
{
this._timer.Enabled = true;
}
public void Stop()
{
this._timer.Enabled = false;
}
public void Add(QueueMessage message)
{
_queue.Enqueue(message);
}
public void Load(IEnumerable<QueueMessage> messages)
{
_queue.Load(messages);
}
private void Notify(object sender, ElapsedEventArgs e)
{
lock (Locker)
{
var message = _queue.Dequeue();
if (message != null)
{
this._messageNotifyEventHandler(message);
}
}
}
private MessageQueueNotifyEventHandler _messageNotifyEventHandler;
public event MessageQueueNotifyEventHandler MessageNotifyEvent
{
add { this._messageNotifyEventHandler += value; }
remove
{
if (this._messageNotifyEventHandler != null)
{
//
this._messageNotifyEventHandler -= value;
}
}
}
}
public class QueueMessage
{
public delegate void CompletedEventHandler(string token);
public event CompletedEventHandler CompletedEvent;
public Guid Id { get; set; }
public string Type { get; set; }
public object Body { get; set; }//todo:还可以使用序列化,在先这里简单处理
public State State { get; set; }
public void Completed()
{
if (CompletedEvent != null)
{
CompletedEvent(this.Token());
}
}
public string Token()
{
return string.Format("{0}***{1}", Id, Body.GetHashCode());
}
}
public enum State
{
None = 0,
Processing,
Error,
Completed
}
}
| Khadron/Peace | Peace/Message Queue/MQ.cs | C# | mit | 6,652 |
<?php
/**
*
* Selector lists.
*
*/
namespace CssCrush;
class SelectorList extends Iterator
{
public function __construct($selectorString, Rule $rule)
{
parent::__construct();
$selectorString = trim(Util::stripCommentTokens($selectorString));
foreach (Util::splitDelimList($selectorString) as $selector) {
if (preg_match(Regex::$patt->abstract, $selector, $m)) {
$rule->name = strtolower($m['name']);
$rule->isAbstract = true;
}
else {
$this->add(new Selector($selector));
}
}
}
public function add(Selector $selector)
{
$this->store[$selector->readableValue] = $selector;
}
public function join($glue = ',')
{
return implode($glue, $this->store);
}
public function expand()
{
static $grouping_patt, $expand, $expandSelector;
if (! $grouping_patt) {
$grouping_patt = Regex::make('~\:any{{ parens }}~iS');
$expand = function ($selector_string) use ($grouping_patt)
{
if (preg_match($grouping_patt, $selector_string, $m, PREG_OFFSET_CAPTURE)) {
list($full_match, $full_match_offset) = $m[0];
$before = substr($selector_string, 0, $full_match_offset);
$after = substr($selector_string, strlen($full_match) + $full_match_offset);
$selectors = [];
// Allowing empty strings for more expansion possibilities.
foreach (Util::splitDelimList($m['parens_content'][0], ['allow_empty_strings' => true]) as $segment) {
if ($selector = trim("$before$segment$after")) {
$selectors[$selector] = true;
}
}
return $selectors;
}
return false;
};
$expandSelector = function ($selector_string) use ($expand)
{
if ($running_stack = $expand($selector_string)) {
$flattened_stack = [];
do {
$loop_stack = [];
foreach ($running_stack as $selector => $bool) {
$selectors = $expand($selector);
if (! $selectors) {
$flattened_stack += [$selector => true];
}
else {
$loop_stack += $selectors;
}
}
$running_stack = $loop_stack;
} while ($loop_stack);
return $flattened_stack;
}
return [$selector_string => true];
};
}
$expanded_set = [];
foreach ($this->store as $original_selector) {
if (stripos($original_selector->value, ':any(') !== false) {
foreach ($expandSelector($original_selector->value) as $selector_string => $bool) {
$new = new Selector($selector_string);
$expanded_set[$new->readableValue] = $new;
}
}
else {
$expanded_set[$original_selector->readableValue] = $original_selector;
}
}
$this->store = $expanded_set;
}
public function merge($rawSelectors)
{
$stack = [];
foreach ($rawSelectors as $rawParentSelector) {
foreach ($this->store as $selector) {
$useParentSymbol = strpos($selector->value, '&') !== false;
if (! $selector->allowPrefix && ! $useParentSymbol) {
$stack[$selector->readableValue] = $selector;
}
elseif ($useParentSymbol) {
$new = new Selector(str_replace('&', $rawParentSelector, $selector->value));
$stack[$new->readableValue] = $new;
}
else {
$new = new Selector("$rawParentSelector {$selector->value}");
$stack[$new->readableValue] = $new;
}
}
}
$this->store = $stack;
}
}
| peteboere/css-crush | lib/CssCrush/SelectorList.php | PHP | mit | 4,370 |
(function ($) {
var theForm;
var theBox;
var theTypeTarget;
var settings;
$.fn.tagbox = function(options) {
var defaults = {
typeTargetNameAndId : "type_target",
tagInputsArrayName : "tag_list",
includeExampleTag : true
};
settings = $.extend(defaults, options);
theBox = this;
theForm = theBox.parents("form");
theTypeTarget = setupTypeTarget();
setupTypeTargetKeyPressHandling();
setupExampleTagElement();
setupSimulatedFocus();
setupDimissTagListener();
return this;
};
/**
*
*/
function setupExampleTagElement(){
if(settings.includeExampleTag){
var exampleTagElement = $(buildExampleTagElement());
theBox.prepend(exampleTagElement);
}
}
/**
* When the fake textarea is clicked, pass focus to the hidden text-field.
* Also, bind to the focus and blur events of the text-field to update the
* fake textarea appearance, hence simulating focus
*/
function setupSimulatedFocus(){
theBox.click(function(event){
theTypeTarget.focus();
});
theTypeTarget.focus(function(event){
theBox.addClass("has_focus");
});
theTypeTarget.blur(function(event){
theBox.removeClass("has_focus");
});
}
/**
*
*/
function setupTypeTarget(){
var typeTarget = $(buildTypeTarget());
theBox.append(typeTarget);
return typeTarget;
}
/**
*
*/
function setupTypeTargetKeyPressHandling(){
//handle input: create tag if key==(enter, tab, comma, space), adjust width
theTypeTarget.keydown(function(event){
var key = event.which
if (key === 13 || key === 9 || key === 44 || key === 188 || key === 32){
event.preventDefault();
verifyAndCreateTag();
}
else
adjustTypeTargetWidth();
});
//adjust width on keyup as well, to cover any case (crossbrowser)
theTypeTarget.keyup(function(event){
adjustTypeTargetWidth();
});
}
/**
*
*/
function setupDimissTagListener() {
theBox.on("click",
".tag_element > .tag_dismiss",
null,
function(event){
event.preventDefault();
var theTagElement = $(this).parent();
removeTagElementAndHiddenInput(theTagElement);
});
}
/**
* to adjust the hidden input's width
*/
function adjustTypeTargetWidth() {
var len = theTypeTarget.val().length;
theTypeTarget.css("width", len*11);
if(parseInt(theTypeTarget.css("width")) < 40){
theTypeTarget.css("width", "40px")
}
}
/**
* if something has been typed in the input, create a new tag
*/
function verifyAndCreateTag() {
var text = theTypeTarget.val();
if(text.length > 0)
insertTagElement(text);
}
/**
*
*/
function insertTagElement(text) {
var jq_newTag = $(buildTagHtmlString(text));
jq_newTag.insertBefore(theTypeTarget);
// resetting the input
theTypeTarget.val("").css("width", "60px");
insertTagHiddenField(text);
}
/**
*
*/
function insertTagHiddenField(text) {
jq_newField = $(buildHiddenInputHtmlString(text));
theForm.prepend(jq_newField);
}
/**
* builds the html string for the tag element
*/
function buildTagHtmlString(text) {
var tag_str = "<div class='tag_element'><span class='tag_label'>" + text +
"</span><a href='#' title='remove' class='tag_dismiss'>×</a></div>";
return tag_str;
}
/**
* builds the html string for a hidden form input
*/
function buildHiddenInputHtmlString(text) {
var input_str = '<input name="' + settings.tagInputsArrayName + '[]" type="hidden" value="' + text + '">';
return input_str;
}
/**
*
*/
function removeTagElementAndHiddenInput(jq_tag){
var tagName = jq_tag.find(".tag_label").html();
// remove the tag from the tag box
jq_tag.remove();
// remove the hidden input
var sel = '[value="' + tagName + '"]';
$(sel).remove();
}
/**
* builds the html string for the example tag
*/
function buildExampleTagElement() {
var tagStr = '<div class="tag_element"><span class="tag_label">example</span><a href="#" title="remove" class="tag_dismiss">×</a></div>';
return tagStr;
}
/**
* builds the html string for the example tag
*/
function buildTypeTarget() {
var tagStr = '<input name="' + settings.typeTargetNameAndId + '" id="' + settings.typeTargetNameAndId + '" type="text" maxlength="40">';
return tagStr;
}
}(jQuery));
// -- DEPRECATED
/**
* adds the tag string to the "chained" hidden input (if used)
* I'm using "$%" to separate entries. I'll parse and split the string server-side
*/
// function addNewTagToHiddenStringField(text) {
// var jq_tagsFormInput = $("#tag_list");
// var new_value = jq_tagsFormInput.val() + text + "$%";
// jq_tagsFormInput.val(new_value);
// }
/**
* removes the tag string from the "chained" hidden input (if used)
*/
// function removeDeletedTagFromHiddenStringField(text) {
// var jq_tagsFormInput = $("#tag_list");
// var originalValue = jq_tagsFormInput.val();
// var pattern = text + "$%";
// var newValue = originalValue.replace(pattern, "");
// jq_tagsFormInput.val(newValue);
// }
| tompave/tagbox | scripts/tagbox.js | JavaScript | mit | 5,917 |
package com.github.neunkasulle.chronocommand.model;
import com.github.neunkasulle.chronocommand.control.UeberTest;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by Janze on 28.02.2016.
*
*/
public class CategoryTest extends UeberTest {
@Test
public void testSetName() throws Exception {
Category category = new Category("WUPWUP");
category.setName("FOO");
assertEquals("FOO", category.getName());
}
@Test
public void testHashCode() throws Exception {
CategoryDAO categoryDAO = CategoryDAO.getInstance();
assertNotEquals(categoryDAO.findCategoryByString("Programming").hashCode(),
categoryDAO.findCategoryByString("Procrastination").hashCode());
}
@Test
public void testEqualsFail() throws Exception {
assertFalse(new Category().equals(new User()));
}
} | neunkasulle/ChronoCommand | code/src/test/java/com/github/neunkasulle/chronocommand/model/CategoryTest.java | Java | mit | 891 |
'use strict';
var _interopRequireDefault = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
exports.__esModule = true;
var _core = require('core-js');
var _core2 = _interopRequireDefault(_core);
var _hyphenate = require('./util');
var _bindingMode = require('aurelia-binding');
function getObserver(behavior, instance, name) {
var lookup = instance.__observers__;
if (lookup === undefined) {
lookup = behavior.observerLocator.getObserversLookup(instance);
behavior.ensurePropertiesDefined(instance, lookup);
}
return lookup[name];
}
var BindableProperty = (function () {
function BindableProperty(nameOrConfig) {
_classCallCheck(this, BindableProperty);
if (typeof nameOrConfig === 'string') {
this.name = nameOrConfig;
} else {
Object.assign(this, nameOrConfig);
}
this.attribute = this.attribute || _hyphenate.hyphenate(this.name);
this.defaultBindingMode = this.defaultBindingMode || _bindingMode.bindingMode.oneWay;
this.changeHandler = this.changeHandler || null;
this.owner = null;
}
BindableProperty.prototype.registerWith = function registerWith(target, behavior, descriptor) {
behavior.properties.push(this);
behavior.attributes[this.attribute] = this;
this.owner = behavior;
if (descriptor) {
this.descriptor = descriptor;
return this.configureDescriptor(behavior, descriptor);
}
};
BindableProperty.prototype.configureDescriptor = function configureDescriptor(behavior, descriptor) {
var name = this.name;
descriptor.configurable = true;
descriptor.enumerable = true;
if ('initializer' in descriptor) {
this.defaultValue = descriptor.initializer;
delete descriptor.initializer;
delete descriptor.writable;
}
if ('value' in descriptor) {
this.defaultValue = descriptor.value;
delete descriptor.value;
delete descriptor.writable;
}
descriptor.get = function () {
return getObserver(behavior, this, name).getValue();
};
descriptor.set = function (value) {
getObserver(behavior, this, name).setValue(value);
};
return descriptor;
};
BindableProperty.prototype.defineOn = function defineOn(target, behavior) {
var name = this.name,
handlerName;
if (this.changeHandler === null) {
handlerName = name + 'Changed';
if (handlerName in target.prototype) {
this.changeHandler = handlerName;
}
}
if (!this.descriptor) {
Object.defineProperty(target.prototype, name, this.configureDescriptor(behavior, {}));
}
};
BindableProperty.prototype.createObserver = function createObserver(executionContext) {
var _this = this;
var selfSubscriber = null,
defaultValue = this.defaultValue,
initialValue;
if (this.hasOptions) {
return;
}
if (this.changeHandler !== null) {
selfSubscriber = function (newValue, oldValue) {
return executionContext[_this.changeHandler](newValue, oldValue);
};
}
if (defaultValue !== undefined) {
initialValue = typeof defaultValue === 'function' ? defaultValue.call(executionContext) : defaultValue;
}
return new BehaviorPropertyObserver(this.owner.taskQueue, executionContext, this.name, selfSubscriber, initialValue);
};
BindableProperty.prototype.initialize = function initialize(executionContext, observerLookup, attributes, behaviorHandlesBind, boundProperties) {
var selfSubscriber,
observer,
attribute,
defaultValue = this.defaultValue;
if (this.isDynamic) {
for (var key in attributes) {
this.createDynamicProperty(executionContext, observerLookup, behaviorHandlesBind, key, attributes[key], boundProperties);
}
} else if (!this.hasOptions) {
observer = observerLookup[this.name];
if (attributes !== undefined) {
selfSubscriber = observer.selfSubscriber;
attribute = attributes[this.attribute];
if (behaviorHandlesBind) {
observer.selfSubscriber = null;
}
if (typeof attribute === 'string') {
executionContext[this.name] = attribute;
observer.call();
} else if (attribute) {
boundProperties.push({ observer: observer, binding: attribute.createBinding(executionContext) });
} else if (defaultValue !== undefined) {
observer.call();
}
observer.selfSubscriber = selfSubscriber;
}
observer.publishing = true;
}
};
BindableProperty.prototype.createDynamicProperty = function createDynamicProperty(executionContext, observerLookup, behaviorHandlesBind, name, attribute, boundProperties) {
var changeHandlerName = name + 'Changed',
selfSubscriber = null,
observer,
info;
if (changeHandlerName in executionContext) {
selfSubscriber = function (newValue, oldValue) {
return executionContext[changeHandlerName](newValue, oldValue);
};
} else if ('dynamicPropertyChanged' in executionContext) {
selfSubscriber = function (newValue, oldValue) {
return executionContext.dynamicPropertyChanged(name, newValue, oldValue);
};
}
observer = observerLookup[name] = new BehaviorPropertyObserver(this.owner.taskQueue, executionContext, name, selfSubscriber);
Object.defineProperty(executionContext, name, {
configurable: true,
enumerable: true,
get: observer.getValue.bind(observer),
set: observer.setValue.bind(observer)
});
if (behaviorHandlesBind) {
observer.selfSubscriber = null;
}
if (typeof attribute === 'string') {
executionContext[name] = attribute;
observer.call();
} else if (attribute) {
info = { observer: observer, binding: attribute.createBinding(executionContext) };
boundProperties.push(info);
}
observer.publishing = true;
observer.selfSubscriber = selfSubscriber;
};
return BindableProperty;
})();
exports.BindableProperty = BindableProperty;
var BehaviorPropertyObserver = (function () {
function BehaviorPropertyObserver(taskQueue, obj, propertyName, selfSubscriber, initialValue) {
_classCallCheck(this, BehaviorPropertyObserver);
this.taskQueue = taskQueue;
this.obj = obj;
this.propertyName = propertyName;
this.callbacks = [];
this.notqueued = true;
this.publishing = false;
this.selfSubscriber = selfSubscriber;
this.currentValue = this.oldValue = initialValue;
}
BehaviorPropertyObserver.prototype.getValue = function getValue() {
return this.currentValue;
};
BehaviorPropertyObserver.prototype.setValue = function setValue(newValue) {
var oldValue = this.currentValue;
if (oldValue != newValue) {
if (this.publishing && this.notqueued) {
this.notqueued = false;
this.taskQueue.queueMicroTask(this);
}
this.oldValue = oldValue;
this.currentValue = newValue;
}
};
BehaviorPropertyObserver.prototype.call = function call() {
var callbacks = this.callbacks,
i = callbacks.length,
oldValue = this.oldValue,
newValue = this.currentValue;
this.notqueued = true;
if (newValue != oldValue) {
if (this.selfSubscriber !== null) {
this.selfSubscriber(newValue, oldValue);
}
while (i--) {
callbacks[i](newValue, oldValue);
}
this.oldValue = newValue;
}
};
BehaviorPropertyObserver.prototype.subscribe = function subscribe(callback) {
var callbacks = this.callbacks;
callbacks.push(callback);
return function () {
callbacks.splice(callbacks.indexOf(callback), 1);
};
};
return BehaviorPropertyObserver;
})(); | AMGTestOrg/templating | dist/commonjs/bindable-property.js | JavaScript | mit | 7,942 |
namespace CohesionAndCoupling
{
using System;
public class UtilsExamples
{
public static void Main()
{
Console.WriteLine(FileUtils.GetFileExtension("example"));
Console.WriteLine(FileUtils.GetFileExtension("example.pdf"));
Console.WriteLine(FileUtils.GetFileExtension("example.new.pdf"));
Console.WriteLine(FileUtils.GetFileNameWithoutExtension("example"));
Console.WriteLine(FileUtils.GetFileNameWithoutExtension("example.pdf"));
Console.WriteLine(FileUtils.GetFileNameWithoutExtension("example.new.pdf"));
Console.WriteLine(
"Distance in the 2D space = {0:f2}",
PointUtils.CalcDistance2D(1, -2, 3, 4));
Console.WriteLine(
"Distance in the 3D space = {0:f2}",
PointUtils.CalcDistance3D(5, 2, -1, 3, -6, 4));
Shape testShape = new Shape(3, 4, 5);
Console.WriteLine("Volume = {0:f2}", testShape.CalcVolume());
Console.WriteLine("Diagonal XYZ = {0:f2}", testShape.CalcDiagonalXYZ());
Console.WriteLine("Diagonal XY = {0:f2}", testShape.CalcDiagonalXY());
Console.WriteLine("Diagonal XZ = {0:f2}", testShape.CalcDiagonalXZ());
Console.WriteLine("Diagonal YZ = {0:f2}", testShape.CalcDiagonalYZ());
}
}
}
| danisio/HQC-HighQualityCode-Homeworks | 07.HighQualityClasses/Task3.CohesionAndCoupling/UtilsExamples.cs | C# | mit | 1,380 |