code
stringlengths 2
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
package net.inpercima.runandfun.service;
import static net.inpercima.runandfun.runkeeper.constants.RunkeeperConstants.ACTIVITIES_MEDIA;
import static net.inpercima.runandfun.runkeeper.constants.RunkeeperConstants.ACTIVITIES_URL_PAGE_SIZE_ONE;
import static net.inpercima.runandfun.runkeeper.constants.RunkeeperConstants.ACTIVITIES_URL_SPECIFIED_PAGE_SIZE_NO_EARLIER_THAN;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.inject.Inject;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.inpercima.restapi.service.RestApiService;
import net.inpercima.runandfun.app.model.AppActivity;
import net.inpercima.runandfun.runkeeper.model.RunkeeperActivities;
import net.inpercima.runandfun.runkeeper.model.RunkeeperActivityItem;
/**
* @author Marcel Jänicke
* @author Sebastian Peters
* @since 26.01.2015
*/
@NoArgsConstructor
@Service
@Slf4j
public class ActivitiesService {
// initial release in 2008 according to http://en.wikipedia.org/wiki/RunKeeper
private static final LocalDate INITIAL_RELEASE_OF_RUNKEEPER = LocalDate.of(2008, 01, 01);
@Inject
private AuthService authService;
@Inject
private RestApiService restApiService;
@Inject
private ActivityRepository repository;
@Inject
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public int indexActivities(final String accessToken) {
final Collection<AppActivity> activities = new ArrayList<>();
final String username = authService.getAppState(accessToken).getUsername();
listActivities(accessToken, calculateFetchDate()).stream().filter(item -> !repository.existsById(item.getId()))
.forEach(item -> addActivity(item, username, activities));
log.info("new activities: {}", activities.size());
if (!activities.isEmpty()) {
repository.saveAll(activities);
}
return activities.size();
}
/**
* List activities live from runkeeper with an accessToken and a date. The full
* size will be determined every time but with the given date only the last
* items will be collected with a max. of the full size.
*
* @param accessToken
* @param from
* @return list of activity items
*/
private List<RunkeeperActivityItem> listActivities(final String accessToken, final LocalDate from) {
log.debug("list activities for token {} until {}", accessToken, from);
// get one item only to get full size
int pageSize = restApiService
.getForObject(ACTIVITIES_URL_PAGE_SIZE_ONE, ACTIVITIES_MEDIA, accessToken, RunkeeperActivities.class)
.getBody().getSize();
// list new activities from given date with max. full size
return restApiService.getForObject(
String.format(ACTIVITIES_URL_SPECIFIED_PAGE_SIZE_NO_EARLIER_THAN, pageSize,
from.format(DateTimeFormatter.ISO_LOCAL_DATE)),
ACTIVITIES_MEDIA, accessToken, RunkeeperActivities.class).getBody().getItemsAsList();
}
private LocalDate calculateFetchDate() {
final AppActivity activity = getLastActivity();
return activity == null ? INITIAL_RELEASE_OF_RUNKEEPER : activity.getDate().toLocalDate();
}
private void addActivity(final RunkeeperActivityItem item, final String username,
final Collection<AppActivity> activities) {
final AppActivity activity = new AppActivity(item.getId(), username, item.getType(), item.getDate(),
item.getDistance(), item.getDuration());
log.debug("prepare {}", activity);
activities.add(activity);
}
/**
* Get last activity from app repository.
*
* @return last activity
*/
public AppActivity getLastActivity() {
return repository.findTopByOrderByDateDesc();
}
/**
* Count activities from app repository.
*
* @return count
*/
public Long countActivities() {
return repository.count();
}
/**
* List activites from app repository.
*
* @param pageable
* @param types
* @param minDate
* @param maxDate
* @param minDistance
* @param maxDistance
* @param query
* @return
*/
public SearchHits<AppActivity> listActivities(final Pageable pageable, final String types, final LocalDate minDate,
final LocalDate maxDate, final Float minDistance, final Float maxDistance, final String query) {
final BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
if (!Strings.isNullOrEmpty(types)) {
final BoolQueryBuilder typesQuery = QueryBuilders.boolQuery();
for (final String type : Splitter.on(',').split(types)) {
typesQuery.should(QueryBuilders.termQuery(AppActivity.FIELD_TYPE, type));
}
queryBuilder.must(typesQuery);
}
if (minDate != null || maxDate != null) {
addDateQuery(queryBuilder, minDate, maxDate);
}
if (minDistance != null || maxDistance != null) {
addDistanceQuery(queryBuilder, minDistance, maxDistance);
}
if (!Strings.isNullOrEmpty(query)) {
addFulltextQuery(queryBuilder, query);
}
if (!queryBuilder.hasClauses()) {
queryBuilder.must(QueryBuilders.matchAllQuery());
}
log.info("{}", queryBuilder);
return elasticsearchRestTemplate.search(
new NativeSearchQueryBuilder().withPageable(pageable).withQuery(queryBuilder).build(),
AppActivity.class, IndexCoordinates.of("activity"));
}
private static void addFulltextQuery(final BoolQueryBuilder queryBuilder, final String query) {
queryBuilder.must(QueryBuilders.termQuery("_all", query.trim()));
}
private static void addDateQuery(final BoolQueryBuilder queryBuilder, final LocalDate minDate,
final LocalDate maxDate) {
final RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(AppActivity.FIELD_DATE);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");
if (minDate != null) {
LocalDateTime minDateTime = minDate.atStartOfDay();
rangeQuery.gte(minDateTime.format(formatter));
}
if (maxDate != null) {
LocalDateTime maxDateTime = maxDate.atStartOfDay();
rangeQuery.lte(maxDateTime.format(formatter));
}
queryBuilder.must(rangeQuery);
}
private static void addDistanceQuery(final BoolQueryBuilder queryBuilder, final Float minDistance,
final Float maxDistance) {
final RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(AppActivity.FIELD_DISTANCE);
if (minDistance != null) {
rangeQuery.gte(minDistance);
}
if (maxDistance != null) {
rangeQuery.lte(maxDistance);
}
queryBuilder.must(rangeQuery);
}
}
| inpercima/run-and-fun | server/src/main/java/net/inpercima/runandfun/service/ActivitiesService.java | Java | mit | 7,790 |
export default function() {
var links = [
{
icon: "fa-sign-in",
title: "Login",
url: "/login"
},
{
icon: "fa-dashboard",
title: "Dashboard",
url: "/"
},
{
icon: "fa-calendar",
title: "Scheduler",
url: "/scheduler"
}
];
return m("#main-sidebar", [
m("ul", {class: "navigation"},
links.map(function(link) {
return m("li", [
m("a", {href: link.url, config: m.route}, [
m("i.menu-icon", {class: "fa " + link.icon}), " ", link.title
])
]);
})
)
]);
}
| dolfelt/scheduler-js | src/component/sidebar.js | JavaScript | mit | 755 |
<?php
/**
* Pure-PHP implementation of SFTP.
*
* PHP version 5
*
* Currently only supports SFTPv2 and v3, which, according to wikipedia.org, "is the most widely used version,
* implemented by the popular OpenSSH SFTP server". If you want SFTPv4/5/6 support, provide me with access
* to an SFTPv4/5/6 server.
*
* The API for this library is modeled after the API from PHP's {@link http://php.net/book.ftp FTP extension}.
*
* Here's a short example of how to use this library:
* <code>
* <?php
* include 'vendor/autoload.php';
*
* $sftp = new \phpseclib\Net\SFTP('www.domain.tld');
* if (!$sftp->login('username', 'password')) {
* exit('Login Failed');
* }
*
* echo $sftp->pwd() . "\r\n";
* $sftp->put('filename.ext', 'hello, world!');
* print_r($sftp->nlist());
* ?>
* </code>
*
* @category Net
* @package SFTP
* @author Jim Wigginton <[email protected]>
* @copyright 2009 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
namespace phpseclib\Net;
use ParagonIE\ConstantTime\Hex;
use phpseclib\Exception\FileNotFoundException;
use phpseclib\Common\Functions\Strings;
/**
* Pure-PHP implementations of SFTP.
*
* @package SFTP
* @author Jim Wigginton <[email protected]>
* @access public
*/
class SFTP extends SSH2
{
/**
* SFTP channel constant
*
* \phpseclib\Net\SSH2::exec() uses 0 and \phpseclib\Net\SSH2::read() / \phpseclib\Net\SSH2::write() use 1.
*
* @see \phpseclib\Net\SSH2::send_channel_packet()
* @see \phpseclib\Net\SSH2::get_channel_packet()
* @access private
*/
const CHANNEL = 0x100;
/**#@+
* @access public
* @see \phpseclib\Net\SFTP::put()
*/
/**
* Reads data from a local file.
*/
const SOURCE_LOCAL_FILE = 1;
/**
* Reads data from a string.
*/
// this value isn't really used anymore but i'm keeping it reserved for historical reasons
const SOURCE_STRING = 2;
/**
* Reads data from callback:
* function callback($length) returns string to proceed, null for EOF
*/
const SOURCE_CALLBACK = 16;
/**
* Resumes an upload
*/
const RESUME = 4;
/**
* Append a local file to an already existing remote file
*/
const RESUME_START = 8;
/**#@-*/
/**
* Packet Types
*
* @see self::__construct()
* @var array
* @access private
*/
private $packet_types = [];
/**
* Status Codes
*
* @see self::__construct()
* @var array
* @access private
*/
private $status_codes = [];
/**
* The Request ID
*
* The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
* concurrent actions, so it's somewhat academic, here.
*
* @var boolean
* @see self::_send_sftp_packet()
* @access private
*/
private $use_request_id = false;
/**
* The Packet Type
*
* The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
* concurrent actions, so it's somewhat academic, here.
*
* @var int
* @see self::_get_sftp_packet()
* @access private
*/
private $packet_type = -1;
/**
* Packet Buffer
*
* @var string
* @see self::_get_sftp_packet()
* @access private
*/
private $packet_buffer = '';
/**
* Extensions supported by the server
*
* @var array
* @see self::_initChannel()
* @access private
*/
private $extensions = [];
/**
* Server SFTP version
*
* @var int
* @see self::_initChannel()
* @access private
*/
private $version;
/**
* Current working directory
*
* @var string
* @see self::realpath()
* @see self::chdir()
* @access private
*/
private $pwd = false;
/**
* Packet Type Log
*
* @see self::getLog()
* @var array
* @access private
*/
private $packet_type_log = [];
/**
* Packet Log
*
* @see self::getLog()
* @var array
* @access private
*/
private $packet_log = [];
/**
* Error information
*
* @see self::getSFTPErrors()
* @see self::getLastSFTPError()
* @var array
* @access private
*/
private $sftp_errors = [];
/**
* Stat Cache
*
* Rather than always having to open a directory and close it immediately there after to see if a file is a directory
* we'll cache the results.
*
* @see self::_update_stat_cache()
* @see self::_remove_from_stat_cache()
* @see self::_query_stat_cache()
* @var array
* @access private
*/
private $stat_cache = [];
/**
* Max SFTP Packet Size
*
* @see self::__construct()
* @see self::get()
* @var array
* @access private
*/
private $max_sftp_packet;
/**
* Stat Cache Flag
*
* @see self::disableStatCache()
* @see self::enableStatCache()
* @var bool
* @access private
*/
private $use_stat_cache = true;
/**
* Sort Options
*
* @see self::_comparator()
* @see self::setListOrder()
* @var array
* @access private
*/
private $sortOptions = [];
/**
* Canonicalization Flag
*
* Determines whether or not paths should be canonicalized before being
* passed on to the remote server.
*
* @see self::enablePathCanonicalization()
* @see self::disablePathCanonicalization()
* @see self::realpath()
* @var bool
* @access private
*/
private $canonicalize_paths = true;
/**
* Request Buffers
*
* @see self::_get_sftp_packet()
* @var array
* @access private
*/
var $requestBuffer = array();
/**
* Default Constructor.
*
* Connects to an SFTP server
*
* @param string $host
* @param int $port
* @param int $timeout
* @return \phpseclib\Net\SFTP
* @access public
*/
public function __construct($host, $port = 22, $timeout = 10)
{
parent::__construct($host, $port, $timeout);
$this->max_sftp_packet = 1 << 15;
$this->packet_types = [
1 => 'NET_SFTP_INIT',
2 => 'NET_SFTP_VERSION',
/* the format of SSH_FXP_OPEN changed between SFTPv4 and SFTPv5+:
SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.1
pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3 */
3 => 'NET_SFTP_OPEN',
4 => 'NET_SFTP_CLOSE',
5 => 'NET_SFTP_READ',
6 => 'NET_SFTP_WRITE',
7 => 'NET_SFTP_LSTAT',
9 => 'NET_SFTP_SETSTAT',
11 => 'NET_SFTP_OPENDIR',
12 => 'NET_SFTP_READDIR',
13 => 'NET_SFTP_REMOVE',
14 => 'NET_SFTP_MKDIR',
15 => 'NET_SFTP_RMDIR',
16 => 'NET_SFTP_REALPATH',
17 => 'NET_SFTP_STAT',
/* the format of SSH_FXP_RENAME changed between SFTPv4 and SFTPv5+:
SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.5 */
18 => 'NET_SFTP_RENAME',
19 => 'NET_SFTP_READLINK',
20 => 'NET_SFTP_SYMLINK',
101=> 'NET_SFTP_STATUS',
102=> 'NET_SFTP_HANDLE',
/* the format of SSH_FXP_NAME changed between SFTPv3 and SFTPv4+:
SFTPv4+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.4
pre-SFTPv4 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02#section-7 */
103=> 'NET_SFTP_DATA',
104=> 'NET_SFTP_NAME',
105=> 'NET_SFTP_ATTRS',
200=> 'NET_SFTP_EXTENDED'
];
$this->status_codes = [
0 => 'NET_SFTP_STATUS_OK',
1 => 'NET_SFTP_STATUS_EOF',
2 => 'NET_SFTP_STATUS_NO_SUCH_FILE',
3 => 'NET_SFTP_STATUS_PERMISSION_DENIED',
4 => 'NET_SFTP_STATUS_FAILURE',
5 => 'NET_SFTP_STATUS_BAD_MESSAGE',
6 => 'NET_SFTP_STATUS_NO_CONNECTION',
7 => 'NET_SFTP_STATUS_CONNECTION_LOST',
8 => 'NET_SFTP_STATUS_OP_UNSUPPORTED',
9 => 'NET_SFTP_STATUS_INVALID_HANDLE',
10 => 'NET_SFTP_STATUS_NO_SUCH_PATH',
11 => 'NET_SFTP_STATUS_FILE_ALREADY_EXISTS',
12 => 'NET_SFTP_STATUS_WRITE_PROTECT',
13 => 'NET_SFTP_STATUS_NO_MEDIA',
14 => 'NET_SFTP_STATUS_NO_SPACE_ON_FILESYSTEM',
15 => 'NET_SFTP_STATUS_QUOTA_EXCEEDED',
16 => 'NET_SFTP_STATUS_UNKNOWN_PRINCIPAL',
17 => 'NET_SFTP_STATUS_LOCK_CONFLICT',
18 => 'NET_SFTP_STATUS_DIR_NOT_EMPTY',
19 => 'NET_SFTP_STATUS_NOT_A_DIRECTORY',
20 => 'NET_SFTP_STATUS_INVALID_FILENAME',
21 => 'NET_SFTP_STATUS_LINK_LOOP',
22 => 'NET_SFTP_STATUS_CANNOT_DELETE',
23 => 'NET_SFTP_STATUS_INVALID_PARAMETER',
24 => 'NET_SFTP_STATUS_FILE_IS_A_DIRECTORY',
25 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT',
26 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED',
27 => 'NET_SFTP_STATUS_DELETE_PENDING',
28 => 'NET_SFTP_STATUS_FILE_CORRUPT',
29 => 'NET_SFTP_STATUS_OWNER_INVALID',
30 => 'NET_SFTP_STATUS_GROUP_INVALID',
31 => 'NET_SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK'
];
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-7.1
// the order, in this case, matters quite a lot - see \phpseclib\Net\SFTP::_parseAttributes() to understand why
$this->attributes = [
0x00000001 => 'NET_SFTP_ATTR_SIZE',
0x00000002 => 'NET_SFTP_ATTR_UIDGID', // defined in SFTPv3, removed in SFTPv4+
0x00000004 => 'NET_SFTP_ATTR_PERMISSIONS',
0x00000008 => 'NET_SFTP_ATTR_ACCESSTIME',
// 0x80000000 will yield a floating point on 32-bit systems and converting floating points to integers
// yields inconsistent behavior depending on how php is compiled. so we left shift -1 (which, in
// two's compliment, consists of all 1 bits) by 31. on 64-bit systems this'll yield 0xFFFFFFFF80000000.
// that's not a problem, however, and 'anded' and a 32-bit number, as all the leading 1 bits are ignored.
(-1 << 31) & 0xFFFFFFFF => 'NET_SFTP_ATTR_EXTENDED'
];
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3
// the flag definitions change somewhat in SFTPv5+. if SFTPv5+ support is added to this library, maybe name
// the array for that $this->open5_flags and similarly alter the constant names.
$this->open_flags = [
0x00000001 => 'NET_SFTP_OPEN_READ',
0x00000002 => 'NET_SFTP_OPEN_WRITE',
0x00000004 => 'NET_SFTP_OPEN_APPEND',
0x00000008 => 'NET_SFTP_OPEN_CREATE',
0x00000010 => 'NET_SFTP_OPEN_TRUNCATE',
0x00000020 => 'NET_SFTP_OPEN_EXCL'
];
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2
// see \phpseclib\Net\SFTP::_parseLongname() for an explanation
$this->file_types = [
1 => 'NET_SFTP_TYPE_REGULAR',
2 => 'NET_SFTP_TYPE_DIRECTORY',
3 => 'NET_SFTP_TYPE_SYMLINK',
4 => 'NET_SFTP_TYPE_SPECIAL',
5 => 'NET_SFTP_TYPE_UNKNOWN',
// the following types were first defined for use in SFTPv5+
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2
6 => 'NET_SFTP_TYPE_SOCKET',
7 => 'NET_SFTP_TYPE_CHAR_DEVICE',
8 => 'NET_SFTP_TYPE_BLOCK_DEVICE',
9 => 'NET_SFTP_TYPE_FIFO'
];
$this->define_array(
$this->packet_types,
$this->status_codes,
$this->attributes,
$this->open_flags,
$this->file_types
);
if (!defined('NET_SFTP_QUEUE_SIZE')) {
define('NET_SFTP_QUEUE_SIZE', 32);
}
}
/**
* Login
*
* @param string $username
* @param $args[] string password
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function login($username, ...$args)
{
$this->auth[] = array_merge([$username], $args);
if (!$this->sublogin($username, ...$args)) {
return false;
}
$this->window_size_server_to_client[self::CHANNEL] = $this->window_size;
$packet = Strings::packSSH2(
'CsN3',
NET_SSH2_MSG_CHANNEL_OPEN,
'session',
self::CHANNEL,
$this->window_size,
0x4000
);
$this->send_binary_packet($packet);
$this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_OPEN;
$response = $this->get_channel_packet(self::CHANNEL, true);
if ($response === false) {
return false;
}
$packet = Strings::packSSH2(
'CNsbs',
NET_SSH2_MSG_CHANNEL_REQUEST,
$this->server_channels[self::CHANNEL],
'subsystem',
true,
'sftp'
);
$this->send_binary_packet($packet);
$this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;
$response = $this->get_channel_packet(self::CHANNEL, true);
if ($response === false) {
// from PuTTY's psftp.exe
$command = "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n" .
"test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n" .
"exec sftp-server";
// we don't do $this->exec($command, false) because exec() operates on a different channel and plus the SSH_MSG_CHANNEL_OPEN that exec() does
// is redundant
$packet = Strings::packSSH2(
'CNsCs',
NET_SSH2_MSG_CHANNEL_REQUEST,
$this->server_channels[self::CHANNEL],
'exec',
1,
$command
);
$this->send_binary_packet($packet);
$this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;
$response = $this->get_channel_packet(self::CHANNEL, true);
if ($response === false) {
return false;
}
}
$this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_DATA;
if (!$this->send_sftp_packet(NET_SFTP_INIT, "\0\0\0\3")) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_VERSION) {
throw new \UnexpectedValueException('Expected NET_SFTP_VERSION. '
. 'Got packet type: ' . $this->packet_type);
}
list($this->version) = Strings::unpackSSH2('N', $response);
while (!empty($response)) {
list($key, $value) = Strings::unpackSSH2('ss', $response);
$this->extensions[$key] = $value;
}
/*
SFTPv4+ defines a 'newline' extension. SFTPv3 seems to have unofficial support for it via '[email protected]',
however, I'm not sure what '[email protected]' is supposed to do (the fact that it's unofficial means that it's
not in the official SFTPv3 specs) and '[email protected]' / 'newline' are likely not drop-in substitutes for
one another due to the fact that 'newline' comes with a SSH_FXF_TEXT bitmask whereas it seems unlikely that
'[email protected]' would.
*/
/*
if (isset($this->extensions['[email protected]'])) {
$this->extensions['newline'] = $this->extensions['[email protected]'];
unset($this->extensions['[email protected]']);
}
*/
$this->use_request_id = true;
/*
A Note on SFTPv4/5/6 support:
<http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.1> states the following:
"If the client wishes to interoperate with servers that support noncontiguous version
numbers it SHOULD send '3'"
Given that the server only sends its version number after the client has already done so, the above
seems to be suggesting that v3 should be the default version. This makes sense given that v3 is the
most popular.
<http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.5> states the following;
"If the server did not send the "versions" extension, or the version-from-list was not included, the
server MAY send a status response describing the failure, but MUST then close the channel without
processing any further requests."
So what do you do if you have a client whose initial SSH_FXP_INIT packet says it implements v3 and
a server whose initial SSH_FXP_VERSION reply says it implements v4 and only v4? If it only implements
v4, the "versions" extension is likely not going to have been sent so version re-negotiation as discussed
in draft-ietf-secsh-filexfer-13 would be quite impossible. As such, what \phpseclib\Net\SFTP would do is close the
channel and reopen it with a new and updated SSH_FXP_INIT packet.
*/
switch ($this->version) {
case 2:
case 3:
break;
default:
return false;
}
$this->pwd = $this->realpath('.');
$this->update_stat_cache($this->pwd, []);
return true;
}
/**
* Disable the stat cache
*
* @access public
*/
function disableStatCache()
{
$this->use_stat_cache = false;
}
/**
* Enable the stat cache
*
* @access public
*/
public function enableStatCache()
{
$this->use_stat_cache = true;
}
/**
* Clear the stat cache
*
* @access public
*/
public function clearStatCache()
{
$this->stat_cache = [];
}
/**
* Enable path canonicalization
*
* @access public
*/
public function enablePathCanonicalization()
{
$this->canonicalize_paths = true;
}
/**
* Enable path canonicalization
*
* @access public
*/
public function disablePathCanonicalization()
{
$this->canonicalize_paths = false;
}
/**
* Returns the current directory name
*
* @return mixed
* @access public
*/
public function pwd()
{
return $this->pwd;
}
/**
* Logs errors
*
* @param string $response
* @param int $status
* @access private
*/
private function logError($response, $status = -1)
{
if ($status == -1) {
list($status) = Strings::unpackSSH2('N', $response);
}
list($error) = $this->status_codes[$status];
if ($this->version > 2) {
list($message) = Strings::unpackSSH2('s', $response);
$this->sftp_errors[] = "$error: $message";
} else {
$this->sftp_errors[] = $error;
}
}
/**
* Canonicalize the Server-Side Path Name
*
* SFTP doesn't provide a mechanism by which the current working directory can be changed, so we'll emulate it. Returns
* the absolute (canonicalized) path.
*
* If canonicalize_paths has been disabled using disablePathCanonicalization(), $path is returned as-is.
*
* @see self::chdir()
* @see self::disablePathCanonicalization()
* @param string $path
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access public
*/
public function realpath($path)
{
if (!$this->canonicalize_paths) {
return $path;
}
if ($this->pwd === false) {
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.9
if (!$this->send_sftp_packet(NET_SFTP_REALPATH, Strings::packSSH2('s', $path))) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_NAME:
// although SSH_FXP_NAME is implemented differently in SFTPv3 than it is in SFTPv4+, the following
// should work on all SFTP versions since the only part of the SSH_FXP_NAME packet the following looks
// at is the first part and that part is defined the same in SFTP versions 3 through 6.
list(, $filename) = Strings::unpackSSH2('Ns', $response);
return $filename;
case NET_SFTP_STATUS:
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_NAME or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
if ($path[0] != '/') {
$path = $this->pwd . '/' . $path;
}
$path = explode('/', $path);
$new = [];
foreach ($path as $dir) {
if (!strlen($dir)) {
continue;
}
switch ($dir) {
case '..':
array_pop($new);
case '.':
break;
default:
$new[] = $dir;
}
}
return '/' . implode('/', $new);
}
/**
* Changes the current directory
*
* @param string $dir
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function chdir($dir)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
// assume current dir if $dir is empty
if ($dir === '') {
$dir = './';
// suffix a slash if needed
} elseif ($dir[strlen($dir) - 1] != '/') {
$dir.= '/';
}
$dir = $this->realpath($dir);
// confirm that $dir is, in fact, a valid directory
if ($this->use_stat_cache && is_array($this->query_stat_cache($dir))) {
$this->pwd = $dir;
return true;
}
// we could do a stat on the alleged $dir to see if it's a directory but that doesn't tell us
// the currently logged in user has the appropriate permissions or not. maybe you could see if
// the file's uid / gid match the currently logged in user's uid / gid but how there's no easy
// way to get those with SFTP
if (!$this->send_sftp_packet(NET_SFTP_OPENDIR, Strings::packSSH2('s', $dir))) {
return false;
}
// see \phpseclib\Net\SFTP::nlist() for a more thorough explanation of the following
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
$handle = substr($response, 4);
break;
case NET_SFTP_STATUS:
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS' .
'Got packet type: ' . $this->packet_type);
}
if (!$this->close_handle($handle)) {
return false;
}
$this->update_stat_cache($dir, []);
$this->pwd = $dir;
return true;
}
/**
* Returns a list of files in the given directory
*
* @param string $dir
* @param bool $recursive
* @return mixed
* @access public
*/
public function nlist($dir = '.', $recursive = false)
{
return $this->nlist_helper($dir, $recursive, '');
}
/**
* Helper method for nlist
*
* @param string $dir
* @param bool $recursive
* @param string $relativeDir
* @return mixed
* @access private
*/
private function nlist_helper($dir, $recursive, $relativeDir)
{
$files = $this->readlist($dir, false);
if (!$recursive || $files === false) {
return $files;
}
$result = [];
foreach ($files as $value) {
if ($value == '.' || $value == '..') {
$result[] = $relativeDir . $value;
continue;
}
if (is_array($this->query_stat_cache($this->realpath($dir . '/' . $value)))) {
$temp = $this->nlist_helper($dir . '/' . $value, true, $relativeDir . $value . '/');
$temp = is_array($temp) ? $temp : [];
$result = array_merge($result, $temp);
} else {
$result[] = $relativeDir . $value;
}
}
return $result;
}
/**
* Returns a detailed list of files in the given directory
*
* @param string $dir
* @param bool $recursive
* @return mixed
* @access public
*/
public function rawlist($dir = '.', $recursive = false)
{
$files = $this->readlist($dir, true);
if (!$recursive || $files === false) {
return $files;
}
static $depth = 0;
foreach ($files as $key => $value) {
if ($depth != 0 && $key == '..') {
unset($files[$key]);
continue;
}
$is_directory = false;
if ($key != '.' && $key != '..') {
if ($this->use_stat_cache) {
$is_directory = is_array($this->query_stat_cache($this->realpath($dir . '/' . $key)));
} else {
$stat = $this->lstat($dir . '/' . $key);
$is_directory = $stat && $stat['type'] === NET_SFTP_TYPE_DIRECTORY;
}
}
if ($is_directory) {
$depth++;
$files[$key] = $this->rawlist($dir . '/' . $key, true);
$depth--;
} else {
$files[$key] = (object) $value;
}
}
return $files;
}
/**
* Reads a list, be it detailed or not, of files in the given directory
*
* @param string $dir
* @param bool $raw
* @return mixed
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access private
*/
private function readlist($dir, $raw = true)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$dir = $this->realpath($dir . '/');
if ($dir === false) {
return false;
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.2
if (!$this->send_sftp_packet(NET_SFTP_OPENDIR, Strings::packSSH2('s', $dir))) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.2
// since 'handle' is the last field in the SSH_FXP_HANDLE packet, we'll just remove the first four bytes that
// represent the length of the string and leave it at that
$handle = substr($response, 4);
break;
case NET_SFTP_STATUS:
// presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
$this->update_stat_cache($dir, []);
$contents = [];
while (true) {
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.2
// why multiple SSH_FXP_READDIR packets would be sent when the response to a single one can span arbitrarily many
// SSH_MSG_CHANNEL_DATA messages is not known to me.
if (!$this->send_sftp_packet(NET_SFTP_READDIR, Strings::packSSH2('s', $handle))) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_NAME:
list($count) = Strings::unpackSSH2('N', $response);
for ($i = 0; $i < $count; $i++) {
list($shortname, $longname) = Strings::unpackSSH2('ss', $response);
$attributes = $this->parseAttributes($response);
if (!isset($attributes['type'])) {
$fileType = $this->parseLongname($longname);
if ($fileType) {
$attributes['type'] = $fileType;
}
}
$contents[$shortname] = $attributes + ['filename' => $shortname];
if (isset($attributes['type']) && $attributes['type'] == NET_SFTP_TYPE_DIRECTORY && ($shortname != '.' && $shortname != '..')) {
$this->update_stat_cache($dir . '/' . $shortname, []);
} else {
if ($shortname == '..') {
$temp = $this->realpath($dir . '/..') . '/.';
} else {
$temp = $dir . '/' . $shortname;
}
$this->update_stat_cache($temp, (object) ['lstat' => $attributes]);
}
// SFTPv6 has an optional boolean end-of-list field, but we'll ignore that, since the
// final SSH_FXP_STATUS packet should tell us that, already.
}
break;
case NET_SFTP_STATUS:
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_EOF) {
$this->logError($response, $status);
return false;
}
break 2;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_NAME or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
if (!$this->close_handle($handle)) {
return false;
}
if (count($this->sortOptions)) {
uasort($contents, [&$this, 'comparator']);
}
return $raw ? $contents : array_keys($contents);
}
/**
* Compares two rawlist entries using parameters set by setListOrder()
*
* Intended for use with uasort()
*
* @param array $a
* @param array $b
* @return int
* @access private
*/
private function comparator($a, $b)
{
switch (true) {
case $a['filename'] === '.' || $b['filename'] === '.':
if ($a['filename'] === $b['filename']) {
return 0;
}
return $a['filename'] === '.' ? -1 : 1;
case $a['filename'] === '..' || $b['filename'] === '..':
if ($a['filename'] === $b['filename']) {
return 0;
}
return $a['filename'] === '..' ? -1 : 1;
case isset($a['type']) && $a['type'] === NET_SFTP_TYPE_DIRECTORY:
if (!isset($b['type'])) {
return 1;
}
if ($b['type'] !== $a['type']) {
return -1;
}
break;
case isset($b['type']) && $b['type'] === NET_SFTP_TYPE_DIRECTORY:
return 1;
}
foreach ($this->sortOptions as $sort => $order) {
if (!isset($a[$sort]) || !isset($b[$sort])) {
if (isset($a[$sort])) {
return -1;
}
if (isset($b[$sort])) {
return 1;
}
return 0;
}
switch ($sort) {
case 'filename':
$result = strcasecmp($a['filename'], $b['filename']);
if ($result) {
return $order === SORT_DESC ? -$result : $result;
}
break;
case 'permissions':
case 'mode':
$a[$sort]&= 07777;
$b[$sort]&= 07777;
default:
if ($a[$sort] === $b[$sort]) {
break;
}
return $order === SORT_ASC ? $a[$sort] - $b[$sort] : $b[$sort] - $a[$sort];
}
}
}
/**
* Defines how nlist() and rawlist() will be sorted - if at all.
*
* If sorting is enabled directories and files will be sorted independently with
* directories appearing before files in the resultant array that is returned.
*
* Any parameter returned by stat is a valid sort parameter for this function.
* Filename comparisons are case insensitive.
*
* Examples:
*
* $sftp->setListOrder('filename', SORT_ASC);
* $sftp->setListOrder('size', SORT_DESC, 'filename', SORT_ASC);
* $sftp->setListOrder(true);
* Separates directories from files but doesn't do any sorting beyond that
* $sftp->setListOrder();
* Don't do any sort of sorting
*
* @param $args[]
* @access public
*/
public function setListOrder(...$args)
{
$this->sortOptions = [];
if (empty($args)) {
return;
}
$len = count($args) & 0x7FFFFFFE;
for ($i = 0; $i < $len; $i+=2) {
$this->sortOptions[$args[$i]] = $args[$i + 1];
}
if (!count($this->sortOptions)) {
$this->sortOptions = ['bogus' => true];
}
}
/**
* Returns the file size, in bytes, or false, on failure
*
* Files larger than 4GB will show up as being exactly 4GB.
*
* @param string $filename
* @return mixed
* @access public
*/
public function size($filename)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$result = $this->stat($filename);
if ($result === false) {
return false;
}
return isset($result['size']) ? $result['size'] : -1;
}
/**
* Save files / directories to cache
*
* @param string $path
* @param mixed $value
* @access private
*/
private function update_stat_cache($path, $value)
{
if ($this->use_stat_cache === false) {
return;
}
// preg_replace('#^/|/(?=/)|/$#', '', $dir) == str_replace('//', '/', trim($path, '/'))
$dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
$temp = &$this->stat_cache;
$max = count($dirs) - 1;
foreach ($dirs as $i => $dir) {
// if $temp is an object that means one of two things.
// 1. a file was deleted and changed to a directory behind phpseclib's back
// 2. it's a symlink. when lstat is done it's unclear what it's a symlink to
if (is_object($temp)) {
$temp = [];
}
if (!isset($temp[$dir])) {
$temp[$dir] = [];
}
if ($i === $max) {
if (is_object($temp[$dir]) && is_object($value)) {
if (!isset($value->stat) && isset($temp[$dir]->stat)) {
$value->stat = $temp[$dir]->stat;
}
if (!isset($value->lstat) && isset($temp[$dir]->lstat)) {
$value->lstat = $temp[$dir]->lstat;
}
}
$temp[$dir] = $value;
break;
}
$temp = &$temp[$dir];
}
}
/**
* Remove files / directories from cache
*
* @param string $path
* @return bool
* @access private
*/
private function remove_from_stat_cache($path)
{
$dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
$temp = &$this->stat_cache;
$max = count($dirs) - 1;
foreach ($dirs as $i => $dir) {
if ($i === $max) {
unset($temp[$dir]);
return true;
}
if (!isset($temp[$dir])) {
return false;
}
$temp = &$temp[$dir];
}
}
/**
* Checks cache for path
*
* Mainly used by file_exists
*
* @param string $path
* @return mixed
* @access private
*/
private function query_stat_cache($path)
{
$dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
$temp = &$this->stat_cache;
foreach ($dirs as $dir) {
if (!isset($temp[$dir])) {
return null;
}
$temp = &$temp[$dir];
}
return $temp;
}
/**
* Returns general information about a file.
*
* Returns an array on success and false otherwise.
*
* @param string $filename
* @return mixed
* @access public
*/
public function stat($filename)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$filename = $this->realpath($filename);
if ($filename === false) {
return false;
}
if ($this->use_stat_cache) {
$result = $this->query_stat_cache($filename);
if (is_array($result) && isset($result['.']) && isset($result['.']->stat)) {
return $result['.']->stat;
}
if (is_object($result) && isset($result->stat)) {
return $result->stat;
}
}
$stat = $this->stat_helper($filename, NET_SFTP_STAT);
if ($stat === false) {
$this->remove_from_stat_cache($filename);
return false;
}
if (isset($stat['type'])) {
if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
$filename.= '/.';
}
$this->update_stat_cache($filename, (object) ['stat' => $stat]);
return $stat;
}
$pwd = $this->pwd;
$stat['type'] = $this->chdir($filename) ?
NET_SFTP_TYPE_DIRECTORY :
NET_SFTP_TYPE_REGULAR;
$this->pwd = $pwd;
if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
$filename.= '/.';
}
$this->update_stat_cache($filename, (object) ['stat' => $stat]);
return $stat;
}
/**
* Returns general information about a file or symbolic link.
*
* Returns an array on success and false otherwise.
*
* @param string $filename
* @return mixed
* @access public
*/
public function lstat($filename)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$filename = $this->realpath($filename);
if ($filename === false) {
return false;
}
if ($this->use_stat_cache) {
$result = $this->query_stat_cache($filename);
if (is_array($result) && isset($result['.']) && isset($result['.']->lstat)) {
return $result['.']->lstat;
}
if (is_object($result) && isset($result->lstat)) {
return $result->lstat;
}
}
$lstat = $this->stat_helper($filename, NET_SFTP_LSTAT);
if ($lstat === false) {
$this->remove_from_stat_cache($filename);
return false;
}
if (isset($lstat['type'])) {
if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) {
$filename.= '/.';
}
$this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
return $lstat;
}
$stat = $this->stat_helper($filename, NET_SFTP_STAT);
if ($lstat != $stat) {
$lstat = array_merge($lstat, ['type' => NET_SFTP_TYPE_SYMLINK]);
$this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
return $stat;
}
$pwd = $this->pwd;
$lstat['type'] = $this->chdir($filename) ?
NET_SFTP_TYPE_DIRECTORY :
NET_SFTP_TYPE_REGULAR;
$this->pwd = $pwd;
if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) {
$filename.= '/.';
}
$this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
return $lstat;
}
/**
* Returns general information about a file or symbolic link
*
* Determines information without calling \phpseclib\Net\SFTP::realpath().
* The second parameter can be either NET_SFTP_STAT or NET_SFTP_LSTAT.
*
* @param string $filename
* @param int $type
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access private
*/
private function stat_helper($filename, $type)
{
// SFTPv4+ adds an additional 32-bit integer field - flags - to the following:
$packet = Strings::packSSH2('s', $filename);
if (!$this->send_sftp_packet($type, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_ATTRS:
return $this->parseAttributes($response);
case NET_SFTP_STATUS:
$this->logError($response);
return false;
}
throw new \UnexpectedValueException('Expected NET_SFTP_ATTRS or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
/**
* Truncates a file to a given length
*
* @param string $filename
* @param int $new_size
* @return bool
* @access public
*/
public function truncate($filename, $new_size)
{
$attr = pack('N3', NET_SFTP_ATTR_SIZE, $new_size / 4294967296, $new_size); // 4294967296 == 0x100000000 == 1<<32
return $this->setstat($filename, $attr, false);
}
/**
* Sets access and modification time of file.
*
* If the file does not exist, it will be created.
*
* @param string $filename
* @param int $time
* @param int $atime
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function touch($filename, $time = null, $atime = null)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$filename = $this->realpath($filename);
if ($filename === false) {
return false;
}
if (!isset($time)) {
$time = time();
}
if (!isset($atime)) {
$atime = $time;
}
$flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE | NET_SFTP_OPEN_EXCL;
$attr = pack('N3', NET_SFTP_ATTR_ACCESSTIME, $time, $atime);
$packet = Strings::packSSH2('sN', $filename, $flags) . $attr;
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
return $this->close_handle(substr($response, 4));
case NET_SFTP_STATUS:
$this->logError($response);
break;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
return $this->setstat($filename, $attr, false);
}
/**
* Changes file or directory owner
*
* Returns true on success or false on error.
*
* @param string $filename
* @param int $uid
* @param bool $recursive
* @return bool
* @access public
*/
public function chown($filename, $uid, $recursive = false)
{
// quoting from <http://www.kernel.org/doc/man-pages/online/pages/man2/chown.2.html>,
// "if the owner or group is specified as -1, then that ID is not changed"
$attr = pack('N3', NET_SFTP_ATTR_UIDGID, $uid, -1);
return $this->setstat($filename, $attr, $recursive);
}
/**
* Changes file or directory group
*
* Returns true on success or false on error.
*
* @param string $filename
* @param int $gid
* @param bool $recursive
* @return bool
* @access public
*/
public function chgrp($filename, $gid, $recursive = false)
{
$attr = pack('N3', NET_SFTP_ATTR_UIDGID, -1, $gid);
return $this->setstat($filename, $attr, $recursive);
}
/**
* Set permissions on a file.
*
* Returns the new file permissions on success or false on error.
* If $recursive is true than this just returns true or false.
*
* @param int $mode
* @param string $filename
* @param bool $recursive
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access public
*/
public function chmod($mode, $filename, $recursive = false)
{
if (is_string($mode) && is_int($filename)) {
$temp = $mode;
$mode = $filename;
$filename = $temp;
}
$attr = pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777);
if (!$this->setstat($filename, $attr, $recursive)) {
return false;
}
if ($recursive) {
return true;
}
$filename = $this->realpath($filename);
// rather than return what the permissions *should* be, we'll return what they actually are. this will also
// tell us if the file actually exists.
// incidentally, SFTPv4+ adds an additional 32-bit integer field - flags - to the following:
$packet = pack('Na*', strlen($filename), $filename);
if (!$this->send_sftp_packet(NET_SFTP_STAT, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_ATTRS:
$attrs = $this->parseAttributes($response);
return $attrs['permissions'];
case NET_SFTP_STATUS:
$this->logError($response);
return false;
}
throw new \UnexpectedValueException('Expected NET_SFTP_ATTRS or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
/**
* Sets information about a file
*
* @param string $filename
* @param string $attr
* @param bool $recursive
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access private
*/
private function setstat($filename, $attr, $recursive)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$filename = $this->realpath($filename);
if ($filename === false) {
return false;
}
$this->remove_from_stat_cache($filename);
if ($recursive) {
$i = 0;
$result = $this->setstat_recursive($filename, $attr, $i);
$this->read_put_responses($i);
return $result;
}
// SFTPv4+ has an additional byte field - type - that would need to be sent, as well. setting it to
// SSH_FILEXFER_TYPE_UNKNOWN might work. if not, we'd have to do an SSH_FXP_STAT before doing an SSH_FXP_SETSTAT.
if (!$this->send_sftp_packet(NET_SFTP_SETSTAT, Strings::packSSH2('s', $filename) . $attr)) {
return false;
}
/*
"Because some systems must use separate system calls to set various attributes, it is possible that a failure
response will be returned, but yet some of the attributes may be have been successfully modified. If possible,
servers SHOULD avoid this situation; however, clients MUST be aware that this is possible."
-- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.6
*/
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
return true;
}
/**
* Recursively sets information on directories on the SFTP server
*
* Minimizes directory lookups and SSH_FXP_STATUS requests for speed.
*
* @param string $path
* @param string $attr
* @param int $i
* @return bool
* @access private
*/
private function setstat_recursive($path, $attr, &$i)
{
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
$entries = $this->readlist($path, true);
if ($entries === false) {
return $this->setstat($path, $attr, false);
}
// normally $entries would have at least . and .. but it might not if the directories
// permissions didn't allow reading
if (empty($entries)) {
return false;
}
unset($entries['.'], $entries['..']);
foreach ($entries as $filename => $props) {
if (!isset($props['type'])) {
return false;
}
$temp = $path . '/' . $filename;
if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) {
if (!$this->setstat_recursive($temp, $attr, $i)) {
return false;
}
} else {
if (!$this->send_sftp_packet(NET_SFTP_SETSTAT, Strings::packSSH2('s', $temp) . $attr)) {
return false;
}
$i++;
if ($i >= NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
}
}
}
if (!$this->send_sftp_packet(NET_SFTP_SETSTAT, Strings::packSSH2('s', $path) . $attr)) {
return false;
}
$i++;
if ($i >= NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
}
return true;
}
/**
* Return the target of a symbolic link
*
* @param string $link
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access public
*/
public function readlink($link)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$link = $this->realpath($link);
if (!$this->send_sftp_packet(NET_SFTP_READLINK, Strings::packSSH2('s', $link))) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_NAME:
break;
case NET_SFTP_STATUS:
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_NAME or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($count) = Strings::unpackSSH2('N', $response);
// the file isn't a symlink
if (!$count) {
return false;
}
list($filename) = Strings::unpackSSH2('s', $response);
return $filename;
}
/**
* Create a symlink
*
* symlink() creates a symbolic link to the existing target with the specified name link.
*
* @param string $target
* @param string $link
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function symlink($target, $link)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
//$target = $this->realpath($target);
$link = $this->realpath($link);
$packet = Strings::packSSH2('ss', $target, $link);
if (!$this->send_sftp_packet(NET_SFTP_SYMLINK, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
return true;
}
/**
* Creates a directory.
*
* @param string $dir
* @param int $mode
* @param bool $recursive
* @return bool
* @access public
*/
public function mkdir($dir, $mode = -1, $recursive = false)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$dir = $this->realpath($dir);
// by not providing any permissions, hopefully the server will use the logged in users umask - their
// default permissions.
$attr = $mode == -1 ? "\0\0\0\0" : pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777);
if ($recursive) {
$dirs = explode('/', preg_replace('#/(?=/)|/$#', '', $dir));
if (empty($dirs[0])) {
array_shift($dirs);
$dirs[0] = '/' . $dirs[0];
}
for ($i = 0; $i < count($dirs); $i++) {
$temp = array_slice($dirs, 0, $i + 1);
$temp = implode('/', $temp);
$result = $this->mkdir_helper($temp, $attr);
}
return $result;
}
return $this->mkdir_helper($dir, $attr);
}
/**
* Helper function for directory creation
*
* @param string $dir
* @param string $attr
* @return bool
* @access private
*/
private function mkdir_helper($dir, $attr)
{
if (!$this->send_sftp_packet(NET_SFTP_MKDIR, Strings::packSSH2('s', $dir) . $attr)) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
return true;
}
/**
* Removes a directory.
*
* @param string $dir
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function rmdir($dir)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$dir = $this->realpath($dir);
if ($dir === false) {
return false;
}
if (!$this->send_sftp_packet(NET_SFTP_RMDIR, Strings::packSSH2('s', $dir))) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
// presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED?
$this->logError($response, $status);
return false;
}
$this->remove_from_stat_cache($dir);
// the following will do a soft delete, which would be useful if you deleted a file
// and then tried to do a stat on the deleted file. the above, in contrast, does
// a hard delete
//$this->update_stat_cache($dir, false);
return true;
}
/**
* Uploads a file to the SFTP server.
*
* By default, \phpseclib\Net\SFTP::put() does not read from the local filesystem. $data is dumped directly into $remote_file.
* So, for example, if you set $data to 'filename.ext' and then do \phpseclib\Net\SFTP::get(), you will get a file, twelve bytes
* long, containing 'filename.ext' as its contents.
*
* Setting $mode to self::SOURCE_LOCAL_FILE will change the above behavior. With self::SOURCE_LOCAL_FILE, $remote_file will
* contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how
* large $remote_file will be, as well.
*
* Setting $mode to self::SOURCE_CALLBACK will use $data as callback function, which gets only one parameter -- number of bytes to return, and returns a string if there is some data or null if there is no more data
*
* If $data is a resource then it'll be used as a resource instead.
*
* Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take
* care of that, yourself.
*
* $mode can take an additional two parameters - self::RESUME and self::RESUME_START. These are bitwise AND'd with
* $mode. So if you want to resume upload of a 300mb file on the local file system you'd set $mode to the following:
*
* self::SOURCE_LOCAL_FILE | self::RESUME
*
* If you wanted to simply append the full contents of a local file to the full contents of a remote file you'd replace
* self::RESUME with self::RESUME_START.
*
* If $mode & (self::RESUME | self::RESUME_START) then self::RESUME_START will be assumed.
*
* $start and $local_start give you more fine grained control over this process and take precident over self::RESUME
* when they're non-negative. ie. $start could let you write at the end of a file (like self::RESUME) or in the middle
* of one. $local_start could let you start your reading from the end of a file (like self::RESUME_START) or in the
* middle of one.
*
* Setting $local_start to > 0 or $mode | self::RESUME_START doesn't do anything unless $mode | self::SOURCE_LOCAL_FILE.
*
* @param string $remote_file
* @param string|resource $data
* @param int $mode
* @param int $start
* @param int $local_start
* @param callable|null $progressCallback
* @throws \UnexpectedValueException on receipt of unexpected packets
* @throws \BadFunctionCallException if you're uploading via a callback and the callback function is invalid
* @throws \phpseclib\Exception\FileNotFoundException if you're uploading via a file and the file doesn't exist
* @return bool
* @access public
* @internal ASCII mode for SFTPv4/5/6 can be supported by adding a new function - \phpseclib\Net\SFTP::setMode().
*/
public function put($remote_file, $data, $mode = self::SOURCE_STRING, $start = -1, $local_start = -1, $progressCallback = null)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$remote_file = $this->realpath($remote_file);
if ($remote_file === false) {
return false;
}
$this->remove_from_stat_cache($remote_file);
$flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE;
// according to the SFTP specs, NET_SFTP_OPEN_APPEND should "force all writes to append data at the end of the file."
// in practice, it doesn't seem to do that.
//$flags|= ($mode & self::RESUME) ? NET_SFTP_OPEN_APPEND : NET_SFTP_OPEN_TRUNCATE;
if ($start >= 0) {
$offset = $start;
} elseif ($mode & self::RESUME) {
// if NET_SFTP_OPEN_APPEND worked as it should _size() wouldn't need to be called
$size = $this->size($remote_file);
$offset = $size !== false ? $size : 0;
} else {
$offset = 0;
$flags|= NET_SFTP_OPEN_TRUNCATE;
}
$packet = Strings::packSSH2('sNN', $remote_file, $flags, 0);
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
$handle = substr($response, 4);
break;
case NET_SFTP_STATUS:
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.3
$dataCallback = false;
switch (true) {
case $mode & self::SOURCE_CALLBACK:
if (!is_callable($data)) {
throw new \BadFunctionCallException("\$data should be is_callable() if you specify SOURCE_CALLBACK flag");
}
$dataCallback = $data;
// do nothing
break;
case is_resource($data):
$mode = $mode & ~self::SOURCE_LOCAL_FILE;
$info = stream_get_meta_data($data);
if ($info['wrapper_type'] == 'PHP' && $info['stream_type'] == 'Input') {
$fp = fopen('php://memory', 'w+');
stream_copy_to_stream($data, $fp);
rewind($fp);
} else {
$fp = $data;
}
break;
case $mode & self::SOURCE_LOCAL_FILE:
if (!is_file($data)) {
throw new FileNotFoundException("$data is not a valid file");
}
$fp = @fopen($data, 'rb');
if (!$fp) {
return false;
}
}
if (isset($fp)) {
$stat = fstat($fp);
$size = !empty($stat) ? $stat['size'] : 0;
if ($local_start >= 0) {
fseek($fp, $local_start);
$size-= $local_start;
}
} elseif ($dataCallback) {
$size = 0;
} else {
$size = strlen($data);
}
$sent = 0;
$size = $size < 0 ? ($size & 0x7FFFFFFF) + 0x80000000 : $size;
$sftp_packet_size = 4096; // PuTTY uses 4096
// make the SFTP packet be exactly 4096 bytes by including the bytes in the NET_SFTP_WRITE packets "header"
$sftp_packet_size-= strlen($handle) + 25;
$i = 0;
while ($dataCallback || ($size === 0 || $sent < $size)) {
if ($dataCallback) {
$temp = call_user_func($dataCallback, $sftp_packet_size);
if (is_null($temp)) {
break;
}
} else {
$temp = isset($fp) ? fread($fp, $sftp_packet_size) : substr($data, $sent, $sftp_packet_size);
if ($temp === false || $temp === '') {
break;
}
}
$subtemp = $offset + $sent;
$packet = pack('Na*N3a*', strlen($handle), $handle, $subtemp / 4294967296, $subtemp, strlen($temp), $temp);
if (!$this->send_sftp_packet(NET_SFTP_WRITE, $packet)) {
if ($mode & self::SOURCE_LOCAL_FILE) {
fclose($fp);
}
return false;
}
$sent+= strlen($temp);
if (is_callable($progressCallback)) {
call_user_func($progressCallback, $sent);
}
$i++;
if ($i == NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
$i = 0;
break;
}
$i = 0;
}
}
if (!$this->read_put_responses($i)) {
if ($mode & self::SOURCE_LOCAL_FILE) {
fclose($fp);
}
$this->close_handle($handle);
return false;
}
if ($mode & self::SOURCE_LOCAL_FILE) {
fclose($fp);
}
return $this->close_handle($handle);
}
/**
* Reads multiple successive SSH_FXP_WRITE responses
*
* Sending an SSH_FXP_WRITE packet and immediately reading its response isn't as efficient as blindly sending out $i
* SSH_FXP_WRITEs, in succession, and then reading $i responses.
*
* @param int $i
* @return bool
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access private
*/
private function read_put_responses($i)
{
while ($i--) {
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
break;
}
}
return $i < 0;
}
/**
* Close handle
*
* @param string $handle
* @return bool
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access private
*/
private function close_handle($handle)
{
if (!$this->send_sftp_packet(NET_SFTP_CLOSE, pack('Na*', strlen($handle), $handle))) {
return false;
}
// "The client MUST release all resources associated with the handle regardless of the status."
// -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.3
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
return true;
}
/**
* Downloads a file from the SFTP server.
*
* Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if
* the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the
* operation.
*
* $offset and $length can be used to download files in chunks.
*
* @param string $remote_file
* @param string|bool|resource $local_file
* @param int $offset
* @param int $length
* @param callable|null $progressCallback
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access public
*/
public function get($remote_file, $local_file = false, $offset = 0, $length = -1, $progressCallback = null)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$remote_file = $this->realpath($remote_file);
if ($remote_file === false) {
return false;
}
$packet = pack('Na*N2', strlen($remote_file), $remote_file, NET_SFTP_OPEN_READ, 0);
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
$handle = substr($response, 4);
break;
case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
if (is_resource($local_file)) {
$fp = $local_file;
$stat = fstat($fp);
$res_offset = $stat['size'];
} else {
$res_offset = 0;
if ($local_file !== false) {
$fp = fopen($local_file, 'wb');
if (!$fp) {
return false;
}
} else {
$content = '';
}
}
$fclose_check = $local_file !== false && !is_resource($local_file);
$start = $offset;
$read = 0;
while (true) {
$i = 0;
while ($i < NET_SFTP_QUEUE_SIZE && ($length < 0 || $read < $length)) {
$tempoffset = $start + $read;
$packet_size = $length > 0 ? min($this->max_sftp_packet, $length - $read) : $this->max_sftp_packet;
$packet = Strings::packSSH2('sN3', $handle, $tempoffset / 4294967296, $tempoffset, $packet_size);
if (!$this->send_sftp_packet(NET_SFTP_READ, $packet, $i)) {
if ($fclose_check) {
fclose($fp);
}
return false;
}
$packet = null;
$read+= $packet_size;
if (is_callable($progressCallback)) {
call_user_func($progressCallback, $read);
}
$i++;
}
if (!$i) {
break;
}
$packets_sent = $i - 1;
$clear_responses = false;
while ($i > 0) {
$i--;
if ($clear_responses) {
$this->get_sftp_packet($packets_sent - $i);
continue;
} else {
$response = $this->get_sftp_packet($packets_sent - $i);
}
switch ($this->packet_type) {
case NET_SFTP_DATA:
$temp = substr($response, 4);
$offset+= strlen($temp);
if ($local_file === false) {
$content.= $temp;
} else {
fputs($fp, $temp);
}
$temp = null;
break;
case NET_SFTP_STATUS:
// could, in theory, return false if !strlen($content) but we'll hold off for the time being
$this->logError($response);
$clear_responses = true; // don't break out of the loop yet, so we can read the remaining responses
break;
default:
if ($fclose_check) {
fclose($fp);
}
throw new \UnexpectedValueException('Expected NET_SFTP_DATA or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
$response = null;
}
if ($clear_responses) {
break;
}
}
if ($length > 0 && $length <= $offset - $start) {
if ($local_file === false) {
$content = substr($content, 0, $length);
} else {
ftruncate($fp, $length + $res_offset);
}
}
if ($fclose_check) {
fclose($fp);
}
if (!$this->close_handle($handle)) {
return false;
}
// if $content isn't set that means a file was written to
return isset($content) ? $content : true;
}
/**
* Deletes a file on the SFTP server.
*
* @param string $path
* @param bool $recursive
* @return bool
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access public
*/
public function delete($path, $recursive = true)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
if (is_object($path)) {
// It's an object. Cast it as string before we check anything else.
$path = (string) $path;
}
if (!is_string($path) || $path == '') {
return false;
}
$path = $this->realpath($path);
if ($path === false) {
return false;
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
if (!$this->send_sftp_packet(NET_SFTP_REMOVE, pack('Na*', strlen($path), $path))) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
// if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
if (!$recursive) {
return false;
}
$i = 0;
$result = $this->delete_recursive($path, $i);
$this->read_put_responses($i);
return $result;
}
$this->remove_from_stat_cache($path);
return true;
}
/**
* Recursively deletes directories on the SFTP server
*
* Minimizes directory lookups and SSH_FXP_STATUS requests for speed.
*
* @param string $path
* @param int $i
* @return bool
* @access private
*/
private function delete_recursive($path, &$i)
{
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
$entries = $this->readlist($path, true);
// normally $entries would have at least . and .. but it might not if the directories
// permissions didn't allow reading
if (empty($entries)) {
return false;
}
unset($entries['.'], $entries['..']);
foreach ($entries as $filename => $props) {
if (!isset($props['type'])) {
return false;
}
$temp = $path . '/' . $filename;
if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) {
if (!$this->delete_recursive($temp, $i)) {
return false;
}
} else {
if (!$this->send_sftp_packet(NET_SFTP_REMOVE, Strings::packSSH2('s', $temp))) {
return false;
}
$this->remove_from_stat_cache($temp);
$i++;
if ($i >= NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
}
}
}
if (!$this->send_sftp_packet(NET_SFTP_RMDIR, Strings::packSSH2('s', $path))) {
return false;
}
$this->remove_from_stat_cache($path);
$i++;
if ($i >= NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
}
return true;
}
/**
* Checks whether a file or directory exists
*
* @param string $path
* @return bool
* @access public
*/
public function file_exists($path)
{
if ($this->use_stat_cache) {
$path = $this->realpath($path);
$result = $this->query_stat_cache($path);
if (isset($result)) {
// return true if $result is an array or if it's an stdClass object
return $result !== false;
}
}
return $this->stat($path) !== false;
}
/**
* Tells whether the filename is a directory
*
* @param string $path
* @return bool
* @access public
*/
public function is_dir($path)
{
$result = $this->get_stat_cache_prop($path, 'type');
if ($result === false) {
return false;
}
return $result === NET_SFTP_TYPE_DIRECTORY;
}
/**
* Tells whether the filename is a regular file
*
* @param string $path
* @return bool
* @access public
*/
public function is_file($path)
{
$result = $this->get_stat_cache_prop($path, 'type');
if ($result === false) {
return false;
}
return $result === NET_SFTP_TYPE_REGULAR;
}
/**
* Tells whether the filename is a symbolic link
*
* @param string $path
* @return bool
* @access public
*/
public function is_link($path)
{
$result = $this->get_lstat_cache_prop($path, 'type');
if ($result === false) {
return false;
}
return $result === NET_SFTP_TYPE_SYMLINK;
}
/**
* Tells whether a file exists and is readable
*
* @param string $path
* @return bool
* @access public
*/
public function is_readable($path)
{
$packet = Strings::packSSH2('sNN', $this->realpath($path), NET_SFTP_OPEN_READ, 0);
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
return true;
case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
/**
* Tells whether the filename is writable
*
* @param string $path
* @return bool
* @access public
*/
public function is_writable($path)
{
$packet = Strings::packSSH2('sNN', $this->realpath($path), NET_SFTP_OPEN_WRITE, 0);
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
return true;
case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
return false;
default:
throw new \UnexpectedValueException('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
/**
* Tells whether the filename is writeable
*
* Alias of is_writable
*
* @param string $path
* @return bool
* @access public
*/
public function is_writeable($path)
{
return $this->is_writable($path);
}
/**
* Gets last access time of file
*
* @param string $path
* @return mixed
* @access public
*/
public function fileatime($path)
{
return $this->get_stat_cache_prop($path, 'atime');
}
/**
* Gets file modification time
*
* @param string $path
* @return mixed
* @access public
*/
public function filemtime($path)
{
return $this->get_stat_cache_prop($path, 'mtime');
}
/**
* Gets file permissions
*
* @param string $path
* @return mixed
* @access public
*/
public function fileperms($path)
{
return $this->get_stat_cache_prop($path, 'permissions');
}
/**
* Gets file owner
*
* @param string $path
* @return mixed
* @access public
*/
public function fileowner($path)
{
return $this->get_stat_cache_prop($path, 'uid');
}
/**
* Gets file group
*
* @param string $path
* @return mixed
* @access public
*/
public function filegroup($path)
{
return $this->get_stat_cache_prop($path, 'gid');
}
/**
* Gets file size
*
* @param string $path
* @return mixed
* @access public
*/
public function filesize($path)
{
return $this->get_stat_cache_prop($path, 'size');
}
/**
* Gets file type
*
* @param string $path
* @return mixed
* @access public
*/
public function filetype($path)
{
$type = $this->get_stat_cache_prop($path, 'type');
if ($type === false) {
return false;
}
switch ($type) {
case NET_SFTP_TYPE_BLOCK_DEVICE:
return 'block';
case NET_SFTP_TYPE_CHAR_DEVICE:
return 'char';
case NET_SFTP_TYPE_DIRECTORY:
return 'dir';
case NET_SFTP_TYPE_FIFO:
return 'fifo';
case NET_SFTP_TYPE_REGULAR:
return 'file';
case NET_SFTP_TYPE_SYMLINK:
return 'link';
default:
return false;
}
}
/**
* Return a stat properity
*
* Uses cache if appropriate.
*
* @param string $path
* @param string $prop
* @return mixed
* @access private
*/
private function get_stat_cache_prop($path, $prop)
{
return $this->get_xstat_cache_prop($path, $prop, 'stat');
}
/**
* Return an lstat properity
*
* Uses cache if appropriate.
*
* @param string $path
* @param string $prop
* @return mixed
* @access private
*/
private function get_lstat_cache_prop($path, $prop)
{
return $this->get_xstat_cache_prop($path, $prop, 'lstat');
}
/**
* Return a stat or lstat properity
*
* Uses cache if appropriate.
*
* @param string $path
* @param string $prop
* @param string $type
* @return mixed
* @access private
*/
private function get_xstat_cache_prop($path, $prop, $type)
{
if ($this->use_stat_cache) {
$path = $this->realpath($path);
$result = $this->query_stat_cache($path);
if (is_object($result) && isset($result->$type)) {
return $result->{$type}[$prop];
}
}
$result = $this->$type($path);
if ($result === false || !isset($result[$prop])) {
return false;
}
return $result[$prop];
}
/**
* Renames a file or a directory on the SFTP server
*
* @param string $oldname
* @param string $newname
* @return bool
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access public
*/
public function rename($oldname, $newname)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$oldname = $this->realpath($oldname);
$newname = $this->realpath($newname);
if ($oldname === false || $newname === false) {
return false;
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
$packet = Strings::packSSH2('ss', $oldname, $newname);
if (!$this->send_sftp_packet(NET_SFTP_RENAME, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
// if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
// don't move the stat cache entry over since this operation could very well change the
// atime and mtime attributes
//$this->update_stat_cache($newname, $this->query_stat_cache($oldname));
$this->remove_from_stat_cache($oldname);
$this->remove_from_stat_cache($newname);
return true;
}
/**
* Parse Attributes
*
* See '7. File Attributes' of draft-ietf-secsh-filexfer-13 for more info.
*
* @param string $response
* @return array
* @access private
*/
private function parseAttributes(&$response)
{
$attr = [];
list($flags) = Strings::unpackSSH2('N', $response);
// SFTPv4+ have a type field (a byte) that follows the above flag field
foreach ($this->attributes as $key => $value) {
switch ($flags & $key) {
case NET_SFTP_ATTR_SIZE: // 0x00000001
// The size attribute is defined as an unsigned 64-bit integer.
// The following will use floats on 32-bit platforms, if necessary.
// As can be seen in the BigInteger class, floats are generally
// IEEE 754 binary64 "double precision" on such platforms and
// as such can represent integers of at least 2^50 without loss
// of precision. Interpreted in filesize, 2^50 bytes = 1024 TiB.
list($upper, $size) = Strings::unpackSSH2('NN', $response);
$attr['size'] = $upper ? 4294967296 * $upper : 0;
$attr['size']+= $size < 0 ? ($size & 0x7FFFFFFF) + 0x80000000 : $size;
break;
case NET_SFTP_ATTR_UIDGID: // 0x00000002 (SFTPv3 only)
list($attr['uid'], $attr['gid']) = Strings::unpackSSH2('NN', $response);
break;
case NET_SFTP_ATTR_PERMISSIONS: // 0x00000004
list($attr['permissions']) = Strings::unpackSSH2('N', $response);
// mode == permissions; permissions was the original array key and is retained for bc purposes.
// mode was added because that's the more industry standard terminology
$attr+= ['mode' => $attr['permissions']];
$fileType = $this->parseMode($attr['permissions']);
if ($fileType !== false) {
$attr+= ['type' => $fileType];
}
break;
case NET_SFTP_ATTR_ACCESSTIME: // 0x00000008
list($attr['atime'], $attr['mtime']) = Strings::unpackSSH2('NN', $response);
break;
case NET_SFTP_ATTR_EXTENDED: // 0x80000000
list($count) = Strings::unpackSSH2('N', $response);
for ($i = 0; $i < $count; $i++) {
list($key, $value) = Strings::unpackSSH2('ss', $response);
$attr[$key] = $value;
}
}
}
return $attr;
}
/**
* Attempt to identify the file type
*
* Quoting the SFTP RFC, "Implementations MUST NOT send bits that are not defined" but they seem to anyway
*
* @param int $mode
* @return int
* @access private
*/
private function parseMode($mode)
{
// values come from http://lxr.free-electrons.com/source/include/uapi/linux/stat.h#L12
// see, also, http://linux.die.net/man/2/stat
switch ($mode & 0170000) {// ie. 1111 0000 0000 0000
case 0000000: // no file type specified - figure out the file type using alternative means
return false;
case 0040000:
return NET_SFTP_TYPE_DIRECTORY;
case 0100000:
return NET_SFTP_TYPE_REGULAR;
case 0120000:
return NET_SFTP_TYPE_SYMLINK;
// new types introduced in SFTPv5+
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2
case 0010000: // named pipe (fifo)
return NET_SFTP_TYPE_FIFO;
case 0020000: // character special
return NET_SFTP_TYPE_CHAR_DEVICE;
case 0060000: // block special
return NET_SFTP_TYPE_BLOCK_DEVICE;
case 0140000: // socket
return NET_SFTP_TYPE_SOCKET;
case 0160000: // whiteout
// "SPECIAL should be used for files that are of
// a known type which cannot be expressed in the protocol"
return NET_SFTP_TYPE_SPECIAL;
default:
return NET_SFTP_TYPE_UNKNOWN;
}
}
/**
* Parse Longname
*
* SFTPv3 doesn't provide any easy way of identifying a file type. You could try to open
* a file as a directory and see if an error is returned or you could try to parse the
* SFTPv3-specific longname field of the SSH_FXP_NAME packet. That's what this function does.
* The result is returned using the
* {@link http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2 SFTPv4 type constants}.
*
* If the longname is in an unrecognized format bool(false) is returned.
*
* @param string $longname
* @return mixed
* @access private
*/
private function parseLongname($longname)
{
// http://en.wikipedia.org/wiki/Unix_file_types
// http://en.wikipedia.org/wiki/Filesystem_permissions#Notation_of_traditional_Unix_permissions
if (preg_match('#^[^/]([r-][w-][xstST-]){3}#', $longname)) {
switch ($longname[0]) {
case '-':
return NET_SFTP_TYPE_REGULAR;
case 'd':
return NET_SFTP_TYPE_DIRECTORY;
case 'l':
return NET_SFTP_TYPE_SYMLINK;
default:
return NET_SFTP_TYPE_SPECIAL;
}
}
return false;
}
/**
* Sends SFTP Packets
*
* See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info.
*
* @param int $type
* @param string $data
* @see self::_get_sftp_packet()
* @see self::send_channel_packet()
* @return bool
* @access private
*/
private function send_sftp_packet($type, $data, $request_id = 1)
{
$packet = $this->use_request_id ?
pack('NCNa*', strlen($data) + 5, $type, $request_id, $data) :
pack('NCa*', strlen($data) + 1, $type, $data);
$start = microtime(true);
$result = $this->send_channel_packet(self::CHANNEL, $packet);
$stop = microtime(true);
if (defined('NET_SFTP_LOGGING')) {
$packet_type = '-> ' . $this->packet_types[$type] .
' (' . round($stop - $start, 4) . 's)';
if (NET_SFTP_LOGGING == self::LOG_REALTIME) {
echo "<pre>\r\n" . $this->format_log([$data], [$packet_type]) . "\r\n</pre>\r\n";
flush();
ob_flush();
} else {
$this->packet_type_log[] = $packet_type;
if (NET_SFTP_LOGGING == self::LOG_COMPLEX) {
$this->packet_log[] = $data;
}
}
}
return $result;
}
/**
* Resets a connection for re-use
*
* @param int $reason
* @access private
*/
protected function reset_connection($reason)
{
parent::reset_connection($reason);
$this->use_request_id = false;
$this->pwd = false;
$this->requestBuffer = [];
}
/**
* Receives SFTP Packets
*
* See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info.
*
* Incidentally, the number of SSH_MSG_CHANNEL_DATA messages has no bearing on the number of SFTP packets present.
* There can be one SSH_MSG_CHANNEL_DATA messages containing two SFTP packets or there can be two SSH_MSG_CHANNEL_DATA
* messages containing one SFTP packet.
*
* @see self::_send_sftp_packet()
* @return string
* @access private
*/
private function get_sftp_packet($request_id = null)
{
if (isset($request_id) && isset($this->requestBuffer[$request_id])) {
$this->packet_type = $this->requestBuffer[$request_id]['packet_type'];
$temp = $this->requestBuffer[$request_id]['packet'];
unset($this->requestBuffer[$request_id]);
return $temp;
}
// in SSH2.php the timeout is cumulative per function call. eg. exec() will
// timeout after 10s. but for SFTP.php it's cumulative per packet
$this->curTimeout = $this->timeout;
$start = microtime(true);
// SFTP packet length
while (strlen($this->packet_buffer) < 4) {
$temp = $this->get_channel_packet(self::CHANNEL, true);
if (is_bool($temp)) {
$this->packet_type = false;
$this->packet_buffer = '';
return false;
}
$this->packet_buffer.= $temp;
}
if (strlen($this->packet_buffer) < 4) {
return false;
}
extract(unpack('Nlength', Strings::shift($this->packet_buffer, 4)));
/** @var integer $length */
$tempLength = $length;
$tempLength-= strlen($this->packet_buffer);
// 256 * 1024 is what SFTP_MAX_MSG_LENGTH is set to in OpenSSH's sftp-common.h
if ($tempLength > 256 * 1024) {
throw new \RuntimeException('Invalid Size');
}
// SFTP packet type and data payload
while ($tempLength > 0) {
$temp = $this->get_channel_packet(self::CHANNEL, true);
if (is_bool($temp)) {
$this->packet_type = false;
$this->packet_buffer = '';
return false;
}
$this->packet_buffer.= $temp;
$tempLength-= strlen($temp);
}
$stop = microtime(true);
$this->packet_type = ord(Strings::shift($this->packet_buffer));
if ($this->use_request_id) {
extract(unpack('Npacket_id', Strings::shift($this->packet_buffer, 4))); // remove the request id
$length-= 5; // account for the request id and the packet type
} else {
$length-= 1; // account for the packet type
}
$packet = Strings::shift($this->packet_buffer, $length);
if (defined('NET_SFTP_LOGGING')) {
$packet_type = '<- ' . $this->packet_types[$this->packet_type] .
' (' . round($stop - $start, 4) . 's)';
if (NET_SFTP_LOGGING == self::LOG_REALTIME) {
echo "<pre>\r\n" . $this->format_log([$packet], [$packet_type]) . "\r\n</pre>\r\n";
flush();
ob_flush();
} else {
$this->packet_type_log[] = $packet_type;
if (NET_SFTP_LOGGING == self::LOG_COMPLEX) {
$this->packet_log[] = $packet;
}
}
}
if (isset($request_id) && $this->use_request_id && $packet_id != $request_id) {
$this->requestBuffer[$packet_id] = array(
'packet_type' => $this->packet_type,
'packet' => $packet
);
return $this->_get_sftp_packet($request_id);
}
return $packet;
}
/**
* Returns a log of the packets that have been sent and received.
*
* Returns a string if NET_SFTP_LOGGING == self::LOG_COMPLEX, an array if NET_SFTP_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SFTP_LOGGING')
*
* @access public
* @return array|string
*/
public function getSFTPLog()
{
if (!defined('NET_SFTP_LOGGING')) {
return false;
}
switch (NET_SFTP_LOGGING) {
case self::LOG_COMPLEX:
return $this->format_log($this->packet_log, $this->packet_type_log);
break;
//case self::LOG_SIMPLE:
default:
return $this->packet_type_log;
}
}
/**
* Returns all errors
*
* @return array
* @access public
*/
public function getSFTPErrors()
{
return $this->sftp_errors;
}
/**
* Returns the last error
*
* @return string
* @access public
*/
public function getLastSFTPError()
{
return count($this->sftp_errors) ? $this->sftp_errors[count($this->sftp_errors) - 1] : '';
}
/**
* Get supported SFTP versions
*
* @return array
* @access public
*/
public function getSupportedVersions()
{
$temp = ['version' => $this->version];
if (isset($this->extensions['versions'])) {
$temp['extensions'] = $this->extensions['versions'];
}
return $temp;
}
/**
* Disconnect
*
* @param int $reason
* @return bool
* @access protected
*/
protected function disconnect_helper($reason)
{
$this->pwd = false;
parent::disconnect_helper($reason);
}
}
| qrux/phputils | inc/phpseclib/Net/SFTP.php | PHP | mit | 99,629 |
/*
--------------------------------------------------------------------------------
Based on class found at: http://ai.stanford.edu/~gal/Code/FindMotifs/
--------------------------------------------------------------------------------
*/
#include "Platform/StableHeaders.h"
#include "Util/Helper/ConfigFile.h"
//------------------------------------------------------------------------------
namespace Dangine {
//------------------------------------------------------------------------------
Config::Config(String filename, String delimiter, String comment, String sentry)
: myDelimiter(delimiter)
, myComment(comment)
, mySentry(sentry)
{
// Construct a Config, getting keys and values from given file
std::ifstream in(filename.c_str());
if (!in) throw file_not_found(filename);
in >> (*this);
}
//------------------------------------------------------------------------------
Config::Config()
: myDelimiter(String(1,'='))
, myComment(String(1,'#'))
{
// Construct a Config without a file; empty
}
//------------------------------------------------------------------------------
void Config::remove(const String& key)
{
// Remove key and its value
myContents.erase(myContents.find(key));
return;
}
//------------------------------------------------------------------------------
bool Config::keyExists(const String& key) const
{
// Indicate whether key is found
mapci p = myContents.find(key);
return (p != myContents.end());
}
//------------------------------------------------------------------------------
/* static */
void Config::trim(String& s)
{
// Remove leading and trailing whitespace
static const char whitespace[] = " \n\t\v\r\f";
s.erase(0, s.find_first_not_of(whitespace));
s.erase(s.find_last_not_of(whitespace) + 1U);
}
//------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const Config& cf)
{
// Save a Config to os
for (Config::mapci p = cf.myContents.begin();
p != cf.myContents.end();
++p)
{
os << p->first << " " << cf.myDelimiter << " ";
os << p->second << std::endl;
}
return os;
}
//------------------------------------------------------------------------------
std::istream& operator>>(std::istream& is, Config& cf)
{
// Load a Config from is
// Read in keys and values, keeping internal whitespace
typedef String::size_type pos;
const String& delim = cf.myDelimiter; // separator
const String& comm = cf.myComment; // comment
const String& sentry = cf.mySentry; // end of file sentry
const pos skip = delim.length(); // length of separator
String nextline = ""; // might need to read ahead to see where value ends
while (is || nextline.length() > 0)
{
// Read an entire line at a time
String line;
if (nextline.length() > 0)
{
line = nextline; // we read ahead; use it now
nextline = "";
}
else
{
std::getline(is, line);
}
// Ignore comments
line = line.substr(0, line.find(comm));
// Check for end of file sentry
if (sentry != "" && line.find(sentry) != String::npos) return is;
// Parse the line if it contains a delimiter
pos delimPos = line.find(delim);
if (delimPos < String::npos)
{
// Extract the key
String key = line.substr(0, delimPos);
line.replace(0, delimPos+skip, "");
// See if value continues on the next line
// Stop at blank line, next line with a key, end of stream,
// or end of file sentry
bool terminate = false;
while(!terminate && is)
{
std::getline(is, nextline);
terminate = true;
String nlcopy = nextline;
Config::trim(nlcopy);
if (nlcopy == "") continue;
nextline = nextline.substr(0, nextline.find(comm));
if (nextline.find(delim) != String::npos)
continue;
if (sentry != "" && nextline.find(sentry) != String::npos)
continue;
nlcopy = nextline;
Config::trim(nlcopy);
if (nlcopy != "") line += "\n";
line += nextline;
terminate = false;
}
// Store key and value
Config::trim(key);
Config::trim(line);
cf.myContents[key] = line; // overwrites if key is repeated
}
}
return is;
}
//------------------------------------------------------------------------------
} // namespace Dangine
//------------------------------------------------------------------------------ | danielsefton/Dangine | Engine/Util/Helper/src/ConfigFile.cpp | C++ | mit | 4,492 |
# frozen_string_literal: true
module Webdrone
class MethodLogger < Module
class << self
attr_accessor :last_time, :screenshot
end
def initialize(methods = nil)
super()
@methods = methods
end
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.7')
def included(base)
@methods ||= base.instance_methods(false)
method_list = @methods
base.class_eval do
method_list.each do |method_name|
original_method = instance_method(method_name)
define_method method_name do |*args, &block|
caller_location = Kernel.caller_locations[0]
cl_path = caller_location.path
cl_line = caller_location.lineno
if @a0.conf.logger && Gem.path.none? { |path| cl_path.include? path }
ini = ::Webdrone::MethodLogger.last_time ||= Time.new
::Webdrone::MethodLogger.screenshot = nil
args_log = [args].compact.reject(&:empty?).map(&:to_s).join(' ')
begin
result = original_method.bind(self).call(*args, &block)
fin = ::Webdrone::MethodLogger.last_time = Time.new
@a0.logs.trace(ini, fin, cl_path, cl_line, base, method_name, args_log, result, nil, ::Webdrone::MethodLogger.screenshot)
result
rescue StandardError => exception
fin = ::Webdrone::MethodLogger.last_time = Time.new
@a0.logs.trace(ini, fin, cl_path, cl_line, base, method_name, args_log, nil, exception, ::Webdrone::MethodLogger.screenshot)
raise exception
end
else
original_method.bind(self).call(*args, &block)
end
end
end
end
end
else
def included(base)
@methods ||= base.instance_methods(false)
method_list = @methods
base.class_eval do
method_list.each do |method_name|
original_method = instance_method(method_name)
define_method method_name do |*args, **kwargs, &block|
caller_location = Kernel.caller_locations[0]
cl_path = caller_location.path
cl_line = caller_location.lineno
if @a0.conf.logger && Gem.path.none? { |path| cl_path.include? path }
ini = ::Webdrone::MethodLogger.last_time ||= Time.new
::Webdrone::MethodLogger.screenshot = nil
args_log = [args, kwargs].compact.reject(&:empty?).map(&:to_s).join(' ')
begin
result = original_method.bind(self).call(*args, **kwargs, &block)
fin = ::Webdrone::MethodLogger.last_time = Time.new
@a0.logs.trace(ini, fin, cl_path, cl_line, base, method_name, args_log, result, nil, ::Webdrone::MethodLogger.screenshot)
result
rescue StandardError => exception
fin = ::Webdrone::MethodLogger.last_time = Time.new
@a0.logs.trace(ini, fin, cl_path, cl_line, base, method_name, args_log, nil, exception, ::Webdrone::MethodLogger.screenshot)
raise exception
end
else
original_method.bind(self).call(*args, **kwargs, &block)
end
end
end
end
end
end
end
class Browser
def logs
@logs ||= Logs.new self
end
end
class Logs
attr_reader :a0
def initialize(a0)
@a0 = a0
@group_trace_count = []
setup_format
setup_trace
end
def trace(ini, fin, from, lineno, base, method_name, args, result, exception, screenshot)
exception = "#{exception.class}: #{exception}" if exception
printf @format, (fin - ini), base, method_name, args, (result || exception) unless a0.conf.logger.to_s == 'quiet'
CSV.open(@path, "a+") do |csv|
csv << [ini.strftime('%Y-%m-%d %H:%M:%S.%L %z'), (fin - ini), from, lineno, base, method_name, args, result, exception, screenshot]
end
@group_trace_count = @group_trace_count.map { |x| x + 1 }
end
def with_group(name, abort_error: false)
ini = Time.new
caller_location = Kernel.caller_locations[0]
cl_path = caller_location.path
cl_line = caller_location.lineno
result = {}
@group_trace_count << 0
exception = nil
begin
yield
rescue StandardError => e
exception = e
bindings = Kernel.binding.callers
bindings[0..].each do |binding|
location = { path: binding.source_location[0], lineno: binding.source_location[1] }
next unless Gem.path.none? { |path| location[:path].include? path }
result[:exception] = {}
result[:exception][:line] = location[:lineno]
result[:exception][:path] = location[:path]
break
end
end
result[:trace_count] = @group_trace_count.pop
fin = Time.new
trace(ini, fin, cl_path, cl_line, Logs, :with_group, [name, { abort_error: abort_error }], result, exception, nil)
puts "abort_error: #{abort_error} exception: #{exception}"
exit if abort_error == true && exception
end
def setup_format
begin
cols, _line = HighLine.default_instance.terminal.terminal_size
rescue StandardError => error
puts "ignoring error: #{error}"
end
cols ||= 120
total = 6 + 15 + 11 + 5
w = cols - total
w /= 2
w1 = w
w2 = cols - total - w1
w1 = 20 if w1 < 20
w2 = 20 if w2 < 20
@format = "%5.3f %14.14s %10s %#{w1}.#{w1}s => %#{w2}.#{w2}s\n"
end
def setup_trace
@path = File.join(a0.conf.outdir, 'a0_webdrone_trace.csv')
CSV.open(@path, "a+") do |csv|
os = "Windows" if OS.windows?
os = "Linux" if OS.linux?
os = "OS X" if OS.osx?
bits = OS.bits
hostname = Socket.gethostname
browser_name = a0.driver.capabilities[:browser_name]
browser_version = a0.driver.capabilities[:version]
browser_platform = a0.driver.capabilities[:platform]
webdrone_version = Webdrone::VERSION
webdrone_platform = "#{RUBY_ENGINE}-#{RUBY_VERSION} #{RUBY_PLATFORM}"
csv << %w.OS ARCH HOSTNAME BROWSER\ NAME BROWSER\ VERSION BROWSER\ PLATFORM WEBDRONE\ VERSION WEBDRONE\ PLATFORM.
csv << [os, bits, hostname, browser_name, browser_version, browser_platform, webdrone_version, webdrone_platform]
end
CSV.open(@path, "a+") do |csv|
csv << %w.DATE DUR FROM LINENO MODULE CALL PARAMS RESULT EXCEPTION SCREENSHOT.
end
end
end
class Clic
include MethodLogger.new %i[id css link button on option xpath]
end
class Conf
include MethodLogger.new %i[timeout= outdir= error= developer= logger=]
end
class Ctxt
include MethodLogger.new %i[create_tab close_tab with_frame reset with_alert ignore_alert with_conf]
end
class Find
include MethodLogger.new %i[id css link button on option xpath]
end
class Form
include MethodLogger.new %i[with_xpath save set get clic mark submit xlsx]
end
class Html
include MethodLogger.new %i[id css link button on option xpath]
end
class Mark
include MethodLogger.new %i[id css link button on option xpath]
end
class Open
include MethodLogger.new %i[url reload]
end
class Shot
include MethodLogger.new %i[screen]
end
class Text
include MethodLogger.new %i[id css link button on option xpath]
end
class Vrfy
include MethodLogger.new %i[id css link button on option xpath]
end
class Wait
include MethodLogger.new %i[for time]
end
class Xlsx
include MethodLogger.new %i[dict rows both save reset]
end
end
| a0/a0-webdrone-ruby | lib/webdrone/logg.rb | Ruby | mit | 7,845 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if XR_MANAGEMENT_ENABLED
using UnityEngine.XR.Management;
#endif // XR_MANAGEMENT_ENABLED
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Utilities that abstract XR settings functionality so that the MRTK need not know which
/// implementation is being used.
/// </summary>
public static class XRSettingsUtilities
{
#if !UNITY_2020_2_OR_NEWER && UNITY_2019_3_OR_NEWER && XR_MANAGEMENT_ENABLED
private static bool? isXRSDKEnabled = null;
#endif // !UNITY_2020_2_OR_NEWER && UNITY_2019_3_OR_NEWER && XR_MANAGEMENT_ENABLED
/// <summary>
/// Checks if an XR SDK plug-in is installed that disables legacy VR. Returns false if so.
/// </summary>
public static bool XRSDKEnabled
{
get
{
#if UNITY_2020_2_OR_NEWER
return true;
#elif UNITY_2019_3_OR_NEWER && XR_MANAGEMENT_ENABLED
if (!isXRSDKEnabled.HasValue)
{
XRGeneralSettings currentSettings = XRGeneralSettings.Instance;
if (currentSettings != null && currentSettings.AssignedSettings != null)
{
#pragma warning disable CS0618 // Suppressing the warning to support xr management plugin 3.x and 4.x
isXRSDKEnabled = currentSettings.AssignedSettings.loaders.Count > 0;
#pragma warning restore CS0618
}
else
{
isXRSDKEnabled = false;
}
}
return isXRSDKEnabled.Value;
#else
return false;
#endif // UNITY_2020_2_OR_NEWER
}
}
}
}
| DDReaper/MixedRealityToolkit-Unity | Assets/MRTK/Core/Utilities/XRSettingsUtilities.cs | C# | mit | 1,780 |
const Koa = require('koa');
const http = require('http');
const destroyable = require('server-destroy');
const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
const passport = require('koa-passport');
const serve = require('koa-static');
const db = require('./db');
const config = require('./config');
const router = require('./routes');
const authStrategies = require('./authStrategies');
const User = require('./models/User');
const app = new Koa();
app.use(bodyParser());
app.keys = [config.get('session_secret')];
app.use(session({}, app));
authStrategies.forEach(passport.use, passport);
passport.serializeUser((user, done) => {
done(null, user.twitterId);
});
passport.deserializeUser(async (twitterId, done) => {
const user = await User.findOne({ twitterId });
done(null, user);
});
app.use(passport.initialize());
app.use(passport.session());
app.use(router.routes());
app.use(router.allowedMethods());
app.use(serve('public'));
app.use(async (ctx, next) => {
await next();
if (ctx.status === 404) {
ctx.redirect('/');
}
});
const server = http.createServer(app.callback());
module.exports = {
start() {
db.start().then(() => {
server.listen(config.get('port'));
destroyable(server);
});
},
stop() {
server.destroy();
db.stop();
},
};
| xz64/image-sharing | server.js | JavaScript | mit | 1,341 |
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
// Add your dependencies
new Sonata\CoreBundle\SonataCoreBundle(),
new Sonata\BlockBundle\SonataBlockBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
//...
// If you haven't already, add the storage bundle
// This example uses SonataDoctrineORMAdmin but
// it works the same with the alternatives
new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
// Then add SonataAdminBundle
new Sonata\AdminBundle\SonataAdminBundle(),
// ...
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| justinecavaglieri/EasySymfony | app/AppKernel.php | PHP | mit | 1,993 |
<?php
namespace app\base;
use Yii;
use yii\base\Component;
class MailService extends Component {
public function init()
{
parent::init();
if ($this->_mail === null) {
$this->_mail = Yii::$app->getMailer();
//$this->_mail->htmlLayout = Yii::getAlias($this->id . '/mails/layouts/html');
//$this->_mail->textLayout = Yii::getAlias($this->id . '/mails/layouts/text');
$this->_mail->viewPath = '@app/modules/' . $module->id . '/mails/views';
if (isset(Yii::$app->params['robotEmail']) && Yii::$app->params['robotEmail'] !== null) {
$this->_mail->messageConfig['from'] = !isset(Yii::$app->params['robotName']) ? Yii::$app->params['robotEmail'] : [Yii::$app->params['robotEmail'] => Yii::$app->params['robotName']];
}
}
return $this->_mail;
}
}
| artkost/yii2-starter-kit | app/base/MailService.php | PHP | mit | 876 |
using System;
using Xamarin.Forms;
namespace EmployeeApp
{
public partial class ClaimDetailPage : ContentPage
{
private ClaimViewModel model;
public ClaimDetailPage(ClaimViewModel cl)
{
InitializeComponent();
model = cl;
BindingContext = model;
ToolbarItem optionbutton = new ToolbarItem
{
Text = "Options",
Order = ToolbarItemOrder.Default,
Priority = 0
};
ToolbarItems.Add(optionbutton);
optionbutton.Clicked += OptionsClicked;
if (model.ImageUrl.StartsWith("http:") || model.ImageUrl.StartsWith("https:"))
{
claimCellImage.Source = new UriImageSource { CachingEnabled = false, Uri = new Uri(model.ImageUrl) };
}
claimHintStackLayout.SetBinding(IsVisibleProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminShowDetailHintConvert(), Mode = BindingMode.OneWay });
claimHintIcon.SetBinding(Image.IsVisibleProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminShowDetailHintIconConvert(), Mode = BindingMode.OneWay });
claimHintTitle.SetBinding(Label.TextProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintTitleConvert(), Mode = BindingMode.OneWay });
claimHintMessage.SetBinding(Label.TextProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintMessageConvert(), Mode = BindingMode.OneWay });
claimHintFrame.SetBinding(Frame.BackgroundColorProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintBkConvert(), Mode = BindingMode.OneWay });
claimHintMessage.SetBinding(Label.TextColorProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintMsgColorConvert(), Mode = BindingMode.OneWay });
InitGridView();
this.Title = "#" + cl.Name;
}
private void InitGridView()
{
if (mainPageGrid.RowDefinitions.Count == 0)
{
claimDetailStackLayout.Padding = new Thickness(0, Display.Convert(40));
claimHintStackLayout.HeightRequest = Display.Convert(110);
Display.SetGridRowsHeight(claimHintGrid, new string[] { "32", "36" });
claimHintIcon.WidthRequest = Display.Convert(32);
claimHintIcon.HeightRequest = Display.Convert(32);
Display.SetGridRowsHeight(mainPageGrid, new string[] { "50", "46", "20", "54", "176", "30", "40", "54", "36", "44", "440", "1*"});
claimDescription.Margin = new Thickness(0, Display.Convert(14));
}
}
public async void OptionsClicked(object sender, EventArgs e)
{
var action = await DisplayActionSheet(null, "Cancel", null, "Approve", "Contact policy holder", "Decline");
switch (action)
{
case "Approve":
model.Status = ClaimStatus.Approved;
model.isNew = false;
break;
case "Decline":
model.Status = ClaimStatus.Declined;
model.isNew = false;
break;
}
}
}
}
| TBag/canviz | Mobile/EmployeeApp/EmployeeApp/EmployeeApp/Views/ClaimDetailPage.xaml.cs | C# | mit | 3,471 |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
=======================
This version of the META tools is a fork of an original version produced
by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
Their license statement:
Copyright (C) 2011-2014 Vanderbilt University
Developed with the sponsorship of the Defense Advanced Research Projects
Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
as defined in DFARS 252.227-7013.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Runtime.InteropServices;
using GME.Util;
using GME.MGA;
namespace GME.CSharp
{
abstract class ComponentConfig
{
// Set paradigm name. Provide * if you want to register it for all paradigms.
public const string paradigmName = "CyPhyML";
// Set the human readable name of the interpreter. You can use white space characters.
public const string componentName = "CyPhyPrepareIFab";
// Specify an icon path
public const string iconName = "CyPhyPrepareIFab.ico";
public const string tooltip = "CyPhyPrepareIFab";
// If null, updated with the assembly path + the iconName dynamically on registration
public static string iconPath = null;
// Uncomment the flag if your component is paradigm independent.
public static componenttype_enum componentType = componenttype_enum.COMPONENTTYPE_INTERPRETER;
public const regaccessmode_enum registrationMode = regaccessmode_enum.REGACCESS_SYSTEM;
public const string progID = "MGA.Interpreter.CyPhyPrepareIFab";
public const string guid = "D3B4ECEE-36EC-4753-9B10-312084B48F2A";
}
}
| pombredanne/metamorphosys-desktop | metamorphosys/META/src/CyPhyPrepareIFab/ComponentConfig.cs | C# | mit | 3,987 |
package cellsociety_team05;
public class SimulationException extends Exception {
public SimulationException(String s) {
super(s);
}
}
| dpak96/CellSociety | src/cellsociety_team05/SimulationException.java | Java | mit | 139 |
PhotoAlbums.Router.map(function() {
this.resource('login');
this.resource('album', {path: '/:album_id'});
this.resource('photo', {path: 'photos/:photo_id'});
});
| adamstegman/photo_albums | app/assets/javascripts/router.js | JavaScript | mit | 168 |
from __future__ import annotations
from collections import defaultdict
from collections.abc import Generator, Iterable, Mapping, MutableMapping
from contextlib import contextmanager
import logging
import re
import textwrap
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, NamedTuple
from markdown_it.rules_block.html_block import HTML_SEQUENCES
from mdformat import codepoints
from mdformat._compat import Literal
from mdformat._conf import DEFAULT_OPTS
from mdformat.renderer._util import (
RE_CHAR_REFERENCE,
decimalify_leading,
decimalify_trailing,
escape_asterisk_emphasis,
escape_underscore_emphasis,
get_list_marker_type,
is_tight_list,
is_tight_list_item,
longest_consecutive_sequence,
maybe_add_link_brackets,
)
from mdformat.renderer.typing import Postprocess, Render
if TYPE_CHECKING:
from mdformat.renderer import RenderTreeNode
LOGGER = logging.getLogger(__name__)
# A marker used to point a location where word wrap is allowed
# to occur.
WRAP_POINT = "\x00"
# A marker used to indicate location of a character that should be preserved
# during word wrap. Should be converted to the actual character after wrap.
PRESERVE_CHAR = "\x00"
def make_render_children(separator: str) -> Render:
def render_children(
node: RenderTreeNode,
context: RenderContext,
) -> str:
return separator.join(child.render(context) for child in node.children)
return render_children
def hr(node: RenderTreeNode, context: RenderContext) -> str:
thematic_break_width = 70
return "_" * thematic_break_width
def code_inline(node: RenderTreeNode, context: RenderContext) -> str:
code = node.content
all_chars_are_whitespace = not code.strip()
longest_backtick_seq = longest_consecutive_sequence(code, "`")
if longest_backtick_seq:
separator = "`" * (longest_backtick_seq + 1)
return f"{separator} {code} {separator}"
if code.startswith(" ") and code.endswith(" ") and not all_chars_are_whitespace:
return f"` {code} `"
return f"`{code}`"
def html_block(node: RenderTreeNode, context: RenderContext) -> str:
content = node.content.rstrip("\n")
# Need to strip leading spaces because we do so for regular Markdown too.
# Without the stripping the raw HTML and Markdown get unaligned and
# semantic may change.
content = content.lstrip()
return content
def html_inline(node: RenderTreeNode, context: RenderContext) -> str:
return node.content
def _in_block(block_name: str, node: RenderTreeNode) -> bool:
while node.parent:
if node.parent.type == block_name:
return True
node = node.parent
return False
def hardbreak(node: RenderTreeNode, context: RenderContext) -> str:
if _in_block("heading", node):
return "<br /> "
return "\\" + "\n"
def softbreak(node: RenderTreeNode, context: RenderContext) -> str:
if context.do_wrap and _in_block("paragraph", node):
return WRAP_POINT
return "\n"
def text(node: RenderTreeNode, context: RenderContext) -> str:
"""Process a text token.
Text should always be a child of an inline token. An inline token
should always be enclosed by a heading or a paragraph.
"""
text = node.content
# Escape backslash to prevent it from making unintended escapes.
# This escape has to be first, else we start multiplying backslashes.
text = text.replace("\\", "\\\\")
text = escape_asterisk_emphasis(text) # Escape emphasis/strong marker.
text = escape_underscore_emphasis(text) # Escape emphasis/strong marker.
text = text.replace("[", "\\[") # Escape link label enclosure
text = text.replace("]", "\\]") # Escape link label enclosure
text = text.replace("<", "\\<") # Escape URI enclosure
text = text.replace("`", "\\`") # Escape code span marker
# Escape "&" if it starts a sequence that can be interpreted as
# a character reference.
text = RE_CHAR_REFERENCE.sub(r"\\\g<0>", text)
# The parser can give us consecutive newlines which can break
# the markdown structure. Replace two or more consecutive newlines
# with newline character's decimal reference.
text = text.replace("\n\n", " ")
# If the last character is a "!" and the token next up is a link, we
# have to escape the "!" or else the link will be interpreted as image.
next_sibling = node.next_sibling
if text.endswith("!") and next_sibling and next_sibling.type == "link":
text = text[:-1] + "\\!"
if context.do_wrap and _in_block("paragraph", node):
text = re.sub(r"\s+", WRAP_POINT, text)
return text
def fence(node: RenderTreeNode, context: RenderContext) -> str:
info_str = node.info.strip()
lang = info_str.split(maxsplit=1)[0] if info_str else ""
code_block = node.content
# Info strings of backtick code fences cannot contain backticks.
# If that is the case, we make a tilde code fence instead.
fence_char = "~" if "`" in info_str else "`"
# Format the code block using enabled codeformatter funcs
if lang in context.options.get("codeformatters", {}):
fmt_func = context.options["codeformatters"][lang]
try:
code_block = fmt_func(code_block, info_str)
except Exception:
# Swallow exceptions so that formatter errors (e.g. due to
# invalid code) do not crash mdformat.
assert node.map is not None, "A fence token must have `map` attribute set"
filename = context.options.get("mdformat", {}).get("filename", "")
warn_msg = (
f"Failed formatting content of a {lang} code block "
f"(line {node.map[0] + 1} before formatting)"
)
if filename:
warn_msg += f". Filename: {filename}"
LOGGER.warning(warn_msg)
# The code block must not include as long or longer sequence of `fence_char`s
# as the fence string itself
fence_len = max(3, longest_consecutive_sequence(code_block, fence_char) + 1)
fence_str = fence_char * fence_len
return f"{fence_str}{info_str}\n{code_block}{fence_str}"
def code_block(node: RenderTreeNode, context: RenderContext) -> str:
return fence(node, context)
def image(node: RenderTreeNode, context: RenderContext) -> str:
description = _render_inline_as_text(node, context)
if context.do_wrap:
# Prevent line breaks
description = description.replace(WRAP_POINT, " ")
ref_label = node.meta.get("label")
if ref_label:
context.env["used_refs"].add(ref_label)
ref_label_repr = ref_label.lower()
if description.lower() == ref_label_repr:
return f"![{description}]"
return f"![{description}][{ref_label_repr}]"
uri = node.attrs["src"]
assert isinstance(uri, str)
uri = maybe_add_link_brackets(uri)
title = node.attrs.get("title")
if title is not None:
return f'![{description}]({uri} "{title}")'
return f"![{description}]({uri})"
def _render_inline_as_text(node: RenderTreeNode, context: RenderContext) -> str:
"""Special kludge for image `alt` attributes to conform CommonMark spec.
Don't try to use it! Spec requires to show `alt` content with
stripped markup, instead of simple escaping.
"""
def text_renderer(node: RenderTreeNode, context: RenderContext) -> str:
return node.content
def image_renderer(node: RenderTreeNode, context: RenderContext) -> str:
return _render_inline_as_text(node, context)
inline_renderers: Mapping[str, Render] = defaultdict(
lambda: make_render_children(""),
{
"text": text_renderer,
"image": image_renderer,
"link": link,
"softbreak": softbreak,
},
)
inline_context = RenderContext(
inline_renderers, context.postprocessors, context.options, context.env
)
return make_render_children("")(node, inline_context)
def link(node: RenderTreeNode, context: RenderContext) -> str:
if node.info == "auto":
autolink_url = node.attrs["href"]
assert isinstance(autolink_url, str)
# The parser adds a "mailto:" prefix to autolink email href. We remove the
# prefix if it wasn't there in the source.
if autolink_url.startswith("mailto:") and not node.children[
0
].content.startswith("mailto:"):
autolink_url = autolink_url[7:]
return "<" + autolink_url + ">"
text = "".join(child.render(context) for child in node.children)
if context.do_wrap:
# Prevent line breaks
text = text.replace(WRAP_POINT, " ")
ref_label = node.meta.get("label")
if ref_label:
context.env["used_refs"].add(ref_label)
ref_label_repr = ref_label.lower()
if text.lower() == ref_label_repr:
return f"[{text}]"
return f"[{text}][{ref_label_repr}]"
uri = node.attrs["href"]
assert isinstance(uri, str)
uri = maybe_add_link_brackets(uri)
title = node.attrs.get("title")
if title is None:
return f"[{text}]({uri})"
assert isinstance(title, str)
title = title.replace('"', '\\"')
return f'[{text}]({uri} "{title}")'
def em(node: RenderTreeNode, context: RenderContext) -> str:
text = make_render_children(separator="")(node, context)
indicator = node.markup
return indicator + text + indicator
def strong(node: RenderTreeNode, context: RenderContext) -> str:
text = make_render_children(separator="")(node, context)
indicator = node.markup
return indicator + text + indicator
def heading(node: RenderTreeNode, context: RenderContext) -> str:
text = make_render_children(separator="")(node, context)
if node.markup == "=":
prefix = "# "
elif node.markup == "-":
prefix = "## "
else: # ATX heading
prefix = node.markup + " "
# There can be newlines in setext headers, but we make an ATX
# header always. Convert newlines to spaces.
text = text.replace("\n", " ")
# If the text ends in a sequence of hashes (#), the hashes will be
# interpreted as an optional closing sequence of the heading, and
# will not be rendered. Escape a line ending hash to prevent this.
if text.endswith("#"):
text = text[:-1] + "\\#"
return prefix + text
def blockquote(node: RenderTreeNode, context: RenderContext) -> str:
marker = "> "
with context.indented(len(marker)):
text = make_render_children(separator="\n\n")(node, context)
lines = text.splitlines()
if not lines:
return ">"
quoted_lines = (f"{marker}{line}" if line else ">" for line in lines)
quoted_str = "\n".join(quoted_lines)
return quoted_str
def _wrap(text: str, *, width: int | Literal["no"]) -> str:
"""Wrap text at locations pointed by `WRAP_POINT`s.
Converts `WRAP_POINT`s to either a space or newline character, thus
wrapping the text. Already existing whitespace will be preserved as
is.
"""
text, replacements = _prepare_wrap(text)
if width == "no":
return _recover_preserve_chars(text, replacements)
wrapper = textwrap.TextWrapper(
break_long_words=False,
break_on_hyphens=False,
width=width,
expand_tabs=False,
replace_whitespace=False,
)
wrapped = wrapper.fill(text)
wrapped = _recover_preserve_chars(wrapped, replacements)
return " " + wrapped if text.startswith(" ") else wrapped
def _prepare_wrap(text: str) -> tuple[str, str]:
"""Prepare text for wrap.
Convert `WRAP_POINT`s to spaces. Convert whitespace to
`PRESERVE_CHAR`s. Return a tuple with the prepared string, and
another string consisting of replacement characters for
`PRESERVE_CHAR`s.
"""
result = ""
replacements = ""
for c in text:
if c == WRAP_POINT:
if not result or result[-1] != " ":
result += " "
elif c in codepoints.UNICODE_WHITESPACE:
result += PRESERVE_CHAR
replacements += c
else:
result += c
return result, replacements
def _recover_preserve_chars(text: str, replacements: str) -> str:
replacement_iterator = iter(replacements)
return "".join(
next(replacement_iterator) if c == PRESERVE_CHAR else c for c in text
)
def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C901
inline_node = node.children[0]
text = inline_node.render(context)
if context.do_wrap:
wrap_mode = context.options["mdformat"]["wrap"]
if isinstance(wrap_mode, int):
wrap_mode -= context.env["indent_width"]
wrap_mode = max(1, wrap_mode)
text = _wrap(text, width=wrap_mode)
# A paragraph can start or end in whitespace e.g. if the whitespace was
# in decimal representation form. We need to re-decimalify it, one reason being
# to enable "empty" paragraphs with whitespace only.
text = decimalify_leading(codepoints.UNICODE_WHITESPACE, text)
text = decimalify_trailing(codepoints.UNICODE_WHITESPACE, text)
lines = text.split("\n")
for i in range(len(lines)):
# Strip whitespace to prevent issues like a line starting tab that is
# interpreted as start of a code block.
lines[i] = lines[i].strip()
# If a line looks like an ATX heading, escape the first hash.
if re.match(r"#{1,6}( |\t|$)", lines[i]):
lines[i] = f"\\{lines[i]}"
# Make sure a paragraph line does not start with ">"
# (otherwise it will be interpreted as a block quote).
if lines[i].startswith(">"):
lines[i] = f"\\{lines[i]}"
# Make sure a paragraph line does not start with "*", "-" or "+"
# followed by a space, tab, or end of line.
# (otherwise it will be interpreted as list item).
if re.match(r"[-*+]( |\t|$)", lines[i]):
lines[i] = f"\\{lines[i]}"
# If a line starts with a number followed by "." or ")" followed by
# a space, tab or end of line, escape the "." or ")" or it will be
# interpreted as ordered list item.
if re.match(r"[0-9]+\)( |\t|$)", lines[i]):
lines[i] = lines[i].replace(")", "\\)", 1)
if re.match(r"[0-9]+\.( |\t|$)", lines[i]):
lines[i] = lines[i].replace(".", "\\.", 1)
# Consecutive "-", "*" or "_" sequences can be interpreted as thematic
# break. Escape them.
space_removed = lines[i].replace(" ", "").replace("\t", "")
if len(space_removed) >= 3:
if all(c == "*" for c in space_removed):
lines[i] = lines[i].replace("*", "\\*", 1) # pragma: no cover
elif all(c == "-" for c in space_removed):
lines[i] = lines[i].replace("-", "\\-", 1)
elif all(c == "_" for c in space_removed):
lines[i] = lines[i].replace("_", "\\_", 1) # pragma: no cover
# A stripped line where all characters are "=" or "-" will be
# interpreted as a setext heading. Escape.
stripped = lines[i].strip(" \t")
if all(c == "-" for c in stripped):
lines[i] = lines[i].replace("-", "\\-", 1)
elif all(c == "=" for c in stripped):
lines[i] = lines[i].replace("=", "\\=", 1)
# Check if the line could be interpreted as an HTML block.
# If yes, prefix it with 4 spaces to prevent this.
for html_seq_tuple in HTML_SEQUENCES:
can_break_paragraph = html_seq_tuple[2]
opening_re = html_seq_tuple[0]
if can_break_paragraph and opening_re.search(lines[i]):
lines[i] = f" {lines[i]}"
break
text = "\n".join(lines)
return text
def list_item(node: RenderTreeNode, context: RenderContext) -> str:
"""Return one list item as string.
This returns just the content. List item markers and indentation are
added in `bullet_list` and `ordered_list` renderers.
"""
block_separator = "\n" if is_tight_list_item(node) else "\n\n"
text = make_render_children(block_separator)(node, context)
if not text.strip():
return ""
return text
def bullet_list(node: RenderTreeNode, context: RenderContext) -> str:
marker_type = get_list_marker_type(node)
first_line_indent = " "
indent = " " * len(marker_type + first_line_indent)
block_separator = "\n" if is_tight_list(node) else "\n\n"
with context.indented(len(indent)):
text = ""
for child_idx, child in enumerate(node.children):
list_item = child.render(context)
formatted_lines = []
line_iterator = iter(list_item.split("\n"))
first_line = next(line_iterator)
formatted_lines.append(
f"{marker_type}{first_line_indent}{first_line}"
if first_line
else marker_type
)
for line in line_iterator:
formatted_lines.append(f"{indent}{line}" if line else "")
text += "\n".join(formatted_lines)
if child_idx != len(node.children) - 1:
text += block_separator
return text
def ordered_list(node: RenderTreeNode, context: RenderContext) -> str:
consecutive_numbering = context.options.get("mdformat", {}).get(
"number", DEFAULT_OPTS["number"]
)
marker_type = get_list_marker_type(node)
first_line_indent = " "
block_separator = "\n" if is_tight_list(node) else "\n\n"
list_len = len(node.children)
starting_number = node.attrs.get("start")
if starting_number is None:
starting_number = 1
assert isinstance(starting_number, int)
if consecutive_numbering:
indent_width = len(
f"{list_len + starting_number - 1}{marker_type}{first_line_indent}"
)
else:
indent_width = len(f"{starting_number}{marker_type}{first_line_indent}")
text = ""
with context.indented(indent_width):
for list_item_index, list_item in enumerate(node.children):
list_item_text = list_item.render(context)
formatted_lines = []
line_iterator = iter(list_item_text.split("\n"))
first_line = next(line_iterator)
if consecutive_numbering:
# Prefix first line of the list item with consecutive numbering,
# padded with zeros to make all markers of even length.
# E.g.
# 002. This is the first list item
# 003. Second item
# ...
# 112. Last item
number = starting_number + list_item_index
pad = len(str(list_len + starting_number - 1))
number_str = str(number).rjust(pad, "0")
formatted_lines.append(
f"{number_str}{marker_type}{first_line_indent}{first_line}"
if first_line
else f"{number_str}{marker_type}"
)
else:
# Prefix first line of first item with the starting number of the
# list. Prefix following list items with the number one
# prefixed by zeros to make the list item marker of even length
# with the first one.
# E.g.
# 5321. This is the first list item
# 0001. Second item
# 0001. Third item
first_item_marker = f"{starting_number}{marker_type}"
other_item_marker = (
"0" * (len(str(starting_number)) - 1) + "1" + marker_type
)
if list_item_index == 0:
formatted_lines.append(
f"{first_item_marker}{first_line_indent}{first_line}"
if first_line
else first_item_marker
)
else:
formatted_lines.append(
f"{other_item_marker}{first_line_indent}{first_line}"
if first_line
else other_item_marker
)
for line in line_iterator:
formatted_lines.append(" " * indent_width + line if line else "")
text += "\n".join(formatted_lines)
if list_item_index != len(node.children) - 1:
text += block_separator
return text
DEFAULT_RENDERERS: Mapping[str, Render] = MappingProxyType(
{
"inline": make_render_children(""),
"root": make_render_children("\n\n"),
"hr": hr,
"code_inline": code_inline,
"html_block": html_block,
"html_inline": html_inline,
"hardbreak": hardbreak,
"softbreak": softbreak,
"text": text,
"fence": fence,
"code_block": code_block,
"link": link,
"image": image,
"em": em,
"strong": strong,
"heading": heading,
"blockquote": blockquote,
"paragraph": paragraph,
"bullet_list": bullet_list,
"ordered_list": ordered_list,
"list_item": list_item,
}
)
class RenderContext(NamedTuple):
"""A collection of data that is passed as input to `Render` and
`Postprocess` functions."""
renderers: Mapping[str, Render]
postprocessors: Mapping[str, Iterable[Postprocess]]
options: Mapping[str, Any]
env: MutableMapping
@contextmanager
def indented(self, width: int) -> Generator[None, None, None]:
self.env["indent_width"] += width
try:
yield
finally:
self.env["indent_width"] -= width
@property
def do_wrap(self) -> bool:
wrap_mode = self.options.get("mdformat", {}).get("wrap", DEFAULT_OPTS["wrap"])
return isinstance(wrap_mode, int) or wrap_mode == "no"
def with_default_renderer_for(self, *syntax_names: str) -> RenderContext:
renderers = dict(self.renderers)
for syntax in syntax_names:
if syntax in DEFAULT_RENDERERS:
renderers[syntax] = DEFAULT_RENDERERS[syntax]
else:
renderers.pop(syntax, None)
return RenderContext(
MappingProxyType(renderers), self.postprocessors, self.options, self.env
)
| executablebooks/mdformat | src/mdformat/renderer/_context.py | Python | mit | 22,558 |
package com.globalforge.infix;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.globalforge.infix.api.InfixSimpleActions;
import com.google.common.collect.ListMultimap;
/*-
The MIT License (MIT)
Copyright (c) 2019-2020 Global Forge LLC
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.
*/
public class TestAndOrSimple {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
private ListMultimap<String, String> getResults(String sampleRule) throws Exception {
InfixSimpleActions rules = new InfixSimpleActions(sampleRule);
String result = rules.transformFIXMsg(TestAndOrSimple.sampleMessage1);
return StaticTestingUtils.parseMessage(result);
}
@Test
public void t1() {
try {
String sampleRule = "&45==0 && &47==0 ? &50=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("50").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t2() {
try {
String sampleRule = "&45==1 && &47==0 ? &50=1 : &50=2";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("2", resultStore.get("50").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t3() {
try {
String sampleRule = "&45!=1 && &47==0 ? &50=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("50").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t4() {
try {
String sampleRule = "&45==0 && &47 != 1 ? &50=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("50").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t9() {
try {
String sampleRule = "&45==0 && &47==0 && &48==1.5 ? &45=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t10() {
try {
String sampleRule = "&45==1 && &47==0 && &48==1.5 ? &45=1 : &47=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t11() {
try {
String sampleRule = "&45==0 && &47==1 && &48==1.5 ? &45=1 : &47=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t12() {
try {
String sampleRule = "&45==0 && &47==0 && &48==1.6 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t13() {
try {
String sampleRule = "&45==0 || &47==0 && &48==1.6 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t14() {
try {
String sampleRule = "&45==0 && &47==0 || &48==1.6 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t15() {
try {
String sampleRule = "&45==0 || &47==0 && &48==1.6 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t16() {
try {
String sampleRule = "(&45==0 || &47==0) && (&48==1.6) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t17() {
try {
String sampleRule = "&45==0 || (&47==0 && &48==1.6) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t18() {
try {
String sampleRule = "^&45 && ^&47 && ^&48 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t19() {
try {
String sampleRule = "^&45 && ^&47 && ^&50 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t20() {
try {
String sampleRule = "^&45 || ^&47 || ^&50 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t21() {
try {
String sampleRule = "!&50 && !&51 && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t22() {
try {
String sampleRule = "^&45 || !&51 && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t23() {
try {
String sampleRule = "(^&45 || !&51) && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t24() {
try {
String sampleRule = "^&45 || (!&51 && !&52) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t25() {
try {
String sampleRule = "!&50 || !&45 && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t26() {
try {
String sampleRule = "(!&50 || !&45) && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t27() {
try {
String sampleRule = "!&50 || (!&45 && !&52) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t28() {
try {
String sampleRule = "!&55 && (!&54 && (!&53 && (!&47 && !&52))) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t29() {
try {
String sampleRule = "!&55 && (!&54 && (!&53 && (!&56 && !&52))) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t30() {
try {
String sampleRule = "(!&55 || (!&54 || (!&53 || (!&52 && !&47)))) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t31() {
try {
String sampleRule = "((((!&55 || !&54) || !&53) || !&52) && !&47) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t32() {
try {
String sampleRule = "(&382[1]->&655!=\"tarz\" || (&382[0]->&655==\"fubi\" "
+ "|| (&382[1]->&375==3 || (&382 >= 2 || (&45 > -1 || (&48 <=1.5 && &47 < 0.0001)))))) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t34() {
try {
// left to right
String sampleRule = "&45 == 0 || &43 == -100 && &207 == \"USA\" ? &43=1 : &43=2";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("2", resultStore.get("43").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t35() {
try {
String sampleRule = "&45 == 0 || (&43 == -100 && &207 == \"USA\") ? &43=1 : &43=2";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("43").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
static final String sampleMessage1 = "8=FIX.4.4" + '\u0001' + "9=1000" + '\u0001' + "35=8"
+ '\u0001' + "44=3.142" + '\u0001' + "60=20130412-19:30:00.686" + '\u0001' + "75=20130412"
+ '\u0001' + "45=0" + '\u0001' + "47=0" + '\u0001' + "48=1.5" + '\u0001' + "49=8dhosb"
+ '\u0001' + "382=2" + '\u0001' + "375=1.5" + '\u0001' + "655=fubi" + '\u0001' + "375=3"
+ '\u0001' + "655=yubl" + '\u0001' + "10=004";
@Test
public void t36() {
try {
// 45=0,
String sampleRule = "(&45 == 0 || &43 == -100) && &207 == \"USA\" ? &43=1 : &43=2";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("2", resultStore.get("43").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
}
| globalforge/infix | src/test/java/com/globalforge/infix/TestAndOrSimple.java | Java | mit | 16,486 |
<?php
namespace App\Controllers;
use App\Models\Queries\ArticleSQL;
use App\Models\Queries\CategorieSQL;
use Core\Language;
use Core\View;
use Core\Controller;
use Helpers\Twig;
use Helpers\Url;
class Categories extends Controller {
public function __construct() {
parent::__construct();
}
public function getCategorie() {
$categorieSQL = new CategorieSQL();
$categorie = $categorieSQL->prepareFindAll()->execute();
$data['categories'] = $categorie;
$data['url'] = SITEURL;
$data['title'] = "Toutes les catégories";
View::rendertemplate('header', $data);
Twig::render('Categorie/index', $data);
View::rendertemplate('footer', $data);
}
public function detailCategorie($id) {
$categorieSQL = new CategorieSQL();
$categorie = $categorieSQL->findById($id);
if($categorie){
$articleSQL = new ArticleSQL();
//$article = $articleSQL->findById($id);
$article = $articleSQL->prepareFindWithCondition("id_categorie = ".$id)->execute();
$data['categorie'] = $categorie;
$data['article'] = $article;
$data['url'] = SITEURL;
$data['title'] = $categorie->titre;
View::rendertemplate('header', $data);
Twig::render('Categorie/detail', $data);
View::rendertemplate('footer', $data);
}else{
$this->getCategorie();
}
}
}
| HelleboidQ/WordPress-en-mieux | app/Controllers/Categories.php | PHP | mit | 1,507 |
require 'test_helper'
require 'bearychat/rtm'
class BearychatTest < Minitest::Test
MOCK_HOOK_URI = 'https://hook.bearychat.com/mock/incoming/hook'
def test_that_it_has_a_version_number
refute_nil ::Bearychat::VERSION
end
def test_incoming_build_by_module
assert_equal true, ::Bearychat.incoming(MOCK_HOOK_URI).is_a?(::Bearychat::Incoming)
end
def test_incoming_send
incoming_stub = stub_request(:post, MOCK_HOOK_URI).with(body: hash_including(:text))
::Bearychat.incoming(MOCK_HOOK_URI).send
assert_requested(incoming_stub)
end
def test_rtm_send
rtm_stub = stub_request(:post, Bearychat::RTM::MESSAGE_URL).with(body: hash_including(:token))
token = 'TOKEN'
::Bearychat.rtm(token).send text: 'test'
assert_requested(rtm_stub)
end
end
| pokka/bearychat-rb | test/bearychat_test.rb | Ruby | mit | 792 |
package iron_hippo_exe
import (
"fmt"
"io"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
"google.golang.org/appengine/urlfetch"
)
const ProjectID = "cpb101demo1"
type DataflowTemplatePostBody struct {
JobName string `json:"jobName"`
GcsPath string `json:"gcsPath"`
Parameters struct {
InputTable string `json:"inputTable"`
OutputProjectID string `json:"outputProjectId"`
OutputKind string `json:"outputKind"`
} `json:"parameters"`
Environment struct {
TempLocation string `json:"tempLocation"`
Zone string `json:"zone"`
} `json:"environment"`
}
func init() {
http.HandleFunc("/cron/start", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
client := &http.Client{
Transport: &oauth2.Transport{
Source: google.AppEngineTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform"),
Base: &urlfetch.Transport{Context: ctx},
},
}
res, err := client.Post(fmt.Sprintf("https://dataflow.googleapis.com/v1b3/projects/%s/templates", ProjectID), "application/json", r.Body)
if err != nil {
log.Errorf(ctx, "ERROR dataflow: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = io.Copy(w, res.Body)
if err != nil {
log.Errorf(ctx, "ERROR Copy API response: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(res.StatusCode)
}
| sinmetal/iron-hippo | appengine/iron_hippo.go | GO | mit | 1,489 |
using NUnit.Framework;
using Ploeh.AutoFixture;
using RememBeer.Models.Dtos;
using RememBeer.Tests.Utils;
namespace RememBeer.Tests.Models.Dtos
{
[TestFixture]
public class BeerDtoTests : TestClassBase
{
[Test]
public void Setters_ShouldSetProperties()
{
var id = this.Fixture.Create<int>();
var breweryId = this.Fixture.Create<int>();
var name = this.Fixture.Create<string>();
var breweryName = this.Fixture.Create<string>();
var dto = new BeerDto();
dto.Id = id;
dto.BreweryId = breweryId;
dto.Name = name;
dto.BreweryName = breweryName;
Assert.AreEqual(id, dto.Id);
Assert.AreEqual(breweryId, dto.BreweryId);
Assert.AreSame(name, dto.Name);
Assert.AreSame(breweryName, dto.BreweryName);
}
}
}
| J0hnyBG/RememBeerMe | src/RememBeer.Tests/Models/Dtos/BeerDtoTests.cs | C# | mit | 908 |
import teca.utils as tecautils
import teca.ConfigHandler as tecaconf
import unittest
class TestFileFilter(unittest.TestCase):
def setUp(self):
self.conf = tecaconf.ConfigHandler(
"tests/test_data/configuration.json",
{"starting_path": "tests/test_data/images"}
)
self.files_list = [
"foo.doc",
"yukinon.jpg",
"cuteflushadoingflushathings.webm"
]
def test_dothefiltering(self):
self.assertTrue("foo.doc" not in
tecautils.filterImages(self.files_list,
self.conf))
self.assertTrue("yukinon.jpg" in
tecautils.filterImages(self.files_list,
self.conf))
def test_nofiles(self):
self.assertEqual(0, len(tecautils.filterImages([], self.conf)))
| alfateam123/Teca | tests/test_utils.py | Python | mit | 902 |
<?php
/*
* This file is part of the Integrated package.
*
* (c) e-Active B.V. <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Integrated\Bundle\AssetBundle\Tests\Manager;
use Integrated\Bundle\AssetBundle\Manager\AssetManager;
/**
* @author Ger Jan van den Bosch <[email protected]>
*/
class AssetManagerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var AssetManager
*/
private $manager;
/**
*/
protected function setUp()
{
$this->manager = new AssetManager();
}
/**
*/
public function testDuplicateFunction()
{
$this->manager->add('script.js');
$this->manager->add('script2.js');
$this->manager->add('script.js');
$this->assertCount(2, $this->manager->getAssets());
}
/**
*/
public function testInlineFunction()
{
$inline = 'html { color: red; }';
$this->manager->add($inline, true);
$asset = $this->manager->getAssets()[0];
$this->assertTrue($asset->isInline());
$this->assertEquals($inline, $asset->getContent());
}
/**
*/
public function testExceptionFunction()
{
$this->setExpectedException('\InvalidArgumentException');
$this->manager->add('script.js', false, 'invalid');
}
/**
*/
public function testPrependFunction()
{
$this->manager->add('script2.js');
$this->manager->add('script3.js', false, AssetManager::MODE_APPEND);
$this->manager->add('script1.js', false, AssetManager::MODE_PREPEND);
$assets = $this->manager->getAssets();
$this->assertEquals('script1.js', $assets[0]->getContent());
$this->assertEquals('script2.js', $assets[1]->getContent());
$this->assertEquals('script3.js', $assets[2]->getContent());
}
}
| integratedfordevelopers/integrated-asset-bundle | Tests/Manager/AssetManagerTest.php | PHP | mit | 1,949 |
import { h, Component } from 'preact';
import moment from 'moment';
const MonthPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-month">{ optionsFor("month", props.date) }</select>
);
const DayPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-date">{ optionsFor("day", props.date) }</select>
);
const YearPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-year">{ optionsFor("year", props.date) }</select>
);
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
const startYear = 1930;
const endYear = 2018;
function optionsFor(field, selectedDate) {
if (field === 'year') {
selected = selectedDate.year();
return [...Array(endYear-startYear).keys()].map((item, i) => {
var isSelected = (startYear + item) == selected;
return (
<option value={startYear + item} selected={isSelected ? 'selected' : ''}>{startYear + item}</option>
);
});
}
else if (field === 'month') {
selected = selectedDate.month();
return months.map((item, i) => {
var isSelected = i == selected;
return (
<option value={i} selected={isSelected ? 'selected' : ''}>{item}</option>
);
});
}
else if (field === 'day') {
var selected = selectedDate.date();
var firstDay = 1;
var lastDay = moment(selectedDate).add(1, 'months').date(1).subtract(1, 'days').date() + 1;
return [...Array(lastDay-firstDay).keys()].map((item, i) => {
var isSelected = (item + 1) == selected;
return (
<option value={item + 1} selected={isSelected ? 'selected': ''}>{item + 1}</option>
)
});
}
}
export default class DatePicker extends Component {
constructor(props) {
super(props);
this.state = {
date: props.date
};
this.onChange = this.onChange.bind(this);
}
onChange(event) {
var month = document.getElementById('select-month').value;
var day = document.getElementById('select-date').value;
var year = document.getElementById('select-year').value;
var newDate = moment().year(year).month(month).date(day);
this.setState({ date: newDate })
this.props.onChange(newDate);
}
render() {
return (
<div>
<MonthPicker date={this.state.date} onChange={this.onChange} />
<DayPicker date={this.state.date} onChange={this.onChange} />
<YearPicker date={this.state.date} onChange={this.onChange} />
</div>
)
}
} | jc4p/natal-charts | app/src/components/DatePicker.js | JavaScript | mit | 2,568 |
'use strict';
angular.module('users').factory('Permissions', ['Authentication', '$location',
function(Authentication, $location) {
// Permissions service logic
// ...
// Public API
return {
//check if user suits the right permissions for visiting the page, Otherwise go to 401
userRolesContains: function (role) {
if (!Authentication.user || Authentication.user.roles.indexOf(role) === -1) {
return false;
} else {
return true;
}
},
//This function returns true if the user is either admin or maintainer
adminOrMaintainer: function () {
if (Authentication.user && (Authentication.user.roles.indexOf('admin')> -1 || Authentication.user.roles.indexOf('maintainer')> -1)) {
return true;
} else {
return false;
}
},
isPermissionGranted: function (role) {
if (!Authentication.user || Authentication.user.roles.indexOf(role) === -1) {
$location.path('/401');
}
},
isAdmin: function () {
if (Authentication.user && (Authentication.user.roles.indexOf('admin') > -1)) {
return true;
} else {
return false;
}
}
};
}
]); | hacor/gamwbras | public/modules/users/services/permissions.client.service.js | JavaScript | mit | 1,228 |
import $ from 'jquery';
import keyboard from 'virtual-keyboard';
$.fn.addKeyboard = function () {
return this.keyboard({
openOn: null,
stayOpen: false,
layout: 'custom',
customLayout: {
'normal': ['7 8 9 {c}', '4 5 6 {del}', '1 2 3 {sign}', '0 0 {dec} {a}'],
},
position: {
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
of: null,
my: 'center top',
at: 'center top',
// at2 is used when "usePreview" is false (centers keyboard at the bottom
// of the input/textarea)
at2: 'center top',
collision: 'flipfit flipfit'
},
reposition: true,
css: {
input: 'form-control input-sm',
container: 'center-block dropdown-menu',
buttonDefault: 'btn btn-default',
buttonHover: 'btn-light',
// used when disabling the decimal button {dec}
// when a decimal exists in the input area
buttonDisabled: 'enabled',
},
});
};
| kamillamagna/NMF_Tool | app/javascript/components/addKeyboard.js | JavaScript | mit | 971 |
require 'nokogiri'
require 'ostruct'
require 'active_support/core_ext/string'
require 'active_support/core_ext/date'
module Lifebouy
class MalformedRequestXml < StandardError
def initialize(xml_errors)
@xml_errors = xml_errors
end
def message
"The request contains the following errors:\n\t#{@xml_errors.join("\n\t")}"
end
end
class MalformedResponseData < MalformedRequestXml
def message
"The response contains the following errors:\n\t#{@xml_errors.join("\n\t")}"
end
end
class RequestHandler
attr_reader :request_error, :schema, :request_doc, :response_error
attr_accessor :response_data
def initialize(wsdl_file, request_xml)
@wsdl = Nokogiri::XML(File.read(wsdl_file))
# Find the root schema node
schema_namespace = @wsdl.namespaces.select { |k,v| v =~ /XMLSchema/ }.first
target_namespace_url = @wsdl.root['targetNamespace']
@target_namespace = @wsdl.namespaces.select { |k,v| v == target_namespace_url}.first
@schema_prefix = schema_namespace.first.split(/:/).last
schema_root = @wsdl.at_xpath("//#{@schema_prefix}:schema").dup
schema_root.add_namespace_definition(@target_namespace.first.split(/:/).last, @target_namespace.last)
# Create a document to store the schema and the parse it into a Schema for validation
@schema_doc = Nokogiri::XML::Document.new
@schema_doc << schema_root
@schema = Nokogiri::XML::Schema(@schema_doc.to_xml)
envelope = Nokogiri::XML(request_xml)
request_data = envelope.at_xpath("//#{envelope.root.namespace.prefix}:Body").first_element_child
@request_doc = Nokogiri::XML::Document.new
@request_doc << request_data
@response_data = OpenStruct.new
end
def validate_request_xml?
begin
validate_request_xml!
return true
rescue MalformedRequestXml => e
@request_error = e
return false
end
end
def validate_request_xml!
request_errors = []
@schema.validate(request_doc).each do |error|
request_errors << "Line #{error.line}: #{error.message}"
end
raise MalformedRequestXml.new(request_errors) unless request_errors.empty?
end
def request_data
@request_data ||= build_request_data
end
def validate_response?
begin
validate_response!
return true
rescue MalformedResponseData => e
@response_error = e
return false
end
end
def validate_response!
raise MalformedResponseData.new(["Empty Responses Not Allowed"]) if response_data.to_h.empty?
@response_xml = nil
response_errors = []
@schema.validate(response_xml).each do |error|
response_errors << "Line #{error.line}: #{error.message}"
end
raise MalformedResponseData.new(response_errors) unless response_errors.empty?
end
def response_xml
@response_xml ||= build_response_xml
end
def response_soap
end
private
def build_response_xml
xml = Nokogiri::XML::Document.new
symbols_and_names = {}
@schema_doc.xpath("//#{@schema_prefix}:element").each do |e_node|
symbols_and_names[e_node[:name].underscore.to_sym] = e_node[:name]
end
xml << ostruct_to_node(@response_data, xml, symbols_and_names)
xml
end
def ostruct_to_node(ostruct, xml, symbols_and_names)
raise MalformedResponseData.new(["Structure Must Contain a Node Name"]) if ostruct.name.blank?
ele = xml.create_element(ostruct.name)
ele.add_namespace_definition(nil, @target_namespace.last)
ostruct.each_pair do |k,v|
next if k == :name
if v.is_a?(OpenStruct)
ele << ostruct_to_node(v, xml, symbols_and_names)
else
ele << create_element_node(xml, symbols_and_names[k], v)
end
end
ele
end
def create_element_node(xml, node_name, value)
t_node = @schema_doc.at_xpath("//#{@schema_prefix}:element[@name='#{node_name}']")
formatted_value = value.to_s
begin
case type_for_element_name(node_name)
when 'integer', 'int'
formatted_value = '%0d' % value
when 'boolean'
formatted_value = (value == true ? 'true' : 'false')
when 'date', 'time', 'dateTime'
formatted_value = value.strftime('%m-%d-%Y')
end
rescue Exception => e
raise MalformedResponseException.new([e.message])
end
to_add = xml.create_element(node_name, formatted_value)
to_add.add_namespace_definition(nil, @target_namespace.last)
to_add
end
def build_request_data
@request_data = node_to_ostruct(@request_doc.first_element_child)
end
def node_to_ostruct(node)
ret = OpenStruct.new
ret[:name] = node.node_name
node.element_children.each do |ele|
if ele.element_children.count > 0
ret[ele.node_name.underscore.to_sym] = node_to_ostruct(ele)
else
ret[ele.node_name.underscore.to_sym] = xml_to_type(ele)
end
end
ret
end
def xml_to_type(node)
return nil if node.text.blank?
case type_for_element_name(node.node_name)
when 'decimal', 'float', 'double'
node.text.to_f
when 'integer', 'int'
node.text.to_i
when 'boolean'
node.text == 'true'
when 'date', 'time', 'dateTime'
Date.parse(node.text)
else
node.text
end
end
def type_for_element_name(node_name)
t_node = @schema_doc.at_xpath("//#{@schema_prefix}:element[@name='#{node_name}']")
raise "No type defined for #{node_name}" unless t_node
t_node[:type].gsub(/#{@schema_prefix}:/, '')
end
end
end | reedswenson/lifebouy | lib/lifebouy/request_handler.rb | Ruby | mit | 5,812 |
/**
* Trait class
*/
function Trait(methods, allTraits) {
allTraits = allTraits || [];
this.traits = [methods];
var extraTraits = methods.$traits;
if (extraTraits) {
if (typeof extraTraits === "string") {
extraTraits = extraTraits.replace(/ /g, '').split(',');
}
for (var i = 0, c = extraTraits.length; i < c; i++) {
this.use(allTraits[extraTraits[i]]);
}
}
}
Trait.prototype = {
constructor: Trait,
use: function (trait) {
if (trait) {
this.traits = this.traits.concat(trait.traits);
}
return this;
},
useBy: function (obj) {
for (var i = 0, c = this.traits.length; i < c; i++) {
var methods = this.traits[i];
for (var prop in methods) {
if (prop !== '$traits' && !obj[prop] && methods.hasOwnProperty(prop)) {
obj[prop] = methods[prop];
}
}
}
}
};
module.exports = Trait;
| azproduction/node-jet | lib/plugins/app/lib/Trait.js | JavaScript | mit | 1,059 |
require 'integrity'
require 'fileutils'
module Integrity
class Notifier
class Artifacts < Notifier::Base
def initialize(commit, config={})
@project = commit.project
super
end
def deliver!
return unless self.commit.successful?
self.publish_artifacts
self.generate_indexes if should_generate_indexes
end
def generate_indexes
Artifacts.generate_index(self.artifact_root, false)
Artifacts.generate_index(File.join(self.artifact_root, @project.name), true)
Artifacts.generate_index(self.artifact_archive_dir, true)
end
def publish_artifacts
self.artifacts.each do |name, config|
next if config.has_key?('disabled') && config['disabled']
artifact_output_dir = File.expand_path(File.join(self.working_dir, config['output_dir']))
if File.exists?(artifact_output_dir)
FileUtils::Verbose.mkdir_p(self.artifact_archive_dir) unless File.exists?(self.artifact_archive_dir)
FileUtils::Verbose.mv artifact_output_dir, self.artifact_archive_dir, :force => true
end
end
end
def artifacts
# If the configuration is missing, try rcov for kicks
@artifacts ||= self.load_config_yaml
@artifacts ||= {'rcov' => { 'output_dir' => 'coverage' }}
@artifacts
end
def artifact_archive_dir
@artifact_archive_dir ||= File.expand_path(File.join(self.artifact_root, @project.name, self.commit.short_identifier))
@artifact_archive_dir
end
def artifact_root
# If the configuration is missing, assume that the export_directory is {integrity_dir}/builds
@artifact_root ||= self.load_artifact_root
@artifact_root ||= Artifacts.default_artifact_path
@artifact_root
end
def working_dir
@working_dir ||= Integrity.config[:export_directory] / "#{Integrity::SCM.working_tree_path(@project.uri)}-#{@project.branch}"
@working_dir
end
def should_generate_indexes
@config.has_key?('generate_indexes') ? @config['generate_indexes'] == '1' : false
end
protected
def load_artifact_root
if @config.has_key?('artifact_root')
root_path = @config['artifact_root']
unless File.exists?(root_path)
default_path = Artifacts.default_artifact_path
Integrity.log "WARNING: Configured artifact_root: #{root_path} does not exist. Using default: #{default_path}"
root_path = default_path
end
end
root_path
end
def load_config_yaml
config = nil
if @config.has_key?('config_yaml')
config_yaml = File.expand_path(File.join(working_dir, @config['config_yaml']))
if File.exists?(config_yaml)
config = YAML.load_file(config_yaml)
else
Integrity.log "WARNING: Configured yaml file: #{config_yaml} does not exist! Using default configuration."
end
end
config
end
class << self
def to_haml
File.read(File.dirname(__FILE__) + "/config.haml")
end
def default_artifact_path
File.expand_path(File.join(Integrity.config[:export_directory], '..', 'public', 'artifacts'))
end
def generate_index(dir, link_to_parent)
hrefs = build_hrefs(dir, link_to_parent)
rendered = render_index(dir, hrefs)
write_index(dir, rendered)
end
def build_hrefs(dir, link_to_parent)
hrefs = {}
Dir.entries(dir).each do |name|
# skip dot files
next if name.match(/^\./)
hrefs[name] = name
hrefs[name] << "/index.html" if File.directory?(File.join(dir, name))
end
hrefs['..'] = '../index.html' if link_to_parent
hrefs
end
def render_index(dir, hrefs)
index_haml = File.read(File.dirname(__FILE__) + '/index.haml')
engine = ::Haml::Engine.new(index_haml, {})
engine.render(nil, {:dir => dir, :hrefs => hrefs})
end
def write_index(dir, content)
index_path = File.join(dir, 'index.html')
File.open(index_path, 'w') {|f| f.write(content) }
end
end
end
register Artifacts
end
end
| subakva/integrity-artifacts | lib/integrity/notifier/artifacts.rb | Ruby | mit | 4,391 |
import {Component, Input} from '@angular/core';
import {CORE_DIRECTIVES} from '@angular/common';
import {ROUTER_DIRECTIVES, Router} from '@angular/router-deprecated';
import {AuthService} from '../common/auth.service';
@Component({
selector: 'todo-navbar',
templateUrl: 'app/navbar/navbar.component.html',
directives: [ROUTER_DIRECTIVES, CORE_DIRECTIVES]
})
export class NavbarComponent {
@Input() brand: string;
@Input() routes: any[];
name: string;
constructor(private _authService: AuthService, private _router: Router) {
this._authService.profile.subscribe(profile => this.name = profile && profile.name);
}
getName() {
console.log('getName');
return this.name;
}
logout($event: Event) {
$event.preventDefault();
this._authService.logout();
this._router.navigateByUrl('/');
}
isLoggedIn() {
return Boolean(this.name);
}
}
| Boychenko/sample-todo-2016 | clients/angular2/app/navbar/navbar.component.ts | TypeScript | mit | 889 |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Game = mongoose.model('Game'),
Team = mongoose.model('Team'),
Player = mongoose.model('Player'),
async = require('async');
exports.all = function(req, res) {
Game.find({'played': true}).exec(function(err, games) {
if (err) {
return res.json(500, {
error: 'fucked up grabbing dem games'
});
}
res.json(games);
});
};
exports.logGame = function(req, res, next) {
var loggedGame = req.body;
Game.findAllMatchesBetweenTeams([loggedGame.teams[0].teamId, loggedGame.teams[1].teamId], function(err, games) {
if (err) {
console.log('error finding matchups\n' + err);
res.json(500, 'fucked up finding dem games');
return;
}
var matchedGame;
var teamOneIndex;
var teamTwoIndex;
for (var gameIdx = 0; gameIdx < games.length; gameIdx += 1) {
if (games[gameIdx].teams[0].home === loggedGame.teams[0].home && games[gameIdx].teams[0].teamId.toString() === loggedGame.teams[0].teamId) {
matchedGame = games[gameIdx];
teamOneIndex = 0;
teamTwoIndex = 1;
break;
} else if (games[gameIdx].teams[1].home === loggedGame.teams[0].home && games[gameIdx].teams[1].teamId.toString() === loggedGame.teams[0].teamId) {
matchedGame = games[gameIdx];
teamOneIndex = 1;
teamTwoIndex = 0;
break;
}
}
if (!matchedGame) {
res.json(500, 'no matchup between those teams found');
return;
}
if (matchedGame.played) {
console.log('match already played!');
res.json(500, 'game already played');
return;
}
matchedGame.teams[teamOneIndex].goals = loggedGame.teams[0].goals;
matchedGame.teams[teamOneIndex].events = loggedGame.teams[0].events;
matchedGame.teams[teamTwoIndex].goals = loggedGame.teams[1].goals;
matchedGame.teams[teamTwoIndex].events = loggedGame.teams[1].events;
matchedGame.played = true;
var datePlayed = new Date();
matchedGame.datePlayed = datePlayed;
matchedGame.save(function(err) {
if (err) {
console.log('failed to save game -- ' + matchedGame + ' -- ' + err );
res.json(500, 'error saving game -- ' + err);
} else {
async.series([
function(callback) {
console.log('PROCESSING EVENTS');
processEvents(matchedGame, callback);
},
function(callback) {
console.log('UPDATING STANDINGS');
updateStandings(callback);
}
],
function(err, results) {
if (err) {
res.sendStatus(400);
console.log(err);
} else {
res.sendStatus(200);
}
});
}
});
});
var processEvents = function(game, callback) {
/*jshint -W083 */
var updatePlayerEvents = function(playerEvents, playerCallback) {
console.log('UPDATING EVENTS FOR PLAYER ' + playerEvents.events[0].player);
findOrCreateAndUpdatePlayer(playerEvents, playerEvents.teamId, playerCallback);
};
var processEventsForTeam = function(team, teamCallback) {
console.log('PROCESSING EVENTS FOR ' + team);
var playerEventMap = {};
for (var eventIdx = 0; eventIdx < team.events.length; eventIdx += 1) {
var playerEvent = team.events[eventIdx];
console.log('PROCESSING EVENT ' + playerEvent);
if (playerEventMap[playerEvent.player] === undefined) {
console.log('PLAYER NOT IN MAP, ADDING ' + playerEvent.player);
playerEventMap[playerEvent.player] = {teamId: team.teamId, events: [], gameDate: game.datePlayed};
}
playerEventMap[playerEvent.player].events.push(playerEvent);
}
console.log('player event map created: ' + playerEventMap);
var playerEventMapValues = [];
for (var key in playerEventMap) {
playerEventMapValues.push(playerEventMap[key]);
}
async.each(playerEventMapValues, updatePlayerEvents, function(err) {
if (err) {
teamCallback(err);
} else {
teamCallback();
}
});
};
async.each(game.teams, processEventsForTeam, function(err) {
if (err) {
callback(err);
} else {
callback();
}
});
};
var findOrCreateAndUpdatePlayer = function(playerEvents, teamId, playerCallback) {
console.log('finding/creating player -- ' + playerEvents + ' -- ' + teamId);
Player.findOne({name: playerEvents.events[0].player, teamId: teamId}, function(err, player) {
if (err) {
console.log('error processing events -- ' + JSON.stringify(playerEvents) + ' -- ' + err);
playerCallback(err);
}
if (!player) {
createAndUpdatePlayer(playerEvents, teamId, playerCallback);
} else {
incrementEvents(player, playerEvents, playerCallback);
}
});
};
var createAndUpdatePlayer = function(playerEvents, teamId, playerCallback) {
Player.create({name: playerEvents.events[0].player, teamId: teamId}, function(err, createdPlayer) {
if (err) {
console.log('error creating player while processing event -- ' + JSON.stringify(playerEvents) + ' -- ' + err);
}
incrementEvents(createdPlayer, playerEvents, playerCallback);
});
};
var incrementEvents = function(player, playerEvents, playerCallback) {
var suspended = false;
for (var eventIdx = 0; eventIdx < playerEvents.events.length; eventIdx += 1) {
var eventType = playerEvents.events[eventIdx].eventType;
if (eventType === 'yellow card') {
player.yellows += 1;
if (player.yellows % 5 === 0) {
suspended = true;
}
} else if (eventType === 'red card') {
player.reds += 1;
suspended = true;
} else if (eventType === 'goal') {
player.goals += 1;
} else if (eventType === 'own goal') {
player.ownGoals += 1;
}
}
player.save(function(err) {
if (err) {
console.log('error incrementing event for player -- ' + JSON.stringify(player) + ' -- ' + eventType);
playerCallback(err);
} else {
if (suspended) {
suspendPlayer(player, playerEvents.gameDate, playerCallback);
} else {
playerCallback();
}
}
});
};
var updateStandings = function(callback) {
Team.find({}, function(err, teams) {
if (err) {
console.log('error retrieving teams for standings update -- ' + err);
callback(err);
} else {
resetStandings(teams);
Game.find({'played': true}, null, {sort: {datePlayed : 1}}, function(err, games) {
if (err) {
console.log('error retrieving played games for standings update -- ' + err);
callback(err);
} else {
for (var gameIdx = 0; gameIdx < games.length; gameIdx += 1) {
processGameForStandings(games[gameIdx], teams);
}
saveStandings(teams, callback);
}
});
}
});
};
var saveStandings = function(teams, standingsCallback) {
var saveTeam = function(team, saveCallback) {
team.save(function(err){
if (err) {
console.log('error saving team -- ' + team + ' -- ' + err);
saveCallback(err);
} else {
saveCallback();
}
});
};
async.each(teams, saveTeam, function(err) {
if (err) {
standingsCallback(err);
} else {
standingsCallback();
}
});
};
var resetStandings = function(teams) {
for (var teamIdx in teams) {
teams[teamIdx].wins = 0;
teams[teamIdx].losses = 0;
teams[teamIdx].draws = 0;
teams[teamIdx].points = 0;
teams[teamIdx].goalsFor = 0;
teams[teamIdx].goalsAgainst = 0;
//teams[teamIdx].suspensions = [];
}
};
var processGameForStandings = function(game, teams) {
for (var teamResultIdx = 0; teamResultIdx < game.teams.length; teamResultIdx += 1) {
var teamResult = game.teams[teamResultIdx];
var opponentResult = game.teams[1 - teamResultIdx];
var team;
for (var teamIdx = 0; teamIdx < teams.length; teamIdx += 1) {
if (teams[teamIdx]._id.equals(teamResult.teamId)) {
team = teams[teamIdx];
break;
}
}
team.lastGamePlayed = game.datePlayed;
team.goalsFor += teamResult.goals;
team.goalsAgainst += opponentResult.goals;
if (teamResult.goals > opponentResult.goals) {
team.wins += 1;
team.points += 3;
} else if (teamResult.goals === opponentResult.goals) {
team.draws += 1;
team.points += 1;
} else {
team.losses += 1;
}
}
// game.played=false;
// game.datePlayed=undefined;
// for (var teamIdx = 0; teamIdx < game.teams.length; teamIdx += 1) {
// game.teams[teamIdx].goals = 0;
// game.teams[teamIdx].events = [];
// }
// game.save();
};
var suspendPlayer = function(player, gameDate, suspensionCallback) {
Team.findOne({_id: player.teamId}, function(err, team){
if (err) {
console.log('error loading team to suspend a dude -- ' + player);
suspensionCallback(err);
} else {
if (!team.suspensions) {
team.suspensions = [];
}
team.suspensions.push({player: player.name, dateSuspended: gameDate});
team.save(function(err) {
if (err) {
console.log('error saving suspension 4 dude -- ' + player + ' -- ' + team);
suspensionCallback(err);
} else {
suspensionCallback();
}
});
}
});
};
}; | javi7/epl-98 | packages/custom/league/server/controllers/games.js | JavaScript | mit | 9,754 |
package championpicker.console;
import com.googlecode.lanterna.gui.*;
import com.googlecode.lanterna.TerminalFacade;
import com.googlecode.lanterna.terminal.Terminal;
import com.googlecode.lanterna.terminal.TerminalSize;
import com.googlecode.lanterna.terminal.swing.SwingTerminal;
import com.googlecode.lanterna.gui.GUIScreen;
import com.googlecode.lanterna.gui.dialog.DialogButtons;
import com.googlecode.lanterna.gui.component.Button;
import com.googlecode.lanterna.gui.component.Panel;
import com.googlecode.lanterna.gui.component.Label;
import com.googlecode.lanterna.gui.Window;
import com.googlecode.lanterna.screen.Screen;
import com.googlecode.lanterna.screen.Screen;
import championpicker.Main;
import championpicker.console.mainStartUp;
import championpicker.console.queueWindow;
import javax.swing.JFrame;
public class mainMenu extends Window{
public mainMenu(String name){
super(name);
queueWindow win = new queueWindow();
addComponent(new Button("Queue!", new Action(){
public void doAction(){
System.out.println("Success!");
mainStartUp.gui.showWindow(win, GUIScreen.Position.CENTER);
}}));
}
} | DanielBoerlage/champion-picker | src/championpicker/console/mainMenu.java | Java | mit | 1,150 |
(function(){
'use strict';
angular.module('GamemasterApp')
.controller('DashboardCtrl', function ($scope, $timeout, $mdSidenav, $http) {
$scope.users = ['Fabio', 'Leonardo', 'Thomas', 'Gabriele', 'Fabrizio', 'John', 'Luis', 'Kate', 'Max'];
})
})(); | jswaldon/gamemaster | public/app/dashboard/dashboard.ctrl.js | JavaScript | mit | 273 |
require 'byebug'
module Vorm
module Validatable
class ValidationError
def clear_all
@errors = Hash.new { |k, v| k[v] = [] }
end
end
end
end
class Valid
include Vorm::Validatable
def self.reset!
@validators = nil
end
end
describe Vorm::Validatable do
before { Valid.reset! }
context "class methods" do
subject { Valid }
describe ".validates" do
it { is_expected.to respond_to(:validates) }
it "raises argument error when given arg is not string" do
expect { subject.validates(:email) }
.to raise_error(ArgumentError, "Field name must be a string")
end
it "raises argument error when no block given" do
expect { subject.validates("email") }
.to raise_error(ArgumentError, "You must provide a block")
end
it "stores a validator" do
subject.validates("email") { "required" }
expect(subject.instance_variable_get('@validators')["email"].length).to be(1)
end
it "stores multiple validators" do
subject.validates("email") { "required" }
subject.validates("email") { "not valid" }
subject.validates("password") { "required" }
expect(subject.instance_variable_get('@validators')["email"].length).to be(2)
expect(subject.instance_variable_get('@validators')["password"].length).to be(1)
end
end
end
context "instance methods" do
subject { Valid.new }
before { subject.errors.clear_all }
describe ".validate!" do
it { is_expected.to respond_to(:validate!) }
it "adds errors when invalid" do
Valid.validates("email") { true }
expect { subject.validate! }.to change { subject.errors.on("email").length }.by(1)
end
it "adds the validation messages to errors for the right field" do
Valid.validates("email") { "not valid" }
subject.valid?
expect(subject.errors.on("email")).to eq(["not valid"])
end
it "adds validation messages to each field when invalid" do
Valid.validates("email") { "required" }
Valid.validates("email") { "not valid" }
Valid.validates("password") { "too short" }
subject.validate!
expect(subject.errors.on("email").length).to be(2)
expect(subject.errors.on("password").length).to be(1)
expect(subject.errors.on("email")).to eq(["required", "not valid"])
expect(subject.errors.on("password")).to eq(["too short"])
end
end
describe ".valid?" do
it { is_expected.to respond_to(:valid?) }
it "calls .validate!" do
expect(subject).to receive(:validate!)
subject.valid?
end
it "calls .errors.empty?" do
expect(subject.errors).to receive(:empty?)
subject.valid?
end
it "returns true when no validations" do
expect(subject).to be_valid
end
it "returns true when validations pass" do
Valid.validates("email") { nil }
expect(subject).to be_valid
end
it "returns false when validations fail" do
Valid.validates("email") { "required" }
expect(subject).not_to be_valid
end
end
end
end
| vastus/vorm | spec/lib/vorm/validatable_spec.rb | Ruby | mit | 3,216 |
module Embratel
class PhoneBill
attr_reader :payables
def initialize(path)
@payables = CSVParser.parse(path)
end
def calls
@calls ||= payables.select(&:call?)
end
def fees
@fees ||= payables.select(&:fee?)
end
def total
@total ||= payables.inject(0) { |sum, payable| sum += payable.cost.to_f }
end
end
end
| mpereira/embratel | lib/embratel/phone_bill.rb | Ruby | mit | 374 |
const express = require('express');
const router = express.Router();
const routes = require('./routes')(router);
module.exports = router;
| abhaydgarg/Simplenote | api/v1/index.js | JavaScript | mit | 139 |
package simulation.generators;
import simulation.data.PetrolStation;
import simulation.data.Road;
/**
* Created by user on 03.06.2017.
*/
public class PetrolStationGenerator {
private Road road;
private int minimalDistanceBetweenStations = 50;
private int maximumDistanceBetweenStations = 200;
private float minimalFuelPrice = 3.5f;
private float maximumFuelPrice = 4f;
public PetrolStationGenerator(Road road) {
this.road = road;
}
public void generateStationsOnTheRoad(){
RandomIntegerGenerator generator = new RandomIntegerGenerator();
int lastStationPosition = 0;
road.addPetrolStation(generateStation(lastStationPosition));
while (lastStationPosition < road.getDistance()){
int nextStationDistance = generator.generateNumberFromRange(minimalDistanceBetweenStations,maximumDistanceBetweenStations);
if(lastStationPosition+nextStationDistance <= road.getDistance()){
road.addPetrolStation(generateStation(lastStationPosition+nextStationDistance));
lastStationPosition += nextStationDistance;
}else{
break;
}
}
}
private PetrolStation generateStation(int positionOnRoad){
float fuelPrice = new RandomFloatGenerator().generateNumberFromRange(minimalFuelPrice,maximumFuelPrice);
return new PetrolStation(positionOnRoad,fuelPrice);
}
public Road getRoad() {
return road;
}
public void setRoad(Road road) {
this.road = road;
}
public int getMinimalDistanceBetweenStations() {
return minimalDistanceBetweenStations;
}
public void setMinimalDistanceBetweenStations(int minimalDistanceBetweenStations) {
this.minimalDistanceBetweenStations = minimalDistanceBetweenStations;
}
public int getMaximumDistanceBetweenStations() {
return maximumDistanceBetweenStations;
}
public void setMaximumDistanceBetweenStations(int maximumDistanceBetweenStations) {
this.maximumDistanceBetweenStations = maximumDistanceBetweenStations;
}
public float getMinimalFuelPrice() {
return minimalFuelPrice;
}
public void setMinimalFuelPrice(float minimalFuelPrice) {
this.minimalFuelPrice = minimalFuelPrice;
}
public float getMaximumFuelPrice() {
return maximumFuelPrice;
}
public void setMaximumFuelPrice(float maximumFuelPrice) {
this.maximumFuelPrice = maximumFuelPrice;
}
}
| MiszelHub/FuzzyDriverRefueling | Fuzzy-Driver/src/main/java/simulation/generators/PetrolStationGenerator.java | Java | mit | 2,533 |
var HDWalletProvider = require("truffle-hdwallet-provider");
var mnemonic = "candy maple cake sugar pudding cream honey rich smooth crumble sweet treat";
module.exports = {
networks: {
development: {
provider: function () {
return new HDWalletProvider(mnemonic, "http://127.0.0.1:7545/", 0, 50);
},
network_id: "*",
},
},
compilers: {
solc: {
version: "^0.5.2",
},
},
};
| manishbisht/Competitive-Programming | Hiring Challenges/Bosch/Blockchain Developer Hiring/Round 2/truffle.js | JavaScript | mit | 484 |
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var path = require("path");
var webpack = require("webpack");
var projectTemplatesRoot = "../../ppb/templates/";
module.exports = {
context: path.resolve(__dirname, "src"),
entry: {
app: "./js/main.js"
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "js/site.js?[hash]",
publicPath: "/site_media/static"
},
module: {
loaders: [
{
test: /\.(gif|png|ico|jpg|svg)$/,
include: [
path.resolve(__dirname, "src/images")
],
loader: "file-loader?name=/images/[name].[ext]"
},
{ test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader") },
{
test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
include: [
path.resolve(__dirname, "/src/fonts"),
path.resolve(__dirname, "../node_modules")
],
loader: "file-loader?name=/fonts/[name].[ext]?[hash]"
},
{ test: /\.jsx?$/, loader: "babel-loader", query: {compact: false} },
]
},
resolve: {
extensions: ["", ".js", ".jsx"],
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new ExtractTextPlugin("css/site.css?[hash]"),
new HtmlWebpackPlugin({
filename: projectTemplatesRoot + "_styles.html",
templateContent: function(templateParams, compilation) {
var link = "";
for (var css in templateParams.htmlWebpackPlugin.files.css) {
link += "<link href='" + templateParams.htmlWebpackPlugin.files.css[css] + "' rel='stylesheet' />\n"
}
return link;
}
}),
new HtmlWebpackPlugin({
filename: projectTemplatesRoot + "_scripts.html",
templateContent: function(templateParams, compilation) {
var script = "";
for (var js in templateParams.htmlWebpackPlugin.files.js) {
script += "<script src='" + templateParams.htmlWebpackPlugin.files.js[js] + "'></script>\n"
}
return script;
}
})
]
};
| pinax/blog.pinaxproject.com | static/webpack.config.js | JavaScript | mit | 2,456 |
var h = require('hyperscript')
var human = require('human-time')
exports.needs = {}
exports.gives = 'message_meta'
exports.create = function () {
function updateTimestampEl(el) {
el.firstChild.nodeValue = human(new Date(el.timestamp))
return el
}
setInterval(function () {
var els = [].slice.call(document.querySelectorAll('.timestamp'))
els.forEach(updateTimestampEl)
}, 60e3)
return function (msg) {
return updateTimestampEl(h('a.enter.timestamp', {
href: '#'+msg.key,
timestamp: msg.value.timestamp,
title: new Date(msg.value.timestamp)
}, ''))
}
}
| cryptix/talebay | modules_basic/timestamp.js | JavaScript | mit | 613 |
import { HookContext, Application, createContext, getServiceOptions } from '@feathersjs/feathers';
import { NotFound, MethodNotAllowed, BadRequest } from '@feathersjs/errors';
import { createDebug } from '@feathersjs/commons';
import isEqual from 'lodash/isEqual';
import { CombinedChannel } from '../channels/channel/combined';
import { RealTimeConnection } from '../channels/channel/base';
const debug = createDebug('@feathersjs/transport-commons');
export const DEFAULT_PARAMS_POSITION = 1;
export const paramsPositions: { [key: string]: number } = {
find: 0,
update: 2,
patch: 2
};
export function normalizeError (e: any) {
const hasToJSON = typeof e.toJSON === 'function';
const result = hasToJSON ? e.toJSON() : {};
if (!hasToJSON) {
Object.getOwnPropertyNames(e).forEach(key => {
result[key] = e[key];
});
}
if (process.env.NODE_ENV === 'production') {
delete result.stack;
}
delete result.hook;
return result;
}
export function getDispatcher (emit: string, socketMap: WeakMap<RealTimeConnection, any>, socketKey?: any) {
return function (event: string, channel: CombinedChannel, context: HookContext, data?: any) {
debug(`Dispatching '${event}' to ${channel.length} connections`);
channel.connections.forEach(connection => {
// The reference between connection and socket is set in `app.setup`
const socket = socketKey ? connection[socketKey] : socketMap.get(connection);
if (socket) {
const eventName = `${context.path || ''} ${event}`.trim();
let result = channel.dataFor(connection) || context.dispatch || context.result;
// If we are getting events from an array but try to dispatch individual data
// try to get the individual item to dispatch from the correct index.
if (!Array.isArray(data) && Array.isArray(context.result) && Array.isArray(result)) {
result = context.result.find(resultData => isEqual(resultData, data));
}
debug(`Dispatching '${eventName}' to Socket ${socket.id} with`, result);
socket[emit](eventName, result);
}
});
};
}
export async function runMethod (app: Application, connection: RealTimeConnection, path: string, method: string, args: any[]) {
const trace = `method '${method}' on service '${path}'`;
const methodArgs = args.slice(0);
const callback = typeof methodArgs[methodArgs.length - 1] === 'function'
? methodArgs.pop() : function () {};
debug(`Running ${trace}`, connection, args);
const handleError = (error: any) => {
debug(`Error in ${trace}`, error);
callback(normalizeError(error));
};
try {
const lookup = app.lookup(path);
// No valid service was found throw a NotFound error
if (lookup === null) {
throw new NotFound(`Service '${path}' not found`);
}
const { service, params: route = {} } = lookup;
const { methods } = getServiceOptions(service);
// Only service methods are allowed
if (!methods.includes(method)) {
throw new MethodNotAllowed(`Method '${method}' not allowed on service '${path}'`);
}
const position = paramsPositions[method] !== undefined ? paramsPositions[method] : DEFAULT_PARAMS_POSITION;
const query = methodArgs[position] || {};
// `params` have to be re-mapped to the query and added with the route
const params = Object.assign({ query, route, connection }, connection);
// `params` is always the last parameter. Error if we got more arguments.
if (methodArgs.length > (position + 1)) {
throw new BadRequest(`Too many arguments for '${method}' method`);
}
methodArgs[position] = params;
const ctx = createContext(service, method);
const returnedCtx: HookContext = await (service as any)[method](...methodArgs, ctx);
const result = returnedCtx.dispatch || returnedCtx.result;
debug(`Returned successfully ${trace}`, result);
callback(null, result);
} catch (error: any) {
handleError(error);
}
}
| feathersjs/feathers | packages/transport-commons/src/socket/utils.ts | TypeScript | mit | 3,996 |
version https://git-lfs.github.com/spec/v1
oid sha256:e40a08695f05163cfb0eaeeef4588fcfad55a6576cfadfb079505495605beb33
size 27133
| yogeshsaroya/new-cdnjs | ajax/libs/fuelux/2.5.0/datepicker.js | JavaScript | mit | 130 |
<?php
class Thread extends Eloquent {
public static $table = 'threads';
public static $timestamps = true;
public function replies()
{
return $this->has_many('Reply');
}
} | hassan-c/laravelapp | application/models/thread.php | PHP | mit | 193 |
#!/usr/bin/env python
from hdf5handler import HDF5Handler
handler = HDF5Handler('mydata.hdf5')
handler.open()
for i in range(100):
handler.put(i, 'numbers')
handler.close()
| iambernie/hdf5handler | examples/opening.py | Python | mit | 183 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Famous Industries Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
import { Geometry } from '../Geometry';
import { GeometryHelper } from '../GeometryHelper';
/**
* This function generates custom buffers and passes them to
* a new static geometry, which is returned to the user.
*
* @class Tetrahedron
* @constructor
*
* @param {Object} options Parameters that alter the
* vertex buffers of the generated geometry.
*
* @return {Object} constructed geometry
*/
class Tetrahedron extends Geometry {
constructor(options) {
//handled by es6 transpiler
//if (!(this instanceof Tetrahedron)) return new Tetrahedron(options);
var textureCoords = [];
var normals = [];
var detail;
var i;
var t = Math.sqrt(3);
var vertices = [
// Back
1, -1, -1 / t,
-1, -1, -1 / t,
0, 1, 0,
// Right
0, 1, 0,
0, -1, t - 1 / t,
1, -1, -1 / t,
// Left
0, 1, 0,
-1, -1, -1 / t,
0, -1, t - 1 / t,
// Bottom
0, -1, t - 1 / t,
-1, -1, -1 / t,
1, -1, -1 / t
];
var indices = [
0, 1, 2,
3, 4, 5,
6, 7, 8,
9, 10, 11
];
for (i = 0; i < 4; i++) {
textureCoords.push(
0.0, 0.0,
0.5, 1.0,
1.0, 0.0
);
}
options = options || {};
while (--detail) GeometryHelper.subdivide(indices, vertices, textureCoords);
normals = GeometryHelper.computeNormals(vertices, indices);
options.buffers = [
{
name: 'a_pos',
data: vertices
},
{
name: 'a_texCoord',
data: textureCoords,
size: 2
},
{
name: 'a_normals',
data: normals
},
{
name: 'indices',
data: indices,
size: 1
}
];
super(options);
}
}
export { Tetrahedron };
| talves/famous-engine | src/webgl-geometries/primitives/Tetrahedron.js | JavaScript | mit | 2,960 |
/*
* Copyright 2016 Christoph Brill <[email protected]>
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using libldt3.attributes;
using libldt3.model.enums;
using libldt3.model.regel;
using libldt3.model.regel.kontext;
using libldt3.model.saetze;
using NodaTime;
namespace libldt3
{
/**
* Simple, reflection and annotation based reader for LDT 3.0.
*
* @author Christoph Brill <[email protected]>
*/
public class LdtReader
{
readonly IDictionary<Type, Regel> regelCache = new Dictionary<Type, Regel>();
readonly LdtConstants.Mode mode;
public LdtReader(LdtConstants.Mode mode)
{
this.mode = mode;
}
/**
* Read the LDT found on a given path.
*
* @param path
* the path of the LDT file (any format handled by NIO
* {@link Path})
* @return the list of Satz elements found in the LDT file
* @throws IOException
* thrown if reading the file failed
*/
public IList<Satz> Read(string path)
{
using (var f = File.Open(path, FileMode.Open))
{
return Read(f);
}
}
/**
* Read the LDT found on a given path.
*
* @param path
* the path of the LDT file
* @return the list of Satz elements found in the LDT file
* @throws IOException
* thrown if reading the file failed
*/
public IList<Satz> Read(FileStream path)
{
var stream = new StreamReader(path, Encoding.GetEncoding("ISO-8859-1"));
return Read(stream);
}
/**
* Read the LDT from a given string stream.
*
* @param stream
* the LDT lines as string stream
* @return the list of Satz elements found in the LDT file
*/
public IList<Satz> Read(StreamReader stream)
{
Stack<object> stack = new Stack<object>();
IList<Satz> data = new List<Satz>();
string line;
int integer = 0;
while ((line = stream.ReadLine()) != null)
{
HandleInput(line, stack, data, integer++);
}
return data;
}
void HandleInput(string line, Stack<object> stack, IList<Satz> data, int lineNo)
{
Trace.TraceInformation("Reading line {0}", line);
// Check if the line meets the minimum requirements (3 digits for
// length, 4 digits for the identifier)
if (line.Length < 7)
{
if (mode == LdtConstants.Mode.STRICT)
{
throw new ArgumentException("Line '" + line + "' (" + lineNo + ") was less than 7 characters, aborting");
}
else
{
Trace.TraceInformation("Line '{0}' ({1}) was less than 7 characters, continuing anyway", line, lineNo);
}
}
// Read the length and check whether it had the correct length
int length = int.Parse(line.Substring(0, 3));
if (length != line.Length + 2)
{
if (mode == LdtConstants.Mode.STRICT)
{
throw new ArgumentException(
"Line '" + line + "' (" + lineNo + ") should have length " + (line.Length + 2) + ", but was " + length);
}
else
{
Trace.TraceInformation("Line '{0}' ({1}) should have length {2}, but was {3}. Ignoring specified length", line, lineNo,
(line.Length + 2), length);
length = line.Length + 2;
}
}
// Read identifier and payload
string identifier = line.Substring(3, 7 - 3);
string payload = line.Substring(7, length - 2 - 7);
switch (identifier)
{
case "8000":
{
// Start: Satz
AssureLength(line, length, 13);
if (stack.Count > 0)
{
if (mode == LdtConstants.Mode.STRICT)
{
throw new InvalidOperationException(
"Stack must be empty when starting a new Satz, but was " + stack.Count + " long");
}
else
{
Trace.TraceInformation("Stack must be empty when starting a new Satz, but was {0}. Clearing and continuing",
stack);
stack.Clear();
}
}
// Extract Satzart from payload and create Satz matching it
Satzart satzart = GetSatzart(payload);
switch (satzart)
{
case Satzart.Befund:
stack.Push(new Befund());
break;
case Satzart.Auftrag:
stack.Push(new Auftrag());
break;
case Satzart.LaborDatenpaketHeader:
stack.Push(new LaborDatenpaketHeader());
break;
case Satzart.LaborDatenpaketAbschluss:
stack.Push(new LaborDatenpaketAbschluss());
break;
case Satzart.PraxisDatenpaketHeader:
stack.Push(new PraxisDatenpaketHeader());
break;
case Satzart.PraxisDatenpaketAbschluss:
stack.Push(new PraxisDatenpaketAbschluss());
break;
default:
throw new ArgumentException("Unsupported Satzart '" + payload + "' found");
}
break;
}
case "8001":
{
// End: Satz
AssureLength(line, length, 13);
object o = stack.Pop();
Datenpaket datenpaket = o.GetType().GetCustomAttribute<Datenpaket>();
if (datenpaket != null)
{
EvaluateContextRules(o, datenpaket.Kontextregeln);
}
if (stack.Count == 0)
{
data.Add((Satz)o);
}
break;
}
case "8002":
{
// Start: Objekt
AssureLength(line, length, 17);
object currentObject1 = PeekCurrentObject(stack);
Objekt annotation1 = currentObject1.GetType().GetCustomAttribute<Objekt>();
if (annotation1 != null)
{
if (annotation1.Value.Length == 0)
{
// If annotation is empty, the parent object would actually
// be the one to deal with
}
else
{
// Match found, everything is fine
if (payload.Equals("Obj_" + annotation1.Value))
{
break;
}
// No match found, abort or inform the developer
if (mode == LdtConstants.Mode.STRICT)
{
throw new ArgumentException(
"In line '" + line + "' (" + lineNo + ") expected Obj_" + annotation1.Value + ", got " + payload);
}
else
{
Trace.TraceError("In line {0} ({1}) expected Obj_{2}, got {3}", line, lineNo, annotation1.Value, payload);
break;
}
}
}
if (mode == LdtConstants.Mode.STRICT)
{
throw new ArgumentException("Line '" + line + "' (" + lineNo + ") started an unexpeted object, stack was " + stack.ToArray());
}
else
{
Trace.TraceWarning("Line '{0}' ({1}) started an unexpeted object, stack was {2}", line, lineNo, stack);
}
break;
}
case "8003":
{
// End: Objekt
AssureLength(line, length, 17);
object o;
Objekt annotation1;
do
{
o = stack.Pop();
annotation1 = o.GetType().GetCustomAttribute<Objekt>();
if (annotation1 != null)
{
if (annotation1.Value.Length != 0 && !("Obj_" + annotation1.Value).Equals(payload)) {
Trace.TraceWarning("Line: {0} ({1}), annotation {2}, payload {3}", line, lineNo, annotation1.Value, payload);
}
EvaluateContextRules(o, annotation1.Kontextregeln);
}
} while (annotation1 != null && annotation1.Value.Length == 0);
if (stack.Count == 0)
{
data.Add((Satz)o);
}
break;
}
default:
// Any line not starting or completing a Satz or Objekt
object currentObject = PeekCurrentObject(stack);
if (currentObject == null)
{
throw new InvalidOperationException("No object when appplying line " + line + " (" + lineNo + ")");
}
// XXX iterating the fields could be replaced by a map to be a bit
// faster when dealing with the same class
foreach (FieldInfo info in currentObject.GetType().GetFields())
{
// Check if we found a Feld annotation, if not this is not our
// field
Feld annotation2 = info.GetCustomAttribute<Feld>();
if (annotation2 == null)
{
continue;
}
// Check if the annotation matches the identifier, if not, this
// is not our field
if (!identifier.Equals(annotation2.Value))
{
continue;
}
try
{
// Check if there is currently a value set
object o = info.GetValue(currentObject);
if (o != null && GetGenericList(info.FieldType) == null)
{
if (mode == LdtConstants.Mode.STRICT)
{
throw new InvalidOperationException(
"Line '" + line + "' (" + lineNo + ") would overwrite existing value " + o + " of " + currentObject + "." + info.Name);
}
else
{
Trace.TraceWarning("Line '{0}' ({1}) would overwrite existing value {2} in object {3}.{4}", line, lineNo, o, currentObject, info);
}
}
ValidateFieldPayload(info, payload);
// Convert the value to its target type ...
object value = ConvertType(info, info.FieldType, payload, stack);
// .. and set the value on the target object
info.SetValue(currentObject, value);
}
catch (Exception e)
{
if (mode == LdtConstants.Mode.STRICT)
{
throw new InvalidOperationException(e.Message, e);
}
else
{
Trace.TraceError(e.Message);
}
}
// We are done with this line
return;
}
// No field with a matching Feld annotation found, check if we are
// an Objekt with an empty value (anonymous object), if so try our
// parent
Objekt annotation = currentObject.GetType().GetCustomAttribute<Objekt>();
if (annotation != null && annotation.Value.Length == 0)
{
stack.Pop();
HandleInput(line, stack, data, lineNo);
return;
}
// Neither we nor our parent could deal with this line
if (mode == LdtConstants.Mode.STRICT)
{
throw new ArgumentException("Failed reading line " + line + " (" + lineNo + "), current stack: " + string.Join(" ", stack.ToArray()));
}
else
{
Trace.TraceWarning("Failed reading line {0} ({1}), current stack: {2}, skipping line", line, lineNo, string.Join(" ", stack.ToArray()));
}
break;
}
}
private void EvaluateContextRules(object o, Type[] kontextRegeln)
{
foreach (Type kontextregel in kontextRegeln)
{
try
{
if (!((Kontextregel)Activator.CreateInstance(kontextregel)).IsValid(o))
{
if (mode == LdtConstants.Mode.STRICT)
{
throw new ArgumentException("Context rule " + kontextregel.Name + " failed on object " + o);
}
else
{
Trace.TraceWarning("Context rule {} failed on object {}", kontextregel.Name, o);
}
}
}
catch (Exception e)
{
if (mode == LdtConstants.Mode.STRICT)
{
throw new ArgumentException("Context rule " + kontextregel.Name + " failed on object " + o, e);
}
else
{
Trace.TraceWarning("Context rule {} failed on object {}", kontextregel.Name, o, e);
}
}
}
}
void ValidateFieldPayload(FieldInfo field, string payload)
{
foreach (Regelsatz regelsatz in field.GetCustomAttributes<Regelsatz>())
{
if (regelsatz.Laenge >= 0)
{
if (payload.Length != regelsatz.Laenge)
{
ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not match expected length "
+ regelsatz.Laenge + ", was " + payload.Length);
}
}
if (regelsatz.MinLaenge >= 0)
{
if (payload.Length < regelsatz.MinLaenge)
{
ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not match expected minimum length "
+ regelsatz.MinLaenge + ", was " + payload.Length);
}
}
if (regelsatz.MaxLaenge >= 0)
{
if (payload.Length > regelsatz.MaxLaenge)
{
ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not match expected maximum length "
+ regelsatz.MaxLaenge + ", was " + payload.Length);
}
}
// No specific rules given, likely only length checks
if (regelsatz.Value.Length == 0)
{
continue;
}
bool found = false;
foreach (Type regel in regelsatz.Value)
{
if (GetRegel(regel).IsValid(payload))
{
found = true;
break;
}
}
if (!found)
{
ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not confirm to any rule of "
+ ToString(regelsatz.Value));
}
}
}
void ValidationFailed(string message)
{
if (mode == LdtConstants.Mode.STRICT)
{
throw new InvalidOperationException(message);
}
else
{
Trace.TraceWarning(message);
}
}
string ToString(Type[] regeln)
{
StringBuilder buffer = new StringBuilder();
foreach (Type regel in regeln)
{
if (buffer.Length > 0)
{
buffer.Append(" or ");
}
buffer.Append(regel.Name);
}
return buffer.ToString();
}
Regel GetRegel(Type regel)
{
Regel instance;
regelCache.TryGetValue(regel, out instance);
if (instance == null)
{
instance = (Regel)Activator.CreateInstance(regel);
regelCache[regel] = instance;
}
return instance;
}
/**
* Extract the Satzart form a given payload
*
* @param payload
* the payload of the line
* @return the Satzart or {@code null}
*/
Satzart GetSatzart(string payload)
{
foreach (Satzart sa in Enum.GetValues(typeof(Satzart)).Cast<Satzart>())
{
if (sa.GetCode().Equals(payload))
{
return sa;
}
}
throw new ArgumentException("Unsupported Satzart '" + payload + "' found");
}
/**
* Peek the current objekt from the stack, if any.
*
* @param stack
* the stack to peek the object from
* @return the current top level element of the stack or {@code null}
*/
static object PeekCurrentObject(Stack<object> stack)
{
if (stack.Count == 0)
{
return null;
}
return stack.Peek();
}
/**
* Check if the line matches the expected length.
*
* @param line
* the line to check
* @param length
* the actual length
* @param target
* the length specified by the line
*/
void AssureLength(string line, int length, int target)
{
if (length != target)
{
if (mode == LdtConstants.Mode.STRICT)
{
throw new ArgumentException(
"Line '" + line + "' must have length " + target + ", was " + length);
}
else
{
Trace.TraceInformation("Line '{0}' must have length {1}, was {2}", line, target, length);
}
}
}
/**
* Convert the string payload into a target class. (Note: There are
* certainly better options out there but this one is simple enough for our
* needs.)
*/
static object ConvertType(FieldInfo field, Type type, string payload, Stack<object> stack)
{
if (type == typeof(string))
{
return payload;
}
if (type == typeof(float) || type == typeof(float?))
{
return float.Parse(payload);
}
if (type == typeof(int) || type == typeof(int?))
{
return int.Parse(payload);
}
if (type == typeof(long) || type == typeof(long?))
{
return long.Parse(payload);
}
if (type == typeof(bool) || type == typeof(bool?))
{
return "1".Equals(payload);
}
if (type == typeof(LocalDate?))
{
return LdtConstants.FORMAT_DATE.Parse(payload).Value;
}
if (type == typeof(LocalTime?))
{
return LdtConstants.FORMAT_TIME.Parse(payload).Value;
}
if (IsNullableEnum(type))
{
Type enumType = Nullable.GetUnderlyingType(type);
MethodInfo method = Type.GetType(enumType.FullName + "Extensions").GetMethod("GetCode");
if (method != null)
{
foreach (object e in Enum.GetValues(enumType))
{
string code = (string)method.Invoke(e, new object[] { e });
if (payload.Equals(code))
{
return e;
}
}
return null;
}
}
if (type.IsEnum)
{
MethodInfo method = Type.GetType(type.FullName + "Extensions").GetMethod("GetCode");
if (method != null)
{
foreach (object e in Enum.GetValues(type))
{
string code = (string)method.Invoke(e, new object[] { e });
if (payload.Equals(code))
{
return e;
}
}
return null;
}
}
Type genericType = GetGenericList(type);
if (genericType != null)
{
object currentObject = PeekCurrentObject(stack);
var o = (System.Collections.IList) field.GetValue(currentObject);
if (o == null)
{
o = (System.Collections.IList) Activator.CreateInstance(typeof(List<>).MakeGenericType(genericType.GetGenericArguments()[0]));
field.SetValue(currentObject, o);
}
o.Add(ConvertType(field, type.GenericTypeArguments[0], payload, stack));
return o;
}
if (type.GetCustomAttribute<Objekt>() != null)
{
object instance = Activator.CreateInstance(type);
stack.Push(instance);
FieldInfo declaredField = type.GetField("Value");
if (declaredField != null)
{
declaredField.SetValue(instance, ConvertType(declaredField, declaredField.FieldType, payload, stack));
}
return instance;
}
throw new ArgumentException("Don't know how to handle type " + type);
}
static bool IsNullableEnum(Type t)
{
Type u = Nullable.GetUnderlyingType(t);
return (u != null) && u.IsEnum;
}
static Type GetGenericList(Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>))
{
return type;
}
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList<>))
{
return interfaceType;
}
}
return null;
}
}
}
| egore/libldt3-cs | libldt3/LdtReader.cs | C# | mit | 18,803 |
var map;
var bounds;
var markers = {};
var cluster_polygons = {};
var zoomTimeout;
var cluster_center_overlay;
var white_overlay;
var overlay_opacity = 50;
var OPACITY_MAX_PIXELS = 57;
var active_cluster_poly;
var marker_image;
var center_marker;
var cluster_center_marker_icon;
function createMap() {
bounds = new google.maps.LatLngBounds ();
markers;
cluster_polygons;
marker_image = {
url: STATIC_URL + "images/red_marker.png",
anchor: new google.maps.Point(4,4)};
center_marker = {
url: STATIC_URL + "images/black_marker.png",
size: new google.maps.Size(20, 20),
anchor: new google.maps.Point(10,10)};
cluster_center_marker_icon = {
url: STATIC_URL + "images/transparent_marker_20_20.gif",
size: new google.maps.Size(20, 20),
anchor: new google.maps.Point(10,10)};
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true
};
map = new google.maps.Map(document.getElementById("canvas"),
mapOptions);
// google.maps.event.addListener(map, 'bounds_changed', function(e) {
// if (zoomTimeout) {
// window.clearTimeout(zoomTimeout);
// }
// zoomTimeout = window.setTimeout(query_points_for_view, 5000);
// })
$.getScript(STATIC_URL + "script/CustomTileOverlay.js", function() {
white_overlay = new CustomTileOverlay(map, overlay_opacity);
white_overlay.show();
google.maps.event.addListener(map, 'tilesloaded', function () {
white_overlay.deleteHiddenTiles(map.getZoom());
});
createOpacityControl(map, overlay_opacity);
});
}
// Thanks https://github.com/gavinharriss/google-maps-v3-opacity-control/!
function createOpacityControl(map, opacity) {
var sliderImageUrl = STATIC_URL + "images/opacity-slider3d14.png";
// Create main div to hold the control.
var opacityDiv = document.createElement('DIV');
opacityDiv.setAttribute("style", "margin:5px;overflow-x:hidden;overflow-y:hidden;background:url(" + sliderImageUrl + ") no-repeat;width:71px;height:21px;cursor:pointer;");
// Create knob
var opacityKnobDiv = document.createElement('DIV');
opacityKnobDiv.setAttribute("style", "padding:0;margin:0;overflow-x:hidden;overflow-y:hidden;background:url(" + sliderImageUrl + ") no-repeat -71px 0;width:14px;height:21px;");
opacityDiv.appendChild(opacityKnobDiv);
var opacityCtrlKnob = new ExtDraggableObject(opacityKnobDiv, {
restrictY: true,
container: opacityDiv
});
google.maps.event.addListener(opacityCtrlKnob, "dragend", function () {
set_overlay_opacity(opacityCtrlKnob.valueX());
});
// google.maps.event.addDomListener(opacityDiv, "click", function (e) {
// var left = findPosLeft(this);
// var x = e.pageX - left - 5; // - 5 as we're using a margin of 5px on the div
// opacityCtrlKnob.setValueX(x);
// set_overlay_opacity(x);
// });
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(opacityDiv);
// Set initial value
var initialValue = OPACITY_MAX_PIXELS / (100 / opacity);
opacityCtrlKnob.setValueX(initialValue);
set_overlay_opacity(initialValue);
}
// Thanks https://github.com/gavinharriss/google-maps-v3-opacity-control/!
function findPosLeft(obj) {
var curleft = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
} while (obj = obj.offsetParent);
return curleft;
}
return undefined;
}
function set_overlay_opacity(value) {
overlay_opacity = (100.0 / OPACITY_MAX_PIXELS) * value;
if (value < 0) value = 0;
if (value == 0) {
if (white_overlay.visible == true) {
white_overlay.hide();
}
}
else {
white_overlay.setOpacity(overlay_opacity);
if (white_overlay.visible == false) {
white_overlay.show();
}
}
}
function query_points_for_view() {
var bounds = map.getBounds();
var x0 = bounds.getNorthEast().lng();
var y0 = bounds.getNorthEast().lat();
var x1 = bounds.getSouthWest().lng();
var y1 = bounds.getSouthWest().lat();
// Remove stuff off screen
var to_remove = [];
// What to remove
$.each(markers, function(idx, marker){
if (!bounds.contains(marker.getPosition()))
{
marker.setMap(null);
to_remove.push(idx);
}
});
$.each(to_remove, function(i, idx){
delete markers[idx];
})
// $.getJSON("/rest/photos_box_contains?x0=" + x0 + "&y0=" + y0 + "&x1=" + x1 + "&y1=" + y1, function(data){
// console.log("got " + data.features.length);
// add_photo_to_map(data.features, 0, 128);
// })
$.getJSON("/rest/clusters_box_contains?x0=" + x0 + "&y0=" + y0 + "&x1=" + x1 + "&y1=" + y1, function(data){
console.log("got " + data.features.length);
add_cluster_to_map(data.features, 0);
})
}
function create_photo_marker(photo_info) {
var loc = new google.maps.LatLng(photo_info.geometry.coordinates[1], photo_info.geometry.coordinates[0]);
var marker = new google.maps.Marker({
map: map,
position: loc,
icon: marker_image
});
var infowindow = new google.maps.InfoWindow({
content: "<div style='width:200px;height:200px'><a href='" + photo_info.properties.photo_url + "'><img src='" + photo_info.properties.photo_thumb_url + "' style='max-width:100%;max-height:100%;'/></div>"
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
markers[photo_info.id] = marker;
}
function add_photo_to_map(photos, i, step) {
for (var j = 0; j < step; j++) {
if (i + j >= photos.length)
{
break;
}
var photo_info = photos[i + j];
if (!markers[photo_info.id]) {
create_photo_marker(photo_info);
}
}
i += step;
if (i < photos.length) {
window.setTimeout(function(){add_photo_to_map(photos, i, step);}, 1);
}
}
function add_clustering_run_to_map(data){
$.each(cluster_polygons, function(idx, poly){
poly.setMap(null);
});
bounds = new google.maps.LatLngBounds ();
cluster_polygons = [];
cluster_center_overlay = new google.maps.OverlayView();
cluster_center_overlay.onAdd = function() {
var layer = d3.select(this.getPanes().overlayMouseTarget).append("div")
.attr("class", "cluster_center");
var projection = this.getProjection();
var max_size = 300;
var max_size_per_2 = max_size / 2;
var marker = layer.selectAll("svg")
.data(data.features)
.each(transform)
.enter().append("svg:svg")
.each(transform)
.each(tie_to_g_marker)
.attr("class", "marker")
.style("z-index", function(cluster) {
return set_default_z_index(cluster);
})
.append("svg:g");
function set_default_z_index(cluster) {
return parseInt(cluster.properties.point_count_relative * 1000 + 100000);
}
marker.append("svg:polygon")
.attr("points", function(cluster){
var out = [];
var last_phase = 0.0;
var last_length = 1.0 / 12.0 * (max_size_per_2 - 1);
var min_l = 0.0;//0.3 * max_size_per_2 * (Math.sqrt(cluster.properties.point_count_relative) * 0.7 + 0.3);
for (var j = 1.0; j <= 12.0; j += 1.0){
var phase = j / 12.0 * 2 * Math.PI;
out.push([max_size_per_2 + Math.sin(last_phase) * min_l, max_size_per_2 - Math.cos(last_phase) * min_l]);
out.push([max_size_per_2 + Math.sin(phase) * min_l, max_size_per_2 - Math.cos(phase) * min_l]);
var second_poly = [];
var l = ( (cluster.properties["points_month_" + parseInt(j) + "_relative"]) * 0.9 + 0.1) *
max_size_per_2 * (cluster.properties.point_count_relative * 0.8 + 0.2);
second_poly.push([max_size_per_2 + Math.sin(last_phase) * min_l, max_size_per_2 - Math.cos(last_phase) * min_l]);
second_poly.push([max_size_per_2 + Math.sin(last_phase) * l, max_size_per_2 - Math.cos(last_phase) * l]);
second_poly.push([max_size_per_2 + Math.sin(phase) * l, max_size_per_2 - Math.cos(phase) * l]);
second_poly.push([max_size_per_2 + Math.sin(phase) * min_l, max_size_per_2 - Math.cos(phase) * min_l]);
second_poly.push(second_poly[0]);
last_phase = phase;
d3.select(this.parentElement)
.append("svg:polygon")
.attr("points", second_poly.join(" "))
.attr("class", "month_" + parseInt(j));
}
return out.join(" ");
})
.attr("class", "cluster_center_marker");
function transform(cluster) {
var coords = cluster.geometry.geometries[0].coordinates;
var d = new google.maps.LatLng(coords[1], coords[0]);
d = projection.fromLatLngToDivPixel(d);
return d3.select(this)
.style("left", (d.x - max_size_per_2) + "px")
.style("top", (d.y - max_size_per_2) + "px");
}
function tie_to_g_marker(cluster){
var coords = cluster.geometry.geometries[0].coordinates;
var d = new google.maps.LatLng(coords[1], coords[0]);
var marker = new google.maps.Marker({
map: map,
position: d,
icon: cluster_center_marker_icon,
zIndex: set_default_z_index(d3.select(this).data()[0])
});
var cluster_center = this;
google.maps.event.addListener(marker, 'mouseover', function() {
d3_cluster_center = d3.select(cluster_center);
d3_cluster_center
.style("transform", "scale(3.0)")
.style("animation-name", "cluster_center_highlight")
.style("z-index", 1001001);
});
google.maps.event.addListener(marker, 'click', function() {
if (active_cluster_poly) {
active_cluster_poly.setMap(null);
}
sidebar_display_cluster_info(d3_cluster_center.data()[0]["id"]);
d3_cluster_center = d3.select(cluster_center);
poly_bounds = new google.maps.LatLngBounds ();
// Define the LatLng coordinates for the polygon's path.
var coords = d3_cluster_center.data()[0].geometry.geometries[1].coordinates[0];
var g_coords = [];
for (j in coords)
{
var c = coords[j];
var co = new google.maps.LatLng(c[1], c[0]);
g_coords.push(co);
poly_bounds.extend(co);
}
// Construct the polygon.
var poly = new google.maps.Polygon({
paths: g_coords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
poly.setMap(map);
active_cluster_poly = poly;
map.fitBounds(poly_bounds);
});
google.maps.event.addListener(marker, 'mouseout', function() {
d3.select(cluster_center)
.style("transform", "scale(1.0)")
.style("animation-name", "cluster_center_unhighlight")
.style("z-index", function(cluster) {
return set_default_z_index(cluster);
});
});
bounds.extend(d);
}
map.fitBounds(bounds);
cluster_center_overlay.draw = function() {
var projection = this.getProjection();
layer.selectAll("svg")
.data(data.features)
.each(transform);
};
};
cluster_center_overlay.setMap(map);
}
function finalize_clustering_run_to_map(clusters){
console.log("finalizing");
map.fitBounds(bounds);
}
function show_clusters_lame() {
var $form = $("#clustering_run_get_form"), url = $form.attr("action");
// Fire some AJAX!
$.ajax({
type: "GET",
url: url,
dataType: "json",
data: {id: $("#clustering_run_get_form_select").val()}
})
.done(function(msg){
add_cluster_to_map(msg.features, 0);
});
}
function show_cluster_centers_lame() {
var $form = $("#clustering_run_get_form"), url = $form.attr("action");
// Fire some AJAX!
$.ajax({
type: "GET",
url: url,
dataType: "json",
data: {id: $("#clustering_run_get_form_select").val()}
})
.done(function(msg){
add_cluster_center_to_map(msg.features, 0);
});
}
function add_cluster_to_map(clusters, i){
// Define the LatLng coordinates for the polygon's path.
var cluster = clusters[i];
var coords = [];
var points = cluster.geometry.geometries[1].coordinates[0];
for (var j = 0; j < points.length; j += 1)
{
coords.push(new google.maps.LatLng(
points[j][1], points[j][0]));
}
var center = cluster.geometry.geometries[0].coordinates;
var loc = new google.maps.LatLng(
center[1],
center[0])
bounds.extend(loc);
// Construct the polygon.
var poly = new google.maps.Polygon({
paths: coords,
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 1,
fillColor: '#FF0000',
fillOpacity: 0.1
});
poly.setMap(map);
// cluster_polygons.push(poly);
if (i < clusters.length - 1) {
window.setTimeout(function(){add_cluster_to_map(clusters, i + 1);}, 1);
} else {
finalize_clustering_run_to_map(clusters);
}
}
function add_cluster_center_to_map(clusters, i){
// Define the LatLng coordinates for the polygon's path.
var cluster = clusters[i];
var coords = [];
var center = cluster.geometry.geometries[0].coordinates;
var loc = new google.maps.LatLng(
center[1],
center[0])
bounds.extend(loc);
var marker = new google.maps.Marker({
map: map,
position: loc
});
if (i < clusters.length - 1) {
window.setTimeout(function(){add_cluster_center_to_map(clusters, i + 1);}, 1);
} else {
finalize_clustering_run_to_map(clusters);
}
}
function show_all() {
map.fitBounds(bounds);
} | joonamo/photoplaces | photoplaces/static/script/map.js | JavaScript | mit | 15,053 |
#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "base58.h"
#include <QMessageBox>
#include <QLocale>
#include <QTextDocument>
#include <QScrollBar>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
QList<SendCoinsRecipient> recipients;
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
#if QT_VERSION < 0x050000
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));
#else
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address));
#endif
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
QCoreApplication::instance()->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handleURI(const QString &uri)
{
SendCoinsRecipient rv;
// URI has to be valid
if (GUIUtil::parseBitcoinURI(uri, &rv))
{
CBitcoinAddress address(rv.address.toStdString());
if (!address.IsValid())
return false;
pasteEntry(rv);
return true;
}
return false;
}
void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(stake);
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(!model || !model->getOptionsModel())
return;
int unit = model->getOptionsModel()->getDisplayUnit();
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
}
void SendCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update labelBalance with the current balance and the current unit
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));
}
}
| devxxxcoin/xxxcoin | src/qt/sendcoinsdialog.cpp | C++ | mit | 9,070 |
{!!
Form::select(
'routes[]',
$allRoutes,
(isset($routes) ? array_keys($routes) : []),
array(
'class' => 'form-control select2',
'placeholder' => 'Enter Routes',
'multiple' => true
)
)
!!}
| stevebauman/maintenance | resources/views/select/routes.blade.php | PHP | mit | 273 |
<?php
namespace Aquatic;
use Aquatic\FedEx\Contract\Address;
use Aquatic\FedEx\Contract\Shipment;
use Aquatic\FedEx\Response\Contract as ResponseContract;
use Aquatic\FedEx\Request\ValidateAddress as ValidateAddressRequest;
use Aquatic\FedEx\Response\ValidateAddress as ValidateAddressResponse;
use Aquatic\FedEx\Request\Shipment\Track as TrackShipmentRequest;
use Aquatic\FedEx\Response\Shipment\Track as TrackShipmentResponse;
use Aquatic\FedEx\Request\Shipment\CustomsAndDuties as CustomsAndDutiesRequest;
use Aquatic\FedEx\Response\Shipment\CustomsAndDuties as CustomsAndDutiesResponse;
// Facade for FedEx requests
class FedEx
{
public static function trackShipment(int $tracking_number): ResponseContract
{
return (new TrackShipmentRequest($tracking_number))
->setCredentials(getenv('FEDEX_KEY'), getenv('FEDEX_PASSWORD'), getenv('FEDEX_ACCOUNT_NUMBER'), getenv('FEDEX_METER_NUMBER'))
->send(new TrackShipmentResponse);
}
public static function customsAndDuties(Shipment $shipment, Address $shipper)
{
return (new CustomsAndDutiesRequest($shipment, $shipper))
->setCredentials(getenv('FEDEX_KEY'), getenv('FEDEX_PASSWORD'), getenv('FEDEX_ACCOUNT_NUMBER'), getenv('FEDEX_METER_NUMBER'))
->send(new CustomsAndDutiesResponse($shipment->getItems()));
}
public static function validateAddress(Address $address)
{
return (new ValidateAddressRequest($address))
->setCredentials(getenv('FEDEX_KEY'), getenv('FEDEX_PASSWORD'), getenv('FEDEX_ACCOUNT_NUMBER'), getenv('FEDEX_METER_NUMBER'))
->send(new ValidateAddressResponse);
}
} | aquaticpond/fedex | src/Aquatic/FedEx.php | PHP | mit | 1,667 |
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { MultiSelect } from '../../src'
class MultiSelectWithStringValues extends Component {
constructor(props) {
super(props)
this.state = {
value: []
}
}
handleChange = (event) => {
const { valueKey } = this.props
this.setState({ value: event.value.map((val) => val[valueKey]) })
}
render() {
const { value } = this.state
return <MultiSelect {...this.props} onChange={this.handleChange} value={value} />
}
}
MultiSelectWithStringValues.propTypes = {
valueKey: PropTypes.string.isRequired
}
export default MultiSelectWithStringValues
| sthomas1618/react-crane | stories/components/MultiSelectWithStringValues.js | JavaScript | mit | 667 |
/* util/operators.hpp
*
* Copyright (C) 2007 Antonio Di Monaco
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#ifndef __OPERATORS_HPP__
#define __OPERATORS_HPP__
template< typename T >
struct EqualComparable
{
friend bool operator!=(const T &a,const T &b) { return !(a == b); }
};
template< typename T >
struct Comparable : public EqualComparable< T >
{
friend bool operator<=(const T &a, const T &b) { return (a < b) || (a == b); }
friend bool operator>(const T &a,const T &b) { return !(a <= b); }
friend bool operator>=(const T &a,const T &b) { return !(a < b); }
};
#endif
| becrux/xfspp | util/operators.hpp | C++ | mit | 700 |
"""
[2015-07-13] Challenge #223 [Easy] Garland words
https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj/20150713_challenge_223_easy_garland_words/
# Description
A [_garland word_](http://blog.vivekhaldar.com/post/89763722591/garland-words) is one that starts and ends with the
same N letters in the same order, for some N greater than 0, but less than the length of the word. I'll call the
maximum N for which this works the garland word's _degree_. For instance, "onion" is a garland word of degree 2,
because its first 2 letters "on" are the same as its last 2 letters. The name "garland word" comes from the fact that
you can make chains of the word in this manner:
onionionionionionionionionionion...
Today's challenge is to write a function `garland` that, given a lowercase word, returns the degree of the word if it's
a garland word, and 0 otherwise.
# Examples
garland("programmer") -> 0
garland("ceramic") -> 1
garland("onion") -> 2
garland("alfalfa") -> 4
# Optional challenges
1. Given a garland word, print out the chain using that word, as with "onion" above. You can make it as long or short
as you like, even infinite.
1. Find the largest degree of any garland word in the [enable1 English word
list](https://code.google.com/p/dotnetperls-controls/downloads/detail?name=enable1.txt).
1. Find a word list for some other language, and see if you can find a language with a garland word with a higher
degree.
*Thanks to /u/skeeto for submitting this challenge on /r/dailyprogrammer_ideas!*
"""
def main():
pass
if __name__ == "__main__":
main()
| DayGitH/Python-Challenges | DailyProgrammer/DP20150713A.py | Python | mit | 1,597 |
/**
*
* Licensed Property to China UnionPay Co., Ltd.
*
* (C) Copyright of China UnionPay Co., Ltd. 2010
* All Rights Reserved.
*
*
* Modification History:
* =============================================================================
* Author Date Description
* ------------ ---------- ---------------------------------------------------
* xshu 2014-05-28 MPI插件包常量定义
* =============================================================================
*/
package com.boyuanitsm.pay.unionpay.config;
public class SDKConstants {
public final static String COLUMN_DEFAULT = "-";
public final static String KEY_DELIMITER = "#";
/** memeber variable: blank. */
public static final String BLANK = "";
/** member variabel: space. */
public static final String SPACE = " ";
/** memeber variable: unline. */
public static final String UNLINE = "_";
/** memeber varibale: star. */
public static final String STAR = "*";
/** memeber variable: line. */
public static final String LINE = "-";
/** memeber variable: add. */
public static final String ADD = "+";
/** memeber variable: colon. */
public final static String COLON = "|";
/** memeber variable: point. */
public final static String POINT = ".";
/** memeber variable: comma. */
public final static String COMMA = ",";
/** memeber variable: slash. */
public final static String SLASH = "/";
/** memeber variable: div. */
public final static String DIV = "/";
/** memeber variable: left . */
public final static String LB = "(";
/** memeber variable: right. */
public final static String RB = ")";
/** memeber variable: rmb. */
public final static String CUR_RMB = "RMB";
/** memeber variable: .page size */
public static final int PAGE_SIZE = 10;
/** memeber variable: String ONE. */
public static final String ONE = "1";
/** memeber variable: String ZERO. */
public static final String ZERO = "0";
/** memeber variable: number six. */
public static final int NUM_SIX = 6;
/** memeber variable: equal mark. */
public static final String EQUAL = "=";
/** memeber variable: operation ne. */
public static final String NE = "!=";
/** memeber variable: operation le. */
public static final String LE = "<=";
/** memeber variable: operation ge. */
public static final String GE = ">=";
/** memeber variable: operation lt. */
public static final String LT = "<";
/** memeber variable: operation gt. */
public static final String GT = ">";
/** memeber variable: list separator. */
public static final String SEP = "./";
/** memeber variable: Y. */
public static final String Y = "Y";
/** memeber variable: AMPERSAND. */
public static final String AMPERSAND = "&";
/** memeber variable: SQL_LIKE_TAG. */
public static final String SQL_LIKE_TAG = "%";
/** memeber variable: @. */
public static final String MAIL = "@";
/** memeber variable: number zero. */
public static final int NZERO = 0;
public static final String LEFT_BRACE = "{";
public static final String RIGHT_BRACE = "}";
/** memeber variable: string true. */
public static final String TRUE_STRING = "true";
/** memeber variable: string false. */
public static final String FALSE_STRING = "false";
/** memeber variable: forward success. */
public static final String SUCCESS = "success";
/** memeber variable: forward fail. */
public static final String FAIL = "fail";
/** memeber variable: global forward success. */
public static final String GLOBAL_SUCCESS = "$success";
/** memeber variable: global forward fail. */
public static final String GLOBAL_FAIL = "$fail";
public static final String UTF_8_ENCODING = "UTF-8";
public static final String GBK_ENCODING = "GBK";
public static final String CONTENT_TYPE = "Content-type";
public static final String APP_XML_TYPE = "application/xml;charset=utf-8";
public static final String APP_FORM_TYPE = "application/x-www-form-urlencoded;charset=";
/******************************************** 5.0报文接口定义 ********************************************/
/** 版本号. */
public static final String param_version = "version";
/** 证书ID. */
public static final String param_certId = "certId";
/** 签名. */
public static final String param_signature = "signature";
/** 编码方式. */
public static final String param_encoding = "encoding";
/** 交易类型. */
public static final String param_txnType = "txnType";
/** 交易子类. */
public static final String param_txnSubType = "txnSubType";
/** 业务类型. */
public static final String param_bizType = "bizType";
/** 前台通知地址 . */
public static final String param_frontUrl = "frontUrl";
/** 后台通知地址. */
public static final String param_backUrl = "backUrl";
/** 接入类型. */
public static final String param_accessType = "accessType";
/** 收单机构代码. */
public static final String param_acqInsCode = "acqInsCode";
/** 商户类别. */
public static final String param_merCatCode = "merCatCode";
/** 商户类型. */
public static final String param_merType = "merType";
/** 商户代码. */
public static final String param_merId = "merId";
/** 商户名称. */
public static final String param_merName = "merName";
/** 商户简称. */
public static final String param_merAbbr = "merAbbr";
/** 二级商户代码. */
public static final String param_subMerId = "subMerId";
/** 二级商户名称. */
public static final String param_subMerName = "subMerName";
/** 二级商户简称. */
public static final String param_subMerAbbr = "subMerAbbr";
/** Cupsecure 商户代码. */
public static final String param_csMerId = "csMerId";
/** 商户订单号. */
public static final String param_orderId = "orderId";
/** 交易时间. */
public static final String param_txnTime = "txnTime";
/** 发送时间. */
public static final String param_txnSendTime = "txnSendTime";
/** 订单超时时间间隔. */
public static final String param_orderTimeoutInterval = "orderTimeoutInterval";
/** 支付超时时间. */
public static final String param_payTimeoutTime = "payTimeoutTime";
/** 默认支付方式. */
public static final String param_defaultPayType = "defaultPayType";
/** 支持支付方式. */
public static final String param_supPayType = "supPayType";
/** 支付方式. */
public static final String param_payType = "payType";
/** 自定义支付方式. */
public static final String param_customPayType = "customPayType";
/** 物流标识. */
public static final String param_shippingFlag = "shippingFlag";
/** 收货地址-国家. */
public static final String param_shippingCountryCode = "shippingCountryCode";
/** 收货地址-省. */
public static final String param_shippingProvinceCode = "shippingProvinceCode";
/** 收货地址-市. */
public static final String param_shippingCityCode = "shippingCityCode";
/** 收货地址-地区. */
public static final String param_shippingDistrictCode = "shippingDistrictCode";
/** 收货地址-详细. */
public static final String param_shippingStreet = "shippingStreet";
/** 商品总类. */
public static final String param_commodityCategory = "commodityCategory";
/** 商品名称. */
public static final String param_commodityName = "commodityName";
/** 商品URL. */
public static final String param_commodityUrl = "commodityUrl";
/** 商品单价. */
public static final String param_commodityUnitPrice = "commodityUnitPrice";
/** 商品数量. */
public static final String param_commodityQty = "commodityQty";
/** 是否预授权. */
public static final String param_isPreAuth = "isPreAuth";
/** 币种. */
public static final String param_currencyCode = "currencyCode";
/** 账户类型. */
public static final String param_accType = "accType";
/** 账号. */
public static final String param_accNo = "accNo";
/** 支付卡类型. */
public static final String param_payCardType = "payCardType";
/** 发卡机构代码. */
public static final String param_issInsCode = "issInsCode";
/** 持卡人信息. */
public static final String param_customerInfo = "customerInfo";
/** 交易金额. */
public static final String param_txnAmt = "txnAmt";
/** 余额. */
public static final String param_balance = "balance";
/** 地区代码. */
public static final String param_districtCode = "districtCode";
/** 附加地区代码. */
public static final String param_additionalDistrictCode = "additionalDistrictCode";
/** 账单类型. */
public static final String param_billType = "billType";
/** 账单号码. */
public static final String param_billNo = "billNo";
/** 账单月份. */
public static final String param_billMonth = "billMonth";
/** 账单查询要素. */
public static final String param_billQueryInfo = "billQueryInfo";
/** 账单详情. */
public static final String param_billDetailInfo = "billDetailInfo";
/** 账单金额. */
public static final String param_billAmt = "billAmt";
/** 账单金额符号. */
public static final String param_billAmtSign = "billAmtSign";
/** 绑定标识号. */
public static final String param_bindId = "bindId";
/** 风险级别. */
public static final String param_riskLevel = "riskLevel";
/** 绑定信息条数. */
public static final String param_bindInfoQty = "bindInfoQty";
/** 绑定信息集. */
public static final String param_bindInfoList = "bindInfoList";
/** 批次号. */
public static final String param_batchNo = "batchNo";
/** 总笔数. */
public static final String param_totalQty = "totalQty";
/** 总金额. */
public static final String param_totalAmt = "totalAmt";
/** 文件类型. */
public static final String param_fileType = "fileType";
/** 文件名称. */
public static final String param_fileName = "fileName";
/** 批量文件内容. */
public static final String param_fileContent = "fileContent";
/** 商户摘要. */
public static final String param_merNote = "merNote";
/** 商户自定义域. */
// public static final String param_merReserved = "merReserved";//接口变更删除
/** 请求方保留域. */
public static final String param_reqReserved = "reqReserved";// 新增接口
/** 保留域. */
public static final String param_reserved = "reserved";
/** 终端号. */
public static final String param_termId = "termId";
/** 终端类型. */
public static final String param_termType = "termType";
/** 交互模式. */
public static final String param_interactMode = "interactMode";
/** 发卡机构识别模式. */
// public static final String param_recognitionMode = "recognitionMode";
public static final String param_issuerIdentifyMode = "issuerIdentifyMode";// 接口名称变更
/** 商户端用户号. */
public static final String param_merUserId = "merUserId";
/** 持卡人IP. */
public static final String param_customerIp = "customerIp";
/** 查询流水号. */
public static final String param_queryId = "queryId";
/** 原交易查询流水号. */
public static final String param_origQryId = "origQryId";
/** 系统跟踪号. */
public static final String param_traceNo = "traceNo";
/** 交易传输时间. */
public static final String param_traceTime = "traceTime";
/** 清算日期. */
public static final String param_settleDate = "settleDate";
/** 清算币种. */
public static final String param_settleCurrencyCode = "settleCurrencyCode";
/** 清算金额. */
public static final String param_settleAmt = "settleAmt";
/** 清算汇率. */
public static final String param_exchangeRate = "exchangeRate";
/** 兑换日期. */
public static final String param_exchangeDate = "exchangeDate";
/** 响应时间. */
public static final String param_respTime = "respTime";
/** 原交易应答码. */
public static final String param_origRespCode = "origRespCode";
/** 原交易应答信息. */
public static final String param_origRespMsg = "origRespMsg";
/** 应答码. */
public static final String param_respCode = "respCode";
/** 应答码信息. */
public static final String param_respMsg = "respMsg";
// 新增四个报文字段merUserRegDt merUserEmail checkFlag activateStatus
/** 商户端用户注册时间. */
public static final String param_merUserRegDt = "merUserRegDt";
/** 商户端用户注册邮箱. */
public static final String param_merUserEmail = "merUserEmail";
/** 验证标识. */
public static final String param_checkFlag = "checkFlag";
/** 开通状态. */
public static final String param_activateStatus = "activateStatus";
/** 加密证书ID. */
public static final String param_encryptCertId = "encryptCertId";
/** 用户MAC、IMEI串号、SSID. */
public static final String param_userMac = "userMac";
/** 关联交易. */
// public static final String param_relationTxnType = "relationTxnType";
/** 短信类型 */
public static final String param_smsType = "smsType";
/** 风控信息域 */
public static final String param_riskCtrlInfo = "riskCtrlInfo";
/** IC卡交易信息域 */
public static final String param_ICTransData = "ICTransData";
/** VPC交易信息域 */
public static final String param_VPCTransData = "VPCTransData";
/** 安全类型 */
public static final String param_securityType = "securityType";
/** 银联订单号 */
public static final String param_tn = "tn";
/** 分期付款手续费率 */
public static final String param_instalRate = "instalRate";
/** 分期付款手续费率 */
public static final String param_mchntFeeSubsidy = "mchntFeeSubsidy";
}
| smjie2800/spring-cloud-microservice-redis-activemq-hibernate-mysql | microservice-provider-pay/src/main/java/com/boyuanitsm/pay/unionpay/config/SDKConstants.java | Java | mit | 13,548 |
require 'faraday'
require 'simple_ratings/foursquare/meta/venue'
module SimpleRatings
class Foursquare < Faraday::Connection
def initialize
super(url: 'https://api.foursquare.com/v2/')
end
def default_params
{
client_id: ENV['FOURSQUARE_CLIENT_ID'],
client_secret: ENV['FOURSQUARE_CLIENT_SECRET'],
v: 20130214
}
end
def search(params)
get('venues/search', default_params.merge(params))
end
def get(url = nil, params = nil, headers = nil)
params ||= {}
params = default_params.merge(params)
super(url, params, headers)
end
# def get(*args)
# super(*build_default_request_arguments(*args))
# end
# def build_default_request_arguments(url = nil, params = nil, headers = nil)
# params ||= {}
# params = default_params.merge(params)
# [url, params, headers]
# end
end
end | benastan/simple_ratings | lib/simple_ratings/foursquare.rb | Ruby | mit | 918 |
using System;
using System.Text;
namespace ExifLibrary
{
/// <summary>
/// Represents an enumerated value.
/// </summary>
public class ExifEnumProperty<T> : ExifProperty
{
protected T mValue;
protected bool mIsBitField;
protected override object _Value { get { return Value; } set { Value = (T)value; } }
public new T Value { get { return mValue; } set { mValue = value; } }
public bool IsBitField { get { return mIsBitField; } }
static public implicit operator T(ExifEnumProperty<T> obj) { return (T)obj.mValue; }
public override string ToString() { return mValue.ToString(); }
public ExifEnumProperty(ExifTag tag, T value, bool isbitfield)
: base(tag)
{
mValue = value;
mIsBitField = isbitfield;
}
public ExifEnumProperty(ExifTag tag, T value)
: this(tag, value, false)
{
;
}
public override ExifInterOperability Interoperability
{
get
{
ushort tagid = ExifTagFactory.GetTagID(mTag);
Type type = typeof(T);
Type basetype = Enum.GetUnderlyingType(type);
if (type == typeof(FileSource) || type == typeof(SceneType))
{
// UNDEFINED
return new ExifInterOperability(tagid, 7, 1, new byte[] { (byte)((object)mValue) });
}
else if (type == typeof(GPSLatitudeRef) || type == typeof(GPSLongitudeRef) ||
type == typeof(GPSStatus) || type == typeof(GPSMeasureMode) ||
type == typeof(GPSSpeedRef) || type == typeof(GPSDirectionRef) ||
type == typeof(GPSDistanceRef))
{
// ASCII
return new ExifInterOperability(tagid, 2, 2, new byte[] { (byte)((object)mValue), 0 });
}
else if (basetype == typeof(byte))
{
// BYTE
return new ExifInterOperability(tagid, 1, 1, new byte[] { (byte)((object)mValue) });
}
else if (basetype == typeof(ushort))
{
// SHORT
return new ExifInterOperability(tagid, 3, 1, ExifBitConverter.GetBytes((ushort)((object)mValue), BitConverterEx.SystemByteOrder, BitConverterEx.SystemByteOrder));
}
else
throw new UnknownEnumTypeException();
}
}
}
/// <summary>
/// Represents an ASCII string. (EXIF Specification: UNDEFINED) Used for the UserComment field.
/// </summary>
public class ExifEncodedString : ExifProperty
{
protected string mValue;
private Encoding mEncoding;
protected override object _Value { get { return Value; } set { Value = (string)value; } }
public new string Value { get { return mValue; } set { mValue = value; } }
public Encoding Encoding { get { return mEncoding; } set { mEncoding = value; } }
static public implicit operator string(ExifEncodedString obj) { return obj.mValue; }
public override string ToString() { return mValue; }
public ExifEncodedString(ExifTag tag, string value, Encoding encoding)
: base(tag)
{
mValue = value;
mEncoding = encoding;
}
public override ExifInterOperability Interoperability
{
get
{
string enc = "";
if (mEncoding == null)
enc = "\0\0\0\0\0\0\0\0";
else if (mEncoding.EncodingName == "US-ASCII")
enc = "ASCII\0\0\0";
else if (mEncoding.EncodingName == "Japanese (JIS 0208-1990 and 0212-1990)")
enc = "JIS\0\0\0\0\0";
else if (mEncoding.EncodingName == "Unicode")
enc = "Unicode\0";
else
enc = "\0\0\0\0\0\0\0\0";
byte[] benc = Encoding.ASCII.GetBytes(enc);
byte[] bstr = (mEncoding == null ? Encoding.ASCII.GetBytes(mValue) : mEncoding.GetBytes(mValue));
byte[] data = new byte[benc.Length + bstr.Length];
Array.Copy(benc, 0, data, 0, benc.Length);
Array.Copy(bstr, 0, data, benc.Length, bstr.Length);
return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, (uint)data.Length, data);
}
}
}
/// <summary>
/// Represents an ASCII string formatted as DateTime. (EXIF Specification: ASCII) Used for the date time fields.
/// </summary>
public class ExifDateTime : ExifProperty
{
protected DateTime mValue;
protected override object _Value { get { return Value; } set { Value = (DateTime)value; } }
public new DateTime Value { get { return mValue; } set { mValue = value; } }
static public implicit operator DateTime(ExifDateTime obj) { return obj.mValue; }
public override string ToString() { return mValue.ToString("yyyy.MM.dd HH:mm:ss"); }
public ExifDateTime(ExifTag tag, DateTime value)
: base(tag)
{
mValue = value;
}
public override ExifInterOperability Interoperability
{
get
{
return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 2, (uint)20, ExifBitConverter.GetBytes(mValue, true));
}
}
}
/// <summary>
/// Represents the exif version as a 4 byte ASCII string. (EXIF Specification: UNDEFINED)
/// Used for the ExifVersion, FlashpixVersion, InteroperabilityVersion and GPSVersionID fields.
/// </summary>
public class ExifVersion : ExifProperty
{
protected string mValue;
protected override object _Value { get { return Value; } set { Value = (string)value; } }
public new string Value { get { return mValue; } set { mValue = value.Substring(0, 4); } }
public ExifVersion(ExifTag tag, string value)
: base(tag)
{
if (value.Length > 4)
mValue = value.Substring(0, 4);
else if (value.Length < 4)
mValue = value + new string(' ', 4 - value.Length);
else
mValue = value;
}
public override string ToString()
{
return mValue;
}
public override ExifInterOperability Interoperability
{
get
{
if (mTag == ExifTag.ExifVersion || mTag == ExifTag.FlashpixVersion || mTag == ExifTag.InteroperabilityVersion)
return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, 4, Encoding.ASCII.GetBytes(mValue));
else
{
byte[] data = new byte[4];
for (int i = 0; i < 4; i++)
data[i] = byte.Parse(mValue[0].ToString());
return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, 4, data);
}
}
}
}
/// <summary>
/// Represents the location and area of the subject (EXIF Specification: 2xSHORT)
/// The coordinate values, width, and height are expressed in relation to the
/// upper left as origin, prior to rotation processing as per the Rotation tag.
/// </summary>
public class ExifPointSubjectArea : ExifUShortArray
{
protected new ushort[] Value { get { return mValue; } set { mValue = value; } }
public ushort X { get { return mValue[0]; } set { mValue[0] = value; } }
public ushort Y { get { return mValue[1]; } set { mValue[1] = value; } }
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("({0:d}, {1:d})", mValue[0], mValue[1]);
return sb.ToString();
}
public ExifPointSubjectArea(ExifTag tag, ushort[] value)
: base(tag, value)
{
;
}
public ExifPointSubjectArea(ExifTag tag, ushort x, ushort y)
: base(tag, new ushort[] { x, y })
{
;
}
}
/// <summary>
/// Represents the location and area of the subject (EXIF Specification: 3xSHORT)
/// The coordinate values, width, and height are expressed in relation to the
/// upper left as origin, prior to rotation processing as per the Rotation tag.
/// </summary>
public class ExifCircularSubjectArea : ExifPointSubjectArea
{
public ushort Diamater { get { return mValue[2]; } set { mValue[2] = value; } }
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("({0:d}, {1:d}) {2:d}", mValue[0], mValue[1], mValue[2]);
return sb.ToString();
}
public ExifCircularSubjectArea(ExifTag tag, ushort[] value)
: base(tag, value)
{
;
}
public ExifCircularSubjectArea(ExifTag tag, ushort x, ushort y, ushort d)
: base(tag, new ushort[] { x, y, d })
{
;
}
}
/// <summary>
/// Represents the location and area of the subject (EXIF Specification: 4xSHORT)
/// The coordinate values, width, and height are expressed in relation to the
/// upper left as origin, prior to rotation processing as per the Rotation tag.
/// </summary>
public class ExifRectangularSubjectArea : ExifPointSubjectArea
{
public ushort Width { get { return mValue[2]; } set { mValue[2] = value; } }
public ushort Height { get { return mValue[3]; } set { mValue[3] = value; } }
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("({0:d}, {1:d}) ({2:d} x {3:d})", mValue[0], mValue[1], mValue[2], mValue[3]);
return sb.ToString();
}
public ExifRectangularSubjectArea(ExifTag tag, ushort[] value)
: base(tag, value)
{
;
}
public ExifRectangularSubjectArea(ExifTag tag, ushort x, ushort y, ushort w, ushort h)
: base(tag, new ushort[] { x, y, w, h })
{
;
}
}
/// <summary>
/// Represents GPS latitudes and longitudes (EXIF Specification: 3xRATIONAL)
/// </summary>
public class GPSLatitudeLongitude : ExifURationalArray
{
protected new MathEx.UFraction32[] Value { get { return mValue; } set { mValue = value; } }
public MathEx.UFraction32 Degrees { get { return mValue[0]; } set { mValue[0] = value; } }
public MathEx.UFraction32 Minutes { get { return mValue[1]; } set { mValue[1] = value; } }
public MathEx.UFraction32 Seconds { get { return mValue[2]; } set { mValue[2] = value; } }
public static explicit operator float(GPSLatitudeLongitude obj) { return obj.ToFloat(); }
public float ToFloat()
{
return (float)Degrees + ((float)Minutes) / 60.0f + ((float)Seconds) / 3600.0f;
}
public override string ToString()
{
return string.Format("{0:F2}°{1:F2}'{2:F2}\"", (float)Degrees, (float)Minutes, (float)Seconds);
}
public GPSLatitudeLongitude(ExifTag tag, MathEx.UFraction32[] value)
: base(tag, value)
{
;
}
public GPSLatitudeLongitude(ExifTag tag, float d, float m, float s)
: base(tag, new MathEx.UFraction32[] { new MathEx.UFraction32(d), new MathEx.UFraction32(m), new MathEx.UFraction32(s) })
{
;
}
}
/// <summary>
/// Represents a GPS time stamp as UTC (EXIF Specification: 3xRATIONAL)
/// </summary>
public class GPSTimeStamp : ExifURationalArray
{
protected new MathEx.UFraction32[] Value { get { return mValue; } set { mValue = value; } }
public MathEx.UFraction32 Hour { get { return mValue[0]; } set { mValue[0] = value; } }
public MathEx.UFraction32 Minute { get { return mValue[1]; } set { mValue[1] = value; } }
public MathEx.UFraction32 Second { get { return mValue[2]; } set { mValue[2] = value; } }
public override string ToString()
{
return string.Format("{0:F2}:{1:F2}:{2:F2}\"", (float)Hour, (float)Minute, (float)Second);
}
public GPSTimeStamp(ExifTag tag, MathEx.UFraction32[] value)
: base(tag, value)
{
;
}
public GPSTimeStamp(ExifTag tag, float h, float m, float s)
: base(tag, new MathEx.UFraction32[] { new MathEx.UFraction32(h), new MathEx.UFraction32(m), new MathEx.UFraction32(s) })
{
;
}
}
/// <summary>
/// Represents an ASCII string. (EXIF Specification: BYTE)
/// Used by Windows XP.
/// </summary>
public class WindowsByteString : ExifProperty
{
protected string mValue;
protected override object _Value { get { return Value; } set { Value = (string)value; } }
public new string Value { get { return mValue; } set { mValue = value; } }
static public implicit operator string(WindowsByteString obj) { return obj.mValue; }
public override string ToString() { return mValue; }
public WindowsByteString(ExifTag tag, string value)
: base(tag)
{
mValue = value;
}
public override ExifInterOperability Interoperability
{
get
{
byte[] data = Encoding.Unicode.GetBytes(mValue);
return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 1, (uint)data.Length, data);
}
}
}
}
| ahzf/ExifLibrary | ExifLibrary/ExifExtendedProperty.cs | C# | mit | 13,977 |
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using ShowFinder.Models;
namespace ShowFinder.Repositories.Interfaces
{
public interface IMongoRepository
{
IMongoDatabase Database(string name);
Task<BsonDocument> GetUserProfile(IMongoCollection<BsonDocument> userProfilesCollection, string hash);
Task<bool> UpdateShows(IMongoCollection<BsonDocument> userProfilesCollection, string userHash, IEnumerable<string> showList);
Task<bool> UpdateDownloadedEpisode(IMongoCollection<BsonDocument> userProfilesCollection, string profileId,
string episodeId, string filteredShowName, DownloadedEpisode downloadedEpisodeData);
Task<bool> DeleteDownloadedEpisode(IMongoCollection<BsonDocument> userProfilesCollection, string profileId,
string episodeId, string filtereShowdName);
Task<bool> UpdateTimeSpan(IMongoCollection<BsonDocument> userProfilesCollection, UserProfile profile);
Task<BsonDocument> GetFromCache(IMongoCollection<BsonDocument> collection, string id);
Task<bool> SetToCache(IMongoCollection<BsonDocument> collection, string id, BsonDocument doc, int daysToExpire);
}
} | YanivHaramati/ShowFinder | ShowFinder/Repositories/Interfaces/IMongoRepository.cs | C# | mit | 1,257 |
/*!
* Module dependencies.
*/
var util = require('util'),
moment = require('moment'),
super_ = require('../Type');
/**
* Date FieldType Constructor
* @extends Field
* @api public
*/
function datearray(list, path, options) {
this._nativeType = [Date];
this._defaultSize = 'medium';
this._underscoreMethods = ['format'];
this._properties = ['formatString'];
this.parseFormatString = options.parseFormat || 'YYYY-MM-DD';
this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY');
if (this.formatString && 'string' !== typeof this.formatString) {
throw new Error('FieldType.Date: options.format must be a string.');
}
datearray.super_.call(this, list, path, options);
}
/*!
* Inherit from Field
*/
util.inherits(datearray, super_);
/**
* Formats the field value
*
* @api public
*/
datearray.prototype.format = function(item, format) {
if (format || this.formatString) {
return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : '';
} else {
return item.get(this.path) || '';
}
};
/**
* Checks that a valid array of dates has been provided in a data object
*
* An empty value clears the stored value and is considered valid
*
* @api public
*/
datearray.prototype.inputIsValid = function(data, required, item) {
var value = this.getValueFromData(data);
var parseFormatString = this.parseFormatString;
if ('string' === typeof value) {
if (!moment(value, parseFormatString).isValid()) {
return false;
}
value = [value];
}
if (required) {
if (value === undefined && item && item.get(this.path) && item.get(this.path).length) {
return true;
}
if (value === undefined || !Array.isArray(value)) {
return false;
}
if (Array.isArray(value) && !value.length) {
return false;
}
}
if (Array.isArray(value)) {
// filter out empty fields
value = value.filter(function(date) {
return date.trim() !== '';
});
// if there are no values left, and requried is true, return false
if (required && !value.length) {
return false;
}
// if any date in the array is invalid, return false
if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) {
return false;
}
}
return (value === undefined || Array.isArray(value));
};
/**
* Updates the value for this field in the item from a data object
*
* @api public
*/
datearray.prototype.updateItem = function(item, data, callback) {
var value = this.getValueFromData(data);
if (value !== undefined) {
if (Array.isArray(value)) {
// Only save valid dates
value = value.filter(function(date) {
return moment(date).isValid();
});
}
if (value === null) {
value = [];
}
if ('string' === typeof value) {
if (moment(value).isValid()) {
value = [value];
}
}
if (Array.isArray(value)) {
item.set(this.path, value);
}
} else item.set(this.path, []);
process.nextTick(callback);
};
/*!
* Export class
*/
module.exports = datearray;
| riyadhalnur/keystone | fields/types/datearray/DateArrayType.js | JavaScript | mit | 3,038 |
# -*- coding: utf-8 -*-
require "em-websocket"
require "eventmachine-tail"
module Tailer
# Extends FileTail to push data tailed to an EM::Channel. All open websockets
# subscribe to a channel for the request stack and this pushes the data to
# all of them at once.
class StackTail < EventMachine::FileTail
def initialize(filename, channel, startpos=-1)
super(filename, startpos)
@channel = channel
@buffer = BufferedTokenizer.new
end
# This method is called whenever FileTail receives an inotify event for
# the tailed file. It breaks up the data per line and pushes a line at a
# time. This is to prevent the last javascript line from being broken up
# over 2 pushes thus breaking the eval on the front end.
def receive_data(data)
# replace non UTF-8 characters with ?
data.encode!('UTF-8', invalid: :replace, undef: :replace, replace: '�')
@buffer.extract(data).each do |line|
@channel.push line
end
end
end
# Checks if stack log symlink exists and creates Tailer for it
def self.stack_tail(stack, channel, channel_count)
if Deployinator.get_visible_stacks.include?(stack)
filename = "#{Deployinator::Helpers::RUN_LOG_PATH}current-#{stack}"
start_pos = (channel_count == 0) ? 0 : -1
File.exists?(filename) ? StackTail.new(filename, channel, start_pos) : false
end
end
end
| etsy/deployinator | lib/deployinator/stack-tail.rb | Ruby | mit | 1,403 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Channels.Sockets
{
using System;
using System.Diagnostics.Contracts;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
public class DefaultDatagramChannelConfig : DefaultChannelConfiguration, IDatagramChannelConfig
{
const int DefaultFixedBufferSize = 2048;
readonly Socket socket;
public DefaultDatagramChannelConfig(IDatagramChannel channel, Socket socket)
: base(channel, new FixedRecvByteBufAllocator(DefaultFixedBufferSize))
{
Contract.Requires(socket != null);
this.socket = socket;
}
public override T GetOption<T>(ChannelOption<T> option)
{
if (ChannelOption.SoBroadcast.Equals(option))
{
return (T)(object)this.Broadcast;
}
if (ChannelOption.SoRcvbuf.Equals(option))
{
return (T)(object)this.ReceiveBufferSize;
}
if (ChannelOption.SoSndbuf.Equals(option))
{
return (T)(object)this.SendBufferSize;
}
if (ChannelOption.SoReuseaddr.Equals(option))
{
return (T)(object)this.ReuseAddress;
}
if (ChannelOption.IpMulticastLoopDisabled.Equals(option))
{
return (T)(object)this.LoopbackModeDisabled;
}
if (ChannelOption.IpMulticastTtl.Equals(option))
{
return (T)(object)this.TimeToLive;
}
if (ChannelOption.IpMulticastAddr.Equals(option))
{
return (T)(object)this.Interface;
}
if (ChannelOption.IpMulticastIf.Equals(option))
{
return (T)(object)this.NetworkInterface;
}
if (ChannelOption.IpTos.Equals(option))
{
return (T)(object)this.TrafficClass;
}
return base.GetOption(option);
}
public override bool SetOption<T>(ChannelOption<T> option, T value)
{
if (base.SetOption(option, value))
{
return true;
}
if (ChannelOption.SoBroadcast.Equals(option))
{
this.Broadcast = (bool)(object)value;
}
else if (ChannelOption.SoRcvbuf.Equals(option))
{
this.ReceiveBufferSize = (int)(object)value;
}
else if (ChannelOption.SoSndbuf.Equals(option))
{
this.SendBufferSize = (int)(object)value;
}
else if (ChannelOption.SoReuseaddr.Equals(option))
{
this.ReuseAddress = (bool)(object)value;
}
else if (ChannelOption.IpMulticastLoopDisabled.Equals(option))
{
this.LoopbackModeDisabled = (bool)(object)value;
}
else if (ChannelOption.IpMulticastTtl.Equals(option))
{
this.TimeToLive = (short)(object)value;
}
else if (ChannelOption.IpMulticastAddr.Equals(option))
{
this.Interface = (EndPoint)(object)value;
}
else if (ChannelOption.IpMulticastIf.Equals(option))
{
this.NetworkInterface = (NetworkInterface)(object)value;
}
else if (ChannelOption.IpTos.Equals(option))
{
this.TrafficClass = (int)(object)value;
}
else
{
return false;
}
return true;
}
public int SendBufferSize
{
get
{
try
{
return this.socket.SendBufferSize;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
set
{
try
{
this.socket.SendBufferSize = value;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
}
public int ReceiveBufferSize
{
get
{
try
{
return this.socket.ReceiveBufferSize;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
set
{
try
{
this.socket.ReceiveBufferSize = value;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
}
public int TrafficClass
{
get
{
try
{
return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService);
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
set
{
try
{
this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService, value);
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
}
public bool ReuseAddress
{
get
{
try
{
return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress) != 0;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
set
{
try
{
this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, value ? 1 : 0);
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
}
public bool Broadcast
{
get
{
try
{
return this.socket.EnableBroadcast;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
set
{
try
{
this.socket.EnableBroadcast = value;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
}
public bool LoopbackModeDisabled
{
get
{
try
{
return !this.socket.MulticastLoopback;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
set
{
try
{
this.socket.MulticastLoopback = !value;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
}
public short TimeToLive
{
get
{
try
{
return (short)this.socket.GetSocketOption(
this.AddressFamilyOptionLevel,
SocketOptionName.MulticastTimeToLive);
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
set
{
try
{
this.socket.SetSocketOption(
this.AddressFamilyOptionLevel,
SocketOptionName.MulticastTimeToLive,
value);
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
}
public EndPoint Interface
{
get
{
try
{
return this.socket.LocalEndPoint;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
set
{
Contract.Requires(value != null);
try
{
this.socket.Bind(value);
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
}
public NetworkInterface NetworkInterface
{
get
{
try
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
int value = (int)this.socket.GetSocketOption(
this.AddressFamilyOptionLevel,
SocketOptionName.MulticastInterface);
int index = IPAddress.NetworkToHostOrder(value);
if (interfaces.Length > 0
&& index >= 0
&& index < interfaces.Length)
{
return interfaces[index];
}
return null;
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
set
{
Contract.Requires(value != null);
try
{
int index = this.GetNetworkInterfaceIndex(value);
if (index >= 0)
{
this.socket.SetSocketOption(
this.AddressFamilyOptionLevel,
SocketOptionName.MulticastInterface,
index);
}
}
catch (ObjectDisposedException ex)
{
throw new ChannelException(ex);
}
catch (SocketException ex)
{
throw new ChannelException(ex);
}
}
}
internal SocketOptionLevel AddressFamilyOptionLevel
{
get
{
if (this.socket.AddressFamily == AddressFamily.InterNetwork)
{
return SocketOptionLevel.IP;
}
if (this.socket.AddressFamily == AddressFamily.InterNetworkV6)
{
return SocketOptionLevel.IPv6;
}
throw new NotSupportedException($"Socket address family {this.socket.AddressFamily} not supported, expecting InterNetwork or InterNetworkV6");
}
}
internal int GetNetworkInterfaceIndex(NetworkInterface networkInterface)
{
Contract.Requires(networkInterface != null);
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
for (int index = 0; index < interfaces.Length; index++)
{
if (interfaces[index].Id == networkInterface.Id)
{
return index;
}
}
return -1;
}
}
}
| dragonphoenix/proto-java-csharp | DotNetty/DotNetty.Transport/Channels/Sockets/DefaultDatagramChannelConfig.cs | C# | mit | 14,695 |
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
class Video
include Claire::Client::Item
end
describe Claire::Client::Item do
#@session.should_receive(:post).with("url", "data", "headers")
#@session = mock("session")
before do
Claire::Client.stub(:get).with('videos/id').and_return xml :item
@video = Video.new(hash_from_xml(:item))
end
describe "its initializer" do
describe "its base_url class attribute" do
it "should default to the class name, pluralized" do
Video.base_url.should == "videos"
end
it "should accept manual overwrite on the class" do
Video.base_url = "lists"
Video.base_url.should == "lists"
Video.base_url = nil
Video.base_url.should == "videos"
end
it "if the class is in a module, it should get the class name only" do
eval %(
module Testing
class Video
include Claire::Client::Item
end
end
)
Testing::Video.base_url.should == "videos"
end
end
context "upon receiving a Hash" do
before :each do
@video = Video.new(hash_from_xml(:item))
end
it "should set partial do true" do
@video.should be_partial
end
it "should skip the <rss> container if it is present" do
@video.title.should be_a_kind_of String
@video.should_not respond_to :rss
end
it "should skip the <channel> container if its present" do
video = Video.new(hash_from_xml(:item_with_channel))
video.title.should be_a_kind_of String
video.should_not respond_to :channel
end
it "should never set 'items' attributes " do
%w(item item_with_channel).each do |type|
video = Video.new(hash_from_xml(type))
video.should_not respond_to :item
video.title.should be_a_kind_of String
end
end
it "should set the link attribute properly (eg ignoring links to other objects/pages)" do
video = Video.new hash_from_xml :item_with_channel
video.link.should be_a_kind_of String
end
it "should set its key/values as properties of the element" do
%w(title link category keywords description).each do |item|
@video.send(item).should be_a_kind_of String
end
%w(thumbnail content).each{ |item| @video.send(item).should be_a_kind_of Array }
end
it "should fail if there is not a link attribute" do
lambda { Video.new( {:rss => {:item => {:name => 'bla'}}} ) }.should raise_error Claire::Error
end
end
context "upon receiving a String" do
before { @video = Video.new 'id' }
it "should open the given string" do
lambda { Video.new "" }.should raise_error
lambda { Video.new "id" }.should_not raise_error
end
it "should parse the result using the XML parsing rules" do
@video.title.should be_a_kind_of String
end
it "should set partial to false" do
@video.should_not be_partial
end
end
end
describe "its comparison (spaceship) operator" do
it "should be defined" do
@video.should respond_to '<=>'
end
it "should compare items by title" do
@video2 = @video.clone
(@video <=> @video2).should be 0
end
end
context "when an undefined method is called" do
it "it should raise error if partial is false"
context "if the item is partial" do
it "should request the full object from server, and replace itself"
it "should return the asked attribute"
end
end
it "should have a list of its children as the children class attribute" do
Claire::Client::Item.children.include?(Video).should be true
end
end | memuller/claire.client | spec/claire_client/item_spec.rb | Ruby | mit | 3,595 |
<?php
namespace Zanson\SMParser\Traits\Song;
use Zanson\SMParser\SMException;
trait Banner
{
public $banner = '';
/**
* @return string
*/
public function getBanner() {
return $this->banner;
}
/**
* @param string $banner
*
* @return $this
* @throws SMException
*/
public function setBanner($banner) {
if (!is_string($banner)) {
throw new SMException("Banner must be a string");
}
$this->banner = $banner;
return $this;
}
} | jasonwatt/SMParser | src/Traits/Song/Banner.php | PHP | mit | 541 |
if ( !window.console ) window.console = { log:function(){} };
jQuery(document).ready(function($) {
console.log('Keep being awesome.');
}); | shampine/180 | public/js/src/script.js | JavaScript | mit | 143 |
package parser
import (
"monkey/ast"
"monkey/token"
)
func (p *Parser) parseStringLiteralExpression() ast.Expression {
return &ast.StringLiteral{Token: p.curToken, Value: p.curToken.Literal}
}
func (p *Parser) parseInterpolatedString() ast.Expression {
is := &ast.InterpolatedString{Token: p.curToken, Value: p.curToken.Literal, ExprMap: make(map[byte]ast.Expression)}
key := "0"[0]
for {
if p.curTokenIs(token.LBRACE) {
p.nextToken()
expr := p.parseExpression(LOWEST)
is.ExprMap[key] = expr
key++
}
p.nextInterpToken()
if p.curTokenIs(token.ISTRING) {
break
}
}
return is
}
| mayoms/monkey | parser/strings.go | GO | mit | 612 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Diagnostics;
namespace ForumHelper
{
public partial class ToastForm : Form
{
public ToastForm()
{
InitializeComponent();
TopMost = true;
ShowInTaskbar = false;
timer = new System.Windows.Forms.Timer();
timer.Interval = 500;
timer.Tick += timer_Tick;
}
private System.Windows.Forms.Timer timer;
private int startPosX;
private int startPosY;
private void ToastForm_Load(object sender, EventArgs e)
{
}
protected override void OnLoad(EventArgs e)
{
startPosX = Screen.PrimaryScreen.WorkingArea.Width - Width;
startPosY = Screen.PrimaryScreen.WorkingArea.Height - Height;
SetDesktopLocation(startPosX, startPosY);
pageLinkLabel.Text = URLEventArgs.Url;
// base.OnLoad(e);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
startPosY -= 50;
if (startPosY < Screen.PrimaryScreen.WorkingArea.Height - Height) timer.Stop();
else
{
SetDesktopLocation(startPosX, startPosY);
timer.Stop();
}
}
private void ToastForm_Click(object sender, EventArgs e)
{
this.Close();
}
private void pageLinkLabelClick(object sender, EventArgs e)
{
Process.Start(this.pageLinkLabel.Text);
this.Close();
}
}
}
| ttitto/PersonalProjects | ForumHelper/ForumHelper/ToastForm.cs | C# | mit | 1,852 |
<?php
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2018 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
use Base64Url\Base64Url;
use Jose\Decrypter;
use Jose\Encrypter;
use Jose\Factory\JWEFactory;
use Jose\Loader;
use Jose\Object\JWEInterface;
use Jose\Object\JWK;
use Jose\Object\JWKSet;
use Jose\Test\Stub\FakeLogger;
use Jose\Test\BaseTestCase;
/**
* Class EncrypterTest.
*
* @group Encrypter
* @group Functional
*/
class EncrypterBaseTest extends BaseTestCase
{
public function testEncryptWithJWTInput()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE(
'FOO',
[
'enc' => 'A256CBC-HS512',
'alg' => 'RSA-OAEP-256',
'zip' => 'DEF',
],
[],
'foo,bar,baz'
);
$jwe = $jwe->addRecipientInformation($this->getRSARecipientKey());
$encrypter->encrypt($jwe);
$encrypted = $jwe->toFlattenedJSON(0);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($encrypted);
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg'));
self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc'));
self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip'));
self::assertNull($loaded->getPayload());
$decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index);
self::assertEquals(0, $index);
self::assertEquals('FOO', $loaded->getPayload());
}
public function testCreateCompactJWEUsingFactory()
{
$jwe = JWEFactory::createJWEToCompactJSON(
'FOO',
$this->getRSARecipientKey(),
[
'enc' => 'A256CBC-HS512',
'alg' => 'RSA-OAEP-256',
'zip' => 'DEF',
]
);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($jwe);
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg'));
self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc'));
self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip'));
self::assertNull($loaded->getPayload());
$decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index);
self::assertEquals(0, $index);
self::assertEquals('FOO', $loaded->getPayload());
}
public function testCreateFlattenedJWEUsingFactory()
{
$jwe = JWEFactory::createJWEToFlattenedJSON(
'FOO',
$this->getRSARecipientKey(),
[
'enc' => 'A256CBC-HS512',
'alg' => 'RSA-OAEP-256',
'zip' => 'DEF',
],
[
'foo' => 'bar',
],
[
'plic' => 'ploc',
],
'A,B,C,D'
);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($jwe);
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg'));
self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc'));
self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip'));
self::assertEquals('bar', $loaded->getSharedHeader('foo'));
self::assertEquals('A,B,C,D', $loaded->getAAD('foo'));
self::assertEquals('ploc', $loaded->getRecipient(0)->getHeader('plic'));
self::assertNull($loaded->getPayload());
$decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index);
self::assertEquals(0, $index);
self::assertEquals('FOO', $loaded->getPayload());
}
public function testEncryptAndLoadFlattenedWithAAD()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE(
$this->getKeyToEncrypt(),
[
'enc' => 'A256CBC-HS512',
'alg' => 'RSA-OAEP-256',
'zip' => 'DEF',
],
[],
'foo,bar,baz'
);
$jwe = $jwe->addRecipientInformation($this->getRSARecipientKey());
$encrypter->encrypt($jwe);
$encrypted = $jwe->toFlattenedJSON(0);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($encrypted);
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg'));
self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc'));
self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip'));
self::assertNull($loaded->getPayload());
$decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index);
self::assertEquals(0, $index);
self::assertTrue(is_array($loaded->getPayload()));
self::assertEquals($this->getKeyToEncrypt(), new JWK($loaded->getPayload()));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Compression method "FIP" not supported
*/
public function testCompressionAlgorithmNotSupported()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE(
$this->getKeyToEncrypt(),
[
'enc' => 'A256CBC-HS512',
'alg' => 'RSA-OAEP-256',
'zip' => 'FIP',
],
[],
'foo,bar,baz'
);
$jwe = $jwe->addRecipientInformation($this->getRSARecipientKey());
$encrypter->encrypt($jwe);
}
public function testMultipleInstructionsNotAllowedWithCompactSerialization()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP', 'RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE('Live long and Prosper.');
$jwe = $jwe->withSharedProtectedHeaders([
'enc' => 'A256CBC-HS512',
]);
$jwe = $jwe->addRecipientInformation($this->getRSARecipientKeyWithAlgorithm(), ['alg' => 'RSA-OAEP']);
$jwe = $jwe->addRecipientInformation($this->getRSARecipientKey(), ['alg' => 'RSA-OAEP-256']);
$encrypter->encrypt($jwe);
self::assertEquals(2, $jwe->countRecipients());
}
public function testMultipleInstructionsNotAllowedWithFlattenedSerialization()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE('Live long and Prosper.');
$jwe = $jwe->withSharedProtectedHeaders([
'enc' => 'A256CBC-HS512',
]);
$jwe = $jwe->addRecipientInformation(
$this->getECDHRecipientPublicKey(),
['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW']
);
$jwe = $jwe->addRecipientInformation(
$this->getRSARecipientKey(),
['kid' => '123456789', 'alg' => 'RSA-OAEP-256']
);
$encrypter->encrypt($jwe);
self::assertEquals(2, $jwe->countRecipients());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Foreign key management mode forbidden.
*/
public function testForeignKeyManagementModeForbidden()
{
$encrypter = Encrypter::createEncrypter(['dir', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE('Live long and Prosper.');
$jwe = $jwe->withSharedProtectedHeaders([
'enc' => 'A256CBC-HS512',
]);
$jwe = $jwe->addRecipientInformation(
$this->getECDHRecipientPublicKey(),
['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW']
);
$jwe = $jwe->addRecipientInformation(
$this->getDirectKey(),
['kid' => 'DIR_1', 'alg' => 'dir']
);
$encrypter->encrypt($jwe);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Key cannot be used to encrypt
*/
public function testOperationNotAllowedForTheKey()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE(
'Foo',
[
'enc' => 'A256CBC-HS512',
'alg' => 'RSA-OAEP-256',
'zip' => 'DEF',
],
[],
'foo,bar,baz'
);
$jwe = $jwe->addRecipientInformation(
$this->getSigningKey()
);
$encrypter->encrypt($jwe);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Key is only allowed for algorithm "RSA-OAEP".
*/
public function testAlgorithmNotAllowedForTheKey()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE(
'FOO',
[
'enc' => 'A256CBC-HS512',
'alg' => 'RSA-OAEP-256',
'zip' => 'DEF',
],
[],
'foo,bar,baz'
);
$jwe = $jwe->addRecipientInformation(
$this->getRSARecipientKeyWithAlgorithm()
);
$encrypter->encrypt($jwe);
}
public function testEncryptAndLoadFlattenedWithDeflateCompression()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A128CBC-HS256'], ['DEF'], new FakeLogger());
$decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A128CBC-HS256'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE($this->getKeySetToEncrypt());
$jwe = $jwe->withSharedProtectedHeaders([
'kid' => '123456789',
'enc' => 'A128CBC-HS256',
'alg' => 'RSA-OAEP-256',
'zip' => 'DEF',
]);
$jwe = $jwe->addRecipientInformation(
$this->getRSARecipientKey()
);
$encrypter->encrypt($jwe);
$encrypted = $jwe->toCompactJSON(0);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($encrypted);
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg'));
self::assertEquals('A128CBC-HS256', $loaded->getSharedProtectedHeader('enc'));
self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip'));
self::assertNull($loaded->getPayload());
$decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index);
self::assertEquals(0, $index);
self::assertTrue(is_array($loaded->getPayload()));
self::assertEquals($this->getKeySetToEncrypt(), new JWKSet($loaded->getPayload()));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Parameter "alg" is missing.
*/
public function testAlgParameterIsMissing()
{
$encrypter = Encrypter::createEncrypter(['A256CBC-HS512'], [], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE($this->getKeyToEncrypt());
$jwe = $jwe->withSharedProtectedHeaders([
'kid' => '123456789',
'enc' => 'A256CBC-HS512',
'zip' => 'DEF',
]);
$jwe = $jwe->addRecipientInformation(
$this->getRSARecipientKey()
);
$encrypter->encrypt($jwe);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Parameter "enc" is missing.
*/
public function testEncParameterIsMissing()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], [], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE($this->getKeyToEncrypt());
$jwe = $jwe->withSharedProtectedHeaders([
'kid' => '123456789',
'alg' => 'RSA-OAEP-256',
'zip' => 'DEF',
]);
$jwe = $jwe->addRecipientInformation(
$this->getRSARecipientKey()
);
$encrypter->encrypt($jwe);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The key encryption algorithm "A256CBC-HS512" is not supported or not a key encryption algorithm instance.
*/
public function testNotAKeyEncryptionAlgorithm()
{
$encrypter = Encrypter::createEncrypter(['A256CBC-HS512'], [], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE($this->getKeyToEncrypt());
$jwe = $jwe->withSharedProtectedHeaders([
'kid' => '123456789',
'enc' => 'A256CBC-HS512',
'alg' => 'A256CBC-HS512',
'zip' => 'DEF',
]);
$jwe = $jwe->addRecipientInformation(
$this->getRSARecipientKey()
);
$encrypter->encrypt($jwe);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The content encryption algorithm "RSA-OAEP-256" is not supported or not a content encryption algorithm instance.
*/
public function testNotAContentEncryptionAlgorithm()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], [], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE($this->getKeyToEncrypt());
$jwe = $jwe->withSharedProtectedHeaders([
'kid' => '123456789',
'enc' => 'RSA-OAEP-256',
'alg' => 'RSA-OAEP-256',
'zip' => 'DEF',
]);
$jwe = $jwe->addRecipientInformation(
$this->getRSARecipientKey()
);
$encrypter->encrypt($jwe);
}
public function testEncryptAndLoadCompactWithDirectKeyEncryption()
{
$encrypter = Encrypter::createEncrypter(['dir'], ['A192CBC-HS384'], ['DEF'], new FakeLogger());
$decrypter = Decrypter::createDecrypter(['dir'], ['A192CBC-HS384'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE($this->getKeyToEncrypt());
$jwe = $jwe->withSharedProtectedHeaders([
'kid' => 'DIR_1',
'enc' => 'A192CBC-HS384',
'alg' => 'dir',
]);
$jwe = $jwe->addRecipientInformation(
$this->getDirectKey()
);
$encrypter->encrypt($jwe);
$encrypted = $jwe->toFlattenedJSON(0);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($encrypted);
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('dir', $loaded->getSharedProtectedHeader('alg'));
self::assertEquals('A192CBC-HS384', $loaded->getSharedProtectedHeader('enc'));
self::assertFalse($loaded->hasSharedHeader('zip'));
self::assertNull($loaded->getPayload());
$decrypter->decryptUsingKeySet($loaded, $this->getSymmetricKeySet(), $index);
self::assertEquals(0, $index);
self::assertTrue(is_array($loaded->getPayload()));
self::assertEquals($this->getKeyToEncrypt(), new JWK($loaded->getPayload()));
}
public function testEncryptAndLoadCompactKeyAgreement()
{
$encrypter = Encrypter::createEncrypter(['ECDH-ES'], ['A192CBC-HS384'], ['DEF'], new FakeLogger());
$decrypter = Decrypter::createDecrypter(['ECDH-ES'], ['A192CBC-HS384'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE(['user_id' => '1234', 'exp' => time() + 3600]);
$jwe = $jwe->withSharedProtectedHeaders([
'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d',
'enc' => 'A192CBC-HS384',
'alg' => 'ECDH-ES',
]);
$jwe = $jwe->addRecipientInformation(
$this->getECDHRecipientPublicKey()
);
$encrypter->encrypt($jwe);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($jwe->toFlattenedJSON(0));
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('ECDH-ES', $loaded->getSharedProtectedHeader('alg'));
self::assertEquals('A192CBC-HS384', $loaded->getSharedProtectedHeader('enc'));
self::assertFalse($loaded->hasSharedProtectedHeader('zip'));
self::assertNull($loaded->getPayload());
$decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index);
self::assertEquals(0, $index);
self::assertTrue($loaded->hasClaims());
self::assertTrue($loaded->hasClaim('user_id'));
self::assertEquals('1234', $loaded->getClaim('user_id'));
}
public function testEncryptAndLoadCompactKeyAgreementWithWrappingCompact()
{
$encrypter = Encrypter::createEncrypter(['ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$decrypter = Decrypter::createDecrypter(['ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE('Live long and Prosper.');
$jwe = $jwe->withSharedProtectedHeaders([
'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d',
'enc' => 'A256CBC-HS512',
'alg' => 'ECDH-ES+A256KW',
]);
$jwe = $jwe->addRecipientInformation(
$this->getECDHRecipientPublicKey()
);
$encrypter->encrypt($jwe);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($jwe->toFlattenedJSON(0));
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('ECDH-ES+A256KW', $loaded->getSharedProtectedHeader('alg'));
self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc'));
self::assertFalse($loaded->hasSharedProtectedHeader('zip'));
self::assertFalse($loaded->hasSharedHeader('zip'));
self::assertNull($loaded->getPayload());
$decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index);
self::assertEquals(0, $index);
self::assertTrue(is_string($loaded->getPayload()));
self::assertEquals('Live long and Prosper.', $loaded->getPayload());
}
public function testEncryptAndLoadWithGCMAndAAD()
{
$encrypter = Encrypter::createEncrypter(['ECDH-ES+A256KW'], ['A256GCM'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE(
'Live long and Prosper.',
[
'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d',
'enc' => 'A256GCM',
'alg' => 'ECDH-ES+A256KW',
],
[],
'foo,bar,baz'
);
$jwe = $jwe->addRecipientInformation(
$this->getECDHRecipientPublicKey()
);
$encrypter->encrypt($jwe);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($jwe->toFlattenedJSON(0));
$decrypter = Decrypter::createDecrypter(['A256GCM'], ['ECDH-ES+A256KW'], ['DEF'], new FakeLogger());
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('ECDH-ES+A256KW', $loaded->getSharedProtectedHeader('alg'));
self::assertEquals('A256GCM', $loaded->getSharedProtectedHeader('enc'));
self::assertFalse($loaded->hasSharedProtectedHeader('zip'));
self::assertFalse($loaded->hasSharedHeader('zip'));
self::assertNull($loaded->getPayload());
$decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index);
self::assertEquals(0, $index);
self::assertTrue(is_string($loaded->getPayload()));
self::assertEquals('Live long and Prosper.', $loaded->getPayload());
}
public function testEncryptAndLoadCompactKeyAgreementWithWrapping()
{
$encrypter = Encrypter::createEncrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$decrypter = Decrypter::createDecrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger());
$jwe = JWEFactory::createJWE('Live long and Prosper.');
$jwe = $jwe->withSharedProtectedHeaders(['enc' => 'A256CBC-HS512']);
$jwe = $jwe->addRecipientInformation(
$this->getECDHRecipientPublicKey(),
['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW']
);
$jwe = $jwe->addRecipientInformation(
$this->getRSARecipientKey(),
['kid' => '123456789', 'alg' => 'RSA-OAEP-256']
);
$encrypter->encrypt($jwe);
$loader = new Loader(new FakeLogger());
$loaded = $loader->load($jwe->toJSON());
self::assertEquals(2, $loaded->countRecipients());
self::assertInstanceOf(JWEInterface::class, $loaded);
self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc'));
self::assertEquals('ECDH-ES+A256KW', $loaded->getRecipient(0)->getHeader('alg'));
self::assertEquals('RSA-OAEP-256', $loaded->getRecipient(1)->getHeader('alg'));
self::assertFalse($loaded->hasSharedHeader('zip'));
self::assertFalse($loaded->hasSharedProtectedHeader('zip'));
self::assertNull($loaded->getPayload());
$decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index);
self::assertEquals(0, $index);
self::assertTrue(is_string($loaded->getPayload()));
self::assertEquals('Live long and Prosper.', $loaded->getPayload());
}
/**
* @return JWK
*/
private function getKeyToEncrypt()
{
$key = new JWK([
'kty' => 'EC',
'use' => 'enc',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI',
]);
return $key;
}
/**
* @return JWKSet
*/
private function getKeySetToEncrypt()
{
$key = new JWK([
'kty' => 'EC',
'use' => 'enc',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI',
]);
$key_set = new JWKSet();
$key_set->addKey($key);
return $key_set;
}
/**
* @return JWK
*/
private function getRSARecipientKey()
{
$key = new JWK([
'kty' => 'RSA',
'use' => 'enc',
'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw',
'e' => 'AQAB',
]);
return $key;
}
/**
* @return JWK
*/
private function getRSARecipientKeyWithAlgorithm()
{
$key = new JWK([
'kty' => 'RSA',
'use' => 'enc',
'alg' => 'RSA-OAEP',
'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw',
'e' => 'AQAB',
]);
return $key;
}
/**
* @return JWK
*/
private function getSigningKey()
{
$key = new JWK([
'kty' => 'EC',
'key_ops' => ['sign', 'verify'],
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI',
]);
return $key;
}
/**
* @return JWK
*/
private function getECDHRecipientPublicKey()
{
$key = new JWK([
'kty' => 'EC',
'key_ops' => ['encrypt', 'decrypt'],
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
]);
return $key;
}
/**
* @return JWK
*/
private function getDirectKey()
{
$key = new JWK([
'kid' => 'DIR_1',
'key_ops' => ['encrypt', 'decrypt'],
'kty' => 'oct',
'k' => Base64Url::encode(hex2bin('00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F')),
]);
return $key;
}
}
| Spomky-Labs/jose | tests/Functional/EncrypterBaseTest.php | PHP | mit | 25,820 |
// Fill out your copyright notice in the Description page of Project Settings.
using UnrealBuildTool;
using System.Collections.Generic;
public class UnrealCamDemoTarget : TargetRules
{
public UnrealCamDemoTarget(TargetInfo Target) : base(Target)
{
Type = TargetType.Game;
ExtraModuleNames.AddRange( new string[] { "UnrealCamDemo" } );
}
}
| mrayy/UnityCam | UnrealCamDemo/Source/UnrealCamDemo.Target.cs | C# | mit | 349 |
package br.com.gamemods.tutorial.ctf;
import org.bukkit.plugin.java.JavaPlugin;
public class CTFGameMods extends JavaPlugin
{
}
| joserobjr/CTFGameMods | src/main/java/br/com/gamemods/tutorial/ctf/CTFGameMods.java | Java | mit | 131 |
'use strict';
var emojiArr = require('./emojis');
var i = 0;
var existingRules = {};
var generateEmoji = function(selector) {
if (!existingRules[selector]) {
existingRules[selector] = emojiArr[i];
if (i !== emojiArr.length) {
i++
} else {
i = 0;
}
}
return existingRules[selector];
}
module.exports = generateEmoji;
| thuongvu/postcss-emoji | emojify.js | JavaScript | mit | 382 |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookFunctionsBesselIRequest.
/// </summary>
public partial class WorkbookFunctionsBesselIRequest : BaseRequest, IWorkbookFunctionsBesselIRequest
{
/// <summary>
/// Constructs a new WorkbookFunctionsBesselIRequest.
/// </summary>
public WorkbookFunctionsBesselIRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new WorkbookFunctionsBesselIRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookFunctionsBesselIRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsBesselIRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsBesselIRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| ginach/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsBesselIRequest.cs | C# | mit | 3,043 |
# -*- coding: utf-8 -*-
require 'helper'
class TestRegressionSetColumn07 < Test::Unit::TestCase
def setup
setup_dir_var
end
def teardown
File.delete(@xlsx) if File.exist?(@xlsx)
end
def test_set_column07
@xlsx = 'set_column07.xlsx'
workbook = WriteXLSX.new(@xlsx)
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
italic = workbook.add_format(:italic => 1)
bold_italic = workbook.add_format(:bold => 1, :italic => 1)
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15]
]
worksheet.write('A1', 'Foo', italic)
worksheet.write('B1', 'Bar', bold)
worksheet.write('A2', data)
worksheet.set_row(12, nil, italic)
worksheet.set_column('F:F', nil, bold)
worksheet.write('F13', nil, bold_italic)
worksheet.insert_image('E12',
File.join(@test_dir, 'regression', 'images/logo.png'))
workbook.close
compare_xlsx_for_regression(File.join(@regression_output, @xlsx), @xlsx)
end
end
| Orphist/write_xlsx | test/regression/test_set_column07.rb | Ruby | mit | 1,095 |
var fractal = fractal || {};
fractal.workerPaths = {
"mandelbrot": "public/js/mandel.js",
};
fractal.Fractal = function (canvas, workerCount) {
this.canvas = canvas;
this.workerCount = workerCount;
this.workerDoneCount = 0;
this.ctx = canvas.getContext("2d");
this.width = canvas.width;
this.height = canvas.height;
this.workerPath = fractal.workerPaths["mandelbrot"];
this.topLeft = new Complex(-1.5, 1.1);
this.bottomRight = new Complex(0.8, -1.1);
this.maxIter = 1200;
var lingrad = this.ctx.createLinearGradient(0, 0, this.width, 0);
lingrad.addColorStop(0, '#00f');
lingrad.addColorStop(0.1, '#fa0');
lingrad.addColorStop(0.5, '#ff0');
lingrad.addColorStop(0.7, '#f1b');
lingrad.addColorStop(1, '#fff');
this.ctx.fillStyle = lingrad;
this.ctx.fillRect(0, 0, this.width, 2);
this.gradientImage = this.ctx.getImageData(0, 0, this.width, 1);
this.imgData = this.ctx.getImageData(0, 0, this.width, this.height);
this.ondone = null;
this.workers = [];
};
fractal.Fractal.prototype = function () {
var computeRow = function (workerIndex, row) {
var args = {
action: "computeRow",
row: row,
workerIndex: workerIndex
};
this.workers[workerIndex].postMessage(args);
};
var initializeWorker = function (workerIndex) {
var drow = (this.bottomRight.imag - this.topLeft.imag) / this.height;
var dcol = (this.bottomRight.real - this.topLeft.real) / this.width;
var args = {
action: "setup",
maxIter: this.maxIter,
width: this.width,
height: this.height,
topLeft: this.topLeft,
bottomRight: this.bottomRight,
drow: drow,
dcol: dcol,
workerIndex: workerIndex,
juliaPoint: this.juliaPoint
};
this.workers[workerIndex].postMessage(args);
};
var createWorkers = function (workerPath) {
var obj = this;
var rowData = obj.ctx.createImageData(obj.width, 1);
for (var workerIndex = 0; workerIndex < obj.workerCount; workerIndex++) {
obj.workers[workerIndex] = new Worker(obj.workerPath);
this.workers[workerIndex].onmessage = function (event) {
if (event.data.logData) {
console.log("Worker: " + event.data.logData);
}
if (event.data.row >= 0) {
var wIndex = event.data.workerIndex;
for (var index = 0; index < obj.width; index++) {
var color = getColor.call(obj, event.data.iterData[index]);
var destIndex = 4 * index;
rowData.data[destIndex] = color.red;
rowData.data[destIndex + 1] = color.green;
rowData.data[destIndex + 2] = color.blue;
rowData.data[destIndex + 3] = color.alpha;
}
obj.ctx.putImageData(rowData, 0, event.data.row);
if (obj.nextRow < obj.height) {
console.log("Worker: " + wIndex, " nextRow: " + obj.nextRow);
computeRow.call(obj, wIndex, obj.nextRow);
obj.nextRow = obj.nextRow + 1;
} else {
obj.workerDoneCount++;
if (obj.workerDoneCount == obj.workerCount) {
var duration = new Date().getTime() - obj.startTime;
if (typeof obj.ondone === 'function') {
obj.ondone(duration);
}
}
}
}
};
}
};
var getColor = function (iter) {
if (iter == this.maxIter) {
return { red: 0, green: 0, blue: 0, alpha: 255 };
}
var index = (iter % this.gradientImage.width) * 4;
return {
red: this.gradientImage.data[index],
green: this.gradientImage.data[index + 1],
blue: this.gradientImage.data[index + 2],
alpha: this.gradientImage.data[index + 3]
};
},
render = function () {
this.startTime = new Date().getTime();
this.workerDoneCount = 0;
createWorkers.call(this, this.workerPath);
this.nextRow = this.workerCount;
for (var workerIndex = 0; workerIndex < this.workerCount; workerIndex++) {
initializeWorker.call(this, workerIndex);
computeRow.call(this, workerIndex, workerIndex);
}
}
return {
render: render
};
} ();
jQuery(function($) {
var fra = new fractal.Fractal(document.getElementById("fractal"), 2);
$('#draw-fractal').on('click',function() {
fra.render();
});
});
| hectoregm/hectoregm | Practica3/public/js/canvas_fractal.js | JavaScript | mit | 4,312 |
describe('raureif', function () {
it('test', function () {
});
});
| chrmod/raureif | tests/node/index-test.js | JavaScript | mit | 71 |
/**
* @file ui/core/styleguide/index//html/01-body/40-main/main.js
* @description Listeners on the body, iframe, and rightpull bar.
*/
/* istanbul ignore if */
if (typeof window === 'object') {
document.addEventListener('DOMContentLoaded', () => {
const $orgs = FEPPER_UI.requerio.$orgs;
const {
uiFns,
uiProps
} = FEPPER_UI;
$orgs['#sg-rightpull'].on('mouseenter', function () {
$orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-hover');
});
$orgs['#sg-rightpull'].on('mouseleave', function () {
$orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover');
});
// Handle manually resizing the viewport.
// 1. On "mousedown" store the click location.
// 2. Make a hidden div visible so that the cursor doesn't get lost in the iframe.
// 3. On "mousemove" calculate the math, save the results to a cookie, and update the viewport.
$orgs['#sg-rightpull'].on('mousedown', function (e) {
uiProps.sgRightpull.posX = e.pageX;
uiProps.sgRightpull.vpWidth = uiProps.vpWidth;
// Show the cover.
$orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-drag');
});
// Add the mouse move event and capture data. Also update the viewport width.
$orgs['#patternlab-body'].on('mousemove', function (e) {
if ($orgs['#sg-cover'].getState().classArray.includes('shown-by-rightpull-drag')) {
let vpWidthNew = uiProps.sgRightpull.vpWidth;
if (uiProps.dockPosition === 'bottom') {
vpWidthNew += 2 * (e.pageX - uiProps.sgRightpull.posX);
}
else {
vpWidthNew += e.pageX - uiProps.sgRightpull.posX;
}
if (vpWidthNew > uiProps.minViewportWidth) {
uiFns.sizeIframe(vpWidthNew, false);
}
}
});
// Handle letting go of rightpull bar after dragging to resize.
$orgs['#patternlab-body'].on('mouseup', function () {
uiProps.sgRightpull.posX = null;
uiProps.sgRightpull.vpWidth = null;
$orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover');
$orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-drag');
});
});
}
| electric-eloquence/fepper-npm | ui/core/styleguide/index/html/01-body/40-main/main.js | JavaScript | mit | 2,224 |
<?php
namespace Checkdomain\Holiday;
use Checkdomain\Holiday\Model\Holiday;
/**
* Class Util
*/
class Util
{
/**
* Instantiates a provider for a given iso code
*
* @param string $iso
*
* @return ProviderInterface
*/
protected function getProvider($iso)
{
$instance = null;
$class = '\\Checkdomain\\Holiday\\Provider\\' . $iso;
if (class_exists($class)) {
$instance = new $class;
}
return $instance;
}
/**
* @param \DateTime|string $date
*
* @return \DateTime
*/
protected function getDateTime($date)
{
if (!$date instanceof \DateTime) {
$date = new \DateTime($date);
}
return $date;
}
/**
* @param string $iso
*
* @return string
*/
protected function getIsoCode($iso)
{
return strtoupper($iso);
}
/**
* Checks wether a given date is a holiday
*
* This method can be used to check whether a specific date is a holiday
* in a specified country and state
*
* @param string $iso
* @param \DateTime|string $date
* @param string $state
*
* @return bool
*/
public function isHoliday($iso, $date = 'now', $state = null)
{
return ($this->getHoliday($iso, $date, $state) !== null);
}
/**
* Provides detailed information about a specific holiday
*
* @param string $iso
* @param \DateTime|string $date
* @param string $state
*
* @return Holiday|null
*/
public function getHoliday($iso, $date = 'now', $state = null)
{
$iso = $this->getIsoCode($iso);
$date = $this->getDateTime($date);
$provider = $this->getProvider($iso);
$holiday = $provider->getHolidayByDate($date, $state);
return $holiday;
}
}
| checkdomain/Holiday | src/Util.php | PHP | mit | 1,932 |
namespace Votter.Services
{
using System;
using System.Linq;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Votter.Services.Startup))]
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
this.ConfigureAuth(app);
}
}
} | Team-Papaya-Web-Services-and-Cloud/Web-Services-and-Cloud-Teamwork-2014 | Votter/Votter.Services/Startup.cs | C# | mit | 331 |
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CharCounterMain{
final static Charset enc = StandardCharsets.US_ASCII ;
public CharCounterMain(String ch, String filedir){
if(ch.length() != 1){
System.out.println("The first argument needs to be a char, found string of length "+ch.length());
System.exit(1);
}
char c = ch.charAt(0);
if( c != ' ' && c != '.' && Character.getNumericValue(c) < 97 && Character.getNumericValue(c) > 122 ){ //compare against the ascii integer values
System.out.println("Need a character in range a-z (lowercase only) or a whitespace or a dot, found "+c+"!");
System.exit(1);
}
Path p = Paths.get(filedir);
try {
BufferedReader bf = Files.newBufferedReader(p,enc);
String line;
String line2 = null ;
while((line = bf.readLine()) != null){
line2 += line ;
}
CharCounter cc = new CharCounter(c,line2);
int freq = cc.getFrequency();
System.out.println(String.format("Frequency of character %c was %d", c,freq));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished, exiting...");
}
public static void main(String[] args){
if(args.length != 2){
System.out.println("Usage : CharCounterMain <char-to-look-for> <text-file-dir>");
}else{
new CharCounterMain(args[0],args[1]);
}
}
}
| dperezmavro/courseworks_uni | year_3/large_scale_and_distributed_systems/src/CharCounterMain.java | Java | mit | 1,792 |
"use strict";
(function() {
// "todos-angular" is just a hard-code id for storage
var LOCAL_STORAGE_KEY = 'todos-angular';
var ENTER_KEY = 13;
var ESC_KEY = 27;
var internalFilters = {
active: function(toDoItem) {
return !toDoItem.completed;
},
completed: function(toDoItem) {
return toDoItem.completed;
}
};
angular.module('ToDoAngular', ['ngRoute'])
.service('storage', function($q) {
// Storage service
return {
save: function(toDoCollection) {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(toDoCollection));
},
load: function() {
var itemCollectionString = localStorage.getItem(LOCAL_STORAGE_KEY);
return itemCollectionString && JSON.parse(itemCollectionString) || [];
}
}
})
.directive('escHandler', function() {
// Define directive for esc key
return {
restrict: 'A',
link: function(scope, iElement, iAttrs) {
function keyEventHandler(event) {
if (event.keyCode === ESC_KEY) {
scope.$apply(iAttrs.escHandler);
}
}
iElement.on('keydown', keyEventHandler);
scope.$on('$destroy', function() {
iElement.off('keydown', keyEventHandler);
});
}
};
})
.directive('enterHandler', function() {
// Define directive for enter key
return {
restrict: 'A',
link: function (scope, iElement, iAttrs) {
function keyEventHandler(event) {
if (event.keyCode === ENTER_KEY) {
scope.$apply(iAttrs.enterHandler);
}
}
iElement.on('keydown', keyEventHandler);
scope.$on('$destroy', function () {
iElement.off('keydown', keyEventHandler);
});
}
};
})
.directive('selectAndFocus', function($timeout) {
// Define directive for focus
return {
restrict: 'A',
link: function(scope, iElement, iAttrs) {
var focusPromise;
scope.$watch(iAttrs.selectAndFocus, function(newValue) {
if (newValue && !focusPromise) {
focusPromise = $timeout(function focus() {
focusPromise = null;
iElement[0].focus();
}, 0, false);
}
});
scope.$on('$destroy', function() {
if (focusPromise) {
$timeout.cancel(focusPromise);
focusPromise = null;
}
});
}
};
})
.directive('toDoItem', function() {
// Define directive for to-do item
return {
restrict: 'A',
templateUrl: 'angular-item-template.html',
scope: {
itemViewModel: '=toDoItem'
},
link: function (scope, iElement, iAttrs) {
scope.editing = false;
scope.originalTitle = '';
scope.$watch('itemViewModel.toDoItem.completed', function(newCompleted) {
iElement.toggleClass('completed', newCompleted);
});
scope.$watch('editing', function(newEditing) {
iElement.toggleClass('editing', newEditing);
});
scope.$watch('itemViewModel.isHidden', function(newHidden) {
iElement.toggleClass('hidden', newHidden);
});
scope.$watchGroup([
'itemViewModel.toDoItem.title',
'itemViewModel.toDoItem.completed'], function() {
scope.$emit('item-updated');
});
scope.destroy = function() {
scope.$emit('remove-item', scope.itemViewModel);
};
scope.edit = function() {
scope.originalTitle = scope.itemViewModel.toDoItem.title;
scope.editing = true;
};
scope.update = function() {
var title = scope.itemViewModel.toDoItem.title || '';
var trimmedTitle = title.trim();
if (scope.editing) {
if (title !== trimmedTitle) {
scope.itemViewModel.toDoItem.title = trimmedTitle;
}
if (!trimmedTitle) {
scope.destroy();
}
scope.editing = false;
}
};
scope.revert = function() {
scope.editing = false;
scope.itemViewModel.toDoItem.title = scope.originalTitle;
};
}
};
})
.controller('AppController', function AppController(
$scope, $routeParams, storedToDoCollection, storage) {
// Define app controller
$scope.toDoCollection = storedToDoCollection.map(function(storedToDo) {
return {
toDoItem: storedToDo,
isHidden: $scope.filter ? !$scope.filter(storedToDo): false
};
});
$scope.currentTitle = '';
$scope.$on('$routeChangeSuccess', function() {
var filterString = $routeParams.filter;
if (filterString && (filterString in internalFilters)) {
$scope.filterString = filterString;
$scope.filter = internalFilters[filterString];
} else {
$scope.filterString = '';
$scope.filter = null;
}
});
function save() {
storage.save($scope.toDoCollection.map(function(toDoViewModel) {
return toDoViewModel.toDoItem;
}));
}
$scope.$watch('filter', function(newFilter) {
$scope.toDoCollection.forEach(function(toDoViewModel) {
toDoViewModel.isHidden = newFilter ? !newFilter(toDoViewModel.toDoItem) : false;
});
});
$scope.$watch(function() {
return $scope.toDoCollection.filter(function(toDoViewModel){
return !toDoViewModel.toDoItem.completed;
}).length;
}, function(newValue) {
if (newValue == null) {
$scope.remainingLabel = '';
} else {
$scope.remainingLabel = newValue === 1 ?
(newValue + ' item left') :
(newValue + ' items left');
}
});
$scope.$watchCollection('toDoCollection', function() {
save();
});
$scope.$on('item-updated', function() {
save();
});
$scope.$on('remove-item', function(scope, toDoViewModel) {
for(var index = 0; index < $scope.toDoCollection.length; index++) {
if ($scope.toDoCollection[index] === toDoViewModel) {
$scope.toDoCollection.splice(index, 1);
return;
}
}
});
$scope.create = function() {
var currentTitle = $scope.currentTitle.trim();
if (currentTitle) {
var toDoItem = {
title: currentTitle,
completed: false
};
var toDoItemViewModel = {
toDoItem: toDoItem,
isHidden: $scope.filter ? !$scope.filter(toDoItem): false
};
$scope.toDoCollection.push(toDoItemViewModel);
$scope.currentTitle = '';
}
};
})
.config(function($routeProvider) {
// Define routing
var routeConfig = {
controller: 'AppController',
templateUrl: 'angular-app-template.html',
resolve: {
storedToDoCollection: function(storage) {
return storage.load();
}
}
};
$routeProvider
.when('/', routeConfig)
.when('/:filter', routeConfig)
.otherwise({
redirectTo: '/'
});
});
})();
| sasyomaru/advanced-javascript-training-material | module3/scripts/angular-app.js | JavaScript | mit | 9,478 |
<?php
namespace Params;
/**
* @codeCoverageIgnore
*/
trait SafeAccess
{
public function __set($name, $value)
{
throw new \Exception("Property [$name] doesn't exist for class [".get_class($this)."] so can't set it");
}
public function __get($name)
{
throw new \Exception("Property [$name] doesn't exist for class [".get_class($this)."] so can't get it");
}
}
| Danack/Blog | vendor/danack/params/lib/Params/SafeAccess.php | PHP | mit | 403 |
from decimal import Decimal
from django import forms
from django.template.loader import render_to_string
from django.template.defaultfilters import slugify
class BaseWidget(forms.TextInput):
"""
Base widget. Do not use this directly.
"""
template = None
instance = None
def get_parent_id(self, name, attrs):
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
return final_attrs['id']
def get_widget_id(self, prefix, name, key=''):
if self.instance:
opts = self.instance._meta
widget_id = '%s-%s-%s_%s-%s' % (prefix, name, opts.app_label, opts.module_name, self.instance.pk)
else:
widget_id = '%s-%s' % (prefix, name)
if key:
widget_id = '%s_%s' % (widget_id, slugify(key))
return widget_id
def get_values(self, min_value, max_value, step=1):
decimal_step = Decimal(str(step))
value = Decimal(str(min_value))
while value <= max_value:
yield value
value += decimal_step
class SliderWidget(BaseWidget):
"""
Slider widget.
In order to use this widget you must load the jQuery.ui slider
javascript.
This widget triggers the following javascript events:
- *slider_change* with the vote value as argument
(fired when the user changes his vote)
- *slider_delete* without arguments
(fired when the user deletes his vote)
It's easy to bind these events using jQuery, e.g.::
$(document).bind('slider_change', function(event, value) {
alert('New vote: ' + value);
});
"""
def __init__(self, min_value, max_value, step, instance=None,
can_delete_vote=True, key='', read_only=False, default='',
template='ratings/slider_widget.html', attrs=None):
"""
The argument *default* is used when the initial value is None.
"""
super(SliderWidget, self).__init__(attrs)
self.min_value = min_value
self.max_value = max_value
self.step = step
self.instance = instance
self.can_delete_vote = can_delete_vote
self.read_only = read_only
self.default = default
self.template = template
self.key = key
def get_context(self, name, value, attrs=None):
# here we convert *min_value*, *max_value*, *step* and *value*
# to string to avoid odd behaviours of Django localization
# in the template (and, for backward compatibility we do not
# want to use the *unlocalize* filter)
attrs['type'] = 'hidden'
return {
'min_value': str(self.min_value),
'max_value': str(self.max_value),
'step': str(self.step),
'can_delete_vote': self.can_delete_vote,
'read_only': self.read_only,
'default': self.default,
'parent': super(SliderWidget, self).render(name, value, attrs),
'parent_id': self.get_parent_id(name, attrs),
'value': str(value),
'has_value': bool(value),
'slider_id': self.get_widget_id('slider', name, self.key),
'label_id': 'slider-label-%s' % name,
'remove_id': 'slider-remove-%s' % name,
}
def render(self, name, value, attrs=None):
context = self.get_context(name, value, attrs or {})
return render_to_string(self.template, context)
class StarWidget(BaseWidget):
"""
Starrating widget.
In order to use this widget you must download the
jQuery Star Rating Plugin available at
http://www.fyneworks.com/jquery/star-rating/#tab-Download
and then load the required javascripts and css, e.g.::
<link href="/path/to/jquery.rating.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/path/to/jquery.MetaData.js"></script>
<script type="text/javascript" src="/path/to/jquery.rating.js"></script>
This widget triggers the following javascript events:
- *star_change* with the vote value as argument
(fired when the user changes his vote)
- *star_delete* without arguments
(fired when the user deletes his vote)
It's easy to bind these events using jQuery, e.g.::
$(document).bind('star_change', function(event, value) {
alert('New vote: ' + value);
});
"""
def __init__(self, min_value, max_value, step, instance=None,
can_delete_vote=True, key='', read_only=False,
template='ratings/star_widget.html', attrs=None):
super(StarWidget, self).__init__(attrs)
self.min_value = min_value
self.max_value = max_value
self.step = step
self.instance = instance
self.can_delete_vote = can_delete_vote
self.read_only = read_only
self.template = template
self.key = key
def get_context(self, name, value, attrs=None):
# here we convert *min_value*, *max_value* and *step*
# to string to avoid odd behaviours of Django localization
# in the template (and, for backward compatibility we do not
# want to use the *unlocalize* filter)
attrs['type'] = 'hidden'
split_value = int(1 / self.step)
if split_value == 1:
values = range(1, self.max_value+1)
split = u''
else:
values = self.get_values(self.min_value, self.max_value, self.step)
split = u' {split:%d}' % split_value
return {
'min_value': str(self.min_value),
'max_value': str(self.max_value),
'step': str(self.step),
'can_delete_vote': self.can_delete_vote,
'read_only': self.read_only,
'values': values,
'split': split,
'parent': super(StarWidget, self).render(name, value, attrs),
'parent_id': self.get_parent_id(name, attrs),
'value': self._get_value(value, split_value),
'star_id': self.get_widget_id('star', name, self.key),
}
def _get_value(self, original, split):
if original:
value = round(original * split) / split
return Decimal(str(value))
def render(self, name, value, attrs=None):
context = self.get_context(name, value, attrs or {})
return render_to_string(self.template, context)
class LikeWidget(BaseWidget):
def __init__(self, min_value, max_value, instance=None,
can_delete_vote=True, template='ratings/like_widget.html', attrs=None):
super(LikeWidget, self).__init__(attrs)
self.min_value = min_value
self.max_value = max_value
self.instance = instance
self.can_delete_vote = can_delete_vote
self.template = template
def get_context(self, name, value, attrs=None):
# here we convert *min_value*, *max_value* and *step*
# to string to avoid odd behaviours of Django localization
# in the template (and, for backward compatibility we do not
# want to use the *unlocalize* filter)
attrs['type'] = 'hidden'
return {
'min_value': str(self.min_value),
'max_value': str(self.max_value),
'can_delete_vote': self.can_delete_vote,
'parent': super(LikeWidget, self).render(name, value, attrs),
'parent_id': self.get_parent_id(name, attrs),
'value': str(value),
'like_id': self.get_widget_id('like', name),
}
def render(self, name, value, attrs=None):
context = self.get_context(name, value, attrs or {})
return render_to_string(self.template, context) | redsolution/django-generic-ratings | ratings/forms/widgets.py | Python | mit | 7,704 |
define(function() {
return {
draw: function(context, t) {
var x = this.getNumber("x", t, 100),
y = this.getNumber("y", t, 100),
size = this.getNumber("size", t, 60),
h = this.getNumber("h", t, 40),
colorLeft = this.getColor("colorLeft", t, "#999999"),
colorRight = this.getColor("colorRight", t, "#cccccc"),
colorTop = this.getColor("colorTop", t, "#eeeeee"),
scaleX = this.getNumber("scaleX", t, 1),
scaleY = this.getNumber("scaleY", t, 1);
context.translate(x, y);
context.scale(scaleX, scaleY);
if(h >= 0) {
context.fillStyle = colorTop;
context.beginPath();
context.moveTo(-size / 2, -h);
context.lineTo(0, -size / 4 - h);
context.lineTo(size / 2, -h);
context.lineTo(size / 2, -1);
context.lineTo(0, size / 4 - 1);
context.lineTo(-size / 2, -1);
context.lineTo(-size / 2, -h);
this.drawFillAndStroke(context, t, true, false);
context.fillStyle = colorLeft;
context.beginPath();
context.moveTo(-size / 2, 0);
context.lineTo(0, size / 4);
context.lineTo(0, size / 4 - h);
context.lineTo(-size / 2, -h);
context.lineTo(-size / 2, 0);
this.drawFillAndStroke(context, t, true, false);
context.fillStyle = colorRight;
context.beginPath();
context.moveTo(size / 2, 0);
context.lineTo(0, size / 4);
context.lineTo(0, size / 4 - h);
context.lineTo(size / 2, -h);
context.lineTo(size / 2, 0);
this.drawFillAndStroke(context, t, true, false);
}
else {
// clip path
context.beginPath();
context.moveTo(-size / 2, 0);
context.lineTo(0, -size / 4);
context.lineTo(size / 2, 0);
context.lineTo(0, size / 4);
context.lineTo(-size / 2, 0);
context.clip();
context.fillStyle = colorRight;
context.beginPath();
context.moveTo(-size / 2, 0);
context.lineTo(0, -size / 4);
context.lineTo(0, -size / 4 -h);
context.lineTo(-size / 2, -h);
context.lineTo(-size / 2, 0);
this.drawFillAndStroke(context, t, true, false);
context.fillStyle = colorLeft;
context.beginPath();
context.moveTo(size / 2, 0);
context.lineTo(0, -size / 4);
context.lineTo(0, -size / 4 -h);
context.lineTo(size / 2, -h);
context.lineTo(size / 2, 0);
this.drawFillAndStroke(context, t, true, false);
context.fillStyle = colorTop;
context.beginPath();
context.moveTo(-size / 2, -h);
context.lineTo(0, -size / 4 - h);
context.lineTo(size / 2, -h);
context.lineTo(0, size / 4 - h);
context.lineTo(-size / 2, -h);
this.drawFillAndStroke(context, t, true, false);
}
}
}
});
| bit101/gifloopcoder | src/src/app/render/shapes/isobox.js | JavaScript | mit | 2,755 |
<?php namespace BoundedContext\Contracts\Generator;
use BoundedContext\Contracts\ValueObject\Identifier as IdentifierVO;
interface Identifier extends ValueObject
{
/**
* Generates a new random Identifier.
*
* @return IdentifierVO
*/
public function generate();
/**
* Generates a null Identifier.
*
* @return IdentifierVO
*/
public function null();
/**
* Generates a new Identifier from a string.
*
* @param string $identifier
* @return IdentifierVO
*/
public function string($identifier);
}
| lyonscf/bounded-context | src/Contracts/Generator/Identifier.php | PHP | mit | 587 |
<?php
return array (
'id' => 'softbank_v702nk2_ver1',
'fallback' => 'softbank_generic',
'capabilities' =>
array (
'physical_screen_height' => '41',
'columns' => '15',
'physical_screen_width' => '34',
'max_image_width' => '176',
'rows' => '6',
'resolution_width' => '176',
'resolution_height' => '208',
'max_image_height' => '173',
'colors' => '262144',
'max_deck_size' => '357000',
'mms_max_size' => '307200',
'mms_max_width' => '640',
'mms_max_height' => '480',
'nokia_series' => '60',
'nokia_feature_pack' => '2',
'nokia_edition' => '2',
'model_name' => '702NKII(NOKIA 6680)',
'uaprof' => 'http://nds1.nds.nokia.com/uaprof/N6680r100-VFKK3G.xml',
'model_extra_info' => 'Vodafone',
'release_date' => '2005_may',
'directdownload_support' => 'true',
'oma_support' => 'true',
'aac' => 'true',
'mp3' => 'true',
'oma_v_1_0_separate_delivery' => 'true',
'flash_lite_version' => '',
'xhtml_file_upload' => 'supported',
),
);
| cuckata23/wurfl-data | data/softbank_v702nk2_ver1.php | PHP | mit | 1,037 |
package com.company;
import java.util.Scanner;
public class Greeting {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String firstName = scanner.nextLine();
String lastName = scanner.nextLine();
int age = Integer.parseInt(scanner.nextLine());
System.out.printf("Hello, %s %s. You are %d years old.", firstName, lastName, age);
}
}
| ivelin1936/Studing-SoftUni- | Programming Fundamentals/DataTypesAndVariables-Lab/src/com/company/Greeting.java | Java | mit | 419 |
package sbahjsic.runtime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import sbahjsic.core.Warnings;
import sbahjsic.core.Warnings.Level;
import sbahjsic.runtime.Operator.BiOperator;
import sbahjsic.runtime.Operator.UnOperator;
import sbahjsic.runtime.Operator.VarargOperator;
import sbahjsic.runtime.type.AnyType;
import sbahjsic.runtime.type.SVoid;
/** Describes a Sbahjsic type.
*
* <p>For all subclasses, there must only exist one instance. To enforce
* this, this class implements final {@code equals()} and {@code hashCode()}
* methods as they are defined in {@code Object}.*/
public abstract class Type {
private final Map<String, Operator> operators = new HashMap<>();
private final Set<Type> supertypes = new HashSet<>();
private final Set<String> fields = new HashSet<>();
private final Map<String, Method> methods = new HashMap<>();
private int priority = 0;
protected Type() {
// Fixes a bug where AnyType tried to add AnyType.INSTANCE, which
// was null at that point, to its own supertypes
if(!getClass().equals(AnyType.class)) {
addSupertype(AnyType.INSTANCE);
}
}
/** Registers a new supertype for this type.
* @param supertype the new supertype*/
public final void addSupertype(Type supertype) {
if(getSupertypes().contains(supertype) || supertype.getSupertypes().contains(this)) {
throw new RecursiveTypedefException(this.toString());
}
if(this != supertype) {
supertypes.add(supertype);
}
}
/** Removes a supertype from this type if it exists.
* @param supertype the supertype to remove*/
public final void removeSupertype(Type supertype) {
supertypes.remove(supertype);
}
/** Registers an unary operator for this type.
* @param op the operator to register
* @param func a function that applies this operator*/
public final void addUnOperator(String op, UnOperator func) {
operators.put(op, Operator.unaryOperator(func));
}
/** Registers a binary operator for this type.
* @param op the operator to register
* @param func a function that applies this operator*/
public final void addBiOperator(String op, BiOperator func) {
operators.put(op, Operator.binaryOperator(func));
}
/** Adds an operator that can accept one or two arguments.
* @param op the operator
* @param unary the unary operator
* @param binary the binary operator*/
protected final void addDoubleOperator(String op, UnOperator unary, BiOperator binary) {
operators.put(op, (con, args) -> {
if(args.length == 1)
return unary.apply(con, args[0]);
else if(args.length == 2)
return binary.apply(con, args[0], args[1]);
throw new OperatorCallException("Called with " + args.length +
" arguments, expected 1 or 2");
});
}
/** Registers a vararg operator for this type.*/
public void addVarargOperator(String op, VarargOperator func) {
operators.put(op, Operator.varargOperator(func));
}
/** Adds a field to this type.
* @param field the field to add*/
protected final void addField(String field) {
fields.add(field);
}
/** Returns a specific operator of this type.
* @param op the operator to search
* @return the operator matching {@code op}
* @throws OperatorCallException if {@code op} isn't defined*/
public final Operator getOperator(String op) {
if(operators.containsKey(op)) {
return operators.get(op);
}
Operator operator = operatorLookup(op);
if(operator == null) {
throw new OperatorCallException("Operator " + op + " not defined on type " + getName());
}
return operator;
}
private final Operator operatorLookup(String op) {
for(Type supertype : supertypes) {
if(supertype.operators.containsKey(op)) {
return supertype.operators.get(op);
}
}
for(Type supertype : supertypes) {
Operator operator = supertype.operatorLookup(op);
if(operator != null) { return operator; }
}
return null;
}
/** Returns a set of all defined operators of this type.
* @return a set of the defined operators of this type*/
public final Set<String> getDefinedOperators() {
Set<String> ops = new HashSet<>();
ops.addAll(operators.keySet());
for(Type supertype : getSupertypes()) {
ops.addAll(supertype.getDefinedOperators());
}
return ops;
}
/** Returns a set of the supertypes of this type.
* @return a set of the supertypes of this type*/
public final Set<Type> getSupertypes() {
Set<Type> types = new HashSet<>();
types.addAll(supertypes);
for(Type supertype : supertypes) {
types.addAll(supertype.getSupertypes());
}
return types;
}
/** Returns the fields declared for this type.
* @return a set of fields declared for this type*/
public final Set<String> getFields() {
Set<String> allFields = new HashSet<>();
allFields.addAll(fields);
for(Type supertype : getSupertypes()) {
allFields.addAll(supertype.getFields());
}
return allFields;
}
/** Adds a method to this type.
* @param name the name of the method
* @param method the method*/
public final void addMethod(String name, Method method) {
methods.put(name, method);
}
/** Returns all methods defined for this type.
* @return all methods defined for this type*/
public final Set<String> getMethods() {
Map<String, Method> allMethods = new HashMap<>();
allMethods.putAll(methods);
for(Type supertype : getSupertypes()) {
allMethods.putAll(supertype.methods);
}
return allMethods.keySet();
}
/** Returns a method of this type.
* @param name the name of the method
* @return the method
* @throws MethodCallException if the method isn't defined for this type*/
public final Method getMethod(String name) {
if(methods.containsKey(name)) {
return methods.get(name);
}
Method method = methodLookup(name);
if(method == null) {
throw new MethodCallException("Method " + name + " not defined for type " + getName());
}
return method;
}
private final Method methodLookup(String name) {
for(Type supertype : supertypes) {
if(supertype.methods.containsKey(name)) {
return supertype.methods.get(name);
}
}
for(Type supertype : supertypes) {
Method method = supertype.methodLookup(name);
if(method != null) { return method; }
}
return null;
}
/** Returns the name of this type.
* @return the name of this type*/
public abstract String getName();
/** Casts a value to this type.
* @param object the value to cast
* @return the casted value*/
public SValue cast(SValue object) {
Warnings.warn(Level.ADVICE, "Undefined cast from " + object.getType() + " to " + this);
return object;
}
/** Returns whether this type is the subtype of some other type. That is
* true if this type or any if its supertypes is the other type.
* @param other the other type
* @return whether this type is the subtype of the other type */
public boolean isSubtype(Type other) {
return this.equals(other) || getSupertypes().contains(other);
}
/** Constructs an instance of this type
* @param context the RuntimeContext
* @param args the arguments passed to the constructor*/
public SValue construct(RuntimeContext context, SValue...args) {
Warnings.warn(Level.NOTIFICATION, "Cannot instantiate " + getName());
return SVoid.VOID;
}
/** Returns the priority of this type, used to determine which operand
* should choose the implementation of a binary operator. Defaults to zero.*/
public int priority() { return priority; }
/** Sets the priority for this type.*/
public void setPriority(int p) {
priority = p;
}
@Override
public final boolean equals(Object o) {
return super.equals(o);
}
@Override
public final int hashCode() {
return super.hashCode();
}
@Override
public final String toString() {
return getName();
}
} | expositionrabbit/Sbahjsic-runtime | src/sbahjsic/runtime/Type.java | Java | mit | 7,839 |
class Person < ActiveRecord::Base
has_many :addresses, dependent: :destroy
accepts_nested_attributes_for :addresses
end
| scotthelm/fencepost | spec/dummy/app/models/person.rb | Ruby | mit | 125 |
import React from 'react';
import {connect} from 'cerebral-view-react';
import styles from './styles.css';
import {
isObject,
isArray,
isString,
isBoolean,
isNumber,
isNull
} from 'common/utils';
import JSONInput from './JSONInput';
import connector from 'connector';
function isInPath(source, target) {
if (!source || !target) {
return false;
}
return target.reduce((isInPath, key, index) => {
if (!isInPath) {
return false;
}
return String(source[index]) === String(key);
}, true);
}
function renderType(value, hasNext, path, propertyKey, highlightPath) {
if (value === undefined) {
return null;
}
if (isArray(value)) {
return (
<ArrayValue
value={value}
hasNext={hasNext}
path={path}
propertyKey={propertyKey}
highlightPath={highlightPath}/>
);
}
if (isObject(value)) {
return (
<ObjectValue
value={value}
hasNext={hasNext}
path={path}
propertyKey={propertyKey}
highlightPath={highlightPath}/>
);
}
return (
<Value
value={value}
hasNext={hasNext}
path={path}
propertyKey={propertyKey}
highlightPath={highlightPath}/>
);
}
class ObjectValue extends React.Component {
static contextTypes = {
options: React.PropTypes.object.isRequired
}
constructor(props, context) {
super(props);
const numberOfKeys = Object.keys(props.value).length;
const isHighlightPath = !!(this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path));
const preventCollapse = this.props.path.length === 0 && context.options.expanded;
this.state = {
isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true)
};
this.onCollapseClick = this.onCollapseClick.bind(this);
this.onExpandClick = this.onExpandClick.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextState.isCollapsed !== this.state.isCollapsed ||
this.context.options.canEdit ||
nextProps.path !== this.props.path ||
nextProps.highlightPath !== this.props.highlightPath
);
}
componentWillReceiveProps(nextProps) {
const context = this.context;
const props = nextProps;
const numberOfKeys = Object.keys(props.value).length;
const isHighlightPath = !!(props.highlightPath && isInPath(props.highlightPath, props.path));
const preventCollapse = props.path.length === 0 && context.options.expanded;
if (this.state.isCollapsed) {
this.setState({
isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true)
});
}
}
onExpandClick() {
this.setState({isCollapsed: false})
}
onCollapseClick() {
this.setState({isCollapsed: true});
}
renderProperty(key, value, index, hasNext, path) {
this.props.path.push(key);
const property = (
<div className={styles.objectProperty} key={index}>
<div className={styles.objectPropertyValue}>{renderType(value, hasNext, path.slice(), key, this.props.highlightPath)}</div>
</div>
);
this.props.path.pop();
return property;
}
renderKeys(keys) {
if (keys.length > 3) {
return keys.slice(0, 3).join(', ') + '...'
}
return keys.join(', ');
}
render() {
const {value, hasNext} = this.props;
const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path);
if (this.state.isCollapsed) {
return (
<div className={isExactHighlightPath ? styles.highlightObject : styles.object} onClick={this.onExpandClick}>
{this.props.propertyKey ? this.props.propertyKey + ': ' : null}
<strong>{'{ '}</strong>{this.renderKeys(Object.keys(value))}<strong>{' }'}</strong>
{hasNext ? ',' : null}
</div>
);
} else if (this.props.propertyKey) {
const keys = Object.keys(value);
return (
<div className={isExactHighlightPath ? styles.highlightObject : styles.object}>
<div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'{ '}</strong></div>
{keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path))}
<div><strong>{' }'}</strong>{hasNext ? ',' : null}</div>
</div>
);
} else {
const keys = Object.keys(value);
return (
<div className={isExactHighlightPath ? styles.highlightObject : styles.object}>
<div onClick={this.onCollapseClick}><strong>{'{ '}</strong></div>
{keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path, this.props.highlightPath))}
<div><strong>{' }'}</strong>{hasNext ? ',' : null}</div>
</div>
);
}
}
}
class ArrayValue extends React.Component {
static contextTypes = {
options: React.PropTypes.object.isRequired
}
constructor(props, context) {
super(props);
const numberOfItems = props.value.length;
const isHighlightPath = this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path);
this.state = {
isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true
};
this.onCollapseClick = this.onCollapseClick.bind(this);
this.onExpandClick = this.onExpandClick.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextState.isCollapsed !== this.state.isCollapsed ||
this.context.options.canEdit ||
nextProps.path !== this.props.path ||
nextProps.highlightPath !== this.props.highlightPath
);
}
componentWillReceiveProps(nextProps) {
const context = this.context;
const props = nextProps;
const numberOfItems = props.value.length;
const isHighlightPath = props.highlightPath && isInPath(props.highlightPath, props.path);
if (this.state.isCollapsed) {
this.setState({
isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true
});
}
}
onExpandClick() {
this.setState({isCollapsed: false})
}
onCollapseClick() {
this.setState({isCollapsed: true});
}
renderItem(item, index, hasNext, path) {
this.props.path.push(index);
const arrayItem = (
<div className={styles.arrayItem} key={index}>
{renderType(item, hasNext, path.slice())}
</div>
);
this.props.path.pop();
return arrayItem;
}
render() {
const {value, hasNext} = this.props;
const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path);
if (this.state.isCollapsed) {
return (
<div className={isExactHighlightPath ? styles.highlightArray : styles.array} onClick={this.onExpandClick}>
{this.props.propertyKey ? this.props.propertyKey + ': ' : null}
<strong>{'[ '}</strong>{value.length}<strong>{' ]'}</strong>
{hasNext ? ',' : null}
</div>
);
} else if (this.props.propertyKey) {
const keys = Object.keys(value);
return (
<div className={isExactHighlightPath ? styles.highlightArray : styles.array}>
<div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'[ '}</strong></div>
{value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))}
<div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div>
</div>
);
} else {
return (
<div className={isExactHighlightPath ? styles.highlightArray : styles.array}>
<div onClick={this.onCollapseClick}><strong>{'[ '}</strong></div>
{value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))}
<div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div>
</div>
);
}
}
}
@connect()
class Value extends React.Component {
static contextTypes = {
options: React.PropTypes.object.isRequired
}
constructor(props) {
super(props);
this.state = {
isEditing: false,
path: props.path.slice()
};
this.onSubmit = this.onSubmit.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onClick = this.onClick.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextProps.value !== this.props.value ||
nextState.isEditing !== this.state.isEditing ||
nextProps.path !== this.props.path
);
}
onClick() {
this.setState({
isEditing: this.context.options.canEdit ? true : false
});
}
onSubmit(value) {
this.props.signals.debugger.modelChanged({
path: this.state.path,
value
})
this.setState({isEditing: false});
connector.sendEvent('changeModel', {
path: this.state.path,
value: value
});
}
onBlur() {
this.setState({isEditing: false});
}
renderValue(value, hasNext) {
const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path);
if (this.state.isEditing) {
return (
<div className={isExactHighlightPath ? styles.highlightValue : null}>
{this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>}
<span>
<JSONInput
value={value}
onBlur={this.onBlur}
onSubmit={this.onSubmit}/>
</span>
{hasNext ? ',' : null}
</div>
);
} else {
return (
<div className={isExactHighlightPath ? styles.highlightValue : null}>
{this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>}
<span onClick={this.onClick}>{isString(value) ? '"' + value + '"' : String(value)}</span>
{hasNext ? ',' : null}
</div>
);
}
}
render() {
let className = styles.string;
if (isNumber(this.props.value)) className = styles.number;
if (isBoolean(this.props.value)) className = styles.boolean;
if (isNull(this.props.value)) className = styles.null;
return (
<div className={className}>
{this.renderValue(this.props.value, this.props.hasNext)}
</div>
);
}
}
class Inspector extends React.Component {
static childContextTypes = {
options: React.PropTypes.object.isRequired
}
getChildContext() {
return {
options: {
expanded: this.props.expanded || false,
canEdit: this.props.canEdit || false
}
}
}
render() {
return renderType(this.props.value, false, [], null, this.props.path);
}
}
export default Inspector;
| cerebral/cerebral-debugger-prototype | versions/v1/components/Debugger/Inspector/index.js | JavaScript | mit | 10,888 |
// Package storagedatalake implements the Azure ARM Storagedatalake service API version 2019-10-31.
//
// Azure Data Lake Storage provides storage for Hadoop and other big data workloads.
package storagedatalake
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultDNSSuffix is the default value for dns suffix
DefaultDNSSuffix = "dfs.core.windows.net"
)
// BaseClient is the base client for Storagedatalake.
type BaseClient struct {
autorest.Client
XMsVersion string
AccountName string
DNSSuffix string
}
// New creates an instance of the BaseClient client.
func New(xMsVersion string, accountName string) BaseClient {
return NewWithoutDefaults(xMsVersion, accountName, DefaultDNSSuffix)
}
// NewWithoutDefaults creates an instance of the BaseClient client.
func NewWithoutDefaults(xMsVersion string, accountName string, dNSSuffix string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
XMsVersion: xMsVersion,
AccountName: accountName,
DNSSuffix: dNSSuffix,
}
}
| Azure/azure-sdk-for-go | services/storage/datalake/2019-10-31/storagedatalake/client.go | GO | mit | 1,358 |
'use strict';
function valuefy(value) {
if (typeof value !== 'object') {
return (typeof value === 'string') ? `"${value}"` : value;
}
let values = [];
if (Array.isArray(value)) {
for (const v of value) {
values.push(valuefy(v));
}
values = `[${values.join(',')}]`;
} else {
for (let v in value) {
if ({}.hasOwnProperty.call(value, v)) {
values.push(`"${v}":${valuefy(value[v])}`);
}
}
values = `{${values.join(',')}}`;
}
return values;
}
function serialize(target) {
if (!target || typeof target !== 'object') {
throw new TypeError('Invalid type of target');
}
let values = [];
for (let t in target) {
if ({}.hasOwnProperty.call(target, t)) {
values.push(`${t}=${valuefy(target[t])}`);
}
}
return values;
}
function extract(t, outter, onlyContent) {
const start = onlyContent ? 1 : 0;
const pad = onlyContent ? 0 : 1;
return t.slice(start, t.lastIndexOf(outter) + pad);
}
function objectify(v) {
if (v[0] === '{') {
return JSON.parse(extract(v, '}'));
} else if (v[0] === '[') {
const set = [];
const es = extract(v, ']', true);
if (es[0] === '[' || es[0] === '{') {
set.push(objectify(es));
} else {
for (const e of es.split(',')) {
set.push(objectify(e));
}
}
return set;
} else if (v[0] === '"') {
v = extract(v, '"', true);
}
return v;
}
function deserialize(values) {
if (!values) {
throw new TypeError('Invalid type of values');
} else if (!Array.isArray(values)) {
values = [values];
}
const target = {};
for (const v of values) {
const fieldValue = v.split('=', 2);
target[fieldValue[0]] = objectify(fieldValue[1]);
}
return target;
}
module.exports = {
pairify: serialize,
parse: deserialize
};
| ragingwind/field-value | index.js | JavaScript | mit | 1,725 |
<?php
namespace App\Notifications\Mship;
use App\Notifications\Notification;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class ForgottenPasswordLink extends Notification implements ShouldQueue
{
use Queueable;
private $token;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($token)
{
parent::__construct();
$this->token = $token;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail', 'database'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$subject = 'SSO Password Reset';
return (new MailMessage)
->from(config('mail.from.address'), 'VATSIM UK Web Services')
->subject($subject)
->view('emails.mship.security.reset_confirmation', ['subject' => $subject, 'recipient' => $notifiable, 'account' => $notifiable, 'token' => route('password.reset', $this->token)]);
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return ['token' => $this->token];
}
}
| atoff/core | app/Notifications/Mship/ForgottenPasswordLink.php | PHP | mit | 1,567 |
export default class TasksService {
static async fetchTasks() {
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await delay(1000);
return [
{ id: 0, description: "task1", status: "Active" },
{ id: 1, description: "task2", status: "Active" },
];
}
}
| guptag/js-frameworks | React/examples/hello-world/src/data/TasksService.js | JavaScript | mit | 308 |
#ifndef RUBY_EXT_UTILS_HPP_
#define RUBY_EXT_UTILS_HPP_ 1
#include <functional>
#include <ruby.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <typeinfo>
#ifdef __GNUC__
#include <cxxabi.h>
#endif
template <typename T>
static const char *
type_name()
{
#ifdef __GNUC__
const int buf_size = 32;
static char tname[buf_size];
if (tname[0] != 0) {
return tname;
}
const std::type_info& id = typeid(T);
int status;
char *name = abi::__cxa_demangle(id.name(), NULL, 0, &status);
if (name != NULL) {
if (status == 0) {
strncpy(tname, name, buf_size - 1);
}
else {
strncpy(tname, id.name(), buf_size - 1);
}
free(name);
}
return tname;
#else
return typeid(T).name();
#endif
}
/*
* undefined reference to ... [g++ (tdm-1) 4.5.2]
*/
// template<typename T>
// static void
// tmp_obj_free(T ptr)
// {
// if (ptr) {
// delete ptr;
// }
// }
// template<typename T>
// static void
// tmp_ary_free(T ptr)
// {
// if (ptr) {
// delete[] ptr;
// }
// }
template<typename T>
static void
tmp_obj_free(void *ptr)
{
if (ptr) {
T obj = static_cast<T>(ptr);
delete obj;
}
}
template<typename T>
static void
tmp_ary_free(void *ptr)
{
if (ptr) {
T obj = static_cast<T>(ptr);
delete[] obj;
}
}
template<typename T>
static inline VALUE
wrap_tmp_obj(T ptr)
{
return Data_Wrap_Struct(rb_cObject, 0, tmp_obj_free<T>, ptr);
}
template<typename T>
static inline VALUE
wrap_tmp_ary(T ptr)
{
return Data_Wrap_Struct(rb_cObject, 0, tmp_ary_free<T>, ptr);
}
void delete_tmp_obj(volatile VALUE *store);
#define delete_tmp_ary(x) delete_tmp_obj(x)
/*
* http://masamitsu-murase.blogspot.jp/2013/12/sevenzipruby-2-c-ruby.html
*/
extern "C" VALUE rxu_run_functor(VALUE p);
#define RXU_PROTECT_FUNC(func) ((VALUE (*)(VALUE))(func))
template<typename T>
static inline
VALUE _rb_protect(T func, int *state)
{
typedef std::function<VALUE ()> func_type;
func_type f = func;
return rb_protect(rxu_run_functor, reinterpret_cast<VALUE>(&f), state);
}
template<typename T1, typename T2>
static inline VALUE
_rb_rescue(T1 func1, T2 func2)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2));
}
#if defined(_MSC_VER) && _MSC_VER <= 1800
template<VALUE& e1, typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL);
}
template<VALUE& e1, VALUE& e2, typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL);
}
template<VALUE& e1, VALUE& e2, VALUE& e3, typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL);
}
template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL);
}
template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, VALUE& e5, typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL);
}
#else
template<VALUE&... exceptions, typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), exceptions..., NULL);
}
#endif
template<typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2, VALUE e1)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL);
}
template<typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL);
}
template<typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL);
}
template<typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL);
}
template<typename T1, typename T2>
static inline VALUE
_rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4, VALUE e5)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_rescue2(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL);
}
template<typename T1, typename T2>
static inline VALUE
_rb_ensure(T1 func1, T2 func2)
{
typedef std::function<VALUE ()> func_type;
func_type f1 = func1;
func_type f2 = func2;
return rb_ensure(
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1),
RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2));
}
extern "C" int rxu_run_functor_foreach(VALUE key, VALUE val, VALUE p);
#define RXU_FOREACH_FUNC(func) ((int (*)(ANYARGS))(func))
template<typename T>
static inline void
_rb_hash_foreach(VALUE obj, T func)
{
typedef std::function<int (VALUE, VALUE)> func_type;
func_type f = func;
rb_hash_foreach(obj, RXU_FOREACH_FUNC(rxu_run_functor_foreach), reinterpret_cast<VALUE>(&f));
}
#endif /* RUBY_EXT_UTILS_HPP_ */
| yagisumi/ruby-gdiplus | ext/gdiplus/ruby_ext_utils.hpp | C++ | mit | 8,156 |
/**
* Vasya Hobot
*
* Copyright (c) 2013-2014 Vyacheslav Slinko
* Licensed under the MIT License
*/
function Message(chat, body) {
this._chat = chat;
this._body = body;
}
Message.prototype.getChat = function() {
return this._chat;
};
Message.prototype.getBody = function() {
return this._body;
};
module.exports = Message;
| vslinko-archive/vasya-hobot | src/client/api/Message.js | JavaScript | mit | 351 |
<?php
namespace PLL\SocialBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
class PostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('content', TextareaType::class, array(
'required' => true,
'label' => false,
))
->add('save', SubmitType::class, array(
'label' => 'timelinepost.label.post',
'translation_domain' => 'forms',
'attr' => array(
'class' => 'post-btn w3-btn w3-theme',
)
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'PLL\SocialBundle\Entity\Post'
));
}
}
?> | Kishlin/Ehub | src/PLL/SocialBundle/Form/Type/PostType.php | PHP | mit | 1,072 |
package septemberpack.september;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import java.util.Random;
/**
* Created by Vlady on 22.10.2015.
*/
/**
* Данный класс реализует отрисовку астероидов
*/
public class Asteroid {
Bitmap bitmap;
/**
* Координаты первого астероида
*/
private int line1x;
private int line1y;
/**
* Координаты второго астероида
*/
private int line2x;
private int line2y;
/**
* Координаты третьего астероида
*/
private int line3x;
private int line3y;
private Random random;
/**
* Конструктор получающий объект картинки будущего астероида и
* задающий астероидам рандомные координаты
* @param bmp - объект картинки астероида
*/
public Asteroid(Bitmap bmp){
this.bitmap = bmp;
random = new Random();
line1x = random.nextInt(880);
line2x = random.nextInt(880);
line3x = random.nextInt(880);
line1y = -random.nextInt(300);
line2y = -random.nextInt(300) - 400; // За пределом экрана минус 400
line3y = -random.nextInt(300) - 800; // За пределом экрана минус 800
}
/**
* Метод отрисовки астероидов
* @param canvas - прямоугольная область экрана для рисования
*/
public void draw(Canvas canvas){
canvas.drawBitmap(bitmap, line1x, line1y, null); // Первая линия
canvas.drawBitmap(bitmap, line2x, line2y, null); // Вторая линия
canvas.drawBitmap(bitmap, line3x, line3y, null); // Третья линия
}
/**
* Метод обновляющий координаты астероидов и задающий новые координаты при уплытии за границы фона
*/
public void update(){
if(line1y > 1400) {
line1y = -80;
line1x = random.nextInt(880);
}
else if(line2y > 1400) {
line2y = -80;
line2x = random.nextInt(880);
}
else if(line3y > 1400) {
line3y = -80;
line3x = random.nextInt(880);
}
line1y += GamePanel.speed;
line2y += GamePanel.speed;
line3y += GamePanel.speed;
}
/*
* Методы возвращают прямоугольную область астероида по его координатам, для проверки столкновения с кораблем
* Реализацию можно было уместить в один метод с четырьмя параметрами, но его вызов был бы нечитаемым
* Поскольку присутствуют всего три астероида, мы имеем возможность сделать для каждого свой метод
*/
public Rect getAsteroid1(){
return new Rect(line1x, line1y, line1x + 100, line1y + 120);
}
public Rect getAsteroid2(){
return new Rect(line2x, line2y, line2x + 100, line2y + 120);
}
public Rect getAsteroid3(){
return new Rect(line3x, line3y, line3x + 100, line3y + 120);
}
}
| vladb55/SeptemberRepository | app/src/main/java/septemberpack/september/Asteroid.java | Java | mit | 3,547 |
import React from 'react';
import { shallow } from 'enzyme';
import UserProfile from '../UserProfile';
import Wrapper from '../Wrapper';
describe('<UserProfile />', () => {
it('should render <Wrapper />', () => {
const wrapper = shallow(<UserProfile />);
expect(wrapper.find(Wrapper).length).toEqual(1);
});
});
| on3iro/Gloomhaven-scenario-creator | src/containers/Auth/tests/UserProfile.test.js | JavaScript | mit | 327 |
class CreateWriMetadataSources < ActiveRecord::Migration[5.1]
def change
create_table :wri_metadata_sources do |t|
t.text :name
t.timestamps
end
end
end
| Vizzuality/climate-watch | db/migrate/20171016113108_create_wri_metadata_sources.rb | Ruby | mit | 177 |
<?php
namespace Davidsneal\MaxCDN\OAuth;
class OAuthDataStore {
function lookup_consumer($consumer_key) {
// implement me
}
function lookup_token($consumer, $token_type, $token) {
// implement me
}
function lookup_nonce($consumer, $token, $nonce, $timestamp) {
// implement me
}
function new_request_token($consumer, $callback = null) {
// return a new token attached to this consumer
}
function new_access_token($token, $consumer, $verifier = null) {
// return a new access token attached to this consumer
// for the user associated with this token if the request token
// is authorized
// should also invalidate the request token
}
}
| davidsneal/laravel-maxcdn | src/MaxCDN/OAuth/OAuthDataStore.php | PHP | mit | 747 |
import React from 'react';
import {
ActivityIndicator,
StyleSheet,
Image,
Text,
View,
ListView,
TouchableOpacity
} from 'react-native';
import Dimensions from 'Dimensions';
const {width, height} = Dimensions.get('window');
import globalVariables from '../globalVariables.js';
import LookCell from './LookCell.js';
import User from './User.js';
import DoneFooter from './DoneFooter.js';
import Icon from 'react-native-vector-icons/Ionicons';
const LookDetail = React.createClass({
getInitialState() {
return {
dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
comments: [],
next:true,
pageNo:1,
animating:true
};
},
getDefaultProps() {
return {
look:{},
navigator:"",
};
},
componentWillMount() {
this.queryRromServer(1);
},
getDataSource(comments) {
// return false;
return this.state.dataSource.cloneWithRows(comments);
},
renderFooter() {
if (!this.state.next) {
return (
<DoneFooter/>
);
}
return <ActivityIndicator style={styles.scrollSpinner} animating={this.state.animating}/>;
},
renderHeader() {
return (
<LookCell
look={this.props.look}
navigator={this.props.navigator}
onSelect={function(){}}
userCell={true}
/>
);
},
onEndReached() {
if(this.props.look.comments_count==0){
this.setState({
next:false,
});
return;
}
if (this.state.next && !this.state.animating) {
this.setState({ animating: true });
this.queryRromServer(this.state.pageNo);
}
},
onSelectUser(user) {
this.props.navigator.push({
component: User,
title: user.name,
backButtonTitle:' ',
passProps: {
user:user,
navigator:this.props.navigator,
},
});
},
// shouldComponentUpdate: function(nextProps, nextState) {
// console.log('LookDetail.js.js-shouldComponentUpdate');
// return JSON.stringify(nextState)!=JSON.stringify(this.state);
// },
renderRow(comments) {
if(!comments.comment||!comments.comment.user){
return false;
}
return (
<TouchableOpacity activeOpacity={0.8} onPress={()=>this.onSelectUser(comments.comment.user)} style={styles.flexContainer}>
<Image source={{uri:comments.comment.user.photo}} style={styles.avatar}/>
<View style={styles.commentBody}>
<View style={styles.commentHeader}>
<View style={{flex:1}}>
<Text style={styles.userName}>{comments.comment.user.name}</Text>
</View>
<View style={styles.timeView}>
<Icon name="ios-clock-outline" color={globalVariables.textBase} size={15}/>
<Text style={styles.time}> {globalVariables.formatDateToString(comments.comment.created_at)}</Text>
</View>
</View>
<Text style={styles.commentText}>{comments.comment.body}</Text>
</View>
</TouchableOpacity>
);
},
render() {
console.log(new Date()-0);
console.log('LookDetail.js.js-render');
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
onEndReached={this.onEndReached}
renderHeader={this.renderHeader}
renderFooter={this.renderFooter}
onEndReachedThreshold={10}
automaticallyAdjustContentInsets={false}
keyboardDismissMode='on-drag'
keyboardShouldPersistTaps={false}
showsVerticalScrollIndicator={true}
style={styles.container}
/>
);
},
queryRromServer(page) {
globalVariables.queryRromServer(globalVariables.apiLookServer+this.props.look.id+'/comments/'+(page||1),this.processsResults);
},
processsResults(data) {
if (!data||!data.comments||!data.comments.length) {
this.setState({
animating: false,
next:false,
});
return;
}
var newComments= this.state.comments.concat(data.comments);
var next=newComments.length>=this.props.look.comments_count?false:true;
this.setState({
comments: newComments,
animating: false,
dataSource: this.getDataSource(newComments),
pageNo: this.state.pageNo+1,
next:next,
});
}
});
const styles = StyleSheet.create({
container: {
paddingTop: 64,
backgroundColor: globalVariables.background,
},
flexContainer: {
opacity:0.97,
padding: 10,
flexDirection: 'row',
justifyContent: 'flex-start',
},
commentBody: {
flex: 1,
flexDirection: "column",
justifyContent: "center",
},
commentHeader: {
flexDirection: "row",
alignItems: "flex-start"
},
userName: {
color:globalVariables.base,
// fontSize:12,
},
timeView:{
// width:50,
flexDirection: "row",
alignItems:'center',
marginRight:5,
},
time:{
color:globalVariables.textBase,
fontSize:12,
// ,
},
commentText: {
// fontSize:12,
marginTop:8,
flexDirection: "row",
color:globalVariables.textBase,
},
avatar: {
borderRadius: 18,
width: 36,
height: 36,
marginRight: 10,
marginLeft: 5,
backgroundColor:globalVariables.textBase2,
},
scrollSpinner: {
marginVertical: 20,
},
});
export default LookDetail;
| rollo-zhou/look | src/components/LookDetail.js | JavaScript | mit | 5,317 |
#!/usr/bin/env python
import sys
import os
from treestore import Treestore
try: taxonomy = sys.argv[1]
except: taxonomy = None
t = Treestore()
treebase_uri = 'http://purl.org/phylo/treebase/phylows/tree/%s'
tree_files = [x for x in os.listdir('trees') if x.endswith('.nex')]
base_uri = 'http://www.phylocommons.org/trees/%s'
tree_list = set(t.list_trees())
for tree_uri in tree_list:
if not 'TB2_' in tree_uri: continue
tree_id = t.id_from_uri(tree_uri)
tb_uri = treebase_uri % (tree_id.replace('_', ':'))
print tree_id, tb_uri
t.annotate(tree_uri, annotations='?tree bibo:cites <%s> .' % tb_uri)
| NESCent/phylocommons | tools/treebase_scraper/annotate_trees.py | Python | mit | 622 |
<?php
/**
* This file belongs to the AnoynmFramework
*
* @author vahitserifsaglam <[email protected]>
* @see http://gemframework.com
*
* Thanks for using
*/
namespace Anonym\Facades;
use Anonym\Patterns\Facade;
/**
* Class Validation
* @package Anonym\Facades
*/
class Validation extends Facade
{
/**
* return the validation facade
*
* @return string
*/
protected static function getFacadeClass(){
return 'validation';
}
}
| AnonymPHP/Anonym-Library | src/Anonym/Facades/Validation.php | PHP | mit | 487 |
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
*
* The Original Code is OIOSAML Java Service Provider.
*
* The Initial Developer of the Original Code is Trifork A/S. Portions
* created by Trifork A/S are Copyright (C) 2008 Danish National IT
* and Telecom Agency (http://www.itst.dk). All Rights Reserved.
*
* Contributor(s):
* Joakim Recht <[email protected]>
* Rolf Njor Jensen <[email protected]>
* Aage Nielsen <[email protected]>
*
*/
package dk.itst.oiosaml.sp.service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dk.itst.oiosaml.logging.Logger;
import dk.itst.oiosaml.logging.LoggerFactory;
import org.apache.commons.configuration.Configuration;
import org.opensaml.DefaultBootstrap;
import org.opensaml.xml.ConfigurationException;
import dk.itst.oiosaml.common.SAMLUtil;
import dk.itst.oiosaml.configuration.FileConfiguration;
import dk.itst.oiosaml.configuration.SAMLConfiguration;
import dk.itst.oiosaml.configuration.SAMLConfigurationFactory;
import dk.itst.oiosaml.error.Layer;
import dk.itst.oiosaml.error.WrappedException;
import dk.itst.oiosaml.logging.Audit;
import dk.itst.oiosaml.logging.Operation;
import dk.itst.oiosaml.sp.UserAssertion;
import dk.itst.oiosaml.sp.UserAssertionHolder;
import dk.itst.oiosaml.sp.bindings.BindingHandler;
import dk.itst.oiosaml.sp.develmode.DevelMode;
import dk.itst.oiosaml.sp.develmode.DevelModeImpl;
import dk.itst.oiosaml.sp.metadata.CRLChecker;
import dk.itst.oiosaml.sp.metadata.IdpMetadata;
import dk.itst.oiosaml.sp.metadata.SPMetadata;
import dk.itst.oiosaml.sp.service.session.Request;
import dk.itst.oiosaml.sp.service.session.SessionCleaner;
import dk.itst.oiosaml.sp.service.session.SessionHandler;
import dk.itst.oiosaml.sp.service.session.SessionHandlerFactory;
import dk.itst.oiosaml.sp.service.util.Constants;
/**
* Servlet filter for checking if the user is authenticated.
*
* <p>
* If the user is authenticated, a session attribute,
* {@link Constants#SESSION_USER_ASSERTION} is set to contain a
* {@link UserAssertion} representing the user. The application layer can access
* this object to retrieve SAML attributes for the user.
* </p>
*
* <p>
* If the user is not authenticated, a <AuthnRequest> is created and sent
* to the IdP. The protocol used for this is selected automatically based on th
* available bindings in the SP and IdP metadata.
* </p>
*
* <p>
* The atual redirects are done by {@link BindingHandler} objects.
* </p>
*
* <p>
* Discovery profile is supported by looking at a request parameter named
* _saml_idp. If the parameter does not exist, the browser is redirected to
* {@link Constants#DISCOVERY_LOCATION}, which reads the domain cookie. If the
* returned value contains ids, one of the ids is selected. If none of the ids
* in the list is registered, an exception is thrown. If no value has been set,
* the first configured IdP is selected automatically.
* </p>
*
* @author Joakim Recht <[email protected]>
* @author Rolf Njor Jensen <[email protected]>
* @author Aage Nielsen <[email protected]>
*/
public class SPFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(SPFilter.class);
private CRLChecker crlChecker = new CRLChecker();
private boolean filterInitialized;
private SAMLConfiguration conf;
private String hostname;
private SessionHandlerFactory sessionHandlerFactory;
private AtomicBoolean cleanerRunning = new AtomicBoolean(false);
private DevelMode develMode;
/**
* Static initializer for bootstrapping OpenSAML.
*/
static {
try {
DefaultBootstrap.bootstrap();
} catch (ConfigurationException e) {
throw new WrappedException(Layer.DATAACCESS, e);
}
}
public void destroy() {
SessionCleaner.stopCleaner();
crlChecker.stopChecker();
if (sessionHandlerFactory != null) {
sessionHandlerFactory.close();
}
SessionHandlerFactory.Factory.close();
}
/**
* Check whether the user is authenticated i.e. having session with a valid
* assertion. If the user is not authenticated an <AuthnRequest> is
* sent to the Login Site.
*
* @param request
* The servletRequest
* @param response
* The servletResponse
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (log.isDebugEnabled())
log.debug("OIOSAML-J SP Filter invoked");
if (!(request instanceof HttpServletRequest)) {
throw new RuntimeException("Not supported operation...");
}
HttpServletRequest servletRequest = ((HttpServletRequest) request);
Audit.init(servletRequest);
if (!isFilterInitialized()) {
try {
Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration();
setRuntimeConfiguration(conf);
} catch (IllegalStateException e) {
request.getRequestDispatcher("/saml/configure").forward(request, response);
return;
}
}
if (conf.getSystemConfiguration().getBoolean(Constants.PROP_DEVEL_MODE, false)) {
log.warn("Running in debug mode, skipping regular filter");
develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf.getSystemConfiguration());
return;
}
if (cleanerRunning.compareAndSet(false, true)) {
SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(), ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30);
}
SessionHandler sessionHandler = sessionHandlerFactory.getHandler();
if (servletRequest.getServletPath().equals(conf.getSystemConfiguration().getProperty(Constants.PROP_SAML_SERVLET))) {
log.debug("Request to SAML servlet, access granted");
chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response);
return;
}
final HttpSession session = servletRequest.getSession();
if (log.isDebugEnabled())
log.debug("sessionId....:" + session.getId());
Boolean forceAuthn = false;
if(request.getParameterMap().containsKey(Constants.QUERY_STRING_FORCE_AUTHN))
{
String forceAuthnAsString = request.getParameter(Constants.QUERY_STRING_FORCE_AUTHN);
forceAuthn = forceAuthnAsString.toLowerCase().equals("true");
}
// Is the user logged in?
if (sessionHandler.isLoggedIn(session.getId()) && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null && !forceAuthn) {
int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel();
int assuranceLevel = conf.getSystemConfiguration().getInt(Constants.PROP_ASSURANCE_LEVEL);
if ((actualAssuranceLevel > 0) && (actualAssuranceLevel < assuranceLevel)) {
sessionHandler.logOut(session);
log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel);
throw new RuntimeException("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel);
}
UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION);
if (log.isDebugEnabled())
log.debug("Everything is ok... Assertion: " + ua);
Audit.log(Operation.ACCESS, servletRequest.getRequestURI());
try {
UserAssertionHolder.set(ua);
HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname);
chain.doFilter(requestWrap, response);
return;
} finally {
UserAssertionHolder.set(null);
}
} else {
session.removeAttribute(Constants.SESSION_USER_ASSERTION);
UserAssertionHolder.set(null);
saveRequestAndGotoLogin((HttpServletResponse) response, servletRequest);
}
}
protected void saveRequestAndGotoLogin(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
SessionHandler sessionHandler = sessionHandlerFactory.getHandler();
String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(request));
String protocol = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL, "saml20");
String loginUrl = conf.getSystemConfiguration().getString(Constants.PROP_SAML_SERVLET, "/saml");
String protocolUrl = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL + "." + protocol);
if (protocolUrl == null) {
throw new RuntimeException("No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol);
}
loginUrl += protocolUrl;
if (log.isDebugEnabled())
log.debug("Redirecting to " + protocol + " login handler at " + loginUrl);
RequestDispatcher dispatch = request.getRequestDispatcher(loginUrl);
dispatch.forward(new SAMLHttpServletRequest(request, hostname, relayState), response);
}
public void init(FilterConfig filterConfig) throws ServletException {
conf = SAMLConfigurationFactory.getConfiguration();
if (conf.isConfigured()) {
try {
Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration();
if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) {
develMode = new DevelModeImpl();
setConfiguration(conf);
setFilterInitialized(true);
return;
}
setRuntimeConfiguration(conf);
setFilterInitialized(true);
return;
} catch (IllegalStateException e) {
log.error("Unable to configure", e);
}
}
setFilterInitialized(false);
}
private void setRuntimeConfiguration(Configuration conf) {
restartCRLChecker(conf);
setFilterInitialized(true);
setConfiguration(conf);
if (!IdpMetadata.getInstance().enableDiscovery()) {
log.info("Discovery profile disabled, only one metadata file found");
} else {
if (conf.getString(Constants.DISCOVERY_LOCATION) == null) {
throw new IllegalStateException("Discovery location cannot be null when discovery profile is active");
}
}
setHostname();
sessionHandlerFactory = SessionHandlerFactory.Factory.newInstance(conf);
sessionHandlerFactory.getHandler().resetReplayProtection(conf.getInt(Constants.PROP_NUM_TRACKED_ASSERTIONIDS));
log.info("Home url: " + conf.getString(Constants.PROP_HOME));
log.info("Assurance level: " + conf.getInt(Constants.PROP_ASSURANCE_LEVEL));
log.info("SP entity ID: " + SPMetadata.getInstance().getEntityID());
log.info("Base hostname: " + hostname);
}
private void setHostname() {
String url = SPMetadata.getInstance().getDefaultAssertionConsumerService().getLocation();
setHostname(url.substring(0, url.indexOf('/', 8)));
}
private void restartCRLChecker(Configuration conf) {
crlChecker.stopChecker();
int period = conf.getInt(Constants.PROP_CRL_CHECK_PERIOD, 600);
if (period > 0) {
crlChecker.startChecker(period, IdpMetadata.getInstance(), conf);
}
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public void setFilterInitialized(boolean b) {
filterInitialized = b;
}
public boolean isFilterInitialized() {
return filterInitialized;
}
public void setConfiguration(Configuration configuration) {
SAMLConfigurationFactory.getConfiguration().setConfiguration(configuration);
conf = SAMLConfigurationFactory.getConfiguration();
}
public void setSessionHandlerFactory(SessionHandlerFactory sessionHandlerFactory) {
this.sessionHandlerFactory = sessionHandlerFactory;
}
public void setDevelMode(DevelMode develMode) {
this.develMode = develMode;
}
}
| Safewhere/kombit-web-java | Kombit.Samples.CH.WebsiteDemo/src/java/dk/itst/oiosaml/sp/service/SPFilter.java | Java | mit | 12,213 |