code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
// Package epiutil is an utility class with functions
// common to all packages in the epi project.
package epiutil
import "math/rand"
// RandStr returns a string of length n constructed
// from pseudo-randomly selected characters from t.
// The pseudo-randomness uses random values from s.
func RandStr(n int, t string, s rand.Source) string {
l := len(t) - 1
chars := make([]byte, n)
if l > 0 {
for i, p := range rand.New(s).Perm(n) {
chars[i] = t[p%l]
}
}
return string(chars)
}
| Java |
var assert = require('assert');
var fs = require('fs');
var requireFiles = require(__dirname + '/../lib/requireFiles');
var files = [
__dirname + '/moch/custom_test.txt',
__dirname + '/moch/json_test.json',
__dirname + '/moch/test.js'
];
describe('requireFiles testing', function(){
describe('Structure type', function(){
it('requireFiles should be a function', function(){
assert.equal(typeof requireFiles, 'function');
});
});
describe('Error', function(){
it('Should throw error when an engine isn\'t supported', function(){
assert.throws(function(){
requireFiles(files, {
'.js' : require,
'.json' : require
});
}, /there is no engine registered/);
});
it('Should not throw an error when everything is ok', function(){
assert.doesNotThrow(function(){
result = requireFiles(files.slice(1, 3), {
'.js' : require,
'.json' : require
});
});
});
});
describe('Custom engine', function(){
it('Custom engines should work', function(){
var result = requireFiles(files, {
'.js' : require,
'.json' : require,
'.txt' : function(path){
return fs.readFileSync(path).toString();
}
});
assert.equal(result[files[0]], 'worked\n');
assert.equal(result[files[1]].worked, true);
assert.equal(result[files[2]], 'worked');
});
});
});
| Java |
package com.reactnativeexample;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "ReactNativeExample";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
}
| Java |
/// <reference path="Global.ts" />
/// <reference path="Decks.ts" />
module ScrollsTypes {
'use strict';
export class DeckCards {
cards:CardsAndStats[] = [];
deck:Deck;
constructor(deck:Deck) {
this.deck = deck;
this.update();
}
update():void {
var r:Card[] = TypesToCards(this.deck.types, _scrolls);
var c:Card[][] = HavingMissingRemainingCards(_cardsReport[1].c, r);
this.cards[0] = new CardsAndStats(c[0], true, true);
this.cards[1] = new CardsAndStats(c[1], true, true);
this.cards[2] = new CardsAndStats(c[2], true, true);
}
addType(type:number):number {
removeDeckStats(this.deck);
var added:number = this.deck.addType(type);
this.update();
addDeckStats(this.deck);
GetDecksStats();
return added;
}
removeType(type:number):number {
removeDeckStats(this.deck);
var removed:number = this.deck.removeType(type);
this.update();
addDeckStats(this.deck);
GetDecksStats();
return removed;
}
replaceDeck(deck:DeckExtended):void {
// this.deck.setDeck(deck.deck);
this.deck.deck = deck.deck;
// this.deck.setAuthor(deck.author);
this.deck.author = deck.author;
this.deck.origin = deck.origin;
this.replaceTypes(deck.types);
}
replaceTypes(types:number[]):void {
removeDeckStats(this.deck);
_.each(_.clone(this.deck.types), (v:number) => {
this.deck.removeType(v);
});
_.each(types, (v:number) => {
this.deck.types.push(v);
});
this.deck.update();
this.update();
addDeckStats(this.deck);
GetDecksStats();
}
}
}
| Java |
class Admin::<%= file_name.classify.pluralize %>Controller < Admin::BaseController
inherit_resources
<% if options[:actions].present? %>
actions <%= options[:actions].map {|a| ":#{a}"}.join(", ") %>
<% else %>
actions :all, except: [:show]
<% end %>
private
def collection
@<%= file_name.pluralize %> ||= end_of_association_chain.page(params[:page]).per(20)
end
end
| Java |
/*
*= require ecm/tags/backend/application
*/
| Java |
{{ with $.Site.Params.themeColor }}
<style type="text/css">
.sidebar {
background-color: {{ . }};
}
.read-more-link a {
border-color: {{ . }};
}
.pagination li a {
color: {{ . }};
border: 1px solid {{ . }};
}
.pagination li.active a {
background-color: {{ . }};
}
.pagination li a:hover {
background-color: {{ . }};
opacity: 0.75;
}
footer a,
.content a,
.related-posts li a:hover {
color: {{ . }};
}
</style>
{{ end }}
| Java |
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);
}
}
| Java |
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
])
]);
})
)
]);
}
| Java |
<html>
<title>nwSGM</title>
<body bgcolor="#000066" text="#FFFF00" link="#8888FF" vlink="#FF0000">
<h1><em>nwSGM</em></h1>
<hr>
<p>
<b><em>Segment generator</em></b>
<p>
<hr>
</body>
</html>
| Java |
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,600);
body {
font-family: 'Open Sans', sans-serif;
margin: auto;
max-width: 100%;
overflow-x: hidden;
}
.container{
margin: 10px auto;
}
@import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro);
.navbar-brand{
font-family: 'Source Sans Pro', sans-serif;
}
.navbar{
background: linear-gradient(#eef, #dfe3e5);
background-color: #dfe3e5;
margin-bottom: 0;
}
.bevel {
vertical-align: middle;
font-size: 1em;
font-weight: bold;
text-shadow: 1px 1px 1px #eee;
/* color: black;*/
color: #d7dee1;
}
.bevel>li>a:hover {
background: none;
}
.nav-pills>li>a {
color: dimgray;
}
.nav-pills>li>a:hover {
color: black;
}
.pull-right>li>a {
margin-bottom: 0;
background-color: white;
}
.nav-pills {
vertical-align: middle;
}
#head{
margin-top: 0;
height:400px;
background: url(cover.png) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
| Java |
<?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 <terrafrost@php.net>
* @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 <terrafrost@php.net>
* @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 'newline@vandyke.com',
however, I'm not sure what 'newline@vandyke.com' is supposed to do (the fact that it's unofficial means that it's
not in the official SFTPv3 specs) and 'newline@vandyke.com' / '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
'newline@vandyke.com' would.
*/
/*
if (isset($this->extensions['newline@vandyke.com'])) {
$this->extensions['newline'] = $this->extensions['newline@vandyke.com'];
unset($this->extensions['newline@vandyke.com']);
}
*/
$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);
}
}
| Java |
/*
--------------------------------------------------------------------------------
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
//------------------------------------------------------------------------------ | Java |
# 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
| Java |
.pad {
padding:30px 30px 30px 30px !important;
}
.button-gm {
min-height: 30px;
line-height: 30px;
font-size: 14px
}
.button-me {
border-color: transparent;
background-color: #00c0f5;
color: #FFF;
position: relative;
display: inline-block;
margin: 10px 0;
padding: 0 12px;
min-width: 52px;
min-height: 32px;
border-width: 1px;
border-style: solid;
border-radius: 4px;
vertical-align: top;
text-align: center;
text-overflow: ellipsis;
font-size: 16px;
line-height: 30px;
cursor: pointer;
}
.footer {
color: #444;
position: absolute;
bottom: 0;
right: 0;
left: 0;
width: 100%;
height: 100px;
}
.weui_uploader_input_wrp {
float: left;
position: relative;
margin-right: 9px;
margin-bottom: 9px;
width: 77px;
height: 77px;
border: 1px solid #D9D9D9;
}
.weui_uploader_input_wrp:before,
.weui_uploader_input_wrp:after {
content: " ";
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #D9D9D9;
}
.weui_uploader_input_wrp:before {
width: 2px;
height: 39.5px;
}
.weui_uploader_input_wrp:after {
width: 39.5px;
height: 2px;
}
.weui_uploader_input_wrp:active {
border-color: #999999;
}
.weui_uploader_input_wrp:active:before,
.weui_uploader_input_wrp:active:after {
background-color: #999999;
}
.center-in-center{
position: absolute;
top: 40%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
} | Java |
// 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
}
}
}
}
| Java |
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();
},
};
| Java |
<?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');
}
}
| Java |
<?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;
}
}
| Java |
<link rel="import" href="../../polymer/polymer-element.html">
<link rel="import" href="../overlay-mixin.html">
<dom-module id="sample-overlay">
<template>
<style>
:host {
background: #ddd;
display: block;
height: 200px;
position: absolute;
width: 200px;
}
:host(:focus) {
border: 2px solid dodgerblue;
}
</style>
Hello!!!
</template>
<script>
class SampleOverlay extends OverlayMixin(Polymer.Element) {
static get is() {return 'sample-overlay';}
}
customElements.define(SampleOverlay.is, SampleOverlay);
</script>
</dom-module> | Java |
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;
}
}
}
}
| Java |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<link rel="stylesheet" href="../css/weui.css"/>
<link rel="stylesheet" href="../css/weuix.css"/>
<script src="../js/zepto.min.js"></script>
<script src="../js/zepto.weui.js"></script>
<script src="../js/clipboard.min.js"></script>
</head>
<body ontouchstart>
<div class="page-hd">
<h1 class="page-hd-title">
字体大小/颜色/背景/标题
</h1>
<p class="page-hd-desc"></p>
</div>
<h1>字体大小与颜色</h1>
<h2>字体大小与颜色</h2>
<h3>字体大小与颜色</h3>
<h4>字体大小与颜色</h4>
<h5>字体大小与颜色</h5>
<h6>字体大小与颜色</h6>
<br>
字体f11-55
<span class='f11'>字体f11</span><span class='f12'>字体f12</span><span class='f13'>字体f13</span><span class='f114'>字体f14</span><span class='f15'>字体15</span><span class='f116'>字体f16</span><span class='f31'>字体f31</span><span class='f32'>字体f32</span><span class='f35'>字体f35</span><span class='f40'>字体f40</span><span class='f45'>字体f45</span><span class='f50'>字体f50</span><span class='f55'>字体f55</span>
<br>
<span class='f-red'>红色f-red</span><span class='f-green'>绿色f-green</span>
<span class='f-blue'>蓝色f-blue</span><span class='f-black'>f-black</span>
<span class='f-white bg-blue'>f-white</span> <span class='f-zi'>f-zi</span> <span class='f-gray'>灰色f-gray</span> <span class='f-yellow'>黄色</span><span class='f-orange'>f-orange</span><span class='f-white bg-blue'>背景蓝色bg-blue</span>
<br>
<span class='bg-orange f-white'>bg-orange</span>
<span class='weui-btn_primary f-white'>背景绿色weui-btn_primary</span>
<span class='weui-btn_warn f-white'>weui-btn_warn</span>
<span class='weui-btn_default f-red'>weui-btn_default</span>
<div class="weui-cells__title">9种常见颜色值</div>
<div class="weui-cells weui-cells_form">
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FA5151">红色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FA5151" style="background:#FA5151;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#07C160">绿色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#07C160" style="background:#07C160;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#10AEFF">蓝色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#10AEFF" style="background:#10AEFF;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#333">黑色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#333" style="background:#333;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FF33CC">紫色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FF33CC" style="background:#FF33CC;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#CCC">灰色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#CCC" style="background:#CCC;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FFFF66">黄色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FFFF66" style="background:#FFFF66;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FF6600">橙色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FF6600" style="background:#FF6600;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FFF">白色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FFF" style="background:#FFF;color:white"/>
</div>
</div>
</div>
</div>
<script>
var clipboard = new Clipboard('.jsclip', {
text: function(e) {
return $(e).data('url')||$(e).data('href');
}
});
clipboard.on('success', function(e) {
$.toast('复制成功');
});
</script>
<br>
<br>
<div class="weui-footer weui-footer_fixed-bottom">
<p class="weui-footer__links">
<a href="../index.html" class="weui-footer__link">WeUI首页</a>
</p>
<p class="weui-footer__text">Copyright © Yoby</p>
</div>
</body>
</html> | Java |
/*
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";
}
}
| Java |
package cellsociety_team05;
public class SimulationException extends Exception {
public SimulationException(String s) {
super(s);
}
}
| Java |
PhotoAlbums.Router.map(function() {
this.resource('login');
this.resource('album', {path: '/:album_id'});
this.resource('photo', {path: 'photos/:photo_id'});
});
| Java |
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''
return f""
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
)
| Java |
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();
}
}
}
| Java |
<?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();
}
}
}
| Java |
import Icon from '../components/Icon.vue'
Icon.register({"arrows":{"width":1792,"height":1792,"paths":[{"d":"M1792 896q0 26-19 45l-256 256q-19 19-45 19t-45-19-19-45v-128h-384v384h128q26 0 45 19t19 45-19 45l-256 256q-19 19-45 19t-45-19l-256-256q-19-19-19-45t19-45 45-19h128v-384h-384v128q0 26-19 45t-45 19-45-19l-256-256q-19-19-19-45t19-45l256-256q19-19 45-19t45 19 19 45v128h384v-384h-128q-26 0-45-19t-19-45 19-45l256-256q19-19 45-19t45 19l256 256q19 19 19 45t-19 45-45 19h-128v384h384v-128q0-26 19-45t45-19 45 19l256 256q19 19 19 45z"}]}})
| Java |
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
| Java |
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)
}
| Java |
Title: On Git and GitHub Flow
Date: 2015-01-01
Recently, I have been making an added effort to seek out and contribute to open source projects on GitHub. The motivation behind this was largely the [24 Pull Requests](http://24pullrequests.com) project, which encourages developers to submit one pull request for each day in December leading up to Christmas. The prospect of being a new contributor to a large, open source project can be daunting, especially to the novice programmer, so this little bit of extrinsic motivation was a nudge in the right direction.
In learning how to properly make use of Git and GitHub, I've referenced a multitude of different resources. With 2015 having just arrived, I'm sure many people have "contribute to more open source projects" on their list of New Year's resolutions as well, so hopefully this article serves as a useful starting point.
## Finding a Project
Choosing a project is left as an exercise to the reader. However, here are my suggestions:
- Look to see if any software you use on a regular basis is open source. Given your familiarity with the software, you will likely be able to identify (and hack on) some bugs or additional features.
- Check out [trending GitHub repositories](https://github.com/trending) for languages that you're familiar with or ones that you're interested in learning, and pick one that seems friendly towards new contributors (most projects on GitHub are) and well-maintained. This technique is useful as you'll be browsing across projects that your fellow open source developers have also deemed interesting.
Remember that even if you can't contribute directly to the codebase due to lack of experience or being overwhelmed by the scale of the project, open source projects appreciate all sorts of contributions. While not as "prestigious", documentation and unit tests are areas that inevitability need to be addressed, and are a good way to become familiar with the project.
## Getting Started
The first step to using Git is installing it. You can do that from Git's [download page](http://git-scm.com/downloads), or through a package manager like Homebrew. My suggestion is to learn Git from the command line, and to avoid using other Git clients; the command line is universal, so being familiar with it to start with will be beneficial in the long run.
That being said, I do have [GitHub for Mac](https://mac.github.com) installed and I use it fairly frequently for selectively choosing specific parts of a file to commit, which is fairly cumbersome to do from the command line. Also, I find looking through the changes that have been made is much easier with the GitHub application compared to using `git diff`.
## Overview
Git tracks content modifications. It does so primarily through the use of commits. Commits can be thought of as snapshots in the development process, and contain authorship and timestamp information among other pieces of metadata. By committing frequently, it becomes trivial to rollback to an old commit if something goes disastrously (or if your simply don't like the changes you made). Because of this, Git (and any other version control system) is extremely powerful, even for projects that aren't collaborative in nature.
There is a convention behind the formatting of commit messages that should be followed, given the collaborative nature of open source projects. The first (or only) line of the commit is a summary of the changes, 50 characters at most, in the imperative tense (as in *add*, not *added*). If you want to expand further, you should leave a blank line and on the third line, begin an extended description wrapped to 72 characters.
Unfortunately, after prolonged periods of time, the quality of commit messages tends to degrade ([relevant XKCD](http://xkcd.com/1296/)). Don't worry about this, though, as you can avoid forcing others to look at your horribly crafted commit messages through a process known as *rebasing*, discussed later in this article.
## Branches and Pull Requests
One concept that is central to Git and GitHub flow is branching. Branches are pointers to commits. When working on feature additions or fixes in a project, it is advisable to *always* work in a separate branch, and either merge or rebase -- discussed later in much more detail -- into the master branch upon competition.
When you open a pull request on GitHub, the branch that you chose is noted. Pushing additional commits to that specific branch will result in them appearing in the pull request. This is one of the strongest cases for using a new branch for every feature or bug fix -- it makes it trivial to open a pull request for that specific change, without incorporating any unrelated changes.
## To Merge or Not to Merge
Merging is the process of merging the commits made in two branches into one branch. This is done when a branch that is being worked on is deemed complete, and the changes are to be merged into the master branch. In the simplest case (where the only commits that have been made are in the topic branch), this is known as a fast-forward merge, and the commits are "played on top of" the master branch. Fast-forward merges can be performed automatically by Git and require no additional effort on the part of the user performing the merge. In other cases, merging either results in a merge commit or the manual resolution of merge conflicts (if the changes made in the branches contradict one another).
Something that Git tutorials tend to gloss over is the rebase command. The reason for this is that rebasing involves *rewriting history*. When you rebase a set of commits, they will change, and if the older set of commits have already been pushed to a remote repository that others have pulled from, pushing new changes will cause a break in continuity for others who try to pull these newly pushed commits. Because of this, it is recommended to only rebase local commits in most cases.
```sh
$ git rebase -i HEAD~n # rebase the last n commits
```
The `-i` flag stands for *interactive*. Upon executing the command, your `$EDITOR` of choice will open with a list of commits from least recent to most recent preceded by the word "pick":
```
#!text
pick a5b977a Ensure all expected resource files exist
pick f08e801 Add problems 311–320
pick 969f9e5 Update tests to ensure resource correspondence
```
Below the list of commits are some instructions about rebasing, including the available commands. To actually rebase, you make changes to the text in the editor and then close it. Here are the operations that you can perform:
- Delete the line, which will remove the commit entirely.
- Change "pick" to a different command, causing the rebase to execute that command instead.
- Rearrange the lines, which will rearrange the order of the commits.
Typically, a project maintainer might ask for you to squash your pull request. What this actually involves doing is rebasing and using the "squash" command to turn multiple commits into just one or a couple logical commits. For example, if you wanted to turn the three commits listed above into one larger commit, you would edit the file to look like the following:
```
#!text
pick a5b977a Ensure all expected resource files exist
squash f08e801 Add problems 311–320
squash 969f9e5 Update tests to ensure resource correspondence
```
Upon closing the editor, a new editor will open up that allows you to edit the commit message of the newly created single commit. The commit messages of each of the commits being squashed are included for the sake of convenience, and when the editor is closed, the non-commented lines become the new commit message.
I mentioned before that rebasing should only be done with local changes that have not been pushed to a remote repository, but in a pull request, by definition, the commits have already been pushed to your fork of the main repository. In this case, it is fine to rebase and push, since it can be assumed that people have not been actively making changes on the feature/fix branch that your pull request is based on. However, Git will not let you push the rebased commits using `git push` out of safety; you have to use `git push -f` to *force* the push to happen.
## Putting It All Together
After forking the project on GitHub, the typical GitHub workflow might look something like this:
```
#!sh
git clone https://github.com/YOUR_GITHUB_USERNAME/PROJECT_NAME.git
cd PROJECT_NAME
git branch my-feature
git checkout my-feature
nano README.md
rm silly-file.txt
git add -A
git commit
git push -u origin my-feature
```
1. Clone your fork to your local development machine.
2. Change the current directory to the project folder.
3. Create a branch called `my-feature`.
4. Switch to the newly created `my-feature` branch.
5. Make changes to `README.md`.
6. Remove `silly-file.txt`.
7. Stage all (`-A`) changes made, including file creations and deletions. You can specify certain files rather than using the `-A` flag to selectively stage changes.
8. Commit the changes that have been staged. Continue to commit new changes and rebase when needed.
9. Push the `my-feature` branch to remote repository aliased as `origin` (your fork), using the `-u` flag to add the branch as a remote tracking branch. (Subsequent pushes will only requre a `git push` with no additional parameters.) Then, open a pull request using GitHub's web interface!
For other Git-related problems that one may run into, Google can usually provide the answer. Be sure to look at [GitHub's help page](https://help.github.com) and the [Git documentation](http://git-scm.com/doc) itself. Here's to lots of open source contributions in 2015!
| Java |
--[[
File: src/animation/frame.lua
Author: Daniel "lytedev" Flanagan
Website: http://dmf.me
Contains the data to specify a piece of a texture over a period of time.
]]--
local Frame = Class{}
function Frame.generate(w, h, imgw, imgh, num, time, frames, offset, start)
local start = start or 0
local tw = math.floor(imgw / w)
local th = math.floor(imgh / h)
local num = num or (tw * th)
local framesArray = {}
for i = start, num - 1, 1 do
-- To change left-to-right-down, modify xid and yid calcs
local xid = i % tw
local yid = math.floor(i / tw)
local frame = Frame(Vector(xid * w, yid * h), Vector(w, h), time, frames, offset)
table.insert(framesArray, frame)
end
return framesArray
end
function Frame:init(source, size, time, frames, offset)
self.source = source or Vector(0, 0)
self.size = size or Vector(16, 16)
self.offset = offset or Vector(0, 0)
self.time = time or 0.2
self.frames = frames or nil
end
function Frame:__tostring()
return string.format("Source: (%s), Size: (%s), Time: %ds, Frames: %i, Offset: (%s)", tostring(self.source), tostring(self.size), self.time, self.frames or 0, tostring(self.offset))
end
return Frame
| Java |
# Input Number
Simple jQuery plugin to add plus and minus controls to an input element
## Installation
Installation can be done through bower
```
bower install develo-input-number --save
```
Then add the script and jQuery to your page.
## Example Usage
```
// Default options, feel free to override them.
var options = {
// Style customisations
className: 'develo-quantity-helper',
buttonClassName: 'button',
// Min and max
max: null,
min: null,
// Plus and minus buttons. Supports html
minusHtml: '-',
plusHtml: '+',
// Callbacks
onDecreased: function( value ){},
onIncreased: function( value ){}
};
$( 'input' ).develoInputNumber();
```
| Java |
/**
* Your Copyright Here
*
* Appcelerator Titanium is Copyright (c) 2009-2010 by Appcelerator, Inc.
* and licensed under the Apache Public License (version 2)
*/
#import <UIKit/UIKit.h>
#import "TiModule.h"
@class iPhoneHTTPServerViewController;
@class HTTPServer;
@interface Com0x82WebserverModule : TiModule
{
HTTPServer *httpServer;
BOOL wasRunning;
}
@property (nonatomic, assign) NSNumber* disconnectsInBackground;
-(id)startServer:(id)args;
@end | Java |
# Awful Recruiters
This used to be a list of third party recruiters. This was on the website:
> I am definitely not saying these companies are awful. Simply that they are a source of undesirable email. This site is simply a list of domains. No claims are being made about the owners or their intentions.
Ideally, it was just a list of third-party recruiters. “Awful” was intended to be humorous. Some people over reacted a bit. Instead of constantly trying to explain myself, I think it's best to just remove the list. The whole point was to get less email. It's easier to ignore irrelevant job emails than empty legal threats.
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="white">
<title>My App</title>
<!-- Path to Framework7 Library CSS-->
<link rel="stylesheet" href="https://framework7.io/dist/css/framework7.ios.min.css">
<link rel="stylesheet" href="https://framework7.io/dist/css/framework7.ios.colors.min.css">
<!-- Path to your custom app styles-->
<link rel="stylesheet" href="css/Framework7.QuickActions.css">
<link rel="stylesheet" href="css/my-app.css">
</head>
<body>
<!-- Status bar overlay for fullscreen mode-->
<div class="statusbar-overlay"></div>
<!-- Panels overlay-->
<div class="panel-overlay"></div>
<!-- Left panel with reveal effect-->
<div class="panel panel-left panel-reveal">
<div class="content-block">
<p>Left panel content goes here</p>
</div>
</div>
<!-- Right panel with cover effect-->
<div class="panel panel-right panel-cover">
<div class="content-block">
<p>Right panel content goes here</p>
</div>
</div>
<!-- Views-->
<div class="views">
<!-- Your main view, should have "view-main" class-->
<div class="view view-main">
<!-- Top Navbar-->
<div class="navbar">
<!-- Navbar inner for Index page-->
<div data-page="index" class="navbar-inner">
<!-- We have home navbar without left link-->
<div class="center sliding">Awesome App</div>
<div class="right">
<!-- Right link contains only icon - additional "icon-only" class--><a href="#" class="link icon-only open-panel"> <i class="icon icon-bars"></i></a>
</div>
</div>
<!-- Navbar inner for About page-->
<div data-page="about" class="navbar-inner cached">
<div class="left sliding"><a href="#" class="back link"> <i class="icon icon-back"></i><span>Back</span></a></div>
<div class="center sliding">About Us</div>
</div>
<!-- Navbar inner for Services page-->
<div data-page="services" class="navbar-inner cached">
<div class="left sliding"><a href="#" class="back link"> <i class="icon icon-back"></i><span>Back</span></a></div>
<div class="center sliding">Services</div>
</div>
<!-- Navbar inner for Form page-->
<div data-page="form" class="navbar-inner cached">
<div class="left sliding"><a href="#" class="back link"> <i class="icon icon-back"></i><span>Back</span></a></div>
<div class="center sliding">Form</div>
</div>
</div>
<!-- Pages, because we need fixed-through navbar and toolbar, it has additional appropriate classes-->
<div class="pages navbar-through toolbar-through">
<!-- Index Page-->
<div data-page="index" class="page">
<!-- Scrollable page content-->
<div class="page-content">
<div class="content-block-title">Welcome To My Awesome App</div>
<div class="content-block">
<div class="content-block-inner">
<p>Couple of worlds here because my app is so awesome!</p>
<p><a href="#" quick-actions-target="#action1" class="link quick-actions">Duis sed</a> <a href="#" data-href='hi @ds' class="peekPop">erat ac</a> eros ultrices pharetra id ut tellus. Praesent rhoncus enim ornare ipsum aliquet ultricies. Pellentesque sodales erat quis elementum sagittis.</p>
</div>
</div>
<div class="content-block-title">What about simple navigation?</div>
<div class="list-block">
<ul>
<li><a href="#about" class="item-link">
<div class="item-content">
<div class="item-inner">
<div class="item-title">About</div>
</div>
</div></a></li>
<li><a href="#services" class="item-link">
<div class="item-content">
<div class="item-inner">
<div class="item-title">Services</div>
</div>
</div></a></li>
<li><a href="#form" class="item-link">
<div class="item-content">
<div class="item-inner">
<div class="item-title">Form</div>
</div>
</div></a></li>
</ul>
</div>
<div class="content-block-title">Side panels</div>
<div class="content-block">
<div class="row">
<div class="col-50"><a href="#" data-panel="left" class="button open-panel">Left Panel</a></div>
<div class="col-50"><a href="#" data-panel="right" class="button open-panel">Right Panel</a></div>
</div>
</div>
</div>
</div>
<!-- About Page-->
<div data-page="about" class="page cached">
<div class="page-content">
<div class="content-block">
<p>You may go <a href="#" class="back">back</a> or load <a href="#services">Services</a> page.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel commodo massa, eu adipiscing mi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus ultricies dictum neque, non varius tortor fermentum at. Curabitur auctor cursus imperdiet. Nam molestie nisi nec est lacinia volutpat in a purus. Maecenas consectetur condimentum viverra. Donec ultricies nec sem vel condimentum. Phasellus eu tincidunt enim, sit amet convallis orci. Vestibulum quis fringilla dolor. </p>
<p>Mauris commodo lacus at nisl lacinia, nec facilisis erat rhoncus. Sed eget pharetra nunc. Aenean vitae vehicula massa, sed sagittis ante. Quisque luctus nec velit dictum convallis. Nulla facilisi. Ut sed erat nisi. Donec non dolor massa. Mauris malesuada dolor velit, in suscipit leo consectetur vitae. Duis tempus ligula non eros pretium condimentum. Cras sed dolor odio.</p>
<p>Suspendisse commodo adipiscing urna, a aliquet sem egestas in. Sed tincidunt dui a magna facilisis bibendum. Nunc euismod consectetur lorem vitae molestie. Proin mattis tellus libero, non hendrerit neque eleifend ac. Pellentesque interdum velit at lacus consectetur scelerisque et id dui. Praesent non fringilla dui, a elementum purus. Proin vitae lacus libero. Nunc eget lectus non mi iaculis interdum vel a velit. Nullam tincidunt purus id lacus ornare, at elementum turpis euismod. Cras mauris enim, congue eu nisl sit amet, pulvinar semper erat. Suspendisse sed mauris diam.</p>
<p>Nam eu mauris leo. Pellentesque aliquam vehicula est, sed lobortis tellus malesuada facilisis. Fusce at hendrerit ligula. Donec eu nibh convallis, pulvinar enim quis, lacinia diam. Ut semper ac magna nec ornare. Integer placerat justo sed nunc suscipit facilisis. Vestibulum ac tincidunt augue. Duis eu aliquet mauris, vel luctus mauris. Nulla non augue nec diam pharetra posuere at in mauris.</p>
</div>
</div>
</div>
<!-- Services Page-->
<div data-page="services" class="page cached">
<div class="page-content">
<div class="content-block">
<p>You may go <a href="#" class="back">back</a> or load <a href="#about">About</a> page.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel commodo massa, eu adipiscing mi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus ultricies dictum neque, non varius tortor fermentum at. Curabitur auctor cursus imperdiet. Nam molestie nisi nec est lacinia volutpat in a purus. Maecenas consectetur condimentum viverra. Donec ultricies nec sem vel condimentum. Phasellus eu tincidunt enim, sit amet convallis orci. Vestibulum quis fringilla dolor. </p>
<p>Mauris commodo lacus at nisl lacinia, nec facilisis erat rhoncus. Sed eget pharetra nunc. Aenean vitae vehicula massa, sed sagittis ante. Quisque luctus nec velit dictum convallis. Nulla facilisi. Ut sed erat nisi. Donec non dolor massa. Mauris malesuada dolor velit, in suscipit leo consectetur vitae. Duis tempus ligula non eros pretium condimentum. Cras sed dolor odio.</p>
<p>Suspendisse commodo adipiscing urna, a aliquet sem egestas in. Sed tincidunt dui a magna facilisis bibendum. Nunc euismod consectetur lorem vitae molestie. Proin mattis tellus libero, non hendrerit neque eleifend ac. Pellentesque interdum velit at lacus consectetur scelerisque et id dui. Praesent non fringilla dui, a elementum purus. Proin vitae lacus libero. Nunc eget lectus non mi iaculis interdum vel a velit. Nullam tincidunt purus id lacus ornare, at elementum turpis euismod. Cras mauris enim, congue eu nisl sit amet, pulvinar semper erat. Suspendisse sed mauris diam.</p>
<p>Nam eu mauris leo. Pellentesque aliquam vehicula est, sed lobortis tellus malesuada facilisis. Fusce at hendrerit ligula. Donec eu nibh convallis, pulvinar enim quis, lacinia diam. Ut semper ac magna nec ornare. Integer placerat justo sed nunc suscipit facilisis. Vestibulum ac tincidunt augue. Duis eu aliquet mauris, vel luctus mauris. Nulla non augue nec diam pharetra posuere at in mauris. </p>
</div>
</div>
</div>
<!-- Form Page-->
<div data-page="form" class="page cached">
<div class="page-content">
<div class="content-block-title">Form Example</div>
<div class="list-block">
<ul>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-name"></i></div>
<div class="item-inner">
<div class="item-title label">Name</div>
<div class="item-input">
<input type="text" placeholder="Your name">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-email"></i></div>
<div class="item-inner">
<div class="item-title label">E-mail</div>
<div class="item-input">
<input type="email" placeholder="E-mail">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-url"></i></div>
<div class="item-inner">
<div class="item-title label">URL</div>
<div class="item-input">
<input type="url" placeholder="URL">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-password"></i></div>
<div class="item-inner">
<div class="item-title label">Password</div>
<div class="item-input">
<input type="password" placeholder="Password">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-tel"></i></div>
<div class="item-inner">
<div class="item-title label">Phone</div>
<div class="item-input">
<input type="tel" placeholder="Phone">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-gender"></i></div>
<div class="item-inner">
<div class="item-title label">Gender</div>
<div class="item-input">
<select>
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-calendar"></i></div>
<div class="item-inner">
<div class="item-title label">Birth date</div>
<div class="item-input">
<input type="date" placeholder="Birth day" value="2014-04-30">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-toggle"></i></div>
<div class="item-inner">
<div class="item-title label">Switch</div>
<div class="item-input">
<label class="label-switch">
<input type="checkbox">
<div class="checkbox"></div>
</label>
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-settings"></i></div>
<div class="item-inner">
<div class="item-title label">Slider</div>
<div class="item-input">
<div class="range-slider">
<input type="range" min="0" max="100" value="50" step="0.1">
</div>
</div>
</div>
</div>
</li>
<li class="align-top">
<div class="item-content">
<div class="item-media"><i class="icon icon-form-comment"></i></div>
<div class="item-inner">
<div class="item-title label">Textarea</div>
<div class="item-input">
<textarea></textarea>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="content-block">
<div class="row">
<div class="col-50"><a href="#" class="button button-big button-fill color-red">Cancel</a></div>
<div class="col-50">
<input type="submit" value="Submit" class="button button-big button-fill color-green">
</div>
</div>
</div>
<div class="content-block-title">Checkbox group</div>
<div class="list-block">
<ul>
<li>
<label class="label-checkbox item-content">
<input type="checkbox" name="ks-checkbox" value="Books" checked>
<div class="item-media"><i class="icon icon-form-checkbox"></i></div>
<div class="item-inner">
<div class="item-title">Books</div>
</div>
</label>
</li>
<li>
<label class="label-checkbox item-content">
<input type="checkbox" name="ks-checkbox" value="Movies">
<div class="item-media"><i class="icon icon-form-checkbox"></i></div>
<div class="item-inner">
<div class="item-title">Movies</div>
</div>
</label>
</li>
<li>
<label class="label-checkbox item-content">
<input type="checkbox" name="ks-checkbox" value="Food">
<div class="item-media"><i class="icon icon-form-checkbox"></i></div>
<div class="item-inner">
<div class="item-title">Food</div>
</div>
</label>
</li>
<li>
<label class="label-checkbox item-content">
<input type="checkbox" name="ks-checkbox" value="Drinks">
<div class="item-media"><i class="icon icon-form-checkbox"></i></div>
<div class="item-inner">
<div class="item-title">Drinks</div>
</div>
</label>
</li>
</ul>
</div>
<div class="content-block-title">Radio buttons group</div>
<div class="list-block">
<ul>
<li>
<label class="label-radio item-content">
<input type="radio" name="ks-radio" value="Books" checked>
<div class="item-inner">
<div class="item-title">Books</div>
</div>
</label>
</li>
<li>
<label class="label-radio item-content">
<input type="radio" name="ks-radio" value="Movies">
<div class="item-inner">
<div class="item-title">Movies</div>
</div>
</label>
</li>
<li>
<label class="label-radio item-content">
<input type="radio" name="ks-radio" value="Food">
<div class="item-inner">
<div class="item-title">Food</div>
</div>
</label>
</li>
<li>
<label class="label-radio item-content">
<input type="radio" name="ks-radio" value="Drinks">
<div class="item-inner">
<div class="item-title">Drinks</div>
</div>
</label>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- Bottom Toolbar-->
<div class="toolbar">
<div class="toolbar-inner">
<a href="#" class="link">Link 1</a>
<a href="#" class="link">Link 2</a></div>
</div>
</div>
</div>
<!-- Quick actions -->
<ul id="action1" class="quick-actions-menu">
<li class="quickaction-item sub-menu-item">
<a class="quickaction-link" href="#">New message</a>
</li>
<li class="quickaction-item sub-menu-item">
<a class="quickaction-link" href="#">Inbox</a>
</li>
</ul>
<!-- Peek and Pop -->
<!-- Path to Framework7 Library JS-->
<script type="text/javascript" src="https://framework7.io/dist/js/framework7.min.js"></script>
<!-- Path to your app js-->
<script type="text/javascript" src="js/Hammer.js"></script>
<!-- Maybe in future: script type="text/javascript" src="js/Forcify.js"></script-->
<script type="text/javascript" src="js/Framework7.QuickActions.js"></script>
<script type="text/javascript" src="js/my-app.js"></script>
</body>
</html>
| Java |
# Controllers
- [Introduction](#introduction)
- [Writing Controllers](#writing-controllers)
- [Basic Controllers](#basic-controllers)
- [Single Action Controllers](#single-action-controllers)
- [Controller Middleware](#controller-middleware)
- [Resource Controllers](#resource-controllers)
- [Partial Resource Routes](#restful-partial-resource-routes)
- [Nested Resources](#restful-nested-resources)
- [Naming Resource Routes](#restful-naming-resource-routes)
- [Naming Resource Route Parameters](#restful-naming-resource-route-parameters)
- [Scoping Resource Routes](#restful-scoping-resource-routes)
- [Localizing Resource URIs](#restful-localizing-resource-uris)
- [Supplementing Resource Controllers](#restful-supplementing-resource-controllers)
- [Dependency Injection & Controllers](#dependency-injection-and-controllers)
<a name="introduction"></a>
## Introduction
Instead of defining all of your request handling logic as closures in your route files, you may wish to organize this behavior using "controller" classes. Controllers can group related request handling logic into a single class. For example, a `UserController` class might handle all incoming requests related to users, including showing, creating, updating, and deleting users. By default, controllers are stored in the `app/Http/Controllers` directory.
<a name="writing-controllers"></a>
## Writing Controllers
<a name="basic-controllers"></a>
### Basic Controllers
Let's take a look at an example of a basic controller. Note that the controller extends the base controller class included with Laravel: `App\Http\Controllers\Controller`:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
class UserController extends Controller
{
/**
* Show the profile for a given user.
*
* @param int $id
* @return \Illuminate\View\View
*/
public function show($id)
{
return view('user.profile', [
'user' => User::findOrFail($id)
]);
}
}
You can define a route to this controller method like so:
use App\Http\Controllers\UserController;
Route::get('/user/{id}', [UserController::class, 'show']);
When an incoming request matches the specified route URI, the `show` method on the `App\Http\Controllers\UserController` class will be invoked and the route parameters will be passed to the method.
> {tip} Controllers are not **required** to extend a base class. However, you will not have access to convenient features such as the `middleware` and `authorize` methods.
<a name="single-action-controllers"></a>
### Single Action Controllers
If a controller action is particularly complex, you might find it convenient to dedicate an entire controller class to that single action. To accomplish this, you may define a single `__invoke` method within the controller:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
class ProvisionServer extends Controller
{
/**
* Provision a new web server.
*
* @return \Illuminate\Http\Response
*/
public function __invoke()
{
// ...
}
}
When registering routes for single action controllers, you do not need to specify a controller method. Instead, you may simply pass the name of the controller to the router:
use App\Http\Controllers\ProvisionServer;
Route::post('/server', ProvisionServer::class);
You may generate an invokable controller by using the `--invokable` option of the `make:controller` Artisan command:
```shell
php artisan make:controller ProvisionServer --invokable
```
> {tip} Controller stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization).
<a name="controller-middleware"></a>
## Controller Middleware
[Middleware](/docs/{{version}}/middleware) may be assigned to the controller's routes in your route files:
Route::get('profile', [UserController::class, 'show'])->middleware('auth');
Or, you may find it convenient to specify middleware within your controller's constructor. Using the `middleware` method within your controller's constructor, you can assign middleware to the controller's actions:
class UserController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('log')->only('index');
$this->middleware('subscribed')->except('store');
}
}
Controllers also allow you to register middleware using a closure. This provides a convenient way to define an inline middleware for a single controller without defining an entire middleware class:
$this->middleware(function ($request, $next) {
return $next($request);
});
<a name="resource-controllers"></a>
## Resource Controllers
If you think of each Eloquent model in your application as a "resource", it is typical to perform the same sets of actions against each resource in your application. For example, imagine your application contains a `Photo` model and a `Movie` model. It is likely that users can create, read, update, or delete these resources.
Because of this common use case, Laravel resource routing assigns the typical create, read, update, and delete ("CRUD") routes to a controller with a single line of code. To get started, we can use the `make:controller` Artisan command's `--resource` option to quickly create a controller to handle these actions:
```shell
php artisan make:controller PhotoController --resource
```
This command will generate a controller at `app/Http/Controllers/PhotoController.php`. The controller will contain a method for each of the available resource operations. Next, you may register a resource route that points to the controller:
use App\Http\Controllers\PhotoController;
Route::resource('photos', PhotoController::class);
This single route declaration creates multiple routes to handle a variety of actions on the resource. The generated controller will already have methods stubbed for each of these actions. Remember, you can always get a quick overview of your application's routes by running the `route:list` Artisan command.
You may even register many resource controllers at once by passing an array to the `resources` method:
Route::resources([
'photos' => PhotoController::class,
'posts' => PostController::class,
]);
<a name="actions-handled-by-resource-controller"></a>
#### Actions Handled By Resource Controller
Verb | URI | Action | Route Name
----------|------------------------|--------------|---------------------
GET | `/photos` | index | photos.index
GET | `/photos/create` | create | photos.create
POST | `/photos` | store | photos.store
GET | `/photos/{photo}` | show | photos.show
GET | `/photos/{photo}/edit` | edit | photos.edit
PUT/PATCH | `/photos/{photo}` | update | photos.update
DELETE | `/photos/{photo}` | destroy | photos.destroy
<a name="customizing-missing-model-behavior"></a>
#### Customizing Missing Model Behavior
Typically, a 404 HTTP response will be generated if an implicitly bound resource model is not found. However, you may customize this behavior by calling the `missing` method when defining your resource route. The `missing` method accepts a closure that will be invoked if an implicitly bound model can not be found for any of the resource's routes:
use App\Http\Controllers\PhotoController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
Route::resource('photos', PhotoController::class)
->missing(function (Request $request) {
return Redirect::route('photos.index');
});
<a name="specifying-the-resource-model"></a>
#### Specifying The Resource Model
If you are using [route model binding](/docs/{{version}}/routing#route-model-binding) and would like the resource controller's methods to type-hint a model instance, you may use the `--model` option when generating the controller:
```shell
php artisan make:controller PhotoController --model=Photo --resource
```
<a name="generating-form-requests"></a>
#### Generating Form Requests
You may provide the `--requests` option when generating a resource controller to instruct Artisan to generate [form request classes](/docs/{{version}}/validation#form-request-validation) for the controller's storage and update methods:
```shell
php artisan make:controller PhotoController --model=Photo --resource --requests
```
<a name="restful-partial-resource-routes"></a>
### Partial Resource Routes
When declaring a resource route, you may specify a subset of actions the controller should handle instead of the full set of default actions:
use App\Http\Controllers\PhotoController;
Route::resource('photos', PhotoController::class)->only([
'index', 'show'
]);
Route::resource('photos', PhotoController::class)->except([
'create', 'store', 'update', 'destroy'
]);
<a name="api-resource-routes"></a>
#### API Resource Routes
When declaring resource routes that will be consumed by APIs, you will commonly want to exclude routes that present HTML templates such as `create` and `edit`. For convenience, you may use the `apiResource` method to automatically exclude these two routes:
use App\Http\Controllers\PhotoController;
Route::apiResource('photos', PhotoController::class);
You may register many API resource controllers at once by passing an array to the `apiResources` method:
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\PostController;
Route::apiResources([
'photos' => PhotoController::class,
'posts' => PostController::class,
]);
To quickly generate an API resource controller that does not include the `create` or `edit` methods, use the `--api` switch when executing the `make:controller` command:
```shell
php artisan make:controller PhotoController --api
```
<a name="restful-nested-resources"></a>
### Nested Resources
Sometimes you may need to define routes to a nested resource. For example, a photo resource may have multiple comments that may be attached to the photo. To nest the resource controllers, you may use "dot" notation in your route declaration:
use App\Http\Controllers\PhotoCommentController;
Route::resource('photos.comments', PhotoCommentController::class);
This route will register a nested resource that may be accessed with URIs like the following:
/photos/{photo}/comments/{comment}
<a name="scoping-nested-resources"></a>
#### Scoping Nested Resources
Laravel's [implicit model binding](/docs/{{version}}/routing#implicit-model-binding-scoping) feature can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model. By using the `scoped` method when defining your nested resource, you may enable automatic scoping as well as instruct Laravel which field the child resource should be retrieved by. For more information on how to accomplish this, please see the documentation on [scoping resource routes](#restful-scoping-resource-routes).
<a name="shallow-nesting"></a>
#### Shallow Nesting
Often, it is not entirely necessary to have both the parent and the child IDs within a URI since the child ID is already a unique identifier. When using unique identifiers such as auto-incrementing primary keys to identify your models in URI segments, you may choose to use "shallow nesting":
use App\Http\Controllers\CommentController;
Route::resource('photos.comments', CommentController::class)->shallow();
This route definition will define the following routes:
Verb | URI | Action | Route Name
----------|-----------------------------------|--------------|---------------------
GET | `/photos/{photo}/comments` | index | photos.comments.index
GET | `/photos/{photo}/comments/create` | create | photos.comments.create
POST | `/photos/{photo}/comments` | store | photos.comments.store
GET | `/comments/{comment}` | show | comments.show
GET | `/comments/{comment}/edit` | edit | comments.edit
PUT/PATCH | `/comments/{comment}` | update | comments.update
DELETE | `/comments/{comment}` | destroy | comments.destroy
<a name="restful-naming-resource-routes"></a>
### Naming Resource Routes
By default, all resource controller actions have a route name; however, you can override these names by passing a `names` array with your desired route names:
use App\Http\Controllers\PhotoController;
Route::resource('photos', PhotoController::class)->names([
'create' => 'photos.build'
]);
<a name="restful-naming-resource-route-parameters"></a>
### Naming Resource Route Parameters
By default, `Route::resource` will create the route parameters for your resource routes based on the "singularized" version of the resource name. You can easily override this on a per resource basis using the `parameters` method. The array passed into the `parameters` method should be an associative array of resource names and parameter names:
use App\Http\Controllers\AdminUserController;
Route::resource('users', AdminUserController::class)->parameters([
'users' => 'admin_user'
]);
The example above generates the following URI for the resource's `show` route:
/users/{admin_user}
<a name="restful-scoping-resource-routes"></a>
### Scoping Resource Routes
Laravel's [scoped implicit model binding](/docs/{{version}}/routing#implicit-model-binding-scoping) feature can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model. By using the `scoped` method when defining your nested resource, you may enable automatic scoping as well as instruct Laravel which field the child resource should be retrieved by:
use App\Http\Controllers\PhotoCommentController;
Route::resource('photos.comments', PhotoCommentController::class)->scoped([
'comment' => 'slug',
]);
This route will register a scoped nested resource that may be accessed with URIs like the following:
/photos/{photo}/comments/{comment:slug}
When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the `Photo` model has a relationship named `comments` (the plural of the route parameter name) which can be used to retrieve the `Comment` model.
<a name="restful-localizing-resource-uris"></a>
### Localizing Resource URIs
By default, `Route::resource` will create resource URIs using English verbs. If you need to localize the `create` and `edit` action verbs, you may use the `Route::resourceVerbs` method. This may be done at the beginning of the `boot` method within your application's `App\Providers\RouteServiceProvider`:
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
Route::resourceVerbs([
'create' => 'crear',
'edit' => 'editar',
]);
// ...
}
Once the verbs have been customized, a resource route registration such as `Route::resource('fotos', PhotoController::class)` will produce the following URIs:
/fotos/crear
/fotos/{foto}/editar
<a name="restful-supplementing-resource-controllers"></a>
### Supplementing Resource Controllers
If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before your call to the `Route::resource` method; otherwise, the routes defined by the `resource` method may unintentionally take precedence over your supplemental routes:
use App\Http\Controller\PhotoController;
Route::get('/photos/popular', [PhotoController::class, 'popular']);
Route::resource('photos', PhotoController::class);
> {tip} Remember to keep your controllers focused. If you find yourself routinely needing methods outside of the typical set of resource actions, consider splitting your controller into two, smaller controllers.
<a name="dependency-injection-and-controllers"></a>
## Dependency Injection & Controllers
<a name="constructor-injection"></a>
#### Constructor Injection
The Laravel [service container](/docs/{{version}}/container) is used to resolve all Laravel controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor. The declared dependencies will automatically be resolved and injected into the controller instance:
<?php
namespace App\Http\Controllers;
use App\Repositories\UserRepository;
class UserController extends Controller
{
/**
* The user repository instance.
*/
protected $users;
/**
* Create a new controller instance.
*
* @param \App\Repositories\UserRepository $users
* @return void
*/
public function __construct(UserRepository $users)
{
$this->users = $users;
}
}
<a name="method-injection"></a>
#### Method Injection
In addition to constructor injection, you may also type-hint dependencies on your controller's methods. A common use-case for method injection is injecting the `Illuminate\Http\Request` instance into your controller methods:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Store a new user.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$name = $request->name;
//
}
}
If your controller method is also expecting input from a route parameter, list your route arguments after your other dependencies. For example, if your route is defined like so:
use App\Http\Controllers\UserController;
Route::put('/user/{id}', [UserController::class, 'update']);
You may still type-hint the `Illuminate\Http\Request` and access your `id` parameter by defining your controller method as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Update the given user.
*
* @param \Illuminate\Http\Request $request
* @param string $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
}
| Java |
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);
}
}
}
| Java |
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)))
| Java |
<?php
/*
* This file is part of the Integrated package.
*
* (c) e-Active B.V. <integrated@e-active.nl>
*
* 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 <gerjan@e-active.nl>
*/
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());
}
}
| Java |
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>
)
}
} | Java |
'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;
}
}
};
}
]); | Java |
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',
},
});
};
| Java |
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 | Java |
/**
* 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;
| Java |
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
| Java |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="http://www.entwicklungshilfe.nrw/typo3conf/ext/wmdb_base_ewh/Resources/Public/img/favicon.ico" type="image/x-icon">
<title>oh-my-zsh Präsentation von Php-Schulung Entwicklungshilfe</title>
<meta name="description" content="oh-my-zsh - Terminal effektiv mit Plugins nutzen PHP-Schulung">
<meta name="author" content="Entwicklungshilfe NRW">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/black.css">
<link rel="stylesheet" href="css/theme/eh.css">
<link rel="stylesheet" href="#" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
<script type="text/javascript">
if(window.location.search.substring(1)){
document.getElementById("theme").href = "css/theme/"+window.location.search.substring(1)+".css";
}
</script>
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>oh-my-zsh</h1>
<h3>Entwicklungshilfe</h3>
<p>
<a href="http://entwicklungshilfe.nrw" target="_blank">entwicklungshilfe.nrw</a> / <a href="http://twitter.com/help_for_devs" target="_blank">@help_for_devs</a> /
<a href="https://www.facebook.com/entwicklungshilfe.nrw" target="_blank">FB/entwicklungshilfe.nrw</a><br>
<small>
<a href="#" onclick="document.getElementById('theme').setAttribute('href','css/theme/black.css'); return false;">Black</a>
<a href="#" onclick="document.getElementById('theme').setAttribute('href','css/theme/white.css'); return false;">White</a>
<a href="#" onclick="document.getElementById('theme').setAttribute('href',''); return false;">EH</a>
</small>
</p>
<aside class="notes">
Don't forget notes
</aside>
</section>
<section>
<section>
<p>
<h3>Powerline font</h3>
<a href="https://github.com/powerline/fonts/blob/master/Meslo/Meslo%20LG%20L%20DZ%20Regular%20for%20Powerline.otf" target="_blank">
https://github.com/powerline/fonts/blob/master/Meslo/Meslo%20LG%20L%20DZ%20Regular%20for%20Powerline.otf
</a><br>
press raw and install <br>
<h4>ZSH installieren</h4>
<a href="https://github.com/robbyrussell/oh-my-zsh" target="_blank">https://github.com/robbyrussell/oh-my-zsh</a><br>
curl -L https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh | sh<br>
or<br>
wget https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O - | sh
</p>
</section>
<section>
<h2>Installation</h2>
<h3>Solarized Theme</h3>
<a href="http://ethanschoonover.com/solarized/files/solarized.zip" target="_blank">http://ethanschoonover.com/solarized/files/solarized.zip</a><br>
unpack and in folder "iterm2-colors-solarized" the "Solrized Dark.itermcolors" double click
</section>
<section>
<h2>Installation</h2>
Open iTerm and pres "cmd + ," at colors "Load Presents" dropdown "Solarized dark".
<p>
<img src="img/oh-my-zsh/SOLARIZED-THEME.png" alt="SOLARIZED THEME iTerm">
</p>
</section>
<section>
<h2>Installation</h2>
Set the new font
<p>
<img src="img/oh-my-zsh/font-settings.png" alt="iTerm font setting">
</p>
</section>
<section>
<h2>Installation</h2>
brew install fortune <br>
brew install cowsay <br>
vim .zshrc<br>
ZSH_THEME="agnoster"<br>
plugins=(git jump jira osx z extract chucknorris history zsh-syntax-highlighting vi-mode web-search history-substring-search)<br>
Iterm restart or open new tab. Enter this command<br>
echo -e "\ue0a0 \ue0a1 \ue0a2 \ue0b0 \ue0b1 \ue0b2"
<p>
<img src="img/oh-my-zsh/test-output.png" alt="oh-my-zsh output">
</p>
</section>
</section>
<section>
<section>
<h2>Sources</h2>
Plugin wiki<br>
<a href="https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins" target="_blank">https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins</a><br>
Cheatsheet<br>
<a href="https://github.com/robbyrussell/oh-my-zsh/wiki/Cheatsheet" target="_blank">https://github.com/robbyrussell/oh-my-zsh/wiki/Cheatsheet</a>
</section>
<section>
<h2>Directories</h2>
<table>
<thead>
<tr>
<th>Alias</th>
<th>Command</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>alias</em></td>
<td align="left">list all aliases</td>
</tr>
<tr>
<td align="left">..</td>
<td align="left">cd ..</td>
</tr>
<tr>
<td align="left">...</td>
<td align="left">cd ../..</td>
</tr>
<tr>
<td align="left">....</td>
<td align="left">cd ../../..</td>
</tr>
<tr>
<td align="left">.....</td>
<td align="left">cd ../../../..</td>
</tr>
<tr>
<td align="left">/</td>
<td align="left">cd /</td>
</tr>
<tr>
<td align="left"><em>md</em></td>
<td align="left">mkdir -p</td>
</tr>
<tr>
<td align="left"><em>rd</em></td>
<td align="left">rmdir</td>
</tr>
<tr>
<td align="left"><em>d</em></td>
<td align="left">dirs -v (lists last used directories)</td>
</tr>
<tr>
<td align="left"><em>~3</em></td>
<td align="left">cd to dir -v 3</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>Usefull git alias</h2>
<table>
<thead>
<tr>
<th>Alias</th>
<th>Command</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>gst</em></td>
<td align="left">git status</td>
</tr>
<tr>
<td align="left"><em>gf</em></td>
<td align="left">git fetch</td>
</tr>
<tr>
<td align="left"><em>gl</em></td>
<td align="left">git pull</td>
</tr>
<tr>
<td align="left"><em>gp</em></td>
<td align="left">git push</td>
</tr>
<tr>
<td align="left"><em>gaa</em></td>
<td align="left">git add --all</td>
</tr>
<tr>
<td align="left"><em>gco</em></td>
<td align="left">git checkout</td>
</tr>
<tr>
<td align="left"><em>gcmsg</em></td>
<td align="left">git commit -m</td>
</tr>
<tr>
<td align="left"><em>gclean</em></td>
<td align="left">git clean -fd</td>
</tr>
<tr>
<td align="left"><em>gcb</em></td>
<td align="left">git checkout -b</td>
</tr>
<tr>
<td align="left"><em>gcm</em></td>
<td align="left">git checkout master</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>Jump plugin</h2>
<table>
<thead>
<tr>
<th>Alias</th>
<th>Command</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>mark</em></td>
<td align="left">mark actual folder with name as mark</td>
</tr>
<tr>
<td align="left"><em>mark yourname</em></td>
<td align="left">mark actual folder with yourname as mark</td>
</tr>
<tr>
<td align="left"><em>jump yourname</em></td>
<td align="left">jump to folder yourname</td>
</tr>
<tr>
<td align="left"><em>unmark yourname</em></td>
<td align="left">remove</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>OSX plugin</h2>
<table>
<thead>
<tr>
<th align="left">Command</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>tab</em></td>
<td align="left">open the current directory in a new tab</td>
</tr>
<tr>
<td align="left"><em>cdf</em></td>
<td align="left">cd to the current Finder directory</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>JIRA plugin</h2>
<table>
<thead>
<tr>
<th align="left">Command</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>jira</em></td>
<td align="left">Open new issue form in browser</td>
</tr>
<tr>
<td align="left"><em>jira ABC-123</em></td>
<td align="left">Open issue in browser</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>History plugin</h2>
<table>
<thead>
<tr>
<th align="left">Alias</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>h</em></td>
<td align="left">List your command history. Equivalent to using <code>history</code>
</td>
</tr>
<tr>
<td align="left"><em>hsi</em></td>
<td align="left">When called without an argument you will get help on <code>grep</code> arguments</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>Extract plugin</h2>
<table>
<thead>
<tr>
<th align="left">Alias</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>extract filename</em></td>
<td align="left">Extract any compressed file<code>history</code>
</td>
</tr>
</tbody>
</table>
</section>
</section>
<section style="text-align: left;">
<h1>Questions?</h1>
</section>
<section style="text-align: left;">
<h1>Thanks</h1>
</section>
<section style="text-align: left;">
<h1>Follow us!</h1>
<div class="col"><i class="follow-icon"><img src="img/twitter.png" alt="Entwicklungshilfe NRW Twitter"></i> <a href="https://twitter.com/help_for_devs" target="_blank">https://twitter.com/help_for_devs</a></div>
<div class="col"><i class="follow-icon"><img src="img/facebook.png" alt="Entwicklungshilfe NRW Facebook"></i> <a href="https://www.facebook.com/entwicklungshilfe.nrw" target="_blank">https://www.facebook.com/entwicklungshilfe.nrw</a></div>
<div class="col"><i class="follow-icon"><img src="img/github.png" alt="Entwicklungshilfe NRW Github"></i> <a href="https://github.com/entwicklungshilfe-nrw" target="_blank">https://github.com/entwicklungshilfe-nrw</a></div>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Optional reveal.js plugins
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, condition: function() { return !!document.querySelector( 'pre code' ); }, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true },
{ src: 'plugin/notes/notes.js', async: true }
]
});
</script>
<script src="js/ga.js"></script>
</body>
</html>
| Java |
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);
}
}
| Java |
'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();
}
});
}
});
};
}; | Java |
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);
}}));
}
} | Java |
(function(){
'use strict';
angular.module('GamemasterApp')
.controller('DashboardCtrl', function ($scope, $timeout, $mdSidenav, $http) {
$scope.users = ['Fabio', 'Leonardo', 'Thomas', 'Gabriele', 'Fabrizio', 'John', 'Luis', 'Kate', 'Max'];
})
})(); | Java |
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
| Java |
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
| Java |
const express = require('express');
const router = express.Router();
const routes = require('./routes')(router);
module.exports = router;
| Java |
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;
}
}
| Java |
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",
},
},
};
| Java |
<!DOCTYPE html>
<!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en" dir="ltr">
<!--<![endif]-->
<!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) -->
<!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca -->
<head>
<!-- Title begins / Début du titre -->
<title>
Groupe Giroux -
Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
</title>
<!-- Title ends / Fin du titre -->
<!-- Meta-data begins / Début des métadonnées -->
<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />
<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />
<!-- EPI-11240 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- MCG-202 -->
<meta content="width=device-width,initial-scale=1" name="viewport">
<!-- EPI-11567 -->
<meta name = "format-detection" content = "telephone=no">
<!-- EPI-12603 -->
<meta name="robots" content="noarchive">
<!-- EPI-11190 - Webtrends -->
<script>
var startTime = new Date();
startTime = startTime.getTime();
</script>
<!--[if gte IE 9 | !IE ]><!-->
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">
<!--<![endif]-->
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">
<!--[if lt IE 9]>
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" />
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script>
<![endif]-->
<!--[if lte IE 9]>
<![endif]-->
<noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript>
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<script>dataLayer1 = [];</script>
<!-- End Google Tag Manager -->
<!-- EPI-11235 -->
<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body class="home" vocab="http://schema.org/" typeof="WebPage">
<!-- EPIC HEADER BEGIN -->
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script>
<!-- End Google Tag Manager -->
<!-- EPI-12801 -->
<span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span>
<ul id="wb-tphp">
<li class="wb-slc">
<a class="wb-sl" href="#wb-cont">Skip to main content</a>
</li>
<li class="wb-slc visible-sm visible-md visible-lg">
<a class="wb-sl" href="#wb-info">Skip to "About this site"</a>
</li>
</ul>
<header role="banner">
<div id="wb-bnr" class="container">
<section id="wb-lng" class="visible-md visible-lg text-right">
<h2 class="wb-inv">Language selection</h2>
<div class="row">
<div class="col-md-12">
<ul class="list-inline mrgn-bttm-0">
<li><a href="nvgt.do?V_TOKEN=1492289850357&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=20428&V_SEARCH.docsStart=20427&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/updt.sec?_flId?_flxKy=e1s1&estblmntNo=234567041301&profileId=61&_evId=bck&lang=eng&V_SEARCH.showStricts=false&prtl=1&_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li>
</ul>
</div>
</div>
</section>
<div class="row">
<div class="brand col-xs-8 col-sm-9 col-md-6">
<a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a>
</div>
<section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn">
<h2>Search and menus</h2>
<ul class="list-inline text-right chvrn">
<li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li>
</ul>
<div id="mb-pnl"></div>
</section>
<!-- Site Search Removed -->
</div>
</div>
<nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement">
<h2 class="wb-inv">Topics menu</h2>
<div class="container nvbar">
<div class="row">
<ul class="list-inline menu">
<li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li>
<li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li>
<li><a href="https://travel.gc.ca/">Travel</a></li>
<li><a href="https://www.canada.ca/en/services/business.html">Business</a></li>
<li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li>
<li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li>
<li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li>
<li><a href="https://www.canada.ca/en/services.html">More services</a></li>
</ul>
</div>
</div>
</nav>
<!-- EPIC BODY BEGIN -->
<nav role="navigation" id="wb-bc" class="" property="breadcrumb">
<h2 class="wb-inv">You are here:</h2>
<div class="container">
<div class="row">
<ol class="breadcrumb">
<li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li>
<li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li>
<li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li>
</ol>
</div>
</div>
</nav>
</header>
<main id="wb-cont" role="main" property="mainContentOfPage" class="container">
<!-- End Header -->
<!-- Begin Body -->
<!-- Begin Body Title -->
<!-- End Body Title -->
<!-- Begin Body Head -->
<!-- End Body Head -->
<!-- Begin Body Content -->
<br>
<!-- Complete Profile -->
<!-- Company Information above tabbed area-->
<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>
<h1 id="wb-cont">
Company profile - Canadian Company Capabilities
</h1>
<div class="profileInfo hidden-print">
<ul class="list-inline">
<li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&rstBtn.x=" class="btn btn-link">New Search</a> |</li>
<li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">
<input type="hidden" name="lang" value="eng" />
<input type="hidden" name="profileId" value="" />
<input type="hidden" name="prtl" value="1" />
<input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" />
<input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />
<input type="hidden" name="V_SEARCH.depth" value="1" />
<input type="hidden" name="V_SEARCH.showStricts" value="false" />
<input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />
</form></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=20426&V_DOCUMENT.docRank=20427&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492289857012&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567088754&profileId=&key.newSearchLabel=">Previous Company</a></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=20428&V_DOCUMENT.docRank=20429&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492289857012&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567144903&profileId=&key.newSearchLabel=">Next Company</a></li>
</ul>
</div>
<details>
<summary>Third-Party Information Liability Disclaimer</summary>
<p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p>
</details>
<h2>
Groupe Giroux
</h2>
<div class="row">
<div class="col-md-5">
<h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2>
<p>Groupe Giroux</p>
<div class="mrgn-tp-md"></div>
<p class="mrgn-bttm-0" ><a href="http://www.arpentage.com"
target="_blank" title="Website URL">http://www.arpentage.com</a></p>
<p><a href="mailto:grg@arpentage.com" title="grg@arpentage.com">grg@arpentage.com</a></p>
</div>
<div class="col-md-4 mrgn-sm-sm">
<h2 class="h5 mrgn-bttm-0">Mailing Address:</h2>
<address class="mrgn-bttm-md">
675, boul. Alphonse-Desjardins<br/>
Bureau 102<br/>
LÉVIS,
Quebec<br/>
G6V 5T3
<br/>
</address>
<h2 class="h5 mrgn-bttm-0">Location Address:</h2>
<address class="mrgn-bttm-md">
675, boul. Alphonse-Desjardins<br/>
Bureau 102<br/>
LÉVIS,
Quebec<br/>
G6V 5T3
<br/>
</address>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(418) 652-8838
</p>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(866) 838-9961</p>
<p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>:
(418) 652-0119</p>
</div>
<div class="col-md-3 mrgn-tp-md">
</div>
</div>
<div class="row mrgn-tp-md mrgn-bttm-md">
<div class="col-md-12">
<h2 class="wb-inv">Company Profile</h2>
<br> Services en arpentage foncier et de construction.
<br>Cadastres, certificats de localisation, relevés topographiques,
<br>Mesurage d'espaces locatifs, cadastre vertical (copropriété).
<br>Implantation de structures et de bâtiments de toutes natures,
<br>etc..<br>
</div>
</div>
<!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> -->
<div class="wb-tabs ignore-session">
<div class="tabpanels">
<details id="details-panel1">
<summary>
Full profile
</summary>
<!-- Tab 1 -->
<h2 class="wb-invisible">
Full profile
</h2>
<!-- Contact Information -->
<h3 class="page-header">
Contact information
</h3>
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
ALAIN
GOSSELIN
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
ARPENTEUR-GEOMETRE <br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(418) 838-9961
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(418) 832-7180
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
agosseli@riq.qc.ca
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Company Description -->
<h3 class="page-header">
Company description
</h3>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1971
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
541370 - Surveying and Mapping (except Geophysical) Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
12
</div>
</div>
</section>
<!-- Products / Services / Licensing -->
<h3 class="page-header">
Product / Service / Licensing
</h3>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Land surveying <br>
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Technology Profile -->
<!-- Market Profile -->
<!-- Sector Information -->
<details class="mrgn-tp-md mrgn-bttm-md">
<summary>
Third-Party Information Liability Disclaimer
</summary>
<p>
Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.
</p>
</details>
</details>
<details id="details-panel2">
<summary>
Contacts
</summary>
<h2 class="wb-invisible">
Contact information
</h2>
<!-- Contact Information -->
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
ALAIN
GOSSELIN
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
ARPENTEUR-GEOMETRE <br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(418) 838-9961
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(418) 832-7180
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
agosseli@riq.qc.ca
</div>
</div>
</section>
</details>
<details id="details-panel3">
<summary>
Description
</summary>
<h2 class="wb-invisible">
Company description
</h2>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1971
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
541370 - Surveying and Mapping (except Geophysical) Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
12
</div>
</div>
</section>
</details>
<details id="details-panel4">
<summary>
Products, services and licensing
</summary>
<h2 class="wb-invisible">
Product / Service / Licensing
</h2>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Land surveying <br>
</div>
</div>
</section>
</details>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
Last Update Date 2017-03-03
</div>
</div>
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
<!-- End Body Content -->
<!-- Begin Body Foot -->
<!-- End Body Foot -->
<!-- END MAIN TABLE -->
<!-- End body -->
<!-- Begin footer -->
<div class="row pagedetails">
<div class="col-sm-5 col-xs-12 datemod">
<dl id="wb-dtmd">
<dt class=" hidden-print">Date Modified:</dt>
<dd class=" hidden-print">
<span><time>2017-03-02</time></span>
</dd>
</dl>
</div>
<div class="clear visible-xs"></div>
<div class="col-sm-4 col-xs-6">
</div>
<div class="col-sm-3 col-xs-6 text-right">
</div>
<div class="clear visible-xs"></div>
</div>
</main>
<footer role="contentinfo" id="wb-info">
<nav role="navigation" class="container wb-navcurr">
<h2 class="wb-inv">About government</h2>
<!-- EPIC FOOTER BEGIN -->
<!-- EPI-11638 Contact us -->
<ul class="list-unstyled colcount-sm-2 colcount-md-3">
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&from=Industries">Contact us</a></li>
<li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li>
<li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li>
<li><a href="https://www.canada.ca/en/news.html">News</a></li>
<li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li>
<li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li>
<li><a href="http://pm.gc.ca/eng">Prime Minister</a></li>
<li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li>
<li><a href="http://open.canada.ca/en/">Open government</a></li>
</ul>
</nav>
<div class="brand">
<div class="container">
<div class="row">
<nav class="col-md-10 ftr-urlt-lnk">
<h2 class="wb-inv">About this site</h2>
<ul>
<li><a href="https://www.canada.ca/en/social.html">Social media</a></li>
<li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li>
<li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li>
</ul>
</nav>
<div class="col-xs-6 visible-sm visible-xs tofpg">
<a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a>
</div>
<div class="col-xs-6 col-md-2 text-right">
<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>
</div>
</div>
</div>
</div>
</footer>
<!--[if gte IE 9 | !IE ]><!-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script>
<!--<![endif]-->
<!--[if lt IE 9]>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script>
<![endif]-->
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script>
<!-- EPI-10519 -->
<span class="wb-sessto"
data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span>
<script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script>
<!-- EPI-11190 - Webtrends -->
<script src="/eic/home.nsf/js/webtrends.js"></script>
<script>var endTime = new Date();</script>
<noscript>
<div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&WT.js=No&WT.tv=9.4.0&dcssip=www.ic.gc.ca"/></div>
</noscript>
<!-- /Webtrends -->
<!-- JS deps -->
<script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script>
<!-- EPI-11262 - Util JS -->
<script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script>
<!-- EPI-11383 -->
<script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script>
<span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span>
</body></html>
<!-- End Footer -->
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
| Java |
# What is fakeLoader.js
fakeLoader.js is a lightweight jQuery plugin that helps you create an animated spinner with a fullscreen loading mask to simulate the page preloading effect.
Check out the demo [http://joaopereirawd.github.io/fakeLoader.js/](http://joaopereirawd.github.io/fakeLoader.js)
## Current Version
`V2.0.0`
### 1. Installing
```js
yarn add jq-fakeloader
or
npm i jq-fakeloader
```
### 2. Include CSS
```css
<link rel="stylesheet" href="../node_modules/dist/fakeLoader.min.css">
```
### 3. Include `javascript` dependencies
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
<script src="../node_modules/dist/fakeLoader.min.js">
```
### 4. Include `fakeLoader` placeholder in the HTML Document
```
<div class="fakeLoader"></div>
```
### 5. Basic Initialize
```js
<script>
$.fakeLoader();
</script>
```
### 6. Options
`timeToHide` //Time in milliseconds for fakeLoader disappear
`spinner` //'spinner1', 'spinner2', 'spinner3', 'spinner4', 'spinner5', 'spinner6', 'spinner7'
`bgColor` //Hex, RGB or RGBA colors
### Support
If you encounter an issue or want to request a feature, you can create an [issue](https://github.com/joaopereirawd/fakeLoader.js/issues)
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>alternative Standard Libary: Elementverzeichnis</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<link href="../../navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../resize.js"></script>
<script type="text/javascript" src="../../navtreedata.js"></script>
<script type="text/javascript" src="../../navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="../../Logo128x128.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">alternative Standard Libary
 <span id="projectnumber">0.29.8</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Erzeugt von Doxygen 1.8.13 -->
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('../../',false,false,'search.php','Suchen');
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('da/d13/classstd_1_1_sys.html','../../');});
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">std::Sys Elementverzeichnis</div> </div>
</div><!--header-->
<div class="contents">
<p>Vollständige Aufstellung aller Elemente für <a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a> einschließlich aller geerbten Elemente.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ac9f240e055773c6ef6b320ed3d9f3acf">fClose</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ac9cb96093b35fe96793d756c2888a1f1">fEOF</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a8fd94047f1bedca9a81b335874d2733a">fError</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a610720c05d13d45ac5f1ad892feaef7f">fFlush</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ae69ad2e413c751ae56644ccf69daba3a">fGetc</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a6e4d49f77b2b856c91a44a38b64c1d53">fIsFile</a>(const char *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#aee6ea3afc7237d4234b5bc43dc3231c6">fOpen</a>(const char *file, const char *fmt)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a025c18bdd6a88e4d26482d10429a95ec">fPrintf</a>(void *file, const char *str)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a2f3038727c96c808d92532b62382e037">fPutc</a>(int c, void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a27592f565d19984eac4e5c16dbb52429">fPuts</a>(const char *str, void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a8e07d03fdef76804b9a6eea7e97e1035">fRead</a>(void *data, const int count, const int size, void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ac14981aad284603b985b1e6470843e88">fSeek</a>(void *file, int off, int org)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#aca38e582c676c1087650aef98c7c0543">fTell</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a8032132dd583eb289416a1b19ce85e37">fWrite</a>(void *data, const int count, const int size, void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a3ae3057f26fbb3e72e4a8af62efdf5c6">mAlloc</a>(size_t size)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a04e4cc78efb94cd4b50162d1637288ae">mAllocE</a>(int elements)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a9c9c270714511ce17ca1ffd134597907">MemCpy</a>(void *to, const void *from, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#abf561c077094bd7b266b7734c73e66da">MemMove</a>(void *to, const void *from, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ad5bfc790ccaf985e62ad98da9c947ab0">MemSet</a>(void *buf, unsigned char value, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a9a9b2d41667f1c106815c6f9edc698fc">mFree</a>(void *mem)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a0d71e77caef7d86e01af361b1cb13353">mReAlloc</a>(void *old, size_t newSize)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ac4f3ff28de45a311f03a1e72af0c15f9">mutex_init_t</a> enum-Bezeichner</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#af9f019109cea02d650c0da099f1d70a2">mutex_type</a> typedef</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#abfb1f1b9ac68790344334a2200e8021c">mutexDestroy</a>(mutex_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a6c0d6b0dc8bbe584027581f446d4279d">mutexInit</a>(mutex_type *mutex, mutex_init_t type=mutex_init_t::Normal, bool shared=false, bool robust=false)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#acef59477c62a5153727cba3626c5e259">mutexLock</a>(mutex_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#abe695d31d915cdc7c2476bfbeae35a0e">mutexTryLock</a>(mutex_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a7221035092b3fa10172d60c821a1064a">mutexUnLock</a>(mutex_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a2fa77232e349020516438ac4940e8f1a">pTotalMem</a>()</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a19eaed4ae0cf3ec1e333b6f9901d67a7">spinlk_type</a> typedef</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a3e7ba115ebb0f563e37927cfb7e85344">spinlockDestroy</a>(spinlk_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a65e031f3724520464f9a98dc7bb48e9e">spinlockInit</a>(spinlk_type *mutex, const void *attr)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#abcb5c5bcc747c46c3670944a327727af">spinlockLock</a>(spinlk_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a9453448f147d0c2d83187ec2c8033089">spinlockTryLock</a>(spinlk_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ae408c7a7438d031c7c853229a31eff63">spinlockUnLock</a>(spinlk_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a478df7ee0c293a50d589680380c9cbfc">vsnPrintf</a>(char *buffer, size_t count, const char *format, va_list argptr)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#aac49efae5fffa0c4ab9fd88060b8f218">wMemCpy</a>(void *to, const void *from, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a3979b4517ff8cad46e14abf65d9604cc">wMemMove</a>(void *to, const void *from, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a7df3f8541dc4ba26336983134b6772d3">wMemSet</a>(void *buf, unsigned char value, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Erzeugt von
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
| Java |
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;
}
})
]
};
| Java |
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)
}, ''))
}
}
| Java |
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);
}
}
| Java |
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import <CoreData/NSSQLIntermediate.h>
// Not exported
@interface NSSQLLimitIntermediate : NSSQLIntermediate
{
unsigned long long _limit;
}
- (id)generateSQLStringInContext:(id)arg1;
- (id)initWithLimit:(unsigned long long)arg1 inScope:(id)arg2;
@end
| Java |
version https://git-lfs.github.com/spec/v1
oid sha256:e40a08695f05163cfb0eaeeef4588fcfad55a6576cfadfb079505495605beb33
size 27133
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Stranger Things Wall</title>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<img src="img/vacio.gif" alt="" id="img" class="img"/>
<p class="txt">Presiona una tecla</p>
<script src="js/script.js"></script>
</body>
</html>
| Java |
<?php
class Thread extends Eloquent {
public static $table = 'threads';
public static $timestamps = true;
public function replies()
{
return $this->has_many('Reply');
}
} | Java |
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<title>Blog | Guilherme Matheus Costa</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link href="/css/essentials.min.css" rel="stylesheet" type="text/css"/>
<meta property="og:site_name" content="Guilherme Matheus Costa"/>
</head>
<body>
<h1>Guilherme Matheus Costa</h1>
<h2>Resume</h2>
</body>
</html> | Java |
#!/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()
| Java |
/**
* 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 };
| Java |
/*
* Copyright 2016 Christoph Brill <egore911@gmail.com>
*
* 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 <egore911@gmail.com>
*/
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;
}
}
}
| Java |
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);
} | Java |
#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()));
}
}
| Java |
{!!
Form::select(
'routes[]',
$allRoutes,
(isset($routes) ? array_keys($routes) : []),
array(
'class' => 'form-control select2',
'placeholder' => 'Enter Routes',
'multiple' => true
)
)
!!}
| Java |
<?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);
}
} | Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Pesho")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pesho")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fc740c6d-ec21-40c6-ad6d-6823d61e8446")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
@charset "utf-8";
/* CSS Document */
/* -------------------------------------------------------------------------- */
/* BASE AD - typically, we do not mess with this section
/* -------------------------------------------------------------------------- */
body, body * {
vertical-align: baseline;
border: 0;
outline: 0;
padding: 0;
margin: 0;
}
/* Div layer for the entire banner. */
#adkit_container {
position: absolute;
width: {{width}}px;
height: {{height}}px;
border: #9b9b9b 1px solid;
top: 0;
left: 0;
margin: auto;
overflow: hidden;
display: none;
}
#adkit_content {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 100;
}
/* Invisible button for background clickthrough. */
#adkit_background_exit {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
cursor: pointer;
opacity: 0;
z-index: 400;
}
:focus {
outline: none;
}
::-moz-focus-inner {
border: 0;
}
/* -------------------------------------------------------------------------- */
/* Your ad styles here */
| Java |
<article class="home_single_post gallery_post_type" typeof="BlogPosting">
{{ partial "post/image_area.html" . }}
<div class="post_content_area">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 col-xs-offset-0 col-sm-offset-2 col-md-offset-2 col-lg-offset-2">
<div class="post_list" property="articleBody">
<header><h2><a href="{{ .Permalink }}" property="headline">{{ .Title }}</a></h2></header>
</div>
{{ partial "post/info.html" . }}
</div>
</div>
</div>
</article>
| Java |
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
| Java |
/* 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
| Java |
"""
[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()
| Java |
/**
*
* 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";
}
| Java |
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 | Java |
//
// Copyright (C) 2006-2008 Mateusz Loskot
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef SOCI_PLATFORM_H_INCLUDED
#define SOCI_PLATFORM_H_INCLUDED
#if defined(_MSC_VER) || defined(__MINGW32__)
#define LL_FMT_FLAGS "I64"
#else
#define LL_FMT_FLAGS "ll"
#endif
// Portability hacks for Microsoft Visual C++ compiler
#ifdef _MSC_VER
#include <stdlib.h>
// Define if you have the vsnprintf variants.
#if _MSC_VER < 1500
# define vsnprintf _vsnprintf
#endif
// Define if you have the snprintf variants.
#if _MSC_VER < 1900
#define snprintf _snprintf
#endif
// Define if you have the strtoll and strtoull variants.
#if _MSC_VER < 1300
# error "Visual C++ versions prior 1300 don't support _strtoi64 and _strtoui64"
#elif _MSC_VER >= 1300 && _MSC_VER < 1800
namespace std {
inline long long strtoll(char const* str, char** str_end, int base)
{
return _strtoi64(str, str_end, base);
}
inline unsigned long long strtoull(char const* str, char** str_end, int base)
{
return _strtoui64(str, str_end, base);
}
}
#endif // _MSC_VER < 1800
#endif // _MSC_VER
#if defined(__CYGWIN__) || defined(__MINGW32__)
#include <stdlib.h>
namespace std {
using ::strtoll;
using ::strtoull;
}
#endif
#endif // SOCI_PLATFORM_H_INCLUDED
| Java |
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);
}
}
}
}
| Java |
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);
}
} | Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>/home/pavm/programming/lib/gft/src/gft_stack.cpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!-- end header part -->
<!-- Generated by Doxygen 1.8.6 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#namespaces">Namespaces</a> |
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">gft_stack.cpp File Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><code>#include "<a class="el" href="gft__stack_8h_source.html">gft_stack.h</a>"</code><br/>
</div><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a>
Namespaces</h2></td></tr>
<tr class="memitem:namespacegft"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft.html">gft</a></td></tr>
<tr class="memdesc:namespacegft"><td class="mdescLeft"> </td><td class="mdescRight">Base namespace for common definitions and prototypes. <br/></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:namespacegft_1_1Stack"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html">gft::Stack</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:aae4b11552918128f72c2c0ce6769ea00"><td class="memItemLeft" align="right" valign="top">Stack * </td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#aae4b11552918128f72c2c0ce6769ea00">gft::Stack::Create</a> (int n)</td></tr>
<tr class="separator:aae4b11552918128f72c2c0ce6769ea00"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac9833a76111d61f284fe131a8439ea79"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#ac9833a76111d61f284fe131a8439ea79">gft::Stack::Destroy</a> (Stack **S)</td></tr>
<tr class="separator:ac9833a76111d61f284fe131a8439ea79"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a9d1618c9defa1ad3e683b7c57d0e3075"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#a9d1618c9defa1ad3e683b7c57d0e3075">gft::Stack::Push</a> (Stack *S, int p)</td></tr>
<tr class="separator:a9d1618c9defa1ad3e683b7c57d0e3075"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a58729721489e11127a35700782ed0ae2"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#a58729721489e11127a35700782ed0ae2">gft::Stack::Pop</a> (Stack *S)</td></tr>
<tr class="separator:a58729721489e11127a35700782ed0ae2"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Feb 25 2015 10:27:50 by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.6
</small></address>
</body>
</html>
| Java |
//
// BABAudioPlaylist.h
// Pods
//
// Created by Bryn Bodayle on May/12/2015.
//
//
#import <Foundation/Foundation.h>
@interface BABAudioPlaylist : NSObject
+ (instancetype)audioPlaylistWithArray:(NSArray *)array;
- (instancetype)initWithArray:(NSArray *)array;
- (id)objectAtIndexedSubscript:(NSUInteger)idx;
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;
@property (nonatomic, readonly) NSInteger count;
@end
| Java |
/*!
* 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;
| Java |
# -*- 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
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_05) on Thu Jul 03 13:49:54 PDT 2008 -->
<TITLE>
edu.sdsc.inca
</TITLE>
<META NAME="keywords" CONTENT="edu.sdsc.inca package">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../edu/sdsc/inca/package-summary.html" target="classFrame">edu.sdsc.inca</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="Consumer.html" title="class in edu.sdsc.inca" target="classFrame">Consumer</A>
<BR>
<A HREF="ConsumerTest.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest</A>
<BR>
<A HREF="ConsumerTest.ConsumerTester.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest.ConsumerTester</A>
<BR>
<A HREF="ConsumerTest.MockAgent.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest.MockAgent</A>
<BR>
<A HREF="ConsumerTest.MockDepot.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest.MockDepot</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| Java |
// 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;
}
}
}
| Java |
/*
* Search first occurence of a particular string in a given text [Finite Automata]
* Author: Progyan Bhattacharya <progyanb@acm.org>
* Repo: Design-And-Analysis-of-Algorithm [MIT LICENSE]
*/
#include "Search.h"
static int NextState(int m, char* pattern, int state, int symbol) {
if (state < m && pattern[state] == symbol) {
return state + 1;
}
for (int next = state, prev = next - 1, i = 0; next > 0; next--) {
if (pattern[prev] == symbol) {
for (i = 0; i < prev; i++) {
if (pattern[i] != pattern[state - next + 1 + i]) {
break;
}
}
if (i == prev) {
return next;
}
}
}
return 0;
}
static void GenerateTable(int m, char* pattern, int Table[m][CHAR_MAX]) {
for (int state = 0, symbol = 0; symbol < CHAR_MAX || (symbol = 0, ++state) < m; symbol++) {
Table[state][symbol] = NextState(m, pattern, state, symbol);
}
}
int Search(int n, char* haystack, int m, char* needle) {
int Table[m + 1][CHAR_MAX], state = 0;
GenerateTable(m + 1, needle, Table);
for (int i = 0; i < n; i++) {
state = Table[state][haystack[i]];
if (state == m) {
return (i - m + 1);
}
}
return -1;
}
| Java |
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 | Java |
PathMission
===========
### Prefix: pm
------------------------------------------------------------------------
`Enum`
PathMissionDisplayType
----------------------
- **Soldier\_Assassination**
- **Soldier\_Defend**
- **Soldier\_Demolition**
- **Soldier\_FirstStrike**
- **Soldier\_Holdout**
- **Soldier\_RescueOp**
- **Soldier\_Security**
- **Soldier\_Swat**
- **Settler\_Cache**
- **Settler\_CivilService**
- **Settler\_Expansion**
- **Settler\_Project**
- **Settler\_PublicSafety**
- **Scientist\_Analysis**
- **Scientist\_Archaeology**
- **Scientist\_Biology**
- **Scientist\_Botany**
- **Scientist\_Chemistry**
- **Scientist\_DatacubeDecryption**
- **Scientist\_Diagnostics**
- **Scientist\_Experimentation**
- **Scientist\_FieldStudy**
- **Scientist\_SpecimenSurvey**
- **Explorer\_Cartography**
- **Explorer\_Exploration**
- **Explorer\_Operations**
- **Explorer\_ScavengerHunt**
- **Explorer\_StakingClaim**
- **Explorer\_Surveillance**
- **Explorer\_Tracking**
- **Explorer\_Vista**
------------------------------------------------------------------------
`Function`
is()
----
------------------------------------------------------------------------
`Method`
\_\_eq() (Deprecated)
---------------------
------------------------------------------------------------------------
`Method`
\_\_gc() (Deprecated)
---------------------
------------------------------------------------------------------------
`Method`
AttemptScientistExperimentation()
---------------------------------
------------------------------------------------------------------------
`Method`
GetCompletedString()
--------------------
------------------------------------------------------------------------
`Method`
GetDisplayType()
----------------
------------------------------------------------------------------------
`Method`
GetDistance()
-------------
------------------------------------------------------------------------
`Method`
GetEpisode()
------------
------------------------------------------------------------------------
`Method`
GetExplorerClueRatio()
----------------------
------------------------------------------------------------------------
`Method`
GetExplorerClueStatus()
-----------------------
------------------------------------------------------------------------
`Method`
GetExplorerClueString()
-----------------------
------------------------------------------------------------------------
`Method`
GetExplorerClueType()
---------------------
------------------------------------------------------------------------
`Method`
GetExplorerHuntSprite()
-----------------------
------------------------------------------------------------------------
`Method`
GetExplorerHuntStartCreature()
------------------------------
------------------------------------------------------------------------
`Method`
GetExplorerHuntStartText()
--------------------------
------------------------------------------------------------------------
`Method`
GetExplorerNodeCount()
----------------------
------------------------------------------------------------------------
`Method`
GetExplorerNodeInfo()
---------------------
------------------------------------------------------------------------
`Method`
GetExplorerPowerMapInfo()
-------------------------
------------------------------------------------------------------------
`Method`
GetExplorerPowerMapReadyText()
------------------------------
------------------------------------------------------------------------
`Method`
GetId()
-------
------------------------------------------------------------------------
`Method`
GetMapIcon()
------------
------------------------------------------------------------------------
`Method`
GetMapLocations()
-----------------
------------------------------------------------------------------------
`Method`
GetMapRegions()
---------------
------------------------------------------------------------------------
`Method`
GetMissionState()
-----------------
------------------------------------------------------------------------
`Method`
GetName()
---------
------------------------------------------------------------------------
`Method`
GetNumCompleted()
-----------------
------------------------------------------------------------------------
`Method`
GetNumNeeded()
--------------
------------------------------------------------------------------------
`Method`
GetRewardData()
---------------
------------------------------------------------------------------------
`Method`
GetRewardXp()
-------------
------------------------------------------------------------------------
`Method`
GetScientistDatacubeDiscoveryZone()
-----------------------------------
------------------------------------------------------------------------
`Method`
GetScientistExperimentationCurrentPatterns()
--------------------------------------------
------------------------------------------------------------------------
`Method`
GetScientistExperimentationInfo()
---------------------------------
------------------------------------------------------------------------
`Method`
GetScientistFieldStudy()
------------------------
------------------------------------------------------------------------
`Method`
GetScientistIcon()
------------------
------------------------------------------------------------------------
`Method`
GetScientistSpecimenSurvey()
----------------------------
------------------------------------------------------------------------
`Method`
GetSettlerMayorInfo()
---------------------
------------------------------------------------------------------------
`Method`
GetSettlerResourceRegions()
---------------------------
------------------------------------------------------------------------
`Method`
GetSettlerScoutInfo()
---------------------
------------------------------------------------------------------------
`Method`
GetSettlerSheriffInfo()
-----------------------
------------------------------------------------------------------------
`Method`
GetSoldierHoldout()
-------------------
------------------------------------------------------------------------
`Method`
GetSpell()
----------
------------------------------------------------------------------------
`Method`
GetSubType()
------------
------------------------------------------------------------------------
`Method`
GetSummary()
------------
------------------------------------------------------------------------
`Method`
GetType()
---------
------------------------------------------------------------------------
`Method`
GetUnlockString()
-----------------
------------------------------------------------------------------------
`Method`
IsComplete()
------------
------------------------------------------------------------------------
`Method`
IsExplorerPowerMapActive()
--------------------------
------------------------------------------------------------------------
`Method`
IsExplorerPowerMapReady()
-------------------------
------------------------------------------------------------------------
`Method`
IsInArea()
----------
------------------------------------------------------------------------
`Method`
IsOptional()
------------
------------------------------------------------------------------------
`Method`
IsStarted()
-----------
------------------------------------------------------------------------
`Method`
RefreshScientistExperimentation()
---------------------------------
------------------------------------------------------------------------
`Method`
ScientistCreatureType\_History() (Deprecated)
---------------------------------------------
------------------------------------------------------------------------
`Method`
ShowExplorerClueHintArrow()
---------------------------
------------------------------------------------------------------------
`Method`
ShowHintArrow()
---------------
------------------------------------------------------------------------
`Method`
ShowPathChecklistHintArrow()
----------------------------
| Java |
<?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;
}
} | Java |
if ( !window.console ) window.console = { log:function(){} };
jQuery(document).ready(function($) {
console.log('Keep being awesome.');
}); | Java |
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
}
| Java |
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();
}
}
}
| Java |
<?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;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.