code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
line_mean
float64
0.5
100
line_max
int64
1
1k
alpha_frac
float64
0.25
1
autogenerated
bool
1 class
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>Boost::context future: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Boost::context future </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="class_future.html">Future</a></li><li class="navelem"><a class="el" href="struct_future_1_1_already_fulfilled.html">AlreadyFulfilled</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Future&lt; ValueType, ErrorType &gt;::AlreadyFulfilled Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="struct_future_1_1_already_fulfilled.html">Future&lt; ValueType, ErrorType &gt;::AlreadyFulfilled</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>what</b>() const noexcept (defined in <a class="el" href="struct_future_1_1_already_fulfilled.html">Future&lt; ValueType, ErrorType &gt;::AlreadyFulfilled</a>)</td><td class="entry"><a class="el" href="struct_future_1_1_already_fulfilled.html">Future&lt; ValueType, ErrorType &gt;::AlreadyFulfilled</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Jul 7 2015 13:05:59 for Boost::context future by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
disnesquick/coopfuture
doc/struct_future_1_1_already_fulfilled-members.html
HTML
mit
4,799
44.704762
427
0.654928
false
<?php use Illuminate\Database\Seeder; // composer require laracasts/testdummy use Laracasts\TestDummy\Factory as TestDummy; class UsersTableSeeder extends Seeder { public function run() { DB::table('users')->insert([ 'name' => 'system', 'email' => 'system@levelup.app', 'password' => bcrypt('system'), ]); } }
Ranthalion/LevelUp
database/seeds/UsersTableSeeder.php
PHP
mit
378
20
45
0.587302
false
package br.eti.qisolucoes.contactcloud.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/").authenticated() .antMatchers("/theme/**", "/plugins/**", "/page/**", "/", "/usuario/form", "/usuario/salvar").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginProcessingUrl("/login").loginPage("/login").permitAll().defaultSuccessUrl("/agenda/abrir", true) .and() .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); auth.userDetailsService(userDetailsService); } }
nosered/contact-cloud
src/main/java/br/eti/qisolucoes/contactcloud/config/SecurityConfig.java
Java
mit
1,557
41.081081
108
0.805395
false
package de.chandre.admintool.security.dbuser.repo; import java.util.List; import java.util.Set; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import de.chandre.admintool.security.dbuser.domain.ATRole; /** * * @author André * @since 1.1.7 */ @Repository public interface RoleRepository extends JpaRepository<ATRole, String> { ATRole findByName(String name); @Query("SELECT r.name FROM ATRole r") List<String> findAllRoleNames(); List<ATRole> findByNameIn(Set<String> ids); List<ATRole> findByIdIn(Set<String> ids); void deleteByName(String name); }
andrehertwig/admintool
admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/repo/RoleRepository.java
Java
mit
724
22.1
71
0.737206
false
#! /bin/bash defaults write com.apple.finder AppleShowAllFiles FALSE killall Finder
worp1900/niftySnippets
console/bash/mac/hideHiddenFilesInFinder.sh
Shell
mit
84
27
55
0.821429
false
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, fillIn } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | inputs/text-input', function (hooks) { setupRenderingTest(hooks); hooks.beforeEach(async function () { this.config = { value: '123 hello', name: 'myInput', disabled: false, autocomplete: 'name', texts: { placeholder: 'Your name', }, }; await render(hbs`<Inputs::TextInput @config={{config}} />`); }); test('it renders', async function (assert) { assert.dom('textarea').hasAttribute('name', 'myInput'); assert.dom('textarea').hasAttribute('autocomplete', 'name'); assert.dom('textarea').hasAttribute('placeholder', 'Your name'); }); test('it updates value', async function (assert) { assert.dom('textarea').hasValue('123 hello'); this.set('config.value', 'hello?'); assert.dom('textarea').hasValue('hello?'); await fillIn('textarea', 'bye!'); assert.equal(this.config.value, 'bye!'); }); test('it can be disabled', async function (assert) { assert.dom('textarea').isNotDisabled(); this.set('config.disabled', true); assert.dom('textarea').isDisabled(); }); test('it supports presence validations', async function (assert) { assert.dom('textarea').doesNotHaveAttribute('required'); this.set('config.validations', { required: true }); assert.dom('textarea').hasAttribute('required'); }); });
nibynic/ember-form-builder
tests/integration/components/inputs/text-input-test.js
JavaScript
mit
1,560
26.857143
72
0.641026
false
#!/usr/bin/env node var listCommand = []; require('./listCommand')(listCommand) var logDetail = (str) => { console.log(' > '+str); } var printHelp = () => { var txtHelp = ""; var h = ' '; var t = ' '; txtHelp += "\n"+h+"Usage : rider [command] \n"; txtHelp += "\n"+h+"Command List : \n"; var maxText = 0; if(listCommand == undefined){ logDetail("not found help detail"); return; } Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; if(maxText < item.name.length+item.params.length) maxText = item.name.length+item.params.length+4; }); var maxT = Math.ceil(maxText/4); Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; var x = (item.name.length+item.params.length+4)/4; x = Math.ceil(x); var space = '\t'; for (var i = 0; i < maxT-x-1; i++) { space += '\t'; } var txt = ""; if(item.params.length > 0){ space += '\t'; txt = '\t'+item.name +" [" +item.params+"] " + space +item.desc+"\n"; }else{ txt = '\t'+item.name + space +item.desc+"\n"; } txtHelp +=txt; txtHelp +"\n"; }); console.log(txtHelp); process.exit(0); } var parseParams = (params, cb) => { if(params.length < 3){ return cb(true); } cb(false); } var checkCommand = (cmd) => { var foundCmd = false; Object.keys(listCommand).forEach((keyName) => { if(keyName == cmd){ foundCmd = true; return; } }); return !foundCmd; } var runCommand = (params, cb) => { var opt = params[2]; var objRun = listCommand[opt]; if(objRun != undefined && objRun != null){ objRun.runCommand(params, cb); } } var main = () => { console.log(">> Rider ... "); var params = process.argv; parseParams(params, (err) => { if(err){ printHelp(); return; } var opt = params[2]; if(opt == "-h" || opt == "--help"){ printHelp(); return; } if(checkCommand(opt)){ printHelp(); return; } runCommand(params, () => { process.exit(0); }); }); } // -- call main function -- main();
khajer/rider.js
cli.js
JavaScript
mit
2,029
17.962617
72
0.566289
false
<?php /* * Arabian language */ $lang = [ 'albums' => 'Альбомы' ];
Speennaker/tanyaprykhodko
application/language/arabian/main_lang.php
PHP
mit
78
7
25
0.492958
false
// // RSAEncryptor.h // iOSProject // // Created by Alpha on 2017/6/12. // Copyright © 2017年 STT. All rights reserved. // #import <Foundation/Foundation.h> @interface RSAEncryptor : NSObject /** * 加密方法 * * @param str 需要加密的字符串 * @param path '.der'格式的公钥文件路径 */ + (NSString *)encryptString:(NSString *)str publicKeyWithContentsOfFile:(NSString *)path; /** * 解密方法 * * @param str 需要解密的字符串 * @param path '.p12'格式的私钥文件路径 * @param password 私钥文件密码 */ + (NSString *)decryptString:(NSString *)str privateKeyWithContentsOfFile:(NSString *)path password:(NSString *)password; /** * 加密方法 * * @param str 需要加密的字符串 * @param pubKey 公钥字符串 */ + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey; /** * 解密方法 * * @param str 需要解密的字符串 * @param privKey 私钥字符串 */ + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey; @end
STT-Ocean/iOSProject
iOSProject/iOSProject/iOSProject/Others/Cers/RSAEncryptor.h
C
mit
1,075
17.916667
120
0.651982
false
# Digital ecosystem dashboard This dashboard was technically and graphically made by [Sebcreation](http://www.sebcreation.com) ## Requirements This application requires [Node JS](http://nodejs.org/), the streaming build system [gulp.js](http://gulpjs.com/) and the [compass](http://compass-style.org/) ruby gem. After installing Node JS, gulp.js can easily be installed via Terminal : ``` $ npm install -g gulp ``` Compass can easily be installed via Terminal : ``` $ gem update --system $ gem install compass ``` Please refer the [user guide](http://compass-style.org/install/)
sebcreation/digital-ecosystem
README.md
Markdown
mit
590
24.652174
169
0.730508
false
<?php namespace Hal\Controller; /* * File: /app/code/core/system/base_controller.php * Purpose: Base class from which all controllers extend */ class Base_Controller { protected $action; public $cache; public $config; private $controller; private $controller_class; private $controller_filename; protected $core; protected $cron; protected $data; protected $db; protected $dispatcher; public $load; public $log; protected $model; protected $param; protected $route; public $session; public $template; public $toolbox; public $view; public function __construct($app) { $this->config = $app['config']; $this->core = $app; $this->cron = $app['cron']; $this->db = $app['database']; $this->dispatcher = $app['dispatcher']; $this->event = $app['event']; $this->load = $app['load']; $this->log = $app['log']; $this->model = $app['system_model']; $this->orm = $app['orm']; $this->route = $app['router']; $this->session = $app['session']; $this->template = $app['template']; $this->toolbox = $app['toolbox']; } public final function parse() { # Define child controller extending this class $this->controller = $this->route->controller; # The class name contained inside child controller $this->controller_class = $this->controller.'_Controller'; # File name of child controller $this->controller_filename = ucwords($this->controller_class).'.php'; # Action being requested from child controller $this->action = $this->route->action; $action = trim(strtolower($this->route->action)); # URL parameters $this->param = $this->route->param; # Pass controller information to view files; used for debugger $this->template->assign('controller', $this->controller); $this->template->assign('controller_class', $this->controller_class); $this->template->assign('controller_filename', $this->controller_filename); $this->template->assign('action', $action); # Admin, Public and Override classes $_admin_class = $this->controller_class; $_web_class = "\Web\Controller\\".$this->controller_class; $_override_class = "\Hal\ControllerOverride\\".$this->controller_class; # Check if the admin controller is being requested if ($this->controller == $this->config->setting('admin_controller') && is_readable(CORE_PATH.'controllers/'.$this->controller_filename) && $this->controller_filename) { # File was found and has proper file permissions require_once CORE_PATH.'controllers/'.$this->controller_filename; if (class_exists($_admin_class)) { # File found and class exists, so instantiate controller class $__instantiate_class = new $this->controller_class($this->core); if (method_exists($__instantiate_class, $action)) { # Class method exists $__instantiate_class->$action(); } else { # Valid controller, but invalid action $this->template->assign('controller_path', CORE_PATH.'controllers/'.$this->controller_filename); $this->template->assign('content', 'error/action.tpl'); } } else { # Controller file exists, but class name # is not formatted / spelled properly $this->template->assign('content', 'error/controller-bad-classname.tpl'); } } # First search for requested controller file in override directory elseif (is_readable(PUBLIC_OVERRIDE_PATH.'controllers/'.$this->controller_filename) && class_exists($_web_class)) { # File was found and has proper file permissions require_once PUBLIC_OVERRIDE_PATH.'controllers/'.$this->controller_filename; if (class_exists($_override_class)) { # File found and class exists, so instantiate controller class $__instantiate_class = new $_override_class($this->core); // if (!is_subclass_of($__instantiate_class, $_web_class)) // { // echo $_override_class . ' DOES NOT EXTEND ' . $_web_class; // } if (method_exists($__instantiate_class, $action)) { # Class method exists $__instantiate_class->$action(); } else { # Valid controller, but invalid action $this->template->assign('controller_path', PUBLIC_OVERRIDE_PATH.'controllers/'.$this->controller_filename); $this->template->assign('content', 'error/action.tpl'); } } else { # Controller file exists, but class name # is not formatted / spelled properly $this->template->assign('content', 'error/controller-bad-classname.tpl'); } } else { if (!is_readable($this->config->setting('controllers_path').$this->controller_filename)) { # Controller file does not exist, or # does not have read permissions if ($this->config->setting('debug_mode') === 'OFF' { return $this->redirect('error/_404'); } else { $controller = new \Web\Controller\Error_Controller($this->core); $controller->controller(); } } # Search for requested controller file in public directory if (is_readable($this->config->setting('controllers_path').$this->controller_filename) && $this->controller_filename) { # File was found and has proper file permissions require_once $this->config->setting('controllers_path').$this->controller_filename; if (class_exists($_web_class)) { # File found and class exists, so instantiate controller class $__instantiate_class = new $_web_class($this->core); if (method_exists($__instantiate_class, $action)) { # Class method exists $__instantiate_class->$action(); } else { # Valid controller, but invalid action if ($this->config->setting('debug_mode') === 'OFF' { $this->redirect('error/_404'); } else { $this->template->assign('controller_path', $this->config->setting('controllers_path').$this->controller_filename); $this->template->assign('content', 'error/action.tpl'); } } } else { # Controller file exists, but class name is not formatted / spelled properly if ($this->config->setting('debug_mode') === 'OFF' { $this->redirect('error/_404'); } else { $this->template->assign('content', 'error/controller-bad-classname.tpl'); } } } else { # Controller file does not exist, or # does not have read permissions if ($this->config->setting('debug_mode') === 'OFF' { $this->redirect('error/_404'); } else { $this->template->assign('content', 'error/controller.tpl'); } } } } public function model($model) { return $this->load->model("$model"); } public function redirect($url) { if ($url === 'http_referer') { return header('Location: '.$_SERVER['HTTP_REFERER']); exit; } return header('Location: '.BASE_URL.$url); } public function session() { return $this->toolbox('session'); } public function toolbox($helper) { # Load a Toolbox helper return $this->toolbox["$helper"]; } }
arout/diamondphp
app/code/core/system/controllers/Base_Controller.php
PHP
mit
6,878
33.913706
170
0.64888
false
--- title: While We're At It category: The Guts of FP order: 1 --- You won't get very far in most imperative languages without the humble `while` loop or one of it's variants such as `for`. Even though for loops are more commonly used, they are just syntactic sugar on while, so let's start there: {% highlight javascript %} let i = 0; while (i < someEndValue) { // do something interesting here i++; } {% endhighlight %} While it's possible for `someEndValue` to be anything it's extremely common for it to be the length of a collection. {% highlight javascript %} let i = 0; while (i < someCollection.length) { // do something with someCollection[i] here i++; } {% endhighlight %} This immediately brings up a problem, if we want to avoid mutating state, what useful thing could we do in the body of the while loop? While is not an expression, so we can't be returning a value. While demands that we mutate something inside the body, even if we are creating a new value each loop we're still rebinding the variable to a new value. This is as close to no-mutation as we can accomplish with while, but we're still clobbering that outer variable each time. {% highlight javascript %} let numbers = []; let i = 0; while (i < 5) { numbers.push(i); i++; } {% endhighlight %} Furthermore, since `while` is not an expression, there is no way to really combine it with anything else. This is a concept known as composition and we'll return to it later. Fortunately there's another construct that can be used to accomplish a looping structure but allows you to return a value at the end and doesn't need to mutate anything or reassign variables. This means you can use `const someValue = doTheThing(...)` or even `const someValue = doTheThing(...).andThen(...)`. You may have never thought about `recursion` this way, but it's true! > Recursion is the ability of a function to be applied to an argument inside itself. If done wrong this leads to an infinite chain of application in much the same way that forgetting the `i++` at the end of a `while` is an infinite loop. {% highlight javascript %} const populateArray = (numbers, i, endValue) => i < endValue ? populateArray([...numbers, i], i + 1, endValue) : numbers; const result = populateArray([], 0, 5); {% endhighlight %} The process of running this function would look like this. {% highlight javascript %} numbers i | | v v populateArray([], 0, 5) numbers i | | v v populateArray([0], 1, 5) numbers i | | v v populateArray([0, 1], 2, 5) numbers i | | v v populateArray([0, 1, 2], 3, 5) numbers i | | v v populateArray([0, 1, 2, 3], 4, 5) numbers i | | v v populateArray([0, 1, 2, 3, 4], 5, 5) {% endhighlight %} When we run `populateArray`, 0 is less than 5, so we recursively call `populateArray` again, but this time with `[0]` and `1` for the `numbers` and `i` arguments. This continues down until `i` is 5 at which point we return the current value of numbers which is `[0, 1, 2, 3, 4]`. This value is in turn returned by each prior `populateArray` and the final result is thus `[0, 1, 2, 3, 4]`. This may look more complex than the `while` example if you're not used to thinking recursively and using it in this manner. Hopefully though you see much of the operations we're performing are the same. - `i < 5` is the same as `i < endValue` - `numbers.push(i)` and `[...numbers, i]` are both adding an element to the array - `i++` and `i + 1` both move the counter up one Everything we could express in a while loop we can do via recursion and not need to mutate an outer variable along the way. With that said though, you probably don't write many while loops given there are constructs that more directly do what you want such as for. Let's look at a few common cases. #### Filter: reject unwanted values {% highlight javascript %} const itemsToKeep = []; for (var i = 0; i < collection.length; i++) { if (someCriteria(collection[i])) { itemsToKeep.push(collection[i]); } } {% endhighlight %} #### Map: transform values {% highlight javascript %} const newCollection = []; for (var i = 0; i < collection.length; i++) { newCollection.push( someOperation(collection[i]) ); } {% endhighlight %} If your language supports a `foreach` style iteration (`for x of y` in ES6) where the value itself is bound to a local variable instead of using an index, these could both be re-written using that. Both these cases have a striking amount of similarity. Hopefully you've noticed this at some point as well. In fact, almost every line of each of these two cases are the same - `const itemsToKeep = []` is `const newCollection = []` - `for (var i = 0; i < collection.length; i++) {` is identical for both - `itemsToKeep.push` is `newCollection.push` The only difference is that in the first case the item is conditionally added, and in the second, the item is processed before being added. This is the fundamental difference between the two operations, one filters out elements, the other maps one value to another. **_If the "when and what to insert" decision could be parameterized, then the rest of the code could be written once and not every time we need this construct._** ### Higher Order Functions To accomplish this feat we would need a function that could be parameterized by another function. {% highlight javascript %} const doThing = (someFunction, someValue) => someFunction(someValue); {% endhighlight %} What are `someFunction` and `someValue`? No idea! Here's a function that receives _another_ function as an argument and can use it to produce a return value. We can go in the opposite direction as well. {% highlight javascript %} const makeFunction = () => (someNumber) => someNumber + 1; const newFunction = makeFunction(); newFunction(5); // 6 {% endhighlight %} This is not particularly interesting, in fact a function written like this could be converted back to a constant like you're used to. {% highlight javascript %} const newFunction = (someNumber) => someNumber + 1; {% endhighlight %} The interesting part is simply that functions are just values and can be returned like any other value, although this is not particularly common in JavaScript. The first function does not need to have zero arguments, in fact it's often useful for it to have arguments since the function that is returned can see and reference those variables. {% highlight javascript %} const makeGreeting = (message) => (name) => message + " " + name; const jolly = makeGreeting("Hello there"); const grouchy = makeGreeting("Get off my lawn!"); jolly("Tina"); // "Hello there Tina" grouchy("Max"); // "Get off my lawn! Max" // we don't need to create an intermediate function makeGreeting("Look ma, no funtion, right")("Sam"); // "Look ma, no funtion, right Sam" {% endhighlight %} The inner returned functions can also be written on a single line {% highlight javascript %} const makeGreeting = (message) => (name) => message + " " + name; {% endhighlight %} > A function that receives another function as an argument, or returns a new function as a return value is known as a **higher order function**. This may not seem very useful at first, but let's apply the idea to the problem from before and see how this both helps eliminates the need for mutation of a variable, and solves a broad class of problems, all at once. ### Fold and Friends For any while loop of the shape with the form: - Initialize a new collection - Iterate over existing collection - Insert values into new collection there is a generalized solution known commonly as `fold`, `reduce`, or `aggregate`. general shape of: {% highlight javascript %} const newValue = fold(thingToDoWithEachNewElement, initialNewValue, collectionToIterateOver); {% endhighlight %} The `thingToDoWithEachNewElement` is a function that takes the working `initialNewValue` and combines it with an element from `collectionToIterateOver`. This might be done by doing a if check in the case of a filter type operation, or by running the element through a function first as in the case of the map type operation. Or it might be something unrelated to collections in the case of a sum type operation. #### Filter type operation {% highlight javascript %} const filterFn = (element, collection) => someCondition(element) ? [...collection, element] : collection; const someCondition = (x) => x > 5; filterFn(7, [4, 5]) // [4, 5, 7] filterFn(4, [4, 5]) // [4, 5] {% endhighlight %} #### Map type operation {% highlight javascript %} const mapFn = (element, collection) => [...collection, someOperation(element)]; const someOperation = (str) => str + "!"; mapFn("hi", []) // ["hi!"] mapFn("excited", ["I", "am"]) // ["I", "am", "excited!"] {% endhighlight %} And we could use these functions with `fold` in a more concrete setting: {% highlight javascript %} const filteredValues = fold(filterFn, [], [3, 4, 5, 6]); const transformedValues = fold(mapFn, [], ["programming", "is", "fun"]); {% endhighlight %} > This is generally the point where people's eyes glaze over as we begin to get a bit more abstract. From here on out, we will be working with concepts you likely have never encountered. This is genuinely hard to get at first, but the "different paradigm" type of understanding is on the other side, so hang in there! ### Exercise Ready for a challenge? Open `exercises/fold.js` in your editor and implement the `fold` function that can operate on arrays. Do this either using a for loop or using recursion (or try both). It matters much less how something like `fold` is implemented "under the hood" as long as the interface is pure. To test your changes, run `npm run -s fold` from the `exercises` directory. > Ask questions! ## [Next](/3-guts-of-fp/type-it-out)
wayfinderio/intro-to-fp
_docs/3-guts-of-fp/while-we-are-at-it.md
Markdown
mit
10,427
42.445833
553
0.678815
false
import { BaseController } from "./BaseController"; import { Route } from "./BaseController"; import * as loadHtml from "./HtmlLoader"; export class MainController extends BaseController { main = (): void => { loadHtml.load(this.requestData, '/views/index.html', {}); } routes: Route[] = [ new Route("/", this.main) ]; }
Kasperki/NodeBlog
blog/MainController.ts
TypeScript
mit
357
22.866667
65
0.613445
false
import React from "react"; import $ from "jquery"; import "bootstrap/dist/js/bootstrap.min"; import "jquery-ui/ui/widgets/datepicker"; import { postFulltimeEmployer, postParttimeEmployer, putFullTimeEmployer, putParttimeEmployer } from "../actions/PostData"; import DropDownBtn from "../components/DropDownBtn"; import {parseBirthdayForServer} from "../utils/Utils"; import {connect} from "react-redux"; class ModalEmployer extends React.Component { componentWillReceiveProps = (nextProps) => { if (nextProps.data) { this.setState(nextProps.data); if (nextProps.data.day_salary) { this.setState({ type: 'congNhat' }) } else { this.setState({ type: 'bienChe' }) } } if (nextProps.data == null) { this.setState(this.emptyObject) } } emptyObject = { "salary_level": "", "name": "", "month_salary": "", "phone": "", "birthday": "", "allowance": "", "department_id": this.props.departments.length > 0 ? this.props.departments[0].id : "", day_salary: "", } onClickSave = () => { let data = { "name": this.state.name, "phone": this.state.phone, "birthday": parseBirthdayForServer(this.state.birthday), "department_id": this.state.department_id, } if (this.state.type === "bienChe") { data.salary_level = this.state.salary_level; data.month_salary = this.state.month_salary; data.allowance = this.state.allowance; if (this.props.data) { putFullTimeEmployer(this.props.data.id, data, this.props.fetchEmployers); } else { postFulltimeEmployer(data, this.props.fetchEmployers); } } if (this.state.type === "congNhat") { data.day_salary = this.state.day_salary; if (this.props.data) { putParttimeEmployer(this.props.data.id, data, this.props.fetchEmployers); } else { postParttimeEmployer(data, this.props.fetchEmployers) } } $('#create').modal('toggle'); } constructor(props) { super(props); this.state = Object.assign(this.emptyObject, {type: null}) } onChangeText = (event) => { this.setState({ [event.target.name]: event.target.value }) } clickType = (type) => { this.setState({ type }) } componentDidMount = () => { $('#datepicker').datepicker({ uiLibrary: 'bootstrap4', iconsLibrary: 'fontawesome', onSelect: (dateText) => { this.setState({ birthday: dateText }) }, dateFormat: 'dd/mm/yy' }); } renderExtraForm = () => { if (this.state.type) { switch (this.state.type) { case "bienChe": return <div> <label htmlFor="id">Lương tháng</label> <div className="input-group"> <input onChange={this.onChangeText} name="month_salary" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.month_salary}/> </div> <label htmlFor="id">Bậc lương</label> <div className="input-group"> <input onChange={this.onChangeText} name="salary_level" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.salary_level}/> </div> <label htmlFor="id">Phụ cấp</label> <div className="input-group"> <input onChange={this.onChangeText} name="allowance" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.allowance}/> </div> </div> break; case "congNhat": return <div> <label htmlFor="id">Lương ngày</label> <div className="input-group"> <input name="day_salary" value={this.state.day_salary} onChange={this.onChangeText} type="text" className="form-control" id="id" aria-describedby="basic-addon3"/> </div> </div> break; } } } onSelectDepartment = (item) => { this.setState({ department_id: item.id }) } renderDropDownBtn = () => { if (this.props.departments.length > 0) { return ( <DropDownBtn onChange={this.onSelectDepartment} default data={this.props.departments}></DropDownBtn> ) } } render() { return ( <div className="modal fade" id="create" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLabel">Thêm nhân viên</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <label htmlFor="name">Tên nhân viên</label> <div className="input-group"> <input onChange={this.onChangeText} value={this.state.name} name="name" type="text" className="form-control" id="name" aria-describedby="basic-addon3"/> </div> <label htmlFor="datepicker">Ngày tháng năm sinh</label> <div className="input-group date" data-provide="datepicker"> <input onClick={this.onChangeText} onChange={this.onChangeText} value={this.state.birthday} name="birthday" type="text" className="form-control" id="datepicker"/> </div> <label htmlFor="phone">Số điện thoại</label> <div className="input-group"> <input onChange={this.onChangeText} value={this.state.phone} name="phone" type="text" className="form-control" id="phone" aria-describedby="basic-addon3"/> </div> <div className="btn-group"> <label htmlFor="name" className="margin-R10">Chọn phòng ban</label> {this.renderDropDownBtn()} </div> <div className="btn-group btn-middle align-middle"> { (() => { if (this.props.data) { if (this.props.data.day_salary === null) { return (<button className="btn btn-primary" id="bien-che">Nhân viên Biên chế </button>) } else { return ( <button className="btn btn-info" id="cong-nhat">Nhân viên Công nhật </button> ) } } else { let arr = []; arr.push(<button onClick={this.clickType.bind(this, "bienChe")} className="btn btn-primary" id="bien-che">Nhân viên Biên chế </button>); arr.push(<button onClick={this.clickType.bind(this, "congNhat")} className="btn btn-info" id="cong-nhat">Nhân viên Công nhật </button>); return arr; } })() } </div> { this.renderExtraForm() } </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data-dismiss="modal">Hủy</button> <button onClick={this.onClickSave} type="button" className="btn btn-primary">Lưu</button> </div> </div> </div> </div> ) } } const mapStateToProps = state => { return { departments: state.app.departments } } export default connect(mapStateToProps)(ModalEmployer)
liemnt/quanlynv
quanlynhanvien/src/components/ModalEmployer.js
JavaScript
mit
10,454
39.621094
120
0.415272
false
require 'spec_helper' describe Character do before do @character = Character.new(name: "Walder Frey", page: 'index.html') end subject { @character} it { should respond_to(:name)} it { should respond_to(:icon)} it { should respond_to(:page)} it { should respond_to(:degrees)} it { should respond_to(:all_relationships)} it { should respond_to(:children)} it { should respond_to(:parents)} it { should respond_to(:relationships)} it { should respond_to(:reverse_relationships)} it { should be_valid} describe "when name is not present" do before {@character.name = nil} it {should_not be_valid} end describe "when page is not present" do before {@character.page = nil} it {should_not be_valid} end describe "character with page already exists" do before do character_with_same_page = @character.dup character_with_same_page.page.upcase! character_with_same_page.save end it { should_not be_valid} end describe "character relationships" do before{ @character.save} let!(:child_character) do FactoryGirl.create(:character) end let!(:relationship) { @character.relationships.build(:child_id => child_character.id)} it "should display for both" do expect(@character.all_relationships.to_a).to eq child_character.all_relationships.to_a end it "should destroy relationships" do relationships = @character.relationships.to_a @character.destroy expect(relationships).not_to be_empty relationships.each do |relationship| expect(Relationship.where(:id => relationship.id)).to be_empty end end end end
thatguyandy27/DegreesOfWalderFrey
degrees_of_frey/spec/models/character_spec.rb
Ruby
mit
1,683
25.296875
92
0.675579
false
package net.sf.jabref.gui.util; import javafx.concurrent.Task; /** * An object that executes submitted {@link Task}s. This * interface provides a way of decoupling task submission from the * mechanics of how each task will be run, including details of thread * use, scheduling, thread pooling, etc. */ public interface TaskExecutor { /** * Runs the given task. * * @param task the task to run * @param <V> type of return value of the task */ <V> void execute(BackgroundTask<V> task); }
Mr-DLib/jabref
src/main/java/net/sf/jabref/gui/util/TaskExecutor.java
Java
mit
528
25.4
70
0.67803
false
require 'test_helper' class Test45sHelperTest < ActionView::TestCase end
thejhubbs/permissionary
test/dummy/test/helpers/test45s_helper_test.rb
Ruby
mit
74
17.5
46
0.810811
false
--- author: generalchoa comments: true date: 2014-01-31 23:22:32+00:00 layout: post slug: week13-day35b-beefmode title: Week13 - Day35B - Beefmode wordpress_id: 1429 categories: - B - StrongLifts tags: - agile 8 - deadlift - dips - incline db press - plank - preacher curls - push-up - seated db curls - shoulder shocker - squat - standing bb curls --- **Weight: **185 lbs ?? **Duration**:  11:45am - 1:02pm ~ 1hr. 17min. Time recorded is from when I started the pre-workout stretches until I started my post-workout stretches.  The Shoulder Shocker felt hugely improved, weights felt light for the first 2 sets.  Usually, I'm dying at the end of the second set.  Weight on the scale was at 187 this morning!  Getting into freshly washed and dried jeans was pretty tough, haha.  Legs are getting too beefy from all this squatting. **Squats:  **3x5xBar + 5x115 + 3x145 + 2x165 + 1x185 + 3x5x205 Went down pretty slow to control the bar and prevent tweaking the back.  This makes it quite a bit harder since I'm increasing time under the bar.  These are getting pretty heavy.  Getting close to the magical 225, 2-plate squat.  I think I may incorporate some back off sets, very similar to Madcow's heavy day scheme or Wendler's Boring But Big accessory. **Seated Plate Raises:  **3x10x25 **Seated Lateral Raise: **3x10x12 **Seated DB Shrug + Clean + Half Press:  **3x10x12 Able to get to the end of the second set without feeling dead.  Felt a huge improvement here.  Doing the cleaning movement, I'm using a more explosive pull to clean the dumbbells up instead just using all shoulders.  It is a clean after all. **Deadlift:  **5x135 + 3x165 + 2x185 + 1x215 + 1x240 + 5x265 Supinated left, regular right.  Pretty heavy, kept the bar glued to my shins.  Not sure if I was rounding, but my low back wasn't killing me afterwards. **Accessories: **Preacher BB Curls:  **14x50** Incline DB Press:  **10x50** Standing EZ Bar Curls:  10x40 Dips:  **12**/4/4 Seated DB Curls:  **10x30** Pushups:  10/10/8 Cranked out some extra reps on the 50lb preacher.  I think once I get to 18+ reps on the 50, I'm going to jump up.  Went up to 50lbs on the incline db press.  These were pretty difficult, so definitely sticking to 50s for a while.  Dips are still improving, both in strength and endurance.  Pushups felt improved today as well.  Going to for 3 sets of 10 reps across next time. **Core: **Elbow Planks: **1min.** Burn, baby, burn.
mbchoa/discipline
_posts/2014-01-31-week13-day35b-beefmode.markdown
Markdown
mit
2,473
41.051724
408
0.735957
false
package com.mgireesh; public class Solution extends VersionControl { public int firstBadVersion(int n) { int badVersion = 0; int start = 1; int end = n; while (start < end) { int mid = start + (end - start) / 2; if (isBadVersion(mid)) { end = mid; } else { start = mid + 1; } } return start; } }
mgireesh05/leetcode
first-bad-version/src/com/mgireesh/Solution.java
Java
mit
331
16.473684
46
0.592145
false
<?php namespace Aurex\Framework\Module\Modules\FormDoctrineModule; use Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension, Silex\Provider\TranslationServiceProvider, Aurex\Framework\Module\ModuleInterface, Silex\Provider\SessionServiceProvider, Silex\Provider\FormServiceProvider, Aurex\Framework\Aurex; /** * Class FormDoctrineModule * * @package Aurex\Framework\Module\Modules\FormDoctrineModule */ class FormDoctrineModule implements ModuleInterface { /** * {@inheritDoc} */ public function integrate(Aurex $aurex) { $aurex->register(new FormServiceProvider); $aurex->register(new SessionServiceProvider); $aurex->register(new TranslationServiceProvider, [ 'locale' => 'en' ]); $aurex['form.extensions'] = $aurex->extend('form.extensions', function ($extensions, $app) { $managerRegistry = new FormManagerRegistry(null, [], ['default'], null, null, '\Doctrine\ORM\Proxy\Proxy'); $managerRegistry->setContainer($app); unset($extensions); return [(new DoctrineOrmExtension($managerRegistry))]; }); $aurex->getInjector()->share($aurex['form.factory']); } /** * {@inheritDoc} */ public function usesConfigurationKey() { return null; } }
J7mbo/Aurex
lib/Framework/Module/Modules/FormDoctrineModule/FormDoctrineModule.php
PHP
mit
1,340
27.531915
119
0.653731
false
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - matrix_expressions_ex.cpp</title></head><body bgcolor='white'><pre> <font color='#009900'>// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt </font> <font color='#009900'>/* This example contains a detailed discussion of the template expression technique used to implement the matrix tools in the dlib C++ library. It also gives examples showing how a user can create their own custom matrix expressions. Note that you should be familiar with the dlib::matrix before reading this example. So if you haven't done so already you should read the matrix_ex.cpp example program. */</font> <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>iostream<font color='#5555FF'>&gt;</font> <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>dlib<font color='#5555FF'>/</font>matrix.h<font color='#5555FF'>&gt;</font> <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> dlib; <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> std; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>void</u></font> <b><a name='custom_matrix_expressions_example'></a>custom_matrix_expressions_example</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>int</u></font> <b><a name='main'></a>main</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <b>{</b> <font color='#009900'>// Declare some variables used below </font> matrix<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>double</u></font>,<font color='#979000'>3</font>,<font color='#979000'>1</font><font color='#5555FF'>&gt;</font> y; matrix<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>double</u></font>,<font color='#979000'>3</font>,<font color='#979000'>3</font><font color='#5555FF'>&gt;</font> M; matrix<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>double</u></font><font color='#5555FF'>&gt;</font> x; <font color='#009900'>// set all elements to 1 </font> y <font color='#5555FF'>=</font> <font color='#979000'>1</font>; M <font color='#5555FF'>=</font> <font color='#979000'>1</font>; <font color='#009900'>// ------------------------- Template Expressions ----------------------------- </font> <font color='#009900'>// Now I will discuss the "template expressions" technique and how it is </font> <font color='#009900'>// used in the matrix object. First consider the following expression: </font> x <font color='#5555FF'>=</font> y <font color='#5555FF'>+</font> y; <font color='#009900'>/* Normally this expression results in machine code that looks, at a high level, like the following: temp = y + y; x = temp Temp is a temporary matrix returned by the overloaded + operator. temp then contains the result of adding y to itself. The assignment operator copies the value of temp into x and temp is then destroyed while the blissful C++ user never sees any of this. This is, however, totally inefficient. In the process described above you have to pay for the cost of constructing a temporary matrix object and allocating its memory. Then you pay the additional cost of copying it over to x. It also gets worse when you have more complex expressions such as x = round(y + y + y + M*y) which would involve the creation and copying of 5 temporary matrices. All these inefficiencies are removed by using the template expressions technique. The basic idea is as follows, instead of having operators and functions return temporary matrix objects you return a special object that represents the expression you wish to perform. So consider the expression x = y + y again. With dlib::matrix what happens is the expression y+y returns a matrix_exp object instead of a temporary matrix. The construction of a matrix_exp does not allocate any memory or perform any computations. The matrix_exp however has an interface that looks just like a dlib::matrix object and when you ask it for the value of one of its elements it computes that value on the spot. Only in the assignment operator does someone ask the matrix_exp for these values so this avoids the use of any temporary matrices. Thus the statement x = y + y is equivalent to the following code: // loop over all elements in y matrix for (long r = 0; r &lt; y.nr(); ++r) for (long c = 0; c &lt; y.nc(); ++c) x(r,c) = y(r,c) + y(r,c); This technique works for expressions of arbitrary complexity. So if you typed x = round(y + y + y + M*y) it would involve no temporary matrices being created at all. Each operator takes and returns only matrix_exp objects. Thus, no computations are performed until the assignment operator requests the values from the matrix_exp it receives as input. There is, however, a slight complication in all of this. It is for statements that involve the multiplication of a complex matrix_exp such as the following: */</font> x <font color='#5555FF'>=</font> M<font color='#5555FF'>*</font><font face='Lucida Console'>(</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font color='#5555FF'>+</font>M<font face='Lucida Console'>)</font>; <font color='#009900'>/* According to the discussion above, this statement would compute the value of M*(M+M+M+M+M+M+M) totally without any temporary matrix objects. This sounds good but we should take a closer look. Consider that the + operator is invoked 6 times. This means we have something like this: x = M * (matrix_exp representing M+M+M+M+M+M+M); M is being multiplied with a quite complex matrix_exp. Now recall that when you ask a matrix_exp what the value of any of its elements are it computes their values *right then*. If you think on what is involved in performing a matrix multiply you will realize that each element of a matrix is accessed M.nr() times. In the case of our above expression the cost of accessing an element of the matrix_exp on the right hand side is the cost of doing 6 addition operations. Thus, it would be faster to assign M+M+M+M+M+M+M to a temporary matrix and then multiply that by M. This is exactly what the dlib::matrix does under the covers. This is because it is able to spot expressions where the introduction of a temporary is needed to speed up the computation and it will automatically do this for you. Another complication that is dealt with automatically is aliasing. All matrix expressions are said to "alias" their contents. For example, consider the following expressions: M + M M * M We say that the expressions (M + M) and (M * M) alias M. Additionally, we say that the expression (M * M) destructively aliases M. To understand why we say (M * M) destructively aliases M consider what would happen if we attempted to evaluate it without first assigning (M * M) to a temporary matrix. That is, if we attempted to perform the following: for (long r = 0; r &lt; M.nr(); ++r) for (long c = 0; c &lt; M.nc(); ++c) M(r,c) = rowm(M,r)*colm(M,c); It is clear that the result would be corrupted and M wouldn't end up with the right values in it. So in this case we must perform the following: temp = M*M; M = temp; This sort of interaction is what defines destructive aliasing. Whenever we are assigning a matrix expression to a destination that is destructively aliased by the expression we need to introduce a temporary. The dlib::matrix is capable of recognizing the two forms of aliasing and introduces temporary matrices only when necessary. */</font> <font color='#009900'>// Next we discuss how to create custom matrix expressions. In what follows we </font> <font color='#009900'>// will define three different matrix expressions and show their use. </font> <font color='#BB00BB'>custom_matrix_expressions_example</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> M<font color='#5555FF'>&gt;</font> <font color='#0000FF'>struct</font> <b><a name='example_op_trans'></a>example_op_trans</b> <b>{</b> <font color='#009900'>/*! This object defines a matrix expression that represents a transposed matrix. As discussed above, constructing this object doesn't compute anything. It just holds a reference to a matrix and presents an interface which defines matrix transposition. !*/</font> <font color='#009900'>// Here we simply hold a reference to the matrix we are supposed to be the transpose of. </font> <b><a name='example_op_trans'></a>example_op_trans</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> M<font color='#5555FF'>&amp;</font> m_<font face='Lucida Console'>)</font> : m<font face='Lucida Console'>(</font>m_<font face='Lucida Console'>)</font><b>{</b><b>}</b> <font color='#0000FF'>const</font> M<font color='#5555FF'>&amp;</font> m; <font color='#009900'>// The cost field is used by matrix multiplication code to decide if a temporary needs to </font> <font color='#009900'>// be introduced. It represents the computational cost of evaluating an element of the </font> <font color='#009900'>// matrix expression. In this case we say that the cost of obtaining an element of the </font> <font color='#009900'>// transposed matrix is the same as obtaining an element of the original matrix (since </font> <font color='#009900'>// transpose doesn't really compute anything). </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> cost <font color='#5555FF'>=</font> M::cost; <font color='#009900'>// Here we define the matrix expression's compile-time known dimensions. Since this </font> <font color='#009900'>// is a transpose we define them to be the reverse of M's dimensions. </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> M::NC; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> M::NR; <font color='#009900'>// Define the type of element in this matrix expression. Also define the </font> <font color='#009900'>// memory manager type used and the layout. Usually we use the same types as the </font> <font color='#009900'>// input matrix. </font> <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::type type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::mem_manager_type mem_manager_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::layout_type layout_type; <font color='#009900'>// This is where the action is. This function is what defines the value of an element of </font> <font color='#009900'>// this matrix expression. Here we are saying that m(c,r) == trans(m)(r,c) which is just </font> <font color='#009900'>// the definition of transposition. Note also that we must define the return type from this </font> <font color='#009900'>// function as a typedef. This typedef lets us either return our argument by value or by </font> <font color='#009900'>// reference. In this case we use the same type as the underlying m matrix. Later in this </font> <font color='#009900'>// example program you will see two other options. </font> <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::const_ret_type const_ret_type; const_ret_type <b><a name='apply'></a>apply</b> <font face='Lucida Console'>(</font><font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> c<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#BB00BB'>m</font><font face='Lucida Console'>(</font>c,r<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// Define the run-time defined dimensions of this matrix. </font> <font color='#0000FF'><u>long</u></font> <b><a name='nr'></a>nr</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>nc</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nc'></a>nc</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>nr</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// Recall the discussion of aliasing. Each matrix expression needs to define what </font> <font color='#009900'>// kind of aliasing it introduces so that we know when to introduce temporaries. The </font> <font color='#009900'>// aliases() function indicates that the matrix transpose expression aliases item if </font> <font color='#009900'>// and only if the m matrix aliases item. </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='aliases'></a>aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>aliases</font><font face='Lucida Console'>(</font>item<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// This next function indicates that the matrix transpose expression also destructively </font> <font color='#009900'>// aliases anything m aliases. I.e. transpose has destructive aliasing. </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='destructively_aliases'></a>destructively_aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>aliases</font><font face='Lucida Console'>(</font>item<font face='Lucida Console'>)</font>; <b>}</b> <b>}</b>; <font color='#009900'>// Here we define a simple function that creates and returns transpose expressions. Note that the </font><font color='#009900'>// matrix_op&lt;&gt; template is a matrix_exp object and exists solely to reduce the amount of boilerplate </font><font color='#009900'>// you have to write to create a matrix expression. </font><font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> M <font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> matrix_op<font color='#5555FF'>&lt;</font>example_op_trans<font color='#5555FF'>&lt;</font>M<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b><a name='example_trans'></a>example_trans</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>M<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> m <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>typedef</font> example_op_trans<font color='#5555FF'>&lt;</font>M<font color='#5555FF'>&gt;</font> op; <font color='#009900'>// m.ref() returns a reference to the object of type M contained in the matrix expression m. </font> <font color='#0000FF'>return</font> matrix_op<font color='#5555FF'>&lt;</font>op<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font color='#BB00BB'>op</font><font face='Lucida Console'>(</font>m.<font color='#BB00BB'>ref</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> T<font color='#5555FF'>&gt;</font> <font color='#0000FF'>struct</font> <b><a name='example_op_vector_to_matrix'></a>example_op_vector_to_matrix</b> <b>{</b> <font color='#009900'>/*! This object defines a matrix expression that holds a reference to a std::vector&lt;T&gt; and makes it look like a column vector. Thus it enables you to use a std::vector as if it was a dlib::matrix. !*/</font> <b><a name='example_op_vector_to_matrix'></a>example_op_vector_to_matrix</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> std::vector<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> vect_<font face='Lucida Console'>)</font> : vect<font face='Lucida Console'>(</font>vect_<font face='Lucida Console'>)</font><b>{</b><b>}</b> <font color='#0000FF'>const</font> std::vector<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> vect; <font color='#009900'>// This expression wraps direct memory accesses so we use the lowest possible cost. </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> cost <font color='#5555FF'>=</font> <font color='#979000'>1</font>; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> <font color='#979000'>0</font>; <font color='#009900'>// We don't know the length of the vector until runtime. So we put 0 here. </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> <font color='#979000'>1</font>; <font color='#009900'>// We do know that it only has one column (since it's a vector) </font> <font color='#0000FF'>typedef</font> T type; <font color='#009900'>// Since the std::vector doesn't use a dlib memory manager we list the default one here. </font> <font color='#0000FF'>typedef</font> default_memory_manager mem_manager_type; <font color='#009900'>// The layout type also doesn't really matter in this case. So we list row_major_layout </font> <font color='#009900'>// since it is a good default. </font> <font color='#0000FF'>typedef</font> row_major_layout layout_type; <font color='#009900'>// Note that we define const_ret_type to be a reference type. This way we can </font> <font color='#009900'>// return the contents of the std::vector by reference. </font> <font color='#0000FF'>typedef</font> <font color='#0000FF'>const</font> T<font color='#5555FF'>&amp;</font> const_ret_type; const_ret_type <b><a name='apply'></a>apply</b> <font face='Lucida Console'>(</font><font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> vect[r]; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nr'></a>nr</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> vect.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nc'></a>nc</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#979000'>1</font>; <b>}</b> <font color='#009900'>// This expression never aliases anything since it doesn't contain any matrix expression (it </font> <font color='#009900'>// contains only a std::vector which doesn't count since you can't assign a matrix expression </font> <font color='#009900'>// to a std::vector object). </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='aliases'></a>aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#979000'>false</font>; <b>}</b> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='destructively_aliases'></a>destructively_aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#979000'>false</font>; <b>}</b> <b>}</b>; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> T <font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> matrix_op<font color='#5555FF'>&lt;</font>example_op_vector_to_matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b><a name='example_vector_to_matrix'></a>example_vector_to_matrix</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> std::vector<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> vector <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>typedef</font> example_op_vector_to_matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font> op; <font color='#0000FF'>return</font> matrix_op<font color='#5555FF'>&lt;</font>op<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font color='#BB00BB'>op</font><font face='Lucida Console'>(</font>vector<font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> M, <font color='#0000FF'>typename</font> T<font color='#5555FF'>&gt;</font> <font color='#0000FF'>struct</font> <b><a name='example_op_add_scalar'></a>example_op_add_scalar</b> <b>{</b> <font color='#009900'>/*! This object defines a matrix expression that represents a matrix with a single scalar value added to all its elements. !*/</font> <b><a name='example_op_add_scalar'></a>example_op_add_scalar</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> M<font color='#5555FF'>&amp;</font> m_, <font color='#0000FF'>const</font> T<font color='#5555FF'>&amp;</font> val_<font face='Lucida Console'>)</font> : m<font face='Lucida Console'>(</font>m_<font face='Lucida Console'>)</font>, val<font face='Lucida Console'>(</font>val_<font face='Lucida Console'>)</font><b>{</b><b>}</b> <font color='#009900'>// A reference to the matrix </font> <font color='#0000FF'>const</font> M<font color='#5555FF'>&amp;</font> m; <font color='#009900'>// A copy of the scalar value that should be added to each element of m </font> <font color='#0000FF'>const</font> T val; <font color='#009900'>// This time we add 1 to the cost since evaluating an element of this </font> <font color='#009900'>// expression means performing 1 addition operation. </font> <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> cost <font color='#5555FF'>=</font> M::cost <font color='#5555FF'>+</font> <font color='#979000'>1</font>; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> M::NR; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> M::NC; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::type type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::mem_manager_type mem_manager_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> M::layout_type layout_type; <font color='#009900'>// Note that we declare const_ret_type to be a non-reference type. This is important </font> <font color='#009900'>// since apply() computes a new temporary value and thus we can't return a reference </font> <font color='#009900'>// to it. </font> <font color='#0000FF'>typedef</font> type const_ret_type; const_ret_type <b><a name='apply'></a>apply</b> <font face='Lucida Console'>(</font><font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> c<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#BB00BB'>m</font><font face='Lucida Console'>(</font>r,c<font face='Lucida Console'>)</font> <font color='#5555FF'>+</font> val; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nr'></a>nr</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>nr</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'><u>long</u></font> <b><a name='nc'></a>nc</b> <font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>nc</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// This expression aliases anything m aliases. </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='aliases'></a>aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>aliases</font><font face='Lucida Console'>(</font>item<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// Unlike the transpose expression. This expression only destructively aliases something if m does. </font> <font color='#009900'>// So this expression has the regular non-destructive kind of aliasing. </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='destructively_aliases'></a>destructively_aliases</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> m.<font color='#BB00BB'>destructively_aliases</font><font face='Lucida Console'>(</font>item<font face='Lucida Console'>)</font>; <b>}</b> <b>}</b>; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> M, <font color='#0000FF'>typename</font> T <font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> matrix_op<font color='#5555FF'>&lt;</font>example_op_add_scalar<font color='#5555FF'>&lt;</font>M,T<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b><a name='add_scalar'></a>add_scalar</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>M<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> m, T val <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>typedef</font> example_op_add_scalar<font color='#5555FF'>&lt;</font>M,T<font color='#5555FF'>&gt;</font> op; <font color='#0000FF'>return</font> matrix_op<font color='#5555FF'>&lt;</font>op<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font color='#BB00BB'>op</font><font face='Lucida Console'>(</font>m.<font color='#BB00BB'>ref</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>, val<font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>void</u></font> <b><a name='custom_matrix_expressions_example'></a>custom_matrix_expressions_example</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <b>{</b> matrix<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>double</u></font><font color='#5555FF'>&gt;</font> <font color='#BB00BB'>x</font><font face='Lucida Console'>(</font><font color='#979000'>2</font>,<font color='#979000'>3</font><font face='Lucida Console'>)</font>; x <font color='#5555FF'>=</font> <font color='#979000'>1</font>, <font color='#979000'>1</font>, <font color='#979000'>1</font>, <font color='#979000'>2</font>, <font color='#979000'>2</font>, <font color='#979000'>2</font>; cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> x <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>// Finally, lets use the matrix expressions we defined above. </font> <font color='#009900'>// prints the transpose of x </font> cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>example_trans</font><font face='Lucida Console'>(</font>x<font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>// prints this: </font> <font color='#009900'>// 11 11 11 </font> <font color='#009900'>// 12 12 12 </font> cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>add_scalar</font><font face='Lucida Console'>(</font>x, <font color='#979000'>10</font><font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>// matrix expressions can be nested, even the user defined ones. </font> <font color='#009900'>// the following statement prints this: </font> <font color='#009900'>// 11 12 </font> <font color='#009900'>// 11 12 </font> <font color='#009900'>// 11 12 </font> cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>example_trans</font><font face='Lucida Console'>(</font><font color='#BB00BB'>add_scalar</font><font face='Lucida Console'>(</font>x, <font color='#979000'>10</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>// Since we setup the alias detection correctly we can even do this: </font> x <font color='#5555FF'>=</font> <font color='#BB00BB'>example_trans</font><font face='Lucida Console'>(</font><font color='#BB00BB'>add_scalar</font><font face='Lucida Console'>(</font>x, <font color='#979000'>10</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>new x:\n</font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> x <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>Do some testing with the example_vector_to_matrix() function: </font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; std::vector<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>float</u></font><font color='#5555FF'>&gt;</font> vect; vect.<font color='#BB00BB'>push_back</font><font face='Lucida Console'>(</font><font color='#979000'>1</font><font face='Lucida Console'>)</font>; vect.<font color='#BB00BB'>push_back</font><font face='Lucida Console'>(</font><font color='#979000'>3</font><font face='Lucida Console'>)</font>; vect.<font color='#BB00BB'>push_back</font><font face='Lucida Console'>(</font><font color='#979000'>5</font><font face='Lucida Console'>)</font>; <font color='#009900'>// Now lets treat our std::vector like a matrix and print some things. </font> cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>example_vector_to_matrix</font><font face='Lucida Console'>(</font>vect<font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; cout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#BB00BB'>add_scalar</font><font face='Lucida Console'>(</font><font color='#BB00BB'>example_vector_to_matrix</font><font face='Lucida Console'>(</font>vect<font face='Lucida Console'>)</font>, <font color='#979000'>10</font><font face='Lucida Console'>)</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> endl; <font color='#009900'>/* As an aside, note that dlib contains functions equivalent to the ones we defined above. They are: - dlib::trans() - dlib::mat() (converts things into matrices) - operator+ (e.g. you can say my_mat + 1) Also, if you are going to be creating your own matrix expression you should also look through the matrix code in the dlib/matrix folder. There you will find many other examples of matrix expressions. */</font> <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> </pre></body></html>
kaathleen/LeapGesture-library
DynamicGestures/dlib-18.5/docs/matrix_expressions_ex.cpp.html
HTML
mit
37,000
91.27182
704
0.641973
false
define('exports@*', [], function(require, exports, module){ exports.a = 1; });
kaelzhang/neuron
test/mod/exports/*/exports.js
JavaScript
mit
84
16
59
0.595238
false
package types // ApiVersion custom ENUM for SDK forward compatibility type ApiVersion int const ( ApiV1 ApiVersion = iota ) // EnvironmentType // https://docs.coinapi.io/#endpoints-2 type EnvironmentType int const ( ProdEncrypted EnvironmentType = iota ProdInsecure TestEncrypted TestInsecure ) // MessageType replicates the official incoming message types as (kinda) string enum. // https://docs.coinapi.io/#messages type MessageType string const ( TRADE MessageType = "trade" QUOTE MessageType = "quote" BOOK_L2_FULL MessageType = "book" // Orderbook L2 (Full) BOOK_L2_TOP_5 MessageType = "book5" // Orderbook L2 (5 best Bid / Ask) BOOK_L2_TOP_20 MessageType = "book20" // Orderbook L2 (20 best Bid / Ask) BOOK_L2_TOP_50 MessageType = "book50" // Orderbook L2 (50 best Bid / Ask) BOOK_L3_FULL MessageType = "book_l3" // Orderbook L3 (Full) https://docs.coinapi.io/#orderbook-l3-full-in OHLCV MessageType = "ohlcv" VOLUME MessageType = "volume" HEARTBEAT MessageType = "hearbeat" // DO NOT FIX! it's a typo in the official msg spec! ERROR MessageType = "error" // Otherwise processMessage(.) fails to handle heartbeat messages! EXCHANGERATE MessageType = "exrate" RECONNECT MessageType = "reconnect" ) // ReconnectType defines the reconnect behavior upon receiving a reconnect message // https://docs.coinapi.io/#reconnect-in type ReconnectType int const ( OnConnectionClose ReconnectType = iota OnReconnectMessage )
coinapi/coinapi-sdk
data-api/go-ws/api/types/enums.go
GO
mit
1,517
30.604167
108
0.714568
false
require 'rubygems' require 'bundler' Bundler.require require 'sinatra' set :public_folder, 'static' get '/' do File.read(File.join('index.html')) end get '/api/' do #content_type :js content_type("application/javascript") response["Content-Type"] = "application/javascript" #require 'config/initializers/beamly.rb' root = ::File.dirname(__FILE__) require ::File.join( root, 'config', 'initializers', 'beamly' ) #require 'config/initializers/beamly' z = Beamly::Epg.new region_id = z.regions.first.id provider_id = z.providers.first.id result = z.catalogues(region_id, provider_id) services = z.epg(result.first.epg_id) today = Date.today.strftime("%Y/%m/%d") schedule = z.schedule(services[8].service_id, today) today_formatted = Date.today.strftime("%Y-%m-%d") headers "Content-Type" => "application/json" json = '[' schedule.each do |item| time_formatted = Time.at(item.start).getlocal.strftime("%Y-%m-%d %H:%M") json += ' { "date": "'+time_formatted+'", "episodes": [ { "show": { "title": "'+item.title+'", "year": 2013, "genres": ["Comedy"], }, "episode":{"images": {"screen": "http://img-a.zeebox.com/940x505/'+item.img+'"}} } ] }, ' end json += ']' formatted_callback = "#{params['callback']}("+json+')' content_type("application/javascript") response["Content-Type"] = "application/javascript" formatted_callback end
TigerWolf/beamly_demo
main.rb
Ruby
mit
1,529
23.66129
90
0.59516
false
using System.Threading.Tasks; using FluentAssertions; using Histrio.Testing; using Xunit; namespace Histrio.Tests.Cell { public class When_getting_a_value_from_a_cell : GivenWhenThen { [Theory, InlineData(true), InlineData(333), InlineData(new[] {true, true}), InlineData("foo")] public void Then_value_the_cell_is_holding_on_to_is_returned<T>(T expectedValue) { var theater = new Theater(); var taskCompletionSource = new TaskCompletionSource<Reply<T>>(); ; Address customer = null; Address cell = null; Given(() => { cell = theater.CreateActor(new CellBehavior<T>()); var set = new Set<T>(expectedValue); theater.Dispatch(set, cell); customer = theater.CreateActor(new AssertionBehavior<Reply<T>>(taskCompletionSource, 1)); }); When(() => { var get = new Get(customer); theater.Dispatch(get, cell); }); Then(async () => { var actualValue = await taskCompletionSource.Task; actualValue.Content.ShouldBeEquivalentTo(expectedValue); }); } } }
MCGPPeters/Histrio
old/src/Histrio.Tests/Cell/When_getting_a_value_from_a_cell.cs
C#
mit
1,321
29.045455
105
0.529902
false
using System.Collections; using System.Collections.Generic; using UnityEngine; public class oscilation : MonoBehaviour { public float m_speed = 0.008f; public int m_distance = 45; private int compteur = 0; private int compteur2 = 0; // Use this for initialization void Start () { Vector3 yOrigin = transform.localPosition; /*Vector3 move = new Vector3(0.0f,0.0f,0.0f); Vector3 move2 = new Vector3(0.0f,0.0f,0.0f); move.y = m_speed; move2.y = -m_speed;*/ } // Update is called once per frame void Update () { if (compteur < m_distance) { Vector3 move = new Vector3(0.0f,0.0f,0.0f); move.y = m_speed; transform.localPosition = transform.localPosition + move; compteur++; } else if (compteur2 < m_distance) { Vector3 move2 = new Vector3(0.0f,0.0f,0.0f); move2.y = -m_speed; compteur2++; transform.localPosition = transform.localPosition + move2; } else { compteur = 0; compteur2 = 0; } } }
Wormkil/firstProject
Assets/oscilation.cs
C#
mit
962
19.869565
61
0.661458
false
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Web; using System.Web.Mvc; using Transit.Models; namespace Transit.Controllers { public class RoutesController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); // GET: Routes public async Task<ActionResult> Index() { var routes = db.Routes.Include(r => r.agency).Include(r => r.type); return View(await routes.ToListAsync()); } // GET: Routes/Details/5 public async Task<ActionResult> Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Route route = await db.Routes.FindAsync(id); if (route == null) { return HttpNotFound(); } return View(route); } // GET: Routes/Create public ActionResult Create() { ViewBag.agencyId = new SelectList(db.Agencies, "id", "name"); ViewBag.typeId = new SelectList(db.RouteTypes, "id", "label"); return View(); } // POST: Routes/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "id,agencyId,label,fullName,description,typeId,url,color,textColor")] Route route) { if (ModelState.IsValid) { db.Routes.Add(route); await db.SaveChangesAsync(); return RedirectToAction("Index"); } ViewBag.agencyId = new SelectList(db.Agencies, "id", "name", route.agencyId); ViewBag.typeId = new SelectList(db.RouteTypes, "id", "label", route.typeId); return View(route); } // GET: Routes/Edit/5 public async Task<ActionResult> Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Route route = await db.Routes.FindAsync(id); if (route == null) { return HttpNotFound(); } ViewBag.agencyId = new SelectList(db.Agencies, "id", "name", route.agencyId); ViewBag.typeId = new SelectList(db.RouteTypes, "id", "label", route.typeId); return View(route); } // POST: Routes/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "id,agencyId,label,fullName,description,typeId,url,color,textColor")] Route route) { if (ModelState.IsValid) { db.Entry(route).State = EntityState.Modified; await db.SaveChangesAsync(); return RedirectToAction("Index"); } ViewBag.agencyId = new SelectList(db.Agencies, "id", "name", route.agencyId); ViewBag.typeId = new SelectList(db.RouteTypes, "id", "label", route.typeId); return View(route); } // GET: Routes/Delete/5 public async Task<ActionResult> Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Route route = await db.Routes.FindAsync(id); if (route == null) { return HttpNotFound(); } return View(route); } // POST: Routes/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<ActionResult> DeleteConfirmed(int id) { Route route = await db.Routes.FindAsync(id); db.Routes.Remove(route); await db.SaveChangesAsync(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
cdchild/TransitApp
Transit/Controllers/RoutesController.cs
C#
mit
4,630
32.781022
145
0.553587
false
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <luck@lucko.me> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lucko.luckperms.nukkit.inject.server; import me.lucko.luckperms.nukkit.LPNukkitPlugin; import cn.nukkit.Server; import cn.nukkit.permission.Permissible; import cn.nukkit.plugin.PluginManager; import java.lang.reflect.Field; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Injects a {@link LuckPermsSubscriptionMap} into the {@link PluginManager}. */ public class InjectorSubscriptionMap implements Runnable { private static final Field PERM_SUBS_FIELD; static { Field permSubsField = null; try { permSubsField = PluginManager.class.getDeclaredField("permSubs"); permSubsField.setAccessible(true); } catch (Exception e) { // ignore } PERM_SUBS_FIELD = permSubsField; } private final LPNukkitPlugin plugin; public InjectorSubscriptionMap(LPNukkitPlugin plugin) { this.plugin = plugin; } @Override public void run() { try { LuckPermsSubscriptionMap subscriptionMap = inject(); if (subscriptionMap != null) { this.plugin.setSubscriptionMap(subscriptionMap); } } catch (Exception e) { this.plugin.getLogger().severe("Exception occurred whilst injecting LuckPerms Permission Subscription map.", e); } } private LuckPermsSubscriptionMap inject() throws Exception { Objects.requireNonNull(PERM_SUBS_FIELD, "PERM_SUBS_FIELD"); PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager(); Object map = PERM_SUBS_FIELD.get(pluginManager); if (map instanceof LuckPermsSubscriptionMap) { if (((LuckPermsSubscriptionMap) map).plugin == this.plugin) { return null; } map = ((LuckPermsSubscriptionMap) map).detach(); } //noinspection unchecked Map<String, Set<Permissible>> castedMap = (Map<String, Set<Permissible>>) map; // make a new subscription map & inject it LuckPermsSubscriptionMap newMap = new LuckPermsSubscriptionMap(this.plugin, castedMap); PERM_SUBS_FIELD.set(pluginManager, newMap); return newMap; } public static void uninject() { try { Objects.requireNonNull(PERM_SUBS_FIELD, "PERM_SUBS_FIELD"); PluginManager pluginManager = Server.getInstance().getPluginManager(); Object map = PERM_SUBS_FIELD.get(pluginManager); if (map instanceof LuckPermsSubscriptionMap) { LuckPermsSubscriptionMap lpMap = (LuckPermsSubscriptionMap) map; PERM_SUBS_FIELD.set(pluginManager, lpMap.detach()); } } catch (Exception e) { e.printStackTrace(); } } }
lucko/LuckPerms
nukkit/src/main/java/me/lucko/luckperms/nukkit/inject/server/InjectorSubscriptionMap.java
Java
mit
4,057
35.54955
124
0.675129
false
jQuery(document).ready(function(){ jQuery('.carousel').carousel() var FPS = 30; var player = $('#player') var pWidth = player.width(); $window = $(window) var wWidth = $window.width(); setInterval(function() { update(); }, 1000/FPS); function update() { if(keydown.space) { player.shoot(); } if(keydown.left) { console.log('go left') player.css('left', '-=10'); } if(keydown.right) { console.log('go right') var x = player.position().left; if(x + pWidth > wWidth) { player.css('left', '0') } else if(x < 0 ) { var p = wWidth + x - pWidth; var t = p + 'px' player.css('left', t) } else { player.css('left', '+=10'); } } } $('') })
ni5ni6/chiptuna.com
js/main.js
JavaScript
mit
739
11.964912
34
0.522327
false
/// <reference path="tsUnit.ts" /> /// <reference path="MockExpression.ts" /> /// <reference path="../src/EventBinding.ts" /> module jsBind { private fireEvent(elem: any): void { if (document.createEventObject) { // IE 9 & 10 var event: any = document.createEventObject(); event.eventType = "onclick"; elem.fireEvent("onclick", event); } else if (dispatchEvent) { // For DOM var evt = document.createEvent("HTMLEvents"); evt.initEvent("click", false, true); elem.dispatchEvent(evt); } else { // IE 8- elem.fireEvent("onclick"); } } export class EventBindingTests { public testEvaluate(c: tsUnit.TestContext): void { var elem: any = document.getElementById("Results"); var expr = new MockExpression(42); var binding = new EventBinding(elem, "click", expr, null, null); binding.evaluate(); fireEvent(elem); c.isTrue(expr.wasEvaluated); } public testDispose(c: tsUnit.TestContext): void { var elem: any = document.getElementById("Results"); var expr = new MockExpression(42); var binding = new EventBinding(elem, "click", expr, null, null); binding.evaluate(); // Check the dispose occurs binding.dispose(); c.isTrue(expr.isDisposed); fireEvent(elem); c.isFalse(expr.wasEvaluated); } } }
voss-tech/jsBind
Code/tests/EventBindingTests.ts
TypeScript
mit
1,578
27.196429
76
0.541191
false
// Copyright (c) 2015 The original author or authors // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #if UNITY_EDITOR using SpriterDotNet; using System; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; namespace SpriterDotNetUnity { public class SpriterImporter : AssetPostprocessor { private static readonly string[] ScmlExtensions = new string[] { ".scml" }; private static readonly float DeltaZ = -0.001f; private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath) { foreach (string asset in importedAssets) { if (!IsScml(asset)) continue; CreateSpriter(asset); } foreach (string asset in deletedAssets) { if (!IsScml(asset)) continue; } for (int i = 0; i < movedAssets.Length; i++) { string asset = movedAssets[i]; if (!IsScml(asset)) continue; } } private static bool IsScml(string path) { return ScmlExtensions.Any(path.EndsWith); } private static void CreateSpriter(string path) { string data = File.ReadAllText(path); Spriter spriter = SpriterParser.Parse(data); string rootFolder = Path.GetDirectoryName(path); foreach (SpriterEntity entity in spriter.Entities) { GameObject go = new GameObject(); go.name = entity.Name; SpriterDotNetBehaviour sdnBehaviour = go.AddComponent<SpriterDotNetBehaviour>(); sdnBehaviour.Entity = entity; sdnBehaviour.enabled = true; LoadSprites(sdnBehaviour, spriter, rootFolder); CreateChildren(entity, sdnBehaviour, spriter, go); string prefabPath = rootFolder + "/" + entity.Name + ".prefab"; PrefabUtility.CreatePrefab(prefabPath, go, ReplacePrefabOptions.ConnectToPrefab); GameObject.DestroyImmediate(go); } } private static void CreateChildren(SpriterEntity entity, SpriterDotNetBehaviour sdnBehaviour, Spriter spriter, GameObject parent) { int maxObjects = 0; foreach (SpriterAnimation animation in entity.Animations) { foreach (SpriterMainLineKey mainKey in animation.MainlineKeys) { maxObjects = Math.Max(maxObjects, mainKey.ObjectRefs.Length); } } sdnBehaviour.Children = new GameObject[maxObjects]; sdnBehaviour.Pivots = new GameObject[maxObjects]; for (int i = 0; i < maxObjects; ++i) { GameObject pivot = new GameObject(); GameObject child = new GameObject(); sdnBehaviour.Pivots[i] = pivot; sdnBehaviour.Children[i] = child; pivot.transform.SetParent(parent.transform); child.transform.SetParent(pivot.transform); child.transform.localPosition = new Vector3(0, 0, DeltaZ * i); pivot.name = "pivot " + i; child.name = "child " + i; child.AddComponent<SpriteRenderer>(); } } private static void LoadSprites(SpriterDotNetBehaviour sdnBehaviour, Spriter spriter, string rootFolder) { sdnBehaviour.Folders = new SdnFolder[spriter.Folders.Length]; for (int i = 0; i < spriter.Folders.Length; ++i) { SpriterFolder folder = spriter.Folders[i]; SdnFolder sdnFolder = new SdnFolder(); sdnFolder.Files = new Sprite[folder.Files.Length]; sdnBehaviour.Folders[i] = sdnFolder; for (int j = 0; j < folder.Files.Length; ++j) { SpriterFile file = folder.Files[j]; string spritePath = rootFolder; spritePath += "/"; spritePath += file.Name; Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(spritePath); if (sprite == null) { Debug.LogWarning("Unable to load sprite: " + spritePath); continue; } sdnFolder.Files[j] = sprite; } } } } } #endif
adamholdenyall/SpriterDotNet
SpriterDotNet.Unity/Assets/SpriterDotNet/SpriterImporter.cs
C#
mit
4,693
33.492647
145
0.550203
false
#!/usr/bin/env python # -*- coding: utf-8 -*- import base64 import json from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from behave import * @step('I share first element in the history list') def step_impl(context): context.execute_steps(u''' given I open History dialog ''') history = context.browser.find_element_by_id("HistoryPopup") entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]') assert len(entries) > 0, "There are no entries in the history" item = entries[0] item.find_elements_by_xpath('.//*[@data-share-item]')[0].click() @then('the json to share is shown with url "{url}" and contains the following headers') def step_impl(context, url): # Wait for modal to appear WebDriverWait(context.browser, 10).until( expected_conditions.visibility_of_element_located( (By.ID, 'ShareRequestForm'))) output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();") snippet = json.loads(output) assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output) for row in context.table: assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key']) assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name]) @step('I click on import request') def step_impl(context): context.execute_steps(u''' given I open History dialog ''') # Click on import context.browser.find_element_by_id('ImportHistory').click() WebDriverWait(context.browser, 10).until( expected_conditions.visibility_of_element_located( (By.ID, 'ImportRequestForm'))) @step('I write a shared request for "{url}"') def step_impl(context, url): req = json.dumps({ "method": "POST", "url": url, "headers": { "Content-Type": "application/json", "X-Test-Header": "shared_request" }, "body": { "type": "form", "content": { "SomeKey": "SomeValue11233", "SomeOtherKey": "SomeOtherValue019", } } }) context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req))) @step('I click on load import request') def step_impl(context): # Import request context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
jsargiot/restman
tests/steps/share.py
Python
mit
2,709
37.15493
158
0.640458
false
--- layout: link type: link link: https://www.bloomberg.com/news/articles/2019-11-05/why-indonesia-failed-to-cash-in-on-the-china-u-s-trade-war title: "Bloomberg: Why Indonesia Failed to Cash in on the China-U.S. Trade War" category: links tags: - life - "daily found" - development - indonesia categories: dailyfound published: true comments: true --- Dengan adanya perang dagang antara Amerika dan Tiongkok, banyak berimbas terhadap industri-industri yang ada didua negara itu, dan beberapa negara di asia tenggara bisa mengambil untung dari kondisi itu. Sebut Vietnam, Thailand, banyak investor yang mengalihkan investasinya ke negara tersebut, alasan kenapa Indonesia tidak begitu besar terkena imbasnya. <!--more--> > The reasons for the poor performance are well documented: inadequate infrastructure, particularly in transport; rigid labor rules; limits on how much foreigners can invest in several industries; bureaucratic red tape and a habit of backtracking on regulations that makes it tricky to do business in the country. Memang sangat berbelit investasi di sini, belum lagi kondisi pekerjanya yang terhitung mahal, belum juga preman-preman, ditambah isu investor asing yang berkonotasi negatif, pemerintah dianggap menjual negara ini ke asing, padahal membuka investasi. Membangun infrastuktur yang bisa dijadikan pendukung pemerataan usaha, juga mempermudah transportasi sehingga atraktif untuk investor, tapi tetap itu dianggap sebagai suatu pemborosan. Ada juga kalimat andalan "Negara ini kaya, masa *gak* bisa mengambil untung dari itu? tidak butuh asing untuk mengelola", dan ucapan-ucapan sejenis, yang mana tentu itu keluar dari ketidak tahuan akan kondisi, seperti penonton bola, biasanya penonton bola lebih pintar dari pemainnya, yang latihan 10 jam sehari, kalau gagal gol akan dibilang bodoh oleh penonton budiman. Sama seperti warga yang mengomentari pemerintah, merasa lebih pintar.
dedenf/dedenf.github.io
_posts/2019-11-06-indonesia-failed-to-take-profit.md
Markdown
mit
1,938
59.59375
371
0.803922
false
import { entryPoint } from '@rpgjs/standalone' import globalConfigClient from './config/client' import globalConfigServer from './config/server' import modules from './modules' document.addEventListener('DOMContentLoaded', function() { entryPoint(modules, { globalConfigClient, globalConfigServer }).start() })
RSamaium/RPG-JS
packages/sample3/src/standalone.ts
TypeScript
mit
338
29.818182
59
0.724852
false
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Elements part // // Contributor: Lionel Duchateau, kurtnoise@free.fr // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" #include <ZenLib/Ztring.h> #include <string> using namespace std; using namespace ZenLib; //--------------------------------------------------------------------------- //*************************************************************************** // Infos //*************************************************************************** //--------------------------------------------------------------------------- #if defined(MEDIAINFO_RIFF_YES) || defined(MEDIAINFO_MK_YES) //--------------------------------------------------------------------------- namespace MediaInfoLib { //--------------------------------------------------------------------------- std::string ExtensibleWave_ChannelMask (int32u ChannelMask) { std::string Text; if ((ChannelMask&0x0007)!=0x0000) Text+="Front:"; if (ChannelMask&0x0001) Text+=" L"; if (ChannelMask&0x0004) Text+=" C"; if (ChannelMask&0x0002) Text+=" R"; if ((ChannelMask&0x0600)!=0x0000) Text+=", Side:"; if (ChannelMask&0x0200) Text+=" L"; if (ChannelMask&0x0400) Text+=" R"; if ((ChannelMask&0x0130)!=0x0000) Text+=", Back:"; if (ChannelMask&0x0010) Text+=" L"; if (ChannelMask&0x0100) Text+=" C"; if (ChannelMask&0x0020) Text+=" R"; if ((ChannelMask&0x0008)!=0x0000) Text+=", LFE"; return Text; } //--------------------------------------------------------------------------- std::string ExtensibleWave_ChannelMask2 (int32u ChannelMask) { std::string Text; int8u Count=0; if (ChannelMask&0x0001) Count++; if (ChannelMask&0x0004) Count++; if (ChannelMask&0x0002) Count++; Text+=Ztring::ToZtring(Count).To_UTF8(); Count=0; if (ChannelMask&0x0200) Count++; if (ChannelMask&0x0400) Count++; Text+="/"+Ztring::ToZtring(Count).To_UTF8(); Count=0; if (ChannelMask&0x0010) Count++; if (ChannelMask&0x0100) Count++; if (ChannelMask&0x0020) Count++; Text+="/"+Ztring::ToZtring(Count).To_UTF8(); Count=0; if (ChannelMask&0x0008) Text+=".1"; return Text; } } //--------------------------------------------------------------------------- #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #ifdef MEDIAINFO_RIFF_YES //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Multiple/File_Riff.h" #if defined(MEDIAINFO_DVDIF_YES) #include "MediaInfo/Multiple/File_DvDif.h" #endif #if defined(MEDIAINFO_OGG_YES) #include "MediaInfo/Multiple/File_Ogg.h" #include "MediaInfo/Multiple/File_Ogg_SubElement.h" #endif #if defined(MEDIAINFO_FFV1_YES) #include "MediaInfo/Video/File_Ffv1.h" #endif #if defined(MEDIAINFO_HUFFYUV_YES) #include "MediaInfo/Video/File_HuffYuv.h" #endif #if defined(MEDIAINFO_MPEG4V_YES) #include "MediaInfo/Video/File_Mpeg4v.h" #endif #if defined(MEDIAINFO_MPEGV_YES) #include "MediaInfo/Video/File_Mpegv.h" #endif #if defined(MEDIAINFO_PRORES_YES) #include "MediaInfo/Video/File_ProRes.h" #endif #if defined(MEDIAINFO_AVC_YES) #include "MediaInfo/Video/File_Avc.h" #endif #if defined(MEDIAINFO_CANOPUS_YES) #include "MediaInfo/Video/File_Canopus.h" #endif #if defined(MEDIAINFO_FRAPS_YES) #include "MediaInfo/Video/File_Fraps.h" #endif #if defined(MEDIAINFO_LAGARITH_YES) #include "MediaInfo/Video/File_Lagarith.h" #endif #if defined(MEDIAINFO_MPEGA_YES) #include "MediaInfo/Audio/File_Mpega.h" #endif #if defined(MEDIAINFO_AAC_YES) #include "MediaInfo/Audio/File_Aac.h" #endif #if defined(MEDIAINFO_AC3_YES) #include "MediaInfo/Audio/File_Ac3.h" #endif #if defined(MEDIAINFO_DTS_YES) #include "MediaInfo/Audio/File_Dts.h" #endif #if defined(MEDIAINFO_JPEG_YES) #include "MediaInfo/Image/File_Jpeg.h" #endif #if defined(MEDIAINFO_SUBRIP_YES) #include "MediaInfo/Text/File_SubRip.h" #endif #if defined(MEDIAINFO_OTHERTEXT_YES) #include "MediaInfo/Text/File_OtherText.h" #endif #if defined(MEDIAINFO_ADPCM_YES) #include "MediaInfo/Audio/File_Adpcm.h" #endif #if defined(MEDIAINFO_PCM_YES) #include "MediaInfo/Audio/File_Pcm.h" #endif #if defined(MEDIAINFO_SMPTEST0337_YES) #include "MediaInfo/Audio/File_SmpteSt0337.h" #endif #if defined(MEDIAINFO_ID3_YES) #include "MediaInfo/Tag/File_Id3.h" #endif #if defined(MEDIAINFO_ID3V2_YES) #include "MediaInfo/Tag/File_Id3v2.h" #endif #if defined(MEDIAINFO_GXF_YES) #if defined(MEDIAINFO_CDP_YES) #include "MediaInfo/Text/File_Cdp.h" #include <cstring> #endif #endif //MEDIAINFO_GXF_YES #include <vector> #include "MediaInfo/MediaInfo_Config_MediaInfo.h" using namespace std; //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Const //*************************************************************************** namespace Elements { const int32u FORM=0x464F524D; const int32u LIST=0x4C495354; const int32u ON2_=0x4F4E3220; const int32u RIFF=0x52494646; const int32u RF64=0x52463634; const int32u AIFC=0x41494643; const int32u AIFC_COMM=0x434F4D4D; const int32u AIFC_COMT=0x434F4D54; const int32u AIFC_FVER=0x46564552; const int32u AIFC_SSND=0x53534E44; const int32u AIFF=0x41494646; const int32u AIFF_COMM=0x434F4D4D; const int32u AIFF_COMT=0x434F4D54; const int32u AIFF_SSND=0x53534E44; const int32u AIFF__c__=0x28632920; const int32u AIFF_ANNO=0x414E4E4F; const int32u AIFF_AUTH=0x41555448; const int32u AIFF_NAME=0x4E414D45; const int32u AIFF_ID3_=0x49443320; const int32u AVI_=0x41564920; const int32u AVI__cset=0x63736574; const int32u AVI__Cr8r=0x43723872; const int32u AVI__exif=0x65786966; const int32u AVI__exif_ecor=0x65636F72; const int32u AVI__exif_emdl=0x656D646C; const int32u AVI__exif_emnt=0x656D6E74; const int32u AVI__exif_erel=0x6572656C; const int32u AVI__exif_etim=0x6574696D; const int32u AVI__exif_eucm=0x6575636D; const int32u AVI__exif_ever=0x65766572; const int32u AVI__goog=0x676F6F67; const int32u AVI__goog_GDAT=0x47444154; const int32u AVI__GMET=0x474D4554; const int32u AVI__hdlr=0x6864726C; const int32u AVI__hdlr_avih=0x61766968; const int32u AVI__hdlr_JUNK=0x4A554E4B; const int32u AVI__hdlr_strl=0x7374726C; const int32u AVI__hdlr_strl_indx=0x696E6478; const int32u AVI__hdlr_strl_JUNK=0x4A554E4B; const int32u AVI__hdlr_strl_strd=0x73747264; const int32u AVI__hdlr_strl_strf=0x73747266; const int32u AVI__hdlr_strl_strh=0x73747268; const int32u AVI__hdlr_strl_strh_auds=0x61756473; const int32u AVI__hdlr_strl_strh_iavs=0x69617673; const int32u AVI__hdlr_strl_strh_mids=0x6D696473; const int32u AVI__hdlr_strl_strh_vids=0x76696473; const int32u AVI__hdlr_strl_strh_txts=0x74787473; const int32u AVI__hdlr_strl_strn=0x7374726E; const int32u AVI__hdlr_strl_vprp=0x76707270; const int32u AVI__hdlr_odml=0x6F646D6C; const int32u AVI__hdlr_odml_dmlh=0x646D6C68; const int32u AVI__hdlr_ON2h=0x4F4E3268; const int32u AVI__idx1=0x69647831; const int32u AVI__INFO=0x494E464F; const int32u AVI__INFO_IARL=0x4941524C; const int32u AVI__INFO_IART=0x49415254; const int32u AVI__INFO_IAS1=0x49415331; const int32u AVI__INFO_IAS2=0x49415332; const int32u AVI__INFO_IAS3=0x49415333; const int32u AVI__INFO_IAS4=0x49415334; const int32u AVI__INFO_IAS5=0x49415335; const int32u AVI__INFO_IAS6=0x49415336; const int32u AVI__INFO_IAS7=0x49415337; const int32u AVI__INFO_IAS8=0x49415338; const int32u AVI__INFO_IAS9=0x49415339; const int32u AVI__INFO_ICDS=0x49434453; const int32u AVI__INFO_ICMS=0x49434D53; const int32u AVI__INFO_ICMT=0x49434D54; const int32u AVI__INFO_ICNT=0x49434E54; const int32u AVI__INFO_ICOP=0x49434F50; const int32u AVI__INFO_ICNM=0x49434E4D; const int32u AVI__INFO_ICRD=0x49435244; const int32u AVI__INFO_ICRP=0x49435250; const int32u AVI__INFO_IDIM=0x4944494D; const int32u AVI__INFO_IDIT=0x49444954; const int32u AVI__INFO_IDPI=0x49445049; const int32u AVI__INFO_IDST=0x49445354; const int32u AVI__INFO_IEDT=0x49454454; const int32u AVI__INFO_IENG=0x49454E47; const int32u AVI__INFO_IFRM=0x4946524D; const int32u AVI__INFO_IGNR=0x49474E52; const int32u AVI__INFO_IID3=0x49494433; const int32u AVI__INFO_IKEY=0x494B4559; const int32u AVI__INFO_ILGT=0x494C4754; const int32u AVI__INFO_ILNG=0x494C4E47; const int32u AVI__INFO_ILYC=0x494C5943; const int32u AVI__INFO_IMED=0x494D4544; const int32u AVI__INFO_IMP3=0x494D5033; const int32u AVI__INFO_IMUS=0x494D5553; const int32u AVI__INFO_INAM=0x494E414D; const int32u AVI__INFO_IPLT=0x49504C54; const int32u AVI__INFO_IPDS=0x49504453; const int32u AVI__INFO_IPRD=0x49505244; const int32u AVI__INFO_IPRT=0x49505254; const int32u AVI__INFO_IPRO=0x4950524F; const int32u AVI__INFO_IRTD=0x49525444; const int32u AVI__INFO_ISBJ=0x4953424A; const int32u AVI__INFO_ISGN=0x4953474E; const int32u AVI__INFO_ISTD=0x49535444; const int32u AVI__INFO_ISTR=0x49535452; const int32u AVI__INFO_ISFT=0x49534654; const int32u AVI__INFO_ISHP=0x49534850; const int32u AVI__INFO_ISMP=0x49534D50; const int32u AVI__INFO_ISRC=0x49535243; const int32u AVI__INFO_ISRF=0x49535246; const int32u AVI__INFO_ITCH=0x49544348; const int32u AVI__INFO_IWEB=0x49574542; const int32u AVI__INFO_IWRI=0x49575249; const int32u AVI__INFO_JUNK=0x4A554E4B; const int32u AVI__JUNK=0x4A554E4B; const int32u AVI__MD5_=0x4D443520; const int32u AVI__movi=0x6D6F7669; const int32u AVI__movi_rec_=0x72656320; const int32u AVI__movi_xxxx_____=0x00005F5F; const int32u AVI__movi_xxxx___db=0x00006462; const int32u AVI__movi_xxxx___dc=0x00006463; const int32u AVI__movi_xxxx___sb=0x00007362; const int32u AVI__movi_xxxx___tx=0x00007478; const int32u AVI__movi_xxxx___wb=0x00007762; const int32u AVI__PrmA=0x50726D41; const int32u AVI__Tdat=0x54646174; const int32u AVI__Tdat_rn_A=0x726E5F41; const int32u AVI__Tdat_rn_O=0x726E5F4F; const int32u AVI__Tdat_tc_A=0x74635F41; const int32u AVI__Tdat_tc_O=0x74635F4F; const int32u AVIX=0x41564958; const int32u AVIX_idx1=0x69647831; const int32u AVIX_movi=0x6D6F7669; const int32u AVIX_movi_rec_=0x72656320; const int32u CADP=0x43414450; const int32u CDDA=0x43444441; const int32u CDDA_fmt_=0x666D7420; const int32u CMJP=0x434D4A50; const int32u CMP4=0x434D5034; const int32u IDVX=0x49445658; const int32u INDX=0x494E4458; const int32u JUNK=0x4A554E4B; const int32u menu=0x6D656E75; const int32u MThd=0x4D546864; const int32u MTrk=0x4D54726B; const int32u PAL_=0x50414C20; const int32u QLCM=0x514C434D; const int32u QLCM_fmt_=0x666D7420; const int32u rcrd=0x72637264; const int32u rcrd_desc=0x64657363; const int32u rcrd_fld_=0x666C6420; const int32u rcrd_fld__anc_=0x616E6320; const int32u rcrd_fld__anc__pos_=0x706F7320; const int32u rcrd_fld__anc__pyld=0x70796C64; const int32u rcrd_fld__finf=0x66696E66; const int32u RDIB=0x52444942; const int32u RMID=0x524D4944; const int32u RMMP=0x524D4D50; const int32u RMP3=0x524D5033; const int32u RMP3_data=0x64617461; const int32u RMP3_INFO=0x494E464F; const int32u RMP3_INFO_IID3=0x49494433; const int32u RMP3_INFO_ILYC=0x494C5943; const int32u RMP3_INFO_IMP3=0x494D5033; const int32u RMP3_INFO_JUNK=0x4A554E4B; const int32u SMV0=0x534D5630; const int32u SMV0_xxxx=0x534D563A; const int32u WAVE=0x57415645; const int32u WAVE__pmx=0x20786D70; const int32u WAVE_aXML=0x61584D4C; const int32u WAVE_bext=0x62657874; const int32u WAVE_cue_=0x63756520; const int32u WAVE_data=0x64617461; const int32u WAVE_ds64=0x64733634; const int32u WAVE_fact=0x66616374; const int32u WAVE_fmt_=0x666D7420; const int32u WAVE_ID3_=0x49443320; const int32u WAVE_id3_=0x69643320; const int32u WAVE_INFO=0x494E464F; const int32u WAVE_iXML=0x69584D4C; const int32u wave=0x77617665; const int32u wave_data=0x64617461; const int32u wave_fmt_=0x666D7420; const int32u W3DI=0x57334449; #define UUID(NAME, PART1, PART2, PART3, PART4, PART5) \ const int64u NAME =0x##PART3##PART2##PART1##ULL; \ const int64u NAME##2=0x##PART4##PART5##ULL; \ UUID(QLCM_QCELP1, 5E7F6D41, B115, 11D0, BA91, 00805FB4B97E) UUID(QLCM_QCELP2, 5E7F6D42, B115, 11D0, BA91, 00805FB4B97E) UUID(QLCM_EVRC, E689D48D, 9076, 46B5, 91EF, 736A5100CEB4) UUID(QLCM_SMV, 8D7C2B75, A797, ED49, 985E, D53C8CC75F84) } //*************************************************************************** // Format //*************************************************************************** //--------------------------------------------------------------------------- void File_Riff::Data_Parse() { //Alignement specific Element_Size-=Alignement_ExtraByte; DATA_BEGIN LIST(AIFC) ATOM_BEGIN ATOM(AIFC_COMM) ATOM(AIFC_COMT) ATOM(AIFC_FVER) ATOM(AIFC_SSND) ATOM_DEFAULT(AIFC_xxxx) ATOM_END_DEFAULT LIST(AIFF) ATOM_BEGIN ATOM(AIFF_COMM) ATOM(AIFF_COMT) ATOM(AIFF_ID3_) LIST_SKIP(AIFF_SSND) ATOM_DEFAULT(AIFF_xxxx) ATOM_END_DEFAULT LIST(AVI_) ATOM_BEGIN ATOM(AVI__Cr8r); ATOM(AVI__cset) LIST(AVI__exif) ATOM_DEFAULT_ALONE(AVI__exif_xxxx) LIST(AVI__goog) ATOM_BEGIN ATOM(AVI__goog_GDAT) ATOM_END ATOM(AVI__GMET) LIST(AVI__hdlr) ATOM_BEGIN ATOM(AVI__hdlr_avih) ATOM(AVI__hdlr_JUNK) LIST(AVI__hdlr_strl) ATOM_BEGIN ATOM(AVI__hdlr_strl_indx) ATOM(AVI__hdlr_strl_JUNK) ATOM(AVI__hdlr_strl_strd) ATOM(AVI__hdlr_strl_strf) ATOM(AVI__hdlr_strl_strh) ATOM(AVI__hdlr_strl_strn) ATOM(AVI__hdlr_strl_vprp) ATOM_END LIST(AVI__hdlr_odml) ATOM_BEGIN ATOM(AVI__hdlr_odml_dmlh) ATOM_END ATOM(AVI__hdlr_ON2h) LIST(AVI__INFO) ATOM_BEGIN ATOM(AVI__INFO_IID3) ATOM(AVI__INFO_ILYC) ATOM(AVI__INFO_IMP3) ATOM(AVI__INFO_JUNK) ATOM_DEFAULT(AVI__INFO_xxxx) ATOM_END_DEFAULT ATOM_DEFAULT(AVI__hdlr_xxxx) ATOM_END_DEFAULT ATOM(AVI__idx1) LIST(AVI__INFO) ATOM_BEGIN ATOM(AVI__INFO_IID3) ATOM(AVI__INFO_ILYC) ATOM(AVI__INFO_IMP3) ATOM(AVI__INFO_JUNK) ATOM_DEFAULT(AVI__INFO_xxxx) ATOM_END_DEFAULT ATOM(AVI__JUNK) ATOM(AVI__MD5_) LIST(AVI__movi) ATOM_BEGIN LIST(AVI__movi_rec_) ATOM_DEFAULT_ALONE(AVI__movi_xxxx) ATOM_DEFAULT(AVI__movi_xxxx) ATOM_END_DEFAULT ATOM(AVI__PrmA); LIST(AVI__Tdat) ATOM_BEGIN ATOM(AVI__Tdat_rn_A) ATOM(AVI__Tdat_rn_O) ATOM(AVI__Tdat_tc_A) ATOM(AVI__Tdat_tc_O) ATOM_END ATOM_DEFAULT(AVI__xxxx) ATOM_END_DEFAULT LIST(AVIX) //OpenDML ATOM_BEGIN ATOM(AVIX_idx1) LIST(AVIX_movi) ATOM_BEGIN LIST(AVIX_movi_rec_) ATOM_DEFAULT_ALONE(AVIX_movi_xxxx) ATOM_DEFAULT(AVIX_movi_xxxx) ATOM_END_DEFAULT ATOM_END ATOM_PARTIAL(CADP) LIST(CDDA) ATOM_BEGIN ATOM(CDDA_fmt_) ATOM_END ATOM_PARTIAL(CMJP) ATOM(CMP4) ATOM(IDVX) LIST(INDX) ATOM_DEFAULT_ALONE(INDX_xxxx) LIST_SKIP(JUNK) LIST_SKIP(menu) ATOM(MThd) LIST_SKIP(MTrk) LIST_SKIP(PAL_) LIST(QLCM) ATOM_BEGIN ATOM(QLCM_fmt_) ATOM_END #if defined(MEDIAINFO_GXF_YES) LIST(rcrd) ATOM_BEGIN ATOM(rcrd_desc) LIST(rcrd_fld_) ATOM_BEGIN LIST(rcrd_fld__anc_) ATOM_BEGIN ATOM(rcrd_fld__anc__pos_) ATOM(rcrd_fld__anc__pyld) ATOM_END ATOM(rcrd_fld__finf) ATOM_END ATOM_END #endif //defined(MEDIAINFO_GXF_YES) LIST_SKIP(RDIB) LIST_SKIP(RMID) LIST_SKIP(RMMP) LIST(RMP3) ATOM_BEGIN LIST(RMP3_data) break; LIST(RMP3_INFO) ATOM_BEGIN ATOM(RMP3_INFO_IID3) ATOM(RMP3_INFO_ILYC) ATOM(RMP3_INFO_IMP3) ATOM(RMP3_INFO_JUNK) ATOM_DEFAULT(RMP3_INFO_xxxx) ATOM_END_DEFAULT ATOM_END ATOM(SMV0) ATOM(SMV0_xxxx) ATOM(W3DI) LIST(WAVE) ATOM_BEGIN ATOM(WAVE__pmx) ATOM(WAVE_aXML) ATOM(WAVE_bext) LIST(WAVE_data) break; ATOM(WAVE_cue_) ATOM(WAVE_ds64) ATOM(WAVE_fact) ATOM(WAVE_fmt_) ATOM(WAVE_ID3_) ATOM(WAVE_id3_) LIST(WAVE_INFO) ATOM_DEFAULT_ALONE(WAVE_INFO_xxxx) ATOM(WAVE_iXML) ATOM_END LIST(wave) ATOM_BEGIN LIST(wave_data) break; ATOM(wave_fmt_) ATOM_END DATA_END if (Alignement_ExtraByte) { Element_Size+=Alignement_ExtraByte; if (Element_Offset+Alignement_ExtraByte==Element_Size) Skip_XX(Alignement_ExtraByte, "Alignement"); } } //*************************************************************************** // Elements //*************************************************************************** //--------------------------------------------------------------------------- void File_Riff::AIFC() { Data_Accept("AIFF Compressed"); Element_Name("AIFF Compressed"); //Filling Fill(Stream_General, 0, General_Format, "AIFF"); Stream_Prepare(Stream_Audio); Kind=Kind_Aiff; #if MEDIAINFO_EVENTS StreamIDs_Width[0]=0; #endif //MEDIAINFO_EVENTS } //--------------------------------------------------------------------------- void File_Riff::AIFC_COMM() { AIFF_COMM(); } //--------------------------------------------------------------------------- void File_Riff::AIFC_COMT() { AIFF_COMT(); } //--------------------------------------------------------------------------- void File_Riff::AIFC_FVER() { Element_Name("Format Version"); //Parsing Skip_B4( "Version"); } //--------------------------------------------------------------------------- void File_Riff::AIFC_SSND() { AIFF_SSND(); } //--------------------------------------------------------------------------- void File_Riff::AIFC_xxxx() { AIFF_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::AIFF() { Data_Accept("AIFF"); Element_Name("AIFF"); //Filling Fill(Stream_General, 0, General_Format, "AIFF"); Stream_Prepare(Stream_Audio); Kind=Kind_Aiff; #if MEDIAINFO_EVENTS StreamIDs_Width[0]=0; #endif //MEDIAINFO_EVENTS } //--------------------------------------------------------------------------- void File_Riff::AIFF_COMM() { Element_Name("Common"); int32u numSampleFrames; int16u numChannels, sampleSize; float80 sampleRate; //Parsing Get_B2 (numChannels, "numChannels"); Get_B4 (numSampleFrames, "numSampleFrames"); Get_B2 (sampleSize, "sampleSize"); Get_BF10(sampleRate, "sampleRate"); if (Data_Remain()) //AIFC { int32u compressionType; Get_C4 (compressionType, "compressionType"); Skip_PA( "compressionName"); //Filling CodecID_Fill(Ztring().From_CC4(compressionType), Stream_Audio, StreamPos_Last, InfoCodecID_Format_Mpeg4); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, Ztring().From_CC4(compressionType)); } else { //Filling Fill(Stream_Audio, StreamPos_Last, Audio_Format, "PCM"); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, "PCM"); } //Filling Fill(Stream_Audio, StreamPos_Last, Audio_Channel_s_, numChannels); Fill(Stream_Audio, StreamPos_Last, Audio_BitDepth, sampleSize); if (sampleRate) Fill(Stream_Audio, StreamPos_Last, Audio_Duration, numSampleFrames/sampleRate*1000); Fill(Stream_Audio, StreamPos_Last, Audio_SamplingRate, sampleRate, 0); //Compute the current codec ID Element_Code=(int64u)-1; Stream_ID=(int32u)-1; stream_Count=1; //Specific cases #if defined(MEDIAINFO_SMPTEST0337_YES) if (Retrieve(Stream_Audio, 0, Audio_CodecID).empty() && numChannels==2 && sampleSize<=32 && sampleRate==48000) //Some SMPTE ST 337 streams are hidden in PCM stream { File_SmpteSt0337* Parser=new File_SmpteSt0337; Parser->Endianness='B'; Parser->Container_Bits=(int8u)sampleSize; Parser->ShouldContinueParsing=true; #if MEDIAINFO_DEMUX if (Config->Demux_Unpacketize_Get()) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #endif //MEDIAINFO_DEMUX Stream[Stream_ID].Parsers.push_back(Parser); } #endif stream& StreamItem = Stream[Stream_ID]; #if defined(MEDIAINFO_PCM_YES) File_Pcm* Parser=new File_Pcm; Parser->Codec=Retrieve(Stream_Audio, StreamPos_Last, Audio_CodecID); if (Parser->Codec.empty() || Parser->Codec==__T("NONE")) Parser->Endianness='B'; Parser->BitDepth=(int8u)sampleSize; #if MEDIAINFO_DEMUX if (Demux_Rate) Parser->Frame_Count_Valid = float64_int64s(Demux_Rate); if (Config->Demux_Unpacketize_Get()) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #else //MEDIAINFO_DEMUX Parser->Frame_Count_Valid=(int64u)-1; //Disabling it, waiting for SMPTE ST 337 parser reject #endif //MEDIAINFO_DEMUX StreamItem.Parsers.push_back(Parser); StreamItem.IsPcm=true; StreamItem.StreamKind=Stream_Audio; #endif #if MEDIAINFO_DEMUX BlockAlign=numChannels*sampleSize/8; AvgBytesPerSec=(int32u)float64_int64s(BlockAlign*(float64)sampleRate); #endif //MEDIAINFO_DEMUX Element_Code=(int64u)-1; Open_Buffer_Init_All(); } //--------------------------------------------------------------------------- void File_Riff::AIFF_COMT() { //Parsing int16u numComments; Get_B2(numComments, "numComments"); for (int16u Pos=0; Pos<=numComments; Pos++) { Ztring text; int16u count; Element_Begin1("Comment"); Skip_B4( "timeStamp"); Skip_B4( "marker"); Get_B2 (count, "count"); count+=count%1; //always even Get_Local(count, text, "text"); Element_End0(); //Filling Fill(Stream_General, 0, General_Comment, text); } } //--------------------------------------------------------------------------- void File_Riff::AIFF_SSND() { WAVE_data(); } //--------------------------------------------------------------------------- void File_Riff::AIFF_SSND_Continue() { WAVE_data_Continue(); } //--------------------------------------------------------------------------- void File_Riff::AIFF_xxxx() { #define ELEMENT_CASE(_ELEMENT, _NAME) \ case Elements::_ELEMENT : Element_Name(_NAME); Name=_NAME; break; //Known? std::string Name; switch(Element_Code) { ELEMENT_CASE(AIFF__c__, "Copyright"); ELEMENT_CASE(AIFF_ANNO, "Comment"); ELEMENT_CASE(AIFF_AUTH, "Performer"); ELEMENT_CASE(AIFF_NAME, "Title"); default : Skip_XX(Element_Size, "Unknown"); return; } //Parsing Ztring text; Get_Local(Element_Size, text, "text"); //Filling Fill(Stream_General, 0, Name.c_str(), text); } //--------------------------------------------------------------------------- void File_Riff::AVI_() { Element_Name("AVI"); //Test if there is only one AVI chunk if (Status[IsAccepted]) { Element_Info1("Problem: 2 AVI chunks, this is not normal"); Skip_XX(Element_TotalSize_Get(), "Data"); return; } Data_Accept("AVI"); //Filling Fill(Stream_General, 0, General_Format, "AVI"); Kind=Kind_Avi; //Configuration Buffer_MaximumSize=64*1024*1024; //Some big frames are possible (e.g YUV 4:2:2 10 bits 1080p) } //--------------------------------------------------------------------------- void File_Riff::AVI__Cr8r() { Element_Name("Adobe Premiere Cr8r"); //Parsing Skip_C4( "FourCC"); Skip_B4( "Size"); Skip_XX(Element_Size-Element_Offset, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__cset() { Element_Name("Regional settings"); //Parsing Skip_L2( "CodePage"); //TODO: take a look about IBM/MS RIFF/MCI Specification 1.0 Skip_L2( "CountryCode"); Skip_L2( "LanguageCode"); Skip_L2( "Dialect"); } //--------------------------------------------------------------------------- void File_Riff::AVI__exif() { Element_Name("Exif (Exchangeable Image File Format)"); } //--------------------------------------------------------------------------- void File_Riff::AVI__exif_xxxx() { Element_Name("Value"); //Parsing Ztring Value; Get_Local(Element_Size, Value, "Value"); //Filling switch (Element_Code) { case Elements::AVI__exif_ecor : Fill(Stream_General, 0, "Make", Value); break; case Elements::AVI__exif_emdl : Fill(Stream_General, 0, "Model", Value); break; case Elements::AVI__exif_emnt : Fill(Stream_General, 0, "MakerNotes", Value); break; case Elements::AVI__exif_erel : Fill(Stream_General, 0, "RelatedImageFile", Value); break; case Elements::AVI__exif_etim : Fill(Stream_General, 0, "Written_Date", Value); break; case Elements::AVI__exif_eucm : Fill(Stream_General, 0, General_Comment, Value); break; case Elements::AVI__exif_ever : break; //Exif version default: Fill(Stream_General, 0, Ztring().From_CC4((int32u)Element_Code).To_Local().c_str(), Value); } } //--------------------------------------------------------------------------- void File_Riff::AVI__goog() { Element_Name("Google specific"); //Filling Fill(Stream_General, 0, General_Format, "Google Video", Unlimited, false, true); } //--------------------------------------------------------------------------- void File_Riff::AVI__goog_GDAT() { Element_Name("Google datas"); } //--------------------------------------------------------------------------- // Google Metadata // void File_Riff::AVI__GMET() { Element_Name("Google Metadatas"); //Parsing Ztring Value; Value.From_Local((const char*)(Buffer+Buffer_Offset+0), (size_t)Element_Size); ZtringListList List; List.Separator_Set(0, __T("\n")); List.Separator_Set(1, __T(":")); List.Max_Set(1, 2); List.Write(Value); //Details #if MEDIAINFO_TRACE if (Config_Trace_Level) { //for (size_t Pos=0; Pos<List.size(); Pos++) // Details_Add_Info(Pos, List(Pos, 0).To_Local().c_str(), List(Pos, 1)); } #endif //MEDIAINFO_TRACE //Filling for (size_t Pos=0; Pos<List.size(); Pos++) { if (List(Pos, 0)==__T("title")) Fill(Stream_General, 0, General_Title, List(Pos, 1)); if (List(Pos, 0)==__T("description")) Fill(Stream_General, 0, General_Title_More, List(Pos, 1)); if (List(Pos, 0)==__T("url")) Fill(Stream_General, 0, General_Title_Url, List(Pos, 1)); if (List(Pos, 0)==__T("docid")) Fill(Stream_General, 0, General_UniqueID, List(Pos, 1)); } } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr() { Element_Name("AVI Header"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_avih() { Element_Name("File header"); //Parsing int32u MicrosecPerFrame, Flags; Get_L4 (MicrosecPerFrame, "MicrosecPerFrame"); Skip_L4( "MaxBytesPerSec"); Skip_L4( "PaddingGranularity"); Get_L4 (Flags, "Flags"); Skip_Flags(Flags, 4, "HasIndex"); Skip_Flags(Flags, 5, "MustUseIndex"); Skip_Flags(Flags, 8, "IsInterleaved"); Skip_Flags(Flags, 9, "UseCKTypeToFindKeyFrames"); Skip_Flags(Flags, 11, "TrustCKType"); Skip_Flags(Flags, 16, "WasCaptureFile"); Skip_Flags(Flags, 17, "Copyrighted"); Get_L4 (avih_TotalFrame, "TotalFrames"); Skip_L4( "InitialFrames"); Skip_L4( "StreamsCount"); Skip_L4( "SuggestedBufferSize"); Skip_L4( "Width"); Skip_L4( "Height"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); if(Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); //Filling if (MicrosecPerFrame>0) avih_FrameRate=1000000.0/MicrosecPerFrame; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_JUNK() { Element_Name("Garbage"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_odml() { Element_Name("OpenDML"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_odml_dmlh() { Element_Name("OpenDML Header"); //Parsing Get_L4(dmlh_TotalFrame, "GrandFrames"); if (Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_ON2h() { Element_Name("On2 header"); //Parsing Skip_XX(Element_Size, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl() { Element_Name("Stream info"); Element_Info1(stream_Count); //Clean up StreamKind_Last=Stream_Max; StreamPos_Last=(size_t)-1; //Compute the current codec ID Stream_ID=(('0'+stream_Count/10)*0x01000000 +('0'+stream_Count )*0x00010000); stream_Count++; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_indx() { Element_Name("Index"); int32u Entry_Count, ChunkId; int16u LongsPerEntry; int8u IndexType, IndexSubType; Get_L2 (LongsPerEntry, "LongsPerEntry"); //Size of each entry in aIndex array Get_L1 (IndexSubType, "IndexSubType"); Get_L1 (IndexType, "IndexType"); Get_L4 (Entry_Count, "EntriesInUse"); //Index of first unused member in aIndex array Get_C4 (ChunkId, "ChunkId"); //FCC of what is indexed //Depends of size of structure... switch (IndexType) { case 0x01 : //AVI_INDEX_OF_CHUNKS switch (IndexSubType) { case 0x00 : AVI__hdlr_strl_indx_StandardIndex(Entry_Count, ChunkId); break; case 0x01 : AVI__hdlr_strl_indx_FieldIndex(Entry_Count, ChunkId); break; //AVI_INDEX_2FIELD default: Skip_XX(Element_Size-Element_Offset, "Unknown"); } break; case 0x0 : //AVI_INDEX_OF_INDEXES switch (IndexSubType) { case 0x00 : case 0x01 : AVI__hdlr_strl_indx_SuperIndex(Entry_Count, ChunkId); break; //AVI_INDEX_2FIELD default: Skip_XX(Element_Size-Element_Offset, "Unknown"); } break; default: Skip_XX(Element_Size-Element_Offset, "Unknown"); } } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_indx_StandardIndex(int32u Entry_Count, int32u ChunkId) { Element_Name("Standard Index"); //Parsing int64u BaseOffset, StreamSize=0; Get_L8 (BaseOffset, "BaseOffset"); Skip_L4( "Reserved3"); for (int32u Pos=0; Pos<Entry_Count; Pos++) { //Is too slow /* Element_Begin1("Index"); int32u Offset, Size; Get_L4 (Offset, "Offset"); //BaseOffset + this is absolute file offset Get_L4 (Size, "Size"); //Bit 31 is set if this is NOT a keyframe Element_Info1(Size&0x7FFFFFFF); if (Size) Element_Info1("KeyFrame"); Element_End0(); */ //Faster method if (Element_Offset+8>Element_Size) break; //Malformed index int32u Offset=LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset ); int32u Size =LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset+4)&0x7FFFFFFF; Element_Offset+=8; //Stream Position and size if (Pos<300 || MediaInfoLib::Config.ParseSpeed_Get()==1.00) { Stream_Structure[BaseOffset+Offset-8].Name=ChunkId&0xFFFF0000; Stream_Structure[BaseOffset+Offset-8].Size=Size; } StreamSize+=(Size&0x7FFFFFFF); Stream[ChunkId&0xFFFF0000].PacketCount++; //Interleaved if (Pos== 0 && (ChunkId&0xFFFF0000)==0x30300000 && Interleaved0_1 ==0) Interleaved0_1 =BaseOffset+Offset-8; if (Pos==Entry_Count/10 && (ChunkId&0xFFFF0000)==0x30300000 && Interleaved0_10==0) Interleaved0_10=BaseOffset+Offset-8; if (Pos== 0 && (ChunkId&0xFFFF0000)==0x30310000 && Interleaved1_1 ==0) Interleaved1_1 =BaseOffset+Offset-8; if (Pos==Entry_Count/10 && (ChunkId&0xFFFF0000)==0x30310000 && Interleaved1_10==0) Interleaved1_10=BaseOffset+Offset-8; } Stream[ChunkId&0xFFFF0000].StreamSize+=StreamSize; if (Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Garbage"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_indx_FieldIndex(int32u Entry_Count, int32u) { Element_Name("Field Index"); //Parsing Skip_L8( "Offset"); Skip_L4( "Reserved2"); for (int32u Pos=0; Pos<Entry_Count; Pos++) { Element_Begin1("Index"); Skip_L4( "Offset"); //BaseOffset + this is absolute file offset Skip_L4( "Size"); //Bit 31 is set if this is NOT a keyframe Skip_L4( "OffsetField2"); //Offset to second field Element_End0(); } } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_indx_SuperIndex(int32u Entry_Count, int32u ChunkId) { Element_Name("Index of Indexes"); //Parsing int64u Offset; Skip_L4( "Reserved0"); Skip_L4( "Reserved1"); Skip_L4( "Reserved2"); stream& StreamItem = Stream[Stream_ID]; for (int32u Pos=0; Pos<Entry_Count; Pos++) { int32u Duration; Element_Begin1("Index of Indexes"); Get_L8 (Offset, "Offset"); Skip_L4( "Size"); //Size of index chunk at this offset Get_L4 (Duration, "Duration"); //time span in stream ticks Index_Pos[Offset]=ChunkId; StreamItem.indx_Duration+=Duration; Element_End0(); } //We needn't anymore Old version NeedOldIndex=false; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_JUNK() { Element_Name("Garbage"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strd() { Element_Name("Stream datas"); //Parsing Skip_XX(Element_Size, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf() { Element_Name("Stream format"); //Parse depending of kind of stream stream& StreamItem = Stream[Stream_ID]; switch (StreamItem.fccType) { case Elements::AVI__hdlr_strl_strh_auds : AVI__hdlr_strl_strf_auds(); break; case Elements::AVI__hdlr_strl_strh_iavs : AVI__hdlr_strl_strf_iavs(); break; case Elements::AVI__hdlr_strl_strh_mids : AVI__hdlr_strl_strf_mids(); break; case Elements::AVI__hdlr_strl_strh_txts : AVI__hdlr_strl_strf_txts(); break; case Elements::AVI__hdlr_strl_strh_vids : AVI__hdlr_strl_strf_vids(); break; default : Element_Info1("Unknown"); } //Registering stream StreamItem.StreamKind=StreamKind_Last; StreamItem.StreamPos=StreamPos_Last; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds() { Element_Info1("Audio"); //Parsing #if !MEDIAINFO_DEMUX int32u AvgBytesPerSec; #endif //!MEDIAINFO_DEMUX int16u FormatTag, Channels; BitsPerSample=0; Get_L2 (FormatTag, "FormatTag"); Get_L2 (Channels, "Channels"); Get_L4 (SamplesPerSec, "SamplesPerSec"); Get_L4 (AvgBytesPerSec, "AvgBytesPerSec"); #if MEDIAINFO_DEMUX Get_L2 (BlockAlign, "BlockAlign"); #else //MEDIAINFO_DEMUX Skip_L2( "BlockAlign"); #endif //MEDIAINFO_DEMUX if (Element_Offset+2<=Element_Size) Get_L2 (BitsPerSample, "BitsPerSample"); if (FormatTag==1) //Only for PCM { //Coherancy if (BitsPerSample && SamplesPerSec*BitsPerSample*Channels/8==AvgBytesPerSec*8) AvgBytesPerSec*=8; //Found in one file. TODO: Provide information to end user about such error //Computing of missing value if (!BitsPerSample && AvgBytesPerSec && SamplesPerSec && Channels) BitsPerSample=(int16u)(AvgBytesPerSec*8/SamplesPerSec/Channels); } //Filling Stream_Prepare(Stream_Audio); stream& StreamItem = Stream[Stream_ID]; StreamItem.Compression=FormatTag; Ztring Codec; Codec.From_Number(FormatTag, 16); Codec.MakeUpperCase(); CodecID_Fill(Codec, Stream_Audio, StreamPos_Last, InfoCodecID_Format_Riff); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, Codec); //May be replaced by codec parser Fill(Stream_Audio, StreamPos_Last, Audio_Codec_CC, Codec); if (Channels) Fill(Stream_Audio, StreamPos_Last, Audio_Channel_s_, (Channels!=5 || FormatTag==0xFFFE)?Channels:6); if (SamplesPerSec) Fill(Stream_Audio, StreamPos_Last, Audio_SamplingRate, SamplesPerSec); if (AvgBytesPerSec) Fill(Stream_Audio, StreamPos_Last, Audio_BitRate, AvgBytesPerSec*8); if (BitsPerSample) Fill(Stream_Audio, StreamPos_Last, Audio_BitDepth, BitsPerSample); StreamItem.AvgBytesPerSec=AvgBytesPerSec; //Saving bitrate for each stream if (SamplesPerSec && TimeReference!=(int64u)-1) { Fill(Stream_Audio, 0, Audio_Delay, float64_int64s(((float64)TimeReference)*1000/SamplesPerSec)); Fill(Stream_Audio, 0, Audio_Delay_Source, "Container (bext)"); } //Specific cases #if defined(MEDIAINFO_DTS_YES) || defined(MEDIAINFO_SMPTEST0337_YES) if (FormatTag==0x1 && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) //Some DTS or SMPTE ST 337 streams are coded "1" { #if defined(MEDIAINFO_DTS_YES) { File_Dts* Parser=new File_Dts; Parser->Frame_Count_Valid=2; Parser->ShouldContinueParsing=true; #if MEDIAINFO_DEMUX if (Config->Demux_Unpacketize_Get() && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #endif //MEDIAINFO_DEMUX StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_SMPTEST0337_YES) { File_SmpteSt0337* Parser=new File_SmpteSt0337; Parser->Container_Bits=(int8u)BitsPerSample; Parser->Aligned=true; Parser->ShouldContinueParsing=true; #if MEDIAINFO_DEMUX if (Config->Demux_Unpacketize_Get() && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #endif //MEDIAINFO_DEMUX StreamItem.Parsers.push_back(Parser); } #endif } #endif //Creating the parser if (0); #if defined(MEDIAINFO_MPEGA_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("MPEG Audio")) { File_Mpega* Parser=new File_Mpega; Parser->CalculateDelay=true; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_AC3_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("AC-3")) { File_Ac3* Parser=new File_Ac3; Parser->Frame_Count_Valid=2; Parser->CalculateDelay=true; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_DTS_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("DTS")) { File_Dts* Parser=new File_Dts; Parser->Frame_Count_Valid=2; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_AAC_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("AAC")) { File_Aac* Parser=new File_Aac; Parser->Mode=File_Aac::Mode_ADTS; Parser->Frame_Count_Valid=1; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_PCM_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("PCM")) { File_Pcm* Parser=new File_Pcm; Parser->Codec=Codec; Parser->Endianness='L'; Parser->BitDepth=(int8u)BitsPerSample; #if MEDIAINFO_DEMUX if (Demux_Rate) Parser->Frame_Count_Valid = float64_int64s(Demux_Rate); if (Config->Demux_Unpacketize_Get() && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #else //MEDIAINFO_DEMUX Parser->Frame_Count_Valid=(int64u)-1; //Disabling it, waiting for SMPTE ST 337 parser reject #endif //MEDIAINFO_DEMUX stream& StreamItem = Stream[Stream_ID]; StreamItem.Parsers.push_back(Parser); StreamItem.IsPcm=true; } #endif #if defined(MEDIAINFO_ADPCM_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("ADPCM")) { //Creating the parser File_Adpcm MI; MI.Codec=Codec; //Parsing Open_Buffer_Init(&MI); Open_Buffer_Continue(&MI, 0); //Filling Finish(&MI); Merge(MI, StreamKind_Last, 0, StreamPos_Last); } #endif #if defined(MEDIAINFO_OGG_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("Vorbis") && FormatTag!=0x566F) //0x566F has config in this chunk { File_Ogg* Parser=new File_Ogg; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif Open_Buffer_Init_All(); //Options if (Element_Offset+2>Element_Size) return; //No options //Parsing int16u Option_Size; Get_L2 (Option_Size, "cbSize"); //Filling if (Option_Size>0) { if (0); else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("MPEG Audio")) { if (Option_Size==12) AVI__hdlr_strl_strf_auds_Mpega(); else Skip_XX(Option_Size, "MPEG Audio - Uknown"); } else if (Codec==__T("AAC") || Codec==__T("FF") || Codec==__T("8180")) AVI__hdlr_strl_strf_auds_Aac(); else if (FormatTag==0x566F) //Vorbis with Config in this chunk AVI__hdlr_strl_strf_auds_Vorbis(); else if (FormatTag==0x6750) //Vorbis with Config in this chunk AVI__hdlr_strl_strf_auds_Vorbis2(); else if (FormatTag==0xFFFE) //Extensible Wave AVI__hdlr_strl_strf_auds_ExtensibleWave(); else if (Element_Offset+Option_Size<=Element_Size) Skip_XX(Option_Size, "Unknown"); else if (Element_Offset!=Element_Size) Skip_XX(Element_Size-Element_Offset, "Error"); } } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_Mpega() { //Parsing Element_Begin1("MPEG Audio options"); Skip_L2( "ID"); Skip_L4( "Flags"); Skip_L2( "BlockSize"); Skip_L2( "FramesPerBlock"); Skip_L2( "CodecDelay"); Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_Aac() { //Parsing Element_Begin1("AAC options"); #if defined(MEDIAINFO_AAC_YES) File_Aac* MI=new File_Aac(); MI->Mode=File_Aac::Mode_AudioSpecificConfig; Open_Buffer_Init(MI); Open_Buffer_Continue(MI); Finish(MI); Merge(*MI, StreamKind_Last, 0, StreamPos_Last); delete MI; //MI=NULL; #else //MEDIAINFO_MPEG4_YES Skip_XX(Element_Size-Element_Offset, "(AudioSpecificConfig)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_Vorbis() { //Parsing Element_Begin1("Vorbis options"); #if defined(MEDIAINFO_OGG_YES) File_Ogg_SubElement MI; Open_Buffer_Init(&MI); Element_Begin1("Element sizes"); //All elements parsing, except last one std::vector<size_t> Elements_Size; size_t Elements_TotalSize=0; int8u Elements_Count; Get_L1(Elements_Count, "Element count"); Elements_Size.resize(Elements_Count+1); //+1 for the last block for (int8u Pos=0; Pos<Elements_Count; Pos++) { int8u Size; Get_L1(Size, "Size"); Elements_Size[Pos]=Size; Elements_TotalSize+=Size; } Element_End0(); if (Element_Offset+Elements_TotalSize>Element_Size) return; //Adding the last block Elements_Size[Elements_Count]=(size_t)(Element_Size-(Element_Offset+Elements_TotalSize)); Elements_Count++; //Parsing blocks for (int8u Pos=0; Pos<Elements_Count; Pos++) { Open_Buffer_Continue(&MI, Elements_Size[Pos]); Open_Buffer_Continue(&MI, 0); Element_Offset+=Elements_Size[Pos]; } //Finalizing Finish(&MI); Merge(MI, StreamKind_Last, 0, StreamPos_Last); Clear(Stream_Audio, StreamPos_Last, Audio_BitDepth); //Resolution is not valid for Vorbis Element_Show(); #else //MEDIAINFO_MPEG4_YES Skip_XX(Element_Size-Element_Offset, "(Vorbis headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_Vorbis2() { //Parsing Skip_XX(8, "Vorbis Unknown"); Element_Begin1("Vorbis options"); #if defined(MEDIAINFO_OGG_YES) stream& StreamItem = Stream[Stream_ID]; Open_Buffer_Continue(StreamItem.Parsers[0]); Open_Buffer_Continue(StreamItem.Parsers[0], 0); Finish(StreamItem.Parsers[0]); Merge(*StreamItem.Parsers[0], StreamKind_Last, 0, StreamPos_Last); Element_Show(); #else //MEDIAINFO_MPEG4_YES Skip_XX(Element_Size-Element_Offset, "(Vorbis headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_ExtensibleWave() { //Parsing int128u SubFormat; int32u ChannelMask; Skip_L2( "ValidBitsPerSample / SamplesPerBlock"); Get_L4 (ChannelMask, "ChannelMask"); Get_GUID(SubFormat, "SubFormat"); FILLING_BEGIN(); if ((SubFormat.hi&0xFFFFFFFFFFFF0000LL)==0x0010000000000000LL && SubFormat.lo==0x800000AA00389B71LL) { CodecID_Fill(Ztring().From_Number((int16u)SubFormat.hi, 16), Stream_Audio, StreamPos_Last, InfoCodecID_Format_Riff); Fill(Stream_Audio, StreamPos_Last, Audio_CodecID, Ztring().From_GUID(SubFormat), true); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, MediaInfoLib::Config.Codec_Get(Ztring().From_Number((int16u)SubFormat.hi, 16)), true); //Creating the parser if (0); #if defined(MEDIAINFO_PCM_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Ztring().From_Number((int16u)SubFormat.hi, 16))==__T("PCM")) { //Creating the parser File_Pcm* Parser=new File_Pcm; Parser->Codec=Ztring().From_GUID(SubFormat); Parser->Endianness='L'; Parser->Sign='S'; Parser->BitDepth=(int8u)BitsPerSample; #if MEDIAINFO_DEMUX if (Config->Demux_Unpacketize_Get() && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #endif //MEDIAINFO_DEMUX stream& StreamItem = Stream[Stream_ID]; StreamItem.Parsers.push_back(Parser); StreamItem.IsPcm=true; } #endif Open_Buffer_Init_All(); } else { CodecID_Fill(Ztring().From_GUID(SubFormat), Stream_Audio, StreamPos_Last, InfoCodecID_Format_Riff); } Fill(Stream_Audio, StreamPos_Last, Audio_ChannelPositions, ExtensibleWave_ChannelMask(ChannelMask)); Fill(Stream_Audio, StreamPos_Last, Audio_ChannelPositions_String2, ExtensibleWave_ChannelMask2(ChannelMask)); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_iavs() { //Standard video header before Iavs? if (Element_Size==72) { Element_Begin0(); AVI__hdlr_strl_strf_vids(); Element_End0(); } Element_Info1("Interleaved Audio/Video"); #ifdef MEDIAINFO_DVDIF_YES if (Element_Size<8*4) return; //Parsing DV_FromHeader=new File_DvDif(); Open_Buffer_Init(DV_FromHeader); //DVAAuxSrc ((File_DvDif*)DV_FromHeader)->AuxToAnalyze=0x50; //Audio source Open_Buffer_Continue(DV_FromHeader, 4); //DVAAuxCtl ((File_DvDif*)DV_FromHeader)->AuxToAnalyze=0x51; //Audio control Open_Buffer_Continue(DV_FromHeader, Buffer+Buffer_Offset+(size_t)Element_Offset, 4); Element_Offset+=4; //DVAAuxSrc1 Skip_L4( "DVAAuxSrc1"); //DVAAuxCtl1 Skip_L4( "DVAAuxCtl1"); //DVVAuxSrc ((File_DvDif*)DV_FromHeader)->AuxToAnalyze=0x60; //Video source Open_Buffer_Continue(DV_FromHeader, 4); //DVAAuxCtl ((File_DvDif*)DV_FromHeader)->AuxToAnalyze=0x61; //Video control Open_Buffer_Continue(DV_FromHeader, 4); //Reserved if (Element_Offset<Element_Size) { Skip_L4( "DVReserved"); Skip_L4( "DVReserved"); } Finish(DV_FromHeader); Stream_Prepare(Stream_Video); stream& StreamItem = Stream[Stream_ID]; StreamItem.Parsers.push_back(new File_DvDif); Open_Buffer_Init(StreamItem.Parsers[0]); #else //MEDIAINFO_DVDIF_YES //Parsing Skip_L4( "DVAAuxSrc"); Skip_L4( "DVAAuxCtl"); Skip_L4( "DVAAuxSrc1"); Skip_L4( "DVAAuxCtl1"); Skip_L4( "DVVAuxSrc"); Skip_L4( "DVVAuxCtl"); Skip_L4( "DVReserved"); Skip_L4( "DVReserved"); //Filling Ztring Codec; Codec.From_CC4(Stream[Stream_ID].fccHandler); Stream_Prepare(Stream_Video); float32 FrameRate=Retrieve(Stream_Video, StreamPos_Last, Video_FrameRate).To_float32(); Fill(Stream_Video, StreamPos_Last, Video_Codec, Codec); //May be replaced by codec parser Fill(Stream_Video, StreamPos_Last, Video_Codec_CC, Codec); if (Codec==__T("dvsd") || Codec==__T("dvsl")) { Fill(Stream_Video, StreamPos_Last, Video_Width, 720); if (FrameRate==25.000) Fill(Stream_Video, StreamPos_Last, Video_Height, 576); else if (FrameRate==29.970) Fill(Stream_Video, StreamPos_Last, Video_Height, 480); Fill(Stream_Video, StreamPos_Last, Video_DisplayAspectRatio, 4.0/3, 3, true); } else if (Codec==__T("dvhd")) { Fill(Stream_Video, StreamPos_Last, Video_Width, 1440); if (FrameRate==25.000) Fill(Stream_Video, StreamPos_Last, Video_Height, 1152); else if (FrameRate==30.000) Fill(Stream_Video, StreamPos_Last, Video_Height, 960); Fill(Stream_Video, StreamPos_Last, Video_DisplayAspectRatio, 4.0/3, 3, true); } Stream_Prepare(Stream_Audio); CodecID_Fill(Codec, Stream_Audio, StreamPos_Last, InfoCodecID_Format_Riff); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, Codec); //May be replaced by codec parser Fill(Stream_Audio, StreamPos_Last, Audio_Codec_CC, Codec); #endif //MEDIAINFO_DVDIF_YES } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_mids() { Element_Info1("Midi"); //Filling Stream_Prepare(Stream_Audio); Fill(Stream_Audio, StreamPos_Last, Audio_Format, "MIDI"); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, "Midi"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_txts() { Element_Info1("Text"); //Parsing Ztring Format; if (Element_Size) { Get_Local(10, Format, "Format"); Skip_XX(22, "Unknown"); } FILLING_BEGIN_PRECISE(); Stream_Prepare(Stream_Text); if (Element_Size==0) { //Creating the parser stream& StreamItem = Stream[Stream_ID]; #if defined(MEDIAINFO_SUBRIP_YES) StreamItem.Parsers.push_back(new File_SubRip); #endif #if defined(MEDIAINFO_OTHERTEXT_YES) StreamItem.Parsers.push_back(new File_OtherText); //For SSA #endif Open_Buffer_Init_All(); } else { Fill(Stream_Text, StreamPos_Last, Text_Format, Format); } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_vids() { Element_Info1("Video"); //Parsing int32u Compression, Width, Height; int16u Resolution; Skip_L4( "Size"); Get_L4 (Width, "Width"); Get_L4 (Height, "Height"); Skip_L2( "Planes"); Get_L2 (Resolution, "BitCount"); //Do not use it Get_C4 (Compression, "Compression"); Skip_L4( "SizeImage"); Skip_L4( "XPelsPerMeter"); Skip_L4( "YPelsPerMeter"); Skip_L4( "ClrUsed"); Skip_L4( "ClrImportant"); //Filling Stream[Stream_ID].Compression=Compression; if (Compression==CC4("DXSB")) { //Divx.com hack for subtitle, this is a text stream in a DivX Format Fill(Stream_General, 0, General_Format, "DivX", Unlimited, true, true); Stream_Prepare(Stream_Text); } else Stream_Prepare(Stream_Video); //Filling CodecID_Fill(Ztring().From_CC4(Compression), StreamKind_Last, StreamPos_Last, InfoCodecID_Format_Riff); Fill(StreamKind_Last, StreamPos_Last, Fill_Parameter(StreamKind_Last, Generic_Codec), Ztring().From_CC4(Compression).To_Local().c_str()); //FormatTag, may be replaced by codec parser Fill(StreamKind_Last, StreamPos_Last, Fill_Parameter(StreamKind_Last, Generic_Codec_CC), Ztring().From_CC4(Compression).To_Local().c_str()); //FormatTag Fill(StreamKind_Last, StreamPos_Last, "Width", Width, 10, true); Fill(StreamKind_Last, StreamPos_Last, "Height", Height>=0x80000000?(-((int32s)Height)):Height, 10, true); // AVI can use negative height for raw to signal that it's coded top-down, not bottom-up if (Resolution==32 && Compression==0x74736363) //tscc Fill(StreamKind_Last, StreamPos_Last, "BitDepth", 8); else if (Compression==0x44495633) //DIV3 Fill(StreamKind_Last, StreamPos_Last, "BitDepth", 8); else if (MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression)).find(__T("Canopus"))!=std::string::npos) //Canopus codecs Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution/3); else if (Compression==0x44585342) //DXSB Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution); else if (MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_ColorSpace).find(__T("RGBA"))!=std::string::npos) //RGB codecs Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution/4); else if (Compression==0x00000000 //RGB || MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_ColorSpace).find(__T("RGB"))!=std::string::npos) //RGB codecs { if (Resolution==32) { Fill(StreamKind_Last, StreamPos_Last, Fill_Parameter(StreamKind_Last, Generic_Format), "RGBA", Unlimited, true, true); Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution/4); //With Alpha } else Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution<=16?8:(Resolution/3)); //indexed or normal } else if (Compression==0x56503632 //VP62 || MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("H.263") //H.263 || MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("VC-1")) //VC-1 Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution/3); Stream[Stream_ID].StreamKind=StreamKind_Last; //Creating the parser if (0); #if defined(MEDIAINFO_FFV1_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("FFV1")) { File_Ffv1* Parser=new File_Ffv1; Parser->Width=Width; Parser->Height=Height; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_HUFFYUV_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("HuffYUV")) { File_HuffYuv* Parser=new File_HuffYuv; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_MPEGV_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("MPEG Video")) { File_Mpegv* Parser=new File_Mpegv; Parser->FrameIsAlwaysComplete=true; Parser->TimeCodeIsNotTrustable=true; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_MPEG4V_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("MPEG-4 Visual")) { File_Mpeg4v* Parser=new File_Mpeg4v; Stream[Stream_ID].Specific_IsMpeg4v=true; Parser->FrameIsAlwaysComplete=true; if (MediaInfoLib::Config.ParseSpeed_Get()>=0.5) Parser->ShouldContinueParsing=true; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_PRORES_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("ProRes")) { File_ProRes* Parser=new File_ProRes; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_AVC_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("AVC")) { File_Avc* Parser=new File_Avc; Parser->FrameIsAlwaysComplete=true; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_CANOPUS_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("Canopus HQ")) { File_Canopus* Parser=new File_Canopus; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_JPEG_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("JPEG")) { File_Jpeg* Parser=new File_Jpeg; Parser->StreamKind=Stream_Video; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_DVDIF_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("DV")) { File_DvDif* Parser=new File_DvDif; Parser->IgnoreAudio=true; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_FRAPS_YES) else if (Compression==0x46505331) //"FPS1" { File_Fraps* Parser=new File_Fraps; Stream[Stream_ID].Parsers.push_back(Parser); } #endif else if (Compression==0x48465955) //"HFUY" { switch (Resolution) { case 16 : Fill(Stream_Video, StreamPos_Last, Video_ColorSpace, "YUV"); Fill(Stream_Video, StreamPos_Last, Video_ChromaSubsampling, "4:2:2"); Fill(Stream_Video, StreamPos_Last, Video_BitDepth, 8); break; case 24 : Fill(Stream_Video, StreamPos_Last, Video_ColorSpace, "RGB"); Fill(Stream_Video, StreamPos_Last, Video_BitDepth, 8); break; case 32 : Fill(Stream_Video, StreamPos_Last, Video_ColorSpace, "RGBA"); Fill(Stream_Video, StreamPos_Last, Video_BitDepth, 8); break; default : ; } } #if defined(MEDIAINFO_LAGARITH_YES) else if (Compression==0x4C414753) //"LAGS" { File_Lagarith* Parser=new File_Lagarith; Stream[Stream_ID].Parsers.push_back(Parser); } #endif Open_Buffer_Init_All(); //Options if (Element_Offset>=Element_Size) return; //No options //Filling if (0); else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("AVC")) AVI__hdlr_strl_strf_vids_Avc(); else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("FFV1")) AVI__hdlr_strl_strf_vids_Ffv1(); else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("HuffYUV")) AVI__hdlr_strl_strf_vids_HuffYUV(Resolution, Height); else Skip_XX(Element_Size-Element_Offset, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_vids_Avc() { //Parsing Element_Begin1("AVC options"); #if defined(MEDIAINFO_AVC_YES) //Can be sized block or with 000001 stream& StreamItem = Stream[Stream_ID]; File_Avc* Parser=(File_Avc*)StreamItem.Parsers[0]; Parser->MustParse_SPS_PPS=false; Parser->SizedBlocks=false; Parser->MustSynchronize=true; int64u Element_Offset_Save=Element_Offset; Open_Buffer_Continue(Parser); if (!Parser->Status[IsAccepted]) { Element_Offset=Element_Offset_Save; delete StreamItem.Parsers[0]; StreamItem.Parsers[0]=new File_Avc; Parser=(File_Avc*)StreamItem.Parsers[0]; Open_Buffer_Init(Parser); Parser->FrameIsAlwaysComplete=true; Parser->MustParse_SPS_PPS=true; Parser->SizedBlocks=true; Parser->MustSynchronize=false; Open_Buffer_Continue(Parser); Element_Show(); } #else //MEDIAINFO_AVC_YES Skip_XX(Element_Size-Element_Offset, "(AVC headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_vids_Ffv1() { //Parsing Element_Begin1("FFV1 options"); #if defined(MEDIAINFO_FFV1_YES) File_Ffv1* Parser=(File_Ffv1*)Stream[Stream_ID].Parsers[0]; Open_Buffer_OutOfBand(Parser); #else //MEDIAINFO_FFV1_YES Skip_XX(Element_Size-Element_Offset, "(FFV1 headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_vids_HuffYUV(int16u BitCount, int32u Height) { //Parsing Element_Begin1("HuffYUV options"); #if defined(MEDIAINFO_HUFFYUV_YES) File_HuffYuv* Parser=(File_HuffYuv*)Stream[Stream_ID].Parsers[0]; Parser->IsOutOfBandData=true; Parser->BitCount=BitCount; Parser->Height=Height; Open_Buffer_Continue(Parser); #else //MEDIAINFO_HUFFYUV_YES Skip_XX(Element_Size-Element_Offset, "(HuffYUV headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strh() { Element_Name("Stream header"); //Parsing int32u fccType, fccHandler, Scale, Rate, Start, Length; int16u Left, Top, Right, Bottom; Get_C4 (fccType, "fccType"); switch (fccType) { case Elements::AVI__hdlr_strl_strh_auds : Get_L4 (fccHandler, "fccHandler"); break; default: Get_C4 (fccHandler, "fccHandler"); } Skip_L4( "Flags"); Skip_L2( "Priority"); Skip_L2( "Language"); Skip_L4( "InitialFrames"); Get_L4 (Scale, "Scale"); Get_L4 (Rate, "Rate"); //Rate/Scale is stream tick rate in ticks/sec Get_L4 (Start, "Start"); Get_L4 (Length, "Length"); Skip_L4( "SuggestedBufferSize"); Skip_L4( "Quality"); Skip_L4( "SampleSize"); Get_L2 (Left, "Frame_Left"); Get_L2 (Top, "Frame_Top"); Get_L2 (Right, "Frame_Right"); Get_L2 (Bottom, "Frame_Bottom"); if(Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); //Filling float32 FrameRate=0; if (Rate>0 && Scale>0) { //FrameRate (without known value detection) FrameRate=((float32)Rate)/Scale; if (FrameRate>1) { float32 Rest=FrameRate-(int32u)FrameRate; if (Rest<0.01) FrameRate-=Rest; else if (Rest>0.99) FrameRate+=1-Rest; else { float32 Rest1001=FrameRate*1001/1000-(int32u)(FrameRate*1001/1000); if (Rest1001<0.001) FrameRate=(float32)((int32u)(FrameRate*1001/1000))*1000/1001; if (Rest1001>0.999) FrameRate=(float32)((int32u)(FrameRate*1001/1000)+1)*1000/1001; } } //Duration if (FrameRate) { int64u Duration=float32_int64s((1000*(float32)Length)/FrameRate); if (avih_TotalFrame>0 //avih_TotalFrame is here because some files have a wrong Audio Duration if TotalFrame==0 (which is a bug, of course!) && (avih_FrameRate==0 || Duration<((float32)avih_TotalFrame)/avih_FrameRate*1000*1.10) //Some file have a nearly perfect header, except that the value is false, trying to detect it (false if 10% more than 1st video) && (avih_FrameRate==0 || Duration>((float32)avih_TotalFrame)/avih_FrameRate*1000*0.90)) //Some file have a nearly perfect header, except that the value is false, trying to detect it (false if 10% less than 1st video) { Fill(StreamKind_Last, StreamPos_Last, "Duration", Duration); } } } switch (fccType) { case Elements::AVI__hdlr_strl_strh_vids : if (FrameRate>0) Fill(Stream_Video, StreamPos_Last, Video_FrameRate, FrameRate, 3); if (Right-Left>0) Fill(Stream_Video, StreamPos_Last, Video_Width, Right-Left, 10, true); if (Bottom-Top>0) Fill(Stream_Video, StreamPos_Last, Video_Height, Bottom-Top, 10, true); break; case Elements::AVI__hdlr_strl_strh_txts : if (Right-Left>0) Fill(Stream_Text, StreamPos_Last, Text_Width, Right-Left, 10, true); if (Bottom-Top>0) Fill(Stream_Text, StreamPos_Last, Text_Height, Bottom-Top, 10, true); break; default: ; } stream& StreamItem = Stream[Stream_ID]; StreamItem.fccType=fccType; StreamItem.fccHandler=fccHandler; StreamItem.Scale=Scale; StreamItem.Rate=Rate; StreamItem.Start=Start; StreamItem.Length=Length; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strn() { Element_Name("Stream name"); //Parsing Ztring Title; Get_Local(Element_Size, Title, "StreamName"); //Filling Fill(StreamKind_Last, StreamPos_Last, "Title", Title); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_vprp() { Element_Name("Video properties"); //Parsing int32u FieldPerFrame; int16u FrameAspectRatio_H, FrameAspectRatio_W; Skip_L4( "VideoFormatToken"); Skip_L4( "VideoStandard"); Skip_L4( "VerticalRefreshRate"); Skip_L4( "HTotalInT"); Skip_L4( "VTotalInLines"); Get_L2 (FrameAspectRatio_H, "FrameAspectRatio Height"); Get_L2 (FrameAspectRatio_W, "FrameAspectRatio Width"); Skip_L4( "FrameWidthInPixels"); Skip_L4( "FrameHeightInLines"); Get_L4 (FieldPerFrame, "FieldPerFrame"); vector<int32u> VideoYValidStartLines; for (int32u Pos=0; Pos<FieldPerFrame; Pos++) { Element_Begin1("Field"); int32u VideoYValidStartLine; Skip_L4( "CompressedBMHeight"); Skip_L4( "CompressedBMWidth"); Skip_L4( "ValidBMHeight"); Skip_L4( "ValidBMWidth"); Skip_L4( "ValidBMXOffset"); Skip_L4( "ValidBMYOffset"); Skip_L4( "VideoXOffsetInT"); Get_L4 (VideoYValidStartLine, "VideoYValidStartLine"); VideoYValidStartLines.push_back(VideoYValidStartLine); Element_End0(); } if(Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); FILLING_BEGIN(); if (FrameAspectRatio_H && FrameAspectRatio_W) Fill(Stream_Video, 0, Video_DisplayAspectRatio, ((float32)FrameAspectRatio_W)/FrameAspectRatio_H, 3); switch (FieldPerFrame) { case 1 : Fill(Stream_Video, 0, Video_ScanType, "Progressive"); break; case 2 : Fill(Stream_Video, 0, Video_ScanType, "Interlaced"); if (VideoYValidStartLines.size()==2 && VideoYValidStartLines[0]<VideoYValidStartLines[1]) Fill(Stream_Video, 0, Video_ScanOrder, "TFF"); if (VideoYValidStartLines.size()==2 && VideoYValidStartLines[0]>VideoYValidStartLines[1]) Fill(Stream_Video, 0, Video_ScanOrder, "BFF"); default: ; } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_xxxx() { AVI__INFO_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::AVI__idx1() { Element_Name("Index (old)"); //Tests if (!NeedOldIndex || Idx1_Offset==(int64u)-1) { Skip_XX(Element_Size, "Data"); return; } //Testing malformed index (index is based on start of the file, wrong) if (16<=Element_Size && Idx1_Offset+4==LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset+ 8)) Idx1_Offset=0; //Fixing base of movi atom, the index think it is the start of the file //Parsing while (Element_Offset+16<=Element_Size) { //Is too slow /* int32u ChunkID, Offset, Size; Element_Begin1("Index"); Get_C4 (ChunkID, "ChunkID"); //Bit 31 is set if this is NOT a keyframe Info_L4(Flags, "Flags"); Skip_Flags(Flags, 0, "NoTime"); Skip_Flags(Flags, 1, "Lastpart"); Skip_Flags(Flags, 2, "Firstpart"); Skip_Flags(Flags, 3, "Midpart"); Skip_Flags(Flags, 4, "KeyFrame"); Get_L4 (Offset, "Offset"); //qwBaseOffset + this is absolute file offset Get_L4 (Size, "Size"); //Bit 31 is set if this is NOT a keyframe Element_Info1(Ztring().From_CC4(ChunkID)); Element_Info1(Size); //Stream Pos and Size int32u StreamID=(ChunkID&0xFFFF0000); Stream[StreamID].StreamSize+=Size; Stream[StreamID].PacketCount++; Stream_Structure[Idx1_Offset+Offset].Name=StreamID; Stream_Structure[Idx1_Offset+Offset].Size=Size; Element_End0(); */ //Faster method int32u StreamID=BigEndian2int32u (Buffer+Buffer_Offset+(size_t)Element_Offset )&0xFFFF0000; int32u Offset =LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset+ 8); int32u Size =LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset+12); stream& Stream_Item=Stream[StreamID]; Stream_Item.StreamSize+=Size; Stream_Item.PacketCount++; stream_structure& Stream_Structure_Item=Stream_Structure[Idx1_Offset+Offset]; Stream_Structure_Item.Name=StreamID; Stream_Structure_Item.Size=Size; Element_Offset+=16; } //Interleaved size_t Pos0=0; size_t Pos1=0; for (std::map<int64u, stream_structure>::iterator Temp=Stream_Structure.begin(); Temp!=Stream_Structure.end(); ++Temp) { switch (Temp->second.Name) { case 0x30300000 : if (Interleaved0_1==0) Interleaved0_1=Temp->first; if (Interleaved0_10==0) { Pos0++; if (Pos0>1) Interleaved0_10=Temp->first; } break; case 0x30310000 : if (Interleaved1_1==0) Interleaved1_1=Temp->first; if (Interleaved1_10==0) { Pos1++; if (Pos1>1) Interleaved1_10=Temp->first; } break; default:; } } } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO() { Element_Name("Tags"); } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO_IID3() { Element_Name("ID3 Tag"); //Parsing #if defined(MEDIAINFO_ID3_YES) File_Id3 MI; Open_Buffer_Init(&MI); Open_Buffer_Continue(&MI); Finish(&MI); Merge(MI, Stream_General, 0, 0); #endif } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO_ILYC() { Element_Name("Lyrics"); } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO_IMP3() { Element_Name("MP3 Information"); } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO_JUNK() { Element_Name("Garbage"); } //--------------------------------------------------------------------------- // List of information atoms // Name X bytes, Pos=0 // void File_Riff::AVI__INFO_xxxx() { //Parsing Ztring Value; Get_Local(Element_Size, Value, "Value"); //Filling stream_t StreamKind=Stream_General; size_t StreamPos=0; size_t Parameter=(size_t)-1; switch (Element_Code) { case 0x00000000 : Parameter=General_Comment; break; case Elements::AVI__INFO_IARL : Parameter=General_Archival_Location; break; case Elements::AVI__INFO_IART : Parameter=General_Director; break; case Elements::AVI__INFO_IAS1 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=0; break; case Elements::AVI__INFO_IAS2 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=1; break; case Elements::AVI__INFO_IAS3 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=2; break; case Elements::AVI__INFO_IAS4 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=3; break; case Elements::AVI__INFO_IAS5 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=4; break; case Elements::AVI__INFO_IAS6 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=5; break; case Elements::AVI__INFO_IAS7 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=6; break; case Elements::AVI__INFO_IAS8 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=7; break; case Elements::AVI__INFO_IAS9 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=8; break; case Elements::AVI__INFO_ICDS : Parameter=General_CostumeDesigner; break; case Elements::AVI__INFO_ICMS : Parameter=General_CommissionedBy; break; case Elements::AVI__INFO_ICMT : Parameter=General_Comment; break; case Elements::AVI__INFO_ICNM : Parameter=General_DirectorOfPhotography; break; case Elements::AVI__INFO_ICNT : Parameter=General_Movie_Country; break; case Elements::AVI__INFO_ICOP : Parameter=General_Copyright; break; case Elements::AVI__INFO_ICRD : Parameter=General_Recorded_Date; Value.Date_From_String(Value.To_Local().c_str()); break; case Elements::AVI__INFO_ICRP : Parameter=General_Cropped; break; case Elements::AVI__INFO_IDIM : Parameter=General_Dimensions; break; case Elements::AVI__INFO_IDIT : Parameter=General_Mastered_Date; Value.Date_From_String(Value.To_Local().c_str()); break; case Elements::AVI__INFO_IDPI : Parameter=General_DotsPerInch; break; case Elements::AVI__INFO_IDST : Parameter=General_DistributedBy; break; case Elements::AVI__INFO_IEDT : Parameter=General_EditedBy; break; case Elements::AVI__INFO_IENG : Parameter=General_EncodedBy; break; case Elements::AVI__INFO_IGNR : Parameter=General_Genre; break; case Elements::AVI__INFO_IFRM : Parameter=General_Part_Position_Total; break; case Elements::AVI__INFO_IKEY : Parameter=General_Keywords; break; case Elements::AVI__INFO_ILGT : Parameter=General_Lightness; break; case Elements::AVI__INFO_ILNG : Parameter=Audio_Language; StreamKind=Stream_Audio; break; case Elements::AVI__INFO_IMED : Parameter=General_OriginalSourceMedium; break; case Elements::AVI__INFO_IMUS : Parameter=General_MusicBy; break; case Elements::AVI__INFO_INAM : Parameter=General_Title; break; case Elements::AVI__INFO_IPDS : Parameter=General_ProductionDesigner; break; case Elements::AVI__INFO_IPLT : Parameter=General_OriginalSourceForm_NumColors; break; case Elements::AVI__INFO_IPRD : Parameter=General_OriginalSourceForm_Name; break; case Elements::AVI__INFO_IPRO : Parameter=General_Producer; break; case Elements::AVI__INFO_IPRT : Parameter=General_Part_Position; break; case Elements::AVI__INFO_IRTD : Parameter=General_LawRating; break; case Elements::AVI__INFO_ISBJ : Parameter=General_Subject; break; case Elements::AVI__INFO_ISFT : Parameter=General_Encoded_Application; break; case Elements::AVI__INFO_ISGN : Parameter=General_Genre; break; case Elements::AVI__INFO_ISHP : Parameter=General_OriginalSourceForm_Sharpness; break; case Elements::AVI__INFO_ISRC : Parameter=General_OriginalSourceForm_DistributedBy; break; case Elements::AVI__INFO_ISRF : Parameter=General_OriginalSourceForm; break; case Elements::AVI__INFO_ISTD : Parameter=General_ProductionStudio; break; case Elements::AVI__INFO_ISTR : Parameter=General_Performer; break; case Elements::AVI__INFO_ITCH : Parameter=General_EncodedBy; break; case Elements::AVI__INFO_IWEB : Parameter=General_Movie_Url; break; case Elements::AVI__INFO_IWRI : Parameter=General_WrittenBy; break; default : ; } Element_Name(MediaInfoLib::Config.Info_Get(StreamKind, Parameter, Info_Name)); Element_Info1(Value); switch (Element_Code) { case Elements::AVI__INFO_ISMP : INFO_ISMP=Value; break; case Elements::AVI__INFO_IGNR : { Ztring ISGN=Retrieve(Stream_General, 0, General_Genre); Clear(Stream_General, 0, General_Genre); Fill(StreamKind, StreamPos, General_Genre, Value); if (!ISGN.empty()) Fill(StreamKind, StreamPos, General_Genre, ISGN); } break; default : if (!Value.empty()) { if (Parameter!=(size_t)-1) Fill(StreamKind, StreamPos, Parameter, Value); else Fill(StreamKind, StreamPos, Ztring().From_CC4((int32u)Element_Code).To_Local().c_str(), Value, true); } } } //--------------------------------------------------------------------------- void File_Riff::AVI__JUNK() { Element_Name("Garbage"); //Library defined size for padding, often used to store library name if (Element_Size<8) { Skip_XX(Element_Size, "Junk"); return; } //Detect DivX files if (CC5(Buffer+Buffer_Offset)==CC5("DivX ")) { Fill(Stream_General, 0, General_Format, "DivX", Unlimited, true, true); } //MPlayer else if (CC8(Buffer+Buffer_Offset)==CC8("[= MPlay") && Retrieve(Stream_General, 0, General_Encoded_Library).empty()) Fill(Stream_General, 0, General_Encoded_Library, "MPlayer"); //Scenalyzer else if (CC8(Buffer+Buffer_Offset)==CC8("scenalyz") && Retrieve(Stream_General, 0, General_Encoded_Library).empty()) Fill(Stream_General, 0, General_Encoded_Library, "Scenalyzer"); //FFMpeg broken files detection else if (CC8(Buffer+Buffer_Offset)==CC8("odmldmlh")) dmlh_TotalFrame=0; //this is not normal to have this string in a JUNK block!!! and in files tested, in this case TotalFrame is broken too //VirtualDubMod else if (CC8(Buffer+Buffer_Offset)==CC8("INFOISFT")) { int32u Size=LittleEndian2int32u(Buffer+Buffer_Offset+8); if (Size>Element_Size-12) Size=(int32u)Element_Size-12; Fill(Stream_General, 0, General_Encoded_Library, (const char*)(Buffer+Buffer_Offset+12), Size); } else if (CC8(Buffer+Buffer_Offset)==CC8("INFOIENG")) { int32u Size=LittleEndian2int32u(Buffer+Buffer_Offset+8); if (Size>Element_Size-12) Size=(int32u)Element_Size-12; Fill(Stream_General, 0, General_Encoded_Library, (const char*)(Buffer+Buffer_Offset+12), Size); } //Other libraries? else if (CC1(Buffer+Buffer_Offset)>=CC1("A") && CC1(Buffer+Buffer_Offset)<=CC1("z") && Retrieve(Stream_General, 0, General_Encoded_Library).empty()) Fill(Stream_General, 0, General_Encoded_Library, (const char*)(Buffer+Buffer_Offset), (size_t)Element_Size); Skip_XX(Element_Size, "Data"); } //--------------------------------------------------------------------------- void File_Riff::AVI__MD5_() { //Parsing while (Element_Offset<Element_Size) { int128u MD5Stored; Get_L16 (MD5Stored, "MD5"); Ztring MD5_PerItem; MD5_PerItem.From_Number(MD5Stored, 16); while (MD5_PerItem.size()<32) MD5_PerItem.insert(MD5_PerItem.begin(), '0'); //Padding with 0, this must be a 32-byte string MD5_PerItem.MakeLowerCase(); MD5s.push_back(MD5_PerItem); } } //--------------------------------------------------------------------------- void File_Riff::AVI__movi() { Element_Name("Datas"); //Only the first time, no need in AVIX if (movi_Size==0) { Idx1_Offset=File_Offset+Buffer_Offset-4; BookMark_Set(); //Remenbering this place, for stream parsing in phase 2 //For each stream std::map<int32u, stream>::iterator Temp=Stream.begin(); while (Temp!=Stream.end()) { if ((Temp->second.Parsers.empty() || Temp->second.Parsers[0]==NULL) && Temp->second.fccType!=Elements::AVI__hdlr_strl_strh_txts) { Temp->second.SearchingPayload=false; stream_Count--; } ++Temp; } } //Probing rec (with index, this is not always tested in the flow if (Element_Size<12) { Element_WaitForMoreData(); return; } if (CC4(Buffer+Buffer_Offset+8)==0x72656320) //"rec " rec__Present=true; //Filling if (!SecondPass) movi_Size+=Element_TotalSize_Get(); //We must parse moov? if (NeedOldIndex || (stream_Count==0 && Index_Pos.empty())) { //Jumping #if MEDIAINFO_TRACE if (Trace_Activated) Param("Data", Ztring("(")+Ztring::ToZtring(Element_TotalSize_Get())+Ztring(" bytes)")); #endif //MEDIAINFO_TRACE Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer return; } //Jump to next useful data AVI__movi_StreamJump(); } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_rec_() { Element_Name("Syncronisation"); rec__Present=true; } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_rec__xxxx() { AVI__movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_xxxx() { if (Element_Code==Elements::AVI__JUNK) { Skip_XX(Element_Size, "Junk"); AVI__movi_StreamJump(); return; } if (Element_Code!=(int64u)-1) Stream_ID=(int32u)(Element_Code&0xFFFF0000); else Stream_ID=(int32u)-1; if (Stream_ID==0x69780000) //ix.. { //AVI Standard Index Chunk AVI__hdlr_strl_indx(); Stream_ID=(int32u)(Element_Code&0x0000FFFF)<<16; AVI__movi_StreamJump(); return; } if ((Element_Code&0x0000FFFF)==0x00006978) //..ix (Out of specs, but found in a Adobe After Effects CS4 DV file { //AVI Standard Index Chunk AVI__hdlr_strl_indx(); Stream_ID=(int32u)(Element_Code&0xFFFF0000); AVI__movi_StreamJump(); return; } stream& StreamItem = Stream[Stream_ID]; #if MEDIAINFO_DEMUX if (StreamItem.Rate) //AVI { int64u Element_Code_Old=Element_Code; Element_Code=((Element_Code_Old>>24)&0xF)*10+((Element_Code_Old>>16)&0xF); Frame_Count_NotParsedIncluded= StreamItem.PacketPos; FrameInfo.DTS=Frame_Count_NotParsedIncluded*1000000000* StreamItem.Scale/ StreamItem.Rate; Demux(Buffer+Buffer_Offset, (size_t)Element_Size, ContentType_MainStream); Element_Code=Element_Code_Old; Frame_Count_NotParsedIncluded=(int64u)-1; } else //WAV { //TODO } #endif //MEDIAINFO_DEMUX StreamItem.PacketPos++; //Finished? if (!StreamItem.SearchingPayload) { Element_DoNotShow(); AVI__movi_StreamJump(); return; } #if MEDIAINFO_TRACE if (Config_Trace_Level) { switch (Element_Code&0x0000FFFF) //2 last bytes { case Elements::AVI__movi_xxxx_____ : Element_Info1("DV"); break; case Elements::AVI__movi_xxxx___db : case Elements::AVI__movi_xxxx___dc : Element_Info1("Video"); break; case Elements::AVI__movi_xxxx___sb : case Elements::AVI__movi_xxxx___tx : Element_Info1("Text"); break; case Elements::AVI__movi_xxxx___wb : Element_Info1("Audio"); break; default : Element_Info1("Unknown"); break; } Element_Info1(Stream[Stream_ID].PacketPos); } #endif //MEDIAINFO_TRACE //Some specific stuff switch (Element_Code&0x0000FFFF) //2 last bytes { case Elements::AVI__movi_xxxx___tx : AVI__movi_xxxx___tx(); break; default : ; } //Parsing for (size_t Pos=0; Pos<StreamItem.Parsers.size(); Pos++) if (StreamItem.Parsers[Pos]) { if (FrameInfo.PTS!=(int64u)-1) StreamItem.Parsers[Pos]->FrameInfo.PTS=FrameInfo.PTS; if (FrameInfo.DTS!=(int64u)-1) StreamItem.Parsers[Pos]->FrameInfo.DTS=FrameInfo.DTS; Open_Buffer_Continue(StreamItem.Parsers[Pos], Buffer+Buffer_Offset+(size_t)Element_Offset, (size_t)(Element_Size-Element_Offset)); Element_Show(); if (StreamItem.Parsers.size()==1 && StreamItem.Parsers[Pos]->Buffer_Size>0) StreamItem.ChunksAreComplete=false; if (StreamItem.Parsers.size()>1) { if (!StreamItem.Parsers[Pos]->Status[IsAccepted] && StreamItem.Parsers[Pos]->Status[IsFinished]) { delete *(StreamItem.Parsers.begin()+Pos); StreamItem.Parsers.erase(StreamItem.Parsers.begin()+Pos); Pos--; } else if (StreamItem.Parsers.size()>1 && StreamItem.Parsers[Pos]->Status[IsAccepted]) { File__Analyze* Parser= StreamItem.Parsers[Pos]; for (size_t Pos2=0; Pos2<StreamItem.Parsers.size(); Pos2++) { if (Pos2!=Pos) delete *(StreamItem.Parsers.begin()+Pos2); } StreamItem.Parsers.clear(); StreamItem.Parsers.push_back(Parser); Pos=0; } } #if MEDIAINFO_DEMUX if (Config->Demux_EventWasSent) { Demux_Parser= StreamItem.Parsers[Pos]; return; } #endif //MEDIAINFO_DEMUX } Element_Offset=Element_Size; //Some specific stuff switch (Element_Code&0x0000FFFF) //2 last bytes { case Elements::AVI__movi_xxxx_____ : case Elements::AVI__movi_xxxx___db : case Elements::AVI__movi_xxxx___dc : AVI__movi_xxxx___dc(); break; case Elements::AVI__movi_xxxx___wb : AVI__movi_xxxx___wb(); break; default : ; } //We must always parse moov? AVI__movi_StreamJump(); Element_Show(); } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_xxxx___dc() { //Finish (if requested) stream& StreamItem = Stream[Stream_ID]; if (StreamItem.Parsers.empty() || StreamItem.Parsers[0]->Status[IsFinished] || (StreamItem.PacketPos>=300 && MediaInfoLib::Config.ParseSpeed_Get()<1.00)) { StreamItem.SearchingPayload=false; stream_Count--; return; } } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_xxxx___tx() { //Parsing int32u Name_Size; Ztring Value; int32u GAB2; Peek_B4(GAB2); if (GAB2==0x47414232 && Element_Size>=17) { Skip_C4( "GAB2"); Skip_L1( "Zero"); Skip_L2( "CodePage"); //2=Unicode Get_L4 (Name_Size, "Name_Size"); Skip_UTF16L(Name_Size, "Name"); Skip_L2( "Four"); Skip_L4( "File_Size"); if (Element_Offset>Element_Size) Element_Offset=Element_Size; //Problem } //Skip it Stream[Stream_ID].SearchingPayload=false; stream_Count--; } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_xxxx___wb() { //Finish (if requested) stream& StreamItem = Stream[Stream_ID]; if (StreamItem.PacketPos>=4 //For having the chunk alignement && (StreamItem.Parsers.empty() || StreamItem.Parsers[0]->Status[IsFinished] || (StreamItem.PacketPos>=300 && MediaInfoLib::Config.ParseSpeed_Get()<1.00))) { StreamItem.SearchingPayload=false; stream_Count--; } } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_StreamJump() { //Jump to next useful data if (!Index_Pos.empty()) { if (Index_Pos.begin()->first<=File_Offset+Buffer_Offset && Element_Code!=Elements::AVI__movi) Index_Pos.erase(Index_Pos.begin()); int64u ToJump=File_Size; if (!Index_Pos.empty()) ToJump=Index_Pos.begin()->first; if (ToJump>File_Size) ToJump=File_Size; if (ToJump>=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2)) //We want always Element movi { #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong() && SecondPass) Hash_ParseUpTo=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2); else #endif //MEDIAINFO_HASH GoTo(File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2), "AVI"); //Not in this chunk } else if (ToJump!=File_Offset+Buffer_Offset+(Element_Code==Elements::AVI__movi?0:Element_Size)) { #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong() && SecondPass) Hash_ParseUpTo=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2); else #endif //MEDIAINFO_HASH GoTo(ToJump, "AVI"); //Not just after } } else if (stream_Count==0) { //Jumping Element_Show(); if (rec__Present) Element_End0(); Info("movi, Jumping to end of chunk"); if (SecondPass) { std::map<int32u, stream>::iterator Temp=Stream.begin(); while (Temp!=Stream.end()) { for (size_t Pos=0; Pos<Temp->second.Parsers.size(); ++Pos) { Temp->second.Parsers[Pos]->Fill(); Temp->second.Parsers[Pos]->Open_Buffer_Unsynch(); } ++Temp; } Finish("AVI"); //The rest is already parsed } else GoTo(File_Offset+Buffer_Offset+Element_TotalSize_Get(), "AVI"); } else if (Stream_Structure_Temp!=Stream_Structure.end()) { do Stream_Structure_Temp++; while (Stream_Structure_Temp!=Stream_Structure.end() && !(Stream[(int32u)Stream_Structure_Temp->second.Name].SearchingPayload && Config->ParseSpeed<1.0)); if (Stream_Structure_Temp!=Stream_Structure.end()) { int64u ToJump=Stream_Structure_Temp->first; if (ToJump>=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2)) { #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong() && SecondPass) Hash_ParseUpTo=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2); else #endif //MEDIAINFO_HASH GoTo(File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2), "AVI"); //Not in this chunk } else if (ToJump!=File_Offset+Buffer_Offset+Element_Size) { #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong() && SecondPass) Hash_ParseUpTo=ToJump; else #endif //MEDIAINFO_HASH GoTo(ToJump, "AVI"); //Not just after } } else Finish("AVI"); } } //--------------------------------------------------------------------------- void File_Riff::AVI__PrmA() { Element_Name("Adobe Premiere PrmA"); //Parsing int32u FourCC, Size; Get_C4 (FourCC, "FourCC"); Get_B4 (Size, "Size"); switch (FourCC) { case 0x50415266: if (Size==20) { int32u PAR_X, PAR_Y; Skip_B4( "Unknown"); Get_B4 (PAR_X, "PAR_X"); Get_B4 (PAR_Y, "PAR_Y"); if (PAR_Y) PAR=((float64)PAR_X)/PAR_Y; } else Skip_XX(Element_Size-Element_Offset, "Unknown"); break; default: for (int32u Pos=8; Pos<Size; Pos++) Skip_B4( "Unknown"); } } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat() { Element_Name("Adobe Premiere Tdat"); } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat_tc_A() { Element_Name("tc_A"); //Parsing Ztring Value; Get_Local(Element_Size, Value, "Unknown"); if (Value.find_first_not_of(__T("0123456789:;"))==string::npos) Tdat_tc_A=Value; } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat_tc_O() { Element_Name("tc_O"); //Parsing Ztring Value; Get_Local(Element_Size, Value, "Unknown"); if (Value.find_first_not_of(__T("0123456789:;"))==string::npos) Tdat_tc_O=Value; } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat_rn_A() { Element_Name("rn_A"); //Parsing Skip_Local(Element_Size, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat_rn_O() { Element_Name("rn_O"); //Parsing Skip_Local(Element_Size, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__xxxx() { Stream_ID=(int32u)(Element_Code&0xFFFF0000); if (Stream_ID==0x69780000) //ix.. { //AVI Standard Index Chunk AVI__hdlr_strl_indx(); Stream_ID=(int32u)(Element_Code&0x0000FFFF)<<16; AVI__movi_StreamJump(); return; } if ((Element_Code&0x0000FFFF)==0x00006978) //..ix (Out of specs, but found in a Adobe After Effects CS4 DV file { //AVI Standard Index Chunk AVI__hdlr_strl_indx(); Stream_ID=(int32u)(Element_Code&0xFFFF0000); AVI__movi_StreamJump(); return; } } //--------------------------------------------------------------------------- void File_Riff::AVIX() { //Filling Fill(Stream_General, 0, General_Format_Profile, "OpenDML", Unlimited, true, true); } //--------------------------------------------------------------------------- void File_Riff::AVIX_idx1() { AVI__idx1(); } //--------------------------------------------------------------------------- void File_Riff::AVIX_movi() { AVI__movi(); } //--------------------------------------------------------------------------- void File_Riff::AVIX_movi_rec_() { AVI__movi_rec_(); } //--------------------------------------------------------------------------- void File_Riff::AVIX_movi_rec__xxxx() { AVIX_movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::AVIX_movi_xxxx() { AVI__movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::CADP() { Element_Name("CMP4 - ADPCM"); //Testing if we have enough data if (Element_Size<4) { Element_WaitForMoreData(); return; } //Parsing int32u Codec; Get_C4 (Codec, "Codec"); #if MEDIAINFO_TRACE if (Trace_Activated) Param("Data", Ztring("(")+Ztring::ToZtring(Element_TotalSize_Get()-Element_Offset)+Ztring(" bytes)")); #endif //MEDIAINFO_TRACE Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer FILLING_BEGIN(); Stream_Prepare(Stream_Audio); if (Codec==0x41647063) //Adpc Fill(Stream_Audio, StreamPos_Last, Audio_Format, "ADPCM"); Fill(Stream_Audio, StreamPos_Last, Audio_StreamSize, Element_TotalSize_Get()); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::CDDA() { Element_Name("Compact Disc for Digital Audio"); //Filling Accept("CDDA"); } //--------------------------------------------------------------------------- void File_Riff::CDDA_fmt_() { //Specs: http://fr.wikipedia.org/wiki/Compact_Disc_Audio_track //Specs: http://www.moon-soft.com/program/FORMAT/sound/cda.htm Element_Name("Stream format"); //Parsing int32u id; int16u Version, tracknb=1; int8u TPositionF=0, TPositionS=0, TPositionM=0, TDurationF=0, TDurationS=0, TDurationM=0; Get_L2 (Version, "Version"); // Always 1 if (Version!=1) { //Not supported Skip_XX(Element_Size-2, "Data"); return; } Get_L2 (tracknb, "Number"); // Start at 1 Get_L4 (id, "id"); Skip_L4( "offset"); // in frames //Priority of FSM format Skip_L4( "Duration"); // in frames //Priority of FSM format Get_L1 (TPositionF, "Track_PositionF"); // in frames Get_L1 (TPositionS, "Track_PositionS"); // in seconds Get_L1 (TPositionM, "Track_PositionM"); // in minutes Skip_L1( "empty"); Get_L1 (TDurationF, "Track_DurationF"); // in frames Get_L1 (TDurationS, "Track_DurationS"); // in seconds Get_L1 (TDurationM, "Track_DurationM"); // in minutes Skip_L1( "empty"); FILLING_BEGIN(); int32u TPosition=TPositionM*60*75+TPositionS*75+TPositionF; int32u TDuration=TDurationM*60*75+TDurationS*75+TDurationF; Fill(Stream_General, 0, General_Track_Position, tracknb); Fill(Stream_General, 0, General_Format, "CDDA"); Fill(Stream_General, 0, General_Format_Info, "Compact Disc for Digital Audio"); Fill(Stream_General, 0, General_UniqueID, id); Fill(Stream_General, 0, General_FileSize, File_Size+TDuration*2352, 10, true); Stream_Prepare(Stream_Audio); Fill(Stream_Audio, 0, Audio_Format, "PCM"); Fill(Stream_Audio, 0, Audio_Format_Settings_Endianness, "Little"); Fill(Stream_Audio, 0, Audio_BitDepth, 16); Fill(Stream_Audio, 0, Audio_Channel_s_, 2); Fill(Stream_Audio, 0, Audio_SamplingRate, 44100); Fill(Stream_Audio, 0, Audio_FrameRate, (float)75); Fill(Stream_Audio, 0, Audio_BitRate, 1411200); Fill(Stream_Audio, 0, Audio_Compression_Mode, "Lossless"); Fill(Stream_Audio, 0, Audio_FrameCount, TDuration); Fill(Stream_Audio, 0, Audio_Duration, float32_int32s(((float32)TDuration)*1000/75)); Fill(Stream_Audio, 0, Audio_Delay, float32_int32s(((float32)TPosition)*1000/75)); //No more need data Finish("CDDA"); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::CMJP() { Element_Name("CMP4 - JPEG"); //Parsing #ifdef MEDIAINFO_JPEG_YES Stream_ID=0; File_Jpeg* Parser=new File_Jpeg; Open_Buffer_Init(Parser); Parser->StreamKind=Stream_Video; Open_Buffer_Continue(Parser); Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer FILLING_BEGIN(); Stream_Prepare(Stream_Video); Fill(Stream_Video, StreamPos_Last, Video_StreamSize, Element_TotalSize_Get()); Finish(Parser); Merge(*Parser, StreamKind_Last, 0, StreamPos_Last); FILLING_END(); Stream[Stream_ID].Parsers.push_back(Parser); #else Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer FILLING_BEGIN(); Stream_Prepare(Stream_Video); Fill(Stream_Video, StreamPos_Last, Video_Format, "JPEG"); Fill(Stream_Video, StreamPos_Last, Video_StreamSize, Element_TotalSize_Get()); FILLING_END(); #endif } //--------------------------------------------------------------------------- void File_Riff::CMP4() { Accept("CMP4"); Element_Name("CMP4 - Header"); //Parsing Ztring Title; Get_Local(Element_Size, Title, "Title"); FILLING_BEGIN(); Fill(Stream_General, 0, General_Format, "CMP4"); Fill(Stream_General, 0, "Title", Title); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::IDVX() { Element_Name("Tags"); } //--------------------------------------------------------------------------- void File_Riff::INDX() { Element_Name("Index (from which spec?)"); } //--------------------------------------------------------------------------- void File_Riff::INDX_xxxx() { Stream_ID=(int32u)(Element_Code&0xFFFF0000); if (Stream_ID==0x69780000) //ix.. { //Index int32u Entry_Count, ChunkId; int16u LongsPerEntry; int8u IndexType, IndexSubType; Get_L2 (LongsPerEntry, "LongsPerEntry"); //Size of each entry in aIndex array Get_L1 (IndexSubType, "IndexSubType"); Get_L1 (IndexType, "IndexType"); Get_L4 (Entry_Count, "EntriesInUse"); //Index of first unused member in aIndex array Get_C4 (ChunkId, "ChunkId"); //FCC of what is indexed Skip_L4( "Unknown"); Skip_L4( "Unknown"); Skip_L4( "Unknown"); for (int32u Pos=0; Pos<Entry_Count; Pos++) { Skip_L8( "Offset"); Skip_L4( "Size"); Skip_L4( "Frame number?"); Skip_L4( "Frame number?"); Skip_L4( "Zero"); } } //Currently, we do not use the index //TODO: use the index Stream_Structure.clear(); } //--------------------------------------------------------------------------- void File_Riff::JUNK() { Element_Name("Junk"); //Parse #if MEDIAINFO_TRACE if (Trace_Activated) Param("Junk", Ztring("(")+Ztring::ToZtring(Element_TotalSize_Get())+Ztring(" bytes)")); #endif //MEDIAINFO_TRACE Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer } //--------------------------------------------------------------------------- void File_Riff::menu() { Element_Name("DivX Menu"); //Filling Stream_Prepare(Stream_Menu); Fill(Stream_Menu, StreamPos_Last, Menu_Format, "DivX Menu"); Fill(Stream_Menu, StreamPos_Last, Menu_Codec, "DivX"); } //--------------------------------------------------------------------------- void File_Riff::MThd() { Element_Name("MIDI header"); //Parsing Skip_B2( "format"); Skip_B2( "ntrks"); Skip_B2( "division"); FILLING_BEGIN_PRECISE(); Accept("MIDI"); Fill(Stream_General, 0, General_Format, "MIDI"); FILLING_ELSE(); Reject("MIDI"); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::MTrk() { Element_Name("MIDI Track"); //Parsing #if MEDIAINFO_TRACE if (Trace_Activated) Param("Data", Ztring("(")+Ztring::ToZtring(Element_TotalSize_Get())+Ztring(" bytes)")); #endif //MEDIAINFO_TRACE Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer FILLING_BEGIN(); Stream_Prepare(Stream_Audio); Fill(Stream_Audio, StreamPos_Last, Audio_Format, "MIDI"); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, "Midi"); Finish("MIDI"); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::PAL_() { Data_Accept("RIFF Palette"); Element_Name("RIFF Palette"); //Filling Fill(Stream_General, 0, General_Format, "RIFF Palette"); } //--------------------------------------------------------------------------- void File_Riff::QLCM() { Data_Accept("QLCM"); Element_Name("QLCM"); //Filling Fill(Stream_General, 0, General_Format, "QLCM"); } //--------------------------------------------------------------------------- void File_Riff::QLCM_fmt_() { //Parsing Ztring codec_name; int128u codec_guid; int32u num_rates; int16u codec_version, average_bps, packet_size, block_size, sampling_rate, sample_size; int8u major, minor; Get_L1 (major, "major"); Get_L1 (minor, "minor"); Get_GUID(codec_guid, "codec-guid"); Get_L2 (codec_version, "codec-version"); Get_Local(80, codec_name, "codec-name"); Get_L2 (average_bps, "average-bps"); Get_L2 (packet_size, "packet-size"); Get_L2 (block_size, "block-size"); Get_L2 (sampling_rate, "sampling-rate"); Get_L2 (sample_size, "sample-size"); Element_Begin1("rate-map-table"); Get_L4 (num_rates, "num-rates"); for (int32u rate=0; rate<num_rates; rate++) { Skip_L2( "rate-size"); Skip_L2( "rate-octet"); } Element_End0(); Skip_L4( "Reserved"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); if (Element_Offset<Element_Size) Skip_L4( "Reserved"); //Some files don't have the 5th reserved dword FILLING_BEGIN_PRECISE(); Stream_Prepare (Stream_Audio); switch (codec_guid.hi) { case Elements::QLCM_QCELP1 : case Elements::QLCM_QCELP2 : Fill(Stream_Audio, 0, Audio_Format, "QCELP"); Fill(Stream_Audio, 0, Audio_Codec, "QCELP"); break; case Elements::QLCM_EVRC : Fill(Stream_Audio, 0, Audio_Format, "EVRC"); Fill(Stream_Audio, 0, Audio_Codec, "EVRC"); break; case Elements::QLCM_SMV : Fill(Stream_Audio, 0, Audio_Format, "SMV"); Fill(Stream_Audio, 0, Audio_Codec, "SMV"); break; default : ; } Fill(Stream_Audio, 0, Audio_BitRate, average_bps); Fill(Stream_Audio, 0, Audio_SamplingRate, sampling_rate); Fill(Stream_Audio, 0, Audio_BitDepth, sample_size); Fill(Stream_Audio, 0, Audio_Channel_s_, 1); FILLING_END(); } #if defined(MEDIAINFO_GXF_YES) //--------------------------------------------------------------------------- void File_Riff::rcrd() { Data_Accept("Ancillary media packets"); Element_Name("Ancillary media packets"); //Filling if (Retrieve(Stream_General, 0, General_Format).empty()) Fill(Stream_General, 0, General_Format, "Ancillary media packets"); //GXF, RDD14-2007 //Clearing old data if (Ancillary) { (*Ancillary)->FrameInfo.DTS=FrameInfo.DTS; Open_Buffer_Continue(*Ancillary, Buffer, 0); } } //--------------------------------------------------------------------------- void File_Riff::rcrd_desc() { Element_Name("Ancillary media packet description"); //Parsing int32u Version; Get_L4 (Version, "Version"); if (Version==2) { Skip_L4( "Number of fields"); Skip_L4( "Length of the ancillary data field descriptions"); Skip_L4( "Byte size of the complete ancillary media packet"); Skip_L4( "Format of the video"); } else Skip_XX(Element_Size-Element_Offset, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld_() { Element_Name("Ancillary data field description"); } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld__anc_() { Element_Name("Ancillary data sample description"); rcrd_fld__anc__pos__LineNumber=(int32u)-1; } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld__anc__pos_() { Element_Name("Ancillary data sample description"); //Parsing Get_L4 (rcrd_fld__anc__pos__LineNumber, "Video line number"); Skip_L4( "Ancillary video color difference or luma space"); Skip_L4( "Ancillary video space"); } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld__anc__pyld() { Element_Name("Ancillary data sample payload"); if (Ancillary) { (*Ancillary)->FrameInfo.DTS=FrameInfo.DTS; (*Ancillary)->LineNumber=rcrd_fld__anc__pos__LineNumber; Open_Buffer_Continue(*Ancillary); } } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld__finf() { Element_Name("Data field description"); //Parsing Skip_L4( "Video field identifier"); } #endif //MEDIAINFO_GXF_YES //--------------------------------------------------------------------------- void File_Riff::RDIB() { Data_Accept("RIFF DIB"); Element_Name("RIFF DIB"); //Filling Fill(Stream_General, 0, General_Format, "RIFF DIB"); } //--------------------------------------------------------------------------- void File_Riff::RMID() { Data_Accept("RIFF MIDI"); Element_Name("RIFF MIDI"); //Filling Fill(Stream_General, 0, General_Format, "RIFF MIDI"); } //--------------------------------------------------------------------------- void File_Riff::RMMP() { Data_Accept("RIFF MMP"); Element_Name("RIFF MMP"); //Filling Fill(Stream_General, 0, General_Format, "RIFF MMP"); } //--------------------------------------------------------------------------- void File_Riff::RMP3() { Data_Accept("RMP3"); Element_Name("RMP3"); //Filling Fill(Stream_General, 0, General_Format, "RMP3"); Kind=Kind_Rmp3; } //--------------------------------------------------------------------------- void File_Riff::RMP3_data() { Element_Name("Raw datas"); Fill(Stream_Audio, 0, Audio_StreamSize, Buffer_DataToParse_End-Buffer_DataToParse_Begin); Stream_Prepare(Stream_Audio); //Creating parser #if defined(MEDIAINFO_MPEGA_YES) File_Mpega* Parser=new File_Mpega; Parser->CalculateDelay=true; Parser->ShouldContinueParsing=true; Open_Buffer_Init(Parser); stream& StreamItem=Stream[(int32u)-1]; StreamItem.StreamKind=Stream_Audio; StreamItem.StreamPos=0; StreamItem.Parsers.push_back(Parser); #else //MEDIAINFO_MPEG4_YES Fill(Stream_Audio, 0, Audio_Format, "MPEG Audio"); Skip_XX(Buffer_DataToParse_End-Buffer_DataToParse_Begin, "Data"); #endif } //--------------------------------------------------------------------------- void File_Riff::RMP3_data_Continue() { #if MEDIAINFO_DEMUX if (Element_Size) { Demux_random_access=true; Demux(Buffer+Buffer_Offset, (size_t)Element_Size, ContentType_MainStream); } #endif //MEDIAINFO_DEMUX Element_Code=(int64u)-1; AVI__movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::SMV0() { Accept("SMV"); //Parsing int8u Version; Skip_C1( "Identifier (continuing)"); Get_C1 (Version, "Version"); Skip_C3( "Identifier (continuing)"); if (Version=='1') { int32u Width, Height, FrameRate, BlockSize, FrameCount; Get_B3 (Width, "Width"); Get_B3 (Height, "Height"); Skip_B3( "0x000010"); Skip_B3( "0x000001"); Get_B3 (BlockSize, "Block size"); Get_B3 (FrameRate, "Frame rate"); Get_B3 (FrameCount, "Frame count"); Skip_B3( "0x000000"); Skip_B3( "0x000000"); Skip_B3( "0x000000"); Skip_B3( "0x010101"); Skip_B3( "0x010101"); Skip_B3( "0x010101"); Skip_B3( "0x010101"); //Filling Fill(Stream_General, 0, General_Format_Profile, "SMV v1"); Stream_Prepare(Stream_Video); Fill(Stream_Video, 0, Video_MuxingMode, "SMV v1"); Fill(Stream_Video, 0, Video_Width, Width); Fill(Stream_Video, 0, Video_Height, Height); Fill(Stream_Video, 0, Video_FrameRate, (float)FrameRate); Fill(Stream_Video, 0, Video_FrameCount, FrameCount); Finish("SMV"); } else if (Version=='2') { int32u Width, Height, FrameRate; Get_L3 (Width, "Width"); Get_L3 (Height, "Height"); Skip_L3( "0x000010"); Skip_L3( "0x000001"); Get_L3 (SMV_BlockSize, "Block size"); Get_L3 (FrameRate, "Frame rate"); Get_L3 (SMV_FrameCount, "Frame count"); Skip_L3( "0x000001"); Skip_L3( "0x000000"); Skip_L3( "Frame rate"); Skip_L3( "0x010101"); Skip_L3( "0x010101"); Skip_L3( "0x010101"); Skip_L3( "0x010101"); //Filling SMV_BlockSize+=3; SMV_FrameCount++; Fill(Stream_General, 0, General_Format_Profile, "SMV v2"); Stream_Prepare(Stream_Video); Fill(Stream_Video, 0, Video_Format, "JPEG"); Fill(Stream_Video, 0, Video_Codec, "JPEG"); Fill(Stream_Video, 0, Video_MuxingMode, "SMV v2"); Fill(Stream_Video, 0, Video_Width, Width); Fill(Stream_Video, 0, Video_Height, Height); Fill(Stream_Video, 0, Video_FrameRate, FrameRate); Fill(Stream_Video, 0, Video_FrameCount, SMV_FrameCount); Fill(Stream_Video, 0, Video_StreamSize, SMV_BlockSize*SMV_FrameCount); } else Finish("SMV"); } //--------------------------------------------------------------------------- void File_Riff::SMV0_xxxx() { //Parsing int32u Size; Get_L3 (Size, "Size"); #if defined(MEDIAINFO_JPEG_YES) //Creating the parser File_Jpeg MI; Open_Buffer_Init(&MI); //Parsing Open_Buffer_Continue(&MI, Size); //Filling Finish(&MI); Merge(MI, Stream_Video, 0, StreamPos_Last); //Positioning Element_Offset+=Size; #else //Parsing Skip_XX(Size, "JPEG data"); #endif Skip_XX(Element_Size-Element_Offset, "Padding"); //Filling #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong()) Element_Offset=Element_Size+(SMV_FrameCount-1)*SMV_BlockSize; #endif //MEDIAINFO_HASH Data_GoTo(File_Offset+Buffer_Offset+(size_t)Element_Size+(SMV_FrameCount-1)*SMV_BlockSize, "SMV"); SMV_BlockSize=0; } //--------------------------------------------------------------------------- void File_Riff::WAVE() { Data_Accept("Wave"); Element_Name("Wave"); //Filling Fill(Stream_General, 0, General_Format, "Wave"); Kind=Kind_Wave; #if MEDIAINFO_EVENTS StreamIDs_Width[0]=0; #endif //MEDIAINFO_EVENTS } //--------------------------------------------------------------------------- void File_Riff::WAVE__pmx() { Element_Name("XMP"); //Parsing Ztring XML_Data; Get_Local(Element_Size, XML_Data, "XML data"); } //--------------------------------------------------------------------------- void File_Riff::WAVE_aXML() { Element_Name("aXML"); //Parsing Skip_Local(Element_Size, "XML data"); } //--------------------------------------------------------------------------- void File_Riff::WAVE_bext() { Element_Name("Broadcast extension"); //Parsing Ztring Description, Originator, OriginatorReference, OriginationDate, OriginationTime, History; int16u Version; Get_Local(256, Description, "Description"); Get_Local( 32, Originator, "Originator"); Get_Local( 32, OriginatorReference, "OriginatorReference"); Get_Local( 10, OriginationDate, "OriginationDate"); Get_Local( 8, OriginationTime, "OriginationTime"); Get_L8 ( TimeReference, "TimeReference"); //To be divided by SamplesPerSec Get_L2 ( Version, "Version"); if (Version==1) Skip_UUID( "UMID"); Skip_XX (602-Element_Offset, "Reserved"); if (Element_Offset<Element_Size) Get_Local(Element_Size-Element_Offset, History, "History"); FILLING_BEGIN(); Fill(Stream_General, 0, General_Description, Description); Fill(Stream_General, 0, General_Producer, Originator); Fill(Stream_General, 0, "Producer_Reference", OriginatorReference); Fill(Stream_General, 0, General_Encoded_Date, OriginationDate+__T(' ')+OriginationTime); Fill(Stream_General, 0, General_Encoded_Library_Settings, History); if (SamplesPerSec && TimeReference!=(int64u)-1) { Fill(Stream_Audio, 0, Audio_Delay, float64_int64s(((float64)TimeReference)*1000/SamplesPerSec)); Fill(Stream_Audio, 0, Audio_Delay_Source, "Container (bext)"); } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_cue_() { Element_Name("Cue points"); //Parsing int32u numCuePoints; Get_L4(numCuePoints, "numCuePoints"); for (int32u Pos=0; Pos<numCuePoints; Pos++) { Element_Begin1("Cue point"); Skip_L4( "ID"); Skip_L4( "Position"); Skip_C4( "DataChunkID"); Skip_L4( "ChunkStart"); Skip_L4( "BlockStart"); Skip_L4( "SampleOffset"); Element_End0(); } } //--------------------------------------------------------------------------- void File_Riff::WAVE_data() { Element_Name("Raw datas"); if (Buffer_DataToParse_End-Buffer_DataToParse_Begin<100) { Skip_XX(Buffer_DataToParse_End-Buffer_Offset, "Unknown"); return; //This is maybe embeded in another container, and there is only the header (What is the junk?) } FILLING_BEGIN(); Fill(Stream_Audio, 0, Audio_StreamSize, Buffer_DataToParse_End-Buffer_DataToParse_Begin); FILLING_END(); //Parsing Element_Code=(int64u)-1; FILLING_BEGIN(); int64u Duration=Retrieve(Stream_Audio, 0, Audio_Duration).To_int64u(); int64u BitRate=Retrieve(Stream_Audio, 0, Audio_BitRate).To_int64u(); if (Duration) { int64u BitRate_New=(Buffer_DataToParse_End-Buffer_DataToParse_Begin)*8*1000/Duration; if (BitRate_New<BitRate*0.95 || BitRate_New>BitRate*1.05) Fill(Stream_Audio, 0, Audio_BitRate, BitRate_New, 10, true); //Correcting the bitrate, it was false in the header } else if (BitRate) { if (IsSub) //Retrieving "data" real size, in case of truncated files and/or wave header in another container Duration=((int64u)LittleEndian2int32u(Buffer+Buffer_Offset-4))*8*1000/BitRate; //TODO: RF64 is not handled else Duration=(Buffer_DataToParse_End-Buffer_DataToParse_Begin)*8*1000/BitRate; Fill(Stream_General, 0, General_Duration, Duration, 10, true); Fill(Stream_Audio, 0, Audio_Duration, Duration, 10, true); } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_data_Continue() { #if MEDIAINFO_DEMUX Element_Code=(int64u)-1; if (AvgBytesPerSec && Demux_Rate) { FrameInfo.DTS=float64_int64s((File_Offset+Buffer_Offset-Buffer_DataToParse_Begin)*1000000000.0/AvgBytesPerSec); FrameInfo.PTS=FrameInfo.DTS; Frame_Count_NotParsedIncluded=float64_int64s(((float64)FrameInfo.DTS)/1000000000.0*Demux_Rate); } Demux_random_access=true; Demux(Buffer+Buffer_Offset, (size_t)Element_Size, ContentType_MainStream); Frame_Count_NotParsedIncluded=(int64u)-1; #endif //MEDIAINFO_DEMUX Element_Code=(int64u)-1; AVI__movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_ds64() { Element_Name("DataSize64"); //Parsing int32u tableLength; Skip_L8( "riffSize"); //Is directly read from the header parser Get_L8 (WAVE_data_Size, "dataSize"); Get_L8 (WAVE_fact_samplesCount, "sampleCount"); Get_L4 (tableLength, "tableLength"); for (int32u Pos=0; Pos<tableLength; Pos++) Skip_L8( "table[]"); } //--------------------------------------------------------------------------- void File_Riff::WAVE_fact() { Element_Name("Sample count"); //Parsing int64u SamplesCount64; int32u SamplesCount; Get_L4 (SamplesCount, "SamplesCount"); SamplesCount64=SamplesCount; if (SamplesCount64==0xFFFFFFFF) SamplesCount64=WAVE_fact_samplesCount; FILLING_BEGIN(); int32u SamplingRate=Retrieve(Stream_Audio, 0, Audio_SamplingRate).To_int32u(); if (SamplingRate) { //Calculating int64u Duration=(SamplesCount64*1000)/SamplingRate; //Coherency test bool IsOK=true; if (File_Size!=(int64u)-1) { int64u BitRate=Retrieve(Stream_Audio, 0, Audio_BitRate).To_int64u(); if (BitRate) { int64u Duration_FromBitRate = File_Size * 8 * 1000 / BitRate; if (Duration_FromBitRate > Duration*1.10 || Duration_FromBitRate < Duration*0.9) IsOK = false; } } //Filling if (IsOK) Fill(Stream_Audio, 0, Audio_Duration, Duration); } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_fmt_() { //Compute the current codec ID Element_Code=(int64u)-1; Stream_ID=(int32u)-1; stream_Count=1; Stream[(int32u)-1].fccType=Elements::AVI__hdlr_strl_strh_auds; AVI__hdlr_strl_strf(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_ID3_() { Element_Name("ID3v2 tags"); //Parsing #if defined(MEDIAINFO_ID3V2_YES) File_Id3v2 MI; Open_Buffer_Init(&MI); Open_Buffer_Continue(&MI); Finish(&MI); Merge(MI, Stream_General, 0, 0); #endif } //--------------------------------------------------------------------------- void File_Riff::WAVE_iXML() { Element_Name("iXML"); //Parsing Skip_Local(Element_Size, "XML data"); } //--------------------------------------------------------------------------- void File_Riff::wave() { Data_Accept("Wave64"); Element_Name("Wave64"); //Filling Fill(Stream_General, 0, General_Format, "Wave64"); } //--------------------------------------------------------------------------- void File_Riff::W3DI() { Element_Name("IDVX tags (Out of specs!)"); //Parsing int32u Size=(int32u)Element_Size; Ztring Title, Artist, Album, Unknown, Genre, Comment; int32u TrackPos; Get_Local(Size, Title, "Title"); Element_Offset=(int32u)Title.size(); Size-=(int32u)Title.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Artist, "Artist"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size(); Size-=(int32u)Artist.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Album, "Album"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size()+1+(int32u)Album.size(); Size-=(int32u)Album.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Unknown, "Unknown"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size()+1+(int32u)Album.size()+1+(int32u)Unknown.size(); Size-=(int32u)Unknown.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Genre, "Genre"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size()+1+(int32u)Album.size()+1+(int32u)Unknown.size()+1+(int32u)Genre.size(); Size-=(int32u)Genre.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Comment, "Comment"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size()+1+(int32u)Album.size()+1+(int32u)Unknown.size()+1+(int32u)Genre.size()+1+(int32u)Comment.size(); Size-=(int32u)Comment.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_L4 (TrackPos, "Track_Position"); if(Element_Offset+8<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); Element_Begin1("Footer"); Skip_L4( "Size"); Skip_C4( "Name"); Element_End0(); //Filling Fill(Stream_General, 0, General_Track, Title); Fill(Stream_General, 0, General_Performer, Artist); Fill(Stream_General, 0, General_Album, Album); Fill(Stream_General, 0, "Unknown", Unknown); Fill(Stream_General, 0, General_Genre, Genre); Fill(Stream_General, 0, General_Comment, Comment); Fill(Stream_General, 0, General_Track_Position, TrackPos); } void File_Riff::Open_Buffer_Init_All() { stream& StreamItem = Stream[Stream_ID]; for (size_t Pos = 0; Pos<StreamItem.Parsers.size(); Pos++) Open_Buffer_Init(StreamItem.Parsers[Pos]); } //*************************************************************************** // C++ //*************************************************************************** } //NameSpace #endif //MEDIAINFO_RIFF_YES
pavel-pimenov/sandbox
mediainfo/MediaInfoLib/Source/MediaInfo/Multiple/File_Riff_Elements.cpp
C++
mit
147,762
37.489711
228
0.499228
false
/////////////////////////////////////////////////////////////////////////////// // // (C) Autodesk, Inc. 2007-2011. All rights reserved. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // /////////////////////////////////////////////////////////////////////////////// #ifndef ATILDEFS_H #include "AtilDefs.h" #endif #ifndef FORMATCODECPROPERTYINTERFACE_H #include "FormatCodecPropertyInterface.h" #endif #ifndef FORMATCODECINCLUSIVEPROPERTYSETINTERFACE_H #define FORMATCODECINCLUSIVEPROPERTYSETINTERFACE_H #if __GNUC__ >= 4 #pragma GCC visibility push(default) #endif namespace Atil { /// <summary> /// This class groups properties into a set of properties much /// like a "structure" in "c". /// </summary> /// class FormatCodecInclusivePropertySetInterface : public FormatCodecPropertyInterface { public: /// <summary> /// The virtual destructor. /// </summary> /// virtual ~FormatCodecInclusivePropertySetInterface (); /// <summary> /// This returns the number of properties in the set. /// </summary> /// /// <returns> /// The number of properties in the set. /// </returns> /// virtual int getNumProperties () const; /// <summary> /// This returns a selected property from the properties in the set. /// </summary> /// /// <param name="nIndex"> /// The index of the property to that is returned. /// </param> /// /// <returns> /// A pointer to the property at the index. This pointer should not be freed by the caller. /// </returns> /// virtual FormatCodecPropertyInterface* getProperty (int nIndex) const; protected: /// <summary> /// (Protected) Copy constructor. /// </summary> /// /// <param name="iter"> /// The instance to be copied. /// </param> /// FormatCodecInclusivePropertySetInterface (const FormatCodecInclusivePropertySetInterface& iter); /// <summary> /// (Protected) The simple constructor. /// </summary> /// FormatCodecInclusivePropertySetInterface (); /// <summary> /// (Protected) The pre-allocating constructor. /// </summary> /// /// <param name="nNumToAlloc"> /// The number of properties that will be in the set. /// </param> /// FormatCodecInclusivePropertySetInterface (int nNumToAlloc); /// <summary> /// (Protected) This sets the property at index in the set. /// </summary> /// /// <param name="nIndex"> /// The index of the property that is to be set. /// </param> /// /// <param name="pProperty"> /// A pointer to the property that should be placed at the index. The /// property will be <c>clone()</c> copied. The pointer is not held by the set. /// </param> /// void setProperty (int nIndex, FormatCodecPropertyInterface* pProperty); /// <summary> /// (Protected) This adds the property to the set. /// </summary> /// /// <param name="pProperty"> /// A pointer to the property that should be placed at the index. The /// property will be <c>clone()</c> copied. The pointer is not held by the set. /// </param> /// void appendProperty (FormatCodecPropertyInterface* pProperty); /// <summary> /// (Protected) The array of property pointers held by the set. /// </summary> /// FormatCodecPropertyInterface** mppProperties; /// <summary> /// (Protected) The number of properties that have been set into the set. /// </summary> int mnNumProperties; /// <summary> /// (Protected) The length of the property array. /// </summary> int mnArraySize; private: FormatCodecInclusivePropertySetInterface& operator= (const FormatCodecInclusivePropertySetInterface& from); }; } // end of namespace Atil #if __GNUC__ >= 4 #pragma GCC visibility pop #endif #endif
kevinzhwl/ObjectARXCore
2013/utils/Atil/Inc/codec_properties/FormatCodecInclusivePropertySetInterface.h
C
mit
4,904
28.459627
115
0.613785
false
'use strict'; // Configuring the Articles module angular.module('about').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('mainmenu', 'About Us', 'about', 'left-margin', '/about-us', true, null, 3); } ]);
spiridonov-oa/people-ma
public/modules/about/config/about.client.config.js
JavaScript
mit
257
27.555556
102
0.607004
false
package cwr; import java.util.ArrayList; public class RobotBite { //0 = time [state] //1 = x [state] //2 = y [state] //3 = energy [state] //4 = bearing radians [relative position] //5 = distance [relative position] //6 = heading radians [travel] //7 = velocity [travel] String name; long cTime; double cx; double cy; cwruBase origin; double cEnergy; double cBearing_radians; double cDistance; double cHeading_radians; double cVelocity; ArrayList<Projection> projec; //forward projections for x public RobotBite(String name, long time, cwruBase self, double energy, double bearing_radians, double distance, double heading_radians, double velocity) { this.name = name; cTime = time; origin = self; cEnergy = energy; cBearing_radians = bearing_radians; double myBearing = self.getHeadingRadians(); //System.out.println("I'm going "+self.getHeadingRadians()); double adjust_bearing = (bearing_radians+myBearing)%(2*Math.PI); //System.out.println("input bearing "+(bearing_radians)); //System.out.println("adjust bearing "+(adjust_bearing)); //System.out.println("math bearing"+(-adjust_bearing+Math.PI/2)); cDistance = distance; cHeading_radians = heading_radians; //System.out.println("location heading "+heading_radians); cVelocity = velocity; double myX = self.getX(); double myY = self.getY(); double math_bearing = (-adjust_bearing+Math.PI/2)%(2*Math.PI); //double math_heading = (-heading_radians+Math.PI/2)%(2*Math.PI); /* * 0 * 90 * -90 180 0 90 * -90 * 180 */ double dX = distance*Math.cos(math_bearing); //System.out.println("location dx:" + dX); double dY = distance*Math.sin(math_bearing); //System.out.println("location dy:" + dY); cx = myX+dX; cy = myY+dY; } public void attachProjection(ArrayList<Projection> projList) { projec = projList; } }
buckbaskin/RoboCodeGit
old_src/cwr/RobotBite.java
Java
mit
1,934
27.028986
67
0.657704
false
export default function closest(n, arr) { let i let ndx let diff let best = Infinity let low = 0 let high = arr.length - 1 while (low <= high) { // eslint-disable-next-line no-bitwise i = low + ((high - low) >> 1) diff = arr[i] - n if (diff < 0) { low = i + 1 } else if (diff > 0) { high = i - 1 } diff = Math.abs(diff) if (diff < best) { best = diff ndx = i } if (arr[i] === n) break } return arr[ndx] }
octopitus/rn-sliding-up-panel
libs/closest.js
JavaScript
mit
493
14.903226
42
0.488844
false
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClearScript.Installer.Demo { public class Class1 { } }
eswann/ClearScript.Installer
src/ClearScript.Installer.Demo/Class1.cs
C#
mit
197
15.25
36
0.74359
false
/** * 斐波那契数列 */ export default function fibonacci(n){ if(n <= 2){ return 1; } let n1 = 1, n2 = 1, sn = 0; for(let i = 0; i < n - 2; i ++){ sn = n1 + n2; n1 = n2; n2 = sn; } return sn; }
lomocc/react-boilerplate
src/utils/fibonacci.js
JavaScript
mit
230
13.533333
37
0.431193
false
import * as UTILS from '@utils'; const app = new WHS.App([ ...UTILS.appModules({ position: new THREE.Vector3(0, 40, 70) }) ]); const halfMat = { transparent: true, opacity: 0.5 }; const box = new WHS.Box({ geometry: { width: 30, height: 2, depth: 2 }, modules: [ new PHYSICS.BoxModule({ mass: 0 }) ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.mesh, ...halfMat }), position: { y: 40 } }); const box2 = new WHS.Box({ geometry: { width: 30, height: 1, depth: 20 }, modules: [ new PHYSICS.BoxModule({ mass: 10, damping: 0.1 }) ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.softbody, ...halfMat }), position: { y: 38, z: 12 } }); const pointer = new WHS.Sphere({ modules: [ new PHYSICS.SphereModule() ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.mesh }) }); console.log(pointer); pointer.position.set(0, 60, -8); pointer.addTo(app); box.addTo(app); box2.addTo(app).then(() => { const constraint = new PHYSICS.DOFConstraint(box2, box, new THREE.Vector3(0, 38, 1) ); app.addConstraint(constraint); constraint.enableAngularMotor(10, 20); }); UTILS.addPlane(app, 250); UTILS.addBasicLights(app); app.start();
WhitestormJS/whs.js
examples/physics/Constraints/DofConstraint/script.js
JavaScript
mit
1,332
13.8
57
0.592342
false
package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.CantRegisterDebitException; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletTransactionRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction; import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.ErrorManager; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletDatabaseConstants; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockBitcoinWalletTransactionRecord; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockDatabaseTableRecord; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; /** * Created by jorgegonzalez on 2015.07.14.. */ @RunWith(MockitoJUnitRunner.class) public class DebitTest { @Mock private ErrorManager mockErrorManager; @Mock private PluginDatabaseSystem mockPluginDatabaseSystem; @Mock private Database mockDatabase; @Mock private DatabaseTable mockWalletTable; @Mock private DatabaseTable mockBalanceTable; @Mock private DatabaseTransaction mockTransaction; private List<DatabaseTableRecord> mockRecords; private DatabaseTableRecord mockBalanceRecord; private DatabaseTableRecord mockWalletRecord; private BitcoinWalletTransactionRecord mockTransactionRecord; private BitcoinWalletBasicWalletAvailableBalance testBalance; @Before public void setUpMocks(){ mockTransactionRecord = new MockBitcoinWalletTransactionRecord(); mockBalanceRecord = new MockDatabaseTableRecord(); mockWalletRecord = new MockDatabaseTableRecord(); mockRecords = new ArrayList<>(); mockRecords.add(mockBalanceRecord); setUpMockitoRules(); } public void setUpMockitoRules(){ when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_TABLE_NAME)).thenReturn(mockWalletTable); when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME)).thenReturn(mockBalanceTable); when(mockBalanceTable.getRecords()).thenReturn(mockRecords); when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord); when(mockDatabase.newTransaction()).thenReturn(mockTransaction); } @Before public void setUpAvailableBalance(){ testBalance = new BitcoinWalletBasicWalletAvailableBalance(mockDatabase); } @Test public void Debit_SuccesfullyInvoked_ReturnsAvailableBalance() throws Exception{ catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()).isNull(); } @Test public void Debit_OpenDatabaseCantOpenDatabase_ReturnsAvailableBalance() throws Exception{ doThrow(new CantOpenDatabaseException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterDebitException.class); } @Test public void Debit_OpenDatabaseDatabaseNotFound_Throws() throws Exception{ doThrow(new DatabaseNotFoundException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterDebitException.class); } @Test public void Debit_DaoCantCalculateBalanceException_ReturnsAvailableBalance() throws Exception{ doThrow(new CantLoadTableToMemoryException("MOCK", null, null, null)).when(mockWalletTable).loadToMemory(); catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterDebitException.class); } }
fvasquezjatar/fermat-unused
DMP/plugin/basic_wallet/fermat-dmp-plugin-basic-wallet-bitcoin-wallet-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/basic_wallet/bitcoin_wallet/developer/bitdubai/version_1/structure/BitcoinWalletBasicWalletAvailableBalance/DebitTest.java
Java
mit
5,573
42.88189
158
0.784138
false
// ****************************************************************** // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // // ****************************************************************** using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Windows.Foundation; namespace Microsoft.Toolkit.Uwp.Services.OAuth { /// <summary> /// OAuth Uri extensions. /// </summary> internal static class OAuthUriExtensions { /// <summary> /// Get query parameters from Uri. /// </summary> /// <param name="uri">Uri to process.</param> /// <returns>Dictionary of query parameters.</returns> public static IDictionary<string, string> GetQueryParams(this Uri uri) { return new WwwFormUrlDecoder(uri.Query).ToDictionary(decoderEntry => decoderEntry.Name, decoderEntry => decoderEntry.Value); } /// <summary> /// Get absolute Uri. /// </summary> /// <param name="uri">Uri to process.</param> /// <returns>Uri without query string.</returns> public static string AbsoluteWithoutQuery(this Uri uri) { if (string.IsNullOrEmpty(uri.Query)) { return uri.AbsoluteUri; } return uri.AbsoluteUri.Replace(uri.Query, string.Empty); } /// <summary> /// Normalize the Uri into string. /// </summary> /// <param name="uri">Uri to process.</param> /// <returns>Normalized string.</returns> public static string Normalize(this Uri uri) { var result = new StringBuilder(string.Format(CultureInfo.InvariantCulture, "{0}://{1}", uri.Scheme, uri.Host)); if (!((uri.Scheme == "http" && uri.Port == 80) || (uri.Scheme == "https" && uri.Port == 443))) { result.Append(string.Concat(":", uri.Port)); } result.Append(uri.AbsolutePath); return result.ToString(); } } }
phmatray/UWPCommunityToolkit
Microsoft.Toolkit.Uwp.Services/OAuth/OAuthUriExtensions.cs
C#
mit
2,612
35.704225
136
0.579432
false
<html><body> <h4>Windows 10 x64 (18363.900)</h4><br> <h2>_OPENCOUNT_REASON</h2> <font face="arial"> OpenCount_SkipLogging = 0n0<br> OpenCount_AsyncRead = 0n1<br> OpenCount_FlushCache = 0n2<br> OpenCount_GetDirtyPage = 0n3<br> OpenCount_GetFlushedVDL = 0n4<br> OpenCount_InitCachemap1 = 0n5<br> OpenCount_InitCachemap2 = 0n6<br> OpenCount_InitCachemap3 = 0n7<br> OpenCount_InitCachemap4 = 0n8<br> OpenCount_InitCachemap5 = 0n9<br> OpenCount_MdlWrite = 0n10<br> OpenCount_MdlWriteAbort = 0n11<br> OpenCount_NotifyMappedWrite = 0n12<br> OpenCount_NotifyMappedWriteCompCallback = 0n13<br> OpenCount_PurgeCache = 0n14<br> OpenCount_PurgeCacheActiveViews = 0n15<br> OpenCount_ReadAhead = 0n16<br> OpenCount_SetFileSize = 0n17<br> OpenCount_SetFileSizeSection = 0n18<br> OpenCount_UninitCachemapReadAhead = 0n19<br> OpenCount_UninitCachemapReg = 0n20<br> OpenCount_UnmapInactiveViews = 0n21<br> OpenCount_UnmapInactiveViews1 = 0n22<br> OpenCount_UnmapInactiveViews2 = 0n23<br> OpenCount_UnmapInactiveViews3 = 0n24<br> OpenCount_WriteBehind = 0n25<br> OpenCount_WriteBehindComplete = 0n26<br> OpenCount_WriteBehindFailAcquire = 0n27<br> </font></body></html>
epikcraw/ggool
public/Windows 10 x64 (18363.900)/_OPENCOUNT_REASON.html
HTML
mit
1,264
37.5625
53
0.720728
false
#ifndef BITMAP_H #define BITMAP_H #include <allegro5/allegro.h> #include <memory> #include "renderlist.h" // This class does double duty as a renderable, and a wrapper for allegro bitmap. class Bitmap; using BitmapPtr = std::shared_ptr<Bitmap>; class Bitmap : public Renderable { ALLEGRO_BITMAP* bitmap; float x, y; float scale; public: Bitmap() : bitmap(nullptr), x(0), y(0), scale(1.0f) {} Bitmap( ALLEGRO_BITMAP* _bitmap, int _x = 0 , int _y = 0 ) : bitmap(_bitmap), x(_x), y(_y), scale(1.0f) {} ~Bitmap(); void render(); void create( int w, int h, int flags = 0 ); bool loadFromFile( const std::string& filename, int flags = 0 ); bool saveToFile( const std::string& filename ); BitmapPtr getSubBitmap( int _x, int _y, int _w, int _h ); void setBitmap( ALLEGRO_BITMAP* nb ); void setBitmap( BitmapPtr& nb ); void blit( const BitmapPtr& other, float x, float y, float scale ); float getX() { return x; } float getY() { return y; } float getScale() { return scale; } void setX( int _x ) { x = _x; } void setY( int _y ) { y = _y; } int getWidth() { return al_get_bitmap_width( bitmap ); } int getHeight() { return al_get_bitmap_height( bitmap ); } void setScale( float _scale ) { scale = _scale; } }; #endif // BITMAP_H
merlinblack/oyunum
src/bitmap.h
C
mit
1,343
24.826923
107
0.60834
false
# BullDawgBeds
Rayjk123/BullDawgBeds
README.md
Markdown
mit
14
14
14
0.857143
false
/* gopm (Go Package Manager) Copyright (c) 2012 cailei (dancercl@gmail.com) The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package main import ( "fmt" "github.com/cailei/gopm_index/gopm/index" "github.com/hailiang/gosocks" "io" "io/ioutil" "log" "net/http" "net/url" "os" ) type Agent struct { client *http.Client } func newAgent() *Agent { client := http.DefaultClient // check if using a proxy proxy_addr := os.Getenv("GOPM_PROXY") if proxy_addr != "" { fmt.Printf("NOTE: Using socks5 proxy: %v\n", proxy_addr) proxy := socks.DialSocksProxy(socks.SOCKS5, proxy_addr) transport := &http.Transport{Dial: proxy} client = &http.Client{Transport: transport} } return &Agent{client} } func (agent *Agent) getFullIndexReader() io.Reader { request := remote_db_host + "/all" return agent._get_body_reader(request) } func (agent *Agent) uploadPackage(meta index.PackageMeta) { request := fmt.Sprintf("%v/publish", remote_db_host) // marshal PackageMeta to json json, err := meta.ToJson() if err != nil { log.Fatalln(err) } // create a POST request response, err := http.PostForm(request, url.Values{"pkg": {string(json)}}) if err != nil { log.Fatalln(err) } body, err := ioutil.ReadAll(response.Body) defer response.Body.Close() if err != nil { log.Fatalln(err) } if len(body) > 0 { fmt.Println(string(body)) } // check response if response.StatusCode != 200 { log.Fatalln(response.Status) } } func (agent *Agent) _get_body_reader(request string) io.ReadCloser { // GET the index content response, err := agent.client.Get(request) if err != nil { log.Fatalln(err) } // check response if response.StatusCode != 200 { body, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatalln(err) } if len(body) > 0 { fmt.Println(string(body)) } log.Fatalln(response.Status) } return response.Body }
cailei/gopm
gopm/agent.go
GO
mit
3,137
25.811966
79
0.661141
false
package org.usfirst.frc.team6135.robot.subsystems; import java.awt.geom.Arc2D.Double; import org.usfirst.frc.team6135.robot.RobotMap; import org.usfirst.frc.team6135.robot.commands.teleopDrive; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SerialPort; import edu.wpi.first.wpilibj.VictorSP; import edu.wpi.first.wpilibj.command.Subsystem; public class Drive extends Subsystem { //Constants private static final boolean rReverse = true; private static final boolean lReverse = false; private static final double kA=0.03; //Objects private VictorSP leftDrive = null; private VictorSP rightDrive = null; public ADXRS450_Gyro gyro=null; public AHRS ahrs=null; public RobotDrive robotDrive=null; //Constructors public Drive() { gyro=RobotMap.gyro; ahrs=new AHRS(SerialPort.Port.kUSB1); robotDrive=new RobotDrive(RobotMap.leftDriveVictor,RobotMap.rightDriveVictor); leftDrive = RobotMap.leftDriveVictor; rightDrive = RobotMap.rightDriveVictor; leftDrive.set(0); rightDrive.set(0); leftDrive.setInverted(lReverse); rightDrive.setInverted(rReverse); ahrs.reset(); } //Direct object access methods public void setMotors(double l, double r) {//sets motor speeds accounting for directions of motors leftDrive.set(l); rightDrive.set(r); } public void setLeft(double d) { leftDrive.set(d); } public void setRight(double d) { rightDrive.set(d); } //Teleop Driving methods private static final double accBoundX = 0.7; //The speed after which the drive starts to accelerate over time private static final int accLoopX = 15; //The number of loops for the bot to accelerate to max speed private int accLoopCountX = 0; public double accCalcX(double input) {//applies a delay for motors to reach full speed for larger joystick inputs if(input > accBoundX && accLoopCountX < accLoopX) {//positive inputs return accBoundX + (input - accBoundX) * (accLoopCountX++ / (double) accLoopX); } else if(input < -accBoundX && accLoopCountX < accLoopX) {//negative inputs return -accBoundX + (input + accBoundX) * (accLoopCountX++ / (double) accLoopX); } else if(Math.abs(input) <= accBoundX) { accLoopCountX = 0; } return input; } private static final double accBoundY = 0.7; //The speed after which the drive starts to accelerate over time private static final int accLoopY = 15; //The number of loops for the bot to accelerate to max speed private int accLoopCountY = 0; public double accCalcY(double input) {//applies a delay for motors to reach full speed for larger joystick inputs if(input > accBoundY && accLoopCountY < accLoopY) {//positive inputs return accBoundY + (input - accBoundY) * (accLoopCountY++ / (double) accLoopY); } else if(input < -accBoundY && accLoopCountY < accLoopY) {//negative inputs return -accBoundY + (input + accBoundY) * (accLoopCountY++ / (double) accLoopY); } else if(Math.abs(input) <= accBoundY) { accLoopCountY = 0; } return input; } private static final double accBoundZ = 0.7; //The speed after which the drive starts to accelerate over time private static final int accLoopZ = 15; //The number of loops for the bot to accelerate to max speed private int accLoopCountZ = 0; public double accCalcZ(double input) {//applies a delay for motors to reach full speed for larger joystick inputs if(input > accBoundZ && accLoopCountZ < accLoopZ) {//positive inputs return accBoundZ + (input - accBoundZ) * (accLoopCountZ++ / (double) accLoopZ); } else if(input < -accBoundZ && accLoopCountZ < accLoopZ) {//negative inputs return -accBoundZ + (input + accBoundZ) * (accLoopCountZ++ / (double) accLoopZ); } else if(Math.abs(input) <= accBoundZ) { accLoopCountZ = 0; } return input; } public double sensitivityCalc(double input) {//Squares magnitude of input to reduce magnitude of smaller joystick inputs if (input >= 0.0) { return (input * input); } else { return -(input * input); } } public void reverse() { leftDrive.setInverted(!leftDrive.getInverted()); rightDrive.setInverted(!rightDrive.getInverted()); VictorSP temp1 = leftDrive; VictorSP temp2 = rightDrive; rightDrive = temp1; leftDrive = temp2; } public double getGyroAngle() { return gyro.getAngle(); } public double getNAVXAngle() { return ahrs.getAngle(); } public void driveStraight() { robotDrive.drive(0.6, -gyro.getAngle()*kA); } @Override protected void initDefaultCommand() { setDefaultCommand(new teleopDrive()); } }
Arctos6135/frc-2017
src/org/usfirst/frc/team6135/robot/subsystems/Drive.java
Java
mit
4,676
33.382353
121
0.717494
false
module Shopping class LineItem < ActiveRecord::Base extend Shopping::AttributeAccessibleHelper belongs_to :cart belongs_to :source, polymorphic: true validate :unique_source_and_cart, on: :create validate :unpurchased_cart validates :quantity, allow_nil: true, numericality: {only_integer: true, greater_than: -1} validates :cart_id, presence: true validates :source_id, presence: true validates :source_type, presence: true attr_accessible :cart_id, :source, :source_id, :source_type, :quantity, :list_price, :sale_price, :options before_create :set_prices, :set_name def unique_source_and_cart other = Shopping::LineItem.where(source_id: self.source_id, source_type: self.source_type, cart_id: self.cart_id) if other.count > 0 self.errors.add(:source, "A line item with identical source and cart exists, update quantity instead (id=#{other.first.id})") end end def unpurchased_cart if cart && cart.purchased? changes.keys.each do |k| self.errors.add(k, "Cannot change `#{k}', cart is purchased") end end end def set_name self.source_name ||= source.try(:name) end def set_prices self.list_price ||= source.try(:price) self.sale_price ||= source.try(:price) end end end
barkbox/shopping
app/models/shopping/line_item.rb
Ruby
mit
1,352
31.190476
133
0.655325
false
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new Tuhn\HelloBundle\TuhnHelloBundle(), new Trungnd\StoreBundle\TrungndStoreBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
longran/project1
app/AppKernel.php
PHP
mit
1,458
38.405405
89
0.665295
false
#!/usr/bin/env python """ This script is used to run tests, create a coverage report and output the statistics at the end of the tox run. To run this script just execute ``tox`` """ import re from fabric.api import local, warn from fabric.colors import green, red if __name__ == '__main__': # Kept some files for backwards compatibility. If support is dropped, # remove it here deprecated_files = '*utils_email*,*utils_log*' local('flake8 --ignore=E126 --ignore=W391 --statistics' ' --exclude=submodules,migrations,build .') local('coverage run --source="django_libs" manage.py test -v 2' ' --traceback --failfast --settings=django_libs.tests.settings' ' --pattern="*_tests.py"') local('coverage html -d coverage' ' --omit="*__init__*,*/settings/*,*/migrations/*,*/tests/*,' '*admin*,{}"'.format(deprecated_files)) total_line = local('grep -n pc_cov coverage/index.html', capture=True) percentage = float(re.findall(r'(\d+)%', total_line)[-1]) if percentage < 100: warn(red('Coverage is {0}%'.format(percentage))) else: print(green('Coverage is {0}%'.format(percentage)))
bitmazk/django-libs
runtests.py
Python
mit
1,182
37.129032
74
0.635364
false
using System; namespace KeyWatcher.Reactive { internal sealed class ObservingKeyWatcher : IObserver<char> { private readonly string id; internal ObservingKeyWatcher(string id) => this.id = id; public void OnCompleted() => Console.Out.WriteLine($"{this.id} - {nameof(this.OnCompleted)}"); public void OnError(Exception error) => Console.Out.WriteLine($"{this.id} - {nameof(this.OnError)} - {error.Message}"); public void OnNext(char value) => Console.Out.WriteLine($"{this.id} - {nameof(this.OnNext)} - {value}"); } }
rockfordlhotka/DistributedComputingDemo
src/KeyWatcher - Core/KeyWatcher.Reactive/ObservingKeyWatcher.cs
C#
mit
552
24
82
0.687273
false
from baroque.entities.event import Event class EventCounter: """A counter of events.""" def __init__(self): self.events_count = 0 self.events_count_by_type = dict() def increment_counting(self, event): """Counts an event Args: event (:obj:`baroque.entities.event.Event`): the event to be counted """ assert isinstance(event, Event) self.events_count += 1 t = type(event.type) if t in self.events_count_by_type: self.events_count_by_type[t] += 1 else: self.events_count_by_type[t] = 1 def count_all(self): """Tells how many events have been counted globally Returns: int """ return self.events_count def count(self, eventtype): """Tells how many events have been counted of the specified type Args: eventtype (:obj:`baroque.entities.eventtype.EventType`): the type of events to be counted Returns: int """ return self.events_count_by_type.get(type(eventtype), 0)
baroquehq/baroque
baroque/datastructures/counters.py
Python
mit
1,120
23.347826
101
0.569643
false
/* Fontname: -Adobe-Times-Medium-R-Normal--11-80-100-100-P-54-ISO10646-1 Copyright: Copyright (c) 1984, 1987 Adobe Systems Incorporated. All Rights Reserved. Copyright (c) 1988, 1991 Digital Equipment Corporation. All Rights Reserved. Glyphs: 191/913 BBX Build Mode: 0 */ const uint8_t u8g2_font_timR08_tf[2170] U8G2_FONT_SECTION("u8g2_font_timR08_tf") = "\277\0\3\2\4\4\2\4\5\13\15\377\375\7\376\7\376\1H\2\277\10a \5\0\246\4!\7q\343" "\304\240\4\42\7#\66E\242\4#\16ubM)I\6\245\62(\245$\1$\14\224^U\64D\242" "i\310\22\0%\21w\42\316\60$Q\322\226$RRJ\332\22\0&\20x\42\226\232\244\312\264D\221" "\226)\311\242\0'\6!\266\204\0(\13\223\32U\22%Q-\312\2)\14\223\32E\26eQ%J" "\42\0*\7\63sE\322\1+\12U\242U\30\15R\30\1,\6\42\336\204\22-\6\23*\305\0." "\6\21\343D\0/\12s\342T%\252D\21\0\60\12tb\215\22yJ\24\0\61\10scM\42u" "\31\62\14tb\215\22eQ\26EC\0\63\14tb\215\22e\211\230\15\11\0\64\14ub]&%" "\245d\320\302\4\65\13tb\315\22\215Y\66$\0\66\13tb\225\22-\221)Q\0\67\12tb\305" " \325\242\254\4\70\14tb\215\22I\211\22I\211\2\71\13tb\215\22\231\222)\221\0:\6Q\343" "D\26;\7b\336L\254\4<\7ScUR+=\10\65\246\305\240\16\2>\10SbEV)\1" "?\13s\42\305\220DI\224&\0@\24\230Z\326\220\205I\264(Q\242D\211\222\230\332\221A\1A" "\15w\42^:&a\222\15R\226\34B\15u\242\305\20U\242d\252D\203\2C\14v\342\315\60d" "jUK\206\4D\20v\342\305 EJ\226dI\226D\303\220\0E\14u\242\305\240DI\70\205\321" "\60F\14u\242\305\240DI\70\205\331\4G\16v\342\315\60dj\64\204[\62$\0H\17w\42\306" "\262dQ\26\15R\26e\311\1I\10s\42\305\22u\31J\12t\42\315\224\265T$\0K\16v\342" "\305\242D\225LL\262(Y\4L\11u\242\305\26v\32\6M\21y\242\306\266hR\322\224\64%K" "\324\262$\3N\20w\42\306\262H\225RR\212\244H\231\22\0O\14v\342\315\220H\243qR\206\4" "P\14u\242\305\20U\242d\12\263\11Q\14\226\332\315\220H\243qRV\3R\15v\342\305\220EM" "[\222E\311\42S\13tb\315\20m\242\64$\0T\12u\242\305\245\24\266-\0U\17w\42\306\262" "dQ\26eQ\26)\332\4V\17w\42\306\262d\221\242%a\222\306\31\0W\22{\241\306r\311J" "R\244%K\230\264fq\226\1X\14w\42\306\262d\225\264\222U\16Y\14w\42\306\262d\225p\215" "\323\11Z\10u\242\305\255\267a[\10\222\332\304\322\27\1\134\11s\342D\224E\265(]\10\222\332\204" "\322\227\1^\7\63sME\11_\6\25V\305 `\6\42\372D\24a\10S\42\205\226\34\2b\14" "ua\205\30N\225(\211\222\5c\7S\42\315T\23d\15ub\225\30-Q\22%Q\244\4e\7" "S\42\315%\23f\12t\42\225\22MYi\1g\14tZ\315\220\64eJ\64$\0h\13va\205" "\232nQO\212\0i\7r\342L\244tj\11\223\331T(uZ\0k\13va\205Z\252d[T" "\22l\10s\42\205\324\313\0m\14X\42\306\42\265D\225\250\342\0n\12Ub\305T\211\222(\61o" "\11Tb\215\22\231\22\5p\16\205U\305\20U\242$J\246\60\233\0q\14\205V\315\22%Q\22E" "cmr\11S\42E\222(Q\62s\10S\42\315\226\15\1t\11d\42M\64eE\1u\14Ub" "\205\62%Q\22EJ\0v\14Va\305\242DY\222\251\21\0w\15Y!\306b\211jIQQ\223" "\14x\12U\242\205\242\324*\211\1y\14vY\205\262D\225P\14\65\21z\11Tb\305\20\65\15\2" "{\12\223\32U\22U\262\250\26|\6\221\232\304\3}\13\223\32E\26\325\222\250\22\1~\7&\352\215" "d\1\240\5\0\246\4\241\7q\333D\62\10\242\14t^U\64DZ\224H\21\0\243\14ub\225\224" "D\331\226I\203\2\244\14efE\226LI\224DK\26\245\15ubE\226TL\321 e\13\0\246" "\6q\242\304\62\247\17\224Z\315\20%QRJJI\64$\0\250\6\23wE\22\251\16wc\326V" "\211\24%\223\224Z\66\1\252\10S*\205\246d\3\253\11DfM\242\64%\1\254\7%\347\305 \6" "\255\6\23*\305\0\256\15wc\326VI\26\223\322-\233\0\257\6\23\66\305\0\260\11D.\215\22I" "\211\2\261\14u\242U\30\15R\230\3\203\0\262\7C\356\314R\31\263\10C\356\304\222-\0\264\6\42" "\366\214\2\265\16uZE\224DI\224D\311\42\206\0\266\23\226\232\315\60(\311\222,\221\222%Y\222" "%Y\222\0\267\6\21\252D\0\270\7\63\26M\266\0\271\10C\356L\42%\3\272\7S*M\307\1" "\273\12DfE\22%\25%\1\274\21w\42N\226HY\24\15I\226h\203\222%\0\275\17w\42N" "\226HY\24\15\211\224\224\232\6\276\17w\42\306\324\230DJ-\321\6%K\0\277\12s\32M\32%" "Q\62\4\300\20\247\42V\16\344p:&a\222\15R\226\34\301\17\247\42f\232\303\351\230\204I\66H" "Yr\302\20\247\42^\232\344h:&a\222\15R\226\34\303\21\247\42^\222%\71\232\216I\230d\203" "\224%\7\304\17\227\42V\222\243\351\230\204I\66HYr\305\20\247\42^\232\244q:&a\222\15R" "\226\34\306\20xb\336 M\225\64\231\206\60\212\206d\10\307\17\246\326\315\60djUK\206,\316\64" "\0\310\17\245\242M\232\3\203\22%\341\24F\303\0\311\16\245\242]\35\30\224(\11\247\60\32\6\312\17" "\245\242U\226\304\203\22%\341\24F\303\0\313\15\225\242MyP\242$\234\302h\30\314\12\243\42E\26" ".Q\227\1\315\12\243\42U\22.Q\227\1\316\11\243\42M\333\22u\31\317\12\223\42E\222-Q\227" "\1\320\20v\342\305 EJ\66DI\226D\303\220\0\321\23\247\42^\222%\71$-R$UJI" ")R\246\4\322\17\246\342U\234CC\42\215\306I\31\22\0\323\17\246\342]\230cC\42\215\306I\31" "\22\0\324\17\246\342]\230\344\310\220H\243qR\206\4\325\20\246\342U\22%\71\64$\322h\234\224!" "\1\326\17\226\342M\224#C\42\215\306I\31\22\0\327\12U\242E\226\324*\265\0\330\22\230\35>\20" "\15\222\251\22\205Q\22E\246A\312\1\331\22\247\42V\16\344\330\262dQ\26eQ\26)\332\4\332\22" "\247\42f\232c\313\222EY\224EY\244h\23\0\333\22\247\42^\232\344\320\262dQ\26eQ\26)" "\332\4\334\22\227\42V\222C\313\222EY\224EY\244h\23\0\335\16\247\42f\232c\226\254\22\256q" ":\1\336\13u\242\305\26N\225)\233\0\337\13tbU\245EJ*C\2\340\11\203\42E\26j\311" "!\341\11\203\42U\22j\311!\342\11\203\42M\233\226\34\2\343\14\204\42M\242\244b\244T\26\0\344" "\11s\42E\222i\311!\345\11\203\42M\27-\71\4\346\13U\242\205\42%\311RR\4\347\11\203\26" "\315TS\262\5\350\11\203\42E\226.K&\351\11\203\42U\222.K&\352\11\203\42M\343\262d\2" "\353\11s\42E\22.K&\354\10\202\342D\24)\35\355\11\203\342T\22J]\0\356\10\203\342L\233" "\324\5\357\11s\342D\222I]\0\360\14\204bM\66$\321\20\231\22\5\361\14\205bMw`\252D" "I\224\30\362\13\204bM\30+\221)Q\0\363\13\204bU\35P\42S\242\0\364\14\204bM\224\304" "JdJ\24\0\365\14\204bM\242\304JdJ\24\0\366\13tbE\22+\221)Q\0\367\12U\242" "U\16\14:\20\1\370\12v]m\64\365iJ\1\371\17\205bM\232\3Q\22%Q\22EJ\0\372" "\17\205bU\226#Q\22%Q\22EJ\0\373\17\205bU\226\304Q\22%Q\22EJ\0\374\15u" "bM\71J\242$J\242H\11\375\17\246Y]\230C\312\22UB\61\324D\0\376\17\245U\205\30N" "\225(\211\222)\314&\0\377\16\226YM\35Q\226\250\22\212\241&\2\0\0\0";
WiseLabCMU/gridballast
Source/framework/main/u8g2/tools/font/build/single_font_files/u8g2_font_timR08_tf.c
C
mit
6,149
79.986667
163
0.665962
false
import React from 'react' import { PlanItineraryContainer } from './index' const PlanMapRoute = () => { return ( <div> <PlanItineraryContainer /> </div> ) } export default PlanMapRoute
in-depth/indepth-demo
src/shared/views/plans/planItinerary/PlanItineraryRoute.js
JavaScript
mit
206
14.846154
48
0.645631
false
// // Reliant.h // Reliant // // Created by Michael Seghers on 18/09/14. // // #ifndef Reliant_Header____FILEEXTENSION___ #define Reliant_Header____FILEEXTENSION___ #import "OCSObjectContext.h" #import "OCSConfiguratorFromClass.h" #import "NSObject+OCSReliantContextBinding.h" #import "NSObject+OCSReliantInjection.h" #endif
appfoundry/Reliant
Reliant/Classes/Reliant.h
C
mit
331
18.470588
45
0.731118
false
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Immutable; using OpenIddict.Abstractions; using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace Squidex.Areas.IdentityServer.Config { public sealed class AlwaysAddTokenHandler : IOpenIddictServerHandler<ProcessSignInContext> { public ValueTask HandleAsync(ProcessSignInContext context) { if (context == null) { return default; } if (!string.IsNullOrWhiteSpace(context.Response.AccessToken)) { var scopes = context.AccessTokenPrincipal?.GetScopes() ?? ImmutableArray<string>.Empty; context.Response.Scope = string.Join(" ", scopes); } return default; } } }
Squidex/squidex
backend/src/Squidex/Areas/IdentityServer/Config/AlwaysAddTokenHandler.cs
C#
mit
1,160
33.058824
103
0.518135
false
using System.Diagnostics.CodeAnalysis; namespace Npoi.Mapper { /// <summary> /// Information for one row that read from file. /// </summary> /// <typeparam name="TTarget">The target mapping type for a row.</typeparam> [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")] public class RowInfo<TTarget> : IRowInfo { #region Properties /// <summary> /// Row number. /// </summary> public int RowNumber { get; set; } /// <summary> /// Constructed value object from the row. /// </summary> public TTarget Value { get; set; } /// <summary> /// Column index of the first error. /// </summary> public int ErrorColumnIndex { get; set; } /// <summary> /// Error message for the first error. /// </summary> public string ErrorMessage { get; set; } #endregion #region Constructors /// <summary> /// Initialize a new RowData object. /// </summary> /// <param name="rowNumber">The row number</param> /// <param name="value">Constructed value object from the row</param> /// <param name="errorColumnIndex">Column index of the first error cell</param> /// <param name="errorMessage">The error message</param> public RowInfo(int rowNumber, TTarget value, int errorColumnIndex, string errorMessage) { RowNumber = rowNumber; Value = value; ErrorColumnIndex = errorColumnIndex; ErrorMessage = errorMessage; } #endregion } }
donnytian/Npoi.Mapper
Npoi.Mapper/src/Npoi.Mapper/RowInfo.cs
C#
mit
1,652
29
95
0.573333
false
const path = require('path'); module.exports = { lazyLoad: true, pick: { posts(markdownData) { return { meta: markdownData.meta, description: markdownData.description, }; }, }, plugins: [path.join(__dirname, '..', 'node_modules', 'bisheng-plugin-description')], routes: [{ path: '/', component: './template/Archive', }, { path: '/posts/:post', dataPath: '/:post', component: './template/Post', }, { path: '/tags', component: './template/TagCloud', }], };
benjycui/bisheng
packages/bisheng-theme-one/src/index.js
JavaScript
mit
536
20.44
86
0.552239
false
<?php namespace WindowsAzure\DistributionBundle\Deployment; /** * @author Stéphane Escandell <stephane.escandell@gmail.com> */ interface CustomIteratorInterface { /** * @param array $dirs * @param array $subdirs */ public function getIterator(array $dirs, array $subdirs); }
beberlei/AzureDistributionBundle
Deployment/CustomIteratorInterface.php
PHP
mit
302
19.133333
61
0.694352
false
import { Injectable } from '@angular/core'; import {Http,Response,ConnectionBackend,Headers,RequestMethod} from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; import{AppHttpUtil} from '../appUtil/httpUtil'; import {AppPermService} from "./permService"; import {AppUrlConfig} from "../appConfig/urlConfig"; @Injectable() export class AppLoginService { constructor(private httpUtil: AppHttpUtil,private urlConfig:AppUrlConfig){ } /** * 用户登录 */ login(_name:string,_pass:string){ return this.httpUtil.ajax({ url:this.urlConfig.emarketService+'system/login/', method:RequestMethod.Post, body:{ loginName:_name, password:_pass } }); } }
inherents/efeNew
app/appService/loginService.ts
TypeScript
mit
841
25.870968
84
0.654262
false
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2016 zilongshanren http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #import <AppKit/AppKit.h> #include "ui/UIEditBox/Mac/CCUITextInput.h" @interface CCUIPasswordTextField : NSTextField<CCUITextInput> { NSMutableDictionary* _placeholderAttributes; } @end
MaiyaT/cocosStudy
Eliminate/builds/jsb-default/frameworks/cocos2d-x/cocos/ui/UIEditBox/Mac/CCUIPasswordTextField.h
C
mit
1,500
40.666667
78
0.703333
false
// Init ES2015 + .jsx environments for .require() require('babel-register'); var express = require('express'); var fluxexapp = require('./fluxexapp'); var serverAction = require('./actions/server'); var fluxexServerExtra = require('fluxex/extra/server'); var app = express(); // Provide /static/js/main.js fluxexServerExtra.initStatic(app); // Mount test page at /test app.use('/product', fluxexServerExtra.createMiddlewareByAction(fluxexapp, serverAction.samplePage)); // Start server app.listen(process.env.TESTPORT || 3000); console.log('Fluxex started! Go http://localhost:3001/product?id=124');
zordius/fluxex
examples/01-history-api/server.js
JavaScript
mit
604
32.555556
100
0.745033
false
import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a
yangshun/cs4243-project
app/surface.py
Python
mit
3,220
29.377358
114
0.581988
false
# Sparse Arrays Internally the V8 engine can represent `Array`s following one of two approaches: - **Fast Elements**: linear storage for compact keys sets. - **Dictionary Elements**: hash table storage (more expensive to access on runtime). If you want V8 to represent your `Array` in the `Fast Elements` form, you need to take into account the following: - Use contiguous keys starting at `0`. - Don't pre-allocate large `Array` (e.g. *> 64K* elements) that you don't use. - Don't delete elements, specially in numeric `Array`s. - Don't load uninitialized or deleted elements. Another consideration: any name used as property name that is not a `String` will be serialized, read more at [Properties Names](v8-tips/properties-names).
Kikobeats/js-mythbusters
docs/v8-tips/sparse-arrays.md
Markdown
mit
739
48.266667
155
0.752368
false
<?php return [ /** *-------------------------------------------------------------------------- * Logging Configuration *-------------------------------------------------------------------------- * * Here you may configure the log settings for your application. Out of * the box, the application uses the Monolog PHP logging library. This gives * you a variety of powerful log handlers / formatters to utilize. * * Available Settings: "single", "daily", "syslog", "errorlog" * */ 'log' => env('APP_LOG', 'single'), 'log_level' => env('APP_LOG_LEVEL', 'debug'), ];
lioneil/pluma
config/logging.php
PHP
mit
633
30.65
80
0.447077
false
# [Demo](https://keaws.github.io/git-api-client/) ## Install ``` npm i npm start ```
Keaws/Keaws.github.io
git-api-client/README.md
Markdown
mit
86
11.285714
49
0.616279
false
A PvPGNChatParser converts raw messages received from PvPGNChat to ChatMessage objects
serpi90/PvPGNChat
PvPGNChat-Model.package/PvPGNChatParser.class/README.md
Markdown
mit
86
86
86
0.883721
false
import { fullSrc } from '../element/element'; import { pixels } from '../math/unit'; import { Clone } from './clone'; import { Container } from './container'; import { Image } from './image'; import { Overlay } from './overlay'; import { Wrapper } from './wrapper'; export class ZoomDOM { static useExisting(element: HTMLImageElement, parent: HTMLElement, grandparent: HTMLElement): ZoomDOM { let overlay = Overlay.create(); let wrapper = new Wrapper(grandparent); let container = new Container(parent); let image = new Image(element); let src = fullSrc(element); if (src === element.src) { return new ZoomDOM(overlay, wrapper, container, image); } else { return new ZoomDOM(overlay, wrapper, container, image, new Clone(container.clone())); } } static create(element: HTMLImageElement): ZoomDOM { let overlay = Overlay.create(); let wrapper = Wrapper.create(); let container = Container.create(); let image = new Image(element); let src = fullSrc(element); if (src === element.src) { return new ZoomDOM(overlay, wrapper, container, image); } else { return new ZoomDOM(overlay, wrapper, container, image, Clone.create(src)); } } readonly overlay: Overlay; readonly wrapper: Wrapper; readonly container: Container; readonly image: Image; readonly clone?: Clone; constructor(overlay: Overlay, wrapper: Wrapper, container: Container, image: Image, clone?: Clone) { this.overlay = overlay; this.wrapper = wrapper; this.container = container; this.image = image; this.clone = clone; } appendContainerToWrapper(): void { this.wrapper.element.appendChild(this.container.element); } replaceImageWithWrapper(): void { let parent = this.image.element.parentElement as HTMLElement; parent.replaceChild(this.wrapper.element, this.image.element); } appendImageToContainer(): void { this.container.element.appendChild(this.image.element); } appendCloneToContainer(): void { if (this.clone !== undefined) { this.container.element.appendChild(this.clone.element); } } replaceImageWithClone(): void { if (this.clone !== undefined) { this.clone.show(); this.image.hide(); } } replaceCloneWithImage(): void { if (this.clone !== undefined) { this.image.show(); this.clone.hide(); } } fixWrapperHeight(): void { this.wrapper.element.style.height = pixels(this.image.element.height); } collapsed(): void { this.overlay.removeFrom(document.body); this.image.deactivate(); this.wrapper.finishCollapsing(); } /** * Called at the end of an expansion to check if the clone loaded before our expansion finished. If it did, and is * still not visible, we can now show it to the client. */ showCloneIfLoaded(): void { if (this.clone !== undefined && this.clone.isLoaded() && this.clone.isHidden()) { this.replaceImageWithClone(); } } }
MikeBull94/zoom.ts
src/dom/zoom-dom.ts
TypeScript
mit
3,272
30.461538
118
0.608496
false
"use strict"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var qs = require("querystring"); var partial = require("lodash.partial"); var endpoints = require("./stats-endpoints"); var dicts = require("./dicts"); var translateKeys = require("./util/translate-keys"); var transport = require("./get-json"); var translate = partial(translateKeys, dicts.jsToNbaMap); var stats = Object.create({ setTransport: function setTransport(_transport) { transport = _transport; }, getTransport: function getTransport() { return transport; } }); Object.keys(endpoints).forEach(function (key) { stats[key] = makeStatsMethod(endpoints[key]); }); function makeStatsMethod(endpoint) { return function statsMethod(query, callback) { if (typeof query === "function") { callback = query; query = {}; } if (typeof callback !== "function") { throw new TypeError("Must pass a callback function."); } var params = _extends({}, endpoint.defaults, translate(query)); transport(endpoint.url, params, function (err, response) { if (err) return callback(err); if (response == null) return callback(); // response is something like "GameID is required" if (typeof response === "string") return callback(new Error(response)); if (endpoint.transform) return callback(null, endpoint.transform(response)); callback(null, response); }); }; } module.exports = stats;
weixiyen/nba
lib/stats.js
JavaScript
mit
1,662
27.672414
257
0.663658
false
<?php /* TwigBundle:Exception:exception.json.twig */ class __TwigTemplate_8d9b12e119daada0de361618d51aaa01 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 if (isset($context["exception"])) { $_exception_ = $context["exception"]; } else { $_exception_ = null; } echo twig_jsonencode_filter($this->getAttribute($_exception_, "toarray")); echo " "; } public function getTemplateName() { return "TwigBundle:Exception:exception.json.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 47 => 8, 30 => 4, 27 => 3, 22 => 4, 117 => 22, 112 => 21, 109 => 20, 104 => 19, 96 => 18, 84 => 14, 80 => 12, 68 => 9, 44 => 7, 26 => 4, 23 => 3, 20 => 2, 17 => 1, 92 => 39, 86 => 6, 79 => 40, 57 => 22, 46 => 7, 37 => 8, 33 => 7, 29 => 6, 24 => 4, 19 => 1, 144 => 54, 138 => 50, 130 => 46, 124 => 24, 121 => 41, 115 => 40, 111 => 38, 108 => 37, 99 => 32, 94 => 29, 91 => 17, 88 => 16, 85 => 26, 77 => 39, 74 => 20, 71 => 19, 65 => 16, 62 => 15, 58 => 8, 54 => 11, 51 => 10, 42 => 9, 38 => 8, 35 => 5, 31 => 4, 28 => 3,); } }
waltertschwe/kids-reading-network
app/cache/prod/twig/8d/9b/12e119daada0de361618d51aaa01.php
PHP
mit
1,455
36.307692
596
0.498282
false
<div id="menu-logo-wrapper" class="animated slideInDown"> <div class="main-menu"> <div class="pull-left"> <div class="toggle-menu-container"> <div class="toggle-menu"> <a href="javascript:void(0)"> <span class="nav-bar"></span> <span class="nav-bar"></span> <span class="nav-bar"></span> </a> </div> </div> <div class="main-nav-wrapper"> <ul class="main-nav"> <li><a href="<?php echo View::url('/'); ?>#about">About</a></li> <li><a href="<?php echo View::url('/'); ?>#flavours">Flavours</a></li> <li><a href="<?php echo View::url('/'); ?>#news">News</a></li> <li><a href="<?php echo View::url('/'); ?>#locate">Locate</a></li> <li><a href="<?php echo View::url('/'); ?>#wholesale">Wholesale</a></li> </ul> </div> </div> <a href="<?php echo View::url('/'); ?>" class="logo pull-right"><img src="<?= $view->getThemePath() ?>/images/logos/main-logo.png" alt=""></a> </div> </div>
zawzawzaw/scoop
application/themes/scooptherapy/elements/menu.php
PHP
mit
988
35.62963
148
0.530364
false
[![Build Status](https://travis-ci.org/practicefusion/ember-background-update.svg)](https://travis-ci.org/practicefusion/ember-background-update) # Ember-background-updates This README outlines the details of collaborating on this Ember addon. ## Installation * `git clone` this repository * `npm install` * `bower install` ## Running * `ember server` * Visit your app at http://localhost:4200. ## Running Tests * `npm test` (Runs `ember try:testall` to test your addon against multiple Ember versions) * `ember test` * `ember test --server` ## Building * `ember build` For more information on using ember-cli, visit [http://www.ember-cli.com/](http://www.ember-cli.com/).
practicefusion/ember-background-update
README.md
Markdown
mit
684
23.428571
145
0.729532
false
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.vmwarecloudsimple.models; import com.azure.resourcemanager.vmwarecloudsimple.fluent.models.CustomizationPolicyInner; /** An immutable client-side representation of CustomizationPolicy. */ public interface CustomizationPolicy { /** * Gets the id property: Customization policy azure id. * * @return the id value. */ String id(); /** * Gets the location property: Azure region. * * @return the location value. */ String location(); /** * Gets the name property: Customization policy name. * * @return the name value. */ String name(); /** * Gets the type property: The type property. * * @return the type value. */ String type(); /** * Gets the description property: Policy description. * * @return the description value. */ String description(); /** * Gets the privateCloudId property: The Private cloud id. * * @return the privateCloudId value. */ String privateCloudId(); /** * Gets the specification property: Detailed customization policy specification. * * @return the specification value. */ CustomizationSpecification specification(); /** * Gets the typePropertiesType property: The type of customization (Linux or Windows). * * @return the typePropertiesType value. */ CustomizationPolicyPropertiesType typePropertiesType(); /** * Gets the version property: Policy version. * * @return the version value. */ String version(); /** * Gets the inner com.azure.resourcemanager.vmwarecloudsimple.fluent.models.CustomizationPolicyInner object. * * @return the inner object. */ CustomizationPolicyInner innerModel(); }
Azure/azure-sdk-for-java
sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/src/main/java/com/azure/resourcemanager/vmwarecloudsimple/models/CustomizationPolicy.java
Java
mit
2,001
24.0125
112
0.647176
false
import React from 'react'; import ErrorIcon from './ErrorIcon'; export const symbols = { 'ErrorIcon -> with filled': <ErrorIcon filled={true} />, 'ErrorIcon -> without filled': <ErrorIcon filled={false} /> };
seekinternational/seek-asia-style-guide
react/ErrorIcon/ErrorIcon.iconSketch.js
JavaScript
mit
214
29.571429
61
0.682243
false
{% extends "base.html"%} {% block title %}Sequence{% endblock %} <!---- css/js dependencies ----> {% block head %} <link rel="stylesheet" type="text/css" href="{{ static_file('css/rhizo/app.css') }}"> <script type="text/javascript" src="/static/js/moment.min.js"></script> <script type="text/javascript" src="/static/js/paho-mqtt.js"></script> <script type="text/javascript" src="{{ static_file('js/rhizo/messages.js') }}"></script> <script type="text/javascript" src="{{ static_file('js/manyplot.js') }}"></script> <style> div#plot { display: none; margin-bottom: 20px; } </style> {% endblock head %} <!---- js code ----> {% block script %} <script> var g_resource = {{ resource|safe }}; var g_resourcePath = '{{ resource_path|safe }}'; // assume includes leading slash var g_thumbnailResourcePath = '{{ thumbnail_resource_path|safe }}'; // assume includes leading slash var g_timestamps = {{ timestamps|safe }}; var g_values = {{ values|safe }}; var g_thumbnailRevs = {{ thumbnail_revs|safe }}; var g_fullImageRevs = {{ full_image_revs|safe }}; var g_plotHandler = null; var g_xData = null; var g_yData = null; var g_tableData = null; $(function() { // add a menus var menuData = createMenuData(); menuData.add('Download', downloadHistory); menuData.add('Summary', dataSummary); menuData.add('Delete Data', deleteAllData); createDropDownMenu({id: 'dataMenu', label: 'Data', compact: true, menuData: menuData}).appendTo($('#menuArea')); // add summary area var dataTypeName = ''; switch (g_resource.system_attributes.data_type) { case 1: dataTypeName = 'numeric'; break; case 2: dataTypeName = 'text'; break; case 3: dataTypeName = 'image'; break; } var nvd = createNameValueData(); nvd.add('ID', g_resource.id); nvd.add('Name', g_resource.name); nvd.add('Data Type', dataTypeName); nvd.add('Decimal Places', g_resource.system_attributes.decimal_places); nvd.add('Units', g_resource.system_attributes.units); nvd.add('Max History', g_resource.system_attributes.max_history); nvd.add('Min Storage Interval', g_resource.system_attributes.min_storage_interval ? g_resource.system_attributes.min_storage_interval + ' seconds' : '0'); createNameValueView(nvd).appendTo($('#sequenceInfo')); var decimalPlaces = g_resource.decimal_places; var format = '.' + decimalPlaces + 'f'; // create plot (for numeric sequences) if (g_resource.system_attributes.data_type == 1) { var valuesRev = g_values.slice(0).reverse(); // fix(faster): do we need to make a copy if we're reversing? var timestampsRev = g_timestamps.slice(0).reverse(); var canvas = document.getElementById('canvas'); // make sure all values are numeric (or null) // fix(faster): combine with reverse (or do on server) var len = valuesRev.length; for (var i = 0; i < len; i++) { var val = valuesRev[i]; if (val !== null) { valuesRev[i] = +val; // convert to number } } // create plot using manyplot library g_plotHandler = createPlotHandler(canvas); g_xData = createDataColumn('timestamp', timestampsRev); g_xData.type = 'timestamp'; g_yData = createDataColumn('value', valuesRev); g_yData.name = g_resource.name; var dataPairs = [ { 'xData': g_xData, 'yData': g_yData, } ]; g_plotHandler.plotter.setData(dataPairs); g_plotHandler.drawPlot(null, null); $('#plot').show(); } // create table of historical values if (g_values.length) { // prep data var tableLength = 200; var timestamps = g_timestamps.slice(0, tableLength); for (var i = 0; i < timestamps.length; i++) { timestamps[i] *= 1000; // fix(later): do this automatically in table? standardize on unix or unix * 1000? } var values = []; if (g_resource.system_attributes.data_type == 3) { values = []; for (var i = 0; i < tableLength; i++) { var fullImageUrl = '/api/v1/resources' + g_resourcePath + '?rev=' + g_fullImageRevs[i]; if (g_thumbnailRevs[i]) { var thumbnailUrl = '/api/v1/resources' + g_thumbnailResourcePath + '?rev=' + g_thumbnailRevs[i]; var link = $('<a>', {href: fullImageUrl}); $('<img>', {src: thumbnailUrl}).appendTo(link); } else { var link = createLink({'text': 'image', 'href': fullImageUrl}); } values.push(link); } } else { values = g_values.slice(0, tableLength); } // create table var div = $('#history'); $('<h2>', {html: 'Recent History'}).appendTo(div); g_tableData = createTableData(); g_tableData.addColumn('Timestamp', timestamps); g_tableData.addColumn('Value', values); g_tableData.setFormat('Timestamp', 'timestamp'); createTable(g_tableData).appendTo(div); } // subscribe to updates var lastSlashPos = g_resourcePath.lastIndexOf('/'); var folderName = g_resourcePath.slice(0, lastSlashPos); subscribeToFolder(folderName); connectWebSocket(); g_wsh.addSequenceHandler(function(path, timestamp, value) { if (path == g_resourcePath) { var unixTimestamp = timestamp.unix(); // update plot if (g_resource.system_attributes.data_type == 1) { g_xData.data.push(unixTimestamp); g_yData.data.push(value); g_plotHandler.plotter.autoBounds(); g_plotHandler.drawPlot(null, null); } // update image // note: not every sequence update will be stored in DB, so not every image update message will include revision_ids if (g_resource.system_attributes.data_type == 3 && params.revision_id && params.thumbnail_revision_id) { var fullImageUrl = '/api/v1/resources' + g_resourcePath + '?rev=' + params.revision_id; var thumbnailUrl = '/api/v1/resources' + g_thumbnailResourcePath + '?rev=' + params.thumbnail_revision_id; var link = $('<a>', {href: fullImageUrl}); $('<img>', {src: thumbnailUrl}).appendTo(link); value = link; } // update table // fix(faster): just add row? if (value) { g_tableData.column('Timestamp').values.unshift(unixTimestamp * 1000); g_tableData.column('Value').values.unshift(value); var div = $('#history'); div.html(''); $('<h2>', {html: 'Recent History'}).appendTo(div); createTable(g_tableData).appendTo(div); } } }); }); function dataSummary() { var handler = function(data) { var len = data.length; var messages = []; var counts = []; for (var i = 0; i < len; i++) { var item = data[i]; messages.push(item[0]); counts.push(item[1]); } var div = $('#history'); div.html(''); // clear out old html $('<h2>', {html: 'History Summary'}).appendTo(div); var tableData = createTableData(); tableData.addColumn('Message', messages); tableData.addColumn('Count', counts); createTable(tableData).appendTo(div); } var params = { 'summary': 1, 'prefix_length': 10, 'count': 10000, 'csrf_token': g_csrfToken, }; $.get('/api/v1/resources' + g_resourcePath, params, handler); } function downloadHistory() { // create a modal var modalDiv = createBasicModal('downloadHistory', 'Download History'); modalDiv.appendTo($('body')); // add date range selectors var todayStr = moment().format('YYYY-MM-DD'); var fg = createFormGroup({id: 'startDate', label: 'Start Date'}).appendTo($('#downloadHistory-body')); createTextInput({id: 'startDate', value: todayStr}).appendTo(fg); var fg = createFormGroup({id: 'endDate', label: 'End Date'}).appendTo($('#downloadHistory-body')); createTextInput({id: 'endDate', value: todayStr}).appendTo(fg); // handle user choosing to proceed $('#downloadHistory-ok').click(function() { var startDate = $('#startDate').val(); var endDate = $('#endDate').val(); var startMoment = moment(startDate); var endMoment = moment(endDate); if (!startMoment.isValid()) { alert('Please enter a valid start date.'); $('#startDate').focus(); } else if (!endMoment.isValid()) { alert('Please enter a valid end date.'); $('#endDate').focus(); } else { var startTimestamp = startMoment.startOf('day').toISOString(); var endTimestamp = endMoment.endOf('day').toISOString(); $('#downloadHistory').modal('hide'); window.location.href = '/api/v1/resources' + g_resourcePath + '?download=1&start_timestamp=' + startTimestamp + '&end_timestamp=' + endTimestamp; } }); // display the modal $('#downloadHistory').modal('show'); } function deleteAllData() { modalConfirm({ title: 'Delete Sequence Data', 'prompt': 'Are you sure you want to <b>delete all data</b> for sequence <b>' + g_resource.name + '</b>?', yesFunc: function() { $.ajax({ url: '/api/v1/resources' + g_resourcePath, data: {'csrf_token': g_csrfToken, 'data_only': 1}, type: 'DELETE', success: function() {window.location.reload();}, // fix(later): make more graceful }); } }); } </script> {% endblock %} <!---- page content ----> {% block content %} <h2>Sequence</h2> <div id="sequenceInfo"></div> <div id="plot"> <canvas id="canvas" width="900" height="400"></canvas> <br> <button class="btn" onclick="g_plotHandler.zoomIn()">Zoom In</button> <button class="btn" onclick="g_plotHandler.zoomOut()">Zoom Out</button> </div> <div id="history"></div> {% endblock %}
rhizolab/rhizo-server
main/templates/resources/sequence.html
HTML
mit
9,049
32.268382
155
0.654768
false
<!DOCTYPE HTML> <?php include '../inc/draft_config.php'; ?><!-- Use relative path to find config file --> <html lang=""> <head> <base href="<?php echo BASE_URL; ?>"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Project Draft — 404</title> <meta name="robots" content="noindex, nofollow"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <?php include INC_PATH . 'pages_resources.php'; ?> <link rel="icon" sizes="16x16" href="assets/favicon-16.png"> <link rel="icon" sizes="32x32" href="assets/favicon-32.png"> <link rel="icon" sizes="48x48" href="assets/favicon-48.png"> <link rel="icon" sizes="64x64" href="assets/favicon-64.png"> <link rel="icon" sizes="128x128" href="assets/favicon-128.png"> <link rel="icon" sizes="192x192" href="assets/favicon-192.png"> </head> <body class="error-404"> <?php $page = 'error-404'; include INC_PATH . 'pages_overhead.php'; ?> <!-- Example 404 content (markup based on Bootstrap 3 framework) --> <div class="container"> <div class="row"> <div class="col-md-12"> <h1>Error 404 <br>Page not found!</h1> <p>Oops! Seems like the page you are looking for no longer exists. <br>You may go <a href='javascript:history.back(1)'>back</a> or <a href='<?php echo BASE_URL; ?>'>start over</a>.</p> <hr> <p class="small text-muted">Rename and edit <code>htaccess</code> file to activate custom error pages.</p> </div> </div> </div> <!-- END of example content --> <?php include INC_PATH . 'pages_scripts.php'; ?> </body> </html>
Kiriniy/Project_Draft
dist/assets/errors/404.php
PHP
mit
1,764
32.884615
127
0.610102
false
#entry { margin: 10px auto 10px auto; font-size: 10pt; width: 100%; height: 70px; display: table; border-radius: 10px; background-color: #301E19; border: 10px; text-align: center; vertical-align: middle; } .coffeeType { width: 265px; height: 34px; margin: 0 auto 0 auto; border-bottom: solid; border-width: 1px; line-height: 30px; display: table; } .coffeeTypeCell { display: table-cell; } .coffeeTime { height: 35px; margin: 0 auto 0 auto; line-height: 30px; display: table; } .coffeeTimeCell { display: table-cell; width: 1000px; }
maxxgl/maxxgl.github.io
app/entry.css
CSS
mit
633
15.684211
32
0.609795
false
package commands import ( "compress/gzip" "errors" "fmt" "io" "os" "path/filepath" "strings" core "github.com/ipfs/go-ipfs/core" cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv" e "github.com/ipfs/go-ipfs/core/commands/e" tar "gx/ipfs/QmQine7gvHncNevKtG9QXxf3nXcwSj6aDDmMm52mHofEEp/tar-utils" uarchive "gx/ipfs/QmSMJ4rZbCJaih3y82Ebq7BZqK6vU2FHsKcWKQiE1DPTpS/go-unixfs/archive" "gx/ipfs/QmWGm4AbZEbnmdgVTza52MSNpEmBdFVqzmAysRbjrRyGbH/go-ipfs-cmds" path "gx/ipfs/QmWqh9oob7ZHQRwU5CdTqpnC8ip8BEkFNrwXRxeNo5Y7vA/go-path" "gx/ipfs/QmYWB8oH6o7qftxoyqTTZhzLrhKCVT7NYahECQTwTtqbgj/pb" dag "gx/ipfs/Qmb2UEG2TAeVrEJSjqsZF7Y2he7wRDkrdt6c3bECxwZf4k/go-merkledag" "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit" ) var ErrInvalidCompressionLevel = errors.New("compression level must be between 1 and 9") const ( outputOptionName = "output" archiveOptionName = "archive" compressOptionName = "compress" compressionLevelOptionName = "compression-level" ) var GetCmd = &cmds.Command{ Helptext: cmdkit.HelpText{ Tagline: "Download IPFS objects.", ShortDescription: ` Stores to disk the data contained an IPFS or IPNS object(s) at the given path. By default, the output will be stored at './<ipfs-path>', but an alternate path can be specified with '--output=<path>' or '-o=<path>'. To output a TAR archive instead of unpacked files, use '--archive' or '-a'. To compress the output with GZIP compression, use '--compress' or '-C'. You may also specify the level of compression by specifying '-l=<1-9>'. `, }, Arguments: []cmdkit.Argument{ cmdkit.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted.").EnableStdin(), }, Options: []cmdkit.Option{ cmdkit.StringOption(outputOptionName, "o", "The path where the output should be stored."), cmdkit.BoolOption(archiveOptionName, "a", "Output a TAR archive."), cmdkit.BoolOption(compressOptionName, "C", "Compress the output with GZIP compression."), cmdkit.IntOption(compressionLevelOptionName, "l", "The level of compression (1-9)."), }, PreRun: func(req *cmds.Request, env cmds.Environment) error { _, err := getCompressOptions(req) return err }, Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error { cmplvl, err := getCompressOptions(req) if err != nil { return err } node, err := cmdenv.GetNode(env) if err != nil { return err } p := path.Path(req.Arguments[0]) ctx := req.Context dn, err := core.Resolve(ctx, node.Namesys, node.Resolver, p) if err != nil { return err } switch dn := dn.(type) { case *dag.ProtoNode: size, err := dn.Size() if err != nil { return err } res.SetLength(size) case *dag.RawNode: res.SetLength(uint64(len(dn.RawData()))) default: return err } archive, _ := req.Options[archiveOptionName].(bool) reader, err := uarchive.DagArchive(ctx, dn, p.String(), node.DAG, archive, cmplvl) if err != nil { return err } return res.Emit(reader) }, PostRun: cmds.PostRunMap{ cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error { req := res.Request() v, err := res.Next() if err != nil { return err } outReader, ok := v.(io.Reader) if !ok { return e.New(e.TypeErr(outReader, v)) } outPath := getOutPath(req) cmplvl, err := getCompressOptions(req) if err != nil { return err } archive, _ := req.Options[archiveOptionName].(bool) gw := getWriter{ Out: os.Stdout, Err: os.Stderr, Archive: archive, Compression: cmplvl, Size: int64(res.Length()), } return gw.Write(outReader, outPath) }, }, } type clearlineReader struct { io.Reader out io.Writer } func (r *clearlineReader) Read(p []byte) (n int, err error) { n, err = r.Reader.Read(p) if err == io.EOF { // callback fmt.Fprintf(r.out, "\033[2K\r") // clear progress bar line on EOF } return } func progressBarForReader(out io.Writer, r io.Reader, l int64) (*pb.ProgressBar, io.Reader) { bar := makeProgressBar(out, l) barR := bar.NewProxyReader(r) return bar, &clearlineReader{barR, out} } func makeProgressBar(out io.Writer, l int64) *pb.ProgressBar { // setup bar reader // TODO: get total length of files bar := pb.New64(l).SetUnits(pb.U_BYTES) bar.Output = out // the progress bar lib doesn't give us a way to get the width of the output, // so as a hack we just use a callback to measure the output, then git rid of it bar.Callback = func(line string) { terminalWidth := len(line) bar.Callback = nil log.Infof("terminal width: %v\n", terminalWidth) } return bar } func getOutPath(req *cmds.Request) string { outPath, _ := req.Options[outputOptionName].(string) if outPath == "" { trimmed := strings.TrimRight(req.Arguments[0], "/") _, outPath = filepath.Split(trimmed) outPath = filepath.Clean(outPath) } return outPath } type getWriter struct { Out io.Writer // for output to user Err io.Writer // for progress bar output Archive bool Compression int Size int64 } func (gw *getWriter) Write(r io.Reader, fpath string) error { if gw.Archive || gw.Compression != gzip.NoCompression { return gw.writeArchive(r, fpath) } return gw.writeExtracted(r, fpath) } func (gw *getWriter) writeArchive(r io.Reader, fpath string) error { // adjust file name if tar if gw.Archive { if !strings.HasSuffix(fpath, ".tar") && !strings.HasSuffix(fpath, ".tar.gz") { fpath += ".tar" } } // adjust file name if gz if gw.Compression != gzip.NoCompression { if !strings.HasSuffix(fpath, ".gz") { fpath += ".gz" } } // create file file, err := os.Create(fpath) if err != nil { return err } defer file.Close() fmt.Fprintf(gw.Out, "Saving archive to %s\n", fpath) bar, barR := progressBarForReader(gw.Err, r, gw.Size) bar.Start() defer bar.Finish() _, err = io.Copy(file, barR) return err } func (gw *getWriter) writeExtracted(r io.Reader, fpath string) error { fmt.Fprintf(gw.Out, "Saving file(s) to %s\n", fpath) bar := makeProgressBar(gw.Err, gw.Size) bar.Start() defer bar.Finish() defer bar.Set64(gw.Size) extractor := &tar.Extractor{Path: fpath, Progress: bar.Add64} return extractor.Extract(r) } func getCompressOptions(req *cmds.Request) (int, error) { cmprs, _ := req.Options[compressOptionName].(bool) cmplvl, cmplvlFound := req.Options[compressionLevelOptionName].(int) switch { case !cmprs: return gzip.NoCompression, nil case cmprs && !cmplvlFound: return gzip.DefaultCompression, nil case cmprs && (cmplvl < 1 || cmplvl > 9): return gzip.NoCompression, ErrInvalidCompressionLevel } return cmplvl, nil }
chriscool/go-ipfs
core/commands/get.go
GO
mit
6,703
25.389764
110
0.687752
false
package org.reasm.m68k.assembly.internal; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import org.reasm.Value; import org.reasm.ValueToBooleanVisitor; /** * The <code>WHILE</code> directive. * * @author Francis Gagné */ @Immutable class WhileDirective extends Mnemonic { @Nonnull static final WhileDirective WHILE = new WhileDirective(); private WhileDirective() { } @Override void assemble(M68KAssemblyContext context) { context.sizeNotAllowed(); final Object blockState = context.getParentBlock(); if (!(blockState instanceof WhileBlockState)) { throw new AssertionError(); } final WhileBlockState whileBlockState = (WhileBlockState) blockState; // The WHILE directive is assembled on every iteration. // Parse the condition operand on the first iteration only. if (!whileBlockState.parsedCondition) { if (context.requireNumberOfOperands(1)) { whileBlockState.conditionExpression = parseExpressionOperand(context, 0); } whileBlockState.parsedCondition = true; } final Value condition; if (whileBlockState.conditionExpression != null) { condition = whileBlockState.conditionExpression.evaluate(context.getEvaluationContext()); } else { condition = null; } final Boolean result = Value.accept(condition, ValueToBooleanVisitor.INSTANCE); if (!(result != null && result.booleanValue())) { // Skip the block body and stop the iteration. whileBlockState.iterator.next(); whileBlockState.hasNextIteration = false; } } }
reasm/reasm-m68k
src/main/java/org/reasm/m68k/assembly/internal/WhileDirective.java
Java
mit
1,747
28.59322
101
0.658076
false
/* * This file is part of FlexibleLogin * * The MIT License (MIT) * * Copyright (c) 2015-2018 contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.games647.flexiblelogin.listener.prevent; import com.flowpowered.math.vector.Vector3i; import com.github.games647.flexiblelogin.FlexibleLogin; import com.github.games647.flexiblelogin.PomData; import com.github.games647.flexiblelogin.config.Settings; import com.google.inject.Inject; import java.util.List; import java.util.Optional; import org.spongepowered.api.command.CommandManager; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.block.InteractBlockEvent; import org.spongepowered.api.event.command.SendCommandEvent; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.event.entity.InteractEntityEvent; import org.spongepowered.api.event.entity.MoveEntityEvent; import org.spongepowered.api.event.filter.Getter; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.filter.cause.Root; import org.spongepowered.api.event.filter.type.Exclude; import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent; import org.spongepowered.api.event.item.inventory.ClickInventoryEvent; import org.spongepowered.api.event.item.inventory.ClickInventoryEvent.NumberPress; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.event.item.inventory.InteractInventoryEvent; import org.spongepowered.api.event.item.inventory.InteractItemEvent; import org.spongepowered.api.event.item.inventory.UseItemStackEvent; import org.spongepowered.api.event.message.MessageChannelEvent; public class PreventListener extends AbstractPreventListener { private final CommandManager commandManager; @Inject PreventListener(FlexibleLogin plugin, Settings settings, CommandManager commandManager) { super(plugin, settings); this.commandManager = commandManager; } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerMove(MoveEntityEvent playerMoveEvent, @First Player player) { if (playerMoveEvent instanceof MoveEntityEvent.Teleport) { return; } Vector3i oldLocation = playerMoveEvent.getFromTransform().getPosition().toInt(); Vector3i newLocation = playerMoveEvent.getToTransform().getPosition().toInt(); if (oldLocation.getX() != newLocation.getX() || oldLocation.getZ() != newLocation.getZ()) { checkLoginStatus(playerMoveEvent, player); } } @Listener(order = Order.FIRST, beforeModifications = true) public void onChat(MessageChannelEvent.Chat chatEvent, @First Player player) { checkLoginStatus(chatEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onCommand(SendCommandEvent commandEvent, @First Player player) { String command = commandEvent.getCommand(); Optional<? extends CommandMapping> commandOpt = commandManager.get(command); if (commandOpt.isPresent()) { CommandMapping mapping = commandOpt.get(); command = mapping.getPrimaryAlias(); //do not blacklist our own commands if (commandManager.getOwner(mapping) .map(pc -> pc.getId().equals(PomData.ARTIFACT_ID)) .orElse(false)) { return; } } commandEvent.setResult(CommandResult.empty()); if (settings.getGeneral().isCommandOnlyProtection()) { List<String> protectedCommands = settings.getGeneral().getProtectedCommands(); if (protectedCommands.contains(command) && !plugin.getDatabase().isLoggedIn(player)) { player.sendMessage(settings.getText().getProtectedCommand()); commandEvent.setCancelled(true); } } else { checkLoginStatus(commandEvent, player); } } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerItemDrop(DropItemEvent dropItemEvent, @First Player player) { checkLoginStatus(dropItemEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerItemPickup(ChangeInventoryEvent.Pickup pickupItemEvent, @Root Player player) { checkLoginStatus(pickupItemEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onItemConsume(UseItemStackEvent.Start itemConsumeEvent, @First Player player) { checkLoginStatus(itemConsumeEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onItemInteract(InteractItemEvent interactItemEvent, @First Player player) { checkLoginStatus(interactItemEvent, player); } // Ignore number press events, because Sponge before this commit // https://github.com/SpongePowered/SpongeForge/commit/f0605fb0bd62ca2f958425378776608c41f16cca // has a duplicate bug. Using this exclude we can ignore it, but still cancel the movement of the item // it appears to be fixed using SpongeForge 4005 (fixed) and 4004 with this change @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryChange(ChangeInventoryEvent changeInventoryEvent, @First Player player) { checkLoginStatus(changeInventoryEvent, player); } @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryInteract(InteractInventoryEvent interactInventoryEvent, @First Player player) { checkLoginStatus(interactInventoryEvent, player); } @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryClick(ClickInventoryEvent clickInventoryEvent, @First Player player) { checkLoginStatus(clickInventoryEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onBlockInteract(InteractBlockEvent interactBlockEvent, @First Player player) { checkLoginStatus(interactBlockEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerInteractEntity(InteractEntityEvent interactEntityEvent, @First Player player) { checkLoginStatus(interactEntityEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerDamage(DamageEntityEvent damageEntityEvent, @First Player player) { //player is damage source checkLoginStatus(damageEntityEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onDamagePlayer(DamageEntityEvent damageEntityEvent, @Getter("getTargetEntity") Player player) { //player is damage target checkLoginStatus(damageEntityEvent, player); } }
games647/FlexibleLogin
src/main/java/com/github/games647/flexiblelogin/listener/prevent/PreventListener.java
Java
mit
8,213
44.375691
111
0.746134
false
<div class="card"> <div class="card-header"> <span class="h3"> Chat Page!! </span> </div> <div class="card-block"> <div class="panel-body"> <ngb-alert [dismissible]="false"> <strong>Warning!</strong> You need to login to see contextual data in chat!! </ngb-alert> <ul class="chat"> <li *ngFor="let message of messages" class="right clearfix"><span class="chat-img" [class.pull-right]="message.isSelf" > <img src="http://placehold.it/50/FA6F57/fff&amp;text={{message.user}}" alt="User Avatar" class="img-circle"/> </span> <div class="chat-body clearfix"> <div class="header"> <small class=" text-muted"><span class="glyphicon glyphicon-time"></span>{{message.timestamp}}</small> <strong [class.pull-right]="message.isSelf" class="primary-font">{{message.user}}</strong> </div> <p> {{message.content}} <a *ngIf="message.isNavigation" [routerLink]="['/indoor-map', {fromLocationId: message.meta.fromLocationId, toLocationId: message.meta.toLocationId }]" >Here</a> </p> </div> </li> </ul> </div> <div class="panel-footer"> <div class="input-group"> <input [(ngModel)]="newMessage.content" id="btn-input" type="text" class="form-control input-sm" placeholder="Type your message here..."> <span class="input-group-btn"> <button class="btn btn-warning btn-sm" id="btn-chat" (click)="send(newMessage)"> Send</button> </span> </div> </div> </div> </div>
rajagopal28/Donna
src/app/chat-bot/chat-bot.component.html
HTML
mit
1,744
43.717949
183
0.534404
false
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class ContributorOrcid(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, uri=None, path=None, host=None): """ ContributorOrcid - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'uri': 'str', 'path': 'str', 'host': 'str' } self.attribute_map = { 'uri': 'uri', 'path': 'path', 'host': 'host' } self._uri = uri self._path = path self._host = host @property def uri(self): """ Gets the uri of this ContributorOrcid. :return: The uri of this ContributorOrcid. :rtype: str """ return self._uri @uri.setter def uri(self, uri): """ Sets the uri of this ContributorOrcid. :param uri: The uri of this ContributorOrcid. :type: str """ self._uri = uri @property def path(self): """ Gets the path of this ContributorOrcid. :return: The path of this ContributorOrcid. :rtype: str """ return self._path @path.setter def path(self, path): """ Sets the path of this ContributorOrcid. :param path: The path of this ContributorOrcid. :type: str """ self._path = path @property def host(self): """ Gets the host of this ContributorOrcid. :return: The host of this ContributorOrcid. :rtype: str """ return self._host @host.setter def host(self, host): """ Sets the host of this ContributorOrcid. :param host: The host of this ContributorOrcid. :type: str """ self._host = host def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, ContributorOrcid): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
orcid_api/models/contributor_orcid.py
Python
mit
3,922
23.06135
105
0.507394
false
package com.contexthub.storageapp; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuItem; import com.chaione.contexthub.sdk.model.VaultDocument; import com.contexthub.storageapp.fragments.AboutFragment; import com.contexthub.storageapp.fragments.EditVaultItemFragment; import com.contexthub.storageapp.fragments.VaultItemListFragment; import com.contexthub.storageapp.models.Person; public class MainActivity extends ActionBarActivity implements VaultItemListFragment.Listener, FragmentManager.OnBackStackChangedListener { private MenuItem menuSearch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(android.R.id.content, new VaultItemListFragment()) .commit(); getSupportFragmentManager().addOnBackStackChangedListener(this); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); setupSearchView(menu.findItem(R.id.action_search)); return true; } private void setupSearchView(final MenuItem menuSearch) { this.menuSearch = menuSearch; SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuSearch); SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text); searchAutoComplete.setHint(R.string.search_hint); searchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { menuSearch.collapseActionView(); getSupportFragmentManager().beginTransaction() .addToBackStack(null) .replace(android.R.id.content, VaultItemListFragment.newInstance(query)) .commit(); return true; } @Override public boolean onQueryTextChange(String query) { return false; } }); } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean isMainFragment = getSupportFragmentManager().getBackStackEntryCount() <= 0; menu.findItem(R.id.action_search).setVisible(isMainFragment); menu.findItem(R.id.action_add).setVisible(isMainFragment); menu.findItem(R.id.action_about).setVisible(isMainFragment); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { menuSearch.collapseActionView(); switch(item.getItemId()) { case R.id.action_add: launchEditVaultItemFragment(null); return true; case R.id.action_about: getSupportFragmentManager().beginTransaction() .addToBackStack(null) .replace(android.R.id.content, new AboutFragment()) .commit(); return true; default: return super.onOptionsItemSelected(item); } } private void launchEditVaultItemFragment(VaultDocument<Person> document) { EditVaultItemFragment fragment = document == null ? new EditVaultItemFragment() : EditVaultItemFragment.newInstance(document); getSupportFragmentManager().beginTransaction() .addToBackStack(null) .replace(android.R.id.content, fragment) .commit(); } @Override public void onItemClick(VaultDocument<Person> document) { menuSearch.collapseActionView(); launchEditVaultItemFragment(document); } @Override public void onBackStackChanged() { supportInvalidateOptionsMenu(); } }
contexthub/storage-android
StorageApp/app/src/main/java/com/contexthub/storageapp/MainActivity.java
Java
mit
4,259
36.690265
139
0.665414
false
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ModelAppServiceInfoProviderTest.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Model.Tests { using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Kephas.Composition.Conventions; using Kephas.Composition.Lite; using Kephas.Model.Elements; using Kephas.Services; using Kephas.Testing.Model; using NUnit.Framework; [TestFixture] public class ModelAppServiceInfoProviderTest : ModelTestBase { public override IEnumerable<Assembly> GetDefaultConventionAssemblies() { return new List<Assembly>(base.GetDefaultConventionAssemblies()) { typeof(IModelSpace).Assembly, }; } [Test] public async Task GetAppServiceInfos_EnsureModelSpaceRegistered() { var ambientServices = new AmbientServices() .RegisterMultiple<IAppServiceInfoProvider>(b => b.WithType<ModelAppServiceInfoProvider>()); var container = this.CreateContainer(ambientServices); var provider = container.GetExport<IModelSpaceProvider>(); await provider.InitializeAsync(new Context(container)); var modelSpace = container.GetExport<IModelSpace>(); Assert.IsInstanceOf<DefaultModelSpace>(modelSpace); } } }
quartz-software/kephas
src/Tests/Kephas.Model.Tests/ModelAppServiceInfoProviderTest.cs
C#
mit
1,803
39.044444
120
0.588562
false
<?php /** * @author Victor Demin <mail@vdemin.com> * @copyright (c) 2015, Victor Demin <mail@vdemin.com> */ namespace GlenDemon\ZabbixApi\Repository; use \GlenDemon\ZabbixApi\Entity\HostGroup; /** * HostGroup repository. */ class HostGroupRepository extends AbstractRepository { /** * Finds an object by its primary key / identifier. * * @param mixed $id The identifier. * * @return HostGroup The object. */ public function find($id) { return parent::find($id); } /** * Finds all objects in the repository. * * @return HostGroup[] The objects. */ public function findAll() { return parent::findAll(); } /** * @inherit */ protected function getRawData(array $params) { return $this->api->hostgroupGet($params); } /** * Finds a single object by a set of criteria. * * @param array $criteria The criteria. * * @return HostGroup|null The object. */ public function findOneBy(array $criteria) { return parent::findOneBy($criteria); } }
glendemon/zabbix-api
src/Repository/HostGroupRepository.php
PHP
mit
1,128
18.789474
55
0.588652
false
// Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.lslboost.org/LICENSE_1_0.txt) // // Preprocessed version of "lslboost/mpl/list/list10_c.hpp" header // -- DO NOT modify by hand! namespace lslboost { namespace mpl { template< typename T , T C0 > struct list1_c : l_item< long_<1> , integral_c< T,C0 > , l_end > { typedef list1_c type; typedef T value_type; }; template< typename T , T C0, T C1 > struct list2_c : l_item< long_<2> , integral_c< T,C0 > , list1_c< T,C1 > > { typedef list2_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2 > struct list3_c : l_item< long_<3> , integral_c< T,C0 > , list2_c< T,C1,C2 > > { typedef list3_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3 > struct list4_c : l_item< long_<4> , integral_c< T,C0 > , list3_c< T,C1,C2,C3 > > { typedef list4_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4 > struct list5_c : l_item< long_<5> , integral_c< T,C0 > , list4_c< T,C1,C2,C3,C4 > > { typedef list5_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5 > struct list6_c : l_item< long_<6> , integral_c< T,C0 > , list5_c< T,C1,C2,C3,C4,C5 > > { typedef list6_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6 > struct list7_c : l_item< long_<7> , integral_c< T,C0 > , list6_c< T,C1,C2,C3,C4,C5,C6 > > { typedef list7_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7 > struct list8_c : l_item< long_<8> , integral_c< T,C0 > , list7_c< T,C1,C2,C3,C4,C5,C6,C7 > > { typedef list8_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8 > struct list9_c : l_item< long_<9> , integral_c< T,C0 > , list8_c< T,C1,C2,C3,C4,C5,C6,C7,C8 > > { typedef list9_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9 > struct list10_c : l_item< long_<10> , integral_c< T,C0 > , list9_c< T,C1,C2,C3,C4,C5,C6,C7,C8,C9 > > { typedef list10_c type; typedef T value_type; }; }}
gazzlab/LSL-gazzlab-branch
liblsl/external/lslboost/mpl/list/aux_/preprocessed/plain/list10_c.hpp
C++
mit
2,868
16.487805
66
0.495816
false
module CardHelper def card_element_properties(node, options = {}) { class: dom_class(node, :card), itemscope: '', itemtype: 'http://schema.org/Thing', itemid: node.uuid, itemtype: node.class.schema_path }.merge(options) end def cardtec_header(node) content_tag(:span, node.uuid, itemprop: :uuid) << content_tag(:span, node.ident, itemprop: :ident) << content_tag(:span, node.class.name, itemprop: :class_name) << content_tag(:span, node.path, itemprop: :path) << content_tag(:span, node.created_at, itemprop: :created_at) << content_tag(:span, node.updated_at, itemprop: :updated_at) end end
dinge/dinghub
app/helpers/card_helper.rb
Ruby
mit
705
31.045455
66
0.602837
false
/* * The MIT License * * Copyright 2014 Jon Arney, Ensor Robotics. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.ensor.robots.roboclawdriver; /** * * @author jona */ class CommandReadMainBatteryVoltage extends CommandReadBatteryVoltage { protected CommandReadMainBatteryVoltage(RoboClaw aRoboClaw) { super(aRoboClaw); } @Override protected byte getCommandByte() { return (byte)24; } @Override protected void onResponse(double voltage) { mRoboClaw.setMainBatteryVoltage(voltage); } }
jarney/snackbot
src/main/java/org/ensor/robots/roboclawdriver/CommandReadMainBatteryVoltage.java
Java
mit
1,602
33.826087
80
0.737203
false
package org.kalnee.trivor.insights.web.rest; import com.codahale.metrics.annotation.Timed; import org.kalnee.trivor.insights.domain.insights.Insights; import org.kalnee.trivor.insights.service.InsightService; import org.kalnee.trivor.nlp.domain.ChunkFrequency; import org.kalnee.trivor.nlp.domain.PhrasalVerbUsage; import org.kalnee.trivor.nlp.domain.SentenceFrequency; import org.kalnee.trivor.nlp.domain.WordUsage; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; import java.util.Set; @RestController @RequestMapping(value = "/api/insights") public class InsightsResource { private final InsightService insightService; public InsightsResource(InsightService insightService) { this.insightService = insightService; } @GetMapping public ResponseEntity<Page<Insights>> findByInsightAndImdb(@RequestParam("imdbId") String imdbId, Pageable pageable) { return ResponseEntity.ok().body(insightService.findByImdbId(imdbId, pageable)); } @GetMapping("/summary") @Timed public ResponseEntity<Map<String, Object>> getInsightsSummary(@RequestParam("imdbId") String imdbId) { return ResponseEntity.ok().body(insightService.getInsightsSummary(imdbId)); } @GetMapping("/sentences/frequency") @Timed public ResponseEntity<List<SentenceFrequency>> findSentencesFrequency(@RequestParam("imdbId") String imdbId, @RequestParam(value = "limit", required = false) Integer limit) { return ResponseEntity.ok().body( insightService.findSentencesFrequencyByImdbId(imdbId, limit) ); } @GetMapping("/chunks/frequency") @Timed public ResponseEntity<List<ChunkFrequency>> findChunksFrequency(@RequestParam("imdbId") String imdbId, @RequestParam(value = "limit", required = false) Integer limit) { return ResponseEntity.ok().body( insightService.findChunksFrequencyByImdbId(imdbId, limit) ); } @GetMapping("/phrasal-verbs/usage") @Timed public ResponseEntity<List<PhrasalVerbUsage>> findPhrasalVerbsUsageByImdbId(@RequestParam("imdbId") String imdbId) { return ResponseEntity.ok().body(insightService.findPhrasalVerbsUsageByImdbId(imdbId)); } @GetMapping("/vocabulary/{vocabulary}/frequency") @Timed public ResponseEntity<Map<String, Integer>> findVocabularyFrequencyByImdbId( @PathVariable("vocabulary") String vocabulary, @RequestParam("imdbId") String imdbId, @RequestParam(value = "limit", required = false) Integer limit) { return ResponseEntity.ok().body(insightService.findVocabularyFrequencyByImdbId(vocabulary, imdbId, limit)); } @GetMapping("/vocabulary/{vocabulary}/usage") @Timed public ResponseEntity<List<WordUsage>> findVocabularyUsageByImdbAndSeasonAndEpisode( @PathVariable("vocabulary") String vocabulary, @RequestParam("imdbId") String imdbId, @RequestParam(value = "season", required = false) Integer season, @RequestParam(value = "episode", required = false) Integer episode) { return ResponseEntity.ok().body( insightService.findVocabularyUsageByImdbAndSeasonAndEpisode(vocabulary, imdbId, season, episode) ); } @GetMapping("/{insight}/genres/{genre}") @Timed public ResponseEntity<List<Insights>> findInsightsByGenre( @PathVariable("genre") String genre) { return ResponseEntity.ok().body(insightService.findInsightsByInsightAndGenre(genre)); } @GetMapping("/{insight}/keywords/{keyword}") @Timed public ResponseEntity<List<Insights>> findInsightsByKeyword( @PathVariable("keyword") String keyword) { return ResponseEntity.ok().body(insightService.findInsightsByInsightAndKeyword(keyword)); } }
kalnee/trivor
insights/src/main/java/org/kalnee/trivor/insights/web/rest/InsightsResource.java
Java
mit
4,162
40.62
139
0.698703
false
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalSuppressions.cs"> // Copyright (c) 2017. All rights reserved. Licensed under the MIT license. See LICENSE file in // the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- // This file is used by Code Analysis to maintain SuppressMessage attributes that are applied to this // project. Project-level suppressions either have no target or are given a specific target and // scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0002:Simplify Member Access", Justification = "This is an auto-generated file.", Scope = "member", Target = "~P:Spritely.Foundations.WebApi.Messages.ResourceManager")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Spritely.Foundations.WebApi.WriteLog.Invoke(System.String)", Scope = "member", Target = "Spritely.Foundations.WebApi.BasicWebApiLogPolicy.#.cctor()", Justification = "Colon is used as a separator for log file output - overkill to move this into resources.")]
spritely/Foundations.WebApi
Foundations.WebApi/GlobalSuppressions.cs
C#
mit
1,356
95.714286
412
0.635894
false
#ifndef _VSARDUINO_H_ #define _VSARDUINO_H_ //Board = Arduino Nano w/ ATmega328 #define __AVR_ATmega328p__ #define __AVR_ATmega328P__ #define ARDUINO 105 #define ARDUINO_MAIN #define __AVR__ #define __avr__ #define F_CPU 16000000L #define __cplusplus #define __inline__ #define __asm__(x) #define __extension__ #define __ATTR_PURE__ #define __ATTR_CONST__ #define __inline__ #define __asm__ #define __volatile__ #define __builtin_va_list #define __builtin_va_start #define __builtin_va_end #define __DOXYGEN__ #define __attribute__(x) #define NOINLINE __attribute__((noinline)) #define prog_void #define PGM_VOID_P int typedef unsigned char byte; extern "C" void __cxa_pure_virtual() {;} int serial_putc(char c, FILE *); void printf_begin(void); static void dhcp_status_cb(int s, const uint16_t *dnsaddr); static void resolv_found_cb(char *name, uint16_t *addr); void ___dhcp_status(int s, const uint16_t *); // // void webclient_datahandler(char *data, u16_t len); void webclient_connected(void); void webclient_timedout(void); void webclient_aborted(void); void webclient_closed(void); #include "D:\arduino\arduino-1.0.5\hardware\arduino\cores\arduino\arduino.h" #include "D:\arduino\arduino-1.0.5\hardware\arduino\variants\eightanaloginputs\pins_arduino.h" #include "D:\Projects\arduino-sensor-network\nrf24l01\RF24SensorTestServerMQTT2\RF24SensorTestServerMQTT2.ino" #endif
radzio/arduino-sensor-network
nrf24l01/RF24SensorTestServerMQTT2/Visual Micro/.RF24SensorTestServerMQTT2.vsarduino.h
C
mit
1,396
27.489796
110
0.724928
false
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2018_04_01 module Models # # List of Vpn-Sites # class GetVpnSitesConfigurationRequest include MsRestAzure # @return [Array<SubResource>] List of resource-ids of the vpn-sites for # which config is to be downloaded. attr_accessor :vpn_sites # @return [String] The sas-url to download the configurations for # vpn-sites attr_accessor :output_blob_sas_url # # Mapper for GetVpnSitesConfigurationRequest class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'GetVpnSitesConfigurationRequest', type: { name: 'Composite', class_name: 'GetVpnSitesConfigurationRequest', model_properties: { vpn_sites: { client_side_validation: true, required: false, serialized_name: 'vpnSites', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'SubResourceElementType', type: { name: 'Composite', class_name: 'SubResource' } } } }, output_blob_sas_url: { client_side_validation: true, required: false, serialized_name: 'outputBlobSasUrl', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2018-04-01/generated/azure_mgmt_network/models/get_vpn_sites_configuration_request.rb
Ruby
mit
1,986
28.205882
78
0.504028
false
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Confidence Intervals on the Standard Deviation</title> <link rel="stylesheet" href="../../../../math.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.77.1"> <link rel="home" href="../../../../index.html" title="Math Toolkit 2.2.1"> <link rel="up" href="../cs_eg.html" title="Chi Squared Distribution Examples"> <link rel="prev" href="../cs_eg.html" title="Chi Squared Distribution Examples"> <link rel="next" href="chi_sq_test.html" title="Chi-Square Test for the Standard Deviation"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../cs_eg.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../cs_eg.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="chi_sq_test.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="math_toolkit.stat_tut.weg.cs_eg.chi_sq_intervals"></a><a class="link" href="chi_sq_intervals.html" title="Confidence Intervals on the Standard Deviation">Confidence Intervals on the Standard Deviation</a> </h5></div></div></div> <p> Once you have calculated the standard deviation for your data, a legitimate question to ask is "How reliable is the calculated standard deviation?". For this situation the Chi Squared distribution can be used to calculate confidence intervals for the standard deviation. </p> <p> The full example code &amp; sample output is in <a href="../../../../../../example/chi_square_std_dev_test.cpp" target="_top">chi_square_std_dev_test.cpp</a>. </p> <p> We'll begin by defining the procedure that will calculate and print out the confidence intervals: </p> <pre class="programlisting"><span class="keyword">void</span> <span class="identifier">confidence_limits_on_std_deviation</span><span class="special">(</span> <span class="keyword">double</span> <span class="identifier">Sd</span><span class="special">,</span> <span class="comment">// Sample Standard Deviation</span> <span class="keyword">unsigned</span> <span class="identifier">N</span><span class="special">)</span> <span class="comment">// Sample size</span> <span class="special">{</span> </pre> <p> We'll begin by printing out some general information: </p> <pre class="programlisting"><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="string">"________________________________________________\n"</span> <span class="string">"2-Sided Confidence Limits For Standard Deviation\n"</span> <span class="string">"________________________________________________\n\n"</span><span class="special">;</span> <span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">setprecision</span><span class="special">(</span><span class="number">7</span><span class="special">);</span> <span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">setw</span><span class="special">(</span><span class="number">40</span><span class="special">)</span> <span class="special">&lt;&lt;</span> <span class="identifier">left</span> <span class="special">&lt;&lt;</span> <span class="string">"Number of Observations"</span> <span class="special">&lt;&lt;</span> <span class="string">"= "</span> <span class="special">&lt;&lt;</span> <span class="identifier">N</span> <span class="special">&lt;&lt;</span> <span class="string">"\n"</span><span class="special">;</span> <span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">setw</span><span class="special">(</span><span class="number">40</span><span class="special">)</span> <span class="special">&lt;&lt;</span> <span class="identifier">left</span> <span class="special">&lt;&lt;</span> <span class="string">"Standard Deviation"</span> <span class="special">&lt;&lt;</span> <span class="string">"= "</span> <span class="special">&lt;&lt;</span> <span class="identifier">Sd</span> <span class="special">&lt;&lt;</span> <span class="string">"\n"</span><span class="special">;</span> </pre> <p> and then define a table of significance levels for which we'll calculate intervals: </p> <pre class="programlisting"><span class="keyword">double</span> <span class="identifier">alpha</span><span class="special">[]</span> <span class="special">=</span> <span class="special">{</span> <span class="number">0.5</span><span class="special">,</span> <span class="number">0.25</span><span class="special">,</span> <span class="number">0.1</span><span class="special">,</span> <span class="number">0.05</span><span class="special">,</span> <span class="number">0.01</span><span class="special">,</span> <span class="number">0.001</span><span class="special">,</span> <span class="number">0.0001</span><span class="special">,</span> <span class="number">0.00001</span> <span class="special">};</span> </pre> <p> The distribution we'll need to calculate the confidence intervals is a Chi Squared distribution, with N-1 degrees of freedom: </p> <pre class="programlisting"><span class="identifier">chi_squared</span> <span class="identifier">dist</span><span class="special">(</span><span class="identifier">N</span> <span class="special">-</span> <span class="number">1</span><span class="special">);</span> </pre> <p> For each value of alpha, the formula for the confidence interval is given by: </p> <p> <span class="inlinemediaobject"><img src="../../../../../equations/chi_squ_tut1.svg"></span> </p> <p> Where <span class="inlinemediaobject"><img src="../../../../../equations/chi_squ_tut2.svg"></span> is the upper critical value, and <span class="inlinemediaobject"><img src="../../../../../equations/chi_squ_tut3.svg"></span> is the lower critical value of the Chi Squared distribution. </p> <p> In code we begin by printing out a table header: </p> <pre class="programlisting"><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="string">"\n\n"</span> <span class="string">"_____________________________________________\n"</span> <span class="string">"Confidence Lower Upper\n"</span> <span class="string">" Value (%) Limit Limit\n"</span> <span class="string">"_____________________________________________\n"</span><span class="special">;</span> </pre> <p> and then loop over the values of alpha and calculate the intervals for each: remember that the lower critical value is the same as the quantile, and the upper critical value is the same as the quantile from the complement of the probability: </p> <pre class="programlisting"><span class="keyword">for</span><span class="special">(</span><span class="keyword">unsigned</span> <span class="identifier">i</span> <span class="special">=</span> <span class="number">0</span><span class="special">;</span> <span class="identifier">i</span> <span class="special">&lt;</span> <span class="keyword">sizeof</span><span class="special">(</span><span class="identifier">alpha</span><span class="special">)/</span><span class="keyword">sizeof</span><span class="special">(</span><span class="identifier">alpha</span><span class="special">[</span><span class="number">0</span><span class="special">]);</span> <span class="special">++</span><span class="identifier">i</span><span class="special">)</span> <span class="special">{</span> <span class="comment">// Confidence value:</span> <span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">fixed</span> <span class="special">&lt;&lt;</span> <span class="identifier">setprecision</span><span class="special">(</span><span class="number">3</span><span class="special">)</span> <span class="special">&lt;&lt;</span> <span class="identifier">setw</span><span class="special">(</span><span class="number">10</span><span class="special">)</span> <span class="special">&lt;&lt;</span> <span class="identifier">right</span> <span class="special">&lt;&lt;</span> <span class="number">100</span> <span class="special">*</span> <span class="special">(</span><span class="number">1</span><span class="special">-</span><span class="identifier">alpha</span><span class="special">[</span><span class="identifier">i</span><span class="special">]);</span> <span class="comment">// Calculate limits:</span> <span class="keyword">double</span> <span class="identifier">lower_limit</span> <span class="special">=</span> <span class="identifier">sqrt</span><span class="special">((</span><span class="identifier">N</span> <span class="special">-</span> <span class="number">1</span><span class="special">)</span> <span class="special">*</span> <span class="identifier">Sd</span> <span class="special">*</span> <span class="identifier">Sd</span> <span class="special">/</span> <span class="identifier">quantile</span><span class="special">(</span><span class="identifier">complement</span><span class="special">(</span><span class="identifier">dist</span><span class="special">,</span> <span class="identifier">alpha</span><span class="special">[</span><span class="identifier">i</span><span class="special">]</span> <span class="special">/</span> <span class="number">2</span><span class="special">)));</span> <span class="keyword">double</span> <span class="identifier">upper_limit</span> <span class="special">=</span> <span class="identifier">sqrt</span><span class="special">((</span><span class="identifier">N</span> <span class="special">-</span> <span class="number">1</span><span class="special">)</span> <span class="special">*</span> <span class="identifier">Sd</span> <span class="special">*</span> <span class="identifier">Sd</span> <span class="special">/</span> <span class="identifier">quantile</span><span class="special">(</span><span class="identifier">dist</span><span class="special">,</span> <span class="identifier">alpha</span><span class="special">[</span><span class="identifier">i</span><span class="special">]</span> <span class="special">/</span> <span class="number">2</span><span class="special">));</span> <span class="comment">// Print Limits:</span> <span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">fixed</span> <span class="special">&lt;&lt;</span> <span class="identifier">setprecision</span><span class="special">(</span><span class="number">5</span><span class="special">)</span> <span class="special">&lt;&lt;</span> <span class="identifier">setw</span><span class="special">(</span><span class="number">15</span><span class="special">)</span> <span class="special">&lt;&lt;</span> <span class="identifier">right</span> <span class="special">&lt;&lt;</span> <span class="identifier">lower_limit</span><span class="special">;</span> <span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">fixed</span> <span class="special">&lt;&lt;</span> <span class="identifier">setprecision</span><span class="special">(</span><span class="number">5</span><span class="special">)</span> <span class="special">&lt;&lt;</span> <span class="identifier">setw</span><span class="special">(</span><span class="number">15</span><span class="special">)</span> <span class="special">&lt;&lt;</span> <span class="identifier">right</span> <span class="special">&lt;&lt;</span> <span class="identifier">upper_limit</span> <span class="special">&lt;&lt;</span> <span class="identifier">endl</span><span class="special">;</span> <span class="special">}</span> <span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">endl</span><span class="special">;</span> </pre> <p> To see some example output we'll use the <a href="http://www.itl.nist.gov/div898/handbook/eda/section3/eda3581.htm" target="_top">gear data</a> from the <a href="http://www.itl.nist.gov/div898/handbook/" target="_top">NIST/SEMATECH e-Handbook of Statistical Methods.</a>. The data represents measurements of gear diameter from a manufacturing process. </p> <pre class="programlisting">________________________________________________ 2-Sided Confidence Limits For Standard Deviation ________________________________________________ Number of Observations = 100 Standard Deviation = 0.006278908 _____________________________________________ Confidence Lower Upper Value (%) Limit Limit _____________________________________________ 50.000 0.00601 0.00662 75.000 0.00582 0.00685 90.000 0.00563 0.00712 95.000 0.00551 0.00729 99.000 0.00530 0.00766 99.900 0.00507 0.00812 99.990 0.00489 0.00855 99.999 0.00474 0.00895 </pre> <p> So at the 95% confidence level we conclude that the standard deviation is between 0.00551 and 0.00729. </p> <h5> <a name="math_toolkit.stat_tut.weg.cs_eg.chi_sq_intervals.h0"></a> <span class="phrase"><a name="math_toolkit.stat_tut.weg.cs_eg.chi_sq_intervals.confidence_intervals_as_a_functi"></a></span><a class="link" href="chi_sq_intervals.html#math_toolkit.stat_tut.weg.cs_eg.chi_sq_intervals.confidence_intervals_as_a_functi">Confidence intervals as a function of the number of observations</a> </h5> <p> Similarly, we can also list the confidence intervals for the standard deviation for the common confidence levels 95%, for increasing numbers of observations. </p> <p> The standard deviation used to compute these values is unity, so the limits listed are <span class="bold"><strong>multipliers</strong></span> for any particular standard deviation. For example, given a standard deviation of 0.0062789 as in the example above; for 100 observations the multiplier is 0.8780 giving the lower confidence limit of 0.8780 * 0.006728 = 0.00551. </p> <pre class="programlisting">____________________________________________________ Confidence level (two-sided) = 0.0500000 Standard Deviation = 1.0000000 ________________________________________ Observations Lower Upper Limit Limit ________________________________________ 2 0.4461 31.9102 3 0.5207 6.2847 4 0.5665 3.7285 5 0.5991 2.8736 6 0.6242 2.4526 7 0.6444 2.2021 8 0.6612 2.0353 9 0.6755 1.9158 10 0.6878 1.8256 15 0.7321 1.5771 20 0.7605 1.4606 30 0.7964 1.3443 40 0.8192 1.2840 50 0.8353 1.2461 60 0.8476 1.2197 100 0.8780 1.1617 120 0.8875 1.1454 1000 0.9580 1.0459 10000 0.9863 1.0141 50000 0.9938 1.0062 100000 0.9956 1.0044 1000000 0.9986 1.0014 </pre> <p> With just 2 observations the limits are from <span class="bold"><strong>0.445</strong></span> up to to <span class="bold"><strong>31.9</strong></span>, so the standard deviation might be about <span class="bold"><strong>half</strong></span> the observed value up to <span class="bold"><strong>30 times</strong></span> the observed value! </p> <p> Estimating a standard deviation with just a handful of values leaves a very great uncertainty, especially the upper limit. Note especially how far the upper limit is skewed from the most likely standard deviation. </p> <p> Even for 10 observations, normally considered a reasonable number, the range is still from 0.69 to 1.8, about a range of 0.7 to 2, and is still highly skewed with an upper limit <span class="bold"><strong>twice</strong></span> the median. </p> <p> When we have 1000 observations, the estimate of the standard deviation is starting to look convincing, with a range from 0.95 to 1.05 - now near symmetrical, but still about + or - 5%. </p> <p> Only when we have 10000 or more repeated observations can we start to be reasonably confident (provided we are sure that other factors like drift are not creeping in). </p> <p> For 10000 observations, the interval is 0.99 to 1.1 - finally a really convincing + or -1% confidence. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2006-2010, 2012-2014 Nikhar Agrawal, Anton Bikineev, Paul A. Bristow, Marco Guazzone, Christopher Kormanyos, Hubert Holin, Bruno Lalande, John Maddock, Johan R&#229;de, Gautam Sewani, Benjamin Sobotta, Thijs van den Berg, Daryle Walker and Xiaogang Zhang<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../cs_eg.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../cs_eg.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="chi_sq_test.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
Franky666/programmiersprachen-raytracer
external/boost_1_59_0/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_intervals.html
HTML
mit
19,774
81.788136
902
0.598766
false
#pragma once #include "messages.h" #include "primitives/string_utils.h" // Given pairs of pulse lens from 2 base stations, this class determines the phase for current cycle // Phases are: // 0) Base 1 (B), horizontal sweep // 1) Base 1 (B), vertical sweep // 2) Base 2 (C), horizontal sweep // 3) Base 2 (C), vertical sweep // // TODO: We might want to introduce a more thorough check for a fix, using the average_error_ value. class CyclePhaseClassifier { public: CyclePhaseClassifier(); // Process the pulse lengths for current cycle (given by incrementing cycle_idx). void process_pulse_lengths(uint32_t cycle_idx, const TimeDelta (&pulse_lens)[num_base_stations]); // Get current cycle phase. -1 if phase is not known (no fix achieved). int get_phase(uint32_t cycle_idx); // Reference to a pair of DataFrameBit-s typedef DataFrameBit (&DataFrameBitPair)[num_base_stations]; // Get updated data bits from the pulse lens for current cycle. // Both bits are always returned, but caller needs to make sure they were updated this cycle by // checking DataFrameBit.cycle_idx == cycle_idx. DataFrameBitPair get_data_bits(uint32_t cycle_idx, const TimeDelta (&pulse_lens)[num_base_stations]); // Reset the state of this classifier - needs to be called if the cycle fix was lost. void reset(); // Print debug information. virtual bool debug_cmd(HashedWord *input_words); virtual void debug_print(PrintStream &stream); private: float expected_pulse_len(bool skip, bool data, bool axis); uint32_t prev_full_cycle_idx_; uint32_t phase_history_; int fix_level_; uint32_t phase_shift_; float pulse_base_len_; DataFrameBit bits_[num_base_stations]; float average_error_; bool debug_print_state_; };
ashtuchkin/vive-diy-position-sensor
include/cycle_phase_classifier.h
C
mit
1,815
33.245283
105
0.699725
false
<?php # MetInfo Enterprise Content Management System # Copyright (C) MetInfo Co.,Ltd (http://www.metinfo.cn). All rights reserved. require_once '../login/login_check.php'; if($action=='modify'){ $shortcut=array(); $query="select * from $met_language where value='$name' and lang='$lang'"; $lang_shortcut=$db->get_one($query); $shortcut['name']=$lang_shortcut?'lang_'.$lang_shortcut['name']:urlencode($name); $shortcut['url']=$url; $shortcut['bigclass']=$bigclass; $shortcut['field']=$field; $shortcut['type']='2'; $shortcut['list_order']=$list_order; $shortcut['protect']='0'; $shortcut['hidden']='0'; foreach($shortcut_list as $key=>$val){ $shortcut_list[$key][name]=$shortcut_list[$key][lang]; } $shortcut_list[]=$shortcut; change_met_cookie('metinfo_admin_shortcut',$shortcut_list); save_met_cookie(); $query="update $met_admin_table set admin_shortcut='".json_encode($shortcut_list)."' where admin_id='$metinfo_admin_name'"; $db->query($query); echo '<script type="text/javascript">parent.window.location.reload();</script>'; die(); //metsave('../system/shortcut.php?anyid='.$anyid.'&lang='.$lang.'&cs='.$cs); }else{ $query="select * from $met_app where download=1"; $app=$db->get_all($query); $css_url="../templates/".$met_skin."/css"; $img_url="../templates/".$met_skin."/images"; include template('system/shortcut_editor'); footer(); } # This program is an open source system, commercial use, please consciously to purchase commercial license. # Copyright (C) MetInfo Co., Ltd. (http://www.metinfo.cn). All rights reserved. ?>
maicong/OpenAPI
MetInfo5.2/admin/system/shortcut_editor.php
PHP
mit
1,564
40.184211
124
0.678389
false
--- layout: post title: 循环队列 date: 2017-05-13 10:54:37 categories: Java --- # Java实现的循环队列 `队列`具有先进先出的特点,本文所说的`循环队列`(以下简称队列)的长度是一定的(可以扩容),如果队列满了,新来的元素会覆盖队列中最先来的元素。 它的使用场景是对内存占用有要求的情况下按序缓存一些数据,比如直播中的弹幕。 * 注意:此实现非线程安全 ```java import java.util.ArrayList; import java.util.List; /** * 容量受限的队列,在队列已满的情况下,新入队的元素会覆盖最老的元素。<br> * <font color="red">此类非线程安全</font> * * @author rongzhisheng * * @param <E> */ public class CircleQueue<E> { private static final int DEFAULT_CAPACITY = 10; private int capacity; private int head;// 即将出队的位置 private int tail;// 即将入队的位置 private List<E> queue; private boolean isFull;// 队列是否已满,队列空和满的时候head==tail public CircleQueue() { this(DEFAULT_CAPACITY); } public CircleQueue(int capacity) { this.capacity = capacity; queue = new ArrayList<>(this.capacity); head = tail = 0; } /** * 入队 * * @param e * @return 是否丢弃了最旧的元素 */ public boolean add(E e) { if (isFull) { head = addIndex(head); addOrSet(e, tail); tail = head; return true; } addOrSet(e, tail); tail = addIndex(tail); if (head == tail) { isFull = true; } return false; } public E poll() { if (!isFull && head == tail) { return null; } E e = queue.get(head); queue.set(head, null); head = addIndex(head); isFull = false; return e; } public int size() { if (!isFull && head == tail) { return 0; } if (isFull) { return capacity; } int i = 0; int h = head; while (h != tail) { i++; h = addIndex(h); } return i; } public int capacity() { return capacity; } public E element(int index) { if (index < 0 || index >= size()) { throw new IllegalArgumentException(); } index = addIndex(head + index - 1); return queue.get(index); } public boolean isEmpty() { return size() == 0; } public List<E> getList() { List<E> list = new ArrayList<>(); final int size = size(); for (int i = 0; i < size; i++) { list.add(element(i)); } return list; } public void clean() { head = tail = 0; isFull = false; queue.clear(); } public void grow(int newCapacity) { if (newCapacity <= capacity) { return; } List<E> data = getList(); queue.clear(); queue.addAll(data); head = 0; tail = head + queue.size(); capacity = newCapacity; isFull = false; } @Override public String toString() { return getList().toString(); } private void addOrSet(E e, int index) { if (queue.size() > index) { queue.set(index, e); return; } if (queue.size() == index) { queue.add(e); return; } throw new IllegalStateException(); } private int addIndex(int i) { return (i + 1) % capacity; } public static void main(String[] args) { int a = 1; CircleQueue<Integer> queue = new CircleQueue<Integer>(5); queue.grow(8); queue.grow(10); for (int i = a; i < a + 6; i++) { queue.add(i); } a += 6; System.out.println(queue); for (int i = a; i < a + 6; i++) { queue.add(i); } a += 6; System.out.println(queue); queue.grow(10); for (int i = a; i < a + 6; i++) { queue.add(i); } a += 6; System.out.println(queue); for (int i = 0; i < 5; i++) { System.out.println(queue.poll()); } System.out.println(queue); queue.clean(); for (int i = 0; i < 3; i++) { queue.add(i); } System.out.println(queue); } } ```
wittyLuzhishen/wittyLuzhishen.github.io
_posts/2017-05-13-circlequeue.md
Markdown
mit
4,557
19.71
72
0.477179
false
/* * The MIT License (MIT) * * Copyright (c) 2015 maldicion069 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ 'use strict'; exports.init = function(req, res){ //res.write("joder\n"); //res.write(req.csrfToken()); //res.end(); req.app.db.models.Experiment.find({}) .select("tableList name uploadedBy dateDevelopment id name neuronType") // Hay que sacar también nombre y tipo D= .exec(function(err, exps) { if(err) { res.send("Error"); } else { console.log(exps); res.render('account/experiments/compare/stage1', { code: req.csrfToken(), experiments: exps }); } }); }; /** * Esta función sirve para que, dado * */ exports.second = function(req, res) { console.log("BODY: " + req.body.fcbklist_value); if(req.body.fcbklist_value.length < 2) { res.redirect("/account/experiments/compare/"); } else { //res.send(req.body); var orArray = []; req.body.fcbklist_value.forEach(function(idExp) { orArray.push({_id: idExp}); }); console.log(orArray); req.app.db.models.Experiment.find({$or: orArray}) .select("tableList name createdBy dateDevelopment id") //.populate("tableList", "id") .populate("createdBy", "username") .exec(function(err, exps) { console.log(err); console.log(JSON.stringify(exps)); res.render("account/experiments/compare/stage2", { experiments: exps, code: req.csrfToken() }); }); } //["54514c6a4650426d2a9bf056","5451853c745acc0a412abf68"] // Con esta lista de ids, lo que hacemos es sacar: // 1. Cada experimento con: // name uploadedBy dateDevelopment id // y el identificador de cada tabla del experimento. // 2. Con esos datos, montamos algo guay con radio button. }; /** * En este método recibimos los id's de los experimentos * y la tabla seleccionada * Por cada tabla, sacamos las columnas comunes entre ellas e * imprimimos los gráficos de una vez */ exports.third = function(req, res) { var peticiones = req.body.tab; console.log(peticiones); var arr = []; /*var mapMatch = { "a": null, "b": null, "c": null, "Datos2": null }*/ var params = req.app.utility.variables; var tabs = []; var headersPaths = []; var data = {}; // To save the return to view var Set = req.app.utility.Set; var commons = new Set(); var async = require('async'); async.series([ // First read data from database and save function(callback){ console.log("ejecuto 1"); async.each(peticiones, function(tabid, call) { console.log(tabid); req.app.db.models.TableExperiment.findById(tabid).populate("assignedTo", "name neuronType createdBy dateDevelopment description").exec(function(err, tab) { var username = ""; async.series({ first: function(call2) { console.log("Paso 1"); console.log("Jodeeer, " + tab.assignedTo.createdBy); /*console.log(tab); async.each(tab, function(tab_, call3) { console.log("Buscamos username " + tab_); req.app.db.models.User.findById(tab_.createdBy._id).select("username").exec(function(err, user) { console.log("USER : " + user); tab.createdBy = user.username; call3(); }); });*/ req.app.db.models.User.findById(tab.assignedTo.createdBy).select("username").exec(function(err, user) { console.log("USER : " + user); tab["username"] = user.username; username = user.username; //tab.username = user.username; call2(); }); }, second: function(call2) { console.log("Paso 2"); // TODO: Controlar "err" var tab_ = {}; tab_.assignedTo = { _id: tab.assignedTo._id, username: username, createdBy: tab.assignedTo.createdBy, name: tab.assignedTo.name, neuronType: tab.assignedTo.neuronType, dateDevelopment: tab.assignedTo.dateDevelopment, description: tab.assignedTo.description }; tab_.id = tab._id; tab_.matrix = tab.matrix; tab_.headers = tab.headers; /* assignedTo: { _id: 545bde715e4a5d4a4089ad21, createdBy: 545bde535e4a5d4a4089ad1f, name: 'Mi physiological', neuronType: 'PHYSIOLOGICAL' }, _id: 545bde715e4a5d4a4089ad52, __v: 0, matrix: */ console.log("SECOND : " + tab_); // Añadimos la tabla al sistema //console.log("Añado " + tab); tabs.push(tab_); // Recorro las cabeceras y genero un mapa con k(header) y v(position) var mapMatch = {}; console.log(tab.headers); tab.headers.forEach(function(header, pos) { if(params.contains(header)) { mapMatch[header] = pos; } }); //console.log("Añado " + JSON.stringify(mapMatch)); headersPaths.push(mapMatch); // Guardamos el mapeo call2(); } }, function(err, results) { call(); }); }); }, function(err) { callback(); }); }, // Filter columns that I use to compare table's experiment function(callback) { console.log("Tengo : " + tabs.length); console.log("Tengo : " + headersPaths.length); // Guardamos todos los valores de "params" en "data" data.headers = {}; params.get().forEach(function(value) { data.headers[value] = [];//undefined; }); console.log(JSON.stringify(data)); // Creamos el attr "exps" dentro de "data" data.exps = []; // Ahora por cada experimento, cargamos los datos correspondientes headersPaths.forEach(function(headerPath, index) { console.log("--------- Empezamos a recorrer con header " + headerPath + " ---------"); var posHeader = 0; Object.keys(headerPath).forEach(function(key) { console.log(key + " <=> " + headerPath[key]); //tabs.forEach(function(tab, ii) { tabs[index].matrix.forEach(function(matrix, area) { //console.log("Header: " + key + "\tNº Tab: " + ii + "\tArea: " + area); data.headers[key][area] = data.headers[key][area] || [0]; // Si existe se queda igual, si no, se añade array data.headers[key][area].push(matrix.data[posHeader]); }); //}); /*var infoData = []; tabs[index].matrix.forEach(function(matrix, area) { infoData.push(matrix.data[posHeader]); }); //console.log(infoData); console.log("Inserta del index " + posHeader); data.headers[key].push(infoData);*/ posHeader++; }); // Volcamos la información del experimento asociado a cada tabla data.exps.push(tabs[index].assignedTo); }); console.log("----------------------"); console.log("----------------------"); //console.log(data); console.log("----------------------"); console.log("----------------------"); /*async.each(arr, function(tab, call) { tab.headers.forEach(function(header, position) { //if(mapMatch[header] != undefined) { if(header in tab.mapMatch) { tab.mapMatch[header] = position; } }); // Remove all columns that not contains in mapMatch //tab.mapMatch.forEach(function(position) { //}); call(); });*/ callback(); } ], // finish callback function(err, results){ console.log("FIN: " + arr.length); console.log(params.intersect(commons)); //res.send(data); /*var ret = { data: data }; res.send(ret);*/ console.log("----------------------"); console.log("----------------------"); console.log("----------------------"); console.log("----------------------"); console.log(JSON.stringify(data)); res.render("account/experiments/compare/stage3", { data: data, code: req.csrfToken(), id: 0 }); }); }; // TODO: No funciona bien T.T /*exports.downloadHTML = function(req, res) { phantom = require('phantom') phantom.create(function(ph){ ph.createPage(function(page) { page.open("http://www.google.com", function(status) { page.render('google.pdf', function(){ console.log('Page Rendered'); ph.exit(); }); }); }); }); };*/
maldicion069/HBPWebNodeJs
views/account/experiments/compare/stages.js
JavaScript
mit
9,900
27.257143
163
0.560667
false
#ifndef ECLAIR_DIRECTORY_H # define ECLAIR_DIRECTORY_H # include "eclair.h" # include <sys/types.h> # include <dirent.h> namespace Eclair { struct DirectoryFile { std::string name; bool is_directory; bool is_regular_file; }; class Directory { private: std::string _dirname; DIR *_dir = nullptr; std::string _error_str; DirectoryFile _file; explicit Directory(); public: explicit Directory(const std::string& dir); virtual ~Directory() noexcept; bool open() noexcept; DirectoryFile *next() noexcept; inline std::string error() const noexcept { return (this->_error_str); } inline std::string path() const noexcept { return (this->_dirname); } static inline std::string current() noexcept { char str[1025]; return (getcwd(str, 1024)); } }; } #endif
alex8092/eclaircpp
include/directory.h
C
mit
824
18.186047
48
0.660194
false