code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?php
defined('C5_EXECUTE') or die("Access Denied.");
global $c;
// grab all the collections belong to the collection type that we're looking at
Loader::model('collection_types');
$ctID = $c->getCollectionTypeID();
$ct = CollectionType::getByID($ctID);
$cList = $ct->getPages();
?>
<div class="ccm-ui">
<form method="post" id="ccmBlockMasterCollectionForm" action="<?php echo $b->getBlockMasterCollectionAliasAction()?>">
<?php if (count($cList) == 0) { ?>
<?php echo t("There are no pages of this type added to your website. If there were, you'd be able to choose which of those pages this block appears on.")?>
<?php } else { ?>
<p><?php echo t("Choose which pages below this particular block should appear on. Any previously selected blocks may also be removed using the checkbox. Click the checkbox in the header to select/deselect all pages.")?></p>
<br/>
<table class="zebra-stripped" >
<tr>
<th>ID</th>
<th><?php echo t('Name')?></th>
<th ><?php echo t('Date Created')?></th>
<th ><?php echo t('Date Modified')?></th>
<th ><input type="checkbox" id="mc-cb-all" /></th>
</tr>
<?php
foreach($cList as $p) { ?>
<tr class="active">
<td><?php echo $p->getCollectionID()?></td>
<td><a href="<?php echo DIR_REL?>/<?php echo DISPATCHER_FILENAME?>?cID=<?php echo $p->getCollectionID()?>" target="_blank"><?php echo $p->getCollectionName()?></a></td>
<td ><?php echo $p->getCollectionDateAdded('m/d/Y','user')?></td>
<td ><?php if ($b->isAlias($p)) { ?> <input type="hidden" name="checkedCIDs[]" value="<?php echo $p->getCollectionID()?>" /><?php } ?><?php echo $p->getCollectionDateLastModified('m/d/Y','user')?></td>
<td ><input class="mc-cb" type="checkbox" name="cIDs[]" value="<?php echo $p->getCollectionID()?>" <?php if ($b->isAlias($p)) { ?> checked <?php } ?> /></td>
</tr>
<?php } ?>
</table>
<?php } ?>
<div class="dialog-buttons">
<a href="#" class="ccm-dialog-close ccm-button-left btn cancel"><?php echo t('Cancel')?></a>
<a href="javascript:void(0)" onclick="$('#ccmBlockMasterCollectionForm').submit()" class="btn primary ccm-button-right accept"><?php echo t('Save')?></a>
</div>
<script type="text/javascript">
$(function() {
$('#mc-cb-all').click(function() {
if (this.checked) {
$('input.mc-cb').each(function() {
$(this).get(0).checked = true;
});
} else {
$('input.mc-cb').each(function() {
$(this).get(0).checked = false;
});
}
});
$('#ccmBlockMasterCollectionForm').each(function() {
ccm_setupBlockForm($(this), '<?php echo $b->getBlockID()?>', 'edit');
});
});
</script>
</form>
</div> | tayeke/Klein-Instruments | concrete/elements/block_master_collection_alias.php | PHP | mit | 2,644 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model AlexanderEmelyanov\yii\modules\articles\models\Article */
$this->title = Yii::t('app', 'Update {modelClass}: ', [
'modelClass' => 'Article',
]) . ' ' . $model->article_id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Articles'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->article_id, 'url' => ['view', 'id' => $model->article_id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="article-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div> | alexander-emelyanov/yii2-articles-module | views/articles/update.php | PHP | mit | 682 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoadblockTagAndContextTables extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('roadblocks'))
{
Schema::create('roadblocks', function(Blueprint $table)
{
$table->increments('id');
$table->string('description');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
if (!Schema::hasTable('project_roadblock'))
{
Schema::create('project_roadblock', function(Blueprint $table)
{
$table->increments('id');
$table->integer('project_id')->unsigned();
$table->foreign('project_id')->references('id')->on('projects');
$table->integer('roadblock_id')->unsigned();
$table->foreign('roadblock_id')->references('id')->on('roadblocks');
$table->timestamps();
});
}
if (!Schema::hasTable('tags'))
{
Schema::create('tags', function(Blueprint $table)
{
$table->increments('id');
$table->string('description');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
if (!Schema::hasTable('project_tag'))
{
Schema::create('project_tag', function(Blueprint $table)
{
$table->increments('id');
$table->integer('project_id')->unsigned();
$table->foreign('project_id')->references('id')->on('projects');
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
$table->timestamps();
});
}
if (!Schema::hasTable('contexts'))
{
Schema::create('contexts', function(Blueprint $table)
{
$table->increments('id');
$table->string('description');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
if (!Schema::hasTable('context_project'))
{
Schema::create('context_project', function(Blueprint $table)
{
$table->increments('id');
$table->integer('project_id')->unsigned();
$table->foreign('project_id')->references('id')->on('projects');
$table->integer('context_id')->unsigned();
$table->foreign('context_id')->references('id')->on('contexts');
$table->timestamps();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (Schema::hasTable('project_roadblock'))
{
Schema::drop('project_roadblock');
}
if (Schema::hasTable('roadblocks'))
{
Schema::drop('roadblocks');
}
if (Schema::hasTable('project_tag'))
{
Schema::drop('project_tag');
}
if (Schema::hasTable('tags'))
{
Schema::drop('tags');
}
if (Schema::hasTable('context_project'))
{
Schema::drop('context_project');
}
if (Schema::hasTable('contexts'))
{
Schema::drop('contexts');
}
}
}
| BBBThunda/projectify | app/database/migrations/2014_09_04_132444_create_roadblock_tag_and_context_tables.php | PHP | mit | 3,901 |
@import url("./bootstrap/css/bootstrap.css");
@import url("./fontawesome/css/font-awesome.css");
body {
}
.navbar-brand img {
max-height: 30px;
margin-right: 20px;
margin-top: -6px;
}
| TokenMarketNet/ethereum-smart-contract-transaction-demo | src/main.css | CSS | mit | 193 |
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 111;
int arr[maxn];
int main()
{
//freopen("in.txt", "r", stdin);
int n, m;
while(2 == scanf("%d%d", &n, &m) && !(n==0 && m==0)) {
for(int i = 0; i < n; ++i)
scanf("%d", &arr[i]);
arr[n] = m;
sort(arr, arr+n+1);
printf("%d", arr[0]);
for(int i = 1; i < n+1; ++i)
printf(" %d", arr[i]);
printf("\n");
}
return 0;
}
| bashell/oj | hdu/2019.cpp | C++ | mit | 485 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ContosoUniversity.WebApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| ChauThan/WebApi101 | src/ContosoUniversity.WebApi/Controllers/ValuesController.cs | C# | mit | 791 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./52b2fda3bd58f1a43a67b48b0bb8d03f82aae6247c19cb3e1f6cb057ca1c8718.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | simonmysun/praxis | TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/76fdc108858381c1bd203e3bd2fb2126995af3857aa91fa0c688c54727428c26.html | HTML | mit | 550 |
/**
* A debounce method that has a sliding window, there's a minimum and maximum wait time
**/
module.exports = function (cb, min, max, settings) {
var ctx, args, next, limit, timeout;
if (!settings) {
settings = {};
}
function fire() {
limit = null;
cb.apply(settings.context || ctx, args);
}
function run() {
var now = Date.now();
if (now >= limit || now >= next) {
fire();
} else {
timeout = setTimeout(run, Math.min(limit, next) - now);
}
}
let fn = function windowed() {
var now = Date.now();
ctx = this;
args = arguments;
next = now + min;
if (!limit) {
limit = now + max;
timeout = setTimeout(run, min);
}
};
fn.clear = function () {
clearTimeout(timeout);
timeout = null;
limit = null;
};
fn.flush = function () {
fire();
fn.clear();
};
fn.shift = function (diff) {
limit += diff;
};
fn.active = function () {
return !!limit;
};
return fn;
};
| b-heilman/bmoor | src/flow/window.js | JavaScript | mit | 935 |
# -*- coding: utf-8 -*-
from flask import Blueprint
from jotonce.api import route
from jotonce.passphrases.models import Passphrase
bp = Blueprint('passphrase', __name__, url_prefix='/passphrase')
@route(bp, '/')
def get():
p = Passphrase.get_random()
return {"results": p}
| nficano/jotonce.com | jotonce/api/passphrases.py | Python | mit | 285 |
package ru.lanbilling.webservice.wsdl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ret" type="{urn:api3}soapVgroupsAddonsStaff" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ret"
})
@XmlRootElement(name = "getVgroupsAddonsStaffResponse")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class GetVgroupsAddonsStaffResponse {
@XmlElement(required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected List<SoapVgroupsAddonsStaff> ret;
/**
* Gets the value of the ret property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ret property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRet().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SoapVgroupsAddonsStaff }
*
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public List<SoapVgroupsAddonsStaff> getRet() {
if (ret == null) {
ret = new ArrayList<SoapVgroupsAddonsStaff>();
}
return this.ret;
}
}
| kanonirov/lanb-client | src/main/java/ru/lanbilling/webservice/wsdl/GetVgroupsAddonsStaffResponse.java | Java | mit | 2,337 |
class AddIndicesToPartialFlow < ActiveRecord::Migration[5.1]
def change
add_index :partial_flows, [ :is_syn, :state ]
add_index :partial_flows, [ :src_ip, :dst_ip, :src_port, :dst_port, :state ], name: 'identify_index'
end
end
| GetPhage/phage | db/migrate/20171029040306_add_indices_to_partial_flow.rb | Ruby | mit | 239 |
#include "background_extractor.h"
namespace TooManyPeeps {
BackgroundExtractor::BackgroundExtractor(const cv::Mat& original, cv::Mat& result,
int historySize, double threshold)
: ProcessFilter(original, result) {
backgroundExtractor = cv::createBackgroundSubtractorMOG2(historySize, threshold, TRACK_SHADOWS);
// If TRACK_SHADOWS = true, shadows are also marked in result with value = 127
}
BackgroundExtractor::BackgroundExtractor(cv::Mat& image, int historySize, double threshold)
: BackgroundExtractor(image, image, historySize, threshold) {
}
BackgroundExtractor::~BackgroundExtractor(void) {
delete backgroundExtractor;
}
void BackgroundExtractor::execute(void) {
backgroundExtractor->apply(get_original(), get_result());
}
};
| 99-bugs/toomanypeeps | opencv_detector/src/lib/filter/background_extractor.cpp | C++ | mit | 783 |
<?php
namespace App;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\MappedSuperclass
* @ORM\HasLifecycleCallbacks()
*/
abstract class Entity
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="datetime")
* @var \DateTime
*/
protected $created;
/**
* @ORM\Column(type="datetime")
* @var \DateTime
*/
protected $updated;
/**
* Constructor
*/
public function __construct()
{
$this->setCreated(new \DateTime());
$this->setUpdated(new \DateTime());
}
/**
* @ORM\PreUpdate
*/
public function setUpdatedValue()
{
$this->setUpdated(new \DateTime());
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @param $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* @param $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* @return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
public function toArray(){
return [
"id"=>$this->id,
"creation_time"=>$this->getCreated()->format('d/m/Y H:i:s'),
"last_update_time"=>$this->getUpdated()->format('d/m/Y H:i:s')
];
}
} | Meshredded/slim-framework_doctrine_mini_web-service | src/App/Entity.php | PHP | mit | 1,676 |
---
title: Comunicación en Tiempo Real
sidebar_label: WebSockets
---
> *This feature is available from version 2.8 onwards.*
Foal allows you to establish two-way interactive communication between your server(s) and your clients. For this, it uses the [socket.io v4](https://socket.io/) library which is primarily based on the **WebSocket** protocol. It supports disconnection detection and automatic reconnection and works with proxies and load balancers.
## Get Started
### Server
```bash
npm install @foal/socket.io
```
*services/websocket.service.ts*
```typescript
import { EventName, ValidatePayload, SocketIOController, WebsocketContext, WebsocketResponse } from '@foal/socket.io';
export class WebsocketController extends SocketIOController {
@EventName('create product')
@ValidatePayload({
additionalProperties: false,
properties: { name: { type: 'string' }},
required: [ 'name' ],
type: 'object'
})
async createProduct(ctx: WebsocketContext, payload: { name: string }) {
const product = new Product();
product.name = payload.name;
await product.save();
// Send a message to all clients.
ctx.socket.broadcast.emit('refresh products');
return new WebsocketResponse();
}
}
```
*src/index.ts*
```typescript
// ...
async function main() {
const serviceManager = new ServiceManager();
const app = await createApp(AppController, { serviceManager });
const httpServer = http.createServer(app);
// Instanciate, init and connect websocket controllers.
await serviceManager.get(WebsocketController).attachHttpServer(httpServer);
// ...
}
```
### Client
> This example uses JavaScript code as client, but socket.io supports also [many other languages](https://socket.io/docs/v4) (python, java, etc).
```bash
npm install socket.io-client@4
```
```typescript
import { io } from 'socket.io-client';
const socket = io('ws://localhost:3001');
socket.on('connect', () => {
socket.emit('create product', { name: 'product 1' }, response => {
if (response.status === 'error') {
console.log(response.error);
}
});
});
socket.on('connect_error', () => {
console.log('Impossible to establish the socket.io connection');
});
socket.on('refresh products', () => {
console.log('refresh products!');
});
```
:::info
When using socket.io with FoalTS, the client function `emit` can only take one, two or three arguments.
```typescript
socket.emit('event name');
socket.emit('event name', { /* payload */ });
socket.emit('event name', { /* payload */ }, response => { /* do something */ });
```
:::
## Architecture
### Controllers and hooks
The WebSocket architecture is very similar to the HTTP architecture. They both have controllers and hooks. While HTTP controllers use paths to handle the various application endpoints, websocket controllers use event names. As with HTTP, event names can be extended with subcontrollers.
*user.controller.ts*
```typescript
import { EventName, WebsocketContext } from '@foal/socket.io';
export class UserController {
@EventName('create')
createUser(ctx: WebsocketContext) {
// ...
}
@EventName('delete')
deleteUser(ctx: WebsocketContext) {
// ...
}
}
```
*websocket.controller.ts*
```typescript
import { SocketIOController, wsController } from '@foal/socket.io';
import { UserController } from './user.controller.ts';
export class WebsocketController extends SocketIOController {
subControllers = [
wsController('users ', UserController)
];
}
```
> Note that the event names are simply concatenated. So you have to manage the spaces between the words yourself if there are any.
#### Contexts
The `Context` and `WebsocketContext` classes share common properties such as the `state`, the `user` and the `session`.
However, unlike their HTTP version, instances of `WebsocketContext` do not have a `request` property but a `socket` property which is the object provided by socket.io. They also have two other attributes: the `eventName` and the `payload` of the request.
#### Responses
A controller method returns a response which is either a `WebsocketResponse` or a `WebsocketErrorResponse`.
If a `WebsocketResponse(data)` is returned, the server will return to the client an object of this form:
```typescript
{
status: 'ok',
data: data
}
```
If it is a `WebsocketErrorResponse(error)`, the returned object will look like this:
```typescript
{
status: 'error',
error: error
}
```
> Note that the `data` and `error` parameters are both optional.
#### Hooks
In the same way, Foal provides hooks for websockets. They work the same as their HTTP version except that some types are different (`WebsocketContext`, `WebsocketResponse|WebsocketErrorResponse`).
```typescript
import { EventName, WebsocketContext, WebsocketErrorResponse, WebsocketHook } from '@foal/socket.io';
export class UserController {
@EventName('create')
@WebsocketHook((ctx, services) => {
if (typeof ctx.payload.name !== 'string') {
return new WebsocketErrorResponse('Invalid name type');
}
})
createUser(ctx: WebsocketContext) {
// ...
}
}
```
#### Summary table
| HTTP | Websocket |
| --- | --- |
| `@Get`, `@Post`, etc | `@EventName` |
| `controller` | `wsController` |
| `Context` | `WebsocketContext` |
| `HttpResponse`(s) | `WebsocketResponse`, `WebsocketErrorResponse` |
| `Hook` | `WebsocketHook` |
| `MergeHooks` | `MergeWebsocketHooks` |
| `getHookFunction`, `getHookFunctions` | `getWebsocketHookFunction`, `getWebsocketHookFunctions` |
### Send a message
At any time, the server can send one or more messages to the client using its `socket` object.
*Server code*
```typescript
import { EventName, WebsocketContext, WebsocketResponse } from '@foal/socket.io';
export class UserController {
@EventName('create')
createUser(ctx: WebsocketContext) {
ctx.socket.emit('event 1', 'first message');
ctx.socket.emit('event 1', 'second message');
return new WebsocketResponse();
}
}
```
*Client code*
```typescript
socket.on('event 1', payload => {
console.log('Message: ', payload);
});
```
### Broadcast a message
If a message is to be broadcast to all clients, you can use the `broadcast` property for this.
*Server code*
```typescript
import { EventName, WebsocketContext, WebsocketResponse } from '@foal/socket.io';
export class UserController {
@EventName('create')
createUser(ctx: WebsocketContext) {
ctx.socket.broadcast.emit('event 1', 'first message');
ctx.socket.broadcast.emit('event 1', 'second message');
return new WebsocketResponse();
}
}
```
*Client code*
```typescript
socket.on('event 1', payload => {
console.log('Message: ', payload);
});
```
### Grouping clients in rooms
Socket.io uses the concept of [rooms](https://socket.io/docs/v4/rooms/) to gather clients in groups. This can be useful if you need to send a message to a particular subset of clients.
```typescript
import { EventName, SocketIOController, WebsocketContext, WebsocketResponse } from '@foal/socket.io';
export class WebsocketController extends SocketIOController {
onConnection(ctx: WebsocketContext) {
ctx.socket.join('some room');
}
@EventName('event 1')
createUser(ctx: WebsocketContext) {
ctx.socket.to('some room').emit('event 2');
return new WebsocketResponse();
}
}
```
### Accessing the socket.io server
You can access the socket.io server anywhere in your code (including your HTTP controllers) by injecting the `WsServer` service.
```typescript
import { dependency, HttpResponseOK, Post } from '@foal/core';
import { WsServer } from '@foal/socket.io';
export class UserController {
@dependency
wsServer: WsServer;
@Post('/users')
createUser() {
// ...
this.wsServer.io.emit('refresh users');
return new HttpResponseOK();
}
}
```
### Error-handling
Any error thrown or rejected in a websocket controller, hook or service, if not caught, is converted to a `WebsocketResponseError`. If the `settings.debug` configuration parameter is `true`, then the error is returned as is to the client. Otherwise, the server returns this response:
```typescript
({
status: 'error',
error: {
code: 'INTERNAL_SERVER_ERROR',
message: 'An internal server error has occurred.'
}
})
```
#### Customizing the error handler
Just as its HTTP version, the `SocketIOController` class supports an optional `handleError` to override the default error handler.
```typescript
import { EventName, renderWebsocketError, SocketIOController, WebsocketContext, WebsocketErrorResponse } from '@foal/socket.io';
class PermissionDenied extends Error {}
export class WebsocketController extends SocketIOController implements ISocketIOController {
@EventName('create user')
createUser() {
throw new PermissionDenied();
}
handleError(error: Error, ctx: WebsocketContext){
if (error instanceof PermissionDenied) {
return new WebsocketErrorResponse('Permission is denied');
}
return renderWebsocketError(error, ctx);
}
}
```
## Payload Validation
Foal provides a default hook `@ValidatePayload` to validate the request payload. It is very similar to its HTTP version `@ValidateBody`.
*Server code*
```typescript
import { EventName, SocketIOController, WebsocketContext, WebsocketResponse } from '@foal/socket.io';
export class WebsocketController extends SocketIOController {
@EventName('create product')
@ValidatePayload({
additionalProperties: false,
properties: { name: { type: 'string' }},
required: [ 'name' ],
type: 'object'
})
async createProduct(ctx: WebsocketContext, payload: { name: string }) {
const product = new Product();
product.name = payload.name;
await product.save();
// Send a message to all clients.
ctx.socket.broadcast.emit('refresh products');
return new WebsocketResponse();
}
}
```
*Validation error response*
```typescript
({
status: 'error',
error: {
code: 'VALIDATION_PAYLOAD_ERROR',
payload: [
// errors
]
}
})
```
## Unit Testing
Testing WebSocket controllers and hooks is very similar to testing their HTTP equivalent. The `WebsocketContext` takes three parameters.
| Name | Type | Description |
| --- | --- | --- |
| `eventName` | `string` | The name of the event. |
| `payload`| `any` | The request payload. |
| `socket` | `any` | The socket (optional). Default: `{}`. |
## Advanced
### Multiple node servers
This example shows how to manage multiple node servers using a redis adapter.
```bash
npm install @socket.io/redis-adapter@7 redis@3
```
*websocket.controller.ts*
```typescript
import { EventName, SocketIOController, WebsocketContext, WebsocketResponse } from '@foal/socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';
export const pubClient = createClient({ url: 'redis://localhost:6379' });
export const subClient = pubClient.duplicate();
export class WebsocketController extends SocketIOController {
adapter = createAdapter(pubClient, subClient);
@EventName('create user')
createUser(ctx: WebsocketContext) {
// Broadcast an event to all clients of all servers.
ctx.socket.broadcast.emit('refresh users');
return new WebsocketResponse();
}
}
```
### Handling connection
If you want to run some code when a Websocket connection is established (for example to join a room or forward the session), you can use the `onConnection` method of the `SocketIOController` for this.
```typescript
import { SocketIOController, WebsocketContext } from '@foal/socket.io';
export class WebsocketController extends SocketIOController {
onConnection(ctx: WebsocketContext) {
// ...
}
}
```
> The context passed in the `onConnection` method has an undefined payload and an empty event name.
#### Error-handling
Any errors thrown or rejected in the `onConnection` is sent back to the client. So you may need to add a `try {} catch {}` in some cases.
This error can be read on the client using the `connect_error` event listener.
```typescript
socket.on("connect_error", () => {
// Do some stuff
socket.connect();
});
```
### Custom server options
Custom options can be passed to the socket.io server as follows. The complete list of options can be found [here](https://socket.io/docs/v4/server-options/).
```typescript
import { SocketIOController } from '@foal/socket.io';
export class WebsocketController extends SocketIOController {
options = {
connectTimeout: 60000
}
}
```
| FoalTS/foal | docs/i18n/es/docusaurus-plugin-content-docs/current/websockets.md | Markdown | mit | 12,529 |
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
mocha = require('gulp-mocha'),
cover = require('gulp-coverage'),
jscs = require('gulp-jscs');
gulp.task('default', ['jscs', 'lint', 'test'], function () {
});
gulp.task('lint', function () {
return gulp.src(['./lib/*.js', './test/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default', {verbose: true}));
});
gulp.task('test', ['jscs', 'lint'], function () {
return gulp.src('./test', {read: false})
.pipe(cover.instrument({
pattern: ['*lib/*.js'],
debugDirectory: 'debug'
}))
.pipe(mocha({reporter: 'nyan'}))
.pipe(cover.gather())
.pipe(cover.format())
.pipe(gulp.dest('reports'));
});
gulp.task('jscs', function () {
return gulp.src(['./lib/*.js', './test/*.js'])
.pipe(jscs());
});
| olavhaugen/telldus-live-promise | gulpfile.js | JavaScript | mit | 875 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RepertoryGridGUI.ufos
{
public partial class ufoConstructAlternative : Form
{
public ufoConstructAlternative()
{
InitializeComponent();
}
}
}
| felixlindemann/RepertoryGrid | RepertoryGrid/RepertoryGridGUI/ufos/ufoConstructAlternative.cs | C# | mit | 407 |
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Detect Edges",
GUID = "d4909010-f701-4c60-85ff-53789ca59743",
Description = "Detects the edges in the current image using various one and two dimensional algorithms.",
GroupName = Global.GroupName,
Order = 9)]
[Icon]
public class DetectEdgesBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Filter")]
[EnumAttribute(typeof(DetectEdgesFilter))]
public virtual DetectEdgesFilter Filter { get; set; }
public virtual bool Greyscale { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.DetectEdges(Filter, Greyscale);
}
public override void SetDefaultValues(ContentType contentType)
{
base.SetDefaultValues(contentType);
Greyscale = false;
}
}
} | vnbaaij/ImageProcessor.Web.Episerver | src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/DetectEdgesBlock.cs | C# | mit | 1,125 |
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
ArrayList<Integer> tmp = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
tmp.add(0, 1);
for (int j = 1; j < tmp.size() - 1; j++) {
tmp.set(j, tmp.get(j) + tmp.get(j + 1));
}
result.add(new ArrayList<>(tmp));
}
return result;
}
}
| liupangzi/codekata | leetcode/Algorithms/118.Pascal'sTriangle/Solution.java | Java | mit | 471 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/lib/pure.min.css">
<link rel="stylesheet" href="../css/whhg.css">
<link rel="stylesheet" href="../css/main.css">
<link rel="icon" type="image/png" href="../favicon.png?v=1.01">
<title>Dining @ CU</title>
</head>
<body>
<div class="header">
<div class="home-menu pure-menu pure-menu-open pure-menu-horizontal pure-menu-fixed">
<a class="pure-menu-heading" href="../">Dining @ CU</a>
<ul>
<li><a href="../">Home</a></li>
<li class="pure-menu-selected"><a href="#">Menu</a></li>
</ul>
</div>
</div>
<div class="splash-container menu-splash-container">
<div class="splash menu-splash">
<h1 class="splash-head menu-splash-head">
Loading your content <span class="loading">...</span>
</h1>
</div>
</div>
<div class="menu-content-wrapper">
<div class="invert-content-wrapper">
<div class="content">
<div class="pure-g-r">
<div class="pure-u-1">
<div class="l-box menu-box">
<h2 class="content-subhead menu-subhead" id="dining-text">
Columbia Dining:
</h2>
</div>
</div>
</div>
</div>
</div>
<div class="content">
<div class="pure-g-r">
<div class="pure-u-1">
<div class="l-box menu-box">
<h3 class="content-subhead menu-subhead">
John Jay
</h3>
<div class="menu-icon-holder">
<i class="icon-pizza menu-icon"></i>
<i class="icon-ban-circle menu-icon menu-sub-icon ban-icon"></i>
<i class="icon-pizza menu-icon-mirror mirror"></i>
<i class="icon-ban-circle menu-icon-mirror menu-sub-icon-mirror ban-icon"></i>
</div>
<p class="menu-p">
John Jay has no pizza today. Please don't be upset, there's no reason for that.
Consider the bustling, driven, priority-oriented network that is John Jay dining - at times like these we've got to take a step back and breathe, acknowledging that all of us are prone to human error.
We know pizza, and we know that it could be just around the corner. Maybe try <a href="#" class="tomorrow-link">Tomorrow?</a>
</p>
</div>
</div>
</div>
</div>
<div class="content menu-gray-content-wrapper">
<div class="pure-g-r">
<div class="pure-u-1">
<div class="l-box menu-box">
<h3 class="content-subhead menu-subhead">
Ferris
</h3>
<div class="menu-icon-holder">
<i class="icon-pizza menu-icon"></i>
<i class="icon-ok-circle menu-icon menu-sub-icon check-icon"></i>
<i class="icon-pizza menu-icon-mirror mirror"></i>
<i class="icon-ok-circle menu-icon-mirror menu-sub-icon-mirror check-icon"></i>
</div>
<p class="menu-p">
Ferris does have pizza today. Thank the stars, it's safe - you can go there. There's no need to be afraid today,
and there's no need to be afraid when you're gripping the steamy, flaky crust between your grateful hands, all the more
supple from the relaxing data-styles we were able to serve you with.
You can't do anything wrong at Ferris Booth! As long as there's pizza! (Ha Ha!).
</p>
</div>
</div>
</div>
</div>
<div class="content">
<div class="pure-g-r">
<div class="pure-u-1">
<div class="l-box menu-box">
<h3 class="content-subhead menu-subhead">
JJ's
</h3>
<div class="menu-icon-holder">
<i class="icon-pizza menu-icon"></i>
<i class="icon-ban-circle menu-icon menu-sub-icon ban-icon"></i>
<i class="icon-pizza menu-icon-mirror mirror"></i>
<i class="icon-ban-circle menu-icon-mirror menu-sub-icon-mirror ban-icon"></i>
</div>
<p class="menu-p">
JJ's ... doesn't have pizza today - and apparently, not tonight either. I'm so sorry.
We know you get hungry late at night, and we know sometimes you can't sleep because of it.
We know you need pizza. Please don't let what happened happen again.
As an alternative, it could be worth your troubles to slide some famous "Mozzarella Sticks"
in a dip bowl of "Marinara Sauce" - even better, you can smear two swads of them on your styrofoam
"Plate", and garnish with the "Omelette Pepperoni" to taste.
At the end of the day, it'll come back soon. Please try <a href="#" class="tomorrow-link">Tomorrow</a>.
Please.
</p>
</div>
</div>
</div>
</div>
<div class="footer s-box">
Dining @ CU - <a href="http://www.millersfantasy.com">Miller's Fantasy</a> 2014
</div>
</div>
<script src="../js/lib/jquery.min.js"></script>
<script src="./js/menu_build.js"></script>
</body>
</html>
| kevin-roark/dining-at-cu | menu/index.html | HTML | mit | 5,671 |
if (typeof window !== 'undefined') {
var less = require('npm:less/lib/less-browser/index')(window, window.less || {})
var head = document.getElementsByTagName('head')[0];
// get all injected style tags in the page
var styles = document.getElementsByTagName('style');
var styleIds = [];
for (var i = 0; i < styles.length; i++) {
if (!styles[i].hasAttribute("data-href")) continue;
styleIds.push(styles[i].getAttribute("data-href"));
}
var loadStyle = function (url) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = request.responseText;
var options = window.less || {};
options.filename = url;
options.rootpath = url.replace(/[^\/]*$/, '');
//render it using less
less.render(data, options).then(function (data) {
//inject it into the head as a style tag
var style = document.createElement('style');
style.textContent = '\r\n' + data.css;
style.setAttribute('type', 'text/css');
//store original type in the data-type attribute
style.setAttribute('data-type', 'text/less');
//store the url in the data-href attribute
style.setAttribute('data-href', url);
head.appendChild(style);
resolve('');
});
} else {
// We reached our target server, but it returned an error
reject()
}
};
request.onerror = function (e) {
reject(e)
};
request.send();
});
}
exports.fetch = function (load) {
// don't reload styles loaded in the head
for (var i = 0; i < styleIds.length; i++)
if (load.address == styleIds[i])
return '';
return loadStyle(load.address);
}
}
else {
exports.translate = function (load) {
// setting format = 'defined' means we're managing our own output
load.metadata.format = 'defined';
};
exports.bundle = function (loads, opts) {
var loader = this;
if (loader.buildCSS === false)
return '';
return loader.import('./less-builder', {name: module.id}).then(function (builder) {
return builder.call(loader, loads, opts);
});
}
}
| Aaike/jspm-less-plugin | less.js | JavaScript | mit | 2,820 |
(function () {
"use strict";
angular.module("myApp.components.notifications")
.factory("KudosNotificationService", KudosNotificationService);
KudosNotificationService.$inject = [
"Transaction"
];
function KudosNotificationService(transactionBackend) {
var service = {
getNewTransactions: getNewTransactions,
setLastTransaction: setLastSeenTransaction
};
return service;
function getNewTransactions() {
return transactionBackend.getNewTransactions()
}
function setLastSeenTransaction(timestamp) {
return transactionBackend.setLastSeenTransactionTimestamp(timestamp)
}
}
})(); | open-kudos/open-kudos-intern-web | src/app/components/kudos-notifications-transaction/kudos-notification-transaction.service.js | JavaScript | mit | 722 |
---
layout: base
published: true
---
<style>
#carouselExampleIndicators{
/*max-height: 70vh;*/
padding-top: -10vh;
padding-bottom: 8vh;
height: 100vh;
position: relative;
}
.carousel-inner{
padding-top: -10vh;
padding-bottom: 8vh;
height: 100vh;
position: relative;
background-color: black;
}
.carousel-item{
padding-top: -10vh;
padding-bottom: 8vh;
height: 100vh;
position: relative;
}
.slide1{
background-image: url(./images/orientation2018-min.jpg);
width: 100vw;
min-height: 296px;
background-position: center center;
background-repeat: no-repeat;
object-fit: cover;
background-size: cover;
text-align: center;
padding-top: 14vh;
padding-bottom: 12vh;
opacity: 0.6;
}
.slide2{
background-image: url(./images/cusec.jpg);
width: 100vw;
min-height: 296px;
background-position: center center;
background-repeat: no-repeat;
object-fit: cover;
background-size: cover;
text-align: center;
padding-top: 14vh;
padding-bottom: 12vh;
opacity: 0.6;
}
.slide3{
background-image: url(./images/bbq20192.jpg);
width: 100vw;
min-height: 296px;
background-position: center center;
background-repeat: no-repeat;
object-fit: cover;
background-size: cover;
text-align: center;
padding-top: 14vh;
padding-bottom: 12vh;
opacity: 0.7;
}
.backgroundCover{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #000;
opacity: 0.3;
z-index: 10;
}
.slide {
transform: translateX(-0%) !important;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!--<div class='background backgroundCover'></div>-->
<div class='main-front-page-subject' style="{{ page.subjectstyle }}">
CARLETON COMPUTER<br>SCIENCE SOCIETY
</div>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="carousel-item active slide1">
<!--<img class="d-block w-100" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" data-color="lightblue" alt="First Image">-->
<div class="carousel-caption d-md-block">
<!--<h5>First Image</h5>-->
</div>
</div>
<div class="carousel-item slide2">
<!--<img class="d-block w-100" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" data-color="lightblue" alt="First Image">-->
<div class="carousel-caption d-md-block">
<!--<h5>Second Image</h5>-->
</div>
</div>
<div class="carousel-item slide3">
<!--<img class="d-block w-100" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" data-color="lightblue" alt="First Image">-->
<div class="carousel-caption d-md-block">
<!--<h5>Third Image</h5>-->
</div>
</div>
</div>
<!-- Controls -->
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap.css">
<script src="https://unpkg.com/popper.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
<script>
$('.carousel').carousel({
interval: 6000,
pause: "false"
});
</script>
<!--
<div class="main-page-image-wrapper" style="
background-image: url('{{ page.pimage }}');">-->
<!--div class="front-logo">
<img style="display:block;"class="cu-logo" src= "/images/cu-logo.png">
</div--><!--
<div class='background'></div>
<div class='main-front-page-subject' style="{{ page.subjectstyle }}">
CARLETON COMPUTER<br>SCIENCE SOCIETY
</div>
</div>
-->
<!--a href="http://ccss.carleton.ca/opportunities/volunteer/" target="_blank" class="skinny-underline">Sign up to be a volunteer!</a-->
{{ content }}
| CarletonComputerScienceSociety/carletoncomputersciencesociety.github.io | _layouts/main.html | HTML | mit | 4,717 |
import numpy as np
from pycqed.analysis import measurement_analysis as ma
from pycqed.analysis_v2 import measurement_analysis as ma2
from pycqed.measurement import sweep_functions as swf
from pycqed.measurement import detector_functions as det
MC_instr = None
VNA_instr = None
def acquire_single_linear_frequency_span(file_name, start_freq=None,
stop_freq=None, center_freq=None,
span=None, nr_avg=1, sweep_mode='auto',
nbr_points=101, power=-20,
bandwidth=100, measure='S21',
options_dict=None):
"""
Acquires a single trace from the VNA.
Inputs:
file_name (str), name of the output file.
start_freq (float), starting frequency of the trace.
stop_freq (float), stoping frequency of the trace.
center_freq (float), central frequency of the trace.
span (float), span of the trace.
nbr_points (int), Number of points within the trace.
power (float), power in dBm.
bandwidth (float), bandwidth in Hz.
measure (str), scattering parameter to measure (ie. 'S21').
Output:
NONE
Beware that start/stop and center/span are just two ways of configuring the
same thing.
"""
# set VNA sweep function
if start_freq != None and stop_freq != None:
MC_instr.set_sweep_function(swf.ZNB_VNA_sweep(VNA_instr,
start_freq=start_freq,
stop_freq=stop_freq,
npts=nbr_points,
force_reset=True))
elif center_freq != None and span != None:
MC_instr.set_sweep_function(swf.ZNB_VNA_sweep(VNA_instr,
center_freq=center_freq,
span=span,
npts=nbr_points,
force_reset=True))
# set VNA detector function
MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr))
# VNA settings
# VNA_instr.average_state('off')
VNA_instr.bandwidth(bandwidth)
# hack to measure S parameters different from S21
str_to_write = "calc:par:meas 'trc1', '%s'" % measure
print(str_to_write)
VNA_instr.visa_handle.write(str_to_write)
VNA_instr.avg(nr_avg)
VNA_instr.number_sweeps_all(nr_avg)
VNA_instr.average_mode(sweep_mode)
VNA_instr.power(power)
VNA_instr.timeout(10**4)
t_start = ma.a_tools.current_timestamp()
MC_instr.run(name=file_name)
t_stop = ma.a_tools.current_timestamp()
t_meas = ma.a_tools.get_timestamps_in_range(t_start, t_stop, label=file_name)
assert len(t_meas) == 1, "Multiple timestamps found for this measurement"
t_meas = t_meas[0]
# ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger')
# ma.VNA_analysis(auto=True, label=file_name)
ma2.VNA_analysis(auto=True, t_start=None, options_dict=options_dict)
def acquire_current_trace(file_name):
"""
Acquires the trace currently displayed on VNA.
Inputs:
file_name (str), name of the output file.
Output:
NONE
"""
# get values from VNA
start_freq = VNA_instr.start_frequency()
stop_freq = VNA_instr.stop_frequency()
nbr_points = VNA_instr.npts()
power = VNA_instr.power()
bandwidth = VNA_instr.bandwidth()
current_sweep_time = VNA_instr.sweep_time()
print(current_sweep_time)
acquire_single_linear_frequency_span(file_name, start_freq=start_freq,
stop_freq=stop_freq,
nbr_points=nbr_points,
power=power, bandwidth=bandwidth)
def acquire_linear_frequency_span_vs_power(file_name, start_freq=None,
stop_freq=None, center_freq=None,
start_power=None, stop_power=None,
step_power=2,
span=None, nbr_points=101,
bandwidth=100, measure='S21'):
"""
Acquires a single trace from the VNA.
Inputs:
file_name (str), name of the output file.
start_freq (float), starting frequency of the trace.
stop_freq (float), stoping frequency of the trace.
center_freq (float), central frequency of the trace.
span (float), span of the trace.
nbr_points (int), Number of points within the trace.
start_power, stop_power, step_power (float), power range in dBm.
bandwidth (float), bandwidth in Hz.
measure (str), scattering parameter to measure (ie. 'S21').
Output:
NONE
Beware that start/stop and center/span are just two ways of configuring the
same thing.
"""
# set VNA sweep function
if start_freq != None and stop_freq != None:
swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr,
start_freq=start_freq,
stop_freq=stop_freq,
npts=nbr_points,
force_reset=True)
MC_instr.set_sweep_function(swf_fct_1D)
elif center_freq != None and span != None:
swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr,
center_freq=center_freq,
span=span,
npts=nbr_points,
force_reset=True)
MC_instr.set_sweep_function(swf_fct_1D)
if start_power != None and stop_power != None:
# it prepares the sweep_points, such that it does not complain.
swf_fct_1D.prepare()
MC_instr.set_sweep_points(swf_fct_1D.sweep_points)
MC_instr.set_sweep_function_2D(VNA_instr.power)
MC_instr.set_sweep_points_2D(np.arange(start_power,
stop_power+step_power/2.,
step_power))
else:
raise ValueError('Need to define power range.')
# set VNA detector function
MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr))
# VNA settings
VNA_instr.average_state('off')
VNA_instr.bandwidth(bandwidth)
# hack to measure S parameters different from S21
str_to_write = "calc:par:meas 'trc1', '%s'" % measure
print(str_to_write)
VNA_instr.visa_handle.write(str_to_write)
VNA_instr.timeout(600)
MC_instr.run(name=file_name, mode='2D')
# ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger')
ma.TwoD_Analysis(auto=True, label=file_name)
def acquire_2D_linear_frequency_span_vs_param(file_name, start_freq=None,
stop_freq=None, center_freq=None,
parameter=None, sweep_vector=None,
span=None, nbr_points=101, power=-20,
bandwidth=100, measure='S21'):
"""
Acquires a single trace from the VNA.
Inputs:
file_name (str), name of the output file.
start_freq (float), starting frequency of the trace.
stop_freq (float), stoping frequency of the trace.
center_freq (float), central frequency of the trace.
span (float), span of the trace.
nbr_points (int), Number of points within the trace.
power (float), power in dBm.
bandwidth (float), bandwidth in Hz.
measure (str), scattering parameter to measure (ie. 'S21').
Output:
NONE
Beware that start/stop and center/span are just two ways of configuring the
same thing.
"""
# set VNA sweep function
if start_freq != None and stop_freq != None:
swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr,
start_freq=start_freq,
stop_freq=stop_freq,
npts=nbr_points,
force_reset=True)
MC_instr.set_sweep_function(swf_fct_1D)
elif center_freq != None and span != None:
swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr,
center_freq=center_freq,
span=span,
npts=nbr_points,
force_reset=True)
MC_instr.set_sweep_function(swf_fct_1D)
if parameter is not None and sweep_vector is not None:
# it prepares the sweep_points, such that it does not complain.
swf_fct_1D.prepare()
MC_instr.set_sweep_points(swf_fct_1D.sweep_points)
MC_instr.set_sweep_function_2D(parameter)
MC_instr.set_sweep_points_2D(sweep_vector)
else:
raise ValueError('Need to define parameter and its range.')
# set VNA detector function
MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr))
# VNA settings
VNA_instr.power(power)
VNA_instr.average_state('off')
VNA_instr.bandwidth(bandwidth)
# hack to measure S parameters different from S21
str_to_write = "calc:par:meas 'trc1', '%s'" % measure
print(str_to_write)
VNA_instr.visa_handle.write(str_to_write)
VNA_instr.timeout(600)
MC_instr.run(name=file_name, mode='2D')
# ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger')
ma.TwoD_Analysis(auto=True, label=file_name)
def acquire_disjoint_frequency_traces(file_name, list_freq_ranges,
power=-20,
bandwidth=100, measure='S21'):
"""
list_freq_ranges is a list that contains the arays defining all the ranges of interest.
"""
for idx, range_array in enumerate(list_freq_ranges):
this_file = file_name + '_%d'%idx
acquire_single_linear_frequency_span(file_name = this_file,
start_freq=range_array[0],
stop_freq=range_array[-1],
nbr_points=len(range_array),
power=power,
bandwidth=bandwidth,
measure=measure)
packing_mmts(file_name, labels=file_name+'__', N=len(list_freq_ranges))
def packing_mmts(file_name, labels, N):
# imports data
# stacks it toghether
for idx in range(N):
this_file = file_name + '_%d'%idx
ma_obj = ma.MeasurementAnalysis(label=this_file, auto=False)
ma_obj.get_naming_and_values()
if idx==0:
data_points = ma_obj.sweep_points
data_vector = ma_obj.measured_values
else:
data_points = np.hstack((data_points,ma_obj.sweep_points))
data_vector = np.hstack((data_vector,ma_obj.measured_values))
del ma_obj
data_vector = np.array(data_vector)
data_points = np.array(data_points)
sort_mask = np.argsort(data_points)
data_points = data_points[sort_mask]
data_vector = data_vector[:,sort_mask]
# keeps track of sweeppoints call
class call_counter:
def __init__(self):
self.counter=0
swp_points_counter = call_counter()
def wrapped_data_importing(counter):
counter.counter += 1
return data_vector[:,counter.counter-1]
detector_inst = det.Function_Detector_list(
sweep_function=wrapped_data_importing,
result_keys=['Amp', 'phase', 'I', 'Q' ,'Amp_dB'],
msmt_kw={'counter': swp_points_counter})
MC_instr.set_sweep_function(swf.None_Sweep(name='VNA sweep'))
MC_instr.set_sweep_points(data_points.flatten())
MC_instr.set_detector_function(detector_inst)
MC_instr.run(name=file_name)
| DiCarloLab-Delft/PycQED_py3 | pycqed/measurement/VNA_module.py | Python | mit | 12,353 |
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "hkl_tree.h"
#include "hkl_alloc.h"
/*
* HklPair
*/
HklPair* hkl_pair_new()
{
HklPair* pair = hkl_alloc_object(HklPair);
pair->key = hkl_string_new();
pair->value = NULL;
return pair;
}
HklPair* hkl_pair_new_from_data(HklString* key, void* value)
{
assert(key != NULL);
HklPair* pair = hkl_pair_new();
hkl_string_copy(pair->key, key);
pair->value = value;
return pair;
}
HklPair* hkl_pair_new_from_utf8(const char* key, void* value)
{
assert(key != NULL);
HklPair* pair = hkl_alloc_object(HklPair);
pair->key = hkl_string_new_from_utf8(key);
pair->value = value;
return pair;
}
HklPair* hkl_pair_new_from_pair(HklPair* pair)
{
assert(pair != NULL);
return hkl_pair_new_from_data(pair->key, pair->value);
}
void hkl_pair_free(HklPair* pair)
{
hkl_string_free(pair->key);
hkl_free_object(pair);
}
/*
* HklTreeNode
*/
static HklTreeNode* hkl_treenode_new(HklString* key, void* value)
{
assert(key != NULL);
HklTreeNode* node = hkl_alloc_object(HklTreeNode);
// Duplicate the string to store in the node
node->pair = hkl_pair_new_from_data(key, value);
node->left = node->right = NULL;
node->isred = true;
return node;
}
static void hkl_treenode_free(HklTreeNode* node)
{
assert(node != NULL);
if (node->left != NULL)
hkl_treenode_free(node->left);
if (node->right != NULL)
hkl_treenode_free(node->right);
hkl_pair_free(node->pair);
hkl_free_object(node);
}
static void hkl_treenode_colorflip(HklTreeNode* node)
{
assert(node != NULL);
node->isred = !node->isred;
if (node->left != NULL)
node->left->isred = !node->left->isred;
if (node->right != NULL)
node->right->isred = !node->right->isred;
}
static int hkl_treenode_isred(HklTreeNode* node)
{
return ((node != NULL) && node->isred);
}
static HklTreeNode* hkl_treenode_rotleft(HklTreeNode* node)
{
assert(node != NULL);
assert(node->right != NULL);
HklTreeNode* right = node->right;
node->right = right->left;
right->left = node;
right->isred = node->isred;
node->isred = true;
return right;
}
static HklTreeNode* hkl_treenode_rotright(HklTreeNode* node)
{
assert(node != NULL);
assert(node->left != NULL);
HklTreeNode* left = node->left;
node->left = left->right;
left->right = node;
left->isred = node->isred;
node->isred = true;
return left;
}
static HklTreeNode* hkl_treenode_redleft(HklTreeNode* node)
{
assert(node != NULL);
hkl_treenode_colorflip(node);
if (node->right != NULL && hkl_treenode_isred(node->right->left))
{
node->right = hkl_treenode_rotright(node->right);
node = hkl_treenode_rotleft(node);
hkl_treenode_colorflip(node);
}
return node;
}
static HklTreeNode* hkl_treenode_redright(HklTreeNode* node)
{
assert(node != NULL);
hkl_treenode_colorflip(node);
if (node->left != NULL && hkl_treenode_isred(node->left->left))
{
node = hkl_treenode_rotright(node);
hkl_treenode_colorflip(node);
}
return node;
}
static HklTreeNode*
hkl_treenode_insert(HklTree* tree, HklTreeNode* node, HklString* key, void* value)
{
assert(key != NULL);
// Insert in an empty node
if (node == NULL)
{
++tree->size;
return hkl_treenode_new(key, value);
}
if (hkl_treenode_isred(node->left) && hkl_treenode_isred(node->right))
hkl_treenode_colorflip(node);
int cmp = hkl_string_compare(node->pair->key, key);
if (cmp == 0) node->pair->value = value;
else if (cmp < 0) node->left = hkl_treenode_insert(tree, node->left, key, value);
else node->right = hkl_treenode_insert(tree, node->right, key, value);
if (hkl_treenode_isred(node->right) && !hkl_treenode_isred(node->left))
node = hkl_treenode_rotleft(node);
if (hkl_treenode_isred(node->left) && hkl_treenode_isred(node->left->left))
node = hkl_treenode_rotright(node);
return node;
}
static HklTreeNode* hkl_treenode_fixup(HklTreeNode* node)
{
assert(node != NULL);
if (hkl_treenode_isred(node->right))
node = hkl_treenode_rotleft(node);
if (hkl_treenode_isred(node->left) && hkl_treenode_isred(node->left->left))
node = hkl_treenode_rotright(node);
if (hkl_treenode_isred(node->left))
hkl_treenode_colorflip(node);
return node;
}
static HklTreeNode* hkl_treenode_removemin(HklTree* tree, HklTreeNode* node)
{
if (node->left == NULL)
{
--tree->size;
hkl_treenode_free(node);
return NULL;
}
if (!hkl_treenode_isred(node->left) && !hkl_treenode_isred(node->left->left))
node = hkl_treenode_redleft(node);
node->left = hkl_treenode_removemin(tree, node->left);
return hkl_treenode_fixup(node);
}
static HklTreeNode* hkl_treenode_findmin(HklTreeNode* node)
{
while (node->left != NULL)
node = node->left;
return node;
}
static HklTreeNode*
hkl_treenode_remove(HklTree* tree, HklTreeNode* node, HklString* key)
{
assert(node != NULL);
assert(key != NULL);
// If key < current node key, go left
if (hkl_string_compare(key, node->pair->key) < 0)
{
if (node->left != NULL)
{
if (!hkl_treenode_isred(node->left) && hkl_treenode_isred(node->left->left))
node = hkl_treenode_redleft(node);
node->left = hkl_treenode_remove(tree, node->left, key);
}
}
else
{
if (hkl_treenode_isred(node->left))
node = hkl_treenode_rotright(node);
if (hkl_string_compare(key, node->pair->key) == 0 && (node->right == NULL))
{
--tree->size;
hkl_treenode_free(node);
return NULL;
}
if (node->right != NULL)
{
if (!hkl_treenode_isred(node->right) && !hkl_treenode_isred(node->right->left))
node = hkl_treenode_redright(node);
if (hkl_string_compare(key, node->pair->key) == 0)
{
node->pair->value = hkl_treenode_findmin(node->right)->pair->value;
node->right = hkl_treenode_removemin(tree, node->right);
}
else
{
node->right = hkl_treenode_remove(tree, node->right, key);
}
}
}
return hkl_treenode_fixup(node);
}
/**
Adaption of Morris Inorder traversal without a Stack or Recursion
*/
static void hkl_treenode_traverse(HklTreeNode* root,
bool(*fn)(HklPair*, void*), void* data)
{
assert(root != NULL);
HklTreeNode *current, *pre;
if(root == NULL)
return;
current = root;
while(current != NULL)
{
if(current->left == NULL)
{
fn(current->pair, data);
current = current->right;
}
else
{
/* Find the inorder predecessor of current */
pre = current->left;
while(pre->right != NULL && pre->right != current)
pre = pre->right;
/* Make current as right child of its inorder predecessor */
if(pre->right == NULL)
{
pre->right = current;
current = current->left;
}
// Revert the changes in the tree
else
{
pre->right = NULL;
fn(current->pair, data);
current = current->right;
}
}
}
}
/*
* HklTree
*/
HklTree* hkl_tree_new()
{
HklTree* tree = hkl_alloc_object(HklTree);
tree->root = NULL;
tree->size = 0;
return tree;
}
HklPair* hkl_tree_search(HklTree* tree, HklString* key)
{
assert(tree != NULL);
assert(key != NULL);
HklTreeNode* node = tree->root;
int cmp = 0;
while (node != NULL)
{
cmp = hkl_string_compare(node->pair->key, key);
if (cmp == 0)
{
return node->pair;
}
else if (cmp < 0)
{
node = node->left;
}
else
{
node = node->right;
}
}
return NULL;
}
void hkl_tree_insert(HklTree* tree, HklString* key, void* value)
{
assert(tree != NULL);
assert(key != NULL);
tree->root = hkl_treenode_insert(tree, tree->root, key, value);
tree->root->isred = false;
++tree->size;
}
void hkl_tree_remove(HklTree* tree, HklString* key)
{
assert(tree != NULL);
assert(key != NULL);
if (tree->root != NULL)
{
tree->root = hkl_treenode_remove(tree, tree->root, key);
if (tree->root != NULL)
{
tree->root->isred = false;
}
}
}
void hkl_tree_clear(HklTree* tree)
{
assert(tree != NULL);
if (tree->root != NULL)
hkl_treenode_free(tree->root);
tree->size = 0;
tree->root = NULL;
}
void hkl_tree_free(HklTree* tree)
{
hkl_tree_clear(tree);
hkl_free_object(tree);
}
void hkl_tree_traverse(HklTree* tree, bool(*fn)(HklPair*, void*), void* data)
{
assert(tree != NULL);
if (tree->root != NULL)
hkl_treenode_traverse(tree->root, fn, data);
}
// This is the form for moved pairs
// This does not make a copy of a pair
static HklTreeNode* hkl_treenode_new_from_pair(HklPair* pair)
{
assert(pair != NULL);
HklTreeNode* node = hkl_alloc_object(HklTreeNode);
node->pair = pair;
node->left = node->right = NULL;
node->isred = true;
return node;
}
static HklTreeNode* hkl_treenode_move_pair(HklTreeNode* node, HklPair* pair)
{
assert(pair != NULL);
if (node == NULL)
return hkl_treenode_new_from_pair(pair);
if (hkl_treenode_isred(node->left) && hkl_treenode_isred(node->right))
hkl_treenode_colorflip(node);
int cmp = hkl_string_compare(node->pair->key, pair->key);
if (cmp == 0)
{
// This shouldnt happen since we only move into empty trees
assert(false);
node->pair = pair;
}
else if (cmp < 0) node->left = hkl_treenode_move_pair(node->left, pair);
else node->right = hkl_treenode_move_pair(node->right, pair);
if (hkl_treenode_isred(node->right) && !hkl_treenode_isred(node->left))
node = hkl_treenode_rotleft(node);
if (hkl_treenode_isred(node->left) && hkl_treenode_isred(node->left->left))
node = hkl_treenode_rotright(node);
return node;
}
void hkl_tree_move_pair(HklTree* tree, HklPair* pair)
{
assert(tree != NULL);
assert(pair != NULL);
tree->root = hkl_treenode_move_pair(tree->root, pair);
tree->root->isred = false;
}
| hkl/hkl | src/hkl_tree.c | C | mit | 9,955 |
/**
(function(){
window.saveUser();
saveBlog();
var util_v1 = new window.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
})();
**/
/**
(function(w){
w.saveUser();
saveBlog();
var util_v1 = new w.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
})(window);
*/
/**
$(function(w){
w.saveUser();
saveBlog();
var util_v1 = new w.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
}(window));
*/
//最保险的方式
$(function(){
window.saveUser();
saveBlog();
var util_v1 = new window.util_v1();
util_v1.ajax();
test1();
test2();
test3();
test4();
});
//note: 当在$(function(){window.test=fn;});赋值到window时,只能在$(function(){})中调用到window.test!
//ques:
/**Q1
$(function(){
window.test = function(){
alert('test');
};
});
// ok
$(function(){
test();
});
// fail
$(function(w){
w.test();
}(window));
// fail
(function(){
test();
})();
*/
| rainbowCN/soul | javascript/research/JS 10 Share/Javascript技术研究第1讲《JS代码的组织》/app2.js | JavaScript | mit | 1,127 |
# Change Log
All notable changes to this project will be documented in this file.
## 1.0.0
- Initial commit copied from
| kasperwelner/Clean-RxSwift-Template | CHANGELOG.md | Markdown | mit | 124 |
Template.login.events({
'submit form': function(){
event.preventDefault();
var email = event.target.email.value;
var password = event.target.password.value;
//error handling
Meteor.loginWithPassword(email, password, function(error){
if (error) {
alert(error.reason);
} else{
Router.go('/');
};
});
}
}); | quanbinn/healthygeek | client/templates/login.js | JavaScript | mit | 336 |
#include "utility/vector.h"
#include "utility/direction.h"
#include <math.h>
static Vector DIRECTIONS[DIRECTION_POOL_SIZE];
void Direction_init() {
double angle = 0.;
int id;
for (id = 0; id < DIRECTION_POOL_SIZE; ++id) {
Vector_set( &DIRECTIONS[id], cos(angle), -sin(angle) );
angle -= 2 * PI / DIRECTION_POOL_SIZE;
}
}
Vector* Direction_getVector(int id) {
return &DIRECTIONS[id];
}
| OrenjiAkira/spacegame | src/utility/direction.c | C | mit | 427 |
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// Flags: --expose_externalize_string
'use strict';
const common = require('../common');
const assert = require('assert');
const path = require('path');
const fs = require('fs');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
const fn = path.join(tmpdir.path, 'write.txt');
const fn2 = path.join(tmpdir.path, 'write2.txt');
const fn3 = path.join(tmpdir.path, 'write3.txt');
const expected = 'ümlaut.';
const constants = fs.constants;
/* eslint-disable no-undef */
common.allowGlobals(externalizeString, isOneByteString, x);
{
const expected = 'ümlaut eins'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(true, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'latin1');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'latin1'));
}
{
const expected = 'ümlaut zwei'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(true, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'utf8');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'utf8'));
}
{
const expected = '中文 1'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(false, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'ucs2');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'ucs2'));
}
{
const expected = '中文 2'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(false, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'utf8');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'utf8'));
}
/* eslint-enable no-undef */
fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) {
assert.ifError(err);
const done = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
const found = fs.readFileSync(fn, 'utf8');
fs.unlinkSync(fn);
assert.strictEqual(expected, found);
});
const written = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(0, written);
fs.write(fd, expected, 0, 'utf8', done);
});
fs.write(fd, '', 0, 'utf8', written);
}));
const args = constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC;
fs.open(fn2, args, 0o644, common.mustCall((err, fd) => {
assert.ifError(err);
const done = common.mustCall((err, written) => {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
const found = fs.readFileSync(fn2, 'utf8');
fs.unlinkSync(fn2);
assert.strictEqual(expected, found);
});
const written = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(0, written);
fs.write(fd, expected, 0, 'utf8', done);
});
fs.write(fd, '', 0, 'utf8', written);
}));
fs.open(fn3, 'w', 0o644, common.mustCall(function(err, fd) {
assert.ifError(err);
const done = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
});
fs.write(fd, expected, done);
}));
[false, 'test', {}, [], null, undefined].forEach((i) => {
common.expectsError(
() => fs.write(i, common.mustNotCall()),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
}
);
common.expectsError(
() => fs.writeSync(i),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
}
);
});
| MTASZTAKI/ApertusVR | plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/parallel/test-fs-write.js | JavaScript | mit | 4,815 |
using System;
using Microsoft.Extensions.DependencyInjection;
using ZptSharp.Dom;
using ZptSharp.Hosting;
namespace ZptSharp
{
/// <summary>
/// Extension methods for <see cref="IBuildsHostingEnvironment"/> instances.
/// </summary>
public static class XmlHostingBuilderExtensions
{
/// <summary>
/// Adds service registrations to the <paramref name="builder"/> in order
/// to enable reading & writing of XML documents.
/// </summary>
/// <param name="builder">The self-hosting builder.</param>
/// <returns>The self-hosting builder instance, after setting it up.</returns>
public static IBuildsHostingEnvironment AddXmlZptDocuments(this IBuildsHostingEnvironment builder)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
builder.ServiceCollection.AddTransient<XmlDocumentProvider>();
builder.ServiceCollection.AddTransient<IGetsXhtmlDtds, Dom.Resources.EmbeddedResourceXhtmlDtdProvider>();
builder.ServiceCollection.AddTransient<IGetsXmlReaderSettings, XmlReaderSettingsFactory>();
builder.ServiceRegistry.DocumentProviderTypes.Add(typeof(XmlDocumentProvider));
return builder;
}
}
}
| csf-dev/ZPT-Sharp | DocumentProviders/ZptSharp.Xml/XmlHostingBuilderExtensions.cs | C# | mit | 1,301 |
abstract sealed class Action
case class Atom(atom: Unit => Action) extends Action {
override def toString() = "atom"
}
case class Fork(a1: Action, a2: Action) extends Action {
override def toString = s"fork ${a1 toString} ${a2 toString}"
}
case class Stop() extends Action {
override def toString = "stop"
}
// Note: The ones marked '/* */' are the original exercises
class Concurrent[A](val func: (A => Action) => Action) {
import Concurrent.roundRobin
def andThen[B](after: Concurrent[B]): Concurrent[B] = flatMap(_ => after)
/* */
def action(): Action = func { x: A => Stop() }
/* */
def fork(): Concurrent[Unit] = Concurrent {
(cont: Unit => Action) => Fork(action(), cont())
}
/* */
def flatMap[B](mapper: A => Concurrent[B]): Concurrent[B] = Concurrent {
(cont: B => Action) => func { x: A => mapper(x).func(cont) }
}
def run(): () => Unit = roundRobin(List[Action](action))
}
object Concurrent {
def apply[A](func: (A => Action) => Action) = new Concurrent[A](func)
def of[A](a: A) = new Concurrent((cont: A => Action) => cont(a))
/* */
def stop[A](): Concurrent[A] = Concurrent {
(cont: A => Action) => Stop()
}
/* */
def atom[A](ioA: Unit => A): Concurrent[A] = Concurrent {
(cont: A => Action) => Atom { x: Unit => cont( ioA (x) ) }
}
/* */
def par[A](c1: Concurrent[A], c2: Concurrent[A]): Concurrent[A] = Concurrent {
(cont: A => Action) => Fork (c1.action(), c2.action())
}
/* */
private def roundRobin(list: List[Action]): () => Unit = list match {
case Nil => () => Unit
case head :: tail => head match {
case Atom(x) => roundRobin(tail ::: List(x()))
case Fork(f1, f2) => roundRobin(f1 :: f2 :: tail)
case Stop() => roundRobin(tail)
}
}
}
| mitochon/hexercise | src/mooc/fp101/Lab5Scala/Concurrent.scala | Scala | mit | 1,856 |
/**
* @generated-from ./$execute.test.js
* This file is autogenerated from a template. Please do not edit it directly.
* To rebuild it from its template use the command
* > npm run generate
* More information can be found in CONTRIBUTING.md
*/
/* eslint-disable no-unused-vars */
import { asyncExecute } from '../..'
describe('asyncExecute', () => {
it('executes forever', async () => {
const iter = asyncExecute(() => 1)
expect((await iter.next())).toEqual({
value: 1,
done: false
})
expect((await iter.next())).toEqual({
value: 1,
done: false
})
expect((await iter.next())).toEqual({
value: 1,
done: false
})
})
it('can be passed additional arguments', async () => {
const iter = asyncExecute((a, b) => a + b + 1, 4, 6)
expect((await iter.next())).toEqual({
value: 11,
done: false
})
expect((await iter.next())).toEqual({
value: 11,
done: false
})
expect((await iter.next())).toEqual({
value: 11,
done: false
})
})
it('executes forever (with promise value)', async () => {
const iter = asyncExecute(() => Promise.resolve(1))
expect((await iter.next())).toEqual({
value: 1,
done: false
})
expect((await iter.next())).toEqual({
value: 1,
done: false
})
expect((await iter.next())).toEqual({
value: 1,
done: false
})
})
})
| sithmel/iter-tools | src/__tests__/async-execute.test.js | JavaScript | mit | 1,434 |
<?php
namespace Brasa\RecursoHumanoBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class RhuCapacitacionTipoRepository extends EntityRepository {
} | wariox3/brasa | src/Brasa/RecursoHumanoBundle/Repository/RhuCapacitacionTipoRepository.php | PHP | mit | 270 |
var through = require('through2');
var cheerio = require('cheerio');
var gulp = require('gulp');
var url = require('url');
var path = require('path');
var fs = require('fs');
var typeMap = {
css: {
tag: 'link',
template: function(contents, el) {
var attribute = el.attr('media');
attribute = attribute ? ' media="' + attribute + '" ' : '';
return '<style' + attribute + '>\n' + String(contents) + '\n</style>';
},
filter: function(el) {
return el.attr('rel') === 'stylesheet' && isLocal(el.attr('href'));
},
getSrc: function(el) {
return el.attr('href');
}
},
js: {
tag: 'script',
template: function(contents) {
return '<script type="text/javascript">\n' + String(contents) + '\n</script>';
},
filter: function(el) {
return isLocal(el.attr('src'));
},
getSrc: function(el) {
return el.attr('src');
}
},
img: {
tag: 'img',
template: function(contents, el) {
el.attr('src', 'data:image/unknown;base64,' + contents.toString('base64'));
return cheerio.html(el);
},
filter: function(el) {
var src = el.attr('src');
return !/\.svg$/.test(src);
},
getSrc: function(el) {
return el.attr('src');
}
},
svg: {
tag: 'img',
template: function(contents) {
return String(contents);
},
filter: function(el) {
var src = el.attr('src');
return /\.svg$/.test(src) && isLocal(src);
},
getSrc: function(el) {
return el.attr('src');
}
}
};
function noop() {
return through.obj(function(file, enc, cb) {
this.push(file);
cb();
});
}
function after(n, cb) {
var i = 0;
return function() {
i++;
if(i === n) cb.apply(this, arguments);
};
}
function isLocal(href) {
return href && href.slice(0, 2) !== '//' && ! url.parse(href).hostname;
}
function replace(el, tmpl) {
return through.obj(function(file, enc, cb) {
el.replaceWith(tmpl(file.contents, el));
this.push(file);
cb();
});
}
function inject($, process, base, cb, opts, relative, ignoredFiles) {
var items = [];
$(opts.tag).each(function(idx, el) {
el = $(el);
if(opts.filter(el)) {
items.push(el);
}
});
if(items.length) {
var done = after(items.length, cb);
items.forEach(function(el) {
var src = opts.getSrc(el) || '';
var file = path.join(src[0] === '/' ? base : relative, src);
if (fs.existsSync(file) && ignoredFiles.indexOf(src) === -1) {
gulp.src(file)
.pipe(process || noop())
.pipe(replace(el, opts.template))
.pipe(through.obj(function(file, enc, cb) {
cb();
}, done));
} else {
done();
}
});
} else {
cb();
}
}
module.exports = function(opts) {
opts = opts || {};
opts.base = opts.base || '';
opts.ignore = opts.ignore || [];
opts.disabledTypes = opts.disabledTypes || [];
return through.obj(function(file, enc, cb) {
var self = this;
var $ = cheerio.load(String(file.contents), {decodeEntities: false});
var typeKeys = Object.getOwnPropertyNames(typeMap);
var done = after(typeKeys.length, function() {
file.contents = new Buffer($.html());
self.push(file);
cb();
});
typeKeys.forEach(function(type) {
if (opts.disabledTypes.indexOf(type) === -1) {
inject($, opts[type], opts.base, done, typeMap[type], path.dirname(file.path), opts.ignore);
} else {
done();
}
});
});
};
| jonnyscholes/gulp-inline | index.js | JavaScript | mit | 3,543 |
package strain
type Ints []int
type Lists [][]int
type Strings []string
func (i Ints) Keep(filter func(int) bool) Ints {
if i == nil {
return nil
}
filtered := []int{}
for _, v := range i {
if filter(v) {
filtered = append(filtered, v)
}
}
i = filtered
return i
}
func (i Ints) Discard(filter func(int) bool) Ints {
if i == nil {
return nil
}
return i.Keep(func(i int) bool {
return !filter(i)
})
}
func (l Lists) Keep(filter func([]int) bool) Lists {
if l == nil {
return nil
}
filtered := [][]int{}
for _, v := range l {
if filter(v) {
filtered = append(filtered, v)
}
}
l = filtered
return l
}
func (s Strings) Keep(filter func(string) bool) Strings {
if s == nil {
return nil
}
filtered := []string{}
for _, v := range s {
if filter(v) {
filtered = append(filtered, v)
}
}
s = filtered
return s
}
| rootulp/exercism | go/strain/strain.go | GO | mit | 862 |
/************************************************************************************
PublicHeader: OVR.h
Filename : OVR_Math.h
Content : Implementation of 3D primitives such as vectors, matrices.
Created : September 4, 2012
Authors : Andrew Reisse, Michael Antonov, Steve LaValle, Anna Yershova
Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved.
Use of this software is subject to the terms of the Oculus license
agreement provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
*************************************************************************************/
#ifndef OVR_Math_h
#define OVR_Math_h
#include <assert.h>
#include <stdlib.h>
#include <math.h>
#include "OVR_Types.h"
#include "OVR_RefCount.h"
namespace OVR {
//-------------------------------------------------------------------------------------
// Constants for 3D world/axis definitions.
// Definitions of axes for coordinate and rotation conversions.
enum Axis
{
Axis_X = 0, Axis_Y = 1, Axis_Z = 2
};
// RotateDirection describes the rotation direction around an axis, interpreted as follows:
// CW - Clockwise while looking "down" from positive axis towards the origin.
// CCW - Counter-clockwise while looking from the positive axis towards the origin,
// which is in the negative axis direction.
// CCW is the default for the RHS coordinate system. Oculus standard RHS coordinate
// system defines Y up, X right, and Z back (pointing out from the screen). In this
// system Rotate_CCW around Z will specifies counter-clockwise rotation in XY plane.
enum RotateDirection
{
Rotate_CCW = 1,
Rotate_CW = -1
};
enum HandedSystem
{
Handed_R = 1, Handed_L = -1
};
// AxisDirection describes which way the axis points. Used by WorldAxes.
enum AxisDirection
{
Axis_Up = 2,
Axis_Down = -2,
Axis_Right = 1,
Axis_Left = -1,
Axis_In = 3,
Axis_Out = -3
};
struct WorldAxes
{
AxisDirection XAxis, YAxis, ZAxis;
WorldAxes(AxisDirection x, AxisDirection y, AxisDirection z)
: XAxis(x), YAxis(y), ZAxis(z)
{ OVR_ASSERT(abs(x) != abs(y) && abs(y) != abs(z) && abs(z) != abs(x));}
};
//-------------------------------------------------------------------------------------
// ***** Math
// Math class contains constants and functions. This class is a template specialized
// per type, with Math<float> and Math<double> being distinct.
template<class Type>
class Math
{
};
// Single-precision Math constants class.
template<>
class Math<float>
{
public:
static const float Pi;
static const float TwoPi;
static const float PiOver2;
static const float PiOver4;
static const float E;
static const float MaxValue; // Largest positive float Value
static const float MinPositiveValue; // Smallest possible positive value
static const float RadToDegreeFactor;
static const float DegreeToRadFactor;
static const float Tolerance; // 0.00001f;
static const float SingularityRadius; //0.00000000001f for Gimbal lock numerical problems
};
// Double-precision Math constants class.
template<>
class Math<double>
{
public:
static const double Pi;
static const double TwoPi;
static const double PiOver2;
static const double PiOver4;
static const double E;
static const double MaxValue; // Largest positive double Value
static const double MinPositiveValue; // Smallest possible positive value
static const double RadToDegreeFactor;
static const double DegreeToRadFactor;
static const double Tolerance; // 0.00001f;
static const double SingularityRadius; //0.00000000001 for Gimbal lock numerical problems
};
typedef Math<float> Mathf;
typedef Math<double> Mathd;
// Conversion functions between degrees and radians
template<class FT>
FT RadToDegree(FT rads) { return rads * Math<FT>::RadToDegreeFactor; }
template<class FT>
FT DegreeToRad(FT rads) { return rads * Math<FT>::DegreeToRadFactor; }
template<class T>
class Quat;
//-------------------------------------------------------------------------------------
// ***** Vector2f - 2D Vector2f
// Vector2f represents a 2-dimensional vector or point in space,
// consisting of coordinates x and y,
template<class T>
class Vector2
{
public:
T x, y;
Vector2() : x(0), y(0) { }
Vector2(T x_, T y_) : x(x_), y(y_) { }
explicit Vector2(T s) : x(s), y(s) { }
bool operator== (const Vector2& b) const { return x == b.x && y == b.y; }
bool operator!= (const Vector2& b) const { return x != b.x || y != b.y; }
Vector2 operator+ (const Vector2& b) const { return Vector2(x + b.x, y + b.y); }
Vector2& operator+= (const Vector2& b) { x += b.x; y += b.y; return *this; }
Vector2 operator- (const Vector2& b) const { return Vector2(x - b.x, y - b.y); }
Vector2& operator-= (const Vector2& b) { x -= b.x; y -= b.y; return *this; }
Vector2 operator- () const { return Vector2(-x, -y); }
// Scalar multiplication/division scales vector.
Vector2 operator* (T s) const { return Vector2(x*s, y*s); }
Vector2& operator*= (T s) { x *= s; y *= s; return *this; }
Vector2 operator/ (T s) const { T rcp = T(1)/s;
return Vector2(x*rcp, y*rcp); }
Vector2& operator/= (T s) { T rcp = T(1)/s;
x *= rcp; y *= rcp;
return *this; }
// Compare two vectors for equality with tolerance. Returns true if vectors match withing tolerance.
bool Compare(const Vector2&b, T tolerance = Mathf::Tolerance)
{
return (fabs(b.x-x) < tolerance) && (fabs(b.y-y) < tolerance);
}
// Dot product overload.
// Used to calculate angle q between two vectors among other things,
// as (A dot B) = |a||b|cos(q).
T operator* (const Vector2& b) const { return x*b.x + y*b.y; }
// Returns the angle from this vector to b, in radians.
T Angle(const Vector2& b) const { return acos((*this * b)/(Length()*b.Length())); }
// Return Length of the vector squared.
T LengthSq() const { return (x * x + y * y); }
// Return vector length.
T Length() const { return sqrt(LengthSq()); }
// Returns distance between two points represented by vectors.
T Distance(Vector2& b) const { return (*this - b).Length(); }
// Determine if this a unit vector.
bool IsNormalized() const { return fabs(LengthSq() - T(1)) < Math<T>::Tolerance; }
// Normalize, convention vector length to 1.
void Normalize() { *this /= Length(); }
// Returns normalized (unit) version of the vector without modifying itself.
Vector2 Normalized() const { return *this / Length(); }
// Linearly interpolates from this vector to another.
// Factor should be between 0.0 and 1.0, with 0 giving full value to this.
Vector2 Lerp(const Vector2& b, T f) const { return *this*(T(1) - f) + b*f; }
// Projects this vector onto the argument; in other words,
// A.Project(B) returns projection of vector A onto B.
Vector2 ProjectTo(const Vector2& b) const { return b * ((*this * b) / b.LengthSq()); }
};
typedef Vector2<float> Vector2f;
typedef Vector2<double> Vector2d;
//-------------------------------------------------------------------------------------
// ***** Vector3f - 3D Vector3f
// Vector3f represents a 3-dimensional vector or point in space,
// consisting of coordinates x, y and z.
template<class T>
class Vector3
{
public:
T x, y, z;
Vector3() : x(0), y(0), z(0) { }
Vector3(T x_, T y_, T z_ = 0) : x(x_), y(y_), z(z_) { }
explicit Vector3(T s) : x(s), y(s), z(s) { }
bool operator== (const Vector3& b) const { return x == b.x && y == b.y && z == b.z; }
bool operator!= (const Vector3& b) const { return x != b.x || y != b.y || z != b.z; }
Vector3 operator+ (const Vector3& b) const { return Vector3(x + b.x, y + b.y, z + b.z); }
Vector3& operator+= (const Vector3& b) { x += b.x; y += b.y; z += b.z; return *this; }
Vector3 operator- (const Vector3& b) const { return Vector3(x - b.x, y - b.y, z - b.z); }
Vector3& operator-= (const Vector3& b) { x -= b.x; y -= b.y; z -= b.z; return *this; }
Vector3 operator- () const { return Vector3(-x, -y, -z); }
// Scalar multiplication/division scales vector.
Vector3 operator* (T s) const { return Vector3(x*s, y*s, z*s); }
Vector3& operator*= (T s) { x *= s; y *= s; z *= s; return *this; }
Vector3 operator/ (T s) const { T rcp = T(1)/s;
return Vector3(x*rcp, y*rcp, z*rcp); }
Vector3& operator/= (T s) { T rcp = T(1)/s;
x *= rcp; y *= rcp; z *= rcp;
return *this; }
// Compare two vectors for equality with tolerance. Returns true if vectors match withing tolerance.
bool Compare(const Vector3&b, T tolerance = Mathf::Tolerance)
{
return (fabs(b.x-x) < tolerance) && (fabs(b.y-y) < tolerance) && (fabs(b.z-z) < tolerance);
}
// Dot product overload.
// Used to calculate angle q between two vectors among other things,
// as (A dot B) = |a||b|cos(q).
T operator* (const Vector3& b) const { return x*b.x + y*b.y + z*b.z; }
// Compute cross product, which generates a normal vector.
// Direction vector can be determined by right-hand rule: Pointing index finder in
// direction a and middle finger in direction b, thumb will point in a.Cross(b).
Vector3 Cross(const Vector3& b) const { return Vector3(y*b.z - z*b.y,
z*b.x - x*b.z,
x*b.y - y*b.x); }
// Returns the angle from this vector to b, in radians.
T Angle(const Vector3& b) const { return acos((*this * b)/(Length()*b.Length())); }
// Return Length of the vector squared.
T LengthSq() const { return (x * x + y * y + z * z); }
// Return vector length.
T Length() const { return sqrt(LengthSq()); }
// Returns distance between two points represented by vectors.
T Distance(Vector3& b) const { return (*this - b).Length(); }
// Determine if this a unit vector.
bool IsNormalized() const { return fabs(LengthSq() - T(1)) < Math<T>::Tolerance; }
// Normalize, convention vector length to 1.
void Normalize() { *this /= Length(); }
// Returns normalized (unit) version of the vector without modifying itself.
Vector3 Normalized() const { return *this / Length(); }
// Linearly interpolates from this vector to another.
// Factor should be between 0.0 and 1.0, with 0 giving full value to this.
Vector3 Lerp(const Vector3& b, T f) const { return *this*(T(1) - f) + b*f; }
// Projects this vector onto the argument; in other words,
// A.Project(B) returns projection of vector A onto B.
Vector3 ProjectTo(const Vector3& b) const { return b * ((*this * b) / b.LengthSq()); }
};
typedef Vector3<float> Vector3f;
typedef Vector3<double> Vector3d;
//-------------------------------------------------------------------------------------
// ***** Matrix4f
// Matrix4f is a 4x4 matrix used for 3d transformations and projections.
// Translation stored in the last column.
// The matrix is stored in row-major order in memory, meaning that values
// of the first row are stored before the next one.
//
// The arrangement of the matrix is chosen to be in Right-Handed
// coordinate system and counterclockwise rotations when looking down
// the axis
//
// Transformation Order:
// - Transformations are applied from right to left, so the expression
// M1 * M2 * M3 * V means that the vector V is transformed by M3 first,
// followed by M2 and M1.
//
// Coordinate system: Right Handed
//
// Rotations: Counterclockwise when looking down the axis. All angles are in radians.
//
// | sx 01 02 tx | // First column (sx, 10, 20): Axis X basis vector.
// | 10 sy 12 ty | // Second column (01, sy, 21): Axis Y basis vector.
// | 20 21 sz tz | // Third columnt (02, 12, sz): Axis Z basis vector.
// | 30 31 32 33 |
//
// The basis vectors are first three columns.
class Matrix4f
{
static Matrix4f IdentityValue;
public:
float M[4][4];
enum NoInitType { NoInit };
// Construct with no memory initialization.
Matrix4f(NoInitType) { }
// By default, we construct identity matrix.
Matrix4f()
{
SetIdentity();
}
Matrix4f(float m11, float m12, float m13, float m14,
float m21, float m22, float m23, float m24,
float m31, float m32, float m33, float m34,
float m41, float m42, float m43, float m44)
{
M[0][0] = m11; M[0][1] = m12; M[0][2] = m13; M[0][3] = m14;
M[1][0] = m21; M[1][1] = m22; M[1][2] = m23; M[1][3] = m24;
M[2][0] = m31; M[2][1] = m32; M[2][2] = m33; M[2][3] = m34;
M[3][0] = m41; M[3][1] = m42; M[3][2] = m43; M[3][3] = m44;
}
Matrix4f(float m11, float m12, float m13,
float m21, float m22, float m23,
float m31, float m32, float m33)
{
M[0][0] = m11; M[0][1] = m12; M[0][2] = m13; M[0][3] = 0;
M[1][0] = m21; M[1][1] = m22; M[1][2] = m23; M[1][3] = 0;
M[2][0] = m31; M[2][1] = m32; M[2][2] = m33; M[2][3] = 0;
M[3][0] = 0; M[3][1] = 0; M[3][2] = 0; M[3][3] = 1;
}
static const Matrix4f& Identity() { return IdentityValue; }
void SetIdentity()
{
M[0][0] = M[1][1] = M[2][2] = M[3][3] = 1;
M[0][1] = M[1][0] = M[2][3] = M[3][1] = 0;
M[0][2] = M[1][2] = M[2][0] = M[3][2] = 0;
M[0][3] = M[1][3] = M[2][1] = M[3][0] = 0;
}
// Multiplies two matrices into destination with minimum copying.
static Matrix4f& Multiply(Matrix4f* d, const Matrix4f& a, const Matrix4f& b)
{
OVR_ASSERT((d != &a) && (d != &b));
int i = 0;
do {
d->M[i][0] = a.M[i][0] * b.M[0][0] + a.M[i][1] * b.M[1][0] + a.M[i][2] * b.M[2][0] + a.M[i][3] * b.M[3][0];
d->M[i][1] = a.M[i][0] * b.M[0][1] + a.M[i][1] * b.M[1][1] + a.M[i][2] * b.M[2][1] + a.M[i][3] * b.M[3][1];
d->M[i][2] = a.M[i][0] * b.M[0][2] + a.M[i][1] * b.M[1][2] + a.M[i][2] * b.M[2][2] + a.M[i][3] * b.M[3][2];
d->M[i][3] = a.M[i][0] * b.M[0][3] + a.M[i][1] * b.M[1][3] + a.M[i][2] * b.M[2][3] + a.M[i][3] * b.M[3][3];
} while((++i) < 4);
return *d;
}
Matrix4f operator* (const Matrix4f& b) const
{
Matrix4f result(Matrix4f::NoInit);
Multiply(&result, *this, b);
return result;
}
Matrix4f& operator*= (const Matrix4f& b)
{
return Multiply(this, Matrix4f(*this), b);
}
Matrix4f operator* (float s) const
{
return Matrix4f(M[0][0] * s, M[0][1] * s, M[0][2] * s, M[0][3] * s,
M[1][0] * s, M[1][1] * s, M[1][2] * s, M[1][3] * s,
M[2][0] * s, M[2][1] * s, M[2][2] * s, M[2][3] * s,
M[3][0] * s, M[3][1] * s, M[3][2] * s, M[3][3] * s);
}
Matrix4f& operator*= (float s)
{
M[0][0] *= s; M[0][1] *= s; M[0][2] *= s; M[0][3] *= s;
M[1][0] *= s; M[1][1] *= s; M[1][2] *= s; M[1][3] *= s;
M[2][0] *= s; M[2][1] *= s; M[2][2] *= s; M[2][3] *= s;
M[3][0] *= s; M[3][1] *= s; M[3][2] *= s; M[3][3] *= s;
return *this;
}
Vector3f Transform(const Vector3f& v) const
{
return Vector3f(M[0][0] * v.x + M[0][1] * v.y + M[0][2] * v.z + M[0][3],
M[1][0] * v.x + M[1][1] * v.y + M[1][2] * v.z + M[1][3],
M[2][0] * v.x + M[2][1] * v.y + M[2][2] * v.z + M[2][3]);
}
Matrix4f Transposed() const
{
return Matrix4f(M[0][0], M[1][0], M[2][0], M[3][0],
M[0][1], M[1][1], M[2][1], M[3][1],
M[0][2], M[1][2], M[2][2], M[3][2],
M[0][3], M[1][3], M[2][3], M[3][3]);
}
void Transpose()
{
*this = Transposed();
}
float SubDet (const int* rows, const int* cols) const
{
return M[rows[0]][cols[0]] * (M[rows[1]][cols[1]] * M[rows[2]][cols[2]] - M[rows[1]][cols[2]] * M[rows[2]][cols[1]])
- M[rows[0]][cols[1]] * (M[rows[1]][cols[0]] * M[rows[2]][cols[2]] - M[rows[1]][cols[2]] * M[rows[2]][cols[0]])
+ M[rows[0]][cols[2]] * (M[rows[1]][cols[0]] * M[rows[2]][cols[1]] - M[rows[1]][cols[1]] * M[rows[2]][cols[0]]);
}
float Cofactor(int I, int J) const
{
const int indices[4][3] = {{1,2,3},{0,2,3},{0,1,3},{0,1,2}};
return ((I+J)&1) ? -SubDet(indices[I],indices[J]) : SubDet(indices[I],indices[J]);
}
float Determinant() const
{
return M[0][0] * Cofactor(0,0) + M[0][1] * Cofactor(0,1) + M[0][2] * Cofactor(0,2) + M[0][3] * Cofactor(0,3);
}
Matrix4f Adjugated() const
{
return Matrix4f(Cofactor(0,0), Cofactor(1,0), Cofactor(2,0), Cofactor(3,0),
Cofactor(0,1), Cofactor(1,1), Cofactor(2,1), Cofactor(3,1),
Cofactor(0,2), Cofactor(1,2), Cofactor(2,2), Cofactor(3,2),
Cofactor(0,3), Cofactor(1,3), Cofactor(2,3), Cofactor(3,3));
}
Matrix4f Inverted() const
{
float det = Determinant();
assert(det != 0);
return Adjugated() * (1.0f/det);
}
void Invert()
{
*this = Inverted();
}
//AnnaSteve:
// a,b,c, are the YawPitchRoll angles to be returned
// rotation a around axis A1
// is followed by rotation b around axis A2
// is followed by rotation c around axis A3
// rotations are CCW or CW (D) in LH or RH coordinate system (S)
template <Axis A1, Axis A2, Axis A3, RotateDirection D, HandedSystem S>
void ToEulerAngles(float *a, float *b, float *c)
{
OVR_COMPILER_ASSERT((A1 != A2) && (A2 != A3) && (A1 != A3));
float psign = -1.0f;
if (((A1 + 1) % 3 == A2) && ((A2 + 1) % 3 == A3)) // Determine whether even permutation
psign = 1.0f;
float pm = psign*M[A1][A3];
if (pm < -1.0f + Math<float>::SingularityRadius)
{ // South pole singularity
*a = 0.0f;
*b = -S*D*Math<float>::PiOver2;
*c = S*D*atan2( psign*M[A2][A1], M[A2][A2] );
}
else if (pm > 1.0 - Math<float>::SingularityRadius)
{ // North pole singularity
*a = 0.0f;
*b = S*D*Math<float>::PiOver2;
*c = S*D*atan2( psign*M[A2][A1], M[A2][A2] );
}
else
{ // Normal case (nonsingular)
*a = S*D*atan2( -psign*M[A2][A3], M[A3][A3] );
*b = S*D*asin(pm);
*c = S*D*atan2( -psign*M[A1][A2], M[A1][A1] );
}
return;
}
//AnnaSteve:
// a,b,c, are the YawPitchRoll angles to be returned
// rotation a around axis A1
// is followed by rotation b around axis A2
// is followed by rotation c around axis A1
// rotations are CCW or CW (D) in LH or RH coordinate system (S)
template <Axis A1, Axis A2, RotateDirection D, HandedSystem S>
void ToEulerAnglesABA(float *a, float *b, float *c)
{
OVR_COMPILER_ASSERT(A1 != A2);
// Determine the axis that was not supplied
int m = 3 - A1 - A2;
float psign = -1.0f;
if ((A1 + 1) % 3 == A2) // Determine whether even permutation
psign = 1.0f;
float c2 = M[A1][A1];
if (c2 < -1.0 + Math<float>::SingularityRadius)
{ // South pole singularity
*a = 0.0f;
*b = S*D*Math<float>::Pi;
*c = S*D*atan2( -psign*M[A2][m],M[A2][A2]);
}
else if (c2 > 1.0 - Math<float>::SingularityRadius)
{ // North pole singularity
*a = 0.0f;
*b = 0.0f;
*c = S*D*atan2( -psign*M[A2][m],M[A2][A2]);
}
else
{ // Normal case (nonsingular)
*a = S*D*atan2( M[A2][A1],-psign*M[m][A1]);
*b = S*D*acos(c2);
*c = S*D*atan2( M[A1][A2],psign*M[A1][m]);
}
return;
}
// Creates a matrix that converts the vertices from one coordinate system
// to another.
//
static Matrix4f AxisConversion(const WorldAxes& to, const WorldAxes& from)
{
// Holds axis values from the 'to' structure
int toArray[3] = { to.XAxis, to.YAxis, to.ZAxis };
// The inverse of the toArray
int inv[4];
inv[0] = inv[abs(to.XAxis)] = 0;
inv[abs(to.YAxis)] = 1;
inv[abs(to.ZAxis)] = 2;
Matrix4f m(0, 0, 0,
0, 0, 0,
0, 0, 0);
// Only three values in the matrix need to be changed to 1 or -1.
m.M[inv[abs(from.XAxis)]][0] = float(from.XAxis/toArray[inv[abs(from.XAxis)]]);
m.M[inv[abs(from.YAxis)]][1] = float(from.YAxis/toArray[inv[abs(from.YAxis)]]);
m.M[inv[abs(from.ZAxis)]][2] = float(from.ZAxis/toArray[inv[abs(from.ZAxis)]]);
return m;
}
static Matrix4f Translation(const Vector3f& v)
{
Matrix4f t;
t.M[0][3] = v.x;
t.M[1][3] = v.y;
t.M[2][3] = v.z;
return t;
}
static Matrix4f Translation(float x, float y, float z = 0.0f)
{
Matrix4f t;
t.M[0][3] = x;
t.M[1][3] = y;
t.M[2][3] = z;
return t;
}
static Matrix4f Scaling(const Vector3f& v)
{
Matrix4f t;
t.M[0][0] = v.x;
t.M[1][1] = v.y;
t.M[2][2] = v.z;
return t;
}
static Matrix4f Scaling(float x, float y, float z)
{
Matrix4f t;
t.M[0][0] = x;
t.M[1][1] = y;
t.M[2][2] = z;
return t;
}
static Matrix4f Scaling(float s)
{
Matrix4f t;
t.M[0][0] = s;
t.M[1][1] = s;
t.M[2][2] = s;
return t;
}
//AnnaSteve : Just for quick testing. Not for final API. Need to remove case.
static Matrix4f RotationAxis(Axis A, float angle, RotateDirection d, HandedSystem s)
{
float sina = s * d *sin(angle);
float cosa = cos(angle);
switch(A)
{
case Axis_X:
return Matrix4f(1, 0, 0,
0, cosa, -sina,
0, sina, cosa);
case Axis_Y:
return Matrix4f(cosa, 0, sina,
0, 1, 0,
-sina, 0, cosa);
case Axis_Z:
return Matrix4f(cosa, -sina, 0,
sina, cosa, 0,
0, 0, 1);
}
}
// Creates a rotation matrix rotating around the X axis by 'angle' radians.
// Rotation direction is depends on the coordinate system:
// RHS (Oculus default): Positive angle values rotate Counter-clockwise (CCW),
// while looking in the negative axis direction. This is the
// same as looking down from positive axis values towards origin.
// LHS: Positive angle values rotate clock-wise (CW), while looking in the
// negative axis direction.
static Matrix4f RotationX(float angle)
{
float sina = sin(angle);
float cosa = cos(angle);
return Matrix4f(1, 0, 0,
0, cosa, -sina,
0, sina, cosa);
}
// Creates a rotation matrix rotating around the Y axis by 'angle' radians.
// Rotation direction is depends on the coordinate system:
// RHS (Oculus default): Positive angle values rotate Counter-clockwise (CCW),
// while looking in the negative axis direction. This is the
// same as looking down from positive axis values towards origin.
// LHS: Positive angle values rotate clock-wise (CW), while looking in the
// negative axis direction.
static Matrix4f RotationY(float angle)
{
float sina = sin(angle);
float cosa = cos(angle);
return Matrix4f(cosa, 0, sina,
0, 1, 0,
-sina, 0, cosa);
}
// Creates a rotation matrix rotating around the Z axis by 'angle' radians.
// Rotation direction is depends on the coordinate system:
// RHS (Oculus default): Positive angle values rotate Counter-clockwise (CCW),
// while looking in the negative axis direction. This is the
// same as looking down from positive axis values towards origin.
// LHS: Positive angle values rotate clock-wise (CW), while looking in the
// negative axis direction.
static Matrix4f RotationZ(float angle)
{
float sina = sin(angle);
float cosa = cos(angle);
return Matrix4f(cosa, -sina, 0,
sina, cosa, 0,
0, 0, 1);
}
// LookAtRH creates a View transformation matrix for right-handed coordinate system.
// The resulting matrix points camera from 'eye' towards 'at' direction, with 'up'
// specifying the up vector. The resulting matrix should be used with PerspectiveRH
// projection.
static Matrix4f LookAtRH(const Vector3f& eye, const Vector3f& at, const Vector3f& up);
// LookAtLH creates a View transformation matrix for left-handed coordinate system.
// The resulting matrix points camera from 'eye' towards 'at' direction, with 'up'
// specifying the up vector.
static Matrix4f LookAtLH(const Vector3f& eye, const Vector3f& at, const Vector3f& up);
// PerspectiveRH creates a right-handed perspective projection matrix that can be
// used with the Oculus sample renderer.
// yfov - Specifies vertical field of view in radians.
// aspect - Screen aspect ration, which is usually width/height for square pixels.
// Note that xfov = yfov * aspect.
// znear - Absolute value of near Z clipping clipping range.
// zfar - Absolute value of far Z clipping clipping range (larger then near).
// Even though RHS usually looks in the direction of negative Z, positive values
// are expected for znear and zfar.
static Matrix4f PerspectiveRH(float yfov, float aspect, float znear, float zfar);
// PerspectiveRH creates a left-handed perspective projection matrix that can be
// used with the Oculus sample renderer.
// yfov - Specifies vertical field of view in radians.
// aspect - Screen aspect ration, which is usually width/height for square pixels.
// Note that xfov = yfov * aspect.
// znear - Absolute value of near Z clipping clipping range.
// zfar - Absolute value of far Z clipping clipping range (larger then near).
static Matrix4f PerspectiveLH(float yfov, float aspect, float znear, float zfar);
static Matrix4f Ortho2D(float w, float h);
};
//-------------------------------------------------------------------------------------
// ***** Quat
// Quatf represents a quaternion class used for rotations.
//
// Quaternion multiplications are done in right-to-left order, to match the
// behavior of matrices.
template<class T>
class Quat
{
public:
// w + Xi + Yj + Zk
T x, y, z, w;
Quat() : x(0), y(0), z(0), w(1) {}
Quat(T x_, T y_, T z_, T w_) : x(x_), y(y_), z(z_), w(w_) {}
// Constructs rotation quaternion around the axis.
Quat(const Vector3<T>& axis, T angle)
{
Vector3<T> unitAxis = axis.Normalized();
T sinHalfAngle = sin(angle * T(0.5));
w = cos(angle * T(0.5));
x = unitAxis.x * sinHalfAngle;
y = unitAxis.y * sinHalfAngle;
z = unitAxis.z * sinHalfAngle;
}
//AnnaSteve:
void AxisAngle(Axis A, T angle, RotateDirection d, HandedSystem s)
{
T sinHalfAngle = s * d *sin(angle * (T)0.5);
T v[3];
v[0] = v[1] = v[2] = (T)0;
v[A] = sinHalfAngle;
//return Quat(v[0], v[1], v[2], cos(angle * (T)0.5));
w = cos(angle * (T)0.5);
x = v[0];
y = v[1];
z = v[2];
}
void GetAxisAngle(Vector3<T>* axis, T* angle) const
{
if (LengthSq() > Math<T>::Tolerance * Math<T>::Tolerance)
{
*axis = Vector3<T>(x, y, z).Normalized();
*angle = 2 * acos(w);
}
else
{
*axis = Vector3<T>(1, 0, 0);
*angle= 0;
}
}
bool operator== (const Quat& b) const { return x == b.x && y == b.y && z == b.z && w == b.w; }
bool operator!= (const Quat& b) const { return x != b.x || y != b.y || z != b.z || w != b.w; }
Quat operator+ (const Quat& b) const { return Quat(x + b.x, y + b.y, z + b.z, w + b.w); }
Quat& operator+= (const Quat& b) { w += b.w; x += b.x; y += b.y; z += b.z; return *this; }
Quat operator- (const Quat& b) const { return Quat(x - b.x, y - b.y, z - b.z, w - b.w); }
Quat& operator-= (const Quat& b) { w -= b.w; x -= b.x; y -= b.y; z -= b.z; return *this; }
Quat operator* (T s) const { return Quat(x * s, y * s, z * s, w * s); }
Quat& operator*= (T s) { w *= s; x *= s; y *= s; z *= s; return *this; }
Quat operator/ (T s) const { T rcp = T(1)/s; return Quat(x * rcp, y * rcp, z * rcp, w *rcp); }
Quat& operator/= (T s) { T rcp = T(1)/s; w *= rcp; x *= rcp; y *= rcp; z *= rcp; return *this; }
// Get Imaginary part vector
Vector3<T> Imag() const { return Vector3<T>(x,y,z); }
// Get quaternion length.
T Length() const { return sqrt(x * x + y * y + z * z + w * w); }
// Get quaternion length squared.
T LengthSq() const { return (x * x + y * y + z * z + w * w); }
// Simple Eulidean distance in R^4 (not SLERP distance, but at least respects Haar measure)
T Distance(const Quat& q) const
{
T d1 = (*this - q).Length();
T d2 = (*this + q).Length(); // Antipoldal point check
return (d1 < d2) ? d1 : d2;
}
T DistanceSq(const Quat& q) const
{
T d1 = (*this - q).LengthSq();
T d2 = (*this + q).LengthSq(); // Antipoldal point check
return (d1 < d2) ? d1 : d2;
}
// Normalize
bool IsNormalized() const { return fabs(LengthSq() - 1) < Math<T>::Tolerance; }
void Normalize() { *this /= Length(); }
Quat Normalized() const { return *this / Length(); }
// Returns conjugate of the quaternion. Produces inverse rotation if quaternion is normalized.
Quat Conj() const { return Quat(-x, -y, -z, w); }
// AnnaSteve fixed: order of quaternion multiplication
// Quaternion multiplication. Combines quaternion rotations, performing the one on the
// right hand side first.
Quat operator* (const Quat& b) const { return Quat(w * b.x + x * b.w + y * b.z - z * b.y,
w * b.y - x * b.z + y * b.w + z * b.x,
w * b.z + x * b.y - y * b.x + z * b.w,
w * b.w - x * b.x - y * b.y - z * b.z); }
//
// this^p normalized; same as rotating by this p times.
Quat PowNormalized(T p) const
{
Vector3<T> v;
T a;
GetAxisAngle(&v, &a);
return Quat(v, a * p);
}
// Rotate transforms vector in a manner that matches Matrix rotations (counter-clockwise,
// assuming negative direction of the axis). Standard formula: q(t) * V * q(t)^-1.
Vector3<T> Rotate(const Vector3<T>& v) const
{
return ((*this * Quat<T>(v.x, v.y, v.z, 0)) * Inverted()).Imag();
}
// Inversed quaternion rotates in the opposite direction.
Quat Inverted() const
{
return Quat(-x, -y, -z, w);
}
// Sets this quaternion to the one rotates in the opposite direction.
void Invert() const
{
*this = Quat(-x, -y, -z, w);
}
// Converting quaternion to matrix.
operator Matrix4f() const
{
T ww = w*w;
T xx = x*x;
T yy = y*y;
T zz = z*z;
return Matrix4f(float(ww + xx - yy - zz), float(T(2) * (x*y - w*z)), float(T(2) * (x*z + w*y)),
float(T(2) * (x*y + w*z)), float(ww - xx + yy - zz), float(T(2) * (y*z - w*x)),
float(T(2) * (x*z - w*y)), float(T(2) * (y*z + w*x)), float(ww - xx - yy + zz) );
}
// GetEulerAngles extracts Euler angles from the quaternion, in the specified order of
// axis rotations and the specified coordinate system. Right-handed coordinate system
// is the default, with CCW rotations while looking in the negative axis direction.
// Here a,b,c, are the Yaw/Pitch/Roll angles to be returned.
// rotation a around axis A1
// is followed by rotation b around axis A2
// is followed by rotation c around axis A3
// rotations are CCW or CW (D) in LH or RH coordinate system (S)
template <Axis A1, Axis A2, Axis A3, RotateDirection D, HandedSystem S>
void GetEulerAngles(T *a, T *b, T *c)
{
OVR_COMPILER_ASSERT((A1 != A2) && (A2 != A3) && (A1 != A3));
T Q[3] = { x, y, z }; //Quaternion components x,y,z
T ww = w*w;
T Q11 = Q[A1]*Q[A1];
T Q22 = Q[A2]*Q[A2];
T Q33 = Q[A3]*Q[A3];
T psign = T(-1.0);
// Determine whether even permutation
if (((A1 + 1) % 3 == A2) && ((A2 + 1) % 3 == A3))
psign = T(1.0);
T s2 = psign * T(2.0) * (psign*w*Q[A2] + Q[A1]*Q[A3]);
if (s2 < (T)-1.0 + Math<T>::SingularityRadius)
{ // South pole singularity
*a = T(0.0);
*b = -S*D*Math<T>::PiOver2;
*c = S*D*atan2((T)2.0*(psign*Q[A1]*Q[A2] + w*Q[A3]),
ww + Q22 - Q11 - Q33 );
}
else if (s2 > (T)1.0 - Math<T>::SingularityRadius)
{ // North pole singularity
*a = (T)0.0;
*b = S*D*Math<T>::PiOver2;
*c = S*D*atan2((T)2.0*(psign*Q[A1]*Q[A2] + w*Q[A3]),
ww + Q22 - Q11 - Q33);
}
else
{
*a = -S*D*atan2((T)-2.0*(w*Q[A1] - psign*Q[A2]*Q[A3]),
ww + Q33 - Q11 - Q22);
*b = S*D*asin(s2);
*c = S*D*atan2((T)2.0*(w*Q[A3] - psign*Q[A1]*Q[A2]),
ww + Q11 - Q22 - Q33);
}
return;
}
template <Axis A1, Axis A2, Axis A3, RotateDirection D>
void GetEulerAngles(T *a, T *b, T *c)
{ GetEulerAngles<A1, A2, A3, D, Handed_R>(a, b, c); }
template <Axis A1, Axis A2, Axis A3>
void GetEulerAngles(T *a, T *b, T *c)
{ GetEulerAngles<A1, A2, A3, Rotate_CCW, Handed_R>(a, b, c); }
// GetEulerAnglesABA extracts Euler angles from the quaternion, in the specified order of
// axis rotations and the specified coordinate system. Right-handed coordinate system
// is the default, with CCW rotations while looking in the negative axis direction.
// Here a,b,c, are the Yaw/Pitch/Roll angles to be returned.
// rotation a around axis A1
// is followed by rotation b around axis A2
// is followed by rotation c around axis A1
// Rotations are CCW or CW (D) in LH or RH coordinate system (S)
template <Axis A1, Axis A2, RotateDirection D, HandedSystem S>
void GetEulerAnglesABA(T *a, T *b, T *c)
{
OVR_COMPILER_ASSERT(A1 != A2);
T Q[3] = {x, y, z}; // Quaternion components
// Determine the missing axis that was not supplied
int m = 3 - A1 - A2;
T ww = w*w;
T Q11 = Q[A1]*Q[A1];
T Q22 = Q[A2]*Q[A2];
T Qmm = Q[m]*Q[m];
T psign = T(-1.0);
if ((A1 + 1) % 3 == A2) // Determine whether even permutation
{
psign = (T)1.0;
}
T c2 = ww + Q11 - Q22 - Qmm;
if (c2 < (T)-1.0 + Math<T>::SingularityRadius)
{ // South pole singularity
*a = (T)0.0;
*b = S*D*Math<T>::Pi;
*c = S*D*atan2( (T)2.0*(w*Q[A1] - psign*Q[A2]*Q[m]),
ww + Q22 - Q11 - Qmm);
}
else if (c2 > (T)1.0 - Math<T>::SingularityRadius)
{ // North pole singularity
*a = (T)0.0;
*b = (T)0.0;
*c = S*D*atan2( (T)2.0*(w*Q[A1] - psign*Q[A2]*Q[m]),
ww + Q22 - Q11 - Qmm);
}
else
{
*a = S*D*atan2( psign*w*Q[m] + Q[A1]*Q[A2],
w*Q[A2] -psign*Q[A1]*Q[m]);
*b = S*D*acos(c2);
*c = S*D*atan2( -psign*w*Q[m] + Q[A1]*Q[A2],
w*Q[A2] + psign*Q[A1]*Q[m]);
}
return;
}
};
typedef Quat<float> Quatf;
typedef Quat<double> Quatd;
//-------------------------------------------------------------------------------------
// ***** Plane
// Consists of a normal vector and distance from the origin where the plane is located.
template<class T>
class Plane : public RefCountBase<Plane<T> >
{
public:
Vector3<T> N;
T D;
Plane() : D(0) {}
// Normals must already be normalized
Plane(const Vector3<T>& n, T d) : N(n), D(d) {}
Plane(T x, T y, T z, T d) : N(x,y,z), D(d) {}
// construct from a point on the plane and the normal
Plane(const Vector3<T>& p, const Vector3<T>& n) : N(n), D(-(p * n)) {}
// Find the point to plane distance. The sign indicates what side of the plane the point is on (0 = point on plane).
T TestSide(const Vector3<T>& p) const
{
return (N * p) + D;
}
Plane<T> Flipped() const
{
return Plane(-N, -D);
}
void Flip()
{
N = -N;
D = -D;
}
bool operator==(const Plane<T>& rhs) const
{
return (this->D == rhs.D && this->N == rhs.N);
}
};
typedef Plane<float> Planef;
}
#endif
| StellaArtois/JRift | JRiftLibrary/LibOVR/Src/Kernel/OVR_Math.h | C | mit | 39,173 |
package main
import (
"fmt"
"time"
"github.com/kevinburke/rct/genetic"
)
func main() {
files := genetic.GetOldFiles(1 * time.Hour)
for _, file := range files {
fmt.Println(file)
}
}
| kevinburke/rct | genetic/get_old_experiments/main.go | GO | mit | 193 |
using System;
namespace SampleWebAPIApp.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Describes a type model.
/// </summary>
public abstract class ModelDescription
{
public string Documentation { get; set; }
public Type ModelType { get; set; }
public string Name { get; set; }
}
} | adzhazhev/ASP.NET-Web-Forms | 01. Introduction-to-ASP.NET/01. Sample-ASP.NET-Apps/SampleWebAPIApp/Areas/HelpPage/ModelDescriptions/ModelDescription.cs | C# | mit | 338 |
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include <miopen/rnn.hpp>
#include <miopen/rnn_util.hpp>
#include <miopen/activ.hpp>
#include <miopen/env.hpp>
#include <miopen/gemm_v2.hpp>
#include <miopen/logger.hpp>
#include <vector>
#include <numeric>
#include <algorithm>
namespace miopen {
// Assuming sequence length is set to > 0 otherwise throw exception.
void RNNDescriptor::RNNForwardInference(Handle& handle,
const int seqLen,
c_array_view<const miopenTensorDescriptor_t> xDesc,
ConstData_t x,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& cxDesc,
ConstData_t cx,
const TensorDescriptor& wDesc,
ConstData_t w,
c_array_view<const miopenTensorDescriptor_t> yDesc,
Data_t y,
const TensorDescriptor& hyDesc,
Data_t hy,
const TensorDescriptor& cyDesc,
Data_t cy,
Data_t workSpace,
size_t workSpaceSize) const
{
if(x == nullptr || w == nullptr || y == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(hxDesc.GetSize() != cxDesc.GetSize() || hxDesc.GetSize() != hyDesc.GetSize() ||
hxDesc.GetSize() != cyDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(workSpaceSize < GetWorkspaceSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Workspace is required");
}
std::string network_config;
std::vector<int> in_n;
int in_h = xDesc[0].GetLengths()[1]; // input vector size
int hy_d = hyDesc.GetLengths()[0]; // biNumLayers
int hy_n = hyDesc.GetLengths()[1]; // max batch size
int hy_h = hyDesc.GetLengths()[2]; // hidden size
int out_h = yDesc[0].GetLengths()[1]; // output vector size
if(in_h <= 0 || hy_h <= 0 || hy_n <= 0 || hy_d <= 0 || out_h <= 0 || seqLen <= 0)
{
MIOPEN_THROW(miopenStatusBadParm);
}
int batch_n = 0;
for(int i = 0; i < seqLen; i++)
{
int batchval, inputvec, batchvalout, outputvec;
std::tie(batchval, inputvec) = miopen::tien<2>(xDesc[i].GetLengths());
std::tie(batchvalout, outputvec) = miopen::tien<2>(yDesc[i].GetLengths());
if(batchval != batchvalout)
{
MIOPEN_THROW(miopenStatusBadParm,
"Input batch length: " + std::to_string(batchval) +
", Output batch length: " + std::to_string(batchvalout));
}
if(i == 0)
{
if(batchval <= 0)
{
MIOPEN_THROW(miopenStatusBadParm, "Input batch is ZERO!");
}
}
else
{
if(batchval > in_n.back() || batchval < 0)
{
MIOPEN_THROW(miopenStatusBadParm,
"Incorrect input batch size at time " + std::to_string(i) +
"! Batch size must not ascend!");
}
}
in_n.push_back(batchval);
batch_n += batchval;
}
int bi = dirMode != 0u ? 2 : 1;
if(out_h != (bi * hy_h))
{
MIOPEN_THROW(miopenStatusBadParm, "Output size doesn't match hidden state size!");
}
float ctime = 0.;
int in_stride = in_h;
int hy_stride = hy_h * bi * static_cast<int>(workspaceScale);
int out_stride = out_h;
int wei_stride = hy_h * bi * static_cast<int>(nHiddenTensorsPerLayer);
int uni_stride = hy_h;
int bi_stride = hy_h * bi;
if(inputMode == miopenRNNskip)
{
if(in_h != hy_h)
{
MIOPEN_THROW(miopenStatusBadParm,
"The input tensor size must equal to the hidden "
"state size of the network in SKIP_INPUT mode!");
}
in_h = 0;
}
size_t wei_shift_bias = (in_h + hy_h + (bi * hy_h + hy_h) * (nLayers - 1)) * wei_stride;
size_t offset;
float alpha0, alpha1, beta_t;
float alpha = 1, beta = 0;
std::vector<int> sp_size(3, 1), sp_stride(3, 1), w_size(3, 1), w_stride(3, 1), x_size(3, 1),
x_stride(3, 1), y_size(3, 1), y_stride(3, 1), hx_size(3, 1), hx_stride(3, 1);
miopen::TensorDescriptor sp_desc, w_desc, x_desc, y_desc, hx_desc;
sp_size[2] = workSpaceSize / GetTypeSize(wDesc.GetType());
sp_stride[0] = sp_size[2];
sp_stride[1] = sp_size[2];
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
SetTensor(handle, sp_desc, workSpace, &beta);
// Update time
profileRNNkernels(handle, 0, ctime);
sp_stride[0] = batch_n * hy_stride;
sp_stride[1] = hy_stride;
sp_size[2] = 1;
w_stride[0] = wei_stride;
w_stride[1] = wei_stride;
x_stride[0] = batch_n * in_stride;
x_stride[1] = in_stride;
y_stride[0] = batch_n * out_stride;
y_stride[1] = out_stride;
if(hy != nullptr || (rnnMode == miopenLSTM && cy != nullptr))
{
hx_size[2] = hy_d * hy_n * hy_h;
hx_stride[0] = hx_size[2];
hx_stride[1] = hx_size[2];
hx_desc = miopen::TensorDescriptor(wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(hy != nullptr)
{
SetTensor(handle, hx_desc, hy, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && cy != nullptr)
{
SetTensor(handle, hx_desc, cy, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
hx_stride[0] = in_n.at(0) * uni_stride;
hx_stride[1] = uni_stride;
#if MIOPEN_USE_GEMM
int wei_shift, prelayer_shift;
int wei_len = 0;
int hid_off = 0;
switch(rnnMode)
{
case miopenRNNRELU:
case miopenRNNTANH:
// printf("run rnn gpu inference \n");
wei_len = hy_h;
hid_off = 0;
break;
case miopenLSTM:
// printf("run lstm gpu inference \n");
wei_len = hy_h * 4;
hid_off = bi * hy_h * 5;
break;
case miopenGRU:
// printf("run gru gpu inference \n");
wei_len = hy_h * 3;
hid_off = bi * hy_h * 3;
break;
}
ActivationDescriptor tanhDesc, sigDesc, activDesc;
sigDesc = {miopenActivationLOGISTIC, 1, 0, 1};
tanhDesc = {miopenActivationTANH, 1, 1, 1};
if(rnnMode == miopenRNNRELU)
{
activDesc = {miopenActivationRELU, 1, 0, 1};
}
else if(rnnMode == miopenRNNTANH)
{
activDesc = {miopenActivationTANH, 1, 1, 1};
}
for(int li = 0; li < nLayers; li++)
{
int hid_shift = li * batch_n * hy_stride;
int hx_shift = li * hy_n * bi_stride;
int wei_shift_bias_temp = static_cast<int>(wei_shift_bias) + li * 2 * wei_stride;
// from input
if(li == 0)
{
if(inputMode == miopenRNNskip)
{
x_size[1] = batch_n;
x_size[2] = hy_h;
sp_size[1] = batch_n;
sp_size[2] = hy_h;
x_desc =
miopen::TensorDescriptor(wDesc.GetType(), x_size.data(), x_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
for(int gi = 0; gi < nHiddenTensorsPerLayer * bi; gi++)
{
CopyTensor(handle, x_desc, x, sp_desc, workSpace, 0, gi * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
batch_n,
wei_len * bi,
in_h,
in_stride,
in_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
x,
0,
w,
0,
workSpace,
hid_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
wei_shift = (in_h + hy_h) * wei_stride + (li - 1) * (bi * hy_h + hy_h) * wei_stride;
prelayer_shift = (li - 1) * batch_n * hy_stride + hid_off;
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
batch_n,
wei_len * bi,
hy_h * bi,
hy_stride,
bi_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
prelayer_shift,
w,
wei_shift,
workSpace,
hid_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(biasMode != 0u)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
w_size[1] = 1;
w_size[2] = wei_stride;
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
w_desc = miopen::TensorDescriptor(wDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
hid_shift,
wei_shift_bias_temp,
hid_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenGRU)
{
sp_size[1] = batch_n;
sp_size[2] = hy_h;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 0;
alpha1 = 0;
beta_t = 0;
for(int bs = 0; bs < bi; bs++)
{
CopyTensor(handle,
sp_desc,
workSpace,
sp_desc,
workSpace,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + hid_off + bs * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + bs * wei_len + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
if(biasMode != 0u)
{
wei_shift_bias_temp += wei_stride;
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
if(hx != nullptr)
{
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
hid_shift,
wei_shift_bias_temp,
hid_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
sp_size[1] = batch_n - in_n.at(0);
sp_size[2] = wei_len;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
w_size[1] = 1;
w_size[2] = wei_len;
w_desc =
miopen::TensorDescriptor(wDesc.GetType(), w_size.data(), w_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
hid_shift + in_n.at(0) * hy_stride,
wei_shift_bias_temp,
hid_shift + in_n.at(0) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
if(dirMode != 0u)
{
if(in_n.at(0) == in_n.at(seqLen - 1))
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
hid_shift + wei_len,
wei_shift_bias_temp + wei_len,
hid_shift + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
int cur_batch = 0;
for(int ti = 0; ti < seqLen; ti++)
{
if(ti != (seqLen - 1))
{
offset = hid_shift + cur_batch * hy_stride;
sp_size[1] = in_n.at(ti + 1);
sp_size[2] = wei_len;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
offset + wei_len,
wei_shift_bias_temp + wei_len,
offset + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
cur_batch += in_n.at(ti);
}
}
}
}
}
// from hidden state
int bacc = 0;
int baccbi = batch_n;
for(int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n.at(seqLen - 1 - ti);
wei_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
int pretime_shift = 0;
int use_time = 0;
for(int ri = 0; ri < bi; ri++)
{
int cur_time = ri == 0 ? ti : seqLen - 1 - ti;
int cur_batch = ri == 0 ? bacc : baccbi;
offset = hid_shift + cur_batch * hy_stride;
if(ti > 0)
{
pretime_shift =
ri == 0 ? hid_shift + (bacc - in_n.at(ti - 1)) * hy_stride
: hid_shift + (baccbi + in_n.at(seqLen - 1 - ti)) * hy_stride;
use_time = ri == 0 ? ti : seqLen - ti;
}
if(in_n.at(cur_time) > 0)
{
if(ti == 0)
{
if(hx != nullptr)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
in_n.at(cur_time),
wei_len,
hy_h,
uni_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
hx,
hx_shift + ri * hy_n * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
workSpace,
static_cast<int>(offset) + ri * wei_len,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
false,
true,
(in_n.at(cur_time) - in_n.at(use_time)),
wei_len,
hy_h,
uni_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
hx,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
workSpace,
static_cast<int>(offset) + ri * wei_len +
in_n.at(use_time) * hy_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(in_n.at(use_time) > 0)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
in_n.at(use_time),
wei_len,
hy_h,
hy_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
pretime_shift + hid_off + ri * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
workSpace,
static_cast<int>(offset) + ri * wei_len,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
// update hidden status
sp_size[1] = in_n.at(cur_time);
if(rnnMode == miopenRNNRELU || rnnMode == miopenRNNTANH)
{
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
activDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenLSTM)
{
if(algoMode == miopenRNNdefault)
{
LSTMForwardHiddenStateUpdate(handle,
wDesc.GetType(),
true,
ti == 0,
ri,
in_n.at(0),
in_n.at(cur_time),
in_n.at(use_time),
hy_h,
hy_stride,
wei_len,
wei_stride,
cx,
hx_shift + ri * hy_n * hy_h,
workSpace,
offset + ri * wei_len,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + bi * wei_len + ri * hy_h,
pretime_shift + bi * wei_len + ri * hy_h,
0,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
continue;
}
// active gate i, f, o
sp_size[2] = hy_h * 3;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// active gate c
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
tanhDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + 3 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// update cell state
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(ti == 0)
{
if(cx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
workSpace,
offset + hy_h + ri * wei_len,
hx_shift + ri * hy_n * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && cx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
workSpace,
offset + hy_h + ri * wei_len +
in_n.at(use_time) * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time) > 0)
{
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + hy_h + ri * wei_len,
pretime_shift + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
}
// active cell state
tanhDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
// update hidden state
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenGRU)
{
// active z, r gate
sp_size[2] = 2 * hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// calculate c gate
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// active c gate
tanhDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// calculate hidden state
alpha0 = -1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
if(ti == 0)
{
if(hx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
hx,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len,
hx_shift + ri * hy_n * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
hx,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len + in_n.at(use_time) * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + hid_off + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time) > 0)
{
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len,
pretime_shift + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
}
}
bacc += in_n.at(ti);
}
// update hy, cy
if(hy != nullptr || (rnnMode == miopenLSTM && cy != nullptr))
{
hx_size[2] = hy_h;
sp_size[2] = hy_h;
bacc = batch_n;
baccbi = 0;
for(int ti = seqLen - 1; ti >= 0; ti--)
{
bacc -= in_n.at(ti);
for(int ri = 0; ri < bi; ri++)
{
int cur_time = ri == 0 ? ti : seqLen - 1 - ti;
int cur_batch = ri == 0 ? bacc : baccbi;
int use_batch = 0;
if(ti < seqLen - 1)
{
int use_time = ri == 0 ? ti + 1 : seqLen - 2 - ti;
use_batch = in_n.at(use_time);
}
if(in_n.at(cur_time) > use_batch)
{
offset = hid_shift + cur_batch * hy_stride;
sp_size[1] = in_n.at(cur_time) - use_batch;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
hx_size[1] = sp_size[1];
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(hy != nullptr)
{
CopyTensor(handle,
sp_desc,
workSpace,
hx_desc,
hy,
static_cast<int>(offset) + hid_off + ri * hy_h +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && cy != nullptr)
{
CopyTensor(handle,
sp_desc,
workSpace,
hx_desc,
cy,
static_cast<int>(offset) + bi * wei_len + ri * hy_h +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
baccbi += in_n.at(seqLen - 1 - ti);
}
}
}
// output
prelayer_shift = (static_cast<int>(nLayers) - 1) * batch_n * hy_stride + hid_off;
sp_size[1] = batch_n;
sp_size[2] = hy_h * bi;
y_size[1] = batch_n;
y_size[2] = out_h;
y_desc = miopen::TensorDescriptor(wDesc.GetType(), y_size.data(), y_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
CopyTensor(handle, sp_desc, workSpace, y_desc, y, prelayer_shift, 0);
// Update time
profileRNNkernels(handle, 2, ctime);
#else
(void)hx;
(void)cx;
(void)offset;
(void)alpha0;
(void)alpha1;
(void)beta_t;
(void)alpha;
(void)bi_stride;
(void)wei_shift_bias;
MIOPEN_THROW("GEMM is not supported");
#endif
}
void RNNDescriptor::RNNForwardTraining(Handle& handle,
const int seqLen,
c_array_view<const miopenTensorDescriptor_t> xDesc,
ConstData_t x,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& cxDesc,
ConstData_t cx,
const TensorDescriptor& wDesc,
ConstData_t w,
c_array_view<const miopenTensorDescriptor_t> yDesc,
Data_t y,
const TensorDescriptor& hyDesc,
Data_t hy,
const TensorDescriptor& cyDesc,
Data_t cy,
Data_t workSpace,
size_t workSpaceSize,
Data_t reserveSpace,
size_t reserveSpaceSize) const
{
(void)workSpace;
if(x == nullptr || w == nullptr || y == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(hxDesc.GetSize() != cxDesc.GetSize() || hxDesc.GetSize() != hyDesc.GetSize() ||
hxDesc.GetSize() != cyDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(workSpaceSize < GetWorkspaceSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Workspace is required");
}
if(reserveSpaceSize < GetReserveSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Reservespace is required");
}
std::string network_config;
std::vector<int> in_n;
int in_h = xDesc[0].GetLengths()[1]; // input vector size
int hy_d = hyDesc.GetLengths()[0]; // biNumLayers
int hy_n = hyDesc.GetLengths()[1]; // max batch size
int hy_h = hyDesc.GetLengths()[2]; // hidden size
int out_h = yDesc[0].GetLengths()[1]; // output vector size
if(in_h <= 0 || hy_h <= 0 || hy_n <= 0 || hy_d <= 0 || out_h <= 0 || seqLen <= 0)
{
MIOPEN_THROW(miopenStatusBadParm);
}
int batch_n = 0;
for(int i = 0; i < seqLen; i++)
{
int batchval, inputvec, batchvalout, outputvec;
std::tie(batchval, inputvec) = miopen::tien<2>(xDesc[i].GetLengths());
std::tie(batchvalout, outputvec) = miopen::tien<2>(yDesc[i].GetLengths());
if(batchval != batchvalout)
{
MIOPEN_THROW(miopenStatusBadParm,
"Input batch length: " + std::to_string(batchval) +
", Output batch length: " + std::to_string(batchvalout));
}
if(i == 0)
{
if(batchval <= 0)
{
MIOPEN_THROW(miopenStatusBadParm, "Input batch is ZERO!");
}
}
else
{
if(batchval > in_n.back() || batchval < 0)
{
MIOPEN_THROW(miopenStatusBadParm,
"Incorrect input batch size at time " + std::to_string(i) +
"! Batch size must not ascend!");
}
}
in_n.push_back(batchval);
batch_n += batchval;
}
int bi = dirMode != 0u ? 2 : 1;
if(out_h != (bi * hy_h))
{
MIOPEN_THROW(miopenStatusBadParm, "Output size doesn't match hidden state size!");
}
float ctime = 0.;
int in_stride = in_h;
int hy_stride = hy_h * bi * static_cast<int>(workspaceScale);
int out_stride = out_h;
int wei_stride = hy_h * bi * static_cast<int>(nHiddenTensorsPerLayer);
int uni_stride = hy_h;
int bi_stride = hy_h * bi;
if(inputMode == miopenRNNskip)
{
if(in_h != hy_h)
{
MIOPEN_THROW(miopenStatusBadParm,
"The input tensor size must equal to the hidden "
"state size of the network in SKIP_INPUT mode!");
}
in_h = 0;
}
size_t wei_shift_bias = (in_h + hy_h + (bi * hy_h + hy_h) * (nLayers - 1)) * wei_stride;
size_t offset;
float alpha0, alpha1, beta_t;
float alpha = 1, beta = 0;
std::vector<int> sp_size(3, 1), sp_stride(3, 1), w_size(3, 1), w_stride(3, 1), x_size(3, 1),
x_stride(3, 1), y_size(3, 1), y_stride(3, 1), hx_size(3, 1), hx_stride(3, 1);
miopen::TensorDescriptor sp_desc, w_desc, x_desc, y_desc, hx_desc;
sp_size[2] = reserveSpaceSize / GetTypeSize(wDesc.GetType());
sp_stride[0] = sp_size[2];
sp_stride[1] = sp_size[2];
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
SetTensor(handle, sp_desc, reserveSpace, &beta);
// Update time
profileRNNkernels(handle, 0, ctime);
sp_stride[0] = batch_n * hy_stride;
sp_stride[1] = hy_stride;
sp_size[2] = 1;
w_stride[0] = wei_stride;
w_stride[1] = wei_stride;
x_stride[0] = batch_n * in_stride;
x_stride[1] = in_stride;
y_stride[0] = batch_n * out_stride;
y_stride[1] = out_stride;
if(hy != nullptr || (rnnMode == miopenLSTM && cy != nullptr))
{
hx_size[2] = hy_d * hy_n * hy_h;
hx_stride[0] = hx_size[2];
hx_stride[1] = hx_size[2];
hx_desc = miopen::TensorDescriptor(wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(hy != nullptr)
{
SetTensor(handle, hx_desc, hy, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && cy != nullptr)
{
SetTensor(handle, hx_desc, cy, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
hx_stride[0] = in_n.at(0) * uni_stride;
hx_stride[1] = uni_stride;
#if MIOPEN_USE_GEMM
int wei_shift, prelayer_shift;
int wei_len = 0;
int hid_off = 0;
switch(rnnMode)
{
case miopenRNNRELU:
case miopenRNNTANH:
// printf("run rnn gpu fwd \n");
wei_len = hy_h;
hid_off = static_cast<int>(nLayers) * batch_n * hy_stride;
break;
case miopenLSTM:
// printf("run lstm gpu fwd \n");
wei_len = hy_h * 4;
hid_off = bi * hy_h * 5;
break;
case miopenGRU:
// printf("run gru gpu fwd \n");
wei_len = hy_h * 3;
hid_off = bi * hy_h * 3;
break;
}
ActivationDescriptor tanhDesc, sigDesc, activDesc;
sigDesc = {miopenActivationLOGISTIC, 1, 0, 1};
tanhDesc = {miopenActivationTANH, 1, 1, 1};
if(rnnMode == miopenRNNRELU)
{
activDesc = {miopenActivationRELU, 1, 0, 1};
}
else if(rnnMode == miopenRNNTANH)
{
activDesc = {miopenActivationTANH, 1, 1, 1};
}
for(int li = 0; li < nLayers; li++)
{
int hid_shift = li * batch_n * hy_stride;
int hx_shift = li * hy_n * bi_stride;
int wei_shift_bias_temp = static_cast<int>(wei_shift_bias) + li * 2 * wei_stride;
// from input
if(li == 0)
{
if(inputMode == miopenRNNskip)
{
x_size[1] = batch_n;
x_size[2] = hy_h;
sp_size[1] = batch_n;
sp_size[2] = hy_h;
x_desc =
miopen::TensorDescriptor(wDesc.GetType(), x_size.data(), x_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
for(int gi = 0; gi < nHiddenTensorsPerLayer * bi; gi++)
{
CopyTensor(handle, x_desc, x, sp_desc, reserveSpace, 0, gi * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
batch_n,
wei_len * bi,
in_h,
in_stride,
in_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
x,
0,
w,
0,
reserveSpace,
hid_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
wei_shift = (in_h + hy_h) * wei_stride + (li - 1) * (bi * hy_h + hy_h) * wei_stride;
prelayer_shift = (li - 1) * batch_n * hy_stride + hid_off;
bool use_dropout = !float_equal(miopen::deref(dropoutDesc).dropout, 0);
if(use_dropout)
{
std::vector<int> drop_size(2), drop_in_str(2, 1), drop_out_str(2, 1);
drop_size[0] = batch_n;
drop_size[1] = hy_h * bi;
drop_in_str[0] = hy_stride;
drop_out_str[0] = hy_h * bi;
auto drop_in_desc = miopen::TensorDescriptor(
wDesc.GetType(), drop_size.data(), drop_in_str.data(), 2);
auto drop_out_desc = miopen::TensorDescriptor(
wDesc.GetType(), drop_size.data(), drop_out_str.data(), 2);
size_t drop_rsv_size = drop_out_desc.GetElementSize();
size_t drop_rsv_start =
algoMode == miopenRNNdefault && rnnMode == miopenLSTM
? nLayers * batch_n * hy_stride + nLayers * batch_n * hy_h * bi
: 2 * nLayers * batch_n * hy_stride;
size_t drop_in_offset = prelayer_shift;
size_t drop_out_offset = drop_rsv_start + (li - 1) * batch_n * hy_h * bi;
size_t drop_rsv_offset = (drop_rsv_start + (nLayers - 1) * batch_n * hy_h * bi) *
(wDesc.GetType() == miopenFloat ? 4 : 2) +
(li - 1) * drop_rsv_size;
miopen::deref(dropoutDesc)
.DropoutForward(handle,
drop_in_desc,
drop_in_desc,
reserveSpace,
drop_out_desc,
reserveSpace,
reserveSpace,
drop_rsv_size,
drop_in_offset,
drop_out_offset,
drop_rsv_offset);
// Update time
profileRNNkernels(handle, 1, ctime);
prelayer_shift = drop_out_offset;
}
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
batch_n,
wei_len * bi,
hy_h * bi,
use_dropout ? hy_h * bi : hy_stride,
bi_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
reserveSpace,
prelayer_shift,
w,
wei_shift,
reserveSpace,
hid_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(biasMode != 0u)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
w_size[1] = 1;
w_size[2] = wei_stride;
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
w_desc = miopen::TensorDescriptor(wDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
hid_shift,
wei_shift_bias_temp,
hid_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenGRU)
{
sp_size[1] = batch_n;
sp_size[2] = hy_h;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 0;
alpha1 = 0;
beta_t = 0;
for(int bs = 0; bs < bi; bs++)
{
CopyTensor(handle,
sp_desc,
reserveSpace,
sp_desc,
reserveSpace,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + hid_off + bs * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + bs * wei_len + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
if(biasMode != 0u)
{
wei_shift_bias_temp += wei_stride;
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
if(hx != nullptr)
{
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
hid_shift,
wei_shift_bias_temp,
hid_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
sp_size[1] = batch_n - in_n.at(0);
sp_size[2] = wei_len;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
w_size[1] = 1;
w_size[2] = wei_len;
w_desc =
miopen::TensorDescriptor(wDesc.GetType(), w_size.data(), w_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
hid_shift + in_n.at(0) * hy_stride,
wei_shift_bias_temp,
hid_shift + in_n.at(0) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
if(dirMode != 0u)
{
if(in_n.at(0) == in_n.at(seqLen - 1))
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
hid_shift + wei_len,
wei_shift_bias_temp + wei_len,
hid_shift + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
int cur_batch = 0;
for(int ti = 0; ti < seqLen; ti++)
{
if(ti != (seqLen - 1))
{
offset = hid_shift + cur_batch * hy_stride;
sp_size[1] = in_n.at(ti + 1);
sp_size[2] = wei_len;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
static_cast<int>(offset) + wei_len,
wei_shift_bias_temp + wei_len,
static_cast<int>(offset) + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
cur_batch += in_n.at(ti);
}
}
}
}
}
// from hidden state
int bacc = 0;
int baccbi = batch_n;
for(int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n.at(seqLen - 1 - ti);
wei_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
int pretime_shift = 0;
int use_time = 0;
for(int ri = 0; ri < bi; ri++)
{
int cur_time = ri == 0 ? ti : seqLen - 1 - ti;
int cur_batch = ri == 0 ? bacc : baccbi;
offset = hid_shift + cur_batch * hy_stride;
if(ti > 0)
{
pretime_shift =
ri == 0 ? hid_shift + (bacc - in_n.at(ti - 1)) * hy_stride
: hid_shift + (baccbi + in_n.at(seqLen - 1 - ti)) * hy_stride;
use_time = ri == 0 ? ti : seqLen - ti;
}
if(in_n.at(cur_time) > 0)
{
if(ti == 0)
{
if(hx != nullptr)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
in_n.at(cur_time),
wei_len,
hy_h,
uni_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
hx,
hx_shift + ri * hy_n * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
reserveSpace,
static_cast<int>(offset) + ri * wei_len,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
false,
true,
(in_n.at(cur_time) - in_n.at(use_time)),
wei_len,
hy_h,
uni_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
hx,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
reserveSpace,
static_cast<int>(offset) + ri * wei_len +
in_n.at(use_time) * hy_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(in_n.at(use_time) > 0)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
in_n.at(use_time),
wei_len,
hy_h,
hy_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
reserveSpace,
pretime_shift + hid_off + ri * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
reserveSpace,
static_cast<int>(offset) + ri * wei_len,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
// update hidden status
sp_size[1] = in_n.at(cur_time);
if(rnnMode == miopenRNNRELU || rnnMode == miopenRNNTANH)
{
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
activDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + ri * wei_len,
offset + ri * wei_len + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenLSTM)
{
if(algoMode == miopenRNNdefault)
{
LSTMForwardHiddenStateUpdate(handle,
wDesc.GetType(),
false,
ti == 0,
ri,
in_n.at(0),
in_n.at(cur_time),
in_n.at(use_time),
hy_h,
hy_stride,
wei_len,
wei_stride,
cx,
hx_shift + ri * hy_n * hy_h,
reserveSpace,
offset + ri * wei_len,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + bi * wei_len + ri * hy_h,
pretime_shift + bi * wei_len + ri * hy_h,
(li * batch_n + cur_batch) * bi * hy_h +
ri * hy_h +
nLayers * batch_n * hy_stride,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
continue;
}
// active gate i, f, o
sp_size[2] = hy_h * 3;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + ri * wei_len,
offset + ri * wei_len + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// active gate c
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
tanhDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + 3 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len +
nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// update cell state
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 3 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(ti == 0)
{
if(cx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
reserveSpace,
offset + hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && cx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
reserveSpace,
offset + hy_h + ri * wei_len +
in_n.at(use_time) * hy_stride +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time) > 0)
{
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
pretime_shift + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
}
// active cell state
tanhDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h +
nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// update hidden state
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h + nLayers * batch_n * hy_stride,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenGRU)
{
// active z, r gate
sp_size[2] = 2 * hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + ri * wei_len,
offset + ri * wei_len + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// calculate c gate
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
CopyTensor(handle,
sp_desc,
reserveSpace,
sp_desc,
reserveSpace,
static_cast<int>(offset) + 2 * hy_h + ri * wei_len,
static_cast<int>(offset) + hid_off + ri * hy_h +
static_cast<int>(nLayers) * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// active c gate
tanhDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len +
nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// calculate hidden state
alpha0 = -1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
if(ti == 0)
{
if(hx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
hx_desc,
hx,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
hx_desc,
hx,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + in_n.at(use_time) * hy_stride +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + hid_off + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time) > 0)
{
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
pretime_shift + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
}
}
bacc += in_n.at(ti);
}
// update hy, cy
if(hy != nullptr || (rnnMode == miopenLSTM && cy != nullptr))
{
hx_size[2] = hy_h;
sp_size[2] = hy_h;
bacc = batch_n;
baccbi = 0;
for(int ti = seqLen - 1; ti >= 0; ti--)
{
bacc -= in_n.at(ti);
for(int ri = 0; ri < bi; ri++)
{
int cur_time = ri == 0 ? ti : seqLen - 1 - ti;
int cur_batch = ri == 0 ? bacc : baccbi;
int use_batch = 0;
if(ti < seqLen - 1)
{
int use_time = ri == 0 ? ti + 1 : seqLen - 2 - ti;
use_batch = in_n.at(use_time);
}
if(in_n.at(cur_time) > use_batch)
{
offset = hid_shift + cur_batch * hy_stride;
sp_size[1] = in_n.at(cur_time) - use_batch;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
hx_size[1] = sp_size[1];
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(hy != nullptr)
{
CopyTensor(handle,
sp_desc,
reserveSpace,
hx_desc,
hy,
static_cast<int>(offset) + hid_off + ri * hy_h +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && cy != nullptr)
{
CopyTensor(handle,
sp_desc,
reserveSpace,
hx_desc,
cy,
static_cast<int>(offset) + bi * wei_len + ri * hy_h +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
baccbi += in_n.at(seqLen - 1 - ti);
}
}
}
// output
prelayer_shift = (static_cast<int>(nLayers) - 1) * batch_n * hy_stride + hid_off;
sp_size[1] = batch_n;
sp_size[2] = hy_h * bi;
y_size[1] = batch_n;
y_size[2] = out_h;
y_desc = miopen::TensorDescriptor(wDesc.GetType(), y_size.data(), y_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
CopyTensor(handle, sp_desc, reserveSpace, y_desc, y, prelayer_shift, 0);
// Update time
profileRNNkernels(handle, 2, ctime);
#else
(void)bi_stride;
(void)alpha;
(void)offset;
(void)alpha0;
(void)alpha1;
(void)beta_t;
(void)hx;
(void)cx;
(void)wei_shift_bias;
MIOPEN_THROW("GEMM is not supported");
#endif
};
void RNNDescriptor::RNNBackwardData(Handle& handle,
const int seqLen,
c_array_view<const miopenTensorDescriptor_t> yDesc,
ConstData_t y,
c_array_view<const miopenTensorDescriptor_t> dyDesc,
ConstData_t dy,
const TensorDescriptor& dhyDesc,
ConstData_t dhy,
const TensorDescriptor& dcyDesc,
ConstData_t dcy,
const TensorDescriptor& wDesc,
ConstData_t w,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& cxDesc,
ConstData_t cx,
c_array_view<const miopenTensorDescriptor_t> dxDesc,
Data_t dx,
const TensorDescriptor& dhxDesc,
Data_t dhx,
const TensorDescriptor& dcxDesc,
Data_t dcx,
Data_t workSpace,
size_t workSpaceSize,
Data_t reserveSpace,
size_t reserveSpaceSize) const
{
// Suppress warning
(void)y;
(void)yDesc;
(void)hxDesc;
(void)cxDesc;
(void)dcxDesc;
(void)dcyDesc;
(void)dhyDesc;
(void)wDesc;
if(dx == nullptr || w == nullptr || dy == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(dhyDesc.GetSize() != dcyDesc.GetSize() || dhyDesc.GetSize() != hxDesc.GetSize() ||
dhyDesc.GetSize() != cxDesc.GetSize() || dhyDesc.GetSize() != dhxDesc.GetSize() ||
dhyDesc.GetSize() != dcxDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(workSpaceSize < GetWorkspaceSize(handle, seqLen, dxDesc))
{
MIOPEN_THROW("Workspace is required");
}
if(reserveSpaceSize < GetReserveSize(handle, seqLen, dxDesc))
{
MIOPEN_THROW("Reservespace is required");
}
std::vector<int> in_n;
int in_h = dxDesc[0].GetLengths()[1];
int hy_d = dhxDesc.GetLengths()[0];
int hy_n = dhxDesc.GetLengths()[1];
int hy_h = dhxDesc.GetLengths()[2];
int out_h = dyDesc[0].GetLengths()[1];
if(in_h <= 0 || hy_h <= 0 || hy_n <= 0 || hy_d <= 0 || out_h <= 0 || seqLen <= 0)
{
MIOPEN_THROW(miopenStatusBadParm);
}
int batch_n = 0;
for(int i = 0; i < seqLen; i++)
{
int batchval, inputvec, batchvalout, outputvec;
std::tie(batchval, inputvec) = miopen::tien<2>(dxDesc[i].GetLengths());
std::tie(batchvalout, outputvec) = miopen::tien<2>(dyDesc[i].GetLengths());
if(batchval != batchvalout)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(i == 0)
{
if(batchval <= 0)
{
MIOPEN_THROW(miopenStatusBadParm, "Input batch is ZERO!");
}
}
else
{
if(batchval > in_n.back() || batchval < 0)
{
MIOPEN_THROW(miopenStatusBadParm,
"Incorrect input batch size at time " + std::to_string(i) +
"! Batch size must not ascend!");
}
}
in_n.push_back(batchval);
batch_n += dxDesc[i].GetLengths()[0];
}
int bi = dirMode != 0u ? 2 : 1;
if(out_h != (bi * hy_h))
{
MIOPEN_THROW(miopenStatusBadParm, "Output size doesn't match hidden state size!");
}
float ctime = 0.;
int in_stride = in_h;
int hy_stride = hy_h * bi * static_cast<int>(workspaceScale);
int out_stride = out_h;
int wei_stride = hy_h * bi * static_cast<int>(nHiddenTensorsPerLayer);
int uni_stride = hy_h;
int bi_stride = hy_h * bi;
if(inputMode == miopenRNNskip)
{
if(in_h != hy_h)
{
MIOPEN_THROW(miopenStatusBadParm,
"The input tensor size must equal to the hidden "
"state size of the network in SKIP_INPUT mode!");
}
in_h = 0;
}
size_t offset;
float alpha0, alpha1, beta_t;
float alpha = 1, beta = 0;
std::vector<int> sp_size(3, 1), sp_stride(3, 1), x_size(3, 1), x_stride(3, 1), y_size(3, 1),
y_stride(3, 1), hx_size(3, 1), hx_stride(3, 1);
miopen::TensorDescriptor sp_desc, x_desc, y_desc, hx_desc;
sp_size[2] = workSpaceSize / GetTypeSize(wDesc.GetType());
sp_stride[0] = sp_size[2];
sp_stride[1] = sp_size[2];
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
SetTensor(handle, sp_desc, workSpace, &beta);
// Update time
profileRNNkernels(handle, 0, ctime);
sp_stride[0] = batch_n * hy_stride;
sp_stride[1] = hy_stride;
sp_size[2] = 1;
x_stride[0] = batch_n * in_stride;
x_stride[1] = in_stride;
y_stride[0] = batch_n * out_stride;
y_stride[1] = out_stride;
if(dhx != nullptr || (rnnMode == miopenLSTM && dcx != nullptr))
{
hx_size[2] = hy_d * hy_n * hy_h;
hx_stride[0] = hx_size[2];
hx_stride[1] = hx_size[2];
hx_desc = miopen::TensorDescriptor(wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(dhx != nullptr)
{
SetTensor(handle, hx_desc, dhx, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && dcx != nullptr)
{
SetTensor(handle, hx_desc, dcx, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
hx_stride[0] = in_n.at(0) * uni_stride;
hx_stride[1] = uni_stride;
#if MIOPEN_USE_GEMM
int prelayer_shift, pretime_shift, cur_time, cur_batch;
int wei_len = 0;
int wei_len_t = 0;
int dhd_off = 0;
int use_time = 0;
int pre_batch = 0;
int use_time2 = 0;
int pre_batch2 = 0;
switch(rnnMode)
{
case miopenRNNRELU:
case miopenRNNTANH:
// printf("run rnn gpu bwd data \n");
wei_len = hy_h;
wei_len_t = hy_h;
dhd_off = 0;
break;
case miopenLSTM:
// printf("run lstm gpu bwd data \n");
wei_len = hy_h * 4;
wei_len_t = hy_h * 4;
dhd_off = bi * hy_h * 5;
break;
case miopenGRU:
// printf("run gru gpu bwd data \n");
wei_len = hy_h * 3;
wei_len_t = hy_h * 2;
dhd_off = bi * hy_h * 3;
break;
}
ActivationDescriptor tanhDesc, sigDesc, activDesc;
sigDesc = {miopenActivationLOGISTIC, 1, 0, 1};
tanhDesc = {miopenActivationTANH, 1, 1, 1};
if(rnnMode == miopenRNNRELU)
{
activDesc = {miopenActivationRELU, 1, 0, 1};
}
else if(rnnMode == miopenRNNTANH)
{
activDesc = {miopenActivationTANH, 1, 1, 1};
}
for(int li = static_cast<int>(nLayers) - 1; li >= 0; li--)
{
int wei_shift = (in_h + hy_h) * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
int hid_shift = li * batch_n * hy_stride;
int hx_shift = li * hy_n * bi_stride;
int weitime_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
// feedback from output
if(li == nLayers - 1)
{
y_size[1] = batch_n;
y_size[2] = out_h;
sp_size[1] = batch_n;
sp_size[2] = hy_h * bi;
y_desc = miopen::TensorDescriptor(wDesc.GetType(), y_size.data(), y_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
CopyTensor(handle, y_desc, dy, sp_desc, workSpace, 0, hid_shift + dhd_off);
// Update time
profileRNNkernels(handle, 1, ctime); // start timing
}
else
{
prelayer_shift = (li + 1) * batch_n * hy_stride;
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
false,
batch_n,
hy_h * bi,
wei_len * bi,
hy_stride,
bi_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
prelayer_shift,
w,
wei_shift,
workSpace,
hid_shift + dhd_off,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
if(!float_equal(miopen::deref(dropoutDesc).dropout, 0))
{
std::vector<int> drop_size(2), drop_in_str(2, 1);
drop_size[0] = batch_n;
drop_size[1] = hy_h * bi;
drop_in_str[0] = hy_stride;
auto drop_in_desc = miopen::TensorDescriptor(
wDesc.GetType(), drop_size.data(), drop_in_str.data(), 2);
size_t drop_rsv_size = drop_in_desc.GetElementSize();
size_t drop_rsv_start =
algoMode == miopenRNNdefault && rnnMode == miopenLSTM
? nLayers * batch_n * hy_stride + nLayers * batch_n * hy_h * bi
: 2 * nLayers * batch_n * hy_stride;
size_t drop_rsv_offset = (drop_rsv_start + (nLayers - 1) * batch_n * hy_h * bi) *
(wDesc.GetType() == miopenFloat ? 4 : 2) +
li * drop_rsv_size;
miopen::deref(dropoutDesc)
.DropoutBackward(handle,
drop_in_desc,
drop_in_desc,
workSpace,
drop_in_desc,
workSpace,
reserveSpace,
drop_rsv_size,
hid_shift + dhd_off,
hid_shift + dhd_off,
drop_rsv_offset);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
// from hidden state
int bacc = batch_n;
int baccbi = 0;
for(int ti = seqLen - 1; ti >= 0; ti--)
{
bacc -= in_n.at(ti);
// from post state
for(int ri = 0; ri < bi; ri++)
{
cur_time = ri == 0 ? ti : seqLen - 1 - ti;
cur_batch = ri == 0 ? bacc : baccbi;
offset = hid_shift + cur_batch * hy_stride;
if(ti < seqLen - 1)
{
use_time = ri == 0 ? ti + 1 : seqLen - 1 - ti;
pre_batch = ri == 0 ? bacc + in_n.at(ti) : baccbi - in_n.at(seqLen - 2 - ti);
}
if(ti > 0)
{
use_time2 = ri == 0 ? ti : seqLen - ti;
pre_batch2 =
ri == 0 ? bacc - in_n.at(ti - 1) : baccbi + in_n.at(seqLen - 1 - ti);
}
if(in_n.at(cur_time) > 0)
{
if(ti == seqLen - 1)
{
if(dhy != nullptr)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time);
sp_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
hx_desc,
dhy,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h,
offset + dhd_off + ri * hy_h,
offset + dhd_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 0 && dhy != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
hx_desc,
dhy,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + dhd_off + ri * hy_h + in_n.at(use_time) * hy_stride,
offset + dhd_off + ri * hy_h + in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
}
pretime_shift =
li * batch_n * hy_stride + pre_batch * hy_stride + ri * wei_len;
if(in_n.at(use_time) > 0)
{
if(rnnMode == miopenGRU)
{
sp_size[1] = in_n.at(use_time);
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
pretime_shift - ri * 2 * hy_h + dhd_off,
pretime_shift + nLayers * batch_n * hy_stride,
offset + dhd_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
CopyTensor(handle,
sp_desc,
workSpace,
sp_desc,
workSpace,
pretime_shift + 2 * hy_h,
static_cast<int>(offset) + ri * wei_len + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
CopyTensor(handle,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
pretime_shift - ri * 2 * hy_h + dhd_off +
static_cast<int>(nLayers) * batch_n * hy_stride,
pretime_shift + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
false,
in_n.at(use_time),
hy_h,
wei_len,
hy_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
pretime_shift,
w,
weitime_shift + ri * wei_len * uni_stride,
workSpace,
static_cast<int>(offset) + dhd_off + ri * hy_h,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
if(rnnMode == miopenGRU)
{
CopyTensor(handle,
sp_desc,
workSpace,
sp_desc,
workSpace,
static_cast<int>(offset) + ri * wei_len + 2 * hy_h,
pretime_shift + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
// update hidden status
sp_size[1] = in_n.at(cur_time);
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
if(rnnMode == miopenRNNRELU || rnnMode == miopenRNNTANH)
{
// activation
activDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + ri * wei_len,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenLSTM)
{
if(algoMode == miopenRNNdefault)
{
LSTMBackwardHiddenStateUpdate(
handle,
wDesc.GetType(),
ti == 0,
ti == seqLen - 1,
ri,
in_n.at(0),
in_n.at(cur_time),
in_n.at(use_time),
in_n.at(use_time2),
hy_h,
hy_stride,
wei_len,
wei_stride,
cx,
hx_shift + ri * hy_n * hy_h,
reserveSpace,
offset + ri * wei_len,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
(li * batch_n + cur_batch) * bi * hy_h + ri * hy_h +
nLayers * batch_n * hy_stride,
li * batch_n * hy_stride + pre_batch2 * hy_stride + bi * wei_len +
ri * hy_h,
dcy,
hx_shift + ri * hy_n * hy_h,
workSpace,
offset + ri * wei_len,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + bi * wei_len + ri * hy_h,
li * batch_n * hy_stride + pre_batch * hy_stride + bi * wei_len +
ri * hy_h,
offset + dhd_off + ri * hy_h,
li * batch_n * hy_stride + pre_batch * hy_stride + hy_h +
ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
continue;
}
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
// update cell state
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + dhd_off + ri * hy_h,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
tanhDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h +
nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(ti == seqLen - 1)
{
if(dcy != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
hx_desc,
dcy,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h,
offset + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 0 && dcy != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
hx_desc,
dcy,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time) * hy_stride,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
pretime_shift = li * batch_n * hy_stride + pre_batch * hy_stride;
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
if(in_n.at(cur_time) != in_n.at(use_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
pretime_shift + bi * wei_len + ri * hy_h,
pretime_shift + hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(cur_time) != in_n.at(use_time))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
// update forget gate
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
if(ti == 0)
{
if(cx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
hx_shift + ri * hy_n * hy_h,
offset + hy_h + ri * wei_len);
}
}
else
{
if(ri == 1 && cx != nullptr && in_n.at(cur_time) > in_n.at(use_time2))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time2);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time2);
sp_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time2) * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time2) * hy_h,
offset + hy_h + ri * wei_len +
in_n.at(use_time2) * hy_stride);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time2) > 0)
{
pretime_shift = li * batch_n * hy_stride + pre_batch2 * hy_stride;
if(in_n.at(cur_time) != in_n.at(use_time2))
{
sp_size[1] = in_n.at(use_time2);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
pretime_shift + bi * wei_len + ri * hy_h,
offset + hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(cur_time) != in_n.at(use_time2))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
}
// update input gate
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
offset + 3 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// update output gate
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + dhd_off + ri * hy_h,
offset + bi * wei_len + ri * hy_h + nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// update c gate
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 3 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
tanhDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + 3 * hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
offset + 3 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[2] = 3 * hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + ri * wei_len,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenGRU)
{
// c gate
alpha0 = 1;
alpha1 = -1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + dhd_off + ri * hy_h,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + dhd_off + ri * hy_h,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
tanhDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// r gate
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + dhd_off + ri * hy_h + nLayers * batch_n * hy_stride,
offset + hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + dhd_off + ri * hy_h + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// z gate
if(ti == 0)
{
if(hx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
hx_desc,
hx,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h,
offset + dhd_off + ri * hy_h,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time2))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time2);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time2);
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
hx_desc,
hx,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time2) * hy_h,
offset + dhd_off + ri * hy_h +
in_n.at(use_time2) * hy_stride,
offset + ri * wei_len + in_n.at(use_time2) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time2) > 0)
{
if(in_n.at(use_time2) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time2);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hid_shift + pre_batch2 * hy_stride + dhd_off + ri * hy_h,
offset + dhd_off + ri * hy_h,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(use_time2) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
}
alpha0 = -1;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + dhd_off + ri * hy_h,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[2] = 2 * hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + ri * wei_len,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
baccbi += in_n.at(seqLen - 1 - ti);
}
// dcx, dhx
if(dhx != nullptr || (rnnMode == miopenLSTM && dcx != nullptr))
{
hx_size[2] = hy_h;
sp_size[2] = hy_h;
bacc = 0;
baccbi = batch_n;
for(int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n.at(seqLen - 1 - ti);
for(int ri = 0; ri < bi; ri++)
{
cur_time = ri == 0 ? ti : seqLen - 1 - ti;
cur_batch = ri == 0 ? bacc : baccbi;
use_time = 0;
int use_batch = 0;
if(ti > 0)
{
use_time = ri == 0 ? ti - 1 : seqLen - ti;
use_batch = in_n.at(use_time);
}
if(in_n.at(cur_time) > use_batch)
{
pretime_shift = li * batch_n * hy_stride + cur_batch * hy_stride;
if(rnnMode == miopenLSTM || rnnMode == miopenGRU)
{
sp_size[1] = in_n.at(cur_time) - use_batch;
hx_size[1] = in_n.at(cur_time) - use_batch;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(dhx != nullptr)
{
if(rnnMode == miopenGRU)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
pretime_shift + 2 * hy_h + ri * wei_len +
use_batch * hy_stride,
pretime_shift + hy_h + ri * wei_len +
use_batch * hy_stride + nLayers * batch_n * hy_stride,
pretime_shift + dhd_off + ri * hy_h +
use_batch * hy_stride + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
false,
false,
(in_n.at(cur_time) - use_batch),
hy_h,
hy_h,
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
0, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(
handle,
gemm_desc,
reserveSpace,
pretime_shift + dhd_off + ri * hy_h + use_batch * hy_stride +
static_cast<int>(nLayers) * batch_n * hy_stride,
w,
weitime_shift + 2 * hy_h * uni_stride +
ri * wei_len * uni_stride,
dhx,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
hx_desc,
dhx,
pretime_shift + dhd_off + ri * hy_h +
use_batch * hy_stride,
pretime_shift + ri * wei_len + use_batch * hy_stride +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
false,
false,
(in_n.at(cur_time) - use_batch),
hy_h,
wei_len_t,
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
pretime_shift + ri * wei_len + use_batch * hy_stride,
w,
weitime_shift + ri * wei_len * uni_stride,
dhx,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && dcx != nullptr)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
if(algoMode == miopenRNNdefault)
{
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
hx_desc,
dcx,
pretime_shift + bi * wei_len + ri * hy_h +
use_batch * hy_stride,
pretime_shift + hy_h + ri * wei_len +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
continue;
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
hx_desc,
dcx,
pretime_shift + bi * wei_len + ri * hy_h +
use_batch * hy_stride,
pretime_shift + hy_h + ri * wei_len + use_batch * hy_stride +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
bacc += in_n.at(ti);
}
}
}
// dinput
if(inputMode == miopenRNNskip)
{
sp_size[1] = batch_n;
sp_size[2] = hy_h;
x_size[1] = batch_n;
x_size[2] = hy_h;
x_desc = miopen::TensorDescriptor(wDesc.GetType(), x_size.data(), x_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
for(int gi = 0; gi < nHiddenTensorsPerLayer * bi; gi++)
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
x_desc,
dx,
&beta_t,
x_desc,
dx,
gi * hy_h,
0,
0);
// Update time
profileRNNkernels(handle, (gi == nHiddenTensorsPerLayer * bi - 1) ? 2 : 1, ctime);
}
}
else
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
false,
batch_n,
in_h,
wei_len * bi,
hy_stride,
in_stride,
in_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
0, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(
handle, gemm_desc, workSpace, 0, w, 0, dx, 0, nullptr, GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 2, ctime);
}
#else
(void)wei_stride;
(void)bi_stride;
(void)alpha;
(void)offset;
(void)alpha0;
(void)alpha1;
(void)beta_t;
(void)hx;
(void)cx;
(void)dhy;
(void)dcy;
(void)reserveSpace;
(void)in_h;
MIOPEN_THROW("GEMM is not supported");
#endif
};
void RNNDescriptor::RNNBackwardWeights(Handle& handle,
const int seqLen,
c_array_view<const miopenTensorDescriptor_t> xDesc,
ConstData_t x,
const TensorDescriptor& hxDesc,
ConstData_t hx,
c_array_view<const miopenTensorDescriptor_t> dyDesc,
ConstData_t dy,
const TensorDescriptor& dwDesc,
Data_t dw,
Data_t workSpace,
size_t workSpaceSize,
ConstData_t reserveSpace,
size_t reserveSpaceSize) const
{
if(x == nullptr || dw == nullptr || dy == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(workSpaceSize < GetWorkspaceSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Workspace is required");
}
if(reserveSpaceSize < GetReserveSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Reservespace is required");
}
std::string network_config;
std::vector<int> in_n;
int in_h = xDesc[0].GetLengths()[1];
int hy_d = hxDesc.GetLengths()[0];
int hy_n = hxDesc.GetLengths()[1];
int hy_h = hxDesc.GetLengths()[2];
int out_h = dyDesc[0].GetLengths()[1];
if(in_h <= 0 || hy_h <= 0 || hy_n <= 0 || hy_d <= 0 || out_h <= 0 || seqLen <= 0)
{
MIOPEN_THROW(miopenStatusBadParm);
}
int batch_n = 0;
for(int i = 0; i < seqLen; i++)
{
int batchval, inputvec, batchvalout, outputvec;
std::tie(batchval, inputvec) = miopen::tien<2>(xDesc[i].GetLengths());
std::tie(batchvalout, outputvec) = miopen::tien<2>(dyDesc[i].GetLengths());
if(batchval != batchvalout)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(i == 0)
{
if(batchval <= 0)
{
MIOPEN_THROW(miopenStatusBadParm, "Input batch is ZERO!");
}
}
else
{
if(batchval > in_n.back() || batchval < 0)
{
MIOPEN_THROW(miopenStatusBadParm,
"Incorrect input batch size at time " + std::to_string(i) +
"! Batch size must not ascend!");
}
}
in_n.push_back(batchval);
batch_n += xDesc[i].GetLengths()[0];
}
int bi = dirMode != 0u ? 2 : 1;
if(out_h != (bi * hy_h))
{
MIOPEN_THROW(miopenStatusBadParm, "Output size doesn't match hidden state size!");
}
float ctime = 0.;
int in_stride = in_h;
int hy_stride = hy_h * bi * static_cast<int>(workspaceScale);
int wei_stride = hy_h * bi * static_cast<int>(nHiddenTensorsPerLayer);
int uni_stride = hy_h;
int bi_stride = hy_h * bi;
if(inputMode == miopenRNNskip)
{
if(in_h != hy_h)
{
MIOPEN_THROW(miopenStatusBadParm,
"The input tensor size must equal to the hidden "
"state size of the network in SKIP_INPUT mode!");
}
in_h = 0;
}
size_t wei_shift_bias = (in_h + hy_h + (bi * hy_h + hy_h) * (nLayers - 1)) * wei_stride;
float alpha0, alpha1, beta_t = 0;
std::vector<int> sp_size(3, 1), sp_stride(3, 1), w_size(3, 1), w_stride(3, 1);
miopen::TensorDescriptor sp_desc, w_desc;
sp_stride[0] = batch_n * hy_stride;
sp_stride[1] = hy_stride;
w_size[2] = dwDesc.GetElementSize();
w_stride[0] = w_size[2];
w_stride[1] = w_size[2];
w_desc = miopen::TensorDescriptor(dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
SetTensor(handle, w_desc, dw, &beta_t);
// Update time
profileRNNkernels(handle, 0, ctime);
w_stride[0] = wei_stride;
w_stride[1] = wei_stride;
w_size[2] = 1;
#if MIOPEN_USE_GEMM
int wei_len = 0;
int hid_off = 0;
int use_time = 0;
int pre_batch = 0;
switch(rnnMode)
{
case miopenRNNRELU:
case miopenRNNTANH:
// printf("run rnn gpu bwd weights \n");
wei_len = hy_h;
hid_off = static_cast<int>(nLayers) * batch_n * hy_stride;
break;
case miopenLSTM:
// printf("run lstm gpu bwd weights \n");
wei_len = hy_h * 4;
hid_off = bi * hy_h * 5;
break;
case miopenGRU:
// printf("run gru gpu bwd weights \n");
wei_len = hy_h * 3;
hid_off = bi * hy_h * 3;
break;
}
for(int li = 0; li < nLayers; li++)
{
int hid_shift = li * batch_n * hy_stride;
int wei_shift = (in_h + hy_h) * wei_stride + (li - 1) * (bi * hy_h + hy_h) * wei_stride;
// between layers
if(li == 0)
{
if(inputMode == miopenRNNlinear)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
true,
false,
wei_len * bi,
in_h,
batch_n,
hy_stride,
in_stride,
in_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
0,
x,
0,
dw,
0,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
bool use_dropout = !float_equal(miopen::deref(dropoutDesc).dropout, 0);
auto prelayer_shift = static_cast<int>(
use_dropout ? (algoMode == miopenRNNdefault && rnnMode == miopenLSTM
? nLayers * batch_n * hy_stride + nLayers * batch_n * hy_h * bi
: 2 * nLayers * batch_n * hy_stride) +
(li - 1) * batch_n * hy_h * bi
: (li - 1) * batch_n * hy_stride + hid_off);
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
true,
false,
wei_len * bi,
hy_h * bi,
batch_n,
hy_stride,
use_dropout ? hy_h * bi : hy_stride,
bi_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
hid_shift,
reserveSpace,
prelayer_shift,
dw,
wei_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(biasMode != 0u)
{
wei_shift = static_cast<int>(wei_shift_bias) + li * 2 * wei_stride;
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
w_size[1] = 1;
w_size[2] = wei_stride;
w_desc = miopen::TensorDescriptor(dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 0;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
w_desc,
dw,
&alpha1,
sp_desc,
workSpace,
&beta_t,
w_desc,
dw,
wei_shift,
hid_shift,
wei_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
// between time
// Calculate feedback for c gate in GRU
if(rnnMode == miopenGRU)
{
sp_size[1] = batch_n;
sp_size[2] = hy_h;
sp_desc =
miopen::TensorDescriptor(dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
for(int ri = 0; ri < bi; ri++)
{
CopyTensor(handle,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
hid_shift + hid_off + ri * hy_h +
static_cast<int>(nLayers) * batch_n * hy_stride,
hid_shift + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
if(biasMode != 0u)
{
wei_shift = static_cast<int>(wei_shift_bias) + li * 2 * wei_stride + wei_stride;
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
if(hx != nullptr)
{
if(rnnMode == miopenGRU)
{
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
w_size[1] = 1;
w_size[2] = wei_stride;
w_desc = miopen::TensorDescriptor(
dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
w_desc,
dw,
&alpha1,
sp_desc,
workSpace,
&beta_t,
w_desc,
dw,
wei_shift,
hid_shift,
wei_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
CopyTensor(handle, w_desc, dw, w_desc, dw, wei_shift - wei_stride, wei_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
sp_size[1] = 1;
sp_size[2] = wei_len;
w_size[1] = 1;
w_size[2] = wei_len;
w_desc =
miopen::TensorDescriptor(dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
for(int bs = 0; bs < batch_n; bs++)
{
if(!(hx == nullptr && bs < in_n.at(0)))
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
dw,
&beta_t,
w_desc,
dw,
hid_shift + bs * hy_stride,
wei_shift,
wei_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
if(dirMode != 0u)
{
sp_size[1] = 1;
sp_size[2] = wei_len;
w_size[1] = 1;
w_size[2] = wei_len;
w_desc = miopen::TensorDescriptor(
dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
int cur_batch = 0;
for(int ti = 0; ti < seqLen - 1; ti++)
{
for(int bs = 0; bs < in_n.at(ti + 1); bs++)
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
dw,
&beta_t,
w_desc,
dw,
hid_shift + (cur_batch + bs) * hy_stride + wei_len,
wei_shift + wei_len,
wei_shift + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
cur_batch += in_n.at(ti);
}
}
}
}
int pretime_shift, hx_shift, cur_time;
bool comb_check = true;
if(seqLen > 2)
{
if(in_n.at(0) != in_n.at(seqLen - 2))
{
comb_check = false;
}
}
if(comb_check)
{
hx_shift = li * hy_n * bi_stride;
wei_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
for(int ri = 0; ri < bi; ri++)
{
hid_shift =
ri == 0 ? li * batch_n * hy_stride
: (li * batch_n * hy_stride + in_n.at(0) * (seqLen - 1) * hy_stride);
cur_time = ri == 0 ? 0 : seqLen - 1;
if(in_n.at(cur_time) > 0 && hx != nullptr)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
in_n.at(cur_time),
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len,
hx,
hx_shift + ri * hy_n * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
if(li == nLayers - 1 && ri == bi - 1 && seqLen == 1)
profileRNNkernels(handle, 2, ctime);
else
profileRNNkernels(handle, 1, ctime);
}
if(seqLen > 1)
{
if(ri == 1 && hx != nullptr && in_n.at(0) > in_n.at(seqLen - 1))
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
(in_n.at(0) - in_n.at(seqLen - 1)),
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len -
(in_n.at(0) - in_n.at(seqLen - 1)) * hy_stride,
hx,
hx_shift + ri * hy_n * hy_h + in_n.at(seqLen - 1) * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
hid_shift = ri == 0 ? (li * batch_n * hy_stride + in_n.at(0) * hy_stride)
: (li * batch_n * hy_stride);
pretime_shift =
ri == 0 ? li * batch_n * hy_stride + hid_off
: li * batch_n * hy_stride + in_n.at(0) * hy_stride + hid_off;
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
in_n.at(0) * (seqLen - 2) + in_n.at(seqLen - 1),
hy_stride,
hy_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len,
reserveSpace,
pretime_shift + ri * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
if(li == nLayers - 1 && ri == bi - 1)
profileRNNkernels(handle, 2, ctime);
else
profileRNNkernels(handle, 1, ctime);
}
}
}
else
{
int bacc = 0;
int baccbi = batch_n;
for(int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n.at(seqLen - 1 - ti);
hx_shift = li * hy_n * bi_stride;
wei_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
for(int ri = 0; ri < bi; ri++)
{
hid_shift = ri == 0 ? (li * batch_n * hy_stride + bacc * hy_stride)
: (li * batch_n * hy_stride + baccbi * hy_stride);
cur_time = ri == 0 ? ti : seqLen - 1 - ti;
if(ti > 0)
{
pre_batch =
ri == 0 ? bacc - in_n.at(ti - 1) : baccbi + in_n.at(seqLen - 1 - ti);
use_time = ri == 0 ? ti : seqLen - ti;
}
if(in_n.at(cur_time) > 0)
{
if(ti == 0)
{
if(hx != nullptr)
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
in_n.at(cur_time),
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len,
hx,
hx_shift + ri * hy_n * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
if(li == nLayers - 1 && ti == seqLen - 1 && ri == bi - 1)
profileRNNkernels(handle, 2, ctime);
else
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
(in_n.at(cur_time) - in_n.at(use_time)),
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(
handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len + in_n.at(use_time) * hy_stride,
hx,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
pretime_shift =
li * batch_n * hy_stride + pre_batch * hy_stride + hid_off;
if(in_n.at(use_time) > 0)
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
in_n.at(use_time),
hy_stride,
hy_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len,
reserveSpace,
pretime_shift + ri * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
if(li == nLayers - 1 && ti == seqLen - 1 && ri == bi - 1)
profileRNNkernels(handle, 2, ctime);
else
profileRNNkernels(handle, 1, ctime);
}
}
}
}
bacc += in_n.at(ti);
}
}
}
#else
(void)in_stride;
(void)alpha0;
(void)wei_shift_bias;
(void)alpha1;
(void)bi_stride;
(void)uni_stride;
(void)hx;
(void)workSpace;
(void)reserveSpace;
MIOPEN_THROW("GEMM is not supported");
#endif
};
} // namespace miopen
| ROCmSoftwarePlatform/MIOpen | src/ocl/rnnocl.cpp | C++ | mit | 222,865 |
<?php
namespace Renovate\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Renovate\MainBundle\Entity\Vacancy;
use Renovate\MainBundle\Entity\Document;
class VacanciesController extends Controller
{
public function indexAction()
{
$timestamp = time();
$token = Document::getToken($timestamp);
$parameters = array(
'timestamp' => $timestamp,
'token' => $token
);
$parameters['page'] = $this->get('renovate.pages')->getPageForUrl($this->getRequest()->getUri());
return $this->render('RenovateMainBundle:Vacancies:index.html.twig', $parameters);
}
public function showVacancyAction($vacancy_name_translit)
{
$em = $this->getDoctrine()->getManager();
$vacancy = $em->getRepository("RenovateMainBundle:Vacancy")->findOneByNameTranslit($vacancy_name_translit);
if ($vacancy == NULL) return $this->redirect($this->generateUrl('renovate_main_homepage'));
$parameters = array("vacancy" => $vacancy);
$parameters['page'] = $this->get('renovate.pages')->getPageForUrl($this->getRequest()->getUri());
return $this->render('RenovateMainBundle:Vacancies:showVacancy.html.twig', $parameters);
}
public function getVacanciesNgAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$response = new Response(json_encode(array("result" => Vacancy::getVacancies($em, $request->query->all(), true))));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function getVacanciesCountNgAction()
{
$em = $this->getDoctrine()->getManager();
$response = new Response(json_encode(array("result" => Vacancy::getVacanciesCount($em))));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function addVacancyNgAction()
{
$em = $this->getDoctrine()->getManager();
$data = json_decode(file_get_contents("php://input"));
$parameters = (object) $data;
$transliterater = $this->get('renovate.transliterater');
$vacancy = Vacancy::addVacancy($em, $transliterater, $parameters);
$response = new Response(json_encode(array("result" => $vacancy->getInArray())));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function removeVacancyNgAction($vacancy_id)
{
$em = $this->getDoctrine()->getManager();
$response = new Response(json_encode(array("result" => Vacancy::removeVacancyById($em, $vacancy_id))));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function editVacancyNgAction($vacancy_id)
{
$em = $this->getDoctrine()->getManager();
$data = json_decode(file_get_contents("php://input"));
$parameters = (object) $data;
$transliterater = $this->get('renovate.transliterater');
$vacancy = Vacancy::editVacancyById($em, $transliterater, $vacancy_id, $parameters);
$response = new Response(json_encode(array("result" => $vacancy->getInArray())));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
| oligarch777/renovate | src/Renovate/MainBundle/Controller/VacanciesController.php | PHP | mit | 3,444 |
#!/bin/bash
apt-get install -y postgresql-client-9.5 postgresql-9.5 postgresql-9.5-postgis-2.2 postgresql-9.5-postgis-2.2-scripts postgresql-server-dev-9.5 postgresql-contrib-9.5
| motobyus/moto | install/postgresql9.5/2.install.sh | Shell | mit | 181 |
export WORKON_HOME="$HOME/.virtualenvs"
export VIRTUALENVWRAPPER_PYTHON='/usr/local/bin/python3'
export PROJECT_HOME="$HOME/code"
source /usr/local/bin/virtualenvwrapper.sh | jacquesd/dotfiles | python/config.zsh | Shell | mit | 172 |
class AddMemberAddressFragments < ActiveRecord::Migration
def up
add_column :members, :street_address, :string
add_column :members, :address_locality, :string
add_column :members, :address_region, :string
add_column :members, :address_country, :string
add_column :members, :postal_code, :string
add_column :members, :organization_type, :string
add_column :members, :organization_vat_id, :string
add_column :members, :organization_company_number, :string
end
def down
remove_column :members, :street_address
remove_column :members, :address_locality
remove_column :members, :address_region
remove_column :members, :address_country
remove_column :members, :postal_code
remove_column :members, :organization_type
remove_column :members, :organization_vat_id
remove_column :members, :organization_company_number
end
end
| theodi/member-directory | db/migrate/20150303135313_add_member_address_fragments.rb | Ruby | mit | 889 |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
// https://stackoverflow.com/a/34384189
namespace PS4Macro.Classes.GlobalHooks
{
public class GlobalKeyboardHookEventArgs : HandledEventArgs
{
public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }
public GlobalKeyboardHookEventArgs(
GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
GlobalKeyboardHook.KeyboardState keyboardState)
{
KeyboardData = keyboardData;
KeyboardState = keyboardState;
}
}
//Based on https://gist.github.com/Stasonix
public class GlobalKeyboardHook : IDisposable
{
public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;
public GlobalKeyboardHook()
{
_windowsHookHandle = IntPtr.Zero;
_user32LibraryHandle = IntPtr.Zero;
_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.
_user32LibraryHandle = LoadLibrary("User32");
if (_user32LibraryHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
if (_windowsHookHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// because we can unhook only in the same thread, not in garbage collector thread
if (_windowsHookHandle != IntPtr.Zero)
{
if (!UnhookWindowsHookEx(_windowsHookHandle))
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = IntPtr.Zero;
// ReSharper disable once DelegateSubtraction
_hookProc -= LowLevelKeyboardProc;
}
}
if (_user32LibraryHandle != IntPtr.Zero)
{
if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_user32LibraryHandle = IntPtr.Zero;
}
}
~GlobalKeyboardHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private IntPtr _windowsHookHandle;
private IntPtr _user32LibraryHandle;
private HookProc _hookProc;
delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool FreeLibrary(IntPtr hModule);
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events are
/// associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">hook type</param>
/// <param name="lpfn">hook procedure</param>
/// <param name="hMod">handle to application instance</param>
/// <param name="dwThreadId">thread identifier</param>
/// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="hhk">handle to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="hHook">handle to current hook</param>
/// <param name="code">hook code passed to hook procedure</param>
/// <param name="wParam">value passed to hook procedure</param>
/// <param name="lParam">value passed to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
public struct LowLevelKeyboardInputEvent
{
/// <summary>
/// A virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int VirtualCode;
/// <summary>
/// A hardware scan code for the key.
/// </summary>
public int HardwareScanCode;
/// <summary>
/// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
/// </summary>
public int Flags;
/// <summary>
/// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
/// </summary>
public int TimeStamp;
/// <summary>
/// Additional information associated with the message.
/// </summary>
public IntPtr AdditionalInformation;
}
public const int WH_KEYBOARD_LL = 13;
//const int HC_ACTION = 0;
public enum KeyboardState
{
KeyDown = 0x0100,
KeyUp = 0x0101,
SysKeyDown = 0x0104,
SysKeyUp = 0x0105
}
public const int VkSnapshot = 0x2c;
//const int VkLwin = 0x5b;
//const int VkRwin = 0x5c;
//const int VkTab = 0x09;
//const int VkEscape = 0x18;
//const int VkControl = 0x11;
const int KfAltdown = 0x2000;
public const int LlkhfAltdown = (KfAltdown >> 8);
public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
{
bool fEatKeyStroke = false;
var wparamTyped = wParam.ToInt32();
if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
{
object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;
var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);
EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
handler?.Invoke(this, eventArguments);
fEatKeyStroke = eventArguments.Handled;
}
return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
}
} | komefai/PS4Macro | PS4Macro/Classes/GlobalHooks/GlobalKeyboardHook.cs | C# | mit | 9,190 |
module Rapa
class AlternateVersion
# @return [Hash]
attr_reader :source
# @param source [Hash]
def initialize(source)
@source = source
end
# @return [String]
def asin
source["ASIN"]
end
# @return [String]
def binding
source["Binding"]
end
# @return [String]
def title
source["Title"]
end
end
end
| r7kamura/rapa | lib/rapa/alternate_version.rb | Ruby | mit | 384 |
/**
* \file
* \brief Implementions of RL domains, Mountain Car (MC), HIV, and Bicycle.
*
* Copyright (c) 2008-2014 Robert D. Vincent.
*/
#include <vector>
#include <utility>
#include <cmath>
#include <string.h>
using namespace std;
#include "domain.h"
#include "random.h"
/** Returns the sign of a real number.
* \param x The number whose sign we wish to extract.
* \return The sign of \c x.
*/
double sign(double x) {
if (x == 0.0) return 0.0;
if (x < 0.0) return -1.0;
return 1.0;
}
/*
double dangle(double x) {
return fabs(x + 2.0*k*M_PI);
}
*/
/**
* Bicycle-balancing task used in Ernst et al. 2005.
*/
class Bicycle : public Domain {
private:
double dt;
double v;
double g;
double d_CM;
double c;
double h;
double M_c;
double M_d;
double M_p;
double M;
double r;
double l;
//double delta_psi; // used for reward calculation.
public:
/** Construct the bicycle balancing domain.
*/
Bicycle() {
numActions = 9;
numSteps = 500;
numDimensions = 7;
dt = 0.01;
v = 10.0/3.6;
g = 9.82;
d_CM = 0.3;
c = 0.66;
h = 0.94;
M_c = 15.0;
M_d = 1.7;
M_p = 60.0;
M = M_c + M_p;
r = 0.34;
l = 1.11;
}
bool isTerminal(vector<double> s) const {
return (s[0] > M_PI*12.0/180.0);
}
double getReward(vector<double> s, int a) const {
if (isTerminal(s)) return -1.0;
//return 0.1 * delta_psi;
return 0;
}
OneStepResult performAction(vector<double> s, int a) {
vector<double> sp(numDimensions, 0.0);
double ad[] = { 0.0, 0.0, 0.0, -0.02, -0.02, -0.02, 0.02, 0.02, 0.02 };
double aT[] = { 0.0, 2.0, -2.0, 0.0, 2.0, -2.0, 0.0, 2.0, -2.0 };
double d = ad[a];
double T = aT[a];
double w = rndInterval(-0.02, 0.02);
double dot_sigma = v/r;
double I_bnc = 13.0/3.0*M_c*h*h + M_p*(h + d_CM)*(h + d_CM);
double I_dc = M_d * r * r;
double I_dv = 3.0/2.0 * M_d * r * r;
double I_dl = 1.0/2.0 * M_d * r * r;
double omega = s[0];
double dot_omega = s[1];
double theta = s[2];
double dot_theta = s[3];
double x_b = s[4];
double y_b = s[5];
double psi = s[6];
double phi = omega + atan(d + w)/h;
double invrf = fabs(sin(theta))/l;
double invrb = fabs(tan(theta))/l;
double invrcm = (theta == 0.0) ? 0.0 : 1.0/sqrt((l-c)*(l-c) + (1.0/invrb)*(1.0/invrb));
sp[0] = omega + dt * dot_omega;
sp[1] = dot_omega + dt * (1.0 / I_bnc) * (M*h*g*sin(phi) - cos(phi)*(I_dc*dot_sigma*dot_theta + sign(theta)*v*v*(M_d*r*(invrb+invrf)+M*h*invrcm)));
sp[2] = theta + dt * dot_theta;
sp[3] = dot_theta + dt * (T - I_dv*dot_sigma*dot_omega)/I_dl;
sp[4] = x_b + dt * v * cos(psi);
sp[5] = y_b + dt * v * sin(psi);
sp[6] = psi + dt * sign(theta)*v*invrb;
//delta_psi = dangle(psi) - dangle(sp[6]);
if (fabs(theta) > M_PI*80.0/180.0) {
sp[2] = sign(theta)*M_PI*80.0/180.0;
sp[3] = 0.0;
}
OneStepResult p(sp, getReward(sp, a));
return p;
}
vector<double> initialState() {
vector<double> s(numDimensions, 0.0);
s[6] = M_PI;
return s;
}
};
/**
* \brief Implements the HIV model defined by Adams et al. (2004, 2005) and
* used by Ernst et al. (2006).
*
* This domain simulates the dynamics of HIV infection at the cellular level.
* It uses a six-dimensional real-valued state
* vector, in the order T1, T2, T1*, T2*, V, E, where T1 and T2 are the
* populations of uninfected type 1 and type 2 cells, and T1* and T2* are
* the populations of infected type 1 and 2 cells. V is the viral population,
* and E is the population of immune effectors.
*
* The problem is deterministic. It has three stable states, corresponding
* to an "uninfected" state, an "unhealthy" state, and a "healthy" state.
* The goal of the problem is to learn how to move the model from the
* unhealthy state to the healthy state.
*
* The action space in this implementation is limited to four discrete
* choices: No therapy, reverse transcriptase inhibitor only (RTI),
* protease inhibitor (PI) only, or both RTI and PI
* simultaneously. The RTI and PI have fixed values.
* These are the stable state vectors:
*
* - unhealthy: (163574.0, 5.0, 11945.0, 46.0, 63919.0, 24.0)
* - healthy: (967839.0, 621.0, 76.0, 6.0, 415.0, 353108.0)
* - uninfected: (1000000.0, 3198.0, 0.0, 0.0, 0.0, 10.0)
*/
class HIV : public Domain {
private:
double Q; /**< Coefficient of the viral load in the reward function. */
double R1; /**< Coefficient of the RTI in the reward function. */
double R2; /**< Coefficient of the PI in the reward function. */
double S; /**< Coefficient of the immune effectors. */
double l1; /**< type 1 cell production rate */
double d1; /**< type 1 cell death rate */
double k1; /**< population 1 infection rate */
double l2; /**< type 2 cell production rate */
double d2; /**< type 2 cell death rate */
double f; /**< treatment efficacy reduction in population 2 */
double k2; /**< population 2 infection rate */
double delta; /**< infected cell death rate */
double m1; /**< immune-induced clearance rate for population 1 */
double m2; /**< immune-induced clearance rate for population 2 */
double NT; /**< virions produced per infected cell */
double c; /**< virus natural death rate */
double p1; /**< average number of virions infecting a type 1 cell */
double p2; /**< average number of virions infecting a type 2 cell */
double lE; /**< immune effector production rate */
double bE; /**< maximum birth rate for immune effectors */
double Kb; /**< saturation constant for immune effector birth */
double dE; /**< maximum death rate for immune effectors */
double Kd; /**< saturation constant for immune effector death */
double deltaE; /**< natural death rate for immune effectors */
// Other constants
double dt; /**< Our integration timestep, in days. */
int nInt; /**< Number of integration steps per action. */
public:
/**
* Constructor for the HIV domain.
*/
HIV() {
numActions = 4;
numSteps = 200;
numDimensions = 6;
// constants for the reward function
Q = 0.1;
R1 = 20000.0;
R2 = 2000.0;
S = 1000.0;
// Constants for the ODE's
l1 = 10000.0; // type 1 cell production rate
d1 = 0.01; // type 1 cell death rate
k1 = 8.0e-7; // population 1 infection rate
l2 = 31.98; // type 2 cell production rate
d2 = 0.01; // type 2 cell death rate
f = 0.34; // treatment efficacy reduction in population 2
k2 = 1e-4; // population 2 infection rate
delta = 0.7; // infected cell death rate
m1 = 1.0e-5; // immune-induced clearance rate for population 1
m2 = 1.0e-5; // immune-induced clearance rate for population 2
NT = 100.0; // virions produced per infected cell
c = 13.0; // virus natural death rate
p1 = 1.0; // average number of virions infecting a type 1 cell
p2 = 1.0; // average number of virions infecting a type 2 cell
lE = 1.0; // immune effector production rate
bE = 0.3; // maximum birth rate for immune effectors
Kb = 100.0; // saturation constant for immune effector birth
dE = 0.25; // maximum death rate for immune effectors
Kd = 500.0; // saturation constant for immune effector death
deltaE = 0.1; // natural death rate for immune effectors
// Other constants
dt = 0.001; // Our integration timestep, in days.
nInt = (int)(5.0 / dt); // Number of integration steps per action.
}
/**
* Calculate the reward for the HIV domain. The reward is a
* continuous function of the action (treatment option), the virus
* population (\c s[4]) and the immune effector count (\c s[5]).
*/
double getReward(vector<double> s, int a) const {
// e1 is between 0.0 and 0.7 (RTI therapy on/off)
// e2 is between 0.0 and 0.3 (PI therapy on/off)
double V = s[4];
double E = s[5];
double e1 = ((a & 1) != 0) ? 0.7 : 0.0;
double e2 = ((a & 2) != 0) ? 0.3 : 0.0;
return -(Q*V + R1*e1*e1 + R2*e2*e2 - S*E);
}
/**
* Calculate the next state of the environment. The equations
* are integrated using a simple Euler method.
*/
OneStepResult performAction(vector<double> s, int a) {
/* This version is restricted to only four possible actions.
*/
double e1 = ((a & 1) != 0) ? 0.7 : 0.0;
double e2 = ((a & 2) != 0) ? 0.3 : 0.0;
vector<double> dy(numDimensions);
vector<double> y = s;
for (int i = 0; i < nInt; i++) {
dy[0] = l1 - d1 * y[0] - (1 - e1) * k1 * y[4] * y[0];
dy[1] = l2 - d2 * y[1] - (1 - f * e1) * k2 * y[4] * y[1];
dy[2] = (1 - e1) * k1 * y[4] * y[0] - delta * y[2] - m1 * y[5] * y[2];
dy[3] = (1 - f * e1) * k2 * y[4] * y[1] - delta * y[3] - m2 * y[5] * y[3];
dy[4] = (1.0 - e2) * NT * delta * (y[2] + y[3]) - c * y[4] -
((1 - e1) * p1 * k1 * y[0] + (1 - f * e1) * p2 * k2 * y[1]) * y[4];
dy[5] = lE + (bE * (y[2] + y[3]) * y[5]) / (y[2] + y[3] + Kb) -
(dE * (y[2] + y[3]) * y[5]) / (y[2] + y[3] + Kd) - deltaE * y[5];
for (int j = 0; j < numDimensions; j++)
y[j] += dy[j] * dt;
}
OneStepResult p(y, getReward(y, a));
return p;
}
/**
* The initial state in the environment is the "sick" stable state.
* There are two other stable states, a "healthy infected" state,
* and an "uninfected" state.
*/
vector<double> initialState() {
vector<double> s(numDimensions);
/* This is the "sick" initial state.
*/
s[0] = 163574.0;
s[1] = 5.0;
s[2] = 11945.0;
s[3] = 46.0;
s[4] = 63919.0;
s[5] = 24.0;
return s;
}
};
/**
* Implementation of the classic "mountain-car" reinforcement learning
* problem from Singh and Sutton 1996. It implements a two-dimensional
* continuous state consisting of the car's position and velocity.
*/
class MC : public Domain {
static const double min_x = -1.2; /**< Minimum position. */
static const double max_x = 0.5; /**< Maximum position. */
static const double min_v = -0.07; /**< Minimum velocity. */
static const double max_v = 0.07; /**< Maximum velocity. */
public:
/**
* Construct a mountain-car environment.
*/
MC() {
numDimensions = 2;
numActions = 3;
numSteps = 2000;
}
/**
* The domain is stochastic, in that it begins at a random initial
* state. It is otherwise deterministic.
*/
bool isStochastic() { return true; }
/**
* Return the reward for this state and action. For mountain car the
* usual implementation is to give a reward of -1 for every time step
* before reaching the goal.
* \param s The state vector.
* \param a The action.
* \return The reward received.
*/
double getReward(vector<double> s, int a) const {
if (isTerminal(s)) {
return 0.0;
}
else return -1.0;
}
/**
* Return the initial state for the task. Selects uniformly random values
* from the legal range of the position and velocity values.
* \return A two-dimensional state vector consisting of a random legal
* position and velocity.
*/
vector<double> initialState() {
vector<double> s(numDimensions);
s[0] = rndInterval(min_x, max_x);
s[1] = rndInterval(min_v, max_v);
return s;
}
/**
* Perform one time step in the mountain car environment.
* \param s The two-dimensional mountain car state vector.
* \param a The action to perform, where 0 means full reverse, 2 means full forward, and 1 implies no acceleration.
* \return A pair containing the next state and reward.
*/
OneStepResult performAction(vector<double> s, int a) {
double acc = 0.0;
if (a == 0) {
acc = -1.0;
}
if (a == 2) {
acc = 1.0;
}
double x0 = s[0];
double v0 = s[1];
double v1 = v0 + acc * 0.001 + cos(3.0 * x0) * -0.0025;
// Enforce bounds.
if (v1 < min_v) {
v1 = min_v;
}
else if (v1 > max_v) {
v1 = max_v;
}
double x1 = x0 + v1;
if (x1 < min_x) {
x1 = min_x;
}
else if (x1 > max_x) {
x1 = max_x;
}
vector<double> s1(numDimensions);
s1[0] = x1;
s1[1] = v1;
OneStepResult p(s1, getReward(s1, a));
return p;
}
/**
* Returns true if the car has reached the goal state.
* \param s The state to evaluate.
* \return True if the car's position is at is maximum.
*/
bool isTerminal(vector<double> s) const { return (s[0] >= max_x); }
};
/**
* Create a domain by name. Avoids having to export domain classes outside
* this module.
* \param name The name of the domain to create. It is not case-sensitive.
* The default is HIV
* \param propfile The name of an optional property file, which will provide
* configuration information for the domain.
* \return The domain object.
*/
Domain *CreateDomain(const char *name, const char *propfile) {
if (!strcasecmp(name, "MC")) {
return new MC();
}
else if (!strcasecmp(name, "Bicycle")) {
return new Bicycle();
}
else if (!strcasecmp(name, "rf")) {
extern Domain *getRF(const char *);
return getRF(propfile);
}
else if (!strcasecmp(name, "tass")) {
extern Domain *getTass(const char *);
return getTass(propfile);
}
else {
return new HIV();
}
}
| rdvincent/fqi | domain.cpp | C++ | mit | 13,528 |
'use strict';
angular.module('app.directives')
.directive('questionBlock',function() {
return {
restrict: 'E',
scope: {
question:'='
},
templateUrl:'/directives/questions/question-block.html'
};
});
| pwithers/agrippa | public/js/directives/question-block.js | JavaScript | mit | 244 |
# mcrypt_compat
[](https://travis-ci.org/phpseclib/mcrypt_compat)
PHP 5.x/7.x polyfill for mcrypt extension.
## Installation
With [Composer](https://getcomposer.org/):
```
composer require phpseclib/mcrypt_compat
```
## Supported algorithms
- rijndael-128
- rijndael-192
- rijndael-256
- des
- blowfish
- rc2
- tripledes
- arcfour
## Unsupported algorithms
- cast-128
- gost
- cast-256
- loki97
- saferplus
- wake
- blowfish-compat
- serpent
- xtea
- enigma
## Supported modes
- cbc
- ncfb
- cfb
- ctr
- ecb
- nofb
- stream
Although `nofb` is supported `ofb` is not. Further, mcrypt_compat's `ncfb` implementation has some incompatibles with mcrypt's implementation where `mcrypt_generic` and `mdecrypt_generic` are concerned. The unit tests elaborate.
| delaneymethod/delaneymethod | craft/app/vendor/phpseclib/mcrypt_compat/README.md | Markdown | mit | 845 |
from asyncio import coroutine
import pytest
from aiohttp import HttpBadRequest, HttpMethodNotAllowed
from fluentmock import create_mock
from aiohttp_rest import RestEndpoint
class CustomEndpoint(RestEndpoint):
def get(self):
pass
def patch(self):
pass
@pytest.fixture
def endpoint():
return RestEndpoint()
@pytest.fixture
def custom_endpoint():
return CustomEndpoint()
def test_exiting_methods_are_registered_during_initialisation(custom_endpoint: CustomEndpoint):
assert len(custom_endpoint.methods) == 2
assert ('GET', custom_endpoint.get) in custom_endpoint.methods.items()
assert ('PATCH', custom_endpoint.patch) in custom_endpoint.methods.items()
def test_register_method(endpoint: RestEndpoint):
def sample_method():
pass
endpoint.register_method('verb', sample_method)
assert ('VERB', sample_method) in endpoint.methods.items()
@pytest.mark.asyncio
async def test_dispatch_uses_correct_handler_for_verb(endpoint: RestEndpoint):
endpoint.register_method('VERB1', coroutine(lambda: 5))
endpoint.register_method('VERB2', coroutine(lambda: 17))
assert await endpoint.dispatch(create_mock(method='VERB1', match_info={})) == 5
assert await endpoint.dispatch(create_mock(method='VERB2', match_info={})) == 17
@pytest.mark.asyncio
async def test_dispatch_passes_request_when_required(endpoint: RestEndpoint):
endpoint.register_method('REQUEST', coroutine(lambda request: request))
request = create_mock(method='REQUEST', match_info={})
assert await endpoint.dispatch(request) == request
@pytest.mark.asyncio
async def test_dispatch_passes_match_info_when_required(endpoint: RestEndpoint):
endpoint.register_method('MATCH_INFO', coroutine(lambda prop1, prop2: (prop2, prop1)))
request = create_mock(method='MATCH_INFO', match_info={'prop1': 1, 'prop2': 2})
assert await endpoint.dispatch(request) == (2, 1)
@pytest.mark.asyncio
async def test_dispatch_raises_bad_request_when_match_info_does_not_exist(endpoint: RestEndpoint):
endpoint.register_method('BAD_MATCH_INFO', coroutine(lambda no_match: no_match))
request = create_mock(method='BAD_MATCH_INFO', match_info={})
with pytest.raises(HttpBadRequest):
await endpoint.dispatch(request)
@pytest.mark.asyncio
async def test_dispatch_raises_method_not_allowed_when_verb_not_matched(endpoint: RestEndpoint):
request = create_mock(method='NO_METHOD')
with pytest.raises(HttpMethodNotAllowed):
await endpoint.dispatch(request)
| atbentley/aiohttp-rest | tests/test_endpoint.py | Python | mit | 2,542 |
package main
import (
"log"
"os"
"golang.org/x/net/context"
"google.golang.org/grpc"
// "google.golang.org/grpc/credentials/oauth"
"google.golang.org/grpc/metadata"
m "github.com/konjoot/grpc/proto/messages"
s "github.com/konjoot/grpc/proto/sessions"
)
const sessionAddr = "localhost:50051"
const messageAddr = "localhost:50052"
var (
defaultLogin = []byte("login")
defaultPass = []byte("pass")
)
func main() {
// Set up a connection to the server.
sessionConn, err := grpc.Dial(sessionAddr, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect to session server: %v", err)
}
defer sessionConn.Close()
session := s.NewSessionClient(sessionConn)
login := defaultLogin
pass := defaultPass
if len(os.Args) > 1 {
login = []byte(os.Args[1])
}
if len(os.Args) > 2 {
pass = []byte(os.Args[2])
}
sess, err := session.Create(context.Background(), &s.SessionRequest{Login: login, Pass: pass})
if err != nil {
log.Fatalf("could not create session: %v", err)
}
messageConn, err := grpc.Dial(messageAddr, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect to message server: %v", err)
}
defer messageConn.Close()
message := m.NewMessageClient(messageConn)
// header usage example
header := metadata.Pairs("Authorization", string(sess.Token))
ctx := metadata.NewContext(context.Background(), header)
msg, err := message.Create(ctx, &m.MessageRequest{User: []byte("user1"), Text: []byte("hello")})
if err != nil {
log.Fatalf("could not create message: %v", err)
}
log.Print(msg)
}
| konjoot/grpc | cmd/messages/client/main.go | GO | mit | 1,558 |
'use strict';
var _ = require('lodash');
var utils = require('../utils');
var d3 = require('d3');
var sunCalc = require('suncalc');
var geocoder = require('geocoder');
var Path = require('svg-path-generator');
var margin = {
top: 20,
right: 0,
bottom: 20,
left: 0
};
var dayOfYear = function(d) {
var j1 = new Date(d);
j1.setMonth(0, 0);
return Math.round((d - j1) / 8.64e7) - 1;
};
/*
* View controller
*/
function Viz($el) {
if (!(this instanceof Viz)) {
return new Viz($el);
}
this.$el = $el;
var $tooltip = $('#tooltip');
// do some cool vizualization here
var width = $el.width() - margin.left - margin.right;
var height = (Math.min(width * 0.6, $(document).height() - $el.offset().top - 180)) - margin.top - margin.bottom;
var today = new Date();
var start = new Date(today.getFullYear(), 0, 1, 12, 0, 0, 0, 0);
var end = new Date(today.getFullYear(), 11, 31, 12, 0, 0, 0, 0);
var dateX = d3.time.scale().domain([start, end]).range([0, width]);
this.x = d3.scale.linear()
.domain([0, 365])
.range([0, width]);
this.y = d3.scale.linear()
.domain([0, 24])
.range([0, height]);
var inverseX = d3.scale.linear()
.range([0, 365])
.domain([0, width]);
var xAxis = d3.svg.axis()
.scale(dateX);
var svg = d3.select($el[0])
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.classed('container', true)
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var self = this;
var hideTimeout;
svg.on('mousemove', function() {
if(!self.times.length) {
return;
}
var coordinates = d3.mouse(this);
var x = coordinates[0];
var i = inverseX(x);
i = Math.floor(i);
self.svg.selectAll('g.day').classed('hover', function(d, idx) {
return idx === i;
});
var format = d3.time.format('%B %e');
$tooltip.find('.date').text(format(self.dates[i]));
var sunset = new Date(self.times[i].sunset);
var sunrise = new Date(self.times[i].sunrise);
format = d3.time.format('%I:%M %p');
console.log(format(sunrise));
console.log(format(sunset));
$tooltip.find('.sunrise').text(format(sunrise));
$tooltip.find('.sunset').text(format(sunset));
var offset = self.$el.offset();
var top = offset.top;
top += self.y(sunrise.getHours() + sunrise.getMinutes() / 60);
var left = self.x(i) + offset.left;
left -= $tooltip.width() / 2;
top -= $tooltip.height() - 15;
$tooltip.css('top', top).css('left', left).show();
clearTimeout(hideTimeout);
}).on('mouseout', function(){
hideTimeout = setTimeout(function() {
$tooltip.fadeOut();
self.svg.selectAll('g.day').classed('hover', false);
}, 750);
});
d3.select($tooltip[0]).on('mouseenter', function() {
clearTimeout(hideTimeout);
});
this.svg = svg;
svg.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', width)
.attr('height', height);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
var max = 0;
for (var d = start, i=0; d < end; d.setDate(d.getDate() + 1), i++) {
this._drawDay(i);
if(i > max) {
max = i;
}
}
var avgGroup = this.svg.append('g').classed('average', true);
avgGroup
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(12))
.horizontalLineTo(self.x(max))
.end();
})
.classed('sunrise', true);
avgGroup
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(12))
.horizontalLineTo(self.x(max))
.end();
})
.classed('sunset', true);
avgGroup
.append('text')
.attr('x', self.x(50))
.attr('y', self.y(12))
.style('opacity', 0)
.classed('sunrise', true);
avgGroup
.append('text')
.attr('x', self.x(250))
.attr('y', self.y(12))
.style('opacity', 0)
.classed('sunset', true);
this.svg
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(today.getHours() + today.getMinutes() / 60))
.horizontalLineTo(self.x(max))
.end();
})
.classed('now', true);
}
Viz.prototype.updatePlace = function(placeName) {
var self = this;
if(placeName.trim() === '') {
return;
}
var times = [];
var dates = [];
geocoder.geocode(placeName, function(err, res) {
if(err) {
return console.log(err);
}
if(!res.results.length) {
return $('.place-name-container').text('Could not find ' + placeName + '!');
}
$('.place-name-container').text(res.results[0].formatted_address);
var location = res.results[0].geometry.location;
var today = new Date();
var start = new Date(today.getFullYear(), 0, 1, 12, 0, 0, 0, 0);
var end = new Date(today.getFullYear()+1, 0, 1, 12, 0, 0, 0, 0);
for (var d = start, i=0; d < end; d.setDate(d.getDate() + 1), i++) {
var time = sunCalc.getTimes(d, location.lat, location.lng);
var isToday = false;
if(d.getDate() === today.getDate() && d.getMonth() === today.getMonth()) {
console.log('Today!');
console.log(d);
isToday = true;
}
self._updateToday(time);
self._updateLine(i, time, isToday);
times.push(time);
dates.push(new Date(d));
}
self._updateAverages(times);
});
this.times = times;
this.dates = dates;
};
Viz.prototype._updateToday = function(times) {
};
Viz.prototype._updateAverages = function(times) {
var avgSunrise = 0, avgSunset = 0;
_.each(times, function(time, i) {
var sunrise = new Date(time.sunrise);
var sunset = new Date(time.sunset);
if(sunset.getDate() !== sunrise.getDate()) {
if(dayOfYear(sunrise) !== i) {
avgSunrise -= 24;
} else {
avgSunset += 24;
}
}
avgSunset += sunset.getHours() + sunset.getMinutes() / 60;
avgSunrise += sunrise.getHours() + sunrise.getMinutes() / 60;
});
avgSunset /= times.length;
avgSunrise /= times.length;
avgSunrise = (avgSunrise + 24) % 24;
avgSunset = (avgSunset + 24) % 24;
var avg = this.svg.select('g.average');
var self = this;
avg.select('path.sunrise')
.transition()
.delay(150)
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(avgSunrise))
.horizontalLineTo(self.x(times.length))
.end();
});
avg.select('path.sunset')
.transition()
.delay(150)
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(avgSunset))
.horizontalLineTo(self.x(times.length))
.end();
});
var format = d3.time.format('%I:%M %p');
var getTimeZone = function() {
return /\((.*)\)/.exec(new Date().toString())[1];
};
var formatHour = function(n) {
var d = new Date();
var hour = Math.floor(n);
var minutes = n - Math.floor(n);
minutes = Math.round(minutes * 60);
d.setHours(hour);
d.setMinutes(minutes);
return format(d) + ' (' + getTimeZone() + ')';
};
avg.select('text.sunrise')
.transition()
.delay(150)
.duration(1500)
.style('opacity', 1)
.attr('y', function() {
if(avgSunrise < 4) {
return self.y(avgSunrise) + 20;
}
return self.y(avgSunrise) - 7;
})
.text(function() {
return 'Average Sunrise: ' + formatHour(avgSunrise);
});
avg.select('text.sunset')
.transition()
.delay(150)
.duration(1500)
.style('opacity', 1).attr('y', function() {
if(avgSunset < 4) {
return self.y(avgSunset) + 20;
}
return self.y(avgSunset) - 7;
})
.text(function() {
return 'Average Sunset: ' + formatHour(avgSunset);
});
};
Viz.prototype._updateLine = function(i, times, today) {
var sunrise = new Date(times.sunrise);
var sunset = new Date(times.sunset);
today = today || false;
var self = this;
var group = this.svg.selectAll('g.day').filter(function(d, idx) {
return i === idx;
});
var start = self.y(sunrise.getHours() + sunrise.getMinutes() / 60);
var end = self.y(sunset.getHours() + sunset.getMinutes() / 60);
if(start < end) {
group
.select('path.day')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), start)
.verticalLineTo(end)
.end();
});
group
.select('path.day-wrap')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), self.y(24))
.verticalLineTo(self.y(24))
.end();
})
.style('stroke-width', 0);
} else {
group
.select('path.day')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), 0)
.verticalLineTo(end)
.end();
});
group
.select('path.day-wrap')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), start)
.verticalLineTo(self.y(24))
.end();
})
.style('stroke-width', (today) ? 2 : 0.5);
}
}
Viz.prototype._drawDay = function(i) {
var today = dayOfYear(new Date()) === i;
var self = this;
var group = this.svg.append('g').classed('day', true);
group
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(i + 0.5), self.y(11.9))
.verticalLineTo(self.y(12.1))
.end();
})
// .style('stroke-width', self.x(i+1) - self.x(i) - .5)
.style('stroke-width', function() {
if(today) {
return 2;
}
return 0.5;
})
.classed('day', true)
.classed('today', today);
group
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(i + 0.5), self.y(24))
.verticalLineTo(self.y(24))
.end();
})
.classed('day-wrap', true)
.classed('today', today);
};
Viz.prototype.destroy = function() {
// destroy d3 object
};
module.exports = Viz;
| mathisonian/sunrise | src/js/viz/viz.js | JavaScript | mit | 11,928 |
// All symbols in the `Runic` script as per Unicode v10.0.0:
[
'\u16A0',
'\u16A1',
'\u16A2',
'\u16A3',
'\u16A4',
'\u16A5',
'\u16A6',
'\u16A7',
'\u16A8',
'\u16A9',
'\u16AA',
'\u16AB',
'\u16AC',
'\u16AD',
'\u16AE',
'\u16AF',
'\u16B0',
'\u16B1',
'\u16B2',
'\u16B3',
'\u16B4',
'\u16B5',
'\u16B6',
'\u16B7',
'\u16B8',
'\u16B9',
'\u16BA',
'\u16BB',
'\u16BC',
'\u16BD',
'\u16BE',
'\u16BF',
'\u16C0',
'\u16C1',
'\u16C2',
'\u16C3',
'\u16C4',
'\u16C5',
'\u16C6',
'\u16C7',
'\u16C8',
'\u16C9',
'\u16CA',
'\u16CB',
'\u16CC',
'\u16CD',
'\u16CE',
'\u16CF',
'\u16D0',
'\u16D1',
'\u16D2',
'\u16D3',
'\u16D4',
'\u16D5',
'\u16D6',
'\u16D7',
'\u16D8',
'\u16D9',
'\u16DA',
'\u16DB',
'\u16DC',
'\u16DD',
'\u16DE',
'\u16DF',
'\u16E0',
'\u16E1',
'\u16E2',
'\u16E3',
'\u16E4',
'\u16E5',
'\u16E6',
'\u16E7',
'\u16E8',
'\u16E9',
'\u16EA',
'\u16EE',
'\u16EF',
'\u16F0',
'\u16F1',
'\u16F2',
'\u16F3',
'\u16F4',
'\u16F5',
'\u16F6',
'\u16F7',
'\u16F8'
]; | mathiasbynens/unicode-data | 10.0.0/scripts/Runic-symbols.js | JavaScript | mit | 1,010 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_TESTS_COUNTED_HPP_INCLUDED
#define CPPCORO_TESTS_COUNTED_HPP_INCLUDED
struct counted
{
static int default_construction_count;
static int copy_construction_count;
static int move_construction_count;
static int destruction_count;
int id;
static void reset_counts()
{
default_construction_count = 0;
copy_construction_count = 0;
move_construction_count = 0;
destruction_count = 0;
}
static int construction_count()
{
return default_construction_count + copy_construction_count + move_construction_count;
}
static int active_count()
{
return construction_count() - destruction_count;
}
counted() : id(default_construction_count++) {}
counted(const counted& other) : id(other.id) { ++copy_construction_count; }
counted(counted&& other) : id(other.id) { ++move_construction_count; other.id = -1; }
~counted() { ++destruction_count; }
};
#endif
| lewissbaker/cppcoro | test/counted.hpp | C++ | mit | 1,141 |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 27 18:31:59 2017
@author: katsuya.ishiyama
"""
from numpy import random
# Definition of module level constants
SUCCESS_CODE = 1
FAILURE_CODE = 0
class Strategy():
def __init__(self, n):
_success_probability = _generate_success_probability(n)
_strategy = {i: p for i, p in enumerate(_success_probability, 1)}
self._n = n
self.strategy = _strategy
self.stock_of_strategy = list(_strategy.keys())
self.tried_strategy = []
self.current_strategy = None
self.previous_strategy = None
self.count_same_strategy = 0
self._result_of_trial = None
def choose_strategy(self):
if not self.stock_of_strategy:
raise ValueError('There is no strategy in stock.')
_chosen_id = random.choice(self.stock_of_strategy, 1)[0]
self.previous_strategy = self.current_strategy
self.current_strategy = _chosen_id
self.count_same_strategy = 0
self.stock_of_strategy.remove(_chosen_id)
_chosen_strategy = {
'chosen_strategy': _chosen_id,
'success_probability': self._get_success_probability()
}
return _chosen_strategy
def _get_success_probability(self):
return self.strategy[self.current_strategy]
def try_strategy(self):
if not self.current_strategy:
raise ValueError('No strategy is chosen.')
self.tried_strategy.append(self.current_strategy)
self._result_of_trial = _get_trial_result(
p=self._get_success_probability()
)
if self.current_strategy == self.previous_strategy:
self.count_same_strategy += 1
return self._result_of_trial
def _get_trial_result(p):
_trial_result = random.choice([FAILURE_CODE, SUCCESS_CODE], size=1, p=[1 - p, p])
return _trial_result[0]
def _generate_success_probability(size):
return random.sample(size)
| Katsuya-Ishiyama/simulation | strategy/strategy.py | Python | mit | 2,013 |
# 美化网站导航
## 前提条件
* [语法](http://www.jianshu.com/p/7d2c5f36702b)
* [Flex 布局](http://www.jianshu.com/p/b2b48c39450b)
* [CSS 常用属性概览](http://www.jianshu.com/p/b2889973263f)
* 会用 Chrome 审查元素
## 概要
类型:总结
难度:简单
## 任务描述
将之前做的导航页,外观如下图所示

要求:
1. 外观要和上图一样。通过用浏览器的开发工具去审查页面的元素来做。页面地址-> https://zhifeclub.github.io/front-end-learn/zero/nav/#course
1. 鼠标移动到左侧导航和右侧的链接上的效果,要和上页面一致。
| zhiFEclub/front-end-learn | resource/task/css/beautify/README.md | Markdown | mit | 756 |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Eloquent\SoftDeletes;
class CreateImagesTable extends Migration
{
//use SoftDeletes;
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('type', 50);
$table->string('filename', 500);
$table->integer('signup_id');
$table->timestamps();
//$table->softDeletes();
$table->foreign('signup_id')->references('id')->on('signups');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
| timitek/GetRealTLanding | database/migrations/2017_10_24_142738_create_images_table.php | PHP | mit | 908 |
package de.v13dev.designpatterns.util;
import java.util.List;
/**
* Created by stebo on 22.03.17.
*/
public class TestHelper {
public static boolean isSortedAscending(List<Integer> list) {
if(list.size() < 2) return true;
for(int i = 1; i < list.size(); i++) {
if(list.get(i - 1) > list.get(i)) {
return false;
}
}
return true;
}
public static boolean isSortedDescending(List<Integer> list) {
if(list.size() < 2) return true;
for(int i = 1; i < list.size(); i++) {
if(list.get(i - 1) < list.get(i)) {
return false;
}
}
return true;
}
}
| ste-bo/designpatterns | src/test/java/de/v13dev/designpatterns/util/TestHelper.java | Java | mit | 705 |
import { FormGroup } from '@angular/forms';
export class PasswordMatchValidator {
static validate(passwordFormGroup: FormGroup) {
const password = passwordFormGroup.controls.password.value;
const repeatPassword =
passwordFormGroup.controls.password_confirmation.value;
if (repeatPassword.length <= 0) {
return null;
}
if (repeatPassword !== password) {
return {
doesMatchPassword: true
};
}
return null;
}
}
| aviabird/angularspree | src/app/shared/custom-validator/password-match-validator.ts | TypeScript | mit | 475 |
<?php
namespace DTR\CrawlerBundle\Services\Crawler;
use DTR\CrawlerBundle\Services\Algorithms\PatternIdentifierInterface;
use DTR\CrawlerBundle\Services\Inspectors\ComponentInspector;
use Symfony\Component\DomCrawler\Crawler;
class MenuCrawler implements CrawlerInterface
{
/**
* @var ComponentInspector
*/
private $component_inspector;
/**
* @var PatternIdentifierInterface
*/
private $pattern;
/**
* @param ComponentInspector $component_inspector
*/
public function __construct(ComponentInspector $component_inspector)
{
$this->component_inspector = $component_inspector;
}
/**
* @param PatternIdentifierInterface $pattern
* @return CrawlerInterface
*/
public function setPattern(PatternIdentifierInterface $pattern)
{
$this->pattern = $pattern;
return $this;
}
/**
* @param $url
* @return array
*/
public function getMenu($url)
{
$contents = $this->chewUrl($url);
$crawler = new Crawler($contents);
$product_html = $this->pattern->getProductHtmlCollection($crawler);
$products = array();
foreach($product_html as $product_dom)
{
$collection = $this->getProductValues($product_dom);
foreach($collection as $product)
$products[] = $product;
}
$logo = $this->getLogo($crawler->filter('body'));
if(empty($logo))
$logo = $products[0]['image'];
return [
'logo' => $logo,
'products' => $products
];
}
/**
* @param Crawler $body
* @return string
*/
public function getLogo(Crawler $body)
{
$all_elements = $body->filter('*')->slice(1);
foreach($all_elements as $element)
{
if($element->hasAttributes())
{
$attr_str = '';
foreach($element->attributes as $attr)
$attr_str .= $attr->nodeName. ' '. $attr->nodeValue. ' ';
if(preg_match_all('/logo/i', $attr_str) > 0)
{
$element = new Crawler($element);
$element = $element->filter('img');
if($element->getNode(0) != null)
return $this->component_inspector->getSource($element);
}
}
}
return '';
/*$all_elements = $all_elements->reduce(function(Crawler $element) {
$classes = $element->extract([ 'class' ]);
if(empty($classes[0]))
return false;
if(preg_match_all('/logo/i', $classes[0]) == 0)
return false;
$image = $element->filter('img');
if($image->getNode(0) == null)
return false;
return true;
});
$logo = '';
if($all_elements->getNode(0) != null)
$logo = $this->component_inspector->getSource($all_elements->first());
return $logo;*/
}
/**
* @param Crawler $product_dom
* @return array
*/
public function getProductValues(Crawler $product_dom)
{
$image = $this->component_inspector->getImage($product_dom);
$title = $this->component_inspector->getTitle($product_dom);
$description = $this->component_inspector->getDescription($product_dom);
list($blocks, $prices) = $this->component_inspector->getPriceInfo($product_dom);
$price_count = count($prices);
$values = array();
if($price_count == 1)
{
$values[] = [
'image' => $image,
'title' => $title,
'description' => $description,
'price' => $this->component_inspector->getPriceFormat($prices[0])
];
}
else
{
for($p = 0; $p != $price_count; ++$p)
{
$diff = $this->component_inspector->getPriceDifferences($blocks[$p], $prices, $prices[$p]);
$price = $this->component_inspector->getPriceFormat($prices[$p]);
$values[] = [
'image' => $image,
'title' => $diff. ' '. $title,
'description' => $description,
'price' => $price
];
}
}
return $values;
}
/**
* @param string $url
* @return string
*/
public function chewUrl($url)
{
$url_parts = parse_url($url);
$base_url = $url_parts['scheme']. '://'. $url_parts['host'];
$this->component_inspector->setBaseUrl($base_url);
return $this->getUrlContents($url);
}
/**
* @param $url string
* @return string
*/
public function getUrlContents($url)
{
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($curl_handle);
curl_close($curl_handle);
return ($contents === FALSE) ? $this->getUrlContents($url) : $contents;
}
} | nfqakademija/dydis-turi-reiksme | src/DTR/CrawlerBundle/Services/Crawler/MenuCrawler.php | PHP | mit | 5,270 |
module Effective
module Providers
module Free
extend ActiveSupport::Concern
def free
raise('free provider is not available') unless EffectiveOrders.free?
@order ||= Order.find(params[:id])
EffectiveResources.authorize!(self, :update, @order)
unless @order.free?
flash[:danger] = 'Unable to process free order with a non-zero total'
redirect_to effective_orders.order_path(@order)
return
end
order_purchased(
payment: 'free order. no payment required.',
provider: 'free',
card: 'none',
purchased_url: free_params[:purchased_url]
)
end
def free_params
params.require(:free).permit(:purchased_url, :declined_url)
end
end
end
end
| code-and-effect/effective_orders | app/controllers/effective/providers/free.rb | Ruby | mit | 809 |
body {
font-size: 1.0em;
} | simplyianm/clububer | themes/2point0/fontsize/large.css | CSS | mit | 27 |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover">
<meta name="theme-color" content="#03375F">
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAARdEBQWL0JrVWMnHBQwFwaK_ZtOfH9T4"></script>
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/icons/16x16.png">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Nextzy">
<link rel="apple-touch-icon" href="%PUBLIC_URL%/icons/16x16.png">
<meta name="msapplication-TileImage" content="%PUBLIC_URL%/icons/16x16.png">
<meta name="msapplication-TileColor" content="#03375F">
<meta property="og:url" content="https://nextzy.me/" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Nextzy Technologies" />
<meta property="og:description" content="We are pirates. We sail and hunt the best mobile and web solution." />
<meta property="og:image" content="https://nextzy.me/images/thumbnail.jpg" />
<meta property="og:image:alt" content="Nextzy goes to the moon." />
<meta name='twitter:url' content='https://nextzy.me/' />
<meta name='twitter:title' content='Nextzy Technologies' />
<meta name='twitter:description' content='We are pirates. We sail and hunt the best mobile and web solution.' />
<meta name='twitter:image' content='https://nextzy.me/images/thumbnail.jpg' />
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<title>Nextzy Technologies</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
| Nextzy/client-nextzy-landing-page-2017 | public/index.html | HTML | mit | 3,000 |
package fr.aumgn.bukkitutils.geom;
import fr.aumgn.bukkitutils.geom.direction.VectorDirection;
import fr.aumgn.bukkitutils.geom.vector.VectorIterator;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import java.util.Iterator;
/**
* Immutable Vector class.
* Inspired from WorldEdit.
*/
public class Vector implements Iterable<Vector> {
private final double x, y, z;
public Vector() {
this.x = 0;
this.y = 0;
this.z = 0;
}
public Vector(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(Location loc) {
this(loc.getX(), loc.getY(), loc.getZ());
}
public Vector(Entity entity) {
this(entity.getLocation());
}
public Vector(Block block) {
this(block.getX(), block.getY(), block.getZ());
}
public double getX() {
return x;
}
public Vector setX(double x) {
return new Vector(x, y, z);
}
public int getBlockX() {
return (int) Math.round(x);
}
public double getY() {
return y;
}
public Vector setY(double y) {
return new Vector(x, y, z);
}
public int getBlockY() {
return (int) Math.round(y);
}
public double getZ() {
return z;
}
public Vector setZ(double z) {
return new Vector(x, y, z);
}
public int getBlockZ() {
return (int) Math.round(z);
}
public Vector add(double i) {
return new Vector(this.x + i, this.y + i, this.z + i);
}
public Vector add(double ox, double oy, double oz) {
return new Vector(x + ox, y + oy, z + oz);
}
public Vector add(Vector other) {
return new Vector(x + other.x, y + other.y, z + other.z);
}
public Vector addX(double ox) {
return new Vector(x + ox, y, z);
}
public Vector addY(double oy) {
return new Vector(x, y + oy, z);
}
public Vector addZ(double oz) {
return new Vector(x, y, z + oz);
}
public Vector subtract(double i) {
return new Vector(x - i, y - i, z - i);
}
public Vector subtract(double ox, double oy, double oz) {
return new Vector(x - ox, y - oy, z - oz);
}
public Vector subtract(Vector other) {
return new Vector(x - other.x, y - other.y, z - other.z);
}
public Vector subtractX(double ox) {
return new Vector(x - ox, y, z);
}
public Vector subtractY(double oy) {
return new Vector(x, y - oy, z);
}
public Vector subtractZ(double oz) {
return new Vector(x, y, z - oz);
}
public Vector multiply(double i) {
return new Vector(x * i, y * i, z * i);
}
public Vector multiply(double ox, double oy, double oz) {
return new Vector(x * ox, y * oy, z * oz);
}
public Vector multiply(Vector other) {
return new Vector(x * other.x, y * other.y, z * other.z);
}
public Vector divide(double i) {
return new Vector(x / i, y / i, z / i);
}
public Vector divide(double ox, double oy, double oz) {
return new Vector(x / ox, y / oy, z / oz);
}
public Vector divide(Vector other) {
return new Vector(x / other.x, y / other.y, z / other.z);
}
public Vector getMiddle(Vector other) {
return new Vector(
(x + other.x) / 2,
(y + other.y) / 2,
(z + other.z) / 2);
}
public boolean isInside(Vector min, Vector max) {
return x >= min.x && x <= max.x
&& y >= min.y && y <= max.y
&& z >= min.z && z <= max.z;
}
public boolean isZero() {
return x == 0.0 && y == 0.0 && z == 0;
}
public Vector positive() {
return new Vector(Math.abs(x), Math.abs(y), Math.abs(z));
}
public double lengthSq() {
return x * x + y * y + z * z;
}
public double length() {
return Math.sqrt(lengthSq());
}
public double distanceSq(Vector other) {
return subtract(other).lengthSq();
}
public double distance(Vector other) {
return subtract(other).length();
}
public Vector normalize() {
return divide(length());
}
public Vector2D to2D() {
return new Vector2D(x, z);
}
public Block toBlock(World world) {
return world.getBlockAt(getBlockX(), getBlockY(), getBlockZ());
}
public Direction toDirection() {
if (isZero()) {
return Direction.NONE;
}
return new VectorDirection(this);
}
public Direction towards(Vector to) {
return to.subtract(this).toDirection();
}
public org.bukkit.util.Vector toBukkit() {
return new org.bukkit.util.Vector(x, y, z);
}
public Location toLocation(World world) {
return toLocation(world, 0.0f, 0.0f);
}
public Location toLocation(World world, Vector2D direction) {
return toLocation(world, direction.toDirection());
}
public Location toLocation(World world, Direction dir) {
return toLocation(world, dir.getYaw(), dir.getPitch());
}
public Location toLocation(World world, float yaw, float pitch) {
return new Location(world, x, getBlockY() + 0.1, z, yaw, pitch);
}
@Override
public Iterator<Vector> iterator() {
return new VectorIterator(new Vector(), this);
}
public Iterable<Vector> rectangle(final Vector max) {
return new Iterable<Vector>() {
@Override
public Iterator<Vector> iterator() {
return new VectorIterator(Vector.this, max);
}
};
}
@Override
public String toString() {
return "(" + x + ", " + y + ", " + z + ")";
}
@Override
public int hashCode() {
return new HashCodeBuilder(23, 11)
.append(x)
.append(y)
.append(z)
.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Vector)) {
return false;
}
Vector o = (Vector) obj;
return x == o.x && y == o.y && z == o.z;
}
public boolean equalsBlock(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Vector)) {
return false;
}
Vector other = (Vector) obj;
return getBlockX() == other.getBlockX()
&& getBlockY() == other.getBlockY()
&& getBlockZ() == other.getBlockZ();
}
}
| aumgn/BukkitUtils | src/main/java/fr/aumgn/bukkitutils/geom/Vector.java | Java | mit | 6,906 |
/**
* Central storage with in-memory cache
*/
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const app = process.type === 'renderer'
? require('electron').remote.app
: require('electron').app;
const _defaultDir = path.join(app.getPath('userData'), 'data');
const _storage = {};
function getPath(options) {
if(options.prefix) {
return path.join(_defaultDir, options.prefix, options.fileName);
}
return path.join(_defaultDir, options.fileName);
}
function ensureDirectoryExists(dir) {
if (!fs.existsSync(dir)){
mkdirp.sync(dir);
}
}
function ensurePrefixExists(prefix) {
ensureDirectoryExists(path.join(_defaultDir, prefix));
}
ensureDirectoryExists(_defaultDir);
const Storage = {};
Storage.set = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
_storage[file] = options.value;
fs.writeFile(file, options.value, callback);
};
Storage.get = function(options, callback) {
const file = getPath(options);
if(file in _storage) {
callback(null, _storage[file]);
return;
}
fs.readFile(file, callback);
};
Storage.append = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
if(!(file in _storage)) {
_storage[file] = [];
}
_storage[file].push(options.value);
fs.appendFile(file, options.value, callback);
};
Storage.delete = function(options, callback) {
const file = getPath(options);
delete _storage[file];
fs.unlink(file, callback);
};
module.exports = Storage;
| scholtzm/punk | src/utils/storage.js | JavaScript | mit | 1,642 |
<?php
class HtmlTest extends \Codeception\TestCase\Test
{
/**
* @var \CodeGuy
*/
protected $codeGuy;
public function testSend()
{
$instance = new \Hahns\Response\Html();
$response = $instance->send('<h1>hello world</h1>');
$this->assertEquals('<h1>hello world</h1>', $response);
$response = $instance->send('');
$this->assertEquals('', $response);
try {
$instance->send([]);
$this->fail();
} catch (InvalidArgumentException $e) { }
try {
$instance->send('', 'as');
$this->fail();
} catch (InvalidArgumentException $e) { }
}
} | pklink/Hahns | tests/unit/Response/HtmlTest.php | PHP | mit | 680 |
require 'spec_helper'
describe AdminsController do
describe 'attempting to access the admin dashboard when not logged in' do
before :each do
get :index, {:id => 2}
end
it 'should redirect to the login page' do
response.should be_redirect
response.should redirect_to('/login')
end
end
end
| Berkeley-BCEF/IntakeApp | spec/controllers/admin_controller_spec.rb | Ruby | mit | 343 |
<?php
header("Access-Control-Allow-Origin:*");
?>
<html>
<head>
<title>TESTS AJAX</title>
<style type="text/css">
.bouton,.obj_prec{
margin-left:4px;
color:blue;
font-size:14px;
font-weight:bold;
cursor:pointer;
}
.bouton:hover{
color:#ccc;
}
#log{
border:1px solid red;
background-color:pink;
}
</style>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function recreer_liste(){
$( "p#result" ).hide( 200, function() {
$( "p#result" ).html('');
afficher();
});
}
function afficher(){
$.ajax({
type:"GET",
url:"http://sfrest.local/app_dev.php/notes.json",
contentType:"text/plain",
dataType:"json",
cache:false,
data:{limit:$("#nb_mess").val()},
success:function(data,status,jqXHR){
showData2(data);
},
error: function (jqXHR,status) {
messager(status,'Affichage Erreur');
}
});
}
function showData2(data){ // de benjamin
messager(data,'Affichage OK');
$("p#result").append($("<ul>"));
$.each(data.notes,function(i,item){
$("p#result ul").append($('<li>'+item.message+' ('+i+')<span num="'+i+'" class="bouton item">Supprimer</span></li>'));
});
$("p#result").show(400);
$(".item").click(function() {
//alert($(this).attr('num'));
remover($(this).attr('num'));
});
}
function remover(n){
$.ajax({
type:"GET",
url:'http://sfrest.local/app_dev.php/notes/'+n+'/remove',
contentType:"text/plain",
dataType:"json",
data:{id:n},
success:function(result){
messager(result,'Suppr OK');
},
error: function (jqXHR,status) {
messager(status + JSON.stringify(jqXHR),'Suppr Erreur');
}
});
recreer_liste();
//setTimeout(recreer_liste,2000);
}
function ajouter(m){
$.ajax({
type: "POST",
url: "http://sfrest.local/app_dev.php/notes.json",
data: {'note[message]':m},
dataType: "json",
success:function(result,status,jqXHR){
messager(result,'Ajout OK');
messager(jqXHR,'Ajout OK');
},
error: function (jqXHR,status) {
messager(status + JSON.stringify(jqXHR),'Ajout Erreur');
}
});
recreer_liste();
}
function messager(mess,quoi){
if(typeof(mess)=='object'){
mess = JSON.stringify(mess);
c = '<div class="obj_prec">Objet</div>';
c += '<div style="display:none">'+mess+'</div>';
$("#log").html(c + $("#log").html());
}else{
$("#log").html(mess+'<br>'+$("#log").html());
}
d = new Date();
dts = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
$("#log").html('['+dts+'] '+$("#log").html());
if(quoi!=undefined){
$("#log").html(quoi+' : '+$("#log").html());
}
$(".obj_prec").click(function() {
$(this).next().toggle();
});
}
$(document).ready(function(){
$("#envoie").click(function() {
ajouter($("#message").val());
});
$("#rafraichir").click(function() {
recreer_liste();
});
afficher();
});
</script>
</head>
<body>
<div id="menus">
Afficher : <input type="text" id="nb_mess" value="10" style="width:30px;"> <span id="rafraichir" class="bouton">Rafraichir</span>
<br><br><input type="text" id="message"> <span id="envoie" class="bouton">Ajouter</span>
</div>
<div id="conteneur" style="min-height:400px;">
<p id="result"></p>
</div>
<div id="log">
</div>
</body>
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
| jc-miralles/WebSymfony | web/tests_ajax.php | PHP | mit | 4,802 |
#include <stdlib.h>
#include "sway/commands.h"
#include "log.h"
struct cmd_results *bar_cmd_secondary_button(int argc, char **argv) {
// TODO TRAY
return cmd_results_new(CMD_INVALID, "secondary_button", "TODO TRAY");
}
| taiyu-len/sway | sway/commands/bar/secondary_button.c | C | mit | 222 |
<?php
namespace Nemundo\Package\FontAwesome\Icon;
use Nemundo\Package\FontAwesome\AbstractFontAwesomeIcon;
class TrashIcon extends AbstractFontAwesomeIcon
{
public function getContent()
{
$this->icon = 'trash';
return parent::getContent();
}
} | nemundo/framework | src/Package/FontAwesome/Icon/TrashIcon.php | PHP | mit | 278 |
import { Component, Input } from '@angular/core';
import { Character } from '../../../data/models/character';
import { LinkLocation } from '../../directive/insertLinks/insertLinks.directive';
@Component({
selector: 'lc-character',
templateUrl: 'character.component.html',
styleUrls: [ 'character.component.scss' ],
})
export class CharacterComponent {
@Input() public excludeLinks: LinkLocation[];
@Input() public character: Character;
}
| manuelhuber/LostColonies | src/app/components/character/character.component.ts | TypeScript | mit | 450 |
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coincontroldialog.h"
#include "ui_coincontroldialog.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "txmempool.h"
#include "walletmodel.h"
#include "wallet/coincontrol.h"
#include "init.h"
#include "policy/fees.h"
#include "policy/policy.h"
#include "validation.h" // For mempool
#include "wallet/fees.h"
#include "wallet/wallet.h"
#include <QApplication>
#include <QCheckBox>
#include <QCursor>
#include <QDialogButtonBox>
#include <QFlags>
#include <QIcon>
#include <QSettings>
#include <QString>
#include <QTreeWidget>
#include <QTreeWidgetItem>
QList<CAmount> CoinControlDialog::payAmounts;
CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
bool CoinControlDialog::fSubtractFeeFromAmount = false;
bool CCoinControlWidgetItem::operator<(const QTreeWidgetItem &other) const {
int column = treeWidget()->sortColumn();
if (column == CoinControlDialog::COLUMN_AMOUNT || column == CoinControlDialog::COLUMN_DATE || column == CoinControlDialog::COLUMN_CONFIRMATIONS)
return data(column, Qt::UserRole).toLongLong() < other.data(column, Qt::UserRole).toLongLong();
return QTreeWidgetItem::operator<(other);
}
CoinControlDialog::CoinControlDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::CoinControlDialog),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
// context menu actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this
lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this
unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTransactionHashAction);
contextMenu->addSeparator();
contextMenu->addAction(lockAction);
contextMenu->addAction(unlockAction);
// context menu signals
connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));
// clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// toggle tree/list mode
connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));
// click on checkbox
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int)));
// click on header
#if QT_VERSION < 0x050000
ui->treeWidget->header()->setClickable(true);
#else
ui->treeWidget->header()->setSectionsClickable(true);
#endif
connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));
// ok button
connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
// (un)select all
connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));
// change coin control first column label due Qt4 bug.
// see https://github.com/bitcoin/bitcoin/issues/5716
ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString());
ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 110);
ui->treeWidget->setColumnWidth(COLUMN_LABEL, 190);
ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 320);
ui->treeWidget->setColumnWidth(COLUMN_DATE, 130);
ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 110);
ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transaction hash in this column, but don't show it
ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it
// default view is sorted by amount desc
sortView(COLUMN_AMOUNT, Qt::DescendingOrder);
// restore list mode and sortorder as a convenience feature
QSettings settings;
if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool())
ui->radioTreeMode->click();
if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder"))
sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt()));
}
CoinControlDialog::~CoinControlDialog()
{
QSettings settings;
settings.setValue("nCoinControlMode", ui->radioListMode->isChecked());
settings.setValue("nCoinControlSortColumn", sortColumn);
settings.setValue("nCoinControlSortOrder", (int)sortOrder);
delete ui;
}
void CoinControlDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel() && _model->getAddressTableModel())
{
updateView();
updateLabelLocked();
CoinControlDialog::updateLabels(_model, this);
}
}
// ok button
void CoinControlDialog::buttonBoxClicked(QAbstractButton* button)
{
if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
done(QDialog::Accepted); // closes the dialog
}
// (un)select all
void CoinControlDialog::buttonSelectAllClicked()
{
Qt::CheckState state = Qt::Checked;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
{
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked)
{
state = Qt::Unchecked;
break;
}
}
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state)
ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state);
ui->treeWidget->setEnabled(true);
if (state == Qt::Unchecked)
coinControl->UnSelectAll(); // just to be sure
CoinControlDialog::updateLabels(model, this);
}
// context menu
void CoinControlDialog::showMenu(const QPoint &point)
{
QTreeWidgetItem *item = ui->treeWidget->itemAt(point);
if(item)
{
contextMenuItem = item;
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
copyTransactionHashAction->setEnabled(true);
if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()))
{
lockAction->setEnabled(false);
unlockAction->setEnabled(true);
}
else
{
lockAction->setEnabled(true);
unlockAction->setEnabled(false);
}
}
else // this means click on parent node in tree mode -> disable all
{
copyTransactionHashAction->setEnabled(false);
lockAction->setEnabled(false);
unlockAction->setEnabled(false);
}
// show context menu
contextMenu->exec(QCursor::pos());
}
}
// context menu action: copy amount
void CoinControlDialog::copyAmount()
{
GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT)));
}
// context menu action: copy label
void CoinControlDialog::copyLabel()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL));
}
// context menu action: copy address
void CoinControlDialog::copyAddress()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS));
}
// context menu action: copy transaction id
void CoinControlDialog::copyTransactionHash()
{
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH));
}
// context menu action: lock coin
void CoinControlDialog::lockCoin()
{
if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked)
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed"));
updateLabelLocked();
}
// context menu action: unlock coin
void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->unlockCoin(outpt);
contextMenuItem->setDisabled(false);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
updateLabelLocked();
}
// copy label "Quantity" to clipboard
void CoinControlDialog::clipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// copy label "Amount" to clipboard
void CoinControlDialog::clipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// copy label "Fee" to clipboard
void CoinControlDialog::clipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// copy label "After fee" to clipboard
void CoinControlDialog::clipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// copy label "Bytes" to clipboard
void CoinControlDialog::clipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, ""));
}
// copy label "Dust" to clipboard
void CoinControlDialog::clipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// copy label "Change" to clipboard
void CoinControlDialog::clipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// treeview: sort
void CoinControlDialog::sortView(int column, Qt::SortOrder order)
{
sortColumn = column;
sortOrder = order;
ui->treeWidget->sortItems(column, order);
ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder);
}
// treeview: clicked on header
void CoinControlDialog::headerSectionClicked(int logicalIndex)
{
if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing
{
ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder);
}
else
{
if (sortColumn == logicalIndex)
sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder);
else
{
sortColumn = logicalIndex;
sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc
}
sortView(sortColumn, sortOrder);
}
}
// toggle tree mode
void CoinControlDialog::radioTreeMode(bool checked)
{
if (checked && model)
updateView();
}
// toggle list mode
void CoinControlDialog::radioListMode(bool checked)
{
if (checked && model)
updateView();
}
// checkbox clicked by user
void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
{
if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked)
coinControl->UnSelect(outpt);
else if (item->isDisabled()) // locked (this happens if "check all" through parent node)
item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
else
coinControl->Select(outpt);
// selection changed -> update labels
if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all
CoinControlDialog::updateLabels(model, this);
}
// TODO: Remove this temporary qt5 fix after Qt5.3 and Qt5.4 are no longer used.
// Fixed in Qt5.5 and above: https://bugreports.qt.io/browse/QTBUG-43473
#if QT_VERSION >= 0x050000
else if (column == COLUMN_CHECKBOX && item->childCount() > 0)
{
if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
item->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
#endif
}
// shows count of locked unspent outputs
void CoinControlDialog::updateLabelLocked()
{
std::vector<COutPoint> vOutpts;
model->listLockedCoins(vOutpts);
if (vOutpts.size() > 0)
{
ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
ui->labelLocked->setVisible(true);
}
else ui->labelLocked->setVisible(false);
}
void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
{
if (!model)
return;
// nPayAmount
CAmount nPayAmount = 0;
bool fDust = false;
CMutableTransaction txDummy;
for (const CAmount &amount : CoinControlDialog::payAmounts)
{
nPayAmount += amount;
if (amount > 0)
{
CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0));
txDummy.vout.push_back(txout);
fDust |= IsDust(txout, ::dustRelayFee);
}
}
CAmount nAmount = 0;
CAmount nPayFee = 0;
CAmount nAfterFee = 0;
CAmount nChange = 0;
unsigned int nBytes = 0;
unsigned int nBytesInputs = 0;
unsigned int nQuantity = 0;
bool fWitness = false;
std::vector<COutPoint> vCoinControl;
std::vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
for (const COutput& out : vOutputs) {
// unselect already spent, very unlikely scenario, this could happen
// when selected are spent elsewhere, like rpc or another computer
uint256 txhash = out.tx->GetHash();
COutPoint outpt(txhash, out.i);
if (model->isSpent(outpt))
{
coinControl->UnSelect(outpt);
continue;
}
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->tx->vout[out.i].nValue;
// Bytes
CTxDestination address;
int witnessversion = 0;
std::vector<unsigned char> witnessprogram;
if (out.tx->tx->vout[out.i].scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram))
{
nBytesInputs += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
fWitness = true;
}
else if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address))
{
CPubKey pubkey;
CKeyID *keyid = boost::get<CKeyID>(&address);
if (keyid && model->getPubKey(*keyid, pubkey))
{
nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
}
else
nBytesInputs += 148; // in all error cases, simply assume 148 here
}
else nBytesInputs += 148;
}
// calculation
if (nQuantity > 0)
{
// Bytes
nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here
if (fWitness)
{
// there is some fudging in these numbers related to the actual virtual transaction size calculation that will keep this estimate from being exact.
// usually, the result will be an overestimate within a couple of satoshis so that the confirmation dialog ends up displaying a slightly smaller fee.
// also, the witness stack size value is a variable sized integer. usually, the number of stack items will be well under the single byte var int limit.
nBytes += 2; // account for the serialized marker and flag bytes
nBytes += nQuantity; // account for the witness byte that holds the number of stack items for each input.
}
// in the subtract fee from amount case, we can tell if zero change already and subtract the bytes, so that fee calculation afterwards is accurate
if (CoinControlDialog::fSubtractFeeFromAmount)
if (nAmount - nPayAmount == 0)
nBytes -= 34;
// Fee
nPayFee = GetMinimumFee(nBytes, *coinControl, ::mempool, ::feeEstimator, nullptr /* FeeCalculation */);
if (nPayAmount > 0)
{
nChange = nAmount - nPayAmount;
if (!CoinControlDialog::fSubtractFeeFromAmount)
nChange -= nPayFee;
// Never create dust outputs; if we would, just add the dust to the fee.
if (nChange > 0 && nChange < MIN_CHANGE)
{
CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0));
if (IsDust(txout, ::dustRelayFee))
{
nPayFee += nChange;
nChange = 0;
if (CoinControlDialog::fSubtractFeeFromAmount)
nBytes -= 34; // we didn't detect lack of change above
}
}
if (nChange == 0 && !CoinControlDialog::fSubtractFeeFromAmount)
nBytes -= 34;
}
// after fee
nAfterFee = std::max<CAmount>(nAmount - nPayFee, 0);
}
// actually update labels
int nDisplayUnit = BitcoinUnits::BTC;
if (model && model->getOptionsModel())
nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity");
QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount");
QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee");
QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee");
QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes");
QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput");
QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange");
// enable/disable "dust" and "change"
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0);
// stats
l1->setText(QString::number(nQuantity)); // Quantity
l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount
l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee
l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee
l5->setText(((nBytes > 0) ? ASYMP_UTF8 : "") + QString::number(nBytes)); // Bytes
l7->setText(fDust ? tr("yes") : tr("no")); // Dust
l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change
if (nPayFee > 0)
{
l3->setText(ASYMP_UTF8 + l3->text());
l4->setText(ASYMP_UTF8 + l4->text());
if (nChange > 0 && !CoinControlDialog::fSubtractFeeFromAmount)
l8->setText(ASYMP_UTF8 + l8->text());
}
// turn label red when dust
l7->setStyleSheet((fDust) ? "color:red;" : "");
// tool tips
QString toolTipDust = tr("This label turns red if any recipient receives an amount smaller than the current dust threshold.");
// how many satoshis the estimated fee can vary per byte we guess wrong
assert(nBytes != 0);
double dFeeVary = (double)nPayFee / nBytes;
QString toolTip4 = tr("Can vary +/- %1 satoshi(s) per input.").arg(dFeeVary);
l3->setToolTip(toolTip4);
l4->setToolTip(toolTip4);
l7->setToolTip(toolTipDust);
l8->setToolTip(toolTip4);
dialog->findChild<QLabel *>("labelCoinControlFeeText") ->setToolTip(l3->toolTip());
dialog->findChild<QLabel *>("labelCoinControlAfterFeeText") ->setToolTip(l4->toolTip());
dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip());
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip());
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip());
// Insufficient funds
QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds");
if (label)
label->setVisible(nChange < 0);
}
void CoinControlDialog::updateView()
{
if (!model || !model->getOptionsModel() || !model->getAddressTableModel())
return;
bool treeMode = ui->radioTreeMode->isChecked();
ui->treeWidget->clear();
ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox
ui->treeWidget->setAlternatingRowColors(!treeMode);
QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
int nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
std::map<QString, std::vector<COutput> > mapCoins;
model->listCoins(mapCoins);
for (const std::pair<QString, std::vector<COutput>>& coins : mapCoins) {
CCoinControlWidgetItem *itemWalletAddress = new CCoinControlWidgetItem();
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
QString sWalletAddress = coins.first;
QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
if (sWalletLabel.isEmpty())
sWalletLabel = tr("(no label)");
if (treeMode)
{
// wallet address
ui->treeWidget->addTopLevelItem(itemWalletAddress);
itemWalletAddress->setFlags(flgTristate);
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
// label
itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel);
// address
itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress);
}
CAmount nSum = 0;
int nChildren = 0;
for (const COutput& out : coins.second) {
nSum += out.tx->tx->vout[out.i].nValue;
nChildren++;
CCoinControlWidgetItem *itemOutput;
if (treeMode) itemOutput = new CCoinControlWidgetItem(itemWalletAddress);
else itemOutput = new CCoinControlWidgetItem(ui->treeWidget);
itemOutput->setFlags(flgCheckbox);
itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
// address
CTxDestination outputAddress;
QString sAddress = "";
if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, outputAddress))
{
sAddress = QString::fromStdString(EncodeDestination(outputAddress));
// if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs
if (!treeMode || (!(sAddress == sWalletAddress)))
itemOutput->setText(COLUMN_ADDRESS, sAddress);
}
// label
if (!(sAddress == sWalletAddress)) // change
{
// tooltip from where the change comes from
itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress));
itemOutput->setText(COLUMN_LABEL, tr("(change)"));
}
else if (!treeMode)
{
QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress);
if (sLabel.isEmpty())
sLabel = tr("(no label)");
itemOutput->setText(COLUMN_LABEL, sLabel);
}
// amount
itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->tx->vout[out.i].nValue));
itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.tx->tx->vout[out.i].nValue)); // padding so that sorting works correctly
// date
itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.tx->GetTxTime()));
// confirmations
itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.nDepth));
itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.nDepth));
// transaction hash
uint256 txhash = out.tx->GetHash();
itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex()));
// vout index
itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
// disable locked coins
if (model->isLockedCoin(txhash, out.i))
{
COutPoint outpt(txhash, out.i);
coinControl->UnSelect(outpt); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed"));
}
// set checkbox
if (coinControl->IsSelected(COutPoint(txhash, out.i)))
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
// amount
if (treeMode)
{
itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)nSum));
}
}
// expand all partially selected
if (treeMode)
{
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
ui->treeWidget->topLevelItem(i)->setExpanded(true);
}
// sort view
sortView(sortColumn, sortOrder);
ui->treeWidget->setEnabled(true);
}
| trippysalmon/bitcoin | src/qt/coincontroldialog.cpp | C++ | mit | 29,915 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./4703c69f923e43a33917a8c255df64036726dfab6335e115d802c67dc861f2e5.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | simonmysun/praxis | TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/d8f1da9c79203f326f97696576bf661b5a4a6a656caad0d54b1eb66df7adeb48.html | HTML | mit | 550 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./20c5dddf18a00c634c481d431f5a710d510181165c30d071ad312ba5525cdc86.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | simonmysun/praxis | TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/45c5b6cd2a2a68330c4a637578e70c087de3f640b237407f583fcd162401c7e6.html | HTML | mit | 550 |
###2015-05-22
####python
* [AlessandroZ/LaZagne](https://github.com/AlessandroZ/LaZagne): Credentials recovery project
* [no13bus/baymax](https://github.com/no13bus/baymax): "Hello, I am your personal health companion"
* [nvbn/thefuck](https://github.com/nvbn/thefuck): Magnificent app which corrects your previous console command.
* [vinta/awesome-python](https://github.com/vinta/awesome-python): A curated list of awesome Python frameworks, libraries and software
* [amoffat/snake](https://github.com/amoffat/snake): Full Python Scripting in Vim
* [karan/slack-overflow](https://github.com/karan/slack-overflow): A programmer's best friend, now in Slack.
* [micahflee/onionshare](https://github.com/micahflee/onionshare): Securely and anonymously share a file of any size
* [earwig/git-repo-updater](https://github.com/earwig/git-repo-updater): A console script that allows you to easily update multiple git repositories at once
* [CIFASIS/VDiscover](https://github.com/CIFASIS/VDiscover): A tool to predict vulnerability discovery of binary only programs
* [josephmisiti/awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning): A curated list of awesome Machine Learning frameworks, libraries and software.
* [fchollet/keras](https://github.com/fchollet/keras): Theano-based Deep Learning library (convnets, recurrent neural networks, and more).
* [mitsuhiko/flask](https://github.com/mitsuhiko/flask): A microframework based on Werkzeug, Jinja2 and good intentions
* [kennethreitz/requests](https://github.com/kennethreitz/requests): Python HTTP Requests for Humans.
* [shadowsocks/shadowsocks](https://github.com/shadowsocks/shadowsocks): A fast tunnel proxy that helps you bypass firewalls
* [scikit-learn/scikit-learn](https://github.com/scikit-learn/scikit-learn): scikit-learn: machine learning in Python
* [ipython/ipython](https://github.com/ipython/ipython): Official repository for IPython itself. Other repos in the IPython organization contain things like the website, documentation builds, etc.
* [scrapy/scrapy](https://github.com/scrapy/scrapy): Scrapy, a fast high-level web crawling & scraping framework for Python.
* [ansible/ansible](https://github.com/ansible/ansible): Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy. Avoid writing scripts or custom code to deploy and update your applications automate in a language that approaches plain English, using SSH, with no agents to install on remote systems.
* [django/django](https://github.com/django/django): The Web framework for perfectionists with deadlines.
* [jakubroztocil/httpie](https://github.com/jakubroztocil/httpie): HTTPie is a command line HTTP client, a user-friendly cURL replacement.
* [sampsyo/beets](https://github.com/sampsyo/beets): music library manager and MusicBrainz tagger
* [odoo/odoo](https://github.com/odoo/odoo): Odoo (formerly OpenERP). Open Source Apps To Grow Your Business.
* [reddit/reddit](https://github.com/reddit/reddit): the code that powers reddit.com
* [jorgebastida/awslogs](https://github.com/jorgebastida/awslogs): AWS CloudWatch logs for Humans
* [numenta/nupic](https://github.com/numenta/nupic): Numenta Platform for Intelligent Computing: a brain-inspired machine intelligence platform, and biologically accurate neural network based on cortical learning algorithms.
####go
* [rakyll/boom](https://github.com/rakyll/boom): HTTP(S) load generator, ApacheBench (ab) replacement, written in Go
* [didip/tollbooth](https://github.com/didip/tollbooth): Simple middleware to rate-limit HTTP requests.
* [GoogleCloudPlatform/kubernetes](https://github.com/GoogleCloudPlatform/kubernetes): Container Cluster Manager from Google
* [golang/go](https://github.com/golang/go): The Go programming language
* [schachmat/wego](https://github.com/schachmat/wego): weather app for the terminal
* [timeglass/glass](https://github.com/timeglass/glass): Automated time tracking for Git repositories
* [docker/docker](https://github.com/docker/docker): Docker - the open-source application container engine
* [avelino/awesome-go](https://github.com/avelino/awesome-go): A curated list of awesome Go frameworks, libraries and software
* [Workiva/go-datastructures](https://github.com/Workiva/go-datastructures): Go
20 stars today
Built by
* [gogits/gogs](https://github.com/gogits/gogs): Gogs(Go Git Service) is a painless self-hosted Git Service.
* [juju/ratelimit](https://github.com/juju/ratelimit): Efficient token-bucket-based rate limiter package.
* [RichardKnop/machinery](https://github.com/RichardKnop/machinery): Machinery is an asynchronous task queue/job queue based on distributed message passing.
* [hashicorp/consul](https://github.com/hashicorp/consul): Consul is a tool for service discovery, monitoring and configuration.
* [syncthing/syncthing](https://github.com/syncthing/syncthing): Open Source Continuous File Synchronization
* [gin-gonic/gin](https://github.com/gin-gonic/gin): Gin is a web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
* [google/cadvisor](https://github.com/google/cadvisor): Analyzes resource usage and performance characteristics of running containers.
* [go-martini/martini](https://github.com/go-martini/martini): Classy web framework for Go
* [spf13/hugo](https://github.com/spf13/hugo): A Fast and Flexible Static Site Generator built with love by spf13 in GoLang
* [astaxie/beego](https://github.com/astaxie/beego): beego is an open-source, high-performance web framework for the Go programming language.
* [mislav/anyenv](https://github.com/mislav/anyenv): rbenv-inspired version manager that can be configured to manage versions of ANYTHING
* [hashicorp/vault](https://github.com/hashicorp/vault): A tool for managing secrets.
* [influxdb/influxdb](https://github.com/influxdb/influxdb): Scalable datastore for metrics, events, and real-time analytics
* [Urban4M/go-flagged](https://github.com/Urban4M/go-flagged): Declarative flag parameters as struct tags
* [rapidloop/rtop](https://github.com/rapidloop/rtop): rtop is an interactive, remote system monitoring tool based on SSH
* [mvdan/xurls](https://github.com/mvdan/xurls): Extract urls from text
####cpp
* [yegord/snowman](https://github.com/yegord/snowman): Snowman decompiler
* [atom/electron](https://github.com/atom/electron): Build cross platform desktop apps with web technologies
* [dmlc/dmlc-core](https://github.com/dmlc/dmlc-core): A common code-base for Distributed Machine Learning in C++
* [dmlc/xgboost](https://github.com/dmlc/xgboost): Large-scale and Distributed Gradient Boosting (GBDT, GBRT or GBM) Library, on single node, hadoop yarn and more.
* [nwjs/nw.js](https://github.com/nwjs/nw.js): Call all Node.js modules directly from DOM and enable a new way of writing applications with all Web technologies.
* [dmlc/cxxnet](https://github.com/dmlc/cxxnet): fast, concise, distributed deep learning framework
* [dmlc/minerva](https://github.com/dmlc/minerva): Minerva: a fast and flexible tool for deep learning on multi-GPU. It provides ndarray programming interface, just like Numpy. Python bindings and C++ bindings are both available. The resulting code can be run on CPU or GPU. Multi-GPU support is very easy.
* [libmx3/mx3](https://github.com/libmx3/mx3): a sample project showcasing/collecting cross platform techniques on mobile
* [Itseez/opencv](https://github.com/Itseez/opencv): Open Source Computer Vision Library
* [BVLC/caffe](https://github.com/BVLC/caffe): Caffe: a fast open framework for deep learning.
* [dmlc/lda](https://github.com/dmlc/lda): C++
15 stars today
Built by
* [philsquared/Catch](https://github.com/philsquared/Catch): A modern, C++-native, header-only, framework for unit-tests, TDD and BDD
* [ariya/phantomjs](https://github.com/ariya/phantomjs): Scriptable Headless WebKit
* [sunag/sea3d](https://github.com/sunag/sea3d): An open-source cross-platform file format for games.
* [rethinkdb/rethinkdb](https://github.com/rethinkdb/rethinkdb): An open-source distributed JSON document database with a pleasant and powerful query language.
* [facebook/rocksdb](https://github.com/facebook/rocksdb): A library that provides an embeddable, persistent key-value store for fast storage.
* [mapbox/mapbox-gl-native](https://github.com/mapbox/mapbox-gl-native): C++/OpenGL vector maps library
* [donho/notepad-plus-plus](https://github.com/donho/notepad-plus-plus): Notepad++ official repository
* [fish-shell/fish-shell](https://github.com/fish-shell/fish-shell): The user-friendly command line shell.
* [mongodb/mongo](https://github.com/mongodb/mongo): The Mongo Database
* [racaljk/hosts](https://github.com/racaljk/hosts): google hosts
* [dmlc/wormhole](https://github.com/dmlc/wormhole): Portable, Scalable and Reliable Distributed Machine Learning, support various platforms including Hadoop YARN, MPI, etc.
* [whoozle/android-file-transfer-linux](https://github.com/whoozle/android-file-transfer-linux): Android File Transfer for Linux
* [REhints/HexRaysCodeXplorer](https://github.com/REhints/HexRaysCodeXplorer): Hex-Rays Decompiler plugin for better code navigation
* [ideawu/ssdb](https://github.com/ideawu/ssdb): SSDB - A fast NoSQL database, an alternative to Redis
####javascript
* [typicode/json-server](https://github.com/typicode/json-server): Get a full fake REST API with zero coding in less than 30 seconds (seriously)
* [olistic/warriorjs](https://github.com/olistic/warriorjs): Game written in JavaScript for learning JavaScript and artificial intelligence.
* [allmobilize/amazeui](https://github.com/allmobilize/amazeui): Amaze UI, a mobile-first and modular front-end framework.
* [Famous/famous](https://github.com/Famous/famous): This repo is being deprecated. Please check out http://github.com/famous/
* [Famous/engine](https://github.com/Famous/engine): JavaScript
101 stars today
Built by
* [nodejs/node](https://github.com/nodejs/node): Node.js Foundation - node.js & io.js Convergence
* [facebook/react](https://github.com/facebook/react): A declarative, efficient, and flexible JavaScript library for building user interfaces.
* [ecomfe/echarts](https://github.com/ecomfe/echarts): Enterprise Charts | Github pages : http://ecomfe.github.io/echarts/index-en.html | Email : echarts@baidu.com | Baidu Hi : 1379172 |
* [mbostock/d3](https://github.com/mbostock/d3): A JavaScript visualization library for HTML and SVG.
* [jashkenas/underscore](https://github.com/jashkenas/underscore): JavaScript's utility _ belt
* [getify/You-Dont-Know-JS](https://github.com/getify/You-Dont-Know-JS): A book series on JavaScript. @YDKJS on twitter.
* [bitshadow/iconate](https://github.com/bitshadow/iconate): Transform your icons with trendy animations.
* [mafintosh/hyperfs](https://github.com/mafintosh/hyperfs): A content-addressable union file system build on top of fuse, hyperlog, leveldb and node
* [yyx990803/vue](https://github.com/yyx990803/vue): Intuitive, fast & composable MVVM for building interactive interfaces.
* [meteor/meteor](https://github.com/meteor/meteor): Meteor, an ultra-simple, database-everywhere, data-on-the-wire, pure-Javascript web framework.
* [kolodny/nip](https://github.com/kolodny/nip): Node Input/output Piper
* [angular/angular.js](https://github.com/angular/angular.js): HTML enhanced for web apps
* [daniel-lundin/snabbt.js](https://github.com/daniel-lundin/snabbt.js): Fast animations with javascript and CSS transforms
* [NeXTs/Clusterize.js](https://github.com/NeXTs/Clusterize.js): Tiny vanilla JS plugin to display large data sets easily
* [asarode/termflix](https://github.com/asarode/termflix): Search and stream torrents from your command line
* [lodash/lodash](https://github.com/lodash/lodash): A JavaScript utility library delivering consistency, modularity, performance, & extras.
* [airbnb/javascript](https://github.com/airbnb/javascript): JavaScript Style Guide
* [rackt/react-router](https://github.com/rackt/react-router): A complete routing solution for React.js
* [chjj/blessed](https://github.com/chjj/blessed): A high-level terminal interface library for node.js.
* [driftyco/ionic](https://github.com/driftyco/ionic): Advanced HTML5 mobile development framework and SDK. Build incredible hybrid apps with web technologies you already know and love. Best friends with AngularJS.
####coffeescript
* [atom/atom](https://github.com/atom/atom): The hackable editor
* [willwhitney/hydrogen](https://github.com/willwhitney/hydrogen): Run code inline in Atom using Jupyter kernels
* [jashkenas/coffeescript](https://github.com/jashkenas/coffeescript): Unfancy JavaScript
* [FelisCatus/SwitchyOmega](https://github.com/FelisCatus/SwitchyOmega): Manage and switch between multiple proxies quickly & easily.
* [github/hubot](https://github.com/github/hubot): A customizable life embetterment robot.
* [philc/vimium](https://github.com/philc/vimium): The hacker's browser.
* [slackhq/hubot-slack](https://github.com/slackhq/hubot-slack): CoffeeScript
5 stars today
Built by
* [pimatic/pimatic](https://github.com/pimatic/pimatic): A home automation server and framework for the raspberry pi running on node.js
* [reactioncommerce/reaction-core](https://github.com/reactioncommerce/reaction-core): Core Reaction Commerce package
* [DerMambo/ms-seo](https://github.com/DerMambo/ms-seo): A seo helper package for meteor.js
* [groupon/testium](https://github.com/groupon/testium): integration test library for Node.js that hooks into mocha (and others) to provide a sync api for controlling browsers
* [fragaria/angular-daterangepicker](https://github.com/fragaria/angular-daterangepicker): Angular.js wrapper for dangrossman/bootstrap-daterangepicker
* [clutchski/coffeelint](https://github.com/clutchski/coffeelint): Lint your CoffeeScript.
* [humphreybc/super-simple-tasks](https://github.com/humphreybc/super-simple-tasks): A simple task tracking app written in Coffeescript that uses localStorage and chrome.storage.sync. Both a website and a Google Chrome extension.
* [morrisjs/morris.js](https://github.com/morrisjs/morris.js): Pretty time-series line graphs
* [karma-runner/karma](https://github.com/karma-runner/karma): Spectacular Test Runner for JavaScript
* [quilljs/quill](https://github.com/quilljs/quill): A cross browser rich text editor with an API
* [codecombat/codecombat](https://github.com/codecombat/codecombat): Multiplayer programming game for learning how to code.
* [baconjs/bacon.js](https://github.com/baconjs/bacon.js): FRP (functional reactive programming) library for Javascript
* [brunch/brunch](https://github.com/brunch/brunch): Fast front-end web app build tool with simple declarative config, seamless incremental compilation for rapid development, an opinionated pipeline and workflow, and core support for source maps.
* [ichord/At.js](https://github.com/ichord/At.js): Add Github like mentions autocomplete to your application.
* [nostalgiaz/bootstrap-switch](https://github.com/nostalgiaz/bootstrap-switch): Turn checkboxes and radio buttons in toggle switches.
* [rails/turbolinks](https://github.com/rails/turbolinks): Turbolinks makes following links in your web application faster (use with Rails Asset Pipeline)
* [basecamp/pow](https://github.com/basecamp/pow): Zero-configuration Rack server for Mac OS X
* [koenbok/Framer](https://github.com/koenbok/Framer): Framer - Prototype Interaction and Animation
| larsbijl/trending_archive | 2015-05/2015-05-22.md | Markdown | mit | 15,635 |
/* *******************************************************
* Released under the MIT License (MIT) --- see LICENSE
* Copyright (c) 2014 Ankit Singla, Sangeetha Abdu Jyothi,
* Chi-Yao Hong, Lucian Popa, P. Brighten Godfrey,
* Alexandra Kolla, Simon Kassing
* ******************************************************** */
package ch.ethz.topobench.graph;
public class TestGraph extends Graph {
public TestGraph(String name, int size) {
super(name, size);
}
public TestGraph(String name, int size, int uniformWeight) {
super(name, size, uniformWeight);
}
public boolean addBidirNeighbor(int n1, int n2) {
return super.addBidirNeighbor(n1, n2);
}
public void setNodeWeight(int i, int weight) {
super.setNodeWeight(i, weight);
}
}
| ndal-eth/topobench | src/test/java/ch/ethz/topobench/graph/TestGraph.java | Java | mit | 799 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ryan Hall Media | Front-end Web Designer from Madison, WI</title>
<!--mobile meta-->
<meta name="viewport" content="width=device-width,initial-scale=1,width=device-width,user-scalable=no">
<meta name="HandheldFriendly" content="true" />
<meta name="MobileOptimized" content="320" />
<!--search meta-->
<meta name="description" content="Ryan Hall Media provides modern and professional front-end web design and development using the latest technologies and best techniques Based out of Madison Wi, let me create your identity.">
<meta property="og:image" content="http://www.ryanhallmedia.com/img/ryan.png" />
<meta name="robots" content="all">
<meta name="author" content="Ryan J. Hall">
<meta name="copyright" content="Ryan Hall Media">
<meta name="keywords" content="web, design, web design, front-end web, photography, identity, branding, logo, layout, app design, ios">
<!--favicon-->
<link rel="shortcut icon" href="favicon.ico">
<!-- googlefonts (playfair, roboto) -->
<link href="https://fonts.googleapis.com/css?family=Playfair+Display:400,700|Roboto:500,700,900" rel="stylesheet">
<!-- icon font -->
<link rel="stylesheet" href="css/font-awesome.min.css" media="screen" title="no title" charset="utf-8">
<!-- bulma framework -->
<link rel="stylesheet" href="css/bulma.min.css" media="screen" title="no title" charset="utf-8">
<!-- animations -->
<link rel="stylesheet" href="css/animate.min.css" media="screen" title="no title" charset="utf-8">
<!-- main styles -->
<link rel="stylesheet" href="css/styles.min.css" media="screen" title="no title" charset="utf-8">
<!-- 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="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- external nav -->
<div class="nav-group">
<div class="navigation startnav preanimate">
<!-- logo -->
<a href="index.html" class="logo">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 1000 719.7" style="enable-background:new 0 0 1000 719.7;" xml:space="preserve">
<path class="st0" d="M549.8,396v320.1c0,1.9,1.6,3.5,3.5,3.5H596c1.9,0,3.5-1.6,3.5-3.5V4.5c0-1.9-1.6-3.5-3.5-3.5h-42.8c-1.9,0-3.5,1.6-3.5,3.5
v338c0,1.9-1.6,3.5-3.5,3.5H303.9c-1.9,0-3.5,1.6-3.5,3.5V389c0,1.9,1.6,3.5,3.5,3.5h242.3C548.2,392.5,549.8,394.1,549.8,396z"/>
<path class="st0" d="M652.3,3.3l131.8,303.2c1.2,2.8,5.2,2.8,6.4,0L924.8,3.1c0.6-1.3,1.8-2.1,3.2-2.1h69.4c1.9,0,3.5,1.6,3.5,3.5V716
c0,1.9-1.6,3.5-3.5,3.5h-43.9c-1.9,0-3.5-1.6-3.5-3.5V91.2c0-3.8-5.2-4.9-6.7-1.4L791.6,434.7c-1.2,2.8-5.2,2.8-6.4,0L645.9,116.2
c-0.2-0.4-0.3-0.9-0.3-1.4V4.7C645.6,0.9,650.8-0.2,652.3,3.3z"/>
<path class="st0" d="M214.3,370.6c-3-1.1-3.1-5.3-0.2-6.5c46.1-18.5,93.7-68.1,93.7-176C307.9,73,248.1,1,128.6,1H4.5C2.6,1,1,2.6,1,4.5v38.4
c0,1.9,1.6,3.5,3.5,3.5h119.6c93,0,130.6,59.8,130.6,142.8c0,94.1-36.5,157.2-135,157.2H4.5c-1.9,0-3.5,1.6-3.5,3.5v38.4
c0,1.9,1.6,3.5,3.5,3.5h110.8c112.9,0,133.9,62,133.9,173.8v150.6c0,1.9,1.6,3.5,3.5,3.5h42.8c1.9,0,3.5-1.6,3.5-3.5v-154
C299,464.7,282.8,396.6,214.3,370.6z"/>
</svg>
</a>
<!-- menu button -->
<div class="navbutton">
<span class="menu">MENU</span>
<span class="bars"></span>
</div>
</div>
<!-- hidden nav -->
<div class="side-nav">
<ul>
<li class="items"><a href="index.html">HOME</a></li>
<li class="items"><a href="work.html">WORK</a></li>
<li class="social">
<a href="https://twitter.com/ryanhallmedia" target="_blank"><i class="fa fa-twitter"></i></a>
<a href="https://facebook.com/ryanhallmedia" target="_blank"><i class="fa fa-facebook"></i></a>
<a href="https://behance.net/ryanhallmedia" target="_blank"><i class="fa fa-behance"></i></a>
<a href="http://codepen.io/RyanHallMedia/" target="_blank"><i class="fa fa-codepen"></i></a>
</li>
</ul>
</div>
</div>
<header class="small">
<!-- background lines -->
<div class="linediv lineone preanimate"></div>
<div class="linediv linetwo preanimate"></div>
<div class="bigtext">
<h1 class="preanimate">CONTACT</h1>
</div>
<div class="info">
<h2 class="preanimate">Whether you have a <span class="high">project idea</span> or <br />just a few <span class="high">questions</span>. Drop me a line <br />I'll get back to you <span class="high">right away</span>.</h2>
<a href="work.html" class="buttonbox preanimate">
<span class="text">Back Home</span>
<span class="box"></span>
</a>
</div>
<a href="mailto:ryan@ryanhallmedia.com?Subject=Hi%20There" class="email is-hidden-mobile" target="_top"><span class="preanimate">ryan@ryanhallmedia.com</span></a>
<div class="line linedown preanimate"><div class="linein animated slideInDownLine infinite"></div></div>
<div class="is-overlay preanimate"></div>
</header>
<section class="contact-from">
<!-- background lines -->
<div class="linediv lineone preanimate"></div>
<div class="linediv linetwo preanimate"></div>
<div class="contain text-left has-text-centered">
<div class="form-set preanimate">
<!-- contact form -->
<form id="contactForm" class="form" onSubmit="return checkform(this)" method="post" action="mailer.php" accept-charset="UTF-8">
<div class="inputs columns is-multiline">
<!-- input group -->
<div class="namegroup group column is-12-mobile is-6-tablet">
<!-- form input -->
<input id="fname" class="input" maxlength="40" name="fname" size="20" type="text" required="">
<!-- underline hover -->
<span class="highlight"></span>
<!-- underline -->
<span class="bar"></span>
<!-- form label -->
<label for="fname" class="loglabel">First Name</label>
</div>
<!-- input group -->
<div class="namegroup group column is-12-mobile is-6-tablet">
<!-- form input -->
<input id="lname" class="input" maxlength="40" name="lname" size="20" type="text" required="">
<!-- underline hover -->
<span class="highlight"></span>
<!-- underline -->
<span class="bar"></span>
<!-- form label -->
<label for="lname" class="loglabel">Last Name</label>
</div>
<!-- input group -->
<div class="namegroup group column is-12-mobile is-6-tablet">
<!-- form input -->
<input id="phone" class="input" maxlength="40" name="phone" size="20" type="number" required="">
<!-- underline hover -->
<span class="highlight"></span>
<!-- underline -->
<span class="bar"></span>
<!-- form label -->
<label for="phone" class="loglabel">Phone</label>
</div>
<!-- input group -->
<div class="namegroup group column is-12-mobile is-6-tablet">
<!-- form input -->
<input id="email" class="input" maxlength="40" name="email" size="20" type="email" required="">
<!-- underline hover -->
<span class="highlight"></span>
<!-- underline -->
<span class="bar"></span>
<!-- form label -->
<label for="email" class="loglabel">Email</label>
</div>
<!-- input group -->
<div class="messagegroup group column is-12-mobile is-12-tablet">
<!-- form input -->
<textarea id="message" rows="2" cols="100" name="message" type="message" class="input" style="resize: none;" required=""></textarea>
<!-- underline hover -->
<span class="highlight"></span>
<!-- underline -->
<span class="bar"></span>
<!-- form label -->
<label for="message" class="loglabel">Your Message</label>
</div>
</div>
<!-- button -->
<button type="submit" class="is-disabled submit buttonbox">
<span class="text">Let's Talk</span>
<span class="box"></span>
</button>
</form>
</div>
</div>
</section>
<footer>
<div class="toppart columns is-multiline">
<div class="column is-12-mobile is-8-tablet talk has-text-left">
<h2 class="light">Let's work together.</h2>
<a href="mailto:ryan@ryanhallmedia.com?Subject=Hi%20There" target="_top" class="buttonline">
<span class="line left"></span>
<span class="text">ryan@ryanhallmedia.com</span>
</a>
</div>
<div class="column is-12-mobile is-4-tablet contactinfo light has-text-right">
<span class="num">920.904.7926</span>
<span class="address">639 E. Johnson St.<br />Madison, WI 53703</span>
</div>
</div>
<div class="bottompart columns is-multiline">
<span class="column is-12-mobile is-6-tablet owner">COPYRIGHT ® <script type="text/javascript">document.write((new Date()).getFullYear());</script> | <a href="index.html">Ryan Hall Media</a></span>
<div class="column is-12-mobile is-6-tablet text social has-text-right">
<a href="https://twitter.com/ryanhallmedia" target="_blank"><i class="fa fa-twitter"></i></a>
<a href="https://facebook.com/ryanhallmedia" target="_blank"><i class="fa fa-facebook"></i></a>
<a href="https://behance.net/ryanhallmedia" target="_blank"><i class="fa fa-behance"></i></a>
<a href="http://codepen.io/RyanHallMedia/" target="_blank"><i class="fa fa-codepen"></i></a>
</div>
</div>
</footer>
</body>
<!-- jquery (all) -->
<script src="js/jquery-2.1.3.min.js" type="text/javascript"></script>
<!-- main js file (all) -->
<script src="js/script.min.js" type="text/javascript"></script>
<!-- scroll animate scripts (all) -->
<script src="js/jquery.scrollme.min.js" type="text/javascript"></script>
<!-- fixes styles for older browsers (all) -->
<script src="js/modernizr-custom.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#fname').on('focusout', function(){
if( $(this).val().length === 0 ) {
$(this).addClass('warning');
$('.form').removeClass('name');
} else {
$(this).removeClass('warning');
$('.form').addClass('name');
}
});
$('#email').on('focusout', function(){
if( $(this).val().length === 0 ) {
$(this).addClass('warning');
$('form').removeClass('email');
} else {
$(this).removeClass('warning');
$('.form').addClass('email');
}
});
$('#message').on('focusout', function(){
if( $(this).val().length === 0 ) {
$(this).addClass('warning');
$('.form').removeClass('comment');
} else {
$(this).removeClass('warning');
$('.form').addClass('comment');
}
});
$('.input').on('focusout', function(){
if( $('.form').is('email, .name, .comment')) {
$('.submit').removeClass('is-disabled');
} else {
$('.submit').addClass('is-disabled');
}
});
});
</script>
<!-- google -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-43959511-1', 'auto');
ga('send', 'pageview');
</script>
</html>
| RyanHallMedia/newsite | contact.html | HTML | mit | 12,753 |
<!DOCTYPE html>
<html class="h-100" lang="en">
{% include _head.htm %}
<body>
{% include _cookie_banner.htm %}
{% include _header.htm %}
<div class="min-h-80 docs-container container-fluid">
<div class="row">
<div class="col-xl-3">
<details class="docs-menu" id="docs-menu">
<summary>Other Wiki Pages (click to view)</summary>
<ul>
{% for page in site.pages %}
{% if page.layout == 'wiki'%}
<li>
<a href="{{ page.url }}">{{ page.title }}</a>
</li>
{% endif %}
{% endfor %}
</ul>
</details>
</div>
<div class="col-xl-6" id="main" role="main">
{{ content }}
</div>
<div class="col-xl-3">
<details class="docs-toc">
<summary>Table of Contents (click to view)</summary>
{% assign cur_page = page.path | split: "/" | last%}
{% include _wiki_toc.md page=cur_page %}
</details>
</div>
</div>
</div>
{% include _footer.htm %}
<!-- Core JS Files -->
<script src="/assets/js/core/jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="/assets/js/core/bootstrap-4.6.1.bundle.min.js" type="text/javascript"></script>
<script src="/assets/js/details-element-polyfill.js" type="text/javascript"></script>
<script> //open by dropdown default if on Desktop, but not on Mobile
const breakpoint = parseInt(
getComputedStyle(document.documentElement).getPropertyValue('--breakpoint-xl')
);
if (screen.width >= breakpoint){
document.getElementById("docs-menu").open = true;
}
</script>
</body>
</html>
| barton2526/Gridcoin-Site | _layouts/wiki.html | HTML | mit | 2,158 |
<div class="{{ field_classes|default:'field' }}{% if field.errors %} error{% endif %}">
{{ field }}
{% if field.errors %}
<div class="ui error message">
{% for error in field.errors %}
<p><i class="warning sign icon"></i> <span>{{ error }}</span></p>
{% endfor %}
</div>
{% endif %}
</div>
| alexey-grom/django-userflow | userflow/templates/userflow/forms/_field-short.html | HTML | mit | 363 |
---
layout: post
title: "MySQL Reflection"
date: 2016-11-16
categories: "projects"
assignment: "true"
---
[Link to Github Repository](https://github.com/ldinkins/malily5)
We continued working on the bash script from Assignment 4 by adding a connection to MySQL. First, we created the database malily if it didn't already exist. Then we fed a dump file into the database. Afterwards, we added the current responses to the database and then outputted the database into the dump file. This created an import-export loop that anyone could use this script and the dump file to have access to the information in the table as well as add to the table.
Originally, we didn't make the script like this. We only had it create a database and add information to a table, making it local. To make sure that Lily and I could both access each other's responses, we created the import dump and the export dump. We ran into some troubles with this, mainly syntax problems. To debug, the script had a line before the insert statement that printed the database and a line after that prints the database. We put this line in to make sure that our additions were going in from different systems. Now, there's only one final line that prints the database table. Our syntax problems were from importing the dump, and it took us a while to realize that mysqldump is a separate command and cannot go into the block of mysql commands. One final thing we had to do was sync our databases to make sure that what was in Lily's database was in mine.
Overall, I thought this assignment was a good refresher in working with MySQL. I previously worked with it in Perl, and I had the most trouble with remembering syntax. Stack Overflow really helped with that though. Also, it was great to work with Lily on this. We tried to work on each step together instead of dividing and conquering. On a personal level, I loved explaining things that made more sense to me than they did to her because I think that being able to break down technical concepts verbally reinforces what I already know. It also made clear the points that I didn't know as well as others, and we Googled our way through it. It was a great learning experience. I think it's easy to bulldoze and just do something yourself if you have a better idea of what's going on, but working as a team was much more rewarding and made the assignment fun. | pillaim/pillaim.github.io | _posts/2016-11-16-mysqlReflection.markdown | Markdown | mit | 2,383 |
<?php
/*
Safe sample
input : use fopen to read /tmp/tainted.txt and put the first line in $tainted
Flushes content of $sanitized if the filter number_float_filter is not applied
construction : use of sprintf via a %d with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$handle = @fopen("/tmp/tainted.txt", "r");
if ($handle) {
if(($tainted = fgets($handle, 4096)) == false) {
$tainted = "";
}
fclose($handle);
} else {
$tainted = "";
}
if (filter_var($sanitized, FILTER_VALIDATE_FLOAT))
$tainted = $sanitized ;
else
$tainted = "" ;
$query = sprintf("$temp = '%d';", $tainted);
$res = eval($query);
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_95/safe/CWE_95__fopen__func_FILTER-VALIDATION-number_float_filter__variable-sprintf_%d_simple_quote.php | PHP | mit | 1,502 |
<?php
/*
* This file is part of App/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
namespace App\Validation\Exceptions;
class PostalCodeException extends ValidationException
{
public static $defaultTemplates = [
self::MODE_DEFAULT => [
self::STANDARD => '{{name}} must be a valid postal code on {{countryCode}}',
],
self::MODE_NEGATIVE => [
self::STANDARD => '{{name}} must not be a valid postal code on {{countryCode}}',
],
];
}
| Javier-Solis/admin-project | app/Validation/Exceptions/PostalCodeException.php | PHP | mit | 662 |
The Skills API Platform
=======================
An open platform to store human skills.
Powered by [API Platform](https://api-platform.com/) and [Fansible Tywin](https://github.com/fansible/tywin).
| OpenSkills/skillsapi | README.md | Markdown | mit | 200 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert Before Example</title>
<script>
onload = insertTagBefore;
function insertTagBefore(){
// CREATE A LI TAG
var list = document.createElement("li");
list.innerHTML = "New Item";
// CREATE A REFERENCE TO THE 3rd LIST ITEM
var destination = document.getElementsByTagName("li")[2];
// INSERT THE NEW LIST ITEM BEFORE THE 3rd LIST ITEM
destination.parentNode.insertBefore(list,destination);
}
</script>
<body>
<ol>
<li>Item Number 1</li>
<li>Item Number 2</li>
<li>Item Number 3</li>
<li>Item Number 4</li>
</ol>
</body>
</head>
</html> | joshsager/Code-Examples | JS_DOM_INSERT_BEFORE/index.html | HTML | mit | 687 |
<?php
/******************************/
/* Submission Form Management */
/******************************/
require_once("../includes/admin_init.php");
require_once("../includes/adminAccount.class.php");
require_once("../includes/subForm.class.php");
require_once("../includes/conference.class.php");
/* Intitalize and output header */
initHeader("Submission Form Management");
/* Lets create an instance of the AdminAccount class, which handles administrator's account */
$adminAccount = new AdminAccount();
/* Let's create an instance of the SubForm class, which handles settings for the submission form */
$subForm = new SubForm($adminAccount->getCurrentConference());
/* Let's create an instance of the Conference class, which handles operations with currently selected conference */
$conference = new Conference($adminAccount->getCurrentConference());
/* Initialize page's template file */
$tpl = new Template("../templates/admin/conference_subform.tpl");
/* On user's attempt to add a new topic */
if (isset($_POST["new_topic"])) {
/* Check if Topic Title is entered */
$err_topic_title = empty($_POST["topic"]);
/* If Page Title is entered, add a new topic */
if ( !$err_topic_title ) {
/* Add topic to the DB */
$subForm->addTopic($_POST["topic"]);
/* Send a success message to the user */
$msg_add_success = true;
}
}
/* On user's attempt to delete a topic */
if (isset($_POST["delete_topic"])) {
/* Delete that page */
$subForm->deleteTopic($_POST["delete_topic"]);
/* Send a success message to the user */
$msg_delete_success = true;
}
/* On user's attempt to save submission form notes */
if (isset($_POST["edit_subform_notes"])) {
/* Save notes to the database */
$subForm->editNotes($_POST["subform_notes"]);
/* Show user a success message */
$msg_notes_success = true;
}
/* On user's attempt to save allowed file types */
if (isset($_POST["edit_file_types"])) {
/* Save file types to the database */
$subForm->editFileTypes($_POST["file_types"]);
/* Show user a success message */
$msg_file_types_success = true;
}
/* Lets assign each topic's data to the template file */
$result = $subForm->getAllTopics();
/* Are there any topics yet? */
if (mysqli_num_rows($result)) {
$topics_found = true;
$i = 1;
while ($data = mysqli_fetch_array($result)) {
/* If even iteration, we need to display different style of table */
if ($i % 2 == 0) {
$even = ' class="even"';
} else {
$even = '';
}
/* Assign data for the loop */
$tpl->assignLoop(array(
"TOPICS.ID" => $data['id'],
"TOPICS.TITLE" => $data['topic'],
"TOPICS.EVEN" => $even,
));
$i++;
}
$tpl->parseLoop('TOPICS');
$tpl->parseIf();
/* No topics yet */
} else {
$topics_not_found = true;
}
/* Parse the error/success message(s) */
$tpl->assignIf(array(
"TOPICS_FOUND" => $topics_found,
"TOPICS_NOT_FOUND" => $topics_not_found,
"ERR_TOPIC_TITLE" => $err_topic_title,
"MSG_DELETE_SUCCESS" => $msg_delete_success,
"MSG_ADD_SUCCESS" => $msg_add_success,
"MSG_NOTES_SUCCESS" => $msg_notes_success,
"MSG_FILE_TYPES_SUCCESS" => $msg_file_types_success,
));
$tpl->parseIf();
/* Get conference's configuration */
$conference_data = $conference->getConfiguration();
/* Assign and parse the submission form notes and allowed file types */
$tpl->assignStr(array(
"SUBFORM_NOTES" => $conference_data['subform_notes'],
"SUBFORM_FILE_TYPES" => $conference_data['subform_file_types'],
));
$tpl->parseStr();
/* Output the final HTML code */
$tpl->output();
/* Intitalize and output footer */
initFooter();
?> | jakkub/Confy | src/admin/conference_subform.php | PHP | mit | 3,708 |
'use strict';
/* global $: true */
/* global animation: true */
/* global boidWeights: true */
//Slider for selecting initial number of boids
//---------------------------------------------
$('#numBoidsSlider').slider({
min: 0,
max: 400,
step: 10,
value: animation.numBoids
});
$('#numBoidsVal').text(animation.numBoids);
$('#numBoidsSlider').on('slide', function (slideEvt) {
$('#numBoidsVal').text(slideEvt.value);
animation.numBoids = slideEvt.value;
});
//Sliders for weights
//--------------------
$('#slider1').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.separation
});
$('#slider1val').text(boidWeights.separation);
$('#slider1').on('slide', function (slideEvt) {
$('#slider1val').text(slideEvt.value);
boidWeights.separation = slideEvt.value;
});
$('#slider2').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.alginment
});
$('#slider2').on('slide', function (slideEvt) {
$('#slider2val').text(boidWeights.alginment);
$('#slider2val').text(slideEvt.value);
boidWeights.alginment = slideEvt.value;
});
$('#slider3').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.cohesion
});
$('#slider3val').text(boidWeights.cohesion);
$('#slider3').on('slide', function (slideEvt) {
$('#slider3val').text(slideEvt.value);
boidWeights.cohesion = slideEvt.value;
});
$('#slider4').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.obstacle
});
$('#slider4val').text(boidWeights.obstacle);
$('#slider4').on('slide', function (slideEvt) {
$('#slider4val').text(slideEvt.value);
boidWeights.obstacle = slideEvt.value;
});
$('#slider5').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.predators
});
$('#slider5val').text(boidWeights.predators);
$('#slider5').on('slide', function (slideEvt) {
$('#slider5val').text(slideEvt.value);
boidWeights.predators = slideEvt.value;
});
| johhat/boids | ui-components/ui.js | JavaScript | mit | 1,967 |
package test;
/**
scala> map
res6: java.util.HashMap[String,java.util.List[String]] = {AAA=[BBB, CCC, EEE], CCC=[DDD]}
scala> test.Test.printCompany(map)
-AAA
-BBB
-CCC
-DDD
-EEE
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
public class Test {
public static void printCompany(HashMap<String, List<String>> graph) {
if (graph.size() == 0) return;
HashSet<String> roots = new HashSet<String>();
for (String v : graph.keySet()) {
roots.add(v);
}
for (String v : graph.keySet()) {
for (String l : graph.get(v)) {
roots.remove(l);
}
}
for (String v : roots) {
printCompany(graph, v, 0);
}
}
private static void printCompany(HashMap<String, List<String>> graph, String vertex, int depth) {
printVertex(vertex, depth);
if (graph.containsKey(vertex)) {
for (String v : graph.get(vertex)) {
printCompany(graph, v, depth + 1);
}
}
}
private static void printVertex(String vertex, int depth) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; i++) {
sb.append(" ");
}
sb.append("-");
sb.append(vertex);
System.out.println(sb.toString());
}
}
| sadikovi/algorithms | careercup/company-structure.java | Java | mit | 1,233 |
#!/bin/sh
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
else
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
fi
local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# use filter instead of exclude so missing patterns dont' throw errors
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries
local basename
basename="$(basename "$1" | sed -E s/\\..+// && exit ${PIPESTATUS[0]})"
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/${basename}.framework/${basename}" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\""
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework 'Pods-HWAYCoreData_Tests/HWAYCoreData.framework'
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework 'Pods-HWAYCoreData_Tests/HWAYCoreData.framework'
fi
| cshireman/HWAYCoreData | Example/Pods/Target Support Files/Pods-HWAYCoreData_Tests/Pods-HWAYCoreData_Tests-frameworks.sh | Shell | mit | 2,620 |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
#import "SChartDataPointMapper.h"
@interface SChartRadialDataPointMapper : NSObject <SChartDataPointMapper>
{
id <SChartRadialDataPointMapperSource> _source;
id <SChartErrorHandler> _errorHandler;
}
@property(nonatomic) id <SChartErrorHandler> errorHandler; // @synthesize errorHandler=_errorHandler;
@property(nonatomic) id <SChartRadialDataPointMapperSource> source; // @synthesize source=_source;
- (struct CGPoint)coordinateForDataValues:(CDStruct_c3b9c2ee)arg1 glViewFrame:(struct CGRect)arg2 xAxisRange:(id)arg3 yAxisRange:(id)arg4;
- (CDStruct_c3b9c2ee)dataValuesForCoordinate:(struct CGPoint)arg1 glViewFrame:(struct CGRect)arg2 xAxisRange:(id)arg3 yAxisRange:(id)arg4;
- (double)pixelValueForDataValue:(id)arg1 glViewFrame:(struct CGRect)arg2 internalAxisRange:(id)arg3 axisOrientation:(int)arg4;
- (double)pixelValueOnYAxisForDataValue:(double)arg1 glViewFrame:(struct CGRect)arg2 internalAxisRange:(id)arg3;
- (double)radiusOnYAxisForDataValue:(double)arg1 glViewFrame:(struct CGRect)arg2 internalAxisRange:(id)arg3;
- (double)angleValueOnXAxisForDataValue:(double)arg1 glViewFrame:(struct CGRect)arg2 internalAxisRange:(id)arg3;
- (double)mapDataValueForPixelValue:(double)arg1 glViewFrame:(struct CGRect)arg2 internalAxisRange:(id)arg3 axisOrientation:(int)arg4;
- (double)mapDataValueOnYAxisForPixelValue:(double)arg1 glViewFrame:(struct CGRect)arg2 internalAxisRange:(id)arg3;
- (double)mapDataValueOnXAxisForAngle:(double)arg1 glViewFrame:(struct CGRect)arg2 internalAxisRange:(id)arg3;
- (double)scaleDataValueForPixelValue:(double)arg1 glViewFrame:(struct CGRect)arg2 internalAxisRange:(id)arg3 axisOrientation:(int)arg4;
- (id)initWithSource:(id)arg1 errorHandler:(id)arg2;
@end
| JChanceHud/GearIndicator | Fitness/SChartRadialDataPointMapper.h | C | mit | 1,871 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>W28770_text</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;">
<div style="float: left;">
<a href="index.html">«</a>
</div>
<div style="float: right;">
</div>
</div>
<hr/>
<div style="position: absolute; margin-left: 1168px; margin-top: 191px;">
<p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">A Gyrodata Directional Survey </p>
</div>
<div style="position: absolute; margin-left: 297px; margin-top: 255px;">
<p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Whiting Oil & Gas Lease: Uran Federal Well: #21-24H, 8 3/4" Case and 6" Hole Location: Nabors #112 AC, Mountrail County, North Dakota <br/>Job Number: RD0315DM104 <br/>MEASURED INCL AZIMUTH DOGLEG VERTICAL CLOSURE DEPTH SEVERITY DEPTH DIST. AZIMUTH <br/>feet deg. deg. deg./ feet feet deg. </p>
</div>
<div style="position: absolute; margin-left: 1147px; margin-top: 722px;">
<p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">100 ft. </p>
</div>
<div style="position: absolute; margin-left: 340px; margin-top: 935px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">12344.00 12438.00 12533.00 12628.00 12723.00 </p>
</div>
<div style="position: absolute; margin-left: 340px; margin-top: 1232px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">12818.00 12913.00 13009.00 13103.00 13199.00 </p>
</div>
<div style="position: absolute; margin-left: 340px; margin-top: 1530px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">13293.00 13388.00 13483.00 13578.00 13673 .00 <br/>13768.00 13863.00 13958.00 14053.00 14148.00 </p>
</div>
<div style="position: absolute; margin-left: 340px; margin-top: 2103px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">14243.00 </p>
</div>
<div style="position: absolute; margin-left: 2975px; margin-top: 2273px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2167px; margin-top: 531px;">
<p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">HORIZONTAL COORDINATES feet </p>
</div>
<div style="position: absolute; margin-left: 637px; margin-top: 935px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">92.37 89.09 89.37 89.59 92.20 </p>
</div>
<div style="position: absolute; margin-left: 637px; margin-top: 1232px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">92.96 91.72 89.48 89.71 90.21 <br/>90.18 91.36 90.97 90.91 90.97 <br/>89.93 90.46 91.16 91.13 91.50 </p>
</div>
<div style="position: absolute; margin-left: 637px; margin-top: 2103px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">91.78 </p>
</div>
<div style="position: absolute; margin-left: 850px; margin-top: 935px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">110.25 109.44 109.40 109.52 109.5] </p>
</div>
<div style="position: absolute; margin-left: 850px; margin-top: 1232px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">109.40 107.75 105.31 105.72 105.73 <br/>106.22 106.75 106.19 106.55 106.73 <br/>106.06 107.94 110.13 109.82 110.42 </p>
</div>
<div style="position: absolute; margin-left: 871px; margin-top: 2103px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 1190px; margin-top: 935px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2.83 3.59 0.30 0.26 2.75 </p>
</div>
<div style="position: absolute; margin-left: 1190px; margin-top: 1232px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.81 2.17 3.45 0.50 0.52 <br/>0.52 1.36 0.72 0.38 0.20 <br/>1.30 2.06 2.42 0.33 0.74 </p>
</div>
<div style="position: absolute; margin-left: 1190px; margin-top: 2082px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.41 </p>
</div>
<div style="position: absolute; margin-left: 1423px; margin-top: 935px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">10382.90 10381.70 103 82.98 103 83.84 103 82.36 </p>
</div>
<div style="position: absolute; margin-left: 1423px; margin-top: 1232px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">10378.08 10374.20 10373.20 10373.86 10373.93 <br/>10373.61 10372.33 10370.40 103 68.84 10367.28 <br/>10366.54 10366.22 10364.87 10362.97 10360.79 </p>
</div>
<div style="position: absolute; margin-left: 1423px; margin-top: 2082px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">10358.07 </p>
</div>
<div style="position: absolute; margin-left: 1721px; margin-top: 935px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">3017.4 31 10.8 3205.2 3299.6 3394.0 <br/>3488.4 3582.7 3677.6 3770.4 3865.2 <br/>3958.2 4052.3 4146.5 4240.7 4334.9 <br/>4429.2 4523.6 4618.3 4713.2 4808.0 </p>
</div>
<div style="position: absolute; margin-left: 1889px; margin-top: 935px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">116.3 116.1 115.9 115.7 115.5 <br/>115.3 115.2 114.9 114.7 114.5 <br/>114.3 114.1 113.9 113.8 113.6 <br/>113.5 113.3 113.2 113.2 113.1 </p>
</div>
<div style="position: absolute; margin-left: 1721px; margin-top: 2082px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">4902.9 </p>
</div>
<div style="position: absolute; margin-left: 1889px; margin-top: 2082px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">113.0 </p>
</div>
<div style="position: absolute; margin-left: 2103px; margin-top: 935px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1334.88 1366.79 1398.37 1430.02 1461.75 <br/>1493.36 1523.59 1550.90 1576.04 1602.06 <br/>1627.93 1654.89 1681.81 1708.58 1735.78 <br/>C/JUJUJMUJ UJUJUJUJUJ <br/>moot/2mm </p>
</div>
<div style="position: absolute; margin-left: 2124px; margin-top: 1785px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1762.60 3 1790.37 3 1821.35 S 1853.80 S 1886.47 S </p>
</div>
<div style="position: absolute; margin-left: 2125px; margin-top: 2082px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1919.39 S </p>
</div>
<div style="position: absolute; margin-left: 2401px; margin-top: 935px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2706.05 E 2794.45 E 2884.03 E 2973.60 E 3063.13 E <br/>3152.61 E 3242.58 E 3334.60 E 3425.17 E 3517.57 E <br/>3607.94 E 3699.03 E 3790.11 E 3881.25 E 3972.26 E </p>
</div>
<div style="position: absolute; margin-left: 2401px; margin-top: 1785px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">4063.39 E 4154.23 E 424402 E 433329 E 4422.47 E </p>
</div>
<div style="position: absolute; margin-left: 2401px; margin-top: 2082px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">4511.54 E </p>
</div>
</body>
</html>
| datamade/elpc_bakken | ocr_extracted/W28770_text/page2.html | HTML | mit | 8,921 |
<?php
/* @var $this UserController */
/* @var $data User */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('level_id')); ?>:</b>
<?php echo CHtml::encode($data->level_id); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('username')); ?>:</b>
<?php echo CHtml::encode($data->username); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('email')); ?>:</b>
<?php echo CHtml::encode($data->email); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('password')); ?>:</b>
<?php echo CHtml::encode($data->password); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('join_date')); ?>:</b>
<?php echo CHtml::encode($data->join_date); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('banned')); ?>:</b>
<?php echo CHtml::encode($data->banned); ?>
<br />
<?php /*
<b><?php echo CHtml::encode($data->getAttributeLabel('active')); ?>:</b>
<?php echo CHtml::encode($data->active); ?>
<br />
*/ ?>
</div> | felladrin/joinuo | protected/views/user/_view.php | PHP | mit | 1,185 |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015 by PyCLibrary Authors, see AUTHORS for more details.
#
# Distributed under the terms of the MIT/X11 license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------------------------------------------------------------------------
"""
Used for extracting data such as macro definitions, variables, typedefs, and
function signatures from C header files.
"""
from __future__ import (division, unicode_literals, print_function,
absolute_import)
import sys
import re
import os
import logging
from inspect import cleandoc
from future.utils import istext, isbytes
from ast import literal_eval
from traceback import format_exc
from .errors import DefinitionError
from .utils import find_header
# Import parsing elements
from .thirdparty.pyparsing import \
(ParserElement, ParseResults, Forward, Optional, Word, WordStart,
WordEnd, Keyword, Regex, Literal, SkipTo, ZeroOrMore, OneOrMore,
Group, LineEnd, stringStart, quotedString, oneOf, nestedExpr,
delimitedList, restOfLine, cStyleComment, alphas, alphanums, hexnums,
lineno, Suppress)
ParserElement.enablePackrat()
logger = logging.getLogger(__name__)
__all__ = ['win_defs', 'CParser']
class Type(tuple):
"""
Representation of a C type. CParser uses this class to store the parsed
typedefs and the types of variable/func.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from tuple and can be seen as the tuples from 0.1.0. In future this might
change to a tuple-like object!!!
Parameters
----------
type_spec : str
a string referring the base type of this type defintion. This may
either be a fundametal type (i.e. 'int', 'enum x') or a type definition
made by a typedef-statement
declarators : str or list of tuple
all following parameters are deriving a type from the type defined
until now. Types can be derived by:
- The string '*': define a pointer to the base type
(i.E. Type('int', '*'))
- The string '&': a reference. T.B.D.
- A list of integers of len 1: define an array with N elements
(N is the first and single entry in the list of integers). If N is
-1, the array definition is seen as 'int x[]'
(i.E. Type('int', [1])
- a N-tuple of 3-tuples: defines a function of N parameters. Every
parameter is a 3 tuple of the form:
(<parameter-name-or-None>, <param-type>, None).
Due to compatibility reasons the return value of the function is
stored in Type.type_spec parameter
(This is **not** the case for function pointers):
(i.E. Type(Type('int', '*'), ( ('param1', Type('int'), None), ) ) )
type_quals : dict of int to list of str (optional)
this optional (keyword-)argument allows to optionally add type
qualifiers for every declarator level. The key 0 refers the type
qualifier of type_spec, while 1 refers to declarators[0], 2 refers to
declarators[1] and so on.
To build more complex types any number of declarators can be combined. i.E.
>>> int * (*a[2])(char *, signed c[]);
if represented as:
>>> Type('int', '*',
>>> ( (None, Type('char', '*'), None),
>>> ('c', Type('signed', [-1]), None) )),
>>> '*', [2])
"""
# Cannot slot a subclass of tuple.
def __new__(cls, type_spec, *declarators, **argv):
return super(Type, cls).__new__(cls, (type_spec,) + declarators)
def __init__(self, type_spec, *declarators, **argv):
super(Type, self).__init__()
self.type_quals = (argv.pop('type_quals', None) or
((),) * (1 + len(declarators)))
if len(self.type_quals) != 1 + len(declarators):
raise ValueError("wrong number of type qualifiers")
assert len(argv) == 0, 'Invalid Parameter'
def __eq__(self, other):
if isinstance(other, Type):
if self.type_quals != other.type_quals:
return False
return super(Type, self).__eq__(other)
def __ne__(self, other):
return not self.__eq__(other)
@property
def declarators(self):
"""Return a tuple of all declarators.
"""
return tuple(self[1:])
@property
def type_spec(self):
"""Return the base type of this type.
"""
return self[0]
def is_fund_type(self):
"""Returns True, if this type is a fundamental type.
Fundamental types are all types, that are not defined via typedef
"""
if (self[0].startswith('struct ') or self[0].startswith('union ') or
self[0].startswith('enum ')):
return True
names = (num_types + nonnum_types + size_modifiers + sign_modifiers +
extra_type_list)
for w in self[0].split():
if w not in names:
return False
return True
def eval(self, type_map, used=None):
"""Resolves the type_spec of this type recursively if it is referring
to a typedef. For resolving the type type_map is used for lookup.
Returns a new Type object.
Parameters
----------
type_map : dict of str to Type
All typedefs that shall be resolved have to be stored in this
type_map.
used : list of str
For internal use only to prevent circular typedefs
"""
used = used or []
if self.is_fund_type():
# Remove 'signed' before returning evaluated type
return Type(re.sub(r'\bsigned\b', '', self.type_spec).strip(),
*self.declarators,
type_quals=self.type_quals)
parent = self.type_spec
if parent in used:
m = 'Recursive loop while evaluating types. (typedefs are {})'
raise DefinitionError(m.format(' -> '.join(used+[parent])))
used.append(parent)
if parent not in type_map:
m = 'Unknown type "{}" (typedefs are {})'
raise DefinitionError(m.format(parent, ' -> '.join(used)))
pt = type_map[parent]
evaled_type = Type(pt.type_spec, *(pt.declarators + self.declarators),
type_quals=(pt.type_quals[:-1] +
(pt.type_quals[-1] +
self.type_quals[0],) +
self.type_quals[1:])
)
return evaled_type.eval(type_map, used)
def add_compatibility_hack(self):
"""If This Type is refering to a function (**not** a function pointer)
a new type is returned, that matches the hack from version 0.1.0.
This hack enforces the return value be encapsulated in a separated Type
object:
Type('int', '*', ())
is converted to
Type(Type('int', '*'), ())
"""
if type(self[-1]) == tuple:
return Type(Type(*self[:-1], type_quals=self.type_quals[:-1]),
self[-1],
type_quals=((), self.type_quals[-1]))
else:
return self
def remove_compatibility_hack(self):
"""Returns a Type object, where the hack from .add_compatibility_hack()
is removed
"""
if len(self) == 2 and isinstance(self[0], Type):
return Type(*(self[0] + (self[1],)))
else:
return self
def __repr__(self):
type_qual_str = ('' if not any(self.type_quals) else
', type_quals='+repr(self.type_quals))
return (type(self).__name__ + '(' +
', '.join(map(repr, self)) + type_qual_str + ')')
class Compound(dict):
"""Base class for representing object using a dict-like interface.
"""
__slots__ = ()
def __init__(self, *members, **argv):
members = list(members)
pack = argv.pop('pack', None)
assert len(argv) == 0
super(Compound, self).__init__(dict(members=members, pack=pack))
def __repr__(self):
packParam = ', pack='+repr(self.pack) if self.pack is not None else ''
return (type(self).__name__ + '(' +
', '.join(map(repr, self.members)) + packParam + ')')
@property
def members(self):
return self['members']
@property
def pack(self):
return self['pack']
class Struct(Compound):
"""Representation of a C struct. CParser uses this class to store the parsed
structs.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from dict and can be seen as the dicts from 0.1.0. In future this might
change to a dict-like object!!!
"""
__slots__ = ()
class Union(Compound):
"""Representation of a C union. CParser uses this class to store the parsed
unions.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from dict and can be seen as the dicts from 0.1.0. In future this might
change to a dict-like object!!!
"""
__slots__ = ()
class Enum(dict):
"""Representation of a C enum. CParser uses this class to store the parsed
enums.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from dict and can be seen as the dicts from 0.1.0. In future this might
change to a dict-like object!!!
"""
__slots__ = ()
def __init__(self, **args):
super(Enum, self).__init__(args)
def __repr__(self):
return (type(self).__name__ + '(' +
', '.join(nm + '=' + repr(val)
for nm, val in sorted(self.items())) +
')')
def win_defs(version='800'):
"""Loads selection of windows headers included with PyCLibrary.
These definitions can either be accessed directly or included before
parsing another file like this:
>>> windefs = c_parser.win_defs()
>>> p = c_parser.CParser("headerFile.h", copy_from=windefs)
Definitions are pulled from a selection of header files included in Visual
Studio (possibly not legal to distribute? Who knows.), some of which have
been abridged because they take so long to parse.
Parameters
----------
version : unicode
Version of the MSVC to consider when parsing.
Returns
-------
parser : CParser
CParser containing all the infos from te windows headers.
"""
header_files = ['WinNt.h', 'WinDef.h', 'WinBase.h', 'BaseTsd.h',
'WTypes.h', 'WinUser.h']
if not CParser._init:
logger.warning('Automatic initialisation : OS is assumed to be win32')
from .init import auto_init
auto_init('win32')
d = os.path.dirname(__file__)
p = CParser(
[os.path.join(d, 'headers', h) for h in header_files],
macros={'_WIN32': '', '_MSC_VER': version, 'CONST': 'const',
'NO_STRICT': None, 'MS_WIN32': ''},
process_all=False
)
p.process_all(cache=os.path.join(d, 'headers', 'WinDefs.cache'))
return p
class CParser(object):
"""Class for parsing C code to extract variable, struct, enum, and function
declarations as well as preprocessor macros.
This is not a complete C parser; instead, it is meant to simplify the
process of extracting definitions from header files in the absence of a
complete build system. Many files will require some amount of manual
intervention to parse properly (see 'replace' and extra arguments)
Parameters
----------
files : str or iterable, optional
File or files which should be parsed.
copy_from : CParser or iterable of CParser, optional
CParser whose definitions should be included.
replace : dict, optional
Specify som string replacements to perform before parsing. Format is
{'searchStr': 'replaceStr', ...}
process_all : bool, optional
Flag indicating whether files should be parsed immediatly. True by
default.
cache : unicode, optional
Path of the cache file from which to load definitions/to which save
definitions as parsing is an expensive operation.
kwargs :
Extra parameters may be used to specify the starting state of the
parser. For example, one could provide a set of missing type
declarations by types={'UINT': ('unsigned int'), 'STRING': ('char', 1)}
Similarly, preprocessor macros can be specified: macros={'WINAPI': ''}
Example
-------
Create parser object, load two files
>>> p = CParser(['header1.h', 'header2.h'])
Remove comments, preprocess, and search for declarations
>>> p.process_ all()
Just to see what was successfully parsed from the files
>>> p.print_all()
Access parsed declarations
>>> all_values = p.defs['values']
>>> functionSignatures = p.defs['functions']
To see what was not successfully parsed
>>> unp = p.process_all(return_unparsed=True)
>>> for s in unp:
print s
"""
#: Increment every time cache structure or parsing changes to invalidate
#: old cache files.
cache_version = 1
#: Private flag allowing to know if the parser has been initiliased.
_init = False
def __init__(self, files=None, copy_from=None, replace=None,
process_all=True, cache=None, **kwargs):
if not self._init:
logger.warning('Automatic initialisation based on OS detection')
from .init import auto_init
auto_init()
# Holds all definitions
self.defs = {}
# Holds definitions grouped by the file they came from
self.file_defs = {}
# Description of the struct packing rules as defined by #pragma pack
self.pack_list = {}
self.init_opts = kwargs.copy()
self.init_opts['files'] = []
self.init_opts['replace'] = {}
self.data_list = ['types', 'variables', 'fnmacros', 'macros',
'structs', 'unions', 'enums', 'functions', 'values']
self.file_order = []
self.files = {}
if files is not None:
if istext(files) or isbytes(files):
files = [files]
for f in self.find_headers(files):
self.load_file(f, replace)
# Initialize empty definition lists
for k in self.data_list:
self.defs[k] = {}
# Holds translations from typedefs/structs/unions to fundamental types
self.compiled_types = {}
self.current_file = None
# Import extra arguments if specified
for t in kwargs:
for k in kwargs[t].keys():
self.add_def(t, k, kwargs[t][k])
# Import from other CParsers if specified
if copy_from is not None:
if not isinstance(copy_from, (list, tuple)):
copy_from = [copy_from]
for p in copy_from:
self.import_dict(p.file_defs)
if process_all:
self.process_all(cache=cache)
def process_all(self, cache=None, return_unparsed=False,
print_after_preprocess=False):
""" Remove comments, preprocess, and parse declarations from all files.
This operates in memory, and thus does not alter the original files.
Parameters
----------
cache : unicode, optional
File path where cached results are be stored or retrieved. The
cache is automatically invalidated if any of the arguments to
__init__ are changed, or if the C files are newer than the cache.
return_unparsed : bool, optional
Passed directly to parse_defs.
print_after_preprocess : bool, optional
If true prints the result of preprocessing each file.
Returns
-------
results : list
List of the results from parse_defs.
"""
if cache is not None and self.load_cache(cache, check_validity=True):
logger.debug("Loaded cached definitions; will skip parsing.")
# Cached values loaded successfully, nothing left to do here
return
results = []
logger.debug(cleandoc('''Parsing C header files (no valid cache found).
This could take several minutes...'''))
for f in self.file_order:
if self.files[f] is None:
# This means the file could not be loaded and there was no
# cache.
mess = 'Could not find header file "{}" or a cache file.'
raise IOError(mess.format(f))
logger.debug("Removing comments from file '{}'...".format(f))
self.remove_comments(f)
logger.debug("Preprocessing file '{}'...".format(f))
self.preprocess(f)
if print_after_preprocess:
print("===== PREPROCSSED {} =======".format(f))
print(self.files[f])
logger.debug("Parsing definitions in file '{}'...".format(f))
results.append(self.parse_defs(f, return_unparsed))
if cache is not None:
logger.debug("Writing cache file '{}'".format(cache))
self.write_cache(cache)
return results
def load_cache(self, cache_file, check_validity=False):
"""Load a cache file.
Used internally if cache is specified in process_all().
Parameters
----------
cache_file : unicode
Path of the file from which the cache should be loaded.
check_validity : bool, optional
If True, then run several checks before loading the cache:
- cache file must not be older than any source files
- cache file must not be older than this library file
- options recorded in cache must match options used to initialize
CParser
Returns
-------
result : bool
Did the loading succeeded.
"""
# Make sure cache file exists
if not istext(cache_file):
raise ValueError("Cache file option must be a unicode.")
if not os.path.isfile(cache_file):
# If file doesn't exist, search for it in this module's path
d = os.path.dirname(__file__)
cache_file = os.path.join(d, "headers", cache_file)
if not os.path.isfile(cache_file):
logger.debug("Can't find requested cache file.")
return False
# Make sure cache is newer than all input files
if check_validity:
mtime = os.stat(cache_file).st_mtime
for f in self.file_order:
# If file does not exist, then it does not count against the
# validity of the cache.
if os.path.isfile(f) and os.stat(f).st_mtime > mtime:
logger.debug("Cache file is out of date.")
return False
try:
# Read cache file
import pickle
cache = pickle.load(open(cache_file, 'rb'))
# Make sure __init__ options match
if check_validity:
if cache['opts'] != self.init_opts:
db = logger.debug
db("Cache file is not valid")
db("It was created using different initialization options")
db('{}'.format(cache['opts']))
db('{}'.format(self.init_opts))
return False
else:
logger.debug("Cache init opts are OK:")
logger.debug('{}'.format(cache['opts']))
if cache['version'] < self.cache_version:
mess = "Cache file is not valid--cache format has changed."
logger.debug(mess)
return False
# Import all parse results
self.import_dict(cache['file_defs'])
return True
except Exception:
logger.exception("Warning--cache read failed:")
return False
def import_dict(self, data):
"""Import definitions from a dictionary.
The dict format should be the same as CParser.file_defs.
Used internally; does not need to be called manually.
"""
for f in data.keys():
self.current_file = f
for k in self.data_list:
for n in data[f][k]:
self.add_def(k, n, data[f][k][n])
def write_cache(self, cache_file):
"""Store all parsed declarations to cache. Used internally.
"""
cache = {}
cache['opts'] = self.init_opts
cache['file_defs'] = self.file_defs
cache['version'] = self.cache_version
import pickle
pickle.dump(cache, open(cache_file, 'wb'))
def find_headers(self, headers):
"""Try to find the specified headers.
"""
hs = []
for header in headers:
if os.path.isfile(header):
hs.append(header)
else:
h = find_header(header)
if not h:
raise OSError('Cannot find header: {}'.format(header))
hs.append(h)
return hs
def load_file(self, path, replace=None):
"""Read a file, make replacements if requested.
Called by __init__, should not be called manually.
Parameters
----------
path : unicode
Path of the file to load.
replace : dict, optional
Dictionary containing strings to replace by the associated value
when loading the file.
"""
if not os.path.isfile(path):
# Not a fatal error since we might be able to function properly if
# there is a cache file.
mess = "Warning: C header '{}' is missing, this may cause trouble."
logger.warning(mess.format(path))
self.files[path] = None
return False
# U causes all newline types to be converted to \n
with open(path, 'rU') as fd:
self.files[path] = fd.read()
if replace is not None:
for s in replace:
self.files[path] = re.sub(s, replace[s], self.files[path])
self.file_order.append(path)
bn = os.path.basename(path)
self.init_opts['replace'][bn] = replace
# Only interested in the file names, the directory may change between
# systems.
self.init_opts['files'].append(bn)
return True
def print_all(self, filename=None):
"""Print everything parsed from files. Useful for debugging.
Parameters
----------
filename : unicode, optional
Name of the file whose definition should be printed.
"""
from pprint import pprint
for k in self.data_list:
print("============== {} ==================".format(k))
if filename is None:
pprint(self.defs[k])
else:
pprint(self.file_defs[filename][k])
# =========================================================================
# --- Processing functions
# =========================================================================
def remove_comments(self, path):
"""Remove all comments from file.
Operates in memory, does not alter the original files.
"""
text = self.files[path]
cplusplus_line_comment = Literal("//") + restOfLine
# match quoted strings first to prevent matching comments inside quotes
comment_remover = (quotedString | cStyleComment.suppress() |
cplusplus_line_comment.suppress())
self.files[path] = comment_remover.transformString(text)
# --- Pre processing
def preprocess(self, path):
"""Scan named file for preprocessor directives, removing them while
expanding macros.
Operates in memory, does not alter the original files.
Currently support :
- conditionals : ifdef, ifndef, if, elif, else (defined can be used
in a if statement).
- definition : define, undef
- pragmas : pragma
"""
# We need this so that eval_expr works properly
self.build_parser()
self.current_file = path
# Stack for #pragma pack push/pop
pack_stack = [(None, None)]
self.pack_list[path] = [(0, None)]
packing = None # Current packing value
text = self.files[path]
# First join together lines split by \\n
text = Literal('\\\n').suppress().transformString(text)
# Define the structure of a macro definition
name = Word(alphas+'_', alphanums+'_')('name')
deli_list = Optional(lparen + delimitedList(name) + rparen)
self.pp_define = (name.setWhitespaceChars(' \t')("macro") +
deli_list.setWhitespaceChars(' \t')('args') +
SkipTo(LineEnd())('value'))
self.pp_define.setParseAction(self.process_macro_defn)
# Comb through lines, process all directives
lines = text.split('\n')
result = []
directive = re.compile(r'\s*#\s*([a-zA-Z]+)(.*)$')
if_true = [True]
if_hit = []
for i, line in enumerate(lines):
new_line = ''
m = directive.match(line)
# Regular code line
if m is None:
# Only include if we are inside the correct section of an IF
# block
if if_true[-1]:
new_line = self.expand_macros(line)
# Macro line
else:
d = m.groups()[0]
rest = m.groups()[1]
if d == 'ifdef':
d = 'if'
rest = 'defined ' + rest
elif d == 'ifndef':
d = 'if'
rest = '!defined ' + rest
# Evaluate 'defined' operator before expanding macros
if d in ['if', 'elif']:
def pa(t):
is_macro = t['name'] in self.defs['macros']
is_macro_func = t['name'] in self.defs['fnmacros']
return ['0', '1'][is_macro or is_macro_func]
rest = (Keyword('defined') +
(name | lparen + name + rparen)
).setParseAction(pa).transformString(rest)
elif d in ['define', 'undef']:
match = re.match(r'\s*([a-zA-Z_][a-zA-Z0-9_]*)(.*)$', rest)
macroName, rest = match.groups()
# Expand macros if needed
if rest is not None and (all(if_true) or d in ['if', 'elif']):
rest = self.expand_macros(rest)
if d == 'elif':
if if_hit[-1] or not all(if_true[:-1]):
ev = False
else:
ev = self.eval_preprocessor_expr(rest)
logger.debug(" "*(len(if_true)-2) + line +
'{}, {}'.format(rest, ev))
if_true[-1] = ev
if_hit[-1] = if_hit[-1] or ev
elif d == 'else':
logger.debug(" "*(len(if_true)-2) + line +
'{}'.format(not if_hit[-1]))
if_true[-1] = (not if_hit[-1]) and all(if_true[:-1])
if_hit[-1] = True
elif d == 'endif':
if_true.pop()
if_hit.pop()
logger.debug(" "*(len(if_true)-1) + line)
elif d == 'if':
if all(if_true):
ev = self.eval_preprocessor_expr(rest)
else:
ev = False
logger.debug(" "*(len(if_true)-1) + line +
'{}, {}'.format(rest, ev))
if_true.append(ev)
if_hit.append(ev)
elif d == 'define':
if not if_true[-1]:
continue
logger.debug(" "*(len(if_true)-1) + "define: " +
'{}, {}'.format(macroName, rest))
try:
# Macro is registered here
self.pp_define.parseString(macroName + ' ' + rest)
except Exception:
logger.exception("Error processing macro definition:" +
'{}, {}'.format(macroName, rest))
elif d == 'undef':
if not if_true[-1]:
continue
try:
self.rem_def('macros', macroName.strip())
except Exception:
if sys.exc_info()[0] is not KeyError:
mess = "Error removing macro definition '{}'"
logger.exception(mess.format(macroName.strip()))
# Check for changes in structure packing
# Support only for #pragme pack (with all its variants
# save show), None is used to signal that the default packing
# is used.
# Those two definition disagree :
# https://gcc.gnu.org/onlinedocs/gcc/Structure-Packing-Pragmas.html
# http://msdn.microsoft.com/fr-fr/library/2e70t5y1.aspx
# The current implementation follows the MSVC doc.
elif d == 'pragma':
if not if_true[-1]:
continue
m = re.match(r'\s+pack\s*\(([^\)]*)\)', rest)
if not m:
continue
if m.groups():
opts = [s.strip() for s in m.groups()[0].split(',')]
pushpop = id = val = None
for o in opts:
if o in ['push', 'pop']:
pushpop = o
elif o.isdigit():
val = int(o)
else:
id = o
packing = val
if pushpop == 'push':
pack_stack.append((packing, id))
elif opts[0] == 'pop':
if id is None:
pack_stack.pop()
else:
ind = None
for j, s in enumerate(pack_stack):
if s[1] == id:
ind = j
break
if ind is not None:
pack_stack = pack_stack[:ind]
if val is None:
packing = pack_stack[-1][0]
mess = ">> Packing changed to {} at line {}"
logger.debug(mess.format(str(packing), i))
self.pack_list[path].append((i, packing))
else:
# Ignore any other directives
mess = 'Ignored directive {} at line {}'
logger.debug(mess.format(d, i))
result.append(new_line)
self.files[path] = '\n'.join(result)
def eval_preprocessor_expr(self, expr):
# Make a few alterations so the expression can be eval'd
macro_diffs = (
Literal('!').setParseAction(lambda: ' not ') |
Literal('&&').setParseAction(lambda: ' and ') |
Literal('||').setParseAction(lambda: ' or ') |
Word(alphas + '_', alphanums + '_').setParseAction(lambda: '0'))
expr2 = macro_diffs.transformString(expr).strip()
try:
ev = bool(eval(expr2))
except Exception:
mess = "Error evaluating preprocessor expression: {} [{}]\n{}"
logger.debug(mess.format(expr, repr(expr2), format_exc()))
ev = False
return ev
def process_macro_defn(self, t):
"""Parse a #define macro and register the definition.
"""
logger.debug("Processing MACRO: {}".format(t))
macro_val = t.value.strip()
if macro_val in self.defs['fnmacros']:
self.add_def('fnmacros', t.macro, self.defs['fnmacros'][macro_val])
logger.debug(" Copy fn macro {} => {}".format(macro_val, t.macro))
else:
if t.args == '':
val = self.eval_expr(macro_val)
self.add_def('macros', t.macro, macro_val)
self.add_def('values', t.macro, val)
mess = " Add macro: {} ({}); {}"
logger.debug(mess.format(t.macro, val,
self.defs['macros'][t.macro]))
else:
self.add_def('fnmacros', t.macro,
self.compile_fn_macro(macro_val,
[x for x in t.args]))
mess = " Add fn macro: {} ({}); {}"
logger.debug(mess.format(t.macro, t.args,
self.defs['fnmacros'][t.macro]))
return "#define " + t.macro + " " + macro_val
def compile_fn_macro(self, text, args):
"""Turn a function macro spec into a compiled description.
"""
# Find all instances of each arg in text.
args_str = '|'.join(args)
arg_regex = re.compile(r'("(\\"|[^"])*")|(\b({})\b)'.format(args_str))
start = 0
parts = []
arg_order = []
# The group number to check for macro names
N = 3
for m in arg_regex.finditer(text):
arg = m.groups()[N]
if arg is not None:
parts.append(text[start:m.start(N)] + '{}')
start = m.end(N)
arg_order.append(args.index(arg))
parts.append(text[start:])
return (''.join(parts), arg_order)
def expand_macros(self, line):
"""Expand all the macro expressions in a string.
Faulty calls to macro function are left untouched.
"""
reg = re.compile(r'("(\\"|[^"])*")|(\b(\w+)\b)')
parts = []
# The group number to check for macro names
N = 3
macros = self.defs['macros']
fnmacros = self.defs['fnmacros']
while True:
m = reg.search(line)
if not m:
break
name = m.groups()[N]
if name in macros:
parts.append(line[:m.start(N)])
line = line[m.end(N):]
parts.append(macros[name])
elif name in fnmacros:
# If function macro expansion fails, just ignore it.
try:
exp, end = self.expand_fn_macro(name, line[m.end(N):])
except Exception:
exp = name
end = 0
mess = "Function macro expansion failed: {}, {}"
logger.error(mess.format(name, line[m.end(N):]))
parts.append(line[:m.start(N)])
start = end + m.end(N)
line = line[start:]
parts.append(exp)
else:
start = m.end(N)
parts.append(line[:start])
line = line[start:]
parts.append(line)
return ''.join(parts)
def expand_fn_macro(self, name, text):
"""Replace a function macro.
"""
# defn looks like ('%s + %s / %s', (0, 0, 1))
defn = self.defs['fnmacros'][name]
arg_list = (stringStart + lparen +
Group(delimitedList(expression))('args') + rparen)
res = [x for x in arg_list.scanString(text, 1)]
if len(res) == 0:
mess = "Function macro '{}' not followed by (...)"
raise DefinitionError(0, mess.format(name))
args, start, end = res[0]
args = [self.expand_macros(arg) for arg in args[0]]
new_str = defn[0].format(*[args[i] for i in defn[1]])
return (new_str, end)
# --- Compilation functions
def parse_defs(self, path, return_unparsed=False):
"""Scan through the named file for variable, struct, enum, and function
declarations.
Parameters
----------
path : unicode
Path of the file to parse for definitions.
return_unparsed : bool, optional
If true, return a string of all lines that failed to match (for
debugging purposes).
Returns
-------
tokens : list
Entire tree of successfully parsed tokens.
"""
self.current_file = path
parser = self.build_parser()
if return_unparsed:
text = parser.suppress().transformString(self.files[path])
return re.sub(r'\n\s*\n', '\n', text)
else:
return [x[0] for x in parser.scanString(self.files[path])]
def build_parser(self):
"""Builds the entire tree of parser elements for the C language (the
bits we support, anyway).
"""
if hasattr(self, 'parser'):
return self.parser
self.struct_type = Forward()
self.enum_type = Forward()
type_ = (fund_type |
Optional(kwl(size_modifiers + sign_modifiers)) + ident |
self.struct_type |
self.enum_type)
if extra_modifier is not None:
type_ += extra_modifier
type_.setParseAction(recombine)
self.type_spec = (type_qualifier('pre_qual') +
type_("name"))
# --- Abstract declarators for use in function pointer arguments
# Thus begins the extremely hairy business of parsing C declarators.
# Whomever decided this was a reasonable syntax should probably never
# breed.
# The following parsers combined with the process_declarator function
# allow us to turn a nest of type modifiers into a correctly
# ordered list of modifiers.
self.declarator = Forward()
self.abstract_declarator = Forward()
# Abstract declarators look like:
# <empty string>
# *
# **[num]
# (*)(int, int)
# *( )(int, int)[10]
# ...etc...
self.abstract_declarator << Group(
type_qualifier('first_typequal') +
Group(ZeroOrMore(Group(Suppress('*') + type_qualifier)))('ptrs') +
((Optional('&')('ref')) |
(lparen + self.abstract_declarator + rparen)('center')) +
Optional(lparen +
Optional(delimitedList(Group(
self.type_spec('type') +
self.abstract_declarator('decl') +
Optional(Literal('=').suppress() + expression,
default=None)('val')
)), default=None) +
rparen)('args') +
Group(ZeroOrMore(lbrack + Optional(expression, default='-1') +
rbrack))('arrays')
)
# Declarators look like:
# varName
# *varName
# **varName[num]
# (*fnName)(int, int)
# * fnName(int arg1=0)[10]
# ...etc...
self.declarator << Group(
type_qualifier('first_typequal') + call_conv +
Group(ZeroOrMore(Group(Suppress('*') + type_qualifier)))('ptrs') +
((Optional('&')('ref') + ident('name')) |
(lparen + self.declarator + rparen)('center')) +
Optional(lparen +
Optional(delimitedList(
Group(self.type_spec('type') +
(self.declarator |
self.abstract_declarator)('decl') +
Optional(Literal('=').suppress() +
expression, default=None)('val')
)),
default=None) +
rparen)('args') +
Group(ZeroOrMore(lbrack + Optional(expression, default='-1') +
rbrack))('arrays')
)
self.declarator_list = Group(delimitedList(self.declarator))
# Typedef
self.type_decl = (Keyword('typedef') + self.type_spec('type') +
self.declarator_list('decl_list') + semi)
self.type_decl.setParseAction(self.process_typedef)
# Variable declaration
self.variable_decl = (
Group(storage_class_spec +
self.type_spec('type') +
Optional(self.declarator_list('decl_list')) +
Optional(Literal('=').suppress() +
(expression('value') |
(lbrace +
Group(delimitedList(expression))('array_values') +
rbrace
)
)
)
) +
semi)
self.variable_decl.setParseAction(self.process_variable)
# Function definition
self.typeless_function_decl = (self.declarator('decl') +
nestedExpr('{', '}').suppress())
self.function_decl = (storage_class_spec +
self.type_spec('type') +
self.declarator('decl') +
nestedExpr('{', '}').suppress())
self.function_decl.setParseAction(self.process_function)
# Struct definition
self.struct_decl = Forward()
struct_kw = (Keyword('struct') | Keyword('union'))
self.struct_member = (
Group(self.variable_decl.copy().setParseAction(lambda: None)) |
# Hack to handle bit width specification.
Group(Group(self.type_spec('type') +
Optional(self.declarator_list('decl_list')) +
colon + integer('bit') + semi)) |
(self.type_spec + self.declarator +
nestedExpr('{', '}')).suppress() |
(self.declarator + nestedExpr('{', '}')).suppress()
)
self.decl_list = (lbrace +
Group(OneOrMore(self.struct_member))('members') +
rbrace)
self.struct_type << (struct_kw('struct_type') +
((Optional(ident)('name') +
self.decl_list) | ident('name'))
)
self.struct_type.setParseAction(self.process_struct)
self.struct_decl = self.struct_type + semi
# Enum definition
enum_var_decl = Group(ident('name') +
Optional(Literal('=').suppress() +
(integer('value') | ident('valueName'))))
self.enum_type << (Keyword('enum') +
(Optional(ident)('name') +
lbrace +
Group(delimitedList(enum_var_decl))('members') +
Optional(comma) + rbrace | ident('name'))
)
self.enum_type.setParseAction(self.process_enum)
self.enum_decl = self.enum_type + semi
self.parser = (self.type_decl | self.variable_decl |
self.function_decl)
return self.parser
def process_declarator(self, decl):
"""Process a declarator (without base type) and return a tuple
(name, [modifiers])
See process_type(...) for more information.
"""
toks = []
quals = [tuple(decl.get('first_typequal', []))]
name = None
logger.debug("DECL: {}".format(decl))
if 'call_conv' in decl and len(decl['call_conv']) > 0:
toks.append(decl['call_conv'])
quals.append(None)
if 'ptrs' in decl and len(decl['ptrs']) > 0:
toks += ('*',) * len(decl['ptrs'])
quals += map(tuple, decl['ptrs'])
if 'arrays' in decl and len(decl['arrays']) > 0:
toks.extend([self.eval_expr(x)] for x in decl['arrays'])
quals += [()] * len(decl['arrays'])
if 'args' in decl and len(decl['args']) > 0:
if decl['args'][0] is None:
toks.append(())
else:
toks.append(tuple([self.process_type(a['type'],
a['decl']) +
(a['val'][0],) for a in decl['args']]
)
)
quals.append(())
if 'ref' in decl:
toks.append('&')
quals.append(())
if 'center' in decl:
(n, t, q) = self.process_declarator(decl['center'][0])
if n is not None:
name = n
toks.extend(t)
quals = quals[:-1] + [quals[-1] + q[0]] + list(q[1:])
if 'name' in decl:
name = decl['name']
return (name, toks, tuple(quals))
def process_type(self, typ, decl):
"""Take a declarator + base type and return a serialized name/type
description.
The description will be a list of elements (name, [basetype, modifier,
modifier, ...]):
- name is the string name of the declarator or None for an abstract
declarator
- basetype is the string representing the base type
- modifiers can be:
- '*' : pointer (multiple pointers "***" allowed)
- '&' : reference
- '__X' : calling convention (windows only). X can be 'cdecl' or
'stdcall'
- list : array. Value(s) indicate the length of each array, -1
for incomplete type.
- tuple : function, items are the output of processType for each
function argument.
Examples:
- int *x[10] => ('x', ['int', [10], '*'])
- char fn(int x) => ('fn', ['char', [('x', ['int'])]])
- struct s (*)(int, int*) =>
(None, ["struct s", ((None, ['int']), (None, ['int', '*'])), '*'])
"""
logger.debug("PROCESS TYPE/DECL: {}/{}".format(typ['name'], decl))
(name, decl, quals) = self.process_declarator(decl)
pre_typequal = tuple(typ.get('pre_qual', []))
return (name, Type(typ['name'], *decl,
type_quals=(pre_typequal + quals[0],) + quals[1:]))
def process_enum(self, s, l, t):
"""
"""
try:
logger.debug("ENUM: {}".format(t))
if t.name == '':
n = 0
while True:
name = 'anon_enum{}'.format(n)
if name not in self.defs['enums']:
break
n += 1
else:
name = t.name[0]
logger.debug(" name: {}".format(name))
if name not in self.defs['enums']:
i = 0
enum = {}
for v in t.members:
if v.value != '':
i = literal_eval(v.value)
if v.valueName != '':
i = enum[v.valueName]
enum[v.name] = i
self.add_def('values', v.name, i)
i += 1
logger.debug(" members: {}".format(enum))
self.add_def('enums', name, enum)
self.add_def('types', 'enum '+name, Type('enum', name))
return ('enum ' + name)
except:
logger.exception("Error processing enum: {}".format(t))
def process_function(self, s, l, t):
"""Build a function definition from the parsing tokens.
"""
logger.debug("FUNCTION {} : {}".format(t, t.keys()))
try:
(name, decl) = self.process_type(t.type, t.decl[0])
if len(decl) == 0 or type(decl[-1]) != tuple:
logger.error('{}'.format(t))
mess = "Incorrect declarator type for function definition."
raise DefinitionError(mess)
logger.debug(" name: {}".format(name))
logger.debug(" sig: {}".format(decl))
self.add_def('functions', name, decl.add_compatibility_hack())
except Exception:
logger.exception("Error processing function: {}".format(t))
def packing_at(self, line):
"""Return the structure packing value at the given line number.
"""
packing = None
for p in self.pack_list[self.current_file]:
if p[0] <= line:
packing = p[1]
else:
break
return packing
def process_struct(self, s, l, t):
"""
"""
try:
str_typ = t.struct_type # struct or union
# Check for extra packing rules
packing = self.packing_at(lineno(l, s))
logger.debug('{} {} {}'.format(str_typ.upper(), t.name, t))
if t.name == '':
n = 0
while True:
sname = 'anon_{}{}'.format(str_typ, n)
if sname not in self.defs[str_typ+'s']:
break
n += 1
else:
if istext(t.name):
sname = t.name
else:
sname = t.name[0]
logger.debug(" NAME: {}".format(sname))
if (len(t.members) > 0 or sname not in self.defs[str_typ+'s'] or
self.defs[str_typ+'s'][sname] == {}):
logger.debug(" NEW " + str_typ.upper())
struct = []
for m in t.members:
typ = m[0].type
val = self.eval_expr(m[0].value)
logger.debug(" member: {}, {}, {}".format(
m, m[0].keys(), m[0].decl_list))
if len(m[0].decl_list) == 0: # anonymous member
member = [None, Type(typ[0]), None]
if m[0].bit:
member.append(int(m[0].bit))
struct.append(tuple(member))
for d in m[0].decl_list:
(name, decl) = self.process_type(typ, d)
member = [name, decl, val]
if m[0].bit:
member.append(int(m[0].bit))
struct.append(tuple(member))
logger.debug(" {} {} {} {}".format(name, decl,
val, m[0].bit))
str_cls = (Struct if str_typ == 'struct' else Union)
self.add_def(str_typ + 's', sname,
str_cls(*struct, pack=packing))
self.add_def('types', str_typ+' '+sname, Type(str_typ, sname))
return str_typ + ' ' + sname
except Exception:
logger.exception('Error processing struct: {}'.format(t))
def process_variable(self, s, l, t):
"""
"""
logger.debug("VARIABLE: {}".format(t))
try:
val = self.eval_expr(t[0])
for d in t[0].decl_list:
(name, typ) = self.process_type(t[0].type, d)
# This is a function prototype
if type(typ[-1]) is tuple:
logger.debug(" Add function prototype: {} {} {}".format(
name, typ, val))
self.add_def('functions', name,
typ.add_compatibility_hack())
# This is a variable
else:
logger.debug(" Add variable: {} {} {}".format(name,
typ, val))
self.add_def('variables', name, (val, typ))
self.add_def('values', name, val)
except Exception:
logger.exception('Error processing variable: {}'.format(t))
def process_typedef(self, s, l, t):
"""
"""
logger.debug("TYPE: {}".format(t))
typ = t.type
for d in t.decl_list:
(name, decl) = self.process_type(typ, d)
logger.debug(" {} {}".format(name, decl))
self.add_def('types', name, decl)
# --- Utility methods
def eval_expr(self, toks):
"""Evaluates expressions.
Currently only works for expressions that also happen to be valid
python expressions.
"""
logger.debug("Eval: {}".format(toks))
try:
if istext(toks) or isbytes(toks):
val = self.eval(toks, None, self.defs['values'])
elif toks.array_values != '':
val = [self.eval(x, None, self.defs['values'])
for x in toks.array_values]
elif toks.value != '':
val = self.eval(toks.value, None, self.defs['values'])
else:
val = None
return val
except Exception:
logger.debug(" failed eval {} : {}".format(toks, format_exc()))
return None
def eval(self, expr, *args):
"""Just eval with a little extra robustness."""
expr = expr.strip()
cast = (lparen + self.type_spec + self.abstract_declarator +
rparen).suppress()
expr = (quotedString | number | cast).transformString(expr)
if expr == '':
return None
return eval(expr, *args)
def add_def(self, typ, name, val):
"""Add a definition of a specific type to both the definition set for
the current file and the global definition set.
"""
self.defs[typ][name] = val
if self.current_file is None:
base_name = None
else:
base_name = os.path.basename(self.current_file)
if base_name not in self.file_defs:
self.file_defs[base_name] = {}
for k in self.data_list:
self.file_defs[base_name][k] = {}
self.file_defs[base_name][typ][name] = val
def rem_def(self, typ, name):
"""Remove a definition of a specific type to both the definition set
for the current file and the global definition set.
"""
if self.current_file is None:
base_name = None
else:
base_name = os.path.basename(self.current_file)
del self.defs[typ][name]
del self.file_defs[base_name][typ][name]
def is_fund_type(self, typ):
"""Return True if this type is a fundamental C type, struct, or
union.
**ATTENTION: This function is legacy and should be replaced by
Type.is_fund_type()**
"""
return Type(typ).is_fund_type()
def eval_type(self, typ):
"""Evaluate a named type into its fundamental type.
**ATTENTION: This function is legacy and should be replaced by
Type.eval()**
"""
if not isinstance(typ, Type):
typ = Type(*typ)
return typ.eval(self.defs['types'])
def find(self, name):
"""Search all definitions for the given name.
"""
res = []
for f in self.file_defs:
fd = self.file_defs[f]
for t in fd:
typ = fd[t]
for k in typ:
if istext(name):
if k == name:
res.append((f, t))
else:
if re.match(name, k):
res.append((f, t, k))
return res
def find_text(self, text):
"""Search all file strings for text, return matching lines.
"""
res = []
for f in self.files:
l = self.files[f].split('\n')
for i in range(len(l)):
if text in l[i]:
res.append((f, i, l[i]))
return res
# --- Basic parsing elements.
def kwl(strs):
"""Generate a match-first list of keywords given a list of strings."""
return Regex(r'\b({})\b'.format('|'.join(strs)))
def flatten(lst):
res = []
for i in lst:
if isinstance(i, (list, tuple)):
res.extend(flatten(i))
else:
res.append(str(i))
return res
def recombine(tok):
"""Flattens a tree of tokens and joins into one big string.
"""
return " ".join(flatten(tok.asList()))
def print_parse_results(pr, depth=0, name=''):
"""For debugging; pretty-prints parse result objects.
"""
start = name + " " * (20 - len(name)) + ':' + '..' * depth
if isinstance(pr, ParseResults):
print(start)
for i in pr:
name = ''
for k in pr.keys():
if pr[k] is i:
name = k
break
print_parse_results(i, depth+1, name)
else:
print(start + str(pr))
# Syntatic delimiters
comma = Literal(",").ignore(quotedString).suppress()
colon = Literal(":").ignore(quotedString).suppress()
semi = Literal(";").ignore(quotedString).suppress()
lbrace = Literal("{").ignore(quotedString).suppress()
rbrace = Literal("}").ignore(quotedString).suppress()
lbrack = Literal("[").ignore(quotedString).suppress()
rbrack = Literal("]").ignore(quotedString).suppress()
lparen = Literal("(").ignore(quotedString).suppress()
rparen = Literal(")").ignore(quotedString).suppress()
# Numbers
int_strip = lambda t: t[0].rstrip('UL')
hexint = Regex('[+-]?\s*0[xX][{}]+[UL]*'.format(hexnums)).setParseAction(int_strip)
decint = Regex('[+-]?\s*[0-9]+[UL]*').setParseAction(int_strip)
integer = (hexint | decint)
# The floating regex is ugly but it is because we do not want to match
# integer to it.
floating = Regex(r'[+-]?\s*((((\d(\.\d*)?)|(\.\d+))[eE][+-]?\d+)|((\d\.\d*)|(\.\d+)))')
number = (floating | integer)
# Miscelaneous
bi_operator = oneOf("+ - / * | & || && ! ~ ^ % == != > < >= <= -> . :: << >> = ? :")
uni_right_operator = oneOf("++ --")
uni_left_operator = oneOf("++ -- - + * sizeof new")
wordchars = alphanums+'_$'
name = (WordStart(wordchars) + Word(alphas+"_", alphanums+"_$") +
WordEnd(wordchars))
size_modifiers = ['short', 'long']
sign_modifiers = ['signed', 'unsigned']
# Syntax elements defined by _init_parser.
expression = Forward()
array_op = lbrack + expression + rbrack
base_types = None
ident = None
call_conv = None
type_qualifier = None
storage_class_spec = None
extra_modifier = None
fund_type = None
extra_type_list = []
num_types = ['int', 'float', 'double']
nonnum_types = ['char', 'bool', 'void']
# Define some common language elements when initialising.
def _init_cparser(extra_types=None, extra_modifiers=None):
global expression
global call_conv, ident
global base_types
global type_qualifier, storage_class_spec, extra_modifier
global fund_type
global extra_type_list
# Some basic definitions
extra_type_list = [] if extra_types is None else list(extra_types)
base_types = nonnum_types + num_types + extra_type_list
storage_classes = ['inline', 'static', 'extern']
qualifiers = ['const', 'volatile', 'restrict', 'near', 'far']
keywords = (['struct', 'enum', 'union', '__stdcall', '__cdecl'] +
qualifiers + base_types + size_modifiers + sign_modifiers)
keyword = kwl(keywords)
wordchars = alphanums+'_$'
ident = (WordStart(wordchars) + ~keyword +
Word(alphas + "_", alphanums + "_$") +
WordEnd(wordchars)).setParseAction(lambda t: t[0])
call_conv = Optional(Keyword('__cdecl') |
Keyword('__stdcall'))('call_conv')
# Removes '__name' from all type specs. may cause trouble.
underscore_2_ident = (WordStart(wordchars) + ~keyword + '__' +
Word(alphanums, alphanums+"_$") +
WordEnd(wordchars)).setParseAction(lambda t: t[0])
type_qualifier = ZeroOrMore((underscore_2_ident + Optional(nestedExpr())) |
kwl(qualifiers))
storage_class_spec = Optional(kwl(storage_classes))
if extra_modifiers:
extra_modifier = ZeroOrMore(kwl(extra_modifiers) +
Optional(nestedExpr())).suppress()
else:
extra_modifier = None
# Language elements
fund_type = OneOrMore(kwl(sign_modifiers + size_modifiers +
base_types)).setParseAction(lambda t: ' '.join(t))
# Is there a better way to process expressions with cast operators??
cast_atom = (
ZeroOrMore(uni_left_operator) + Optional('('+ident+')').suppress() +
((ident + '(' + Optional(delimitedList(expression)) + ')' |
ident + OneOrMore('[' + expression + ']') |
ident | number | quotedString
) |
('(' + expression + ')')) +
ZeroOrMore(uni_right_operator)
)
# XXX Added name here to catch macro functions on types
uncast_atom = (
ZeroOrMore(uni_left_operator) +
((ident + '(' + Optional(delimitedList(expression)) + ')' |
ident + OneOrMore('[' + expression + ']') |
ident | number | name | quotedString
) |
('(' + expression + ')')) +
ZeroOrMore(uni_right_operator)
)
atom = cast_atom | uncast_atom
expression << Group(atom + ZeroOrMore(bi_operator + atom))
expression.setParseAction(recombine)
| mrh1997/pyclibrary | pyclibrary/c_parser.py | Python | mit | 62,500 |
package com.slicer.utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
public class AssetLoader {
public static Texture bgGame, bgGameOver, bgFinish, score, soundOn, soundOff;
public static Sound gameOver, victory, slice, click;
public static FileHandle levelsFile;
public static boolean sound = true;
public static void load() {
bgGame = new Texture(Gdx.files.internal("data/images/bg1.jpeg"));
bgGameOver = new Texture(Gdx.files.internal("data/images/bg3.png"));
bgFinish = new Texture(Gdx.files.internal("data/images/bg2.png"));
soundOn = new Texture(Gdx.files.internal("data/images/on.png"));
soundOff = new Texture(Gdx.files.internal("data/images/off.png"));
score = new Texture(Gdx.files.internal("data/images/score.png"));
gameOver = Gdx.audio.newSound(Gdx.files.internal("data/sound/gameOver.wav"));
victory = Gdx.audio.newSound(Gdx.files.internal("data/sound/victory.wav"));
slice = Gdx.audio.newSound(Gdx.files.internal("data/sound/slice.wav"));
click = Gdx.audio.newSound(Gdx.files.internal("data/sound/click.wav"));
levelsFile = Gdx.files.internal("data/levels/levels.json");
}
public static void play(Sound s) {
if (sound)
s.play();
}
public static void dispose() {
bgGame.dispose();
bgGameOver.dispose();
bgFinish.dispose();
gameOver.dispose();
victory.dispose();
slice.dispose();
}
} | burakkose/libgdx-game-slicer | core/src/com/slicer/utils/AssetLoader.java | Java | mit | 1,612 |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'iframe', 'ko', {
border: '프레임 테두리 표시',
noUrl: '아이프레임 주소(URL)를 입력해주세요.',
scrolling: '스크롤바 사용',
title: '아이프레임 속성',
toolbar: '아이프레임'
} );
| otto-torino/gino | ckeditor/plugins/iframe/lang/ko.js | JavaScript | mit | 424 |
//
// SMCampaignsManager.h
// SessionM
//
// Copyright © 2018 SessionM. All rights reserved.
//
#ifndef __SM_CAMPAIGNS_MANAGER__
#define __SM_CAMPAIGNS_MANAGER__
#import "SMFeedMessage.h"
#import "SMPromotion.h"
#import "SMError.h"
#import "SMBaseDelegate.h"
NS_ASSUME_NONNULL_BEGIN
/*!
@const SM_CAMPAIGNS_MANAGER_REQUEST_DID_FAIL_NOTIFICATION
@abstract Notifies observers that an API request failed.
@discussion An @link SMError @/link object containing information about why the request failed can be accessed from the notification's <code>userInfo</code> property with the @link SM_MANAGER_NOTIFICATION_ERROR_KEY @/link key.
*/
extern NSString *const SM_CAMPAIGNS_MANAGER_REQUEST_DID_FAIL_NOTIFICATION NS_SWIFT_NAME(campaignsRequestFailureNotification);
/*!
@const SM_CAMPAIGNS_MANAGER_DID_FETCH_FEED_MESSAGES_NOTIFICATION
@abstract Notifies observers that feed message campaigns were fetched.
@discussion An <code>NSArray</code> of @link SMFeedMessage @/link objects can be accessed from the notification's <code>userInfo</code> property with the @link SM_MANAGER_NOTIFICATION_DATA_KEY @/link key.
*/
extern NSString *const SM_CAMPAIGNS_MANAGER_DID_FETCH_FEED_MESSAGES_NOTIFICATION NS_SWIFT_NAME(fetchedFeedMessagesNotification);
/*!
@const SM_CAMPAIGNS_MANAGER_DID_FETCH_PROMOTIONS_NOTIFICATION
@abstract Notifies observers that promotional campaigns were fetched.
@discussion An <code>NSArray</code> of @link SMPromotion @/link objects can be accessed from the notification's <code>userInfo</code> property with the @link SM_MANAGER_NOTIFICATION_DATA_KEY @/link key.
*/
extern NSString *const SM_CAMPAIGNS_MANAGER_DID_FETCH_PROMOTIONS_NOTIFICATION NS_SWIFT_NAME(fetchedPromotionsNotification);
/*!
@protocol SMCampaignsDelegate
@abstract Defines callbacks for @link SMCampaignsManager @/link methods.
*/
@protocol SMCampaignsDelegate <SMBaseDelegate>
@optional
/*!
@abstract Notifies delegate that feed message campaigns were fetched.
@discussion This method is called in response to @link fetchFeedMessages @/link and @link fetchFeedMessagesWithLocale: @/link.
@param messages The message campaigns.
@deprecated Use block methods instead.
*/
- (void)didFetchFeedMessages:(NSArray<SMFeedMessage *> *)messages __attribute__((deprecated("Use block methods instead"))) NS_SWIFT_NAME(didFetchFeedMessages(_:));
@end
/*!
@typedef didFetchFeedMessages
@abstract Completion handler block type for @link fetchFeedMessagesWithCompletionHandler: @/link and @link fetchFeedMessagesWithLocale:completionHandler: @/link.
*/
typedef void (^didFetchFeedMessages)(NSArray<SMFeedMessage *>* _Nullable messages, SMError * _Nullable error) NS_SWIFT_NAME(FetchFeedMessagesCompletionHandler);
/*!
@typedef didFetchPromotions
@abstract Completion handler block type for @link fetchPromotionsWithCompletionHandler: @/link and @link fetchPromotionsWithCompletionHandlerWithLocale:completionHandler: @/link.
*/
typedef void (^didFetchPromotions)(NSArray<SMPromotion *>* _Nullable promotions, SMError * _Nullable error) NS_SWIFT_NAME(FetchPromotionsCompletionHandler);
/*!
@class SMCampaignsManager
@abstract This API manager contains methods for fetching promotional campaign data.
*/
@interface SMCampaignsManager : NSObject
/*!
@abstract Singleton that interfaces with the SessionM Platform Campaigns API.
@result <code>SMCampaignsManager</code> service object.
*/
+ (SMCampaignsManager *)instance;
/*!
@property delegate
@abstract Object that implements @link SMCampaignsDelegate @/link callbacks.
*/
@property(nonatomic, weak) id<SMCampaignsDelegate> _Nullable delegate;
/*!
@property feedMessages
@abstract Feed message campaigns.
@discussion This property is updated in response to a successful @link fetchFeedMessagesWithCompletionHandler: @/link or @link fetchFeedMessagesWithLocale:completionHandler: @/link call.
*/
@property(nonatomic, strong, readonly) NSArray<SMFeedMessage *> *feedMessages;
/*!
@property promotions
@abstract Promotional campaigns.
@discussion This property is updated in response to a successful @link fetchPromotionsWithCompletionHandler: @/link or @link fetchPromotionsWithLocale:completionHandler: @/link call.
*/
@property(nonatomic, strong, readonly) NSArray<SMPromotion *> *promotions;
/*!
@abstract Makes a request to update @link feedMessages @/link with feed message campaigns targeted to the current user's locale (default value is @link //apple_ref/occ/instp/SessionM/customLocale @/link if set and <code>[NSLocale currentLocale]</code> otherwise).
@discussion @link didFetchFeedMessages: @/link is called in response to this method.
@result <code>BOOL</code> indicating whether the request will be sent.
@deprecated Use @link fetchFeedMessagesWithCompletionHandler: @/link.
*/
- (BOOL)fetchFeedMessages __attribute__((deprecated("Use fetchFeedMessagesWithCompletionHandler:")));
/*!
@abstract Makes a request to update @link feedMessages @/link with feed message campaigns targeted to the current user's locale (default value is @link //apple_ref/occ/instp/SessionM/customLocale @/link if set and <code>[NSLocale currentLocale]</code> otherwise).
@param completionHandler The block to execute after the request is processed.
@result <code>BOOL</code> indicating whether the request will be sent.
*/
- (BOOL)fetchFeedMessagesWithCompletionHandler:(didFetchFeedMessages)completionHandler NS_SWIFT_NAME(fetchFeedMessages(completionHandler:));
/*!
@abstract Makes a request to update @link feedMessages @/link with feed message campaigns targeted to the specified locale.
@discussion @link didFetchFeedMessages: @/link is called in response to this method.
@param locale The locale in which the fetch will be restricted.
@result <code>BOOL</code> indicating whether the request will be sent.
@deprecated Use @link fetchFeedMessagesWithLocale:completionHandler: @/link.
*/
- (BOOL)fetchFeedMessagesWithLocale:(NSLocale *)locale __attribute__((deprecated("Use fetchFeedMessagesWithLocale:completionHandler:"))) NS_SWIFT_NAME(fetchFeedMessages(for:));
/*!
@abstract Makes a request to update @link feedMessages @/link with feed message campaigns targeted to the specified locale.
@param locale The locale in which the fetch will be restricted.
@param completionHandler The block to execute after the request is processed.
@result <code>BOOL</code> indicating whether the request will be sent.
*/
- (BOOL)fetchFeedMessagesWithLocale:(NSLocale *)locale completionHandler:(didFetchFeedMessages)completionHandler NS_SWIFT_NAME(fetchFeedMessages(for:completionHandler:));
/*!
@abstract Makes a request to update @link promotions @/link with promotional campaigns targeted to the current user's locale (default value is @link //apple_ref/occ/instp/SessionM/customLocale @/link if set and <code>[NSLocale currentLocale]</code> otherwise).
@param completionHandler The block to execute after the request is processed.
@result <code>BOOL</code> indicating whether the request will be sent.
*/
- (BOOL)fetchPromotionsWithCompletionHandler:(didFetchPromotions)completionHandler;
/*!
@abstract Makes a request to update @link promotions @/link with promotional campaigns targeted to the specified locale.
@param locale The locale in which the fetch will be restricted.
@param completionHandler The block to execute after the request is processed.
@result <code>BOOL</code> indicating whether the request will be sent.
*/
- (BOOL)fetchPromotionsWithLocale:(NSLocale *)locale completionHandler:(didFetchPromotions)completionHandler;
/*!
@abstract Executes the action associated with the specified message.
@param message The @link SMFeedMessage @/link instance whose action will be executed.
@discussion Performs the specified message's action as specified by @link //apple_ref/occ/instp/SMFeedMessage/actionType @/link.
*/
- (void)executeActionForMessage:(SMFeedMessage *)message NS_SWIFT_NAME(executeAction(for:));
@end
NS_ASSUME_NONNULL_END
#endif /* __SM_CAMPAIGNS_MANAGER__ */
| sessionm/ios-smp-example | Pods/SessionMFramework/SessionM_iOS_v2.5.2.1/SessionMFramework.framework/Headers/SMCampaignsManager.h | C | mit | 7,990 |
---
layout: page
title: Works
permalink: /data/
---
Here are some of the things I did, or I was involved in somehow, and software I maintain.
UnToLD
-------
Unsupervised Topic-based Lexical Debias
[Website](/untold)
Hurtlex
-------
Hurtlex is a multilingual lexicon of offensive, aggressive and hateful words.
It was created starting from an original resource by linguist Tullio De Mauro
and semi-automatically translated into many languages.
[Hurtlex repository](https://github.com/valeriobasile/hurtlex)
KNEWS
-----
KNEWS (Knowledge Extraction With Semantics) is a software that bridges
semantic parsing, word sense disambiguation, and entity linking to
produce a unified, LOD-compliant abstract representation of meaning.
[KNEWS source code](https://github.com/valeriobasile/learningbyreading)
[KNEWS demo](http://gingerbeard.alwaysdata.net/knews/)
TWITA
--------------------------
The collection of tweets from Twitter in Italian language.
[Link](/twita/)
C&C API
-------
HTTP RESTful API to analyze English natural language using the
[C&C](http://svn.ask.it.usyd.edu.au/trac/candc) tools
and [Boxer](http://svn.ask.it.usyd.edu.au/trac/candc/wiki/boxer).
[Link](/candcapi/)
Delicious Folksonomy Dataset
------------------------------
A dataset obtained crawling [Delicious](https://delicious.com/), the social
bookmarking website.
[Link](/delicious/)
C&C/Boxer Web Interface
-----------------------
Web interface for the [C&C](http://svn.ask.it.usyd.edu.au/trac/candc)/[Boxer](http://svn.ask.it.usyd.edu.au/trac/candc/wiki/boxer)
linguistic analysis pipeline.
[Link](http://gmb.let.rug.nl/webdemo/)
Twitter Crawler
---------------
Python module to search and download messages from [Twitter](https://twitter.com).
[Link (github)](https://github.com/valeriobasile/twittercrawler)
Listnet
-------
[GNU Octave]() implementation of the Listnet learning-to-rank algorithm.
[Link (github)](https://github.com/valeriobasile/listnet)
The Groningen Meaning Bank
--------------------------
A large corpus of semantically annotated English text that anyone can edit.
[Link (external)](http://gmb.let.rug.nl/)
Wordrobe
------------------------------
A [Game With A Purpose](https://en.wikipedia.org/wiki/Human-based_computation_game) to collect linguistic annotation.
[Link (external)](http://www.wordrobe.org)
Elephant
-------
Word and sentence boundary detection software (a *tokenizer*, that is),
based on supervised statistical methods.
[Link (external)](http://gmb.let.rug.nl/elephant)
| valeriobasile/valeriobasile.github.io | projects.md | Markdown | mit | 2,523 |
#ifndef SIDECAR_GUI_PPIWIDGET_PATHSETTING_H // -*- C++ -*-
#define SIDECAR_GUI_PPIWIDGET_PATHSETTING_H
#include "QtWidgets/QLabel"
#include "QtWidgets/QPushButton"
#include "GUI/StringSetting.h"
namespace SideCar {
namespace GUI {
class PathSetting : public StringSetting {
Q_OBJECT
public:
PathSetting(PresetManager* mgr, QLabel* viewer, QPushButton* editor, const QString& prompt, const QString& types,
bool global = false);
private slots:
void choosePath();
private:
QString prompt_;
QString types_;
QString last_;
};
} // end namespace GUI
} // end namespace SideCar
#endif
| bradhowes/sidecar | GUI/PathSetting.h | C | mit | 626 |
''' This file contains tests for the bar plot.
'''
import matplotlib.pyplot as plt
import pytest
import shap
from .utils import explainer # (pytest fixture do not remove) pylint: disable=unused-import
@pytest.mark.mpl_image_compare
def test_simple_bar(explainer): # pylint: disable=redefined-outer-name
""" Check that the bar plot is unchanged.
"""
shap_values = explainer(explainer.data)
fig = plt.figure()
shap.plots.bar(shap_values, show=False)
plt.tight_layout()
return fig
| slundberg/shap | tests/plots/test_bar.py | Python | mit | 509 |
/**
* Hydro configuration
*
* @param {Hydro} hydro
*/
module.exports = function(hydro) {
hydro.set({
suite: 'equals',
timeout: 500,
plugins: [
require('hydro-chai'),
require('hydro-bdd')
],
chai: {
chai: require('chai'),
styles: ['should'],
stack: true
}
})
}
| jkroso/equals | test/hydro.conf.js | JavaScript | mit | 324 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_40) on Sun Oct 06 19:07:34 PDT 2013 -->
<title>pacman.controllers Class Hierarchy</title>
<meta name="date" content="2013-10-06">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="pacman.controllers Class Hierarchy";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../pacman/package-tree.html">Prev</a></li>
<li><a href="../../pacman/controllers/examples/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?pacman/controllers/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package pacman.controllers</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">pacman.controllers.<a href="../../pacman/controllers/Controller.html" title="class in pacman.controllers"><span class="strong">Controller</span></a><T> (implements java.lang.Runnable)
<ul>
<li type="circle">pacman.controllers.<a href="../../pacman/controllers/HumanController.html" title="class in pacman.controllers"><span class="strong">HumanController</span></a></li>
</ul>
</li>
<li type="circle">java.awt.event.KeyAdapter (implements java.awt.event.KeyListener)
<ul>
<li type="circle">pacman.controllers.<a href="../../pacman/controllers/KeyBoardInput.html" title="class in pacman.controllers"><span class="strong">KeyBoardInput</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../pacman/package-tree.html">Prev</a></li>
<li><a href="../../pacman/controllers/examples/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?pacman/controllers/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| bpgabin/pacman-vs-ghosts | doc/pacman/controllers/package-tree.html | HTML | mit | 4,702 |
# -*- coding: utf-8 -*-
from datetime import timedelta, datetime
import asyncio
import random
from .api import every, once_at, JobSchedule, default_schedule_manager
__all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday',
'every_thursday', 'every_friday', 'every_saturday', 'every_sunday',
'once_at_next_monday', 'once_at_next_tuesday', 'once_at_next_wednesday',
'once_at_next_thursday', 'once_at_next_friday', 'once_at_next_saturday',
'once_at_next_sunday', 'every_random_interval']
def every_random_interval(job, interval: timedelta, loop=None):
"""
executes the job randomly once in the specified interval.
example:
run a job every day at random time
run a job every hour at random time
:param job: a callable(co-routine function) which returns
a co-routine or a future or an awaitable
:param interval: the interval can also be given in the format of datetime.timedelta,
then seconds, minutes, hours, days, weeks parameters are ignored.
:param loop: io loop if the provided job is a custom future linked up
with a different event loop.
:return: schedule object, so it could be cancelled at will of the user by
aschedule.cancel(schedule)
"""
if loop is None:
loop = asyncio.get_event_loop()
start = loop.time()
def wait_time_gen():
count = 0
while True:
rand = random.randrange(round(interval.total_seconds()))
tmp = round(start + interval.total_seconds() * count + rand - loop.time())
yield tmp
count += 1
schedule = JobSchedule(job, wait_time_gen(), loop=loop)
# add it to default_schedule_manager, so that user can aschedule.cancel it
default_schedule_manager.add_schedule(schedule)
return schedule
def every_day(job, loop=None):
return every(job, timedelta=timedelta(days=1), loop=loop)
def every_week(job, loop=None):
return every(job, timedelta=timedelta(days=7), loop=loop)
every_monday = lambda job, loop=None: _every_weekday(job, 0, loop=loop)
every_tuesday = lambda job, loop=None: _every_weekday(job, 1, loop=loop)
every_wednesday = lambda job, loop=None: _every_weekday(job, 2, loop=loop)
every_thursday = lambda job, loop=None: _every_weekday(job, 3, loop=loop)
every_friday = lambda job, loop=None: _every_weekday(job, 4, loop=loop)
every_saturday = lambda job, loop=None: _every_weekday(job, 5, loop=loop)
every_sunday = lambda job, loop=None: _every_weekday(job, 6, loop=loop)
once_at_next_monday = lambda job, loop=None: _once_at_weekday(job, 0, loop=loop)
once_at_next_tuesday = lambda job, loop=None: _once_at_weekday(job, 1, loop=loop)
once_at_next_wednesday = lambda job, loop=None: _once_at_weekday(job, 2, loop=loop)
once_at_next_thursday = lambda job, loop=None: _once_at_weekday(job, 3, loop=loop)
once_at_next_friday = lambda job, loop=None: _once_at_weekday(job, 4, loop=loop)
once_at_next_saturday = lambda job, loop=None: _once_at_weekday(job, 5, loop=loop)
once_at_next_sunday = lambda job, loop=None: _once_at_weekday(job, 6, loop=loop)
def _nearest_weekday(weekday):
return datetime.now() + timedelta(days=(weekday - datetime.now().weekday()) % 7)
def _every_weekday(job, weekday, loop=None):
return every(job, timedelta=timedelta(days=7), start_at=_nearest_weekday(weekday), loop=loop)
def _once_at_weekday(job, weekday, loop=None):
return once_at(job, _nearest_weekday(weekday), loop=loop)
| eightnoteight/aschedule | aschedule/ext.py | Python | mit | 3,564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.