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
|
---|---|---|---|---|---|
module JSE
class FieldValueTransform
def initialize(field)
@field = field
end
def apply(hash)
hash[@field]
end
end
end
| rhburrows/jse | lib/jse/field_value_transform.rb | Ruby | mit | 152 |
/**
* Returns the reverse of a string
* @param {String} string
* @return {String}
*/
function reverseString (string) {
return string.split('').reverse().join('')
}
/**
* countChars - Returns an object with character frequency
* @param {String} string
* @return {Object}
*/
function charCount (string) {
const charCounts = {}
for (let i = 0; i < string.length; i++) {
const char = string[i]
if (charCounts[char]) {
charCounts[char]++
} else {
charCounts[char] = 1
}
}
return charCounts
}
module.exports = {
reverse: reverseString,
charCount: charCount
}
| TylerK/ctci | utils/strings.js | JavaScript | mit | 609 |
---
layout: page
title: Rain Exquisite Air Party
date: 2016-05-24
author: Johnny West
tags: weekly links, java
status: published
summary: Nunc accumsan convallis lacinia. Praesent.
banner: images/banner/people.jpg
booking:
startDate: 11/05/2016
endDate: 11/07/2016
ctyhocn: AUSMFHX
groupCode: REAP
published: true
---
Donec at ante interdum massa pharetra rutrum. Integer sed purus auctor, lacinia enim sit amet, tempus sem. Vestibulum sagittis est eu eros congue, sit amet sollicitudin augue commodo. Duis dictum nec ipsum eget semper. Curabitur eu consequat neque. Suspendisse quis gravida mi. In in venenatis nisl. Phasellus pretium quam libero, a tincidunt arcu vestibulum at. Aenean sit amet molestie velit. Nulla sit amet porta sapien, sit amet euismod diam. Nullam placerat eros eget est pretium porttitor. Maecenas sed tincidunt justo.
* Aliquam cursus ipsum et dui maximus posuere
* Phasellus a lacus sit amet tortor aliquam sollicitudin
* Nam eget risus sit amet turpis pharetra ullamcorper.
Donec et luctus ante. Curabitur efficitur molestie lorem, id auctor felis sodales in. Phasellus eu enim nec tortor consectetur viverra id eu orci. Nam tincidunt rutrum orci, rutrum egestas velit egestas vitae. In eget aliquet nisl. Sed placerat mollis ante sit amet molestie. Duis imperdiet non libero ut pharetra. Proin porta metus id auctor volutpat. Quisque dictum gravida scelerisque. Proin vehicula arcu risus, vitae congue magna suscipit vel. Etiam lobortis mauris eu neque porta pulvinar.
| KlishGroup/prose-pogs | pogs/A/AUSMFHX/REAP/index.md | Markdown | mit | 1,508 |
package com.blackstone.goldenquran.models;
/**
* Created by Abdullah on 6/11/2017.
*/
public class ChangeIconEvent {
}
| salemoh/GoldenQuranAndroid | app/src/main/java/com/blackstone/goldenquran/models/ChangeIconEvent.java | Java | mit | 123 |
<?php
/*
Unsafe sample
input : Get a serialize string in POST and unserialize it
sanitize : use of the function htmlspecialchars. Sanitizes the query but has a high chance to produce unexpected results
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$string = $_POST['UserData'] ;
$tainted = unserialize($string);
$tainted = htmlspecialchars($tainted, ENT_QUOTES);
//flaw
$var = header("'Location: " . $tainted .".php'");
?> | stivalet/PHP-Vulnerability-test-suite | URF/CWE_601/unsafe/CWE_601__unserialize__func_htmlspecialchars__header_file_name-concatenation_simple_quote.php | PHP | mit | 1,349 |
using Newtonsoft.Json;
using System;
namespace ShopifySharp.Filters
{
public class ShopifyPaymentsDisputeFilter : ListFilter
{
/// <summary>
/// Return only disputes before the specified ID.
/// </summary>
[JsonProperty("last_id")]
public long? LastId { get; set; }
/// <summary>
/// Return only disputes with the specified status.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
/// <summary>
/// Return only disputes with the specified initiated_at date.
/// </summary>
[JsonProperty("initiated_at ")]
public DateTimeOffset? InitiatedAt { get; set; }
}
} | addsb/ShopifySharp | ShopifySharp/Filters/ShopifyPaymentsDisputeFilter.cs | C# | mit | 719 |
package DBJPA;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class);
CustomerRepository repository = context.getBean(CustomerRepository.class);
// save a couple of customers
repository.save(new Customer("Jack", "Bauer"));
repository.save(new Customer("Chloe", "O'Brian"));
repository.save(new Customer("Kim", "Bauer"));
repository.save(new Customer("David", "Palmer"));
repository.save(new Customer("Michelle", "Dessler"));
// fetch all customers
Iterable<Customer> customers = repository.findAll();
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : customers) {
System.out.println(customer);
}
System.out.println();
// fetch an individual customer by ID
Customer customer = repository.findOne(1L);
System.out.println("Customer found with findOne(1L):");
System.out.println("--------------------------------");
System.out.println(customer);
System.out.println();
// fetch customers by last name
List<Customer> bauers = repository.findByLastName("Bauer");
System.out.println("Customer found with findByLastName('Bauer'):");
System.out.println("--------------------------------------------");
for (Customer bauer : bauers) {
System.out.println(bauer);
}
context.close();
}
}
| jamescheng16/M2-E-service | J2EE/dbjpa/src/main/java/DBJPA/Application.java | Java | mit | 1,936 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="sv">
<head>
<!-- Generated by javadoc (1.8.0_77) on Wed Apr 27 18:22:01 CEST 2016 -->
<title>TrackServiceImplTest</title>
<meta name="date" content="2016-04-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="TrackServiceImplTest";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../limmen/business/services/implementations/TrackServiceImpl.html" title="class in limmen.business.services.implementations"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?limmen/business/services/implementations/TrackServiceImplTest.html" target="_top">Frames</a></li>
<li><a href="TrackServiceImplTest.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">limmen.business.services.implementations</div>
<h2 title="Class TrackServiceImplTest" class="title">Class TrackServiceImplTest</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>limmen.business.services.implementations.TrackServiceImplTest</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">TrackServiceImplTest</span>
extends java.lang.Object</pre>
<div class="block">Unit test-suite for the track service implementation</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Kim Hammar on 2016-03-24.</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../limmen/business/services/implementations/TrackServiceImplTest.html#TrackServiceImplTest--">TrackServiceImplTest</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../limmen/business/services/implementations/TrackServiceImplTest.html#setUp--">setUp</a></span>()</code>
<div class="block">This method is used for initializing the test, and called before tests are executed.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../limmen/business/services/implementations/TrackServiceImplTest.html#testCreateNewTrack--">testCreateNewTrack</a></span>()</code>
<div class="block">Test of the createNewTrack method</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../limmen/business/services/implementations/TrackServiceImplTest.html#testGetAllTracks--">testGetAllTracks</a></span>()</code>
<div class="block">Test for the getAllTracks method</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../limmen/business/services/implementations/TrackServiceImplTest.html#testGetTrack--">testGetTrack</a></span>()</code>
<div class="block">Test of the getTrack method</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../limmen/business/services/implementations/TrackServiceImplTest.html#testUpdateTrack--">testUpdateTrack</a></span>()</code>
<div class="block">Test of the updateTrack method</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="TrackServiceImplTest--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>TrackServiceImplTest</h4>
<pre>public TrackServiceImplTest()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="setUp--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setUp</h4>
<pre>public void setUp()</pre>
<div class="block">This method is used for initializing the test, and called before tests are executed.</div>
</li>
</ul>
<a name="testGetAllTracks--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>testGetAllTracks</h4>
<pre>public void testGetAllTracks()</pre>
<div class="block">Test for the getAllTracks method</div>
</li>
</ul>
<a name="testGetTrack--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>testGetTrack</h4>
<pre>public void testGetTrack()</pre>
<div class="block">Test of the getTrack method</div>
</li>
</ul>
<a name="testCreateNewTrack--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>testCreateNewTrack</h4>
<pre>public void testCreateNewTrack()</pre>
<div class="block">Test of the createNewTrack method</div>
</li>
</ul>
<a name="testUpdateTrack--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>testUpdateTrack</h4>
<pre>public void testUpdateTrack()</pre>
<div class="block">Test of the updateTrack method</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../limmen/business/services/implementations/TrackServiceImpl.html" title="class in limmen.business.services.implementations"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?limmen/business/services/implementations/TrackServiceImplTest.html" target="_top">Frames</a></li>
<li><a href="TrackServiceImplTest.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Limmen/chinook | java_backend/chinook_rest/javadoc/limmen/business/services/implementations/TrackServiceImplTest.html | HTML | mit | 11,728 |
<?php
namespace Application\Modules\Rest\Controllers;
/**
* Class PagesController
*
* @package Application\Modules\Rest
* @subpackage Controllers
* @since PHP >=5.6
* @version 1.0
* @author Stanislav WEB | Lugansk <[email protected]>
* @filesource /Application/Modules/Rest/Controllers/PagesController.php
*/
class PagesController extends ControllerBase {
/**
* REST cache container
*
* @var \Application\Modules\Rest\Services\RestCacheService $cache
*/
protected $cache;
/**
* Cache key
*
* @var string $key
*/
protected $key;
/**
* Initialize cache service
*/
public function initialize() {
$this->cache = $this->di->get('RestCache');
$this->key = ($this->request->isGet() && $this->config->cache->enable === true)
? md5($this->request->getUri()) : null;
}
/**
* GET Pages action
*/
public function getAction() {
$this->response = $this->cache->exists($this->key) ? $this->cache->get($this->key)
: $this->cache->set(
$this->getDI()->get('PageMapper')->read($this->rest->getParams()),
$this->key,
true
);
}
} | stanislav-web/Phalcon-development | Application/Modules/Rest/Controllers/PagesController.php | PHP | mit | 1,242 |
const redux = (reducer, initialState) => {
let currentState = initialState;
const dispatch = action => {
currentState = reducer(currentState, action);
};
const getState = () => currentState;
return ({
dispatch,
getState,
});
};
const store = redux(reducer, initialState);
const action = { type, payload };
store.dispatch(action);
store.getState();
| adispring/reduce-share | code/redux3.js | JavaScript | mit | 375 |
require 'slop'
require 'pathname'
require 'passwords/version'
require 'passwords/language'
require 'passwords/wordlist'
require 'passwords/generator'
module Passwords
end
| bjoernalbers/passwords | lib/passwords.rb | Ruby | mit | 172 |
// Kuko Framework - https://github.com/Rejcx/Kuko - Rachel J. Morris - MIT License
#ifndef _KUKO_BASEENTITY
#define _KUKO_BASEENTITY
#include <SDL.h>
#include "../base/Sprite.hpp"
#include "../base/PositionRect.hpp"
namespace kuko
{
class BaseEntity
{
public:
virtual void Setup( const std::string& name, SDL_Texture* texture, FloatRect pos );
virtual void SetFrame( IntRect frame );
virtual void Cleanup();
virtual void Update();
virtual void Draw();
virtual void DrawWithOffset( float offsetX, float offsetY );
virtual kuko::FloatRect GetPosition() const;
void SetPosition( float x, float y );
void SetPosition( const FloatRect& pos );
bool IsCollision( const BaseEntity& other );
bool IsCollision( const FloatRect& otherRect );
bool IsClicked( int x, int y );
bool IsSolid();
void SetSolid( bool val );
protected:
std::string m_id;
kuko::FloatRect m_position;
Sprite m_sprite;
bool m_isSolid;
void UpdateSprite();
};
}
#endif
| Rejcx/Raheeda | entities/BaseEntity.hpp | C++ | mit | 1,025 |
import Ember from 'ember';
import CrossModelsRoutingParentMixin from 'ember-cross-models-routing/mixins/cross-models-routing-parent';
import { module, test } from 'qunit';
module('Unit | Mixin | cross models routing parent');
// Replace this with your real tests.
test('it works', function(assert) {
let CrossModelsRoutingParentObject = Ember.Object.extend(CrossModelsRoutingParentMixin);
let subject = CrossModelsRoutingParentObject.create();
assert.ok(subject);
});
| onechiporenko/ember-cross-models-routing | tests/unit/mixins/cross-models-routing-parent-test.js | JavaScript | mit | 476 |
/* Copyright (c) 2010 Michael Lidgren
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace MELHARFI
{
namespace Lidgren.Network
{
internal enum NetMessageType : byte
{
Unconnected = 0,
UserUnreliable = 1,
UserSequenced1 = 2,
UserSequenced2 = 3,
UserSequenced3 = 4,
UserSequenced4 = 5,
UserSequenced5 = 6,
UserSequenced6 = 7,
UserSequenced7 = 8,
UserSequenced8 = 9,
UserSequenced9 = 10,
UserSequenced10 = 11,
UserSequenced11 = 12,
UserSequenced12 = 13,
UserSequenced13 = 14,
UserSequenced14 = 15,
UserSequenced15 = 16,
UserSequenced16 = 17,
UserSequenced17 = 18,
UserSequenced18 = 19,
UserSequenced19 = 20,
UserSequenced20 = 21,
UserSequenced21 = 22,
UserSequenced22 = 23,
UserSequenced23 = 24,
UserSequenced24 = 25,
UserSequenced25 = 26,
UserSequenced26 = 27,
UserSequenced27 = 28,
UserSequenced28 = 29,
UserSequenced29 = 30,
UserSequenced30 = 31,
UserSequenced31 = 32,
UserSequenced32 = 33,
UserReliableUnordered = 34,
UserReliableSequenced1 = 35,
UserReliableSequenced2 = 36,
UserReliableSequenced3 = 37,
UserReliableSequenced4 = 38,
UserReliableSequenced5 = 39,
UserReliableSequenced6 = 40,
UserReliableSequenced7 = 41,
UserReliableSequenced8 = 42,
UserReliableSequenced9 = 43,
UserReliableSequenced10 = 44,
UserReliableSequenced11 = 45,
UserReliableSequenced12 = 46,
UserReliableSequenced13 = 47,
UserReliableSequenced14 = 48,
UserReliableSequenced15 = 49,
UserReliableSequenced16 = 50,
UserReliableSequenced17 = 51,
UserReliableSequenced18 = 52,
UserReliableSequenced19 = 53,
UserReliableSequenced20 = 54,
UserReliableSequenced21 = 55,
UserReliableSequenced22 = 56,
UserReliableSequenced23 = 57,
UserReliableSequenced24 = 58,
UserReliableSequenced25 = 59,
UserReliableSequenced26 = 60,
UserReliableSequenced27 = 61,
UserReliableSequenced28 = 62,
UserReliableSequenced29 = 63,
UserReliableSequenced30 = 64,
UserReliableSequenced31 = 65,
UserReliableSequenced32 = 66,
UserReliableOrdered1 = 67,
UserReliableOrdered2 = 68,
UserReliableOrdered3 = 69,
UserReliableOrdered4 = 70,
UserReliableOrdered5 = 71,
UserReliableOrdered6 = 72,
UserReliableOrdered7 = 73,
UserReliableOrdered8 = 74,
UserReliableOrdered9 = 75,
UserReliableOrdered10 = 76,
UserReliableOrdered11 = 77,
UserReliableOrdered12 = 78,
UserReliableOrdered13 = 79,
UserReliableOrdered14 = 80,
UserReliableOrdered15 = 81,
UserReliableOrdered16 = 82,
UserReliableOrdered17 = 83,
UserReliableOrdered18 = 84,
UserReliableOrdered19 = 85,
UserReliableOrdered20 = 86,
UserReliableOrdered21 = 87,
UserReliableOrdered22 = 88,
UserReliableOrdered23 = 89,
UserReliableOrdered24 = 90,
UserReliableOrdered25 = 91,
UserReliableOrdered26 = 92,
UserReliableOrdered27 = 93,
UserReliableOrdered28 = 94,
UserReliableOrdered29 = 95,
UserReliableOrdered30 = 96,
UserReliableOrdered31 = 97,
UserReliableOrdered32 = 98,
Unused1 = 99,
Unused2 = 100,
Unused3 = 101,
Unused4 = 102,
Unused5 = 103,
Unused6 = 104,
Unused7 = 105,
Unused8 = 106,
Unused9 = 107,
Unused10 = 108,
Unused11 = 109,
Unused12 = 110,
Unused13 = 111,
Unused14 = 112,
Unused15 = 113,
Unused16 = 114,
Unused17 = 115,
Unused18 = 116,
Unused19 = 117,
Unused20 = 118,
Unused21 = 119,
Unused22 = 120,
Unused23 = 121,
Unused24 = 122,
Unused25 = 123,
Unused26 = 124,
Unused27 = 125,
Unused28 = 126,
Unused29 = 127,
LibraryError = 128,
Ping = 129, // used for RTT calculation
Pong = 130, // used for RTT calculation
Connect = 131,
ConnectResponse = 132,
ConnectionEstablished = 133,
Acknowledge = 134,
Disconnect = 135,
Discovery = 136,
DiscoveryResponse = 137,
NatPunchMessage = 138, // send between peers
NatIntroduction = 139, // send to master server
NatIntroductionConfirmRequest = 142,
NatIntroductionConfirmed = 143,
ExpandMTURequest = 140,
ExpandMTUSuccess = 141,
}
}
} | melharfi/MELHARFI-2D-Game-Engine | Project/MELHARFI/LidgrenNetwork/NetMessageType.cs | C# | mit | 6,625 |
import {
moduleForModel,
test
} from 'ember-qunit';
moduleForModel('payment-method', 'PaymentMethod', {
// Specify the other units that are required for this test.
needs: []
});
test('it exists', function() {
var model = this.subject();
// var store = this.store();
ok(!!model);
});
| hhff/ember-cli-spree-core | tests/unit/models/payment-method-test.js | JavaScript | mit | 299 |
using System;
namespace CronScheduling
{
// http://ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx
/// <summary>
/// For testing.
/// </summary>
internal static class SystemTime
{
public static Func<DateTime> NowFn = () => DateTime.UtcNow;
public static DateTime Now
{
get { return NowFn(); }
}
}
}
| sergeyt/CronDaemon | src/CronDaemon/SystemTime.cs | C# | mit | 342 |
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<meta http-equiv="refresh" content="0; URL=http://www.grazr.com/config.html">
</head>
<body>
</body>
</html>
| mesadynamics/hypercube-all | web/hypercube/publishers/pages/Grazr.html | HTML | mit | 198 |
module Tolk
class Translation < ActiveRecord::Base
self.table_name = "tolk_translations"
scope :containing_text, lambda {|query| where("tolk_translations.text LIKE ?", "%#{query}%") }
serialize :text
serialize :previous_text
validate :validate_text_not_nil, :if => proc {|r| r.primary.blank? && !r.explicit_nil && !r.boolean?}
validate :check_matching_variables, :if => proc { |tr| tr.primary_translation.present? }
validates_uniqueness_of :phrase_id, :scope => :locale_id
belongs_to :phrase, :class_name => 'Tolk::Phrase'
belongs_to :locale, :class_name => 'Tolk::Locale'
validates_presence_of :locale_id
before_save :set_primary_updated
before_save :set_previous_text
attr_accessor :primary
before_validation :fix_text_type, :unless => proc {|r| r.primary }
attr_accessor :explicit_nil
before_validation :set_explicit_nil
def boolean?
text.is_a?(TrueClass) || text.is_a?(FalseClass) || text == 't' || text == 'f'
end
def up_to_date?
not out_of_date?
end
def out_of_date?
primary_updated?
end
def primary_translation
@_primary_translation ||= begin
if locale && !locale.primary?
phrase.translations.primary
end
end
end
def text=(value)
value = value.to_s if value.kind_of?(Fixnum)
if primary_translation && primary_translation.boolean?
value = case value.to_s.downcase.strip
when 'true', 't'
true
when 'false', 'f'
false
else
self.explicit_nil = true
nil
end
super unless value == text
else
value = value.strip if value.is_a?(String)
super unless value.to_s == text
end
end
def value
if text.is_a?(String) && /^\d+$/.match(text)
text.to_i
elsif (primary_translation || self).boolean?
%w[true t].member?(text.to_s.downcase.strip)
else
text
end
end
def self.detect_variables(search_in)
variables = case search_in
when String then Set.new(search_in.scan(/\{\{(\w+)\}\}/).flatten + search_in.scan(/\%\{(\w+)\}/).flatten)
when Array then search_in.inject(Set[]) { |carry, item| carry + detect_variables(item) }
when Hash then search_in.values.inject(Set[]) { |carry, item| carry + detect_variables(item) }
else Set[]
end
# delete special i18n variable used for pluralization itself (might not be used in all values of
# the pluralization keys, but is essential to use pluralization at all)
if search_in.is_a?(Hash) && Tolk::Locale.pluralization_data?(search_in)
variables.delete_if {|v| v == 'count' }
else
variables
end
end
def variables
self.class.detect_variables(text)
end
def variables_match?
self.variables == primary_translation.variables
end
private
def set_explicit_nil
if self.text == '~'
self.text = nil
self.explicit_nil = true
end
end
def fix_text_type
if primary_translation.present?
if self.text.is_a?(String) && !primary_translation.text.is_a?(String)
self.text = begin
YAML.load(self.text.strip)
rescue ArgumentError
nil
end
end
if primary_translation.boolean?
self.text = case self.text.to_s.strip
when 'true'
true
when 'false'
false
else
nil
end
elsif primary_translation.text.class != self.text.class
self.text = nil
end
end
true
end
def set_primary_updated
self.primary_updated = false
true
end
def set_previous_text
self.previous_text = self.text_was if text_changed?
true
end
def check_matching_variables
unless variables_match?
if primary_translation.variables.empty?
self.errors.add(:variables, "The primary translation does not contain substitutions, so this should neither.")
else
self.errors.add(:variables, "The translation should contain the substitutions of the primary translation: (#{primary_translation.variables.to_a.join(', ')}), found (#{self.variables.to_a.join(', ')}).")
end
end
end
def validate_text_not_nil
return unless text.nil?
errors.add :text, :blank
end
end
end
| munirent/tolk | app/models/tolk/translation.rb | Ruby | mit | 4,487 |
require 'spec_helper'
describe QueueingRabbit::JobExtensions::NewRelic do
let(:installation) {
Proc.new do
job.class_eval { include QueueingRabbit::JobExtensions::NewRelic }
end
}
let(:new_relic) { Module.new }
before do
stub_const('NewRelic::Agent::Instrumentation::ControllerInstrumentation',
new_relic)
end
context 'when is being installed into an instantiated job' do
let(:job) { Class.new(QueueingRabbit::AbstractJob) }
it 'registers a transaction tracer' do
job.should_receive(:add_transaction_tracer).
with(:perform, :category => :task)
installation.call
end
end
# Don't know how to get this test working on Ruby 1.8.7
context 'when is being installed into a class based job', :ruby => '1.8.7' do
let(:job) { Class.new { def self.perform; end } }
it 'registers a transaction tracer' do
job.class.should_receive(:add_transaction_tracer).
with(:perform, :category => :task)
installation.call
end
end
end | temochka/queueing_rabbit | spec/unit/queueing_rabbit/extensions/new_relic_spec.rb | Ruby | mit | 1,036 |
<?php
App::uses('DomainsController', 'Controller');
/**
* DomainsController Test Case
*
*/
class DomainsControllerTest extends ControllerTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array(
'app.domain',
'app.mail_list',
'app.moderation_queue',
'app.archived_message',
'app.member',
'app.mail_lists_member'
);
/**
* testIndex method
*
* @return void
*/
public function testIndex() {
$this->testAction('/domains/index', array(
'return' => 'vars'
));
$this->assertCount(1, $this->vars['domains']);
}
/**
* testView method
*
* @expectedException NotFoundException
* @return void
*/
public function testViewWithoutDomain() {
$this->testAction('/domains/view', array(
'return' => 'vars'
));
}
/**
* testView method
*
* @return void
*/
public function testView() {
$domainId = '52f8928d-6588-4f6f-ab87-430ef6570d8e';
$this->testAction('/domains/view/' . $domainId, array(
'return' => 'vars'
));
$this->assertEquals($this->vars['domain']['Domain']['id'], $domainId);
$this->assertCount(1, $this->vars['domain']['MailList']);
}
/**
* testAdd method
*
* @return void
*/
public function testAdd() {
}
/**
* testEdit method
*
* @return void
*/
public function testEdit() {
}
/**
* testDelete method
*
* @return void
*/
public function testDelete() {
}
}
| dakota/CakeList | Test/Case/Controller/DomainsControllerTest.php | PHP | mit | 1,357 |
/*jslint node: true */
'use strict';
/**
* 相依模組
*/
var util = require('util');
var crypto = require('crypto');
var http = require('http');
var https = require('https');
var querystring = require('querystring');
var _ = require('lodash');
/**
* API 查詢端點
*
* @constant {object}
*/
var _ENDPOINT = {
// 訂單查詢
queryTradeInfo: '/Cashier/QueryTradeInfo',
// 信用卡定期定額訂單查詢
queryPeriodCreditCardTradeInfo: '/Cashier/QueryPeriodCreditCardTradeInfo',
// 信用卡關帳/退刷/取消/放棄
creditDetailDoAction: '/CreditDetail/DoAction',
//
aioChargeback: '/Cashier/AioChargeback'
};
/**
* 回傳值非 JSON 物件之 API 查詢端點
*
* @constant {string[]}
*/
var _RETURN_NON_OBJECT_ENDPOINT = [
_ENDPOINT.queryTradeInfo,
_ENDPOINT.creditDetailDoAction,
_ENDPOINT.aioChargeback
];
/**
* API 錯誤訊息
*
* @constant {object}
*/
var _ERROR_MESSAGES = {
initializeRequired: 'Allpay not initialized',
keyAndSecretRequired: 'Key and secret cannot be empty',
missingParameter: 'Missing parameter ',
wrongParameter: 'Wrong parameter '
};
/**
* 設定
*
* @property {string} merchantID - 廠商編號
* @property {string} hashKey - HashKey
* @property {string} hashIV - HashIV
* @property {string} baseUrl - API base url
* @property {boolean} useSSL - 使用 SSL 連線
* @property {boolean} debug - 顯示除錯訊息
* @property {boolean} initialized - 初始化註記
* @private
*/
var _api = {
merchantID: '',
hashKey: '',
hashIV: '',
baseUrl: 'payment.allpay.com.tw',
port: 443,
useSSL: true,
debug: false,
initialized: false
};
/**
* 建構子
*
* @param {object} opts - 參數
* @param {string} opts.merchantID - 廠商編號
* @param {string} opts.hashKey - Hashkey
* @param {string} opts.hashIV - HashIV
* @param {boolean} opts.debug - 選填. 顯示除錯訊息
*/
var Allpay = function(opts) {
if (typeof opts !== 'object') {
return sendErrorResponse(null, new Error(_ERROR_MESSAGES.missingParameter));
}
if (!opts.hasOwnProperty('merchantID') || !opts.merchantID) {
return sendErrorResponse(null, new Error(_ERROR_MESSAGES.wrongParameter + '"merchantID"'));
}
if (!opts.hasOwnProperty('hashKey') || !opts.hashKey) {
return sendErrorResponse(null, new Error(_ERROR_MESSAGES.wrongParameter + '"hashKey"'));
}
if (!opts.hasOwnProperty('hashIV') || !opts.hashIV) {
return sendErrorResponse(null, new Error(_ERROR_MESSAGES.wrongParameter + '"hashIV"'));
}
if (!(this instanceof Allpay)) {
return new Allpay(opts);
}
this.version = require('../package.json').version;
_api.merchantID = opts.merchantID;
_api.hashKey = opts.hashKey;
_api.hashIV = opts.hashIV;
_api.debug = opts.debug || false;
_api.initialized = true;
};
Allpay.prototype = {
/**
* 設定連線參數
*
* @param {object} opts - 參數
* @param {string} opts.baseUrl - 選填. 網址
* @param {string} opts.port - 選填. 連接埠
* @param {boolean} opts.useSSL - 選填. 使用 SSL 連線
*/
setHost: function(opts) {
_api.baseUrl = opts.baseUrl || _api.baseUrl;
_api.port = opts.port || _api.port;
_api.useSSL = opts.hasOwnProperty('useSSL') ? opts.useSSL : _api.useSSL;
},
/**
* 產生交易檢查碼
*
* @param {Object} data - 交易資料
*/
genCheckMacValue: function(data) {
// 若有 CheckMacValue 則先移除
if (data.hasOwnProperty('CheckMacValue')) {
delete data.CheckMacValue;
}
// 使用物件 key 排序資料
var keys = Object.keys(data);
var sortedKeys = _.sortBy(keys, function(key) {
return key;
});
var uri = _.map(sortedKeys, function(key) {
return key + '=' + data[key];
}).join('&');
uri = util.format('HashKey=%s&%s&HashIV=%s', _api.hashKey, uri, _api.hashIV);
uri = encodeURIComponent(uri);
var regex;
var find = ["%2d", "%5f", "%2e", "%21", "%2a", "%28", "%29", "%20"];
var replace = ["-", "_", ".", "!", "*", "(", ")", "+"];
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
uri = uri.replace(regex, replace[i]);
}
uri = uri.toLowerCase();
var checksum = crypto.createHash('md5').update(uri).digest('hex').toUpperCase();
return checksum;
},
/**
* 訂單查詢
*
* @param {object} opts - 參數
* @param {string} opts.MerchantTradeNo - 廠商交易編號
* @param {string} opts.PlatformID - 選填. 特約合作平台商代號
* @param {string} opts.CheckMacValue - 選填. 檢查碼
* @param {requestCallback} callback - 處理回應的 callback
*/
queryTradeInfo: function(opts, callback) {
var data = {};
if (typeof opts !== 'object') {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.missingParameter));
}
// 廠商編號
data.MerchantID = _api.merchantID;
// 廠商交易編號
if (!opts.hasOwnProperty('MerchantTradeNo') || !opts.MerchantTradeNo) {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.wrongParameter + '"MerchantTradeNo"'));
}
data.MerchantTradeNo = opts.MerchantTradeNo;
// 驗證時間
data.TimeStamp = Date.now();
// 特約合作平台商代號
if (opts.hasOwnProperty('PlatformID') && opts.PlatformID) {
data.PlatformID = opts.PlatformID;
}
// 檢查碼
data.CheckMacValue = opts.hasOwnProperty('CheckMacValue') ? opts.CheckMacValue : this.genCheckMacValue(data);
sendRequest('POST', _ENDPOINT.queryTradeInfo, data, callback);
},
/**
* 信用卡定期定額訂單查詢
*
* @param {object} opts - 參數
* @param {string} opts.MerchantTradeNo - 廠商交易編號
* @param {string} opts.CheckMacValue - 選填. 檢查碼
* @param {requestCallback} callback - 處理回應的 callback
*/
queryPeriodCreditCardTradeInfo: function(opts, callback) {
var data = {};
if (typeof opts !== 'object') {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.missingParameter));
}
// 廠商編號
data.MerchantID = _api.merchantID;
// 廠商交易編號
if (!opts.hasOwnProperty('MerchantTradeNo') || !opts.MerchantTradeNo) {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.wrongParameter + '"MerchantTradeNo"'));
}
data.MerchantTradeNo = opts.MerchantTradeNo;
// 驗證時間
data.TimeStamp = Date.now();
// 檢查碼
data.CheckMacValue = opts.hasOwnProperty('CheckMacValue') ? opts.CheckMacValue : this.genCheckMacValue(data);
sendRequest('POST', _ENDPOINT.queryPeriodCreditCardTradeInfo, data, callback);
},
/**
* 信用卡關帳/退刷/取消/放棄
*
* @param {object} opts - 參數
* @param {string} opts.MerchantTradeNo - 廠商交易編號
* @param {string} opts.TradeNo - AllPay 的交易編號
* @param {string} opts.Action - 執行動作
* @param {string} opts.TotalAmount - 金額
* @param {string} opts.PlatformID - 選填. 特約合作平台商代號
* @param {string} opts.CheckMacValue - 選填. 檢查碼
*/
creditDetailDoAction: function(opts, callback) {
var data = {};
if (typeof opts !== 'object') {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.missingParameter));
}
// 廠商編號
data.MerchantID = _api.merchantID;
// 廠商交易編號
if (!opts.hasOwnProperty('MerchantTradeNo') || !opts.MerchantTradeNo) {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.wrongParameter + '"MerchantTradeNo"'));
}
data.MerchantTradeNo = opts.MerchantTradeNo;
// AllPay 的交易編號
if (!opts.hasOwnProperty('TradeNo') || !opts.TradeNo) {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.wrongParameter + '"TradeNo"'));
}
data.TradeNo = opts.TradeNo;
// 執行動作
if (!opts.hasOwnProperty('Action') || !opts.Action) {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.wrongParameter + '"Action"'));
}
data.Action = opts.Action;
// 執行動作
if (!opts.hasOwnProperty('TotalAmount') || isNaN(Number(opts.TotalAmount))) {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.wrongParameter + '"TotalAmount"'));
}
data.TotalAmount = Number(opts.TotalAmount);
// 特約合作平台商代號
if (opts.hasOwnProperty('PlatformID') && opts.PlatformID) {
data.PlatformID = opts.PlatformID;
}
// 檢查碼
data.CheckMacValue = opts.hasOwnProperty('CheckMacValue') ? opts.CheckMacValue : this.genCheckMacValue(data);
sendRequest('POST', _ENDPOINT.creditDetailDoAction, data, callback);
},
/**
* 廠商通知退款
*
* @param {object} opts - 參數
* @param {string} opts.MerchantTradeNo - 廠商交易編號
* @param {string} opts.TradeNo - AllPay 的交易編號
* @param {string} opts.ChargeBackTotalAmount - 退款金額
* @param {string} opts.Remark - 選填. 備註欄位
* @param {string} opts.PlatformID - 選填. 特約合作平台商代號
* @param {string} opts.CheckMacValue - 選填. 檢查碼
*/
aioChargeback: function(opts, callback) {
var data = {};
if (typeof opts !== 'object') {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.missingParameter));
}
// 廠商編號
data.MerchantID = _api.merchantID;
// 廠商交易編號
if (!opts.hasOwnProperty('MerchantTradeNo') || !opts.MerchantTradeNo) {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.wrongParameter + '"MerchantTradeNo"'));
}
data.MerchantTradeNo = opts.MerchantTradeNo;
// AllPay 的交易編號
if (!opts.hasOwnProperty('TradeNo') || !opts.TradeNo) {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.wrongParameter + '"TradeNo"'));
}
data.TradeNo = opts.TradeNo;
// 退款金額
if (!opts.hasOwnProperty('ChargeBackTotalAmount') || !opts.ChargeBackTotalAmount) {
return sendErrorResponse(callback, new Error(_ERROR_MESSAGES.wrongParameter + '"ChargeBackTotalAmount"'));
}
data.ChargeBackTotalAmount = opts.ChargeBackTotalAmount;
// 備註欄位
if (opts.hasOwnProperty('Remark') && opts.Remark) {
data.Remark = opts.Remark;
}
// 特約合作平台商代號
if (opts.hasOwnProperty('PlatformID') && opts.PlatformID) {
data.PlatformID = opts.PlatformID;
}
// 檢查碼
data.CheckMacValue = opts.hasOwnProperty('CheckMacValue') ? opts.CheckMacValue : this.genCheckMacValue(data);
sendRequest('POST', _ENDPOINT.aioChargeback, data, callback);
}
};
/**
* Send HTTP/HTTPS request
*
* @param {string} method - HTTP 方法
* @param {string} path - 請求路徑
* @param {object} data - 資料物件
* @param {requestCallback} callback - 處理回應的 callback
* @private
*/
function sendRequest(method, path, data, callback) {
if (!_api.initialized) {
throw _ERROR_MESSAGES.initializeRequired;
}
log('The following data will be sent');
log(data);
var dataString = querystring.stringify(data);
var header = {
'Content-Type': 'application/x-www-form-urlencoded'
};
// 使用 POST 時設定 Content-Length 標頭
if (method === 'POST') {
header['Content-Length'] = dataString.length;
} else {
path += '?' + dataString;
}
var options = {
host: _api.baseUrl,
port: 443,
path: path,
method: method,
headers: header
};
var request;
if (!_api.useSSL) {
options.port = 80;
request = http.request(options);
} else {
request = https.request(options);
}
log(options);
if (method === 'POST') {
request.write(dataString);
}
request.end();
var buffer = '';
request.on('response', function (response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
buffer += chunk;
});
response.on('end', function () {
var responseData;
log('response ended');
if (callback) {
var err = null;
// 另外處理非 JSON 物件的返回值
if (_RETURN_NON_OBJECT_ENDPOINT.indexOf(path) !== -1) {
if (response.statusCode === 200) {
var responseArr;
if (path === _ENDPOINT.aioChargeback) {
responseArr = buffer.split('|');
responseData = {
status: responseArr[0],
message: responseArr[1]
};
} else {
responseArr = buffer.split('&');
responseData = {};
for (var i in responseArr) {
var key = responseArr[i].split('=')[0];
var val = responseArr[i].split('=')[1];
responseData[key] = val;
}
}
} else {
err = response.statusCode;
}
} else {
try {
responseData = JSON.parse(buffer);
} catch (_error) {
var parserError = _error;
log(parserError);
log('could not convert API response to JSON, above error is ignored and raw API response is returned to client');
err = parserError;
}
}
callback(err, responseData);
}
});
response.on('close', function (e) {
log('problem with API request detailed stacktrace below ');
log(e);
callback(e);
});
});
request.on('error', function (e) {
log('problem with API request detailed stacktrace below ');
log(e);
callback(e);
});
}
/**
* 返回或拋出錯誤回應
*
* @param {requestCallback} callback - 處理回應的 callback
* @param {Object} err - 錯誤物件
* @param {Object} returnData - 回應資料
* @private
*/
function sendErrorResponse(callback, err, returnData) {
if (callback) {
callback(err, returnData);
} else {
throw err;
}
}
/**
* 訊息紀錄
*
* @param {Object} - 訊息物件
* @private
*/
function log(message) {
if (message instanceof Error) {
console.log(message.stack);
}
if (_api.debug) {
if (typeof message === 'object') {
console.log(JSON.stringify(message, null, 2));
} else {
console.log(message);
}
}
}
/**
* 模組匯出
*/
module.exports = Allpay;
| FuYaoDe/node-allpay | lib/allpay.js | JavaScript | mit | 14,278 |
require 'rapid_api/auth/concerns/jwt_helpers'
require 'rapid_api/auth/concerns/authenticated_controller'
require 'rapid_api/auth/concerns/sessions_controller'
module RapidApi
module Auth
module Concerns
end
end
end
| briandavidwetzel/rapid_api | lib/rapid_api/auth/concerns.rb | Ruby | mit | 229 |
/* eslint import/no-extraneous-dependencies:0, no-return-assign:0 */
const HydraServiceFactory = require('./../index').HydraServiceFactory
const router = require('koa-router')()
const factory = new HydraServiceFactory({
hydra: {
serviceName: 'koa-service-test',
serviceDescription: 'Basic koa service on top of Hydra',
serviceIP: '127.0.0.1',
servicePort: 3000,
serviceType: 'koa',
serviceVersion: '1.0.0',
redis: {
host: '127.0.0.1',
port: 6379,
db: 15
}
}
})
factory.init().then(() =>
factory.getService((service) => {
router.get('/v1/welcome', async ctx => (ctx.body = 'Hello World!'))
service.use(router.routes())
})
)
| jkyberneees/hydra-integration | demos/koa.js | JavaScript | mit | 692 |
/*
* File: CentralGui.h
* Module: MasterFEnd
* Author: James Kuczynski
* Email: [email protected]
* File Description: This file will contain the qcentralwidget of the
* qmainwindow. Currently, it is divided into four sections
* (although this could be changed), north, south, east,
* and west.
*
* Created on May 6, 2015, 4:33 PM
*/
#ifndef CENTRAL_GUI_H
#define CENTRAL_GUI_H
#include <QWidget>
#include <QGridLayout>
#include <QTabWidget>
#include <QProgressBar>
#include <iostream>
#include "TabGui.h"
#include "FileTreeGui.h"
#include "RunPanelGui.h"
#include "NavigatorGui.h"
#include "OutputGui.h"
#include "WindowsConsoleText.h"
#include "UnixConsoleText.h"
#ifdef _WIN32
namespace cct = WindowsConsoleText;
#elif __APPLE
namespace cct = UnixConsoleText;
#elif __linux
namespace cct = UnixConsoleText;
#endif
using namespace std;
class CentralGui : public QWidget
{
Q_OBJECT
private:
TabGui* northGuiPtr;
FileTreeGui* fileTreeGuiPtr;
RunPanelGui* runPanelGuiPtr;
NavigatorGui* navigatorGuiPtr;
OutputGui* southGuiPtr;
QGridLayout* outerLayout;
private slots:
;
public:
/**
* Constructor.
*
* @param parent reference to parent type.
*/
CentralGui(QWidget* parent = 0);
/**
*
*
* @param northGuiPtr
*/
void setNorthGuiPtr(TabGui* northGuiPtr);
/**
*
*
* @return
*/
TabGui* getNorthGuiPtr();
/**
*
*
* @param fileTreeGuiPtr
*/
void setFileTreeGuiPtr(FileTreeGui* fileTreeGuiPtr);
/**
*
*
* @return
*/
FileTreeGui* getFileTreeGuiPtr();
void setRunPanelGuiPtr(RunPanelGui* runPanelGuiPtr);
RunPanelGui* getRunPanelGuiPtr();
/**
*
*
* @param navigatorGuiPtr
*/
void setNavigatorGuiPtr(NavigatorGui* navigatorGuiPtr);
/**
*
*
* @return
*/
NavigatorGui* getNavigatorGuiPtr();
/**
*
*
* @param southGuiPtr
*/
void setSouthGuiPtr(OutputGui* southGuiPtr);
/**
*
*
* @return
*/
OutputGui* getSouthGuiPtr();
/**
*
*
* @return
*/
static QProgressBar getProgressBarPtr();
/**
*
*
* @param northTabWidgetPtr
*/
void passNorthTabWidgetPtr(QTabWidget* northTabWidgetPtr);
/**
*
*
* @param southTabWidgetPtr
*/
void passSouthTabWidgetPtr(QTabWidget* southTabWidgetPtr);
/**
* Classic toString method.
*
* @return class data.
*/
QString* toString();
/**
* Destructor.
*/
~CentralGui();
};
#endif /* CENTRAL_GUI_H */ | DeepBlue14/rqt_ide | modules/ide_old/src/CentralGui.h | C | mit | 3,302 |
<?php
require_once BSA_PATH . 'inc/util.php';
class BsaCaptcha {
// Option name
const OPTION_NAME = 'bsa_captcha';
// Validate field
const FIELD_VALID = 'valid_field';
// Difference between captcha code and validation code
const CODE_DIFF = 2;
// Be called when the plugin is installed
static function install() {
BsaUtil::enable(self::OPTION_NAME);
}
// Add field to setting menu
static function setting_init() {
// Setting field of Prevent Spam Comments
BsaUtil::add_field(self::OPTION_NAME,
__('Prevent Spam Comments', 'bjh-site-assistant'),
array(__CLASS__, 'add_field'));
}
static function add_field() {
BsaUtil::add_checkbox(self::OPTION_NAME);
}
// Add a simple captcha of random 3 digits number for anonymous comments
static function add_captcha_field($fields) {
// Only add for article and page
if (BsaUtil::is_enabled(self::OPTION_NAME) && is_singular() && !is_user_logged_in()) {
// 3 digits of validation code
global $number;
$number = vsprintf('%03d',rand(0, 999));
// reuse the style of "url" field
$captcha_field = str_replace('"url"', self::OPTION_NAME, $fields['url']);
// replace the url label by validation code
$label_start = strpos($captcha_field, '>', strpos($captcha_field, '<label ')) + 1;
$label_length = strpos($captcha_field, '</label>', $name_start) - $label_start;
$captcha_field = substr_replace($captcha_field,
__('Code', 'bjh-site-assistant') . ':<em>' . $number . '</em>',
$label_start,
$label_length);
// Add placeholder to remind user
$label_start = strpos($captcha_field, '<input ') + 6;
$placeholder = ' placeholder="' . __('Please input the code aside', 'bjh-site-assistant')
. '" alt="' . $number . '" ';
$captcha_field = substr_replace($captcha_field, $placeholder, $label_start, 1);
$fields[self::OPTION_NAME] = $captcha_field;
// Add a hidden field to valid the captcha at backend
$fields[self::FIELD_VALID] = '<input type="hidden" id="' . self::FIELD_VALID
. '" name="' . self::FIELD_VALID . '" value="1">';
}
return $fields;
}
// Add JS to validate the captcha
static function validate_captcha() {
// Only add for article and page
if (BsaUtil::is_enabled(self::OPTION_NAME) && is_singular() && !is_user_logged_in()) {
?>
<script type="text/javascript">
var submitBtn = document.getElementById("submit");
submitBtn.disabled = true;
var codeField = document.getElementById("<?php echo self::OPTION_NAME; ?>");
var validField = document.getElementById("<?php echo self::FIELD_VALID; ?>");
codeField.onkeyup = function() {
if (codeField.value == codeField.alt) {
submitBtn.disabled = false;
validField.value = Number(codeField.value) + <?php echo self::CODE_DIFF; ?>;
} else {
submitBtn.disabled = true;
}
}
</script>
<?php
}
}
// Add the number posted to backend
static function validate_post_number($comment_data) {
if (BsaUtil::is_enabled(self::OPTION_NAME) && !is_user_logged_in()) {
$validation = intval($_POST[self::FIELD_VALID]);
$code = intval($_POST[self::OPTION_NAME]);
if (($validation - $code) != self::CODE_DIFF) {
wp_die(__('Error: Code is not valid!', 'bjh-site-assistant'));
}
}
return $comment_data;
}
}
// Add option to setting page
add_action('admin_init', 'BsaCaptcha::setting_init');
// Add field to comment form
add_filter('comment_form_default_fields', 'BsaCaptcha::add_captcha_field');
// Add validate JS to the end of comment form.
add_action('comment_form', 'BsaCaptcha::validate_captcha');
// Backend validation for the code
add_filter('pre_comment_on_post', 'BsaCaptcha::validate_post_number');
| bjhee/bjh-site-assistant | func/bjh-captcha.php | PHP | mit | 4,233 |

###################
Prototype for volunteers of Tinderbox festival.
###################
This is in development school project repo created for Tinderbox festival volunteers. It's a responsive application build with CodeIgniter framework and Bootstrap 3.
Tinderbox is Fyn largest festival and one of largest music festival in Denmark. It is held in Tusindarskoven, located on the outskirt of Odense.
*******************
Server Requirements
*******************
PHP version 5.6 or newer is recommended.
It should work on 5.3.7 as well, but we strongly advise you NOT to run
such old versions of PHP, because of potential security and performance
issues, as well as missing features.
************
Installation
************
Before cloning this repo Please see the `installation section <https://codeigniter.com/user_guide/installation/index.html>`_
of the CodeIgniter User Guide.
*******
License
*******
Please see the `license
agreement <https://github.com/bcit-ci/CodeIgniter/blob/develop/user_guide_src/source/license.rst>`_.
*********
Resources
*********
- `User Guide <https://codeigniter.com/docs>`_
- `Language File Translations <https://github.com/bcit-ci/codeigniter3-translations>`_
- `Community Forums <http://forum.codeigniter.com/>`_
| joingi/tinbox | README.md | Markdown | mit | 1,288 |
package com.iluwatar.bridge.service2;
import com.iluwatar.bridge.itfc2.ISoulEatingMagicWeaponImp;
public class Stormbringer implements ISoulEatingMagicWeaponImp {
@Override
public void wieldImp() {
System.out.println("wielding Stormbringer");
}
@Override
public void swingImp() {
System.out.println("swinging Stormbringer");
}
@Override
public void unwieldImp() {
System.out.println("unwielding Stormbringer");
}
@Override
public void eatSoulImp() {
System.out.println("Stormbringer devours the enemy's soul");
}
}
| rbible/java-design-patterns | styles-struct/bridge/src/main/java/com/iluwatar/bridge/service2/Stormbringer.java | Java | mit | 602 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coq bench</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../../..">Unstable</a></li>
<li><a href=".">8.4pl4 / contrib:three-gap 8.4.dev</a></li>
<li class="active"><a href="">2014-11-19 11:05:16</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../../../../../about.html">About</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href=".">« Up</a>
<h1>
contrib:three-gap
<small>
8.4.dev
<span class="label label-danger">Uninstallation error</span>
</small>
</h1>
<p><em><script>document.write(moment("2014-11-19 11:05:16 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2014-11-19 11:05:16 UTC)</em><p>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:three-gap/coq:contrib:three-gap.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>The package is valid.
</pre></dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --dry-run coq:contrib:three-gap.8.4.dev coq.8.4pl4</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 s</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.4pl4).
The following actions will be performed:
- install coq:contrib:three-gap.8.4.dev
=== 1 to install ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
=-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Building coq:contrib:three-gap.8.4.dev:
coq_makefile -f Make -o Makefile
make -j4
make install
Installing coq:contrib:three-gap.8.4.dev.
</pre></dd>
</dl>
<p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --deps-only coq:contrib:three-gap.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --verbose coq:contrib:three-gap.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>14 s</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- install coq:contrib:three-gap.8.4.dev
=== 1 to install ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[coq:contrib:three-gap] Fetching git://clarus.io/three-gap#v8.4
Initialized empty Git repository in /home/bench/.opam/packages.dev/coq:contrib:three-gap.8.4.dev/.git/
[master (root-commit) cd4c45d] opam-git-init
warning: no common commits
From git://clarus.io/three-gap
* [new branch] v8.4 -> opam-ref
* [new branch] v8.4 -> origin/v8.4
LICENSE
Make
Makefile
Nat_compl.v
bench.log
description
preuve1.v
preuve2.v
prop_elem.v
prop_fl.v
three_gap.v
tools.v
HEAD is now at 27c572b Sauvegarde des bench.log
=-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Building coq:contrib:three-gap.8.4.dev:
coq_makefile -f Make -o Makefile
make -j4
make install
coqdep -c -slash -R . ThreeGap "Nat_compl.v" > "Nat_compl.v.d" || ( RV=$?; rm -f "Nat_compl.v.d"; exit ${RV} )
coqdep -c -slash -R . ThreeGap "tools.v" > "tools.v.d" || ( RV=$?; rm -f "tools.v.d"; exit ${RV} )
coqdep -c -slash -R . ThreeGap "prop_elem.v" > "prop_elem.v.d" || ( RV=$?; rm -f "prop_elem.v.d"; exit ${RV} )
coqdep -c -slash -R . ThreeGap "prop_fl.v" > "prop_fl.v.d" || ( RV=$?; rm -f "prop_fl.v.d"; exit ${RV} )
coqdep -c -slash -R . ThreeGap "preuve1.v" > "preuve1.v.d" || ( RV=$?; rm -f "preuve1.v.d"; exit ${RV} )
coqdep -c -slash -R . ThreeGap "preuve2.v" > "preuve2.v.d" || ( RV=$?; rm -f "preuve2.v.d"; exit ${RV} )
coqdep -c -slash -R . ThreeGap "three_gap.v" > "three_gap.v.d" || ( RV=$?; rm -f "three_gap.v.d"; exit ${RV} )
coqc -q -R . ThreeGap Nat_compl
coqc -q -R . ThreeGap tools
coqc -q -R . ThreeGap prop_elem
coqc -q -R . ThreeGap prop_fl
coqc -q -R . ThreeGap preuve1
coqc -q -R . ThreeGap preuve2
coqc -q -R . ThreeGap three_gap
for i in three_gap.vo preuve2.vo preuve1.vo prop_fl.vo prop_elem.vo tools.vo Nat_compl.vo; do \
install -d `dirname /home/bench/.opam/system/lib/coq/user-contrib/ThreeGap/$i`; \
install -m 0644 $i /home/bench/.opam/system/lib/coq/user-contrib/ThreeGap/$i; \
done
Installing coq:contrib:three-gap.8.4.dev.
</pre></dd>
</dl>
<h2>Installation size</h2>
<p>Data not available in this bench.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq:contrib:three-gap.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 s</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- remove coq:contrib:three-gap.8.4.dev
=== 1 to remove ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[coq:contrib:three-gap] Fetching git://clarus.io/three-gap#v8.4
=-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Removing coq:contrib:three-gap.8.4.dev.
rm -R /home/bench/.opam/system/lib/coq/user-contrib/three-gap
[WARNING] failure in package uninstall script, some files may remain:
# opam-version 1.2.0
# os linux
# command rm -R /home/bench/.opam/system/lib/coq/user-contrib/three-gap
# path /home/bench/.opam/system/build/coq:contrib:three-gap.8.4.dev
# compiler system (4.01.0)
# exit-code 1
# env-file /home/bench/.opam/system/build/coq:contrib:three-gap.8.4.dev/coq:contrib:three-gap-2301-1872ec.env
# stdout-file /home/bench/.opam/system/build/coq:contrib:three-gap.8.4.dev/coq:contrib:three-gap-2301-1872ec.out
# stderr-file /home/bench/.opam/system/build/coq:contrib:three-gap.8.4.dev/coq:contrib:three-gap-2301-1872ec.err
### stderr ###
# rm: cannot remove '/home/bench/.opam/system/lib/coq/user-contrib/three-gap': No such file or directory
</pre></dd>
<dt>Missing removes</dt>
<dd>
<ul>
<li><code>/home/bench/.opam/system/lib/coq/user-contrib/ThreeGap</code></li>
<li><code>/home/bench/.opam/system/lib/coq/user-contrib/ThreeGap/preuve1.vo</code></li>
<li><code>/home/bench/.opam/system/lib/coq/user-contrib/ThreeGap/tools.vo</code></li>
<li><code>/home/bench/.opam/system/lib/coq/user-contrib/ThreeGap/prop_fl.vo</code></li>
<li><code>/home/bench/.opam/system/lib/coq/user-contrib/ThreeGap/three_gap.vo</code></li>
<li><code>/home/bench/.opam/system/lib/coq/user-contrib/ThreeGap/prop_elem.vo</code></li>
<li><code>/home/bench/.opam/system/lib/coq/user-contrib/ThreeGap/Nat_compl.vo</code></li>
<li><code>/home/bench/.opam/system/lib/coq/user-contrib/ThreeGap/preuve2.vo</code></li>
</ul>
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html> | coq-bench/coq-bench.github.io-old | clean/Linux-x86_64-4.01.0-1.2.0/unstable/8.4pl4/contrib:three-gap/8.4.dev/2014-11-19_11-05-16.html | HTML | mit | 10,736 |
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from '../auth/auth.guard';
import { DoHomeComponent } from './do-home/do-home.component';
const routes: Routes = [
{path: '', canActivate: [AuthGuard], children: [
{path: '', pathMatch: 'full', component: DoHomeComponent}
]}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class DismantlingOrderRoutingModule { }
| rxjs-space/lyfront | deprecated/dismantling-order/dismantling-order-routing.module.ts | TypeScript | mit | 491 |
final class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| leomindez/From-Java-To-Ceylon | code/java/classes/classes-04.java | Java | mit | 251 |
#ifndef SANDBOX_MEYERCLP_APPS_DREME_H_
#define SANDBOX_MEYERCLP_APPS_DREME_H_
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <math.h>
#include <seqan/basic.h>
#include <seqan/file.h>
#include <seqan/find.h>
#include <seqan/stream.h>
#include <seqan/find_motif.h>
#include <seqan/index.h>
#include <seqan/sequence.h>
#include <seqan/misc/misc_interval_tree.h>
using namespace seqan;
struct Seq
{
StringSet<CharString> ids;
unsigned c; // Anzahl der Motive, provisorisch
StringSet<String<Dna5> > seqs;//
Index< StringSet<String<Dna5> > > SArray;
unsigned seed;
unsigned int SeqsNumber;
std::map<String<Dna5>,unsigned int > seqCounter;//maps the Sequence-Kmere to a Counter for the Sequence
std::map<String<Iupac>,unsigned int> generalizedKmer;
std::map<String<Iupac>,double > SortedPValueReversed;
std::multimap<double,String<Dna5> > SortedPValue;
std::multimap<double,String<Iupac> > generalizedSortedPValue;
std::map<unsigned int,std::map<Iupac,double> > freqMatrix;
String< std::map<unsigned int,std::map<Iupac,double> > > allPWMs;
std::map<unsigned int,std::map<Iupac,double> > weightMatrix;
std::map<unsigned int, double > seqLogoMatrix;
std::map<unsigned int, double > columnEntropy;
std::map<unsigned int,std::map<Iupac,double> > InformationContentMatrix;
FrequencyDistribution<Dna5> frequencies;
/**
In BuildFrequencyMatrix werden die gefundenen Intervalle des Top-Motivs an Intervalls gehängt
Am Ende der while wird dann ein IntervallTree für jede Sequenz erzeugt, sodass im nächsten Schritt direkt geschaut werden kann ob ein Motiv mit einem schon
gefundenen überlappt
**/
typedef IntervalAndCargo<unsigned, unsigned> TInterval;
String<String<TInterval> > intervals;//String<TInterval> enthält alle Intervalle einer Sequenz. String<String<..>> enthält alle Sequenzen
String<IntervalTree<unsigned> > intervalTrees; // Tree für schnellere Suche erstellen --> String von Trees, da mehrere Sequenzen
String<unsigned> results;
double pValue;
};
struct IupacMaps
{
std::map<unsigned int,char> IupacMap;
std::map<char,unsigned int> IupacMapReversed;
std::map<char,String<Iupac> > IupacMapReplace; //stores the replacement-chars
std::map<char,String<Dna5> > IupacMapReplaceReversed;
std::map<String<Dna5>, char > IupacMapInversed;
};
struct Euklidisch_;
typedef Tag<Euklidisch_> Euklidisch;
struct Pearson_;
typedef Tag<Pearson_> Pearson;
struct Mahalanobis_;
typedef Tag<Mahalanobis_> Mahalanobis;
struct Entropy_;
typedef Tag<Entropy_> Entropy;
void readFastA(struct Seq &seq, CharString fname);
template <typename TStream>
void PrintFastA(TStream & stream, Seq &seq);
void initST(Seq &seq);
void PrintST(Seq &seq);
void priorFreq(Seq &seq);
void initExactKmer(Seq &seq,Seq &back,unsigned int kmer_len,unsigned int kmer_len_end);
void CountKmer(Seq &seq, Finder<Index<StringSet<String<Dna5> > > > &finder, String<Dna5> &Kmer);
void CountKmer(std::map<String<Iupac>,unsigned int > &Dna5CounterMap, Finder<Index<StringSet<String<Iupac> > > > &finder, String<Iupac> &Kmer,Seq &seq,IupacMaps &IMap);
void PrintMap(std::map<String<Dna5>,unsigned int > &Dna5CounterMap,unsigned int SeqsNumber);
void PrintMap(std::map<String<Iupac>,unsigned int > &Dna5CounterMap,unsigned int SeqsNumber);
void PrintMap(std::multimap<double,String<Dna5> > &pValueMap);
void PrintMap(std::map<String<Iupac>,unsigned int> &generalizedKmer);
void PrintMap(Seq &seq,bool foreground);
void DebugMap(Seq &seq,Seq &back,std::map<String<Dna5>,unsigned int > &sequencesCounter,std::map<String<Dna5>,unsigned int > &backgroundCounter);
void DebugMultiMap(std::map<String<Dna5>,unsigned int > &sequencesCounter,std::multimap<double,String<Dna5> > &SortedPValue);
double* logFac;
void logFactorial(unsigned int len);
double calcFET(unsigned int a,unsigned int b,unsigned int c,unsigned int d);
void modifyFET(unsigned int a,unsigned int b,unsigned int c,unsigned int d, double &pValue);
void DebugFisherExact(unsigned int a,unsigned int b,unsigned int c,unsigned int d);
void FisherExactTest(Seq &seq, Seq &back);
void FisherExactTest(std::map<String<Iupac>,unsigned int > &SequenceCounter,std::map<String<Iupac>,unsigned int > &BackgroundCounter, Seq &seq, Seq &back);
double FisherExactTest(Seq &seq, Seq &back,std::multimap<double,String<Dna5> > &GeneralizedSortedPValueTemp);
void MapIupac(IupacMaps &IMaps);
void InitGeneralization(IupacMaps &IMaps,Seq &seq, Seq &back);
void loopOverKmer(Seq &seq,String<Iupac> &temp,String<Iupac> &Kmer,Iterator<String<Iupac> >::Type &tempIt,Finder<Index<StringSet<String<Dna5> > > > &finder,unsigned int &counter,std::vector<int> &CounterV,IupacMaps &IMap);
void FindKmer(Seq &seq,String<Iupac> &temp,Finder<Index<StringSet<String<Dna5> > > > &finder,unsigned int &counter,std::vector<int> &CounterV);
void GeneralizeKmer(String<Dna5> Kmer, IupacMaps &IMaps,Seq &seq, Seq &back);
void GeneralizeKmer(String<Iupac> Kmer,std::map<String<Iupac>,unsigned int> &generalizedKmerTemp,std::map<String<Iupac>,unsigned int> &generalizedKmerBackgroundTemp,IupacMaps &IMaps,Seq &seq, Seq &back);
void estimateCounter(Seq &seq,String<Iupac> temp,String<Iupac> temp2,unsigned int &counter);
void estimateCounter(Seq &seq,std::map<String<Iupac>,unsigned int> &generalizedKmer,String<Iupac> temp,String<Iupac> temp2,unsigned int &counter);
void exactGeneralizeCount(std::multimap<double,String<Iupac> > &SortedPValueG,std::map<String<Iupac>,unsigned int > &seqCounter,std::map<String<Iupac>,unsigned int > &backCounter,Finder<Index<StringSet<String<Dna5> > > > &finder,Finder<Index<StringSet<String<Dna5> > > > &finderB,Seq &seq, Seq &back,IupacMaps &IMap);
void FindTopKmer(Seq &seq,String<Iupac> &temp,Finder<Index<StringSet<String<Dna5> > > > &finder,unsigned int &counter,std::vector<int> &CounterV);
void FindTopKmer(Seq &seq,String<Dna5> &temp,Finder<Index<StringSet<String<Dna5> > > > &finder,unsigned int &counter,std::vector<int> &CounterV);
void loopOverTopKmer( Seq &seq,String<Iupac> &temp,String<Iupac> &Kmer,Iterator<String<Iupac> >::Type &tempIt,Finder<Index<StringSet<String<Dna5> > > > &finder,unsigned int &counter,std::vector<int> &CounterV,IupacMaps &IMap);
void BuildFrequencyMatrix( Finder<Index<StringSet<String<Dna5> > > > &finder, String<Iupac> &Kmer,Seq &seq, IupacMaps &IMaps);
void BuildFrequencyMatrix( Finder<Index<StringSet<String<Dna5> > > > &finder,String<Dna5> &Kmer,Seq &seq, IupacMaps &IMaps);
void BuildWeightMatrix(Seq &seq);
void BuildInformationContentMatrix(Seq &seq);
void ComparePWM(Seq &seq,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix1,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix2, Entropy const & tag);
void ComparePWM(Seq &seq,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix1,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix2, Euklidisch const & tag);
void PWMClustering(Seq &seq);
void replaceKmer(Seq &seq,unsigned int stringNumber, unsigned int begin, unsigned int end);
void readFastA( struct Seq &seq,
CharString fname){
//########### einlesen in ids und seqs
//Variable um Sequenz und ID zu speichern
std::fstream fasta(toCString(fname), std:: ios_base::in | std::ios_base::binary);
if(!fasta.good()){
std::cerr << "Could not open file: \"" << fname << "\"" << std::endl;
std::exit(1);
}
typedef String<char,MMap<> > TMMapString;
TMMapString mmapString;
if(!open(mmapString, toCString(fname), OPEN_RDONLY))
std::exit(1);
RecordReader<TMMapString, DoublePass<Mapped> > reader(mmapString);
AutoSeqStreamFormat formatTag;
if(!checkStreamFormat(reader,formatTag)){
std::cerr<<"Could not determine file format!"<<std::endl;
std::exit(1);
}
std::cout<<"File format is "<<getAutoSeqStreamFormatName(formatTag)<<'\n';
StringSet<CharString> ids;
StringSet<String<Dna5> > seqs;//
if(read2(ids,seqs,reader,formatTag) !=0){
std::cerr<<"ERROR reading FASTA"<<std::endl;
std::exit(1);
}
seq.ids = ids;
seq.seqs = seqs;
}
template <typename TStream>
void PrintFastA(TStream & stream,
Seq &seq){
SEQAN_ASSERT_EQ(length(seq.ids), length(seq.seqs));
typedef Iterator<StringSet<CharString>, Rooted>::Type TIdIter;
typedef Iterator<StringSet<String<Dna5> >, Standard>::Type TSeqIter;//Dna5Q
TIdIter idIt =begin(seq.ids, Rooted());
TSeqIter seqIt=begin(seq.seqs, Standard());
for(;!atEnd(idIt);++idIt,++seqIt){
stream <<*idIt<<'\t'<<*seqIt<<std::endl;
}
}
void initST(Seq &seq){
//creates a index based on an enhanced suffix array
indexText(seq.SArray) = seq.seqs;
}
void PrintST(Seq &seq){
typedef Index<StringSet<String<Dna5> > > TMyIndex;//Dna5Q
Iterator<TMyIndex, BottomUp<> >::Type myIterator(seq.SArray);
for(;!atEnd(myIterator);++myIterator){
std::cout<<representative(myIterator)<<std::endl;
}
}
/***
Berechnet relative Hintergrund-Wahrscheinlichkeit von ACGT
***/
void priorFreq(Seq &seq){
typedef Iterator<StringSet<String<Dna5> >, Standard>::Type TSeqIter;
TSeqIter seqItbegin=begin(seq.seqs, Standard());
TSeqIter seqItend=end(seq.seqs, Standard());
absFreqOfLettersInSetOfSeqs(seq.frequencies,seqItbegin,seqItend);
normalize(seq.frequencies);
}
//iniate Search in Fore- and Background
void initExactKmer( Seq &seq,
Seq &back,
unsigned int kmer_len,
unsigned int kmer_len_end){
Finder<Index<StringSet<String<Dna5> > > > finder(seq.SArray);
Finder<Index<StringSet<String<Dna5> > > > finderB(back.SArray);//finder background
typedef Index< StringSet<String<Dna5> > > TMyIndex;
//kmer_len= 3;//minimal kmer-length
//kmer_len_end=8;//maximal length
if(kmer_len<1) kmer_len=3;
if(kmer_len_end<kmer_len) kmer_len_end=kmer_len+1;
//std::cout<<"kmer: "<<kmer_len<<std::endl;
//std::cout<<"end: "<<kmer_len_end<<std::endl;
typedef Iterator<StringSet<String<Dna5> > >::Type TStringSetIterator;
unsigned int slen=0;
String<Dna5> Kmer;//current Kmer
std::cout<<std::endl<<std::endl;
for(;kmer_len<=kmer_len_end;++kmer_len){//loop over all possible Kmer-length -->3-8
for(TStringSetIterator it=begin(seq.seqs);it!=end(seq.seqs);++it){//loop over all sequences
slen=length(value(it));//length of the current seq
if(slen==0) continue;
else if(slen<kmer_len) continue;
//std::cout<<"Sequence: "<<value(it)<<std::endl;
for(unsigned int i=0;i<slen-kmer_len+1;++i){//loop over all Kmere in the current sequence
Kmer=infix(value(it),i,i+kmer_len);//optimieren
//std::cout<<Kmer<<" ";
//if(Kmer[kmer_len-1]=='N'){//'AAAN'AAAA ---> AAA'NAAA'A --> after continue AAAN'AAAA'
// i+=kmer_len;
// continue;
//}
if(seq.seqCounter.find(Kmer)!=seq.seqCounter.end()) continue;// if Kmer is in the Map -->nothing to do
// //Pattern<String<Dna5> > pattern(Kmer);
// std::cout<<"count";
CountKmer(back,finderB,Kmer);
CountKmer(seq,finder,Kmer);
}
}
}
//}
}
//gets the current Kmer and searches it in the index
//max(cumulated sum of the counter)=SeqsNumber --> counts number of sequences containing the motif
void CountKmer( Seq &seq,
Finder<Index<StringSet<String<Dna5> > > > &finder,
String<Dna5> &Kmer){
std::vector<int> CounterV(seq.SeqsNumber+1,0);//counter for storing 1 or 0 for each Seq + the cumulated sum of the counter in the last field
//std::cout<<"vor while ";
clear(finder);
while(find(finder,Kmer)){//search the current Kmer in all sequences
//std::cout<<'[' <<beginPosition(finder)<<','<<endPosition(finder)<<")\t"<<infix(finder)<<std::endl;//Debug
if(seq.c>1){//nur im foreground
clear(seq.results);
findIntervals(seq.intervalTrees[beginPosition(finder).i1], beginPosition(finder).i2, endPosition(finder).i2, seq.results);
}// wenn results>0, dann überlappt das Kmer --> nicht aufzählen
if(CounterV[beginPosition(finder).i1] == 0 && length(seq.results)==0){//count number of sequences containing the motif, not the occurrences to avoid problems with self-overlapping
++CounterV[beginPosition(finder).i1];
++CounterV[seq.SeqsNumber];//last Position in CounterV is cumulated sum
}
}
seq.seqCounter[Kmer]=CounterV[seq.SeqsNumber];
CounterV.clear();
}
void loopOverKmer( Seq &seq,
String<Iupac> &temp,
String<Iupac> &Kmer,
Iterator<String<Iupac> >::Type &tempIt,
Finder<Index<StringSet<String<Dna5> > > > &finder,
unsigned int &counter,
std::vector<int> &CounterV,
IupacMaps &IMap){
String<Dna5> replace;
Iterator<String<Dna5> >::Type replaceIt;
Iterator<String<Iupac> >::Type tempIttemp;
char resetTemp;
if(tempIt==end(temp)) return;
if((*tempIt == 'A' || *tempIt == 'C' ||*tempIt == 'G' ||*tempIt == 'T')){
loopOverKmer(seq,temp,temp,++tempIt,finder,counter,CounterV,IMap);//only replace the position with a wildcard
return;
}
replace=IMap.IupacMapReplaceReversed[*tempIt];
replaceIt = begin(replace);
for(;replaceIt!=end(replace);++replaceIt){
temp = Kmer;// reset temp
resetTemp = IMap.IupacMapInversed[replace];
*tempIt = *replaceIt;
//if not end call fkt. with temp
// if end call find --> &counter
tempIttemp=tempIt;//der rekursive aufruf mit diesem, da die schleife mit tempIt weitergehen soll
if(tempIt+1!=end(temp)){
loopOverKmer(seq,temp,temp,++tempIttemp,finder,counter,CounterV,IMap);
}
if((*tempIttemp == 'A' || *tempIttemp == 'C' || *tempIttemp == 'G' || *tempIttemp == 'T' || tempIttemp == end(temp))){
FindKmer(seq,temp,finder,counter,CounterV);
}
*tempIt=resetTemp;
}
//}
}
void FindKmer( Seq &seq,
String<Iupac> &temp,
Finder<Index<StringSet<String<Dna5> > > > &finder,
unsigned int &counter,
std::vector<int> &CounterV){
clear(finder);
while(find(finder,temp)){//search the current Kmer in all sequences
//std::cout<<'[' <<beginPosition(finder)<<','<<endPosition(finder)<<")\t"<<infix(finder)<<std::endl;//Debug
if(seq.c>1){//nur im foreground
clear(seq.results);
findIntervals(seq.intervalTrees[beginPosition(finder).i1], beginPosition(finder).i2, endPosition(finder).i2, seq.results);
}
if(CounterV[beginPosition(finder).i1] == 0 && length(seq.results)==0){//count number of sequences containing the motif, not the occurrences to avoid problems with self-overlapping
//ansonsten müsste das array noch einmal durch gegangen werden und an jeder stellt !=0 ++
++CounterV[beginPosition(finder).i1];
++CounterV[seq.SeqsNumber];//last Position in CounterV is cumulated sum
++counter;
}
}
}
/*
for counting the top 100 generalizedKmere exact
todo -->template
*/
void CountKmer( std::map<String<Iupac>,unsigned int > &seqCounter,
Finder<Index<StringSet<String<Dna5> > > > &finder,
String<Iupac> &Kmer,
Seq &seq,
IupacMaps &IMap){
String<Iupac> temp;
Iterator<String<Iupac> >::Type tempIt;
temp=Kmer;
tempIt = begin(temp);
unsigned int counter=0;
std::vector<int> CounterV(seq.SeqsNumber+1,0);//counter for storing 1 or 0 for each Seq + the cumulated sum of the counter in the last field
//std::cout<<"Kmer "<<Kmer<<std::endl;
loopOverKmer(seq,temp,Kmer,tempIt,finder,counter,CounterV,IMap);
seqCounter[Kmer]=counter;
//std::cout<<Kmer<<" "<<seqCounter[Kmer]<<" ";
//std::cout<<temp<<" "<<CounterV[SeqsNumber]<<std::endl;
CounterV.clear();
/*
Der clear hier bewirkt, dass bei ASG entweder ACG oder AGG vorkommen darf,
falls beide vorkommen(in einer Sequenz) wird der counter trotzdem nur um 1 erhöht
-->Counter für AGG ist falsch, ASG stimmt jedoch wieder. Counter[AGG] --> irrelevant
-->AGG wird jedes mal wenns benötigt wird neu berechnet-->optimieren
*/
}
//void replaceKmer( Seq &seq,
// String<unsigned int> &replaceString){
//
// unsigned int beg =0;
// unsigned int endP =0;
// unsigned int Snumber =0;
//
// //std::cout<<stringNumber<<" "<<begin<<" "<<end<<std::endl;
// Iterator<String<unsigned int> >::Type StringIt;
// StringIt = begin(replaceString);
// for(;StringIt!=end(replaceString);++StringIt){
// Snumber = *StringIt;
// ++StringIt;
// beg = *StringIt;
// ++StringIt;
// endP = *StringIt;
// //std::cout<<Snumber<<" "<<beg<<" "<<endP<<std::endl;
// for(;beg<endP;++beg)
// {
// seq.seqs[Snumber][beg]='N';
// }
// //replace(seq.seqs[*StringIt],*(++StringIt),*(++StringIt),'N');
// }
//
//
//}
///////////////////////////////////
void FindTopKmer(Seq &seq,
String<Iupac> &temp,
Finder<Index<StringSet<String<Dna5> > > > &finder,
unsigned int &counter,
std::vector<int> &CounterV){
typedef IntervalAndCargo<unsigned, unsigned> TInterval;
clear(finder);
//std::cout<<temp<<" vor-while"<<std::endl;
while(find(finder,temp)){//search the current Kmer in all sequences
if(seq.c==1){//nur im ersten Schritt in Intervals speichern, danach kann direkt an den Tree angefügt werden
appendValue(seq.intervals[beginPosition(finder).i1], TInterval(beginPosition(finder).i2, endPosition(finder).i2, 0));
}
else if(seq.c>1)
addInterval(seq.intervalTrees[beginPosition(finder).i1], TInterval(beginPosition(finder).i2, endPosition(finder).i2, 0));
if(CounterV[beginPosition(finder).i1] == 0){//count number of sequences containing the motif, not the occurrences to avoid problems with self-overlapping
++CounterV[beginPosition(finder).i1];
++CounterV[seq.SeqsNumber];//last Position in CounterV is cumulated sum
++counter;
}
}
for( unsigned int k =0;k< length(temp);++k){//berechnet Frequenz der Nukleotide, wobei jedes Motiv wieder nur einmal pro Sequenz zählt!
seq.freqMatrix[k][temp[k]]+=CounterV[seq.SeqsNumber]; //GCAGCA --> counter der einzelnen wird um die gleiche anzahl hochgezählt, GCAGTA --> usw. Nicht-Wildcards haben W'keit 1
}
CounterV.clear();
}
void FindTopKmer(Seq &seq,
String<Dna5> &temp,
Finder<Index<StringSet<String<Dna5> > > > &finder,
unsigned int &counter,
std::vector<int> &CounterV){
typedef IntervalAndCargo<unsigned, unsigned> TInterval;
clear(finder);
//std::cout<<temp<<" vor-while"<<std::endl;
while(find(finder,temp)){//search the current Kmer in all sequences
if(seq.c==1){//nur im ersten Schritt in Intervals speichern, danach kann direkt an den Tree angefügt werden
appendValue(seq.intervals[beginPosition(finder).i1], TInterval(beginPosition(finder).i2, endPosition(finder).i2, 0));
}
else if(seq.c>1)
addInterval(seq.intervalTrees[beginPosition(finder).i1], TInterval(beginPosition(finder).i2, endPosition(finder).i2, 0));
if(CounterV[beginPosition(finder).i1] == 0){//count number of sequences containing the motif, not the occurrences to avoid problems with self-overlapping
++CounterV[beginPosition(finder).i1];
++CounterV[seq.SeqsNumber];//last Position in CounterV is cumulated sum
++counter;
}
}
for( unsigned int k =0;k< length(temp);++k){//berechnet Frequenz der Nukleotide, wobei jedes Motiv wieder nur einmal pro Sequenz zählt!
seq.freqMatrix[k][temp[k]]+=CounterV[seq.SeqsNumber]; //GCAGCA --> counter der einzelnen wird um die gleiche anzahl hochgezählt, GCAGTA --> usw. Nicht-Wildcards haben W'keit 1
}
CounterV.clear();
}
void loopOverTopKmer( Seq &seq,
String<Iupac> &temp,
String<Iupac> &Kmer,
Iterator<String<Iupac> >::Type &tempIt,
Finder<Index<StringSet<String<Dna5> > > > &finder,
unsigned int &counter,
std::vector<int> &CounterV,
IupacMaps &IMaps){
String<Dna5> replace;
Iterator<String<Dna5> >::Type replaceIt;
Iterator<String<Iupac> >::Type tempIttemp;
char resetTemp;//bei mehr als einer wildcard, müssen die weiter hinten liegenden nach abarbeitung resetet werden, ansonsten werden diese im nächsten schritt übergangen
if(tempIt==end(temp)) return;//&&(tempIt+1!=end(temp))
/*freq[*tempIt]=1;
freqMatrix[pos]=freq;
freqMatrix[pos]['A']=1;
freq.clear();*/
//std::cout<<" "<<*tempIt<<" ";
if((*tempIt == 'A' || *tempIt == 'C' ||*tempIt == 'G' ||*tempIt == 'T')){
loopOverTopKmer(seq,temp,temp,++tempIt,finder,counter,CounterV,IMaps);//only replace the position with a wildcard
return;//nach diesem schritt immer return, sonst gelangt man in eine loop
}
replace=IMaps.IupacMapReplaceReversed[*tempIt];
replaceIt = begin(replace);
for(;replaceIt!=end(replace);++replaceIt){
//std::cout<<" "<<temp<<" "<<Kmer<<" "<<*replaceIt<<std::endl;
temp = Kmer;// reset temp
resetTemp = IMaps.IupacMapInversed[replace]; //falls Y ersetzt wird, ist replace CT --> also resetTemp wieder Y
//std::cout<<" resetTemp "<<resetTemp<<std::endl;
*tempIt = *replaceIt;
//std::cout<<" re "<<temp<<" ";
tempIttemp=tempIt;//der rekursive aufruf mit diesem, da die schleife mit tempIt weitergehen soll
// std::cout<<" "<<temp<<" "<<Kmer<<" "<<*replaceIt<<std::endl;
if(tempIt+1!=end(temp)){
//std::cout<<"vor if "<<temp<<std::endl;
loopOverTopKmer(seq,temp,temp,++tempIttemp,finder,counter,CounterV,IMaps);
//std::cout<<*tempIttemp<<" tempittemp "<<std::endl;
}
//zu häufig aufgerufen
if((*tempIttemp == 'A' || *tempIttemp == 'C' || *tempIttemp == 'G' || *tempIttemp == 'T' || tempIttemp == end(temp))){//falls nicht, dann kann dies übersprungen werden
/**
posTemp gibt die Stelle an, an der man sich grad befindet
--> freqMatrix enthält für jede Position die W'keit für ACGT
--> counter ist die Anzahl wie oft das Wildcard Motiv insgesamt gefunden wurde
--> CounterV an letzter Stelle die Anzahl für das jeweilige nicht-Wildcard Motiv
--> bei GSAKYA z.B. als Motiv wird jedes Motiv bei 'S' vier mal gesucht(durch die anderen 2 Wildcards)
--> CounterV für 1 bis posTemp aufaddieren --> in freqMatrix und zwar für die jeweiligen *tempIt-chars
--> am Ende alle durch counter teilen --> aufpassen, für jeweilige pos gibts verschiedene counter
--> FindKmer wird nur mit ganzen aufgerufen, also alle addieren, dann ist der counter auch gleich?
**/
std::vector<int> CounterV(seq.SeqsNumber+1,0);
FindTopKmer(seq,temp,finder,counter,CounterV);
}
*tempIt=resetTemp;
//if ende von replaceIt, dann begin(replace) in temp speichern und mitübergeben--> referenz?
}
}
/***
Computes PWM
***/
void BuildFrequencyMatrix( Finder<Index<StringSet<String<Dna5> > > > &finder,
String<Iupac> &Kmer,
Seq &seq,
IupacMaps &IMaps){
//std::cout<<Kmer<<std::endl;
//freqMatrix -->unsigned int = position in Kmer, position 1 in map = prob. for A, pos. 2 = prob. for C...
String<Iupac> temp;
Iterator<String<Iupac> >::Type tempIt;
temp=Kmer;
tempIt = begin(temp);
unsigned int counter=0;
std::vector<int> CounterV(seq.SeqsNumber+1,0);
loopOverTopKmer(seq,temp,Kmer,tempIt,finder,counter,CounterV,IMaps);
CounterV.clear();
//loopOver funktionier, aber jetzt wird der counter nicht mehr richtig berechnet --> fixen + andere loop anpassen
//Durch die wildcards mehrere Vorkommen pro Sequence möglich:
//seqCounter[temp]=CounterV[seq.SeqsNumber];
//std::cout<<temp<<" "<<*replaceIt<<" ";
if(counter>0){//normalisieren des Counters
for( unsigned int k =0;k< length(temp);++k){
seq.freqMatrix[k]['A']=(seq.freqMatrix[k]['A']+seq.frequencies[0])/(counter+1);//corrected freq (with pseudocount)
seq.freqMatrix[k]['C']=(seq.freqMatrix[k]['C']+seq.frequencies[1])/(counter+1);
seq.freqMatrix[k]['G']=(seq.freqMatrix[k]['G']+seq.frequencies[2])/(counter+1);
seq.freqMatrix[k]['T']=(seq.freqMatrix[k]['T']+seq.frequencies[3])/(counter+1);
}
}
else
seq.freqMatrix.clear();
}
/**
Version für nicht generalisierte
**/
void BuildFrequencyMatrix( Finder<Index<StringSet<String<Dna5> > > > &finder,
String<Dna5> &Kmer,
Seq &seq,
IupacMaps &IMaps){
//std::cout<<Kmer<<std::endl;
//freqMatrix -->unsigned int = position in Kmer, position 1 in map = prob. for A, pos. 2 = prob. for C...
String<Iupac> temp;
Iterator<String<Iupac> >::Type tempIt;
temp=Kmer;
tempIt = begin(temp);
unsigned int counter=0;
std::vector<int> CounterV(seq.SeqsNumber+1,0);
FindTopKmer(seq,Kmer,finder,counter,CounterV);
CounterV.clear();
if(counter>0){//normalisieren des Counters
for( unsigned int k =0;k< length(temp);++k){
seq.freqMatrix[k]['A']=(seq.freqMatrix[k]['A']+seq.frequencies[0])/(counter+1);//corrected freq (with pseudocount)
seq.freqMatrix[k]['C']=(seq.freqMatrix[k]['C']+seq.frequencies[1])/(counter+1);
seq.freqMatrix[k]['G']=(seq.freqMatrix[k]['G']+seq.frequencies[2])/(counter+1);
seq.freqMatrix[k]['T']=(seq.freqMatrix[k]['T']+seq.frequencies[3])/(counter+1);
}
}
else
seq.freqMatrix.clear();
}
//////////////////////////////////////
//FreqMatrix output
void PrintMap( Seq &seq,
bool foreground){
std::map<Iupac,double> freq;
std::cout<<std::endl;
if(foreground)
std::cout<<"foreground: "<<std::endl;
else
std::cout<<"background: "<<std::endl;
for(unsigned int j=0;j<length(seq.freqMatrix);++j){
freq=seq.freqMatrix[j];
std::cout<<"Position: "<<j<<" A: "<<freq['A']<<std::endl;
std::cout<<"Position: "<<j<<" C: "<<freq['C']<<std::endl;
std::cout<<"Position: "<<j<<" G: "<<freq['G']<<std::endl;
std::cout<<"Position: "<<j<<" T: "<<freq['T']<<std::endl;
std::cout<<std::endl;
}
}
void BuildWeightMatrix(Seq &seq){
for(unsigned int j=0;j<length(seq.freqMatrix);++j){
seq.weightMatrix[j]['A'] = log(seq.freqMatrix[j]['A']/seq.frequencies[0]);
seq.weightMatrix[j]['C'] = log(seq.freqMatrix[j]['C']/seq.frequencies[1]);
seq.weightMatrix[j]['G'] = log(seq.freqMatrix[j]['G']/seq.frequencies[2]);
seq.weightMatrix[j]['T'] = log(seq.freqMatrix[j]['T']/seq.frequencies[3]);
}
}
void BuildInformationContentMatrix(Seq &seq){
double e = 3/(2*log(2)*seq.SeqsNumber);//4-1 = 3, 4= Anzahl Nukleotide --> small-error correction
for(unsigned int j=0;j<length(seq.freqMatrix);++j){
seq.InformationContentMatrix[j]['A'] = seq.freqMatrix[j]['A']*seq.weightMatrix[j]['A'];
seq.InformationContentMatrix[j]['C'] = seq.freqMatrix[j]['C']*seq.weightMatrix[j]['C'];
seq.InformationContentMatrix[j]['G'] = seq.freqMatrix[j]['G']*seq.weightMatrix[j]['G'];
seq.InformationContentMatrix[j]['T'] = seq.freqMatrix[j]['T']*seq.weightMatrix[j]['T'];
seq.seqLogoMatrix[j]= 2- (-(seq.InformationContentMatrix[j]['A']+seq.InformationContentMatrix[j]['C']+seq.InformationContentMatrix[j]['G']+seq.InformationContentMatrix[j]['T'])+ e);
}
}
//void ComparePWM(Seq &seq,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix1,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix2, Entropy const & tag){
//
// /***
// Matrizen müssen nicht gleich lang sein --> vorher mit fester Größe noch einmal die kMere scannen?
// Matrizen alignen?
// Im Fall der Ungleichheit --> Alle möglichen Alignments(treshold) beachten, Minimum nehmen
// ***/
//
// /****
// Für jede Spalte=Position einen Eintrag für je zwei zu vergleichende PWMs
// Eintrag ist = 0, wenn die Werte identisch sind. Je größer die Zahl, desto unterschiedlicher die Werte
// Was wenn Wert = Hintergrundverteilung? --> Eintrag wäre = 0, obwohl das nichts mit dem Motiv zu tun hat
//
// Für jede Spalte berechnen und durch Spaltenanzahl teilen
// ****/
// seq.columnEntropy[0]=0;
//
// for(unsigned int j=1;j<length(freqMatrix1)+1;++j){
// seq.columnEntropy[j] = freqMatrix1[j-1]['A']*log(freqMatrix1[j-1]['A']/freqMatrix2[j-1]['A']);
// seq.columnEntropy[j] += freqMatrix1[j-1]['C']*log(freqMatrix1[j-1]['C']/freqMatrix2[j-1]['C']);
// seq.columnEntropy[j] += freqMatrix1[j-1]['G']*log(freqMatrix1[j-1]['G']/freqMatrix2[j-1]['G']);
// seq.columnEntropy[j] += freqMatrix1[j-1]['T']*log(freqMatrix1[j-1]['T']/freqMatrix2[j-1]['T']);
// seq.columnEntropy[j] += freqMatrix2[j-1]['A']*log(freqMatrix2[j-1]['A']/freqMatrix1[j-1]['A']);
// seq.columnEntropy[j] += freqMatrix2[j-1]['C']*log(freqMatrix2[j-1]['C']/freqMatrix1[j-1]['C']);
// seq.columnEntropy[j] += freqMatrix2[j-1]['G']*log(freqMatrix2[j-1]['G']/freqMatrix1[j-1]['G']);
// seq.columnEntropy[j] += freqMatrix2[j-1]['T']*log(freqMatrix2[j-1]['T']/freqMatrix1[j-1]['T']);
// seq.columnEntropy[j] = seq.columnEntropy[j]/2;
// seq.columnEntropy[0] += seq.columnEntropy[j];
//
// }
// seq.columnEntropy[0]=seq.columnEntropy[0]/length(freqMatrix1);
//
//}
//
//void ComparePWM(Seq &seq,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix1,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix2, Euklidisch const & tag){
//
// seq.columnEntropy[0]=0;
// for(unsigned int j=1;j<length(freqMatrix1)+1;++j){
//
// seq.columnEntropy[j] = (freqMatrix1[j-1]['A'] - freqMatrix2[j-1]['A'])*(freqMatrix1[j-1]['A'] - freqMatrix2[j-1]['A']);
// seq.columnEntropy[j] += (freqMatrix1[j-1]['C'] - freqMatrix2[j-1]['C'])*(freqMatrix1[j-1]['C'] - freqMatrix2[j-1]['C']);
// seq.columnEntropy[j] += (freqMatrix1[j-1]['G'] - freqMatrix2[j-1]['G'])*(freqMatrix1[j-1]['G'] - freqMatrix2[j-1]['G']);
// seq.columnEntropy[j] += (freqMatrix1[j-1]['T'] - freqMatrix2[j-1]['T'])*(freqMatrix1[j-1]['T'] - freqMatrix2[j-1]['T']);
// seq.columnEntropy[j] = sqrt(seq.columnEntropy[j]);
// seq.columnEntropy[0] += seq.columnEntropy[j];
// }
// seq.columnEntropy[0]=seq.columnEntropy[0]/length(freqMatrix1);//enthält durchschnitt der spalten
//
//}
/****
Speichert die jeweiligen Mittelwerte der 2 übergebenen Matrizen
****/
void BuildMeanOf2PWMs(Seq &seq,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix1,std::map<unsigned int,std::map<Iupac,double> > &freqMatrix2){
/*for(unsigned int j=0;j<length(freqMatrix1);++j){
freqMatrix1[j]['A'] = (freqMatrix1[j]['A']+freqMatrix2[j]['A']);
freqMatrix1[j]['C'] = (freqMatrix1[j]['C']+freqMatrix2[j]['C']);
freqMatrix1[j]['G'] = (freqMatrix1[j]['G']+freqMatrix2[j]['G']);
freqMatrix1[j]['T'] = (freqMatrix1[j]['T']+freqMatrix2[j]['T']);
}*/
}
void PWMClustering(Seq &seq){
String<double> minDifference;
resize(minDifference,3);
unsigned allPWMsLength=length(seq.allPWMs);
String<String<double > > compare;
String<double> compareTemp;
/*for(unsigned int i=0;i<allPWMsLength-1;++i){
for(unsigned int j=i+1;j<allPWMsLength;++j){
ComparePWM(seq,seq.allPWMs[i],seq.allPWMs[j],Euklidisch());
appendValue(compareTemp,seq.columnEntropy[0]);
if(minDifference==0 || minDifference>seq.columnEntropy[0]){
minDifference[0]=seq.columnEntropy[0];
minDifference[1]=i;
minDifference[2]=j;
}
}
appendValue(compare,compareTemp);
clear(compareTemp);
}
std::cout<<length(compare)<<" "<<length(compare[0])<<" "<<length(compare[1])<<std::endl;
std::cout<<compare[0][0]<<" "<<compare[0][1]<<" "<<compare[1][0];
*/
while(minDifference[0]<1){
BuildMeanOf2PWMs(seq,seq.allPWMs[minDifference[1]],seq.allPWMs[minDifference[2]]);//bildet aus 2PWMs die Mittelwerte und speichert sie in
//UpdatePWMMatrix();
}
}
/*Prints the Mapping:
Kmer Seq1 Seq2 ... Seqn CumulatedCounter
-->Template
*/
void PrintMap( std::map<String<Dna5>,unsigned int> &Dna5CounterMap,
unsigned int SeqsNumber){
std::cout<<std::endl;
std::map<String<Dna5>,unsigned int>::iterator MapIterator;
for(MapIterator=Dna5CounterMap.begin(); MapIterator !=Dna5CounterMap.end();++MapIterator){
std::cout<<(*MapIterator).first<<" ";
std::cout<<(*MapIterator).second<<" ";
std::cout<<std::endl;
}
}
void PrintMap( std::map<String<Iupac>,unsigned int > &Dna5CounterMap,
unsigned int SeqsNumber){
std::cout<<std::endl;
std::map<String<Iupac>,unsigned int >::iterator MapIterator;
for(MapIterator=Dna5CounterMap.begin(); MapIterator !=Dna5CounterMap.end();++MapIterator){
std::cout<<(*MapIterator).first<<" ";
std::cout<<(*MapIterator).second<<" ";
std::cout<<std::endl;
}
}
void PrintMap(std::multimap<double,String<Dna5> > &pValueMap){
std::multimap<double,String<Dna5> >::iterator MapIterator;
for(MapIterator=pValueMap.begin();MapIterator !=pValueMap.end();++MapIterator){
std::cout<<(*MapIterator).first<<" ";
std::cout<<(*MapIterator).second<<std::endl;
}
}
void PrintMap(std::multimap<double,String<Iupac> > &pValueMap){
std::multimap<double,String<Iupac> >::iterator MapIterator;
//std::cout<<pValueMap.size()<<std::endl;
int i=0;
for(MapIterator=pValueMap.begin();MapIterator !=pValueMap.end() && i<10;++MapIterator,++i){
std::cout<<(*MapIterator).first<<" ";
std::cout<<(*MapIterator).second<<std::endl;
}
}
//to print the generalizedKmerMap
void PrintMap(std::map<String<Iupac>,unsigned int> &generalizedKmer){
std::map<String<Iupac>, unsigned int>::iterator MapIterator;
int i=0;
for(MapIterator=generalizedKmer.begin();MapIterator!=generalizedKmer.end() && i<20;++MapIterator,++i){
std::cout<<(*MapIterator).first<<" ";
std::cout<<(*MapIterator).second<<" ";
}
}
//Test the Map-lengths match eachother and with the sequences
void DebugMap( Seq &seq,
Seq &back,
std::map<String<Dna5>,std::vector<int> > &sequencesCounter,
std::map<String<Dna5>,std::vector<int> > &backgroundCounter){
typedef std::map<String<Dna5>,std::vector<int> > Dna5CounterMap;
Dna5CounterMap::iterator MapIterator;
MapIterator=sequencesCounter.begin();
Dna5CounterMap::iterator MapIteratorB;
MapIteratorB=backgroundCounter.begin();
SEQAN_ASSERT_EQ(length(sequencesCounter),length(backgroundCounter));
SEQAN_ASSERT_EQ(length((*MapIterator).second),(length(seq.ids)+1));//+1, because of the last field in vector
SEQAN_ASSERT_EQ(length((*MapIteratorB).second),(length(back.ids)+1));
//std::cout<<length(sequencesCounter)<<std::endl;
//std::cout<<length((*MapIterator).second)<<std::endl;
//std::cout<<length(backgroundCounter)<<std::endl;
//std::cout<<length((*MapIteratorB).second)<<std::endl;
//std::cout<<length(seq.ids)<<std::endl;
//std::cout<<length(back.ids)<<std::endl;
}
void DebugMultiMap( std::map<String<Dna5>,std::vector<int> > &sequencesCounter,
std::multimap<double,String<Dna5> > &SortedPValue){
SEQAN_ASSERT_EQ(length(sequencesCounter),SortedPValue.size());
}
void logFactorial(unsigned int len){
double* p;
unsigned int i=1;
p = (double*)malloc(sizeof(double)*(len+1));
p[0]=0;
for(;i<=len;++i){
p[i]= p[i-1] + log(i);
}
logFac =p;
}
double calcFET( unsigned int a,
unsigned int b,
unsigned int c,
unsigned int d){
return exp(logFac[a+b] + logFac[c+d] + logFac[a+c] + logFac[b+d] -
(logFac[a+b+c+d] + logFac[a]+ logFac[b] + logFac[c] +logFac[d]));
}
void modifyFET( unsigned int a,
unsigned int b,
unsigned int c,
unsigned int d,
double &pValue){
pValue= calcFET(a,b,c,d);
// //std::cout<<(*MapI).first<<" "<<pValue<<" ";
while(b!=0 && c!=0){//modify to be more extrem
++a;
--b;
--c;
++d;
pValue += calcFET(a,b,c,d);
// //std::cout<<pValue<<" ";
}
}
/***************************
log((a+b)!(c+d)!(a+c)!(b+d)!/a!b!c!d!n!) = logFactorial(a+b) + logFactorial(c+d) +
logFactorial(a+c) + logFactorial(b+d) -
(logFactorial(a+b+c+d) + logFactorial(a)+
logFactorial(b) + logFactorial(c) +
logFactorial(d))
pValue = exp(log((a+b)!(c+d)!(a+c)!(b+d)!/a!b!c!d!n!))
a=In Sequenz gefunden b=In Background gefunden
c=In Sequenz !gefunden d=In Background !gefunden
a = sequenceCounter b= backgroundCounter
a+c=SeqsNumber b+d=backgroundNumber
--> c= SeqsNumber - cumulated(sequenceCounter)
d= backgroundNumber - cumulated(backgroundCounter)
Für den einseitigen Test zusätzlich:
++a und --c
Für den zweiseitigen Test:
++a und --c
--a und ++c
****************************/
void FisherExactTest(Seq &seq,
Seq &back){
double pValue=0;
typedef std::map<String<Dna5>,unsigned int >::iterator MapIterator;
MapIterator MapI=seq.seqCounter.begin();
MapIterator MapIB=back.seqCounter.begin();
//std::cout<<(*MapI).first<<" "<<(*MapI).second.back()<<std::endl;
//std::cout<<(*MapIB).first<<" "<<(*MapIB).second.back()<<std::endl;
for(;MapI!=seq.seqCounter.end();++MapI,++MapIB){
modifyFET((*MapI).second,(*MapIB).second,(seq.SeqsNumber - (*MapI).second),(back.SeqsNumber - (*MapIB).second),pValue);
//std::cout<<pValue<<std::endl;
//SortedPValue[pValue]=(*MapI).first;
seq.SortedPValue.insert(std::pair<double,String<Dna5> > (pValue, (*MapI).first));
seq.SortedPValueReversed.insert(std::pair<String<Iupac>,double > ((*MapI).first,pValue));
}
}
//--> templates verwenden
void FisherExactTest(std::map<String<Iupac>,unsigned int > &SequenceCounter,
std::map<String<Iupac>,unsigned int > &BackgroundCounter,
Seq &seq,
Seq &back){
double pValue=0;
typedef std::map<String<Iupac>,unsigned int >::iterator MapIterator;
MapIterator MapI=SequenceCounter.begin();
MapIterator MapIB=BackgroundCounter.begin();
//std::cout<<(*MapI).first<<" "<<(*MapI).second.back()<<std::endl;
//std::cout<<(*MapIB).first<<" "<<(*MapIB).second.back()<<std::endl;
for(;MapI!=SequenceCounter.end();++MapI,++MapIB){
modifyFET((*MapI).second,(*MapIB).second,(seq.SeqsNumber - (*MapI).second),(back.SeqsNumber - (*MapIB).second),pValue);
seq.generalizedSortedPValue.insert(std::pair<double,String<Iupac> > (pValue, (*MapI).first));
seq.SortedPValueReversed.insert(std::pair< String<Iupac>,double> ((*MapI).first,pValue));
}
}
/*
Fisher-Exact-Test for generalized Kmere
*/
double FisherExactTest( Seq &seq,
Seq &back,
std::multimap<double,String<Iupac> > &GeneralizedSortedPValueTemp){
//std::cout<<"begin Fisher "<<seq.generalizedKmer.size()<<" "<<back.generalizedKmer.size()<<std::endl;
if(seq.generalizedKmer.size()==0)
return 2;
typedef std::map<String<Iupac>,unsigned int >::iterator MapIterator;
std::multimap<double,String<Iupac> >::iterator MapIterator2;
MapIterator MapI = seq.generalizedKmer.begin();
MapIterator MapIB= back.generalizedKmer.begin();
double pValue=0;
//std::cout<<generalizedKmerSequence.size();
for(;MapI!=seq.generalizedKmer.end();++MapI,++MapIB){
if((*MapI).second > seq.SeqsNumber || (*MapIB).second > back.SeqsNumber){ std::cout<<(*MapI).first<<" "<<(*MapI).second<<" "<<(*MapIB).first<<" "<<(*MapIB).second<<std::endl;}
modifyFET((*MapI).second,(*MapIB).second,seq.SeqsNumber - (*MapI).second,back.SeqsNumber - (*MapIB).second,pValue);
GeneralizedSortedPValueTemp.insert(std::pair<double,String<Iupac> > (pValue, (*MapI).first));//not seq.generalizedSortedPValue, because this is the temp one
seq.SortedPValueReversed.insert(std::pair<String<Iupac>,double > ((*MapI).first,pValue));
}
return GeneralizedSortedPValueTemp.begin()->first;
}
//void DebugFisherExact(unsigned int a,unsigned int b,unsigned int c,unsigned int d){
//
// double pValue=0;
// if(c<a || d < b){
// std::cerr<<"Cumulated Counter too large";
// exit(1);
// }
// c=c-a;
// d=d-b;
// SEQAN_ASSERT_EQ((logFactorial(2+1+4+2)),(logFactorial(9)));
//
// std::cout<<"a: "<<a<<" b: "<<b<<" c: "<<c<<" d: "<<d<<std::endl;
// pValue= logFactorial(a+b) + logFactorial(c+d) + logFactorial(a+c) + logFactorial(b+d) - (logFactorial(a+b+c+d) + logFactorial(a)+ logFactorial(b) + logFactorial(c) +logFactorial(d));
// std::cout<<"log(pValue) "<<pValue<<std::endl;
// pValue=logFactorial(a+b) + logFactorial(c+d) + logFactorial(a+c) + logFactorial(b+d) ;
// std::cout<<"the dividend: "<<pValue<<std::endl;
// pValue=- (logFactorial(2+1+4+2) + logFactorial(2)+ logFactorial(1) + logFactorial(4) +logFactorial(2));
// std::cout<<"the divisor: "<<pValue<<std::endl;
// pValue= (logFactorial(1));
// std::cout<<"logFactorial(1): "<<pValue<<std::endl;
// pValue= (logFactorial(0));
// std::cout<<"logFactorial(0): "<<pValue<<std::endl;
//
//
//}
void MapIupac(IupacMaps &IMaps ){
IMaps.IupacMap.get_allocator().allocate(16);
IMaps.IupacMap[0]='U';
IMaps.IupacMap[1]='T';
IMaps.IupacMap[2]='A';
IMaps.IupacMap[3]='W';
IMaps.IupacMap[4]='C';
IMaps.IupacMap[5]='Y';
IMaps.IupacMap[6]='M';
IMaps.IupacMap[7]='H';
IMaps.IupacMap[8]='G';
IMaps.IupacMap[9]='K';
IMaps.IupacMap[10]='R';
IMaps.IupacMap[11]='D';
IMaps.IupacMap[12]='S';
IMaps.IupacMap[13]='B';
IMaps.IupacMap[14]='V';
IMaps.IupacMap[15]='N';
IMaps.IupacMapReversed.get_allocator().allocate(16);
IMaps.IupacMapReversed['U']=0;
IMaps.IupacMapReversed['T']=1;
IMaps.IupacMapReversed['A']=2;
IMaps.IupacMapReversed['W']=3;
IMaps.IupacMapReversed['C']=4;
IMaps.IupacMapReversed['Y']=5;
IMaps.IupacMapReversed['M']=6;
IMaps.IupacMapReversed['H']=7;
IMaps.IupacMapReversed['G']=8;
IMaps.IupacMapReversed['K']=9;
IMaps.IupacMapReversed['R']=10;
IMaps.IupacMapReversed['D']=11;
IMaps.IupacMapReversed['S']=12;
IMaps.IupacMapReversed['B']=13;
IMaps.IupacMapReversed['V']=14;
IMaps.IupacMapReversed['N']=15;
IMaps.IupacMapReplace.get_allocator().allocate(14);
IMaps.IupacMapReplace['R']="CT";//in Iupac-notation R=AG --> CT left
IMaps.IupacMapReplace['Y']="AG";
IMaps.IupacMapReplace['S']="AT";
IMaps.IupacMapReplace['W']="CG";
IMaps.IupacMapReplace['K']="AC";
IMaps.IupacMapReplace['M']="GT";
IMaps.IupacMapReplace['D']="C";
IMaps.IupacMapReplace['H']="G";
IMaps.IupacMapReplace['B']="A";
IMaps.IupacMapReplace['V']="T";
IMaps.IupacMapReplace['A']="CGT";
IMaps.IupacMapReplace['C']="AGT";
IMaps.IupacMapReplace['G']="ACT";
IMaps.IupacMapReplace['T']="ACG";
IMaps.IupacMapReplaceReversed.get_allocator().allocate(11);
IMaps.IupacMapReplaceReversed['R']="AG";
IMaps.IupacMapReplaceReversed['Y']="CT";
IMaps.IupacMapReplaceReversed['S']="CG";
IMaps.IupacMapReplaceReversed['W']="AT";
IMaps.IupacMapReplaceReversed['K']="GT";
IMaps.IupacMapReplaceReversed['M']="AC";
IMaps.IupacMapReplaceReversed['D']="AGT";
IMaps.IupacMapReplaceReversed['H']="ACT";
IMaps.IupacMapReplaceReversed['B']="CGT";
IMaps.IupacMapReplaceReversed['V']="ACG";
IMaps.IupacMapReplaceReversed['N']="ACGT";
IMaps.IupacMapInversed.get_allocator().allocate(11);
IMaps.IupacMapInversed["AG"]='R';
IMaps.IupacMapInversed["CT"]='Y';
IMaps.IupacMapInversed["CG"]='S';
IMaps.IupacMapInversed["AT"]='W';
IMaps.IupacMapInversed["GT"]='K';
IMaps.IupacMapInversed["AC"]='M';
IMaps.IupacMapInversed["AGT"]='D';
IMaps.IupacMapInversed["ACT"]='H';
IMaps.IupacMapInversed["CGT"]='B';
IMaps.IupacMapInversed["ACG"]='V';
IMaps.IupacMapInversed["ACGT"]='N';
}
/* - initiate by repeatedly picking the top motifs from SortedPValue
- calls GeneralizeKmer and the EstimateFunction
*/
void InitGeneralization(IupacMaps &IMaps,
Seq &seq,
Seq &back){
std::multimap<double,String<Dna5> >::iterator MapIterator;
std::multimap<double,String<Iupac> >::iterator MapIteratorT;
std::multimap<double,String<Iupac> > generalizedSortedPValueTemp;
std::map<String<Iupac>,unsigned int> generalizedKmerTemp;
std::map<String<Iupac>,unsigned int> generalizedKmerBackgroundTemp;
unsigned int i=0;
unsigned int limit;
if(seq.SortedPValue.size()>seq.seed) limit=seq.seed;//seed meist = 100
else if(seq.SortedPValue.size()==0) return;
else limit = seq.SortedPValue.size();
for(MapIterator=seq.SortedPValue.begin();i<limit;++MapIterator,++i){//iterate over Top100
GeneralizeKmer((*MapIterator).second,IMaps,seq,back);
}
/*
- only do the next function call, if in the last at least one pValue<treshold
- call GeneralizeKmer in loop
*/
//PrintMap(seq.generalizedKmer);
//seq.generalizedSortedPValue.insert(seq.SortedPValue.begin(),seq.SortedPValue.end());
double topPValue = FisherExactTest(seq,back,generalizedSortedPValueTemp);// lowest pValue from the first generalization
double topPValueOld =seq.SortedPValue.begin()->first;//lowest pValue before generalization
while(topPValue<0.05 && topPValue<topPValueOld){//only start a new round, if the top PValue is an improvement of the old one
/*
while wird das erste mal mit generalizedKmer aufgerufen und dem tempor√§ren mapping der pValues
das tempor√§re mapping wird in das richtige mapping gemerged und gecleant, damit geschaut werden kann, ob bei den neuen pValues ein wert
über dem treshold ist --> falls nicht bricht die while ab
falls doch wird generalizedKmer kopiert und gecleant aus dem gleichen grund, damit, nur die neuen generalisierten Kmere untersucht werden
--> das Temp hier, um über alle alten zu gehen, um diese weiter zu generalisieren
*/
seq.generalizedSortedPValue.insert(generalizedSortedPValueTemp.begin(),generalizedSortedPValueTemp.end());
generalizedKmerTemp.clear();
generalizedKmerBackgroundTemp.clear();
generalizedKmerTemp=seq.generalizedKmer;
generalizedKmerBackgroundTemp=back.generalizedKmer;
back.generalizedKmer.clear();
seq.generalizedKmer.clear();
// generalizedMapIterator= generalizedKmerTemp.begin();
if(generalizedSortedPValueTemp.size()>seq.seed) limit=seq.seed;
else if(generalizedSortedPValueTemp.size()==0) return;
else limit = generalizedSortedPValueTemp.size();
i=0;//only Top100
for(MapIteratorT=generalizedSortedPValueTemp.begin();i<limit;++MapIteratorT,++i){//iterate over Top100
//Temp ums zu finden, aber das normale auch übergeben, zum neu befüllen
GeneralizeKmer((*MapIteratorT).second,generalizedKmerTemp,generalizedKmerBackgroundTemp,IMaps,seq,back);
}
generalizedSortedPValueTemp.clear();
//std::cout<<"nach for"<<std::endl;
topPValueOld =topPValue;
topPValue = FisherExactTest(seq,back,generalizedSortedPValueTemp);
//std::cout<<"nach Fisher "<<topPValue<<" "<<topPValueOld<<std::endl;
};
}
/* - gets a Kmer and replaces each position successively with each possible ambiguity Code(Iupac)
- only one wildcard per String at one time
- the unsigned int corresponds to the estimated counter
- String<Dna5> for initialization
*/
void GeneralizeKmer(String<Dna5> Kmer,
IupacMaps &IMaps,
Seq &seq,
Seq &back){
String<Iupac> temp;//temporary String --> generalizedKmer[temp]
String<Iupac> temp2;//Kmer with replaced position--> relevant for estimateCounter
Iterator<String<Iupac> >::Type tempIt;//Iterator over temp --> same length as Kmer
String<Dna5> replace = "ACGT";//replace the current position with each possible ambiguity code --> A,C,G or T
Iterator<String<Dna5> >::Type replaceIt;
unsigned int counter =0;
char tempChar;
//replaceIt = begin(replace);
temp = Kmer;
temp2=Kmer;
tempIt = begin(temp);
for(;tempIt!=end(temp);++tempIt){//loop over each position in kmer
replaceIt = begin(replace);
for(;replaceIt!=end(replace);++replaceIt){// loop over ACGT
temp = Kmer;// reset temp
if(*tempIt == *replaceIt) continue; // there is no Iupac for "AA", in return "AG" = "R"
//std::cout<<temp<<" ";
tempChar =*tempIt;//stores the current char because of temp2
*tempIt=*replaceIt;
temp2=temp;//temp2 ist nun das mit dem char für die neue wildcard
*tempIt=tempChar;//temp wieder das alte, wird aber im nächsten schritt mit einer neuen wildcard ergänzt
*tempIt =IMaps.IupacMap[IMaps.IupacMapReversed[*tempIt] + IMaps.IupacMapReversed[*replaceIt]];//compute Iupac-letter--> A + G = R and replace the current location in temp
//std::cout<<Kmer<<" "<<temp<<" "<<temp2<<std::endl;
if(seq.generalizedKmer.find(temp)!=seq.generalizedKmer.end()) continue;// if Kmer is in the Map -->nothing to do
//estimateCounter mit Kmer und temp2 aufrufen --> Kmer=AAA temp2=TAA temp=WAA
estimateCounter(seq,Kmer,temp2,counter);
seq.generalizedKmer[temp]=counter;//temp ist das neue motiv
estimateCounter(back,Kmer,temp2,counter);
back.generalizedKmer[temp]=counter;
}
}
//PrintMap(seq.generalizedKmer);
}
/* - the same as above except that each String has already a wildcard
*/
void GeneralizeKmer(String<Iupac> Kmer,
std::map<String<Iupac>,unsigned int> &generalizedKmerTemp,
std::map<String<Iupac>,unsigned int> &generalizedKmerBackgroundTemp,
IupacMaps &IMaps,
Seq &seq,
Seq &back){
String<Iupac> temp;//temporary String --> generalizedKmer[temp]
String<Iupac> temp2;//Kmer with replaced position--> relevant for estimateCounter
Iterator<String<Iupac> >::Type tempIt;//Iterator over temp --> same length as Kmer
String<Iupac> replace;
Iterator<String<Iupac> >::Type replaceIt;
unsigned int counter =0;
char tempChar;
temp = Kmer;
tempIt = begin(temp);
//std::cout<<temp<<" ";
for(;tempIt!=end(temp);++tempIt){//loop over each position in kmer
//if(*tempIt == 'A' || *tempIt == 'C' ||*tempIt == 'G' ||*tempIt == 'T') continue;//only replace the position with a wildcard
if(*tempIt =='N')continue;//gibt nichts mehr zu ersetzen
replace=IMaps.IupacMapReplace[*tempIt];
replaceIt = begin(replace);
for(;replaceIt!=end(replace);++replaceIt){// loop over the replacement-chars, W=AT --> replace=CG
temp = Kmer;// reset temp
//std::cout<<*replaceIt<<std::endl;
tempChar =*tempIt;//stores the current char because of temp2
*tempIt=*replaceIt;//replace the current char for temp2
temp2=temp;
*tempIt=tempChar;
*tempIt =IMaps.IupacMap[IMaps.IupacMapReversed[*tempIt] + IMaps.IupacMapReversed[*replaceIt]];
if(seq.SortedPValueReversed[Kmer] >= 0.05 || seq.SortedPValueReversed[temp2] >= 0.05) continue;//only if Kmer and temp2 are significant estimate the counter
if(generalizedKmerTemp.find(temp)!=generalizedKmerTemp.end()) continue;
//std::cout<<Kmer<<" "<<temp<<" "<<temp2<<std::endl;
estimateCounter(seq,generalizedKmerTemp,Kmer,temp2,counter);
seq.generalizedKmer[temp]=counter;
estimateCounter(back,generalizedKmerBackgroundTemp,Kmer,temp2,counter);
back.generalizedKmer[temp]=counter;
//std::cout<<temp<<" "<<counter<<std::endl;
}
}
/**
- gehe über Kmer --> if ACGT continue
- else rufe IupacMapReplace auf
- -->for(;replaceIt!=end(replace);++replaceIt) --> loop über den String aus IupacMapReplace
- temp ist das neue Kmer und temp2 die neue wildcard--> estimateCounter aufrufen --> für fore- und background
- funktion wird in for-schleife aufgerufen --> geht über alle
- clear generaliedKmer vor der for-schleife
- --> wird neu befüllt und kann mit FisherExact aufgerufen werden
- SortedPValue wird berechnet (in temp) und überprüft ob noch ein wert drunter ist-->falls ja insertiere temp in den rest
- falls nein nehme die top100 und rufe exactSearch auf
**/
}
//void loopOverRecplacement(String<Iupac> &temp,String<Iupac> &temp2,String<Iupac> Kmer,Iterator<String<Iupac> >::Type tempIt,unsigned int counter){
// char tempChar;
// String<Iupac> replace;
// Iterator<String<Iupac> >::Type replaceIt;
//
// replace=IupacMapReplace[*tempIt];
// replaceIt = begin(replace);
//
// for(;replaceIt!=end(replace);++replaceIt){// loop over the replacement-chars
// temp = Kmer;// reset temp
// tempChar =*tempIt;//stores the current char because of temp2
// *tempIt=*replaceIt;//replace the current char for temp2
// temp2=temp;
// *tempIt=tempChar;
//
// *tempIt =IupacMap[IupacMapReversed[*tempIt] + IupacMapReversed[*replaceIt]];
// //only if Kmer and temp2 are significant estimate the counter
// if(generalizedKmerTemp.find(temp)!=generalizedKmerTemp.end()) continue;
// estimateCounter(SequenceCounter,generalizedKmerTemp,Kmer,temp2,counter,SeqsNumber);
// generalizedKmer[temp]=counter;
// estimateCounter(BackgroundCounter,generalizedKmerBackgroundTemp,Kmer,temp2,counter,BackgroundNumber);
// generalizedKmerBackground[temp]=counter;
// //std::cout<<temp<<" "<<counter<<std::endl;
// }
//
//}
/*
- estimates the Counter for the initial wildcard-Kmere
- SequencesCounter and BackgroundCounter
*/
void estimateCounter(Seq &seq,
String<Iupac> temp,
String<Iupac> temp2,
unsigned int &counter){
//std::cout<<temp<<" "<<temp2<<std::endl;
unsigned int RE1=seq.seqCounter.find(temp)->second;//das alte motiv aus dem letzten schritt
if(seq.seqCounter.find(temp2)!=seq.seqCounter.end()){//falls temp2 ein altes motiv ist, hat es einen counter
counter= RE1+ seq.seqCounter.find(temp2)->second - (RE1*seq.seqCounter.find(temp2)->second)/seq.SeqsNumber;
//std::cout<<temp<<" "<<temp2<<" "<<RE1<<" "<<SequenceCounter.find(temp2)->second.back()<<" "<<counter<<std::endl;
if(counter>seq.SeqsNumber){ std::cout<<"if "<<counter<<" "<<temp<<" "<<RE1<<" "<<temp2<<" "<<seq.seqCounter.find(temp2)->second<<" SeqsNumer "<<seq.SeqsNumber<<std::endl;
system("PAUSE");
}
}
else{
counter=RE1;//RE2=0, da noch nicht vorhanden
//std::cout<<"else "<<counter<<std::endl;
if(counter>seq.SeqsNumber){ std::cout<<"else "<<counter<<" "<<temp<<" "<<RE1<<" "<<temp2<<" SeqsNumer "<<seq.SeqsNumber<<std::endl;
system("PAUSE");
}
}
}
/*
- estimated the Counter for the next Kmer
*/
void estimateCounter(Seq &seq,
std::map<String<Iupac>,unsigned int> &generalizedKmer,
String<Iupac> temp,
String<Iupac> temp2,
unsigned int &counter){
if(generalizedKmer.find(temp)== generalizedKmer.end()){
std::cerr<<"Error, could not find "<<temp<<" in generalizedKmer"<<std::endl;
std::exit(1);
}
//String<Iupac>="AAWR";
unsigned int RE1=(*generalizedKmer.find(temp)).second;//the new seed RE is a Kmer with wildcard
//temp2 may be in generalizedKmer or in SequenceCounter
if(seq.seqCounter.find(temp2)!=seq.seqCounter.end()){// if temp2 is in SequenceCounter do the same as above --> has no wildcard
counter= RE1+ seq.seqCounter.find(temp2)->second- (RE1*seq.seqCounter.find(temp2)->second)/seq.SeqsNumber;
//std::cout<<temp<<" "<<temp2<<" "<<RE1<<" "<<SequenceCounter.find(temp2)->second.back()<<" "<<counter<<std::endl;
if(counter>seq.SeqsNumber){ std::cout<<"if "<<counter<<" "<<temp<<" "<<RE1<<" "<<temp2<<" "<<seq.seqCounter.find(temp2)->second<<" SeqsNumer "<<seq.SeqsNumber<<std::endl;
system("PAUSE");
}
}
else if(generalizedKmer.find(temp2)!=generalizedKmer.end()){//if temp2 has a wildcard and is found in generalizedKmer
counter= RE1+ generalizedKmer.find(temp2)->second - (RE1*generalizedKmer.find(temp2)->second)/seq.SeqsNumber;
//std::cout<<temp<<" "<<temp2<<" "<<RE1<<" "<<generalizedKmer.find(temp2)->second<<" "<<counter<<std::endl;
if(counter>seq.SeqsNumber){ std::cout<<"elif "<<counter<<" "<<temp<<" "<<RE1<<" "<<temp2<<" "<<generalizedKmer.find(temp2)->second<<" SeqsNumer "<<seq.SeqsNumber<<std::endl;
system("PAUSE");
}
}
else{//if temp2 is not found
counter= RE1;//RE2=0
if(counter>seq.SeqsNumber){ std::cout<<"else "<<counter<<" "<<temp<<" "<<RE1<<" "<<temp2<<" SeqsNumer "<<seq.SeqsNumber<<std::endl;
system("PAUSE");
}
}
}
void exactGeneralizeCount( std::map<String<Iupac>,unsigned int > &seqCounter,
std::map<String<Iupac>,unsigned int > &backCounter,
Finder<Index<StringSet<String<Dna5> > > > &finder,
Finder<Index<StringSet<String<Dna5> > > > &finderB,
Seq &seq,
Seq &back,
IupacMaps &IMap){
std::multimap<double,String<Iupac> >::iterator generalizedSortedPValueIt;
//std::map<String<Iupac>,double > generalizedSortedPValueReversed;
generalizedSortedPValueIt = seq.generalizedSortedPValue.begin();
for(unsigned int i=0;i<seq.seed && generalizedSortedPValueIt!=seq.generalizedSortedPValue.end() ;++i,++generalizedSortedPValueIt){
//std::cout<<length(seq.generalizedSortedPValue)<<" "<<seq.generalizedSortedPValue.size()<<" ";
//std::cout<<(*generalizedSortedPValueIt).second<<" ";
if(seqCounter.find((*generalizedSortedPValueIt).second)!=seqCounter.end()) continue;
CountKmer(seqCounter,finder,(*generalizedSortedPValueIt).second,seq,IMap);
CountKmer(backCounter,finderB,(*generalizedSortedPValueIt).second,back,IMap);
}
seq.generalizedSortedPValue.clear();
//PrintMap(seqCounter,seq.SeqsNumber);
FisherExactTest(seqCounter,backCounter,seq,back);//computes the pValue of each Motif due to the counter
std::cout<<std::endl;
//PrintMap(seq.generalizedSortedPValue);
seqCounter.clear();
backCounter.clear();
}
#endif // #ifndef SANDBOX_MEYERCLP_APPS_DREME_H_ | bkahlert/seqan-research | raw/pmbs12/pmsb13-data-20120615/sources/brbym28nz827lxic copy/578/sandbox/meyerclp/apps/dreme/dreme.h | C | mit | 56,343 |
#include <msp430.h>
#include "uart.h"
/**
* Receive Data (RXD) at P1.1
* Transmit Data (TXD) at P1.2
*/
#define RXD BIT1
#define TXD BIT2
/**
* Callback handler for recieving data through the UART buffer
*/
void (*uart_rx_isr_ptr)(unsigned char c);
void uart_init(void) {
// initialize the function pointer to NULL
uart_set_rx_isr_ptr(0L);
// Select the recieve and transmit pins
P1SEL = RXD + TXD;
P1SEL2 = RXD + TXD;
// SMCLK
UCA0CTL1 |= UCSSEL_2;
// 1MHz 9600
UCA0BR0 = 104;
UCA0BR1 = 0;
// Modulation UCBRSx = 1
UCA0MCTL = UCBRS0;
// Initialize USCI state machine
UCA0CTL1 &= ~UCSWRST;
// Enable USCI_A0 RX interrupt
IE2 |= UCA0RXIE;
}
void uart_set_rx_isr_ptr(void (*isr_ptr)(unsigned char c)) {
uart_rx_isr_ptr = isr_ptr;
}
unsigned char uart_get_character() {
// USCI_A0 RX buffer ready? If so return the character from the buffer
while (!(IFG2&UCA0RXIFG));
return UCA0RXBUF;
}
void uart_put_character(unsigned char c) {
// USCI_A0 TX buffer ready? If so, pass the next character from the buffer
while (!(IFG2&UCA0TXIFG));
UCA0TXBUF = c;
}
void uart_put_string(const char *str) {
while(*str) uart_put_character(*str++);
}
__attribute__ ((interrupt(USCIAB0RX_VECTOR)))
void USCI0RX_ISR(void) {
if(uart_rx_isr_ptr != 0L) {
(uart_rx_isr_ptr)(UCA0RXBUF);
}
} | mpiannucci/HelloMSP430 | source/uart.c | C | mit | 1,394 |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2009 Jason Booth
Copyright (c) 2011-2012 openxlive.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
public class MenuLayerPriorityTest : CCLayer
{
private CCMenu m_pMenu1;
private CCMenu m_pMenu2;
private bool m_bPriority;
public MenuLayerPriorityTest()
{
}
public override void OnEnter()
{
base.OnEnter();
// Testing empty menu
m_pMenu1 = new CCMenu();
m_pMenu2 = new CCMenu();
// Menu 1
CCMenuItemFont item1 = new CCMenuItemFont("Return to Main Menu", menuCallback);
CCMenuItemFont item2 = new CCMenuItemFont("Disable menu for 5 seconds", disableMenuCallback);
m_pMenu1.AddChild(item1);
m_pMenu1.AddChild(item2);
m_pMenu1.AlignItemsVertically(2);
AddChild(m_pMenu1);
// Menu 2
m_bPriority = true;
//CCMenuItemFont.setFontSize(48);
item1 = new CCMenuItemFont("Toggle priority", togglePriorityCallback);
item1.Scale = 1.5f;
item1.Color = new CCColor3B(0, 0, 255);
m_pMenu2.AddChild(item1);
AddChild(m_pMenu2);
}
public void menuCallback(object pSender)
{
((CCLayerMultiplex) Parent).SwitchTo(0);
}
public void disableMenuCallback(object pSender)
{
m_pMenu1.Enabled = false;
CCDelayTime wait = new CCDelayTime (5);
CCCallFunc enable = new CCCallFunc(enableMenuCallback);
CCFiniteTimeAction seq = new CCSequence(wait, enable);
m_pMenu1.RunAction(seq);
}
private void enableMenuCallback()
{
m_pMenu1.Enabled = true;
}
private void togglePriorityCallback(object pSender)
{
// if (m_bPriority)
// {
// m_pMenu2.HandlerPriority = (CCMenu.DefaultMenuHandlerPriority + 20);
// m_bPriority = false;
// }
// else
// {
// m_pMenu2.HandlerPriority = (CCMenu.DefaultMenuHandlerPriority - 20);
// m_bPriority = true;
// }
}
}
}
| hig-ag/CocosSharp | tests/tests/classes/tests/MenuTest/MenuLayerPriorityTest.cs | C# | mit | 3,665 |
---
layout: default
---
<div id="home">
<div id="header">
<div class="container text-center">
<h1 id="title">Júlio César</h1>
<p id="intro">
Brazilian software developer graduated on Computer Science at <a href="http://ufabc.edu.br/" target="_blank">Universidade Federal do ABC</a>, who always finds some time to his lifelong companions: <a href="http://steamcommunity.com/id/thejcs" target="_blank">gaming</a> and <a href="https://github.com/julioc" target="_blank">coding</a><br/>
Sporadically, I spend my time on the offline world too…
</p>
</div>
</div>
<div class="container">
<div id="contact">
<p>In case you want to <strike>stalk</strike> know me better, you can click throught the links:</p>
<ul id="social" class="list-inline">
<li>
<a target="_blank" href="https://github.com/julioc" class="fa-stack fa-lg social-github">
<i class="fa fa-github-square fa-stack-2x"></i>
</a>
</li>
<li>
<a target="_blank" href="https://br.linkedin.com/in/julioc0" class="fa-stack fa-lg social-linkedin">
<i class="fa fa-linkedin-square fa-stack-2x"></i>
</a>
</li>
<li>
<a target="_blank" href="https://steamcommunity.com/id/thejcs" class="fa-stack fa-lg social-steam">
<i class="fa fa-steam-square fa-stack-2x"></i>
</a>
</li>
</ul>
<p>
If you still need more, try checking out <a href="{{ site.baseurl }}resume/en">my resumé</a><br/>
Also, feel free to contact me at <a href="mailto:[email protected]" target="_blank">[email protected]</a>
</p>
</div>
</div>
</div>
<div class="container">
{% if false %}
{% if site.posts != empty %}
<div id="posts">
<h3>Journal Entries</h3>
<ul>
{% for post in site.posts %}
<li>
<span class="date">{{ post.date | date: "%d %b %Y" }}</span>
<a href="{{ post.url }}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% endif %}
</div>
| JulioC/julioc.github.io | index.html | HTML | mit | 2,077 |
#ifndef RENDER_DRAW_CALL_H
#define RENDER_DRAW_CALL_H 1
namespace open {
class IStore;
class IMaterial;
class IGeometry;
class IRenderPass;
class IRenderContext;
class DrawCall {
public:
DrawCall();
~DrawCall();
void bind(IGeometry* geometry, IMaterial* material, IRenderPass* pass, IStore* store);
IRenderPass* getRenderPass();
void beforeRender();
void render(IRenderContext* context);
private:
class Imp;
Imp* _imp;
};
}
#endif | spotsking/open | main/src/Render/RenderEngine/DrawCall.h | C | mit | 460 |
module Data.Smashy.Types where
import Data.Vector.Storable.Mutable (IOVector)
import Data.Word (Word8, Word32, Word64)
import Data.Smashy.Constants
data PositionInfo = KeyFoundAt Word32
| KeyValueFoundAt Word32
| SameSizeDifferentValue Word32 Word32 Word32
| DifferentSize Word32 Word32 Word32
| FreeAt Word32
| HashTableFull
| TermListFull
| ValueListFull deriving Show
data HashMap a b = HashMap {getMapLocation :: Location,
getMapHash :: HashTable Word64,
getMapKeys :: TermList a,
getMapValues :: TermList b}
data HashSet a = HashSet {getSetLocation :: Location,
getSetHash :: HashTable Word32,
getSetTerms :: TermList a}
data HashTable a = HashTable {getHashSize :: Word32,
getHashData :: IOVector a,
getHashSpace :: Int}
data TermList a = TermList {getPosition :: Position,
getSize :: Int,
getData :: IOVector Word8,
getSpace :: Int}
type Position = Int
data Location = Ram
| Disk FilePath
| Hybrid FilePath deriving Show
data DataLocation = InRam
| OnDisk FilePath deriving (Read, Show)
decrTableSpace :: HashTable a -> HashTable a
decrTableSpace (HashTable hashSize hashData hashSpace)
= HashTable hashSize hashData (hashSpace - 1)
advanceTo :: TermList a -> Position -> TermList a
advanceTo (TermList termPos termSize termData termSpace) termPos'
= TermList termPos' termSize termData (termSpace - (termPos' - termPos))
getHashLocation :: Location -> DataLocation
getHashLocation Ram = InRam
getHashLocation (Hybrid _) = InRam
getHashLocation (Disk fp) = OnDisk (fp ++ hashFileName)
getKeysLocation :: Location -> DataLocation
getKeysLocation Ram = InRam
getKeysLocation (Hybrid fp) = OnDisk (fp ++ keyFileName)
getKeysLocation (Disk fp) = OnDisk (fp ++ keyFileName)
getValsLocation :: Location -> DataLocation
getValsLocation Ram = InRam
getValsLocation (Hybrid fp) = OnDisk (fp ++ valFileName)
getValsLocation (Disk fp) = OnDisk (fp ++ valFileName)
getBasePath :: Location -> Maybe FilePath
getBasePath loc = case loc of
Ram -> Nothing
Disk fp -> Just fp
Hybrid fp -> Just fp
data TermComparison = Matched
| SSDV
| DS deriving Show | jahaynes/smashy | src/Data/Smashy/Types.hs | Haskell | mit | 2,764 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Uncas.EBS.UI
{
/// <summary>
/// Code behind for the language page.
/// </summary>
public partial class Language
{
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
| uncas/hibes | src/Uncas.EBS.UI/Language.aspx.designer.cs | C# | mit | 882 |
export const androidClipboard = {"viewBox":"0 0 512 512","children":[{"name":"path","attribs":{"d":"M405.333,80h-87.35C310.879,52.396,285.821,32,256,32s-54.879,20.396-61.983,48h-87.35C83.198,80,64,99.198,64,122.667\r\n\tv314.665C64,460.801,83.198,480,106.667,480h298.666C428.802,480,448,460.801,448,437.332V122.667C448,99.198,428.802,80,405.333,80\r\n\tz M256,80c11.729,0,21.333,9.599,21.333,21.333s-9.604,21.334-21.333,21.334s-21.333-9.6-21.333-21.334S244.271,80,256,80z M408,440\r\n\tH104V120h40v72h224v-72h40V440z"},"children":[]}]}; | wmira/react-icons-kit | src/ionicons/androidClipboard.js | JavaScript | mit | 536 |
package com.groupdocs.ui.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.io.File;
import static com.groupdocs.ui.config.DefaultDirectories.defaultViewerDirectory;
import static com.groupdocs.ui.config.DefaultDirectories.relativePathToAbsolute;
@Component
public class ViewerConfiguration extends CommonConfiguration {
@Value("${viewer.filesDirectory}")
private String filesDirectory;
@Value("${viewer.fontsDirectory}")
private String fontsDirectory;
@Value("#{new Integer('${viewer.preloadPageCount}')}")
private Integer preloadPageCount;
@Value("#{new Boolean('${viewer.zoom}')}")
private Boolean zoom;
@Value("#{new Boolean('${viewer.search}')}")
private Boolean search;
@Value("#{new Boolean('${viewer.thumbnails}')}")
private Boolean thumbnails;
@Value("#{new Boolean('${viewer.rotate}')}")
private Boolean rotate;
@Value("${viewer.defaultDocument}")
private String defaultDocument;
@Value("#{new Boolean('${viewer.htmlMode}')}")
private Boolean htmlMode;
@Value("#{new Boolean('${viewer.cache}')}")
private boolean cache;
@Value("#{new Boolean('${viewer.saveRotateState}')}")
private boolean saveRotateState = true;
@Value("${viewer.watermarkText}")
private String watermarkText;
@Value("#{new Boolean('${viewer.printAllowed}')}")
private Boolean printAllowed;
@Value("#{new Boolean('${viewer.showGridLines}')}")
private Boolean showGridLines;
@Value("${viewer.cacheFolderName}")
private String cacheFolderName;
@PostConstruct
public void init() {
this.filesDirectory = StringUtils.isEmpty(this.filesDirectory) ? defaultViewerDirectory() : relativePathToAbsolute(this.filesDirectory);
}
public String getFilesDirectory() {
if (!StringUtils.isEmpty(filesDirectory) && !filesDirectory.endsWith(File.separator)) {
return filesDirectory + File.separator;
}
return filesDirectory;
}
public void setFilesDirectory(String filesDirectory) {
this.filesDirectory = filesDirectory;
}
public String getFontsDirectory() {
return fontsDirectory;
}
public void setFontsDirectory(String fontsDirectory) {
this.fontsDirectory = fontsDirectory;
}
public Integer getPreloadPageCount() {
return preloadPageCount;
}
public void setPreloadPageCount(Integer preloadPageCount) {
this.preloadPageCount = preloadPageCount;
}
public Boolean isZoom() {
return zoom;
}
public void setZoom(Boolean zoom) {
this.zoom = zoom;
}
public Boolean isSearch() {
return search;
}
public void setSearch(Boolean search) {
this.search = search;
}
public Boolean isThumbnails() {
return thumbnails;
}
public void setThumbnails(Boolean thumbnails) {
this.thumbnails = thumbnails;
}
public Boolean isRotate() {
return rotate;
}
public void setRotate(Boolean rotate) {
this.rotate = rotate;
}
public String getDefaultDocument() {
return defaultDocument;
}
public void setDefaultDocument(String defaultDocument) {
this.defaultDocument = defaultDocument;
}
public Boolean isHtmlMode() {
return htmlMode;
}
public void setHtmlMode(Boolean htmlMode) {
this.htmlMode = htmlMode;
}
public boolean isCache() {
return cache;
}
public void setCache(boolean cache) {
this.cache = cache;
}
public boolean isSaveRotateState() {
return saveRotateState;
}
public void setSaveRotateState(boolean saveRotateState) {
this.saveRotateState = saveRotateState;
}
public String getWatermarkText() {
return watermarkText;
}
public void setWatermarkText(String watermarkText) {
this.watermarkText = watermarkText;
}
public Boolean getPrintAllowed() {
return printAllowed;
}
public void setPrintAllowed(Boolean printAllowed) {
this.printAllowed = printAllowed;
}
public Boolean getShowGridLines() {
return showGridLines;
}
public void setShowGridLines(Boolean showGridLines) {
this.showGridLines = showGridLines;
}
public String getCacheFolderName() {
return cacheFolderName;
}
public void setCacheFolderName(String cacheFolderName) {
this.cacheFolderName = cacheFolderName;
}
@Override
public String toString() {
return "ViewerConfiguration{" +
"filesDirectory='" + filesDirectory + '\'' +
", fontsDirectory='" + fontsDirectory + '\'' +
", preloadPageCount=" + preloadPageCount +
", zoom=" + zoom +
", search=" + search +
", thumbnails=" + thumbnails +
", rotate=" + rotate +
", defaultDocument='" + defaultDocument + '\'' +
", htmlMode=" + htmlMode +
", cache=" + cache +
", saveRotateState=" + saveRotateState +
", watermarkText='" + watermarkText + '\'' +
", printAllowed=" + printAllowed +
", showGridLines=" + showGridLines +
", cacheFolderName=" + cacheFolderName +
'}';
}
}
| groupdocs-viewer/GroupDocs.Viewer-for-Java | Demos/Spring/src/main/java/com/groupdocs/ui/config/ViewerConfiguration.java | Java | mit | 5,555 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.addTodo = addTodo;
exports.addTodoWithValidate = addTodoWithValidate;
exports.showMessage = showMessage;
exports.clearMessage = clearMessage;
exports.completeTodo = completeTodo;
exports.setVisibilityFilter = setVisibilityFilter;
/*
* action types
*/
var TodoActionTypes = exports.TodoActionTypes = {
ADD: "TODO.INCREMENT",
COMPLETE: "TODO.DECREMENT",
SET_VISIBILITY_FILTER: "TODO.SET_VISIBILITY_FILTER ",
SHOW_MESSAGE: "TODO.SHOW_MESSAGE",
CLEAR_MESSAGE: "TODO.CLEAR_MESSAGE"
};
/*
* action creators
*/
function addTodo(inputText) {
return { type: TodoActionTypes.ADD, inputText: inputText };
}
;
function addTodoWithValidate(inputText) {
return function (dispatch, getState) {
var _getState = getState();
var todos = _getState.todos;
//validate
var err = "";
if (inputText == null || inputText == "") {
err = "please input todo.";
} else if (todos.find(function (x) {
return x.text == inputText;
}) != null) {
err = "already registerd.";
}
//Show Error or Add Todo
if (err) {
//Error
dispatch(showMessage({
text: err,
type: "error"
}));
} else {
//Add
dispatch(addTodo(inputText));
dispatch(clearMessage());
}
};
}
;
function showMessage(message) {
return { type: TodoActionTypes.SHOW_MESSAGE, message: message };
}
;
function clearMessage() {
return { type: TodoActionTypes.CLEAR_MESSAGE };
}
;
function completeTodo(key) {
return { type: TodoActionTypes.COMPLETE, key: key };
}
;
function setVisibilityFilter(filter) {
return { type: TodoActionTypes.SET_VISIBILITY_FILTER, filter: filter };
}
; | mad-nectarine/nodejs-sample-react-flux | public/scripts/actions/TodoACtions.js | JavaScript | mit | 1,876 |
#require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/conversions'
module WeichatRails
class Message
class << self
def from_hash msg_hash
self.new(msg_hash)
end
def to to_user
new(:ToUserName=>to_user, :CreateTime=>Time.now.to_i)
end
end
class ArticleBuilder
attr_reader :items
#delegate :count, to: :items
def initialize
@items=Array.new
end
def count
items.length
end
def item title:"title", description:nil, pic_url:nil, url:nil
items << {:Title=> title, :Description=> description, :PicUrl=> pic_url, :Url=> url}.reject { |_k, v| v.nil? }
end
end
attr_reader :message_hash
def initialize(msg_hash)
@message_hash = msg_hash || {}
end
def [](key)
message_hash[key]
end
def reply
Message.new( :ToUserName=>message_hash[:FromUserName], :FromUserName=>message_hash[:ToUserName], :CreateTime=>Time.now.to_i)
end
def as type
case type
when :text
message_hash[:Content]
when :image, :voice, :video, :shortvideo
WeichatRails.api.media(message_hash[:MediaId])
when :location
message_hash.slice(:Location_X, :Location_Y, :Scale, :Label).inject({}){|results, value|
results[value[0].to_s.underscore.to_sym] = value[1]
results
}
else
raise "Don't know how to parse message as #{type}"
end
end
def kefu msg_type
update(:MsgType => msg_type)
end
def transfer_customer_service
update(MsgType: 'transfer_customer_service')
end
def to openid
update(:ToUserName=>openid)
end
def agent_id(agentid)
update(AgentId: agentid)
end
def success
update(MsgType: 'success')
end
def text content
update(:MsgType=>"text", :Content=>content)
end
def image media_id
update(:MsgType=>"image", :Image=>{:MediaId=>media_id})
end
def voice media_id
update(:MsgType=>"voice", :Voice=>{:MediaId=>media_id})
end
def video media_id, opts={}
video_fields = camelize_hash_keys({media_id: media_id}.merge(opts.slice(:title, :description)))
update(:MsgType=>"video", :Video=>video_fields)
end
def music thumb_media_id, music_url, opts={}
music_fields = camelize_hash_keys(opts.slice(:title, :description, :HQ_music_url).merge(music_url: music_url, thumb_media_id: thumb_media_id))
update(:MsgType=>"music", :Music=>music_fields)
end
def news collection, &block
if block_given?
article = ArticleBuilder.new
collection.each{|item| yield(article, item)}
items = article.items
else
items = collection.collect do |item|
item.symbolize_keys.slice(:title, :description, :pic_url, :url).reject { |_k,v| v.nil? }
end
end
update(:MsgType=>"news", :ArticleCount=> items.count,:Articles=> items.collect{|item| camelize_hash_keys(item)})
end
def template(opts = {})
template_fields = camelize_hash_keys(opts.symbolize_keys.slice(:template_id, :topcolor, :url, :data))
update(MsgType: 'template', Template: template_fields)
end
def to_xml
message_hash.to_xml(root: "xml", children: "item", skip_instruct: true, skip_types: true)
end
TO_JSON_KEY_MAP = {
'ToUserName' => 'touser',
'MediaId' => 'media_id',
'ThumbMediaId' => 'thumb_media_id',
'TemplateId' => 'template_id'
}
TO_JSON_ALLOWED = %w(touser msgtype content image voice video music news articles template agentid)
def to_json
json_hash = deep_recursive(message_hash) do |key, value|
key = key.to_s
[(TO_JSON_KEY_MAP[key] || key.downcase), value]
end
json_hash = json_hash.select { |k, _v| TO_JSON_ALLOWED.include? k }
case json_hash['msgtype']
when 'text'
json_hash['text'] = { 'content' => json_hash.delete('content') }
when 'news'
json_hash['news'] = { 'articles' => json_hash.delete('articles') }
when 'template'
json_hash.merge! json_hash['template']
end
JSON.generate(json_hash)
end
def save_to! model_class
model = model_class.new(underscore_hash_keys(message_hash))
model.save!
return self
end
private
def camelize_hash_keys hash
deep_recursive(hash){|key, value| [key.to_s.camelize.to_sym, value]}
end
def underscore_hash_keys hash
deep_recursive(hash){|key, value| [key.to_s.underscore.to_sym, value]}
end
def update fields={}
message_hash.merge!(fields)
return self
end
def deep_recursive hash, &block
hash.inject({}) do |memo, val|
key,value = *val
case value.class.name
when "Hash"
value = deep_recursive(value, &block)
when "Array"
value = value.collect{|item| item.is_a?(Hash) ? deep_recursive(item, &block) : item}
end
key,value = yield(key, value)
memo.merge!(key => value)
end
end
end
end
| javyliu/weichat_rails | lib/weichat_rails/message.rb | Ruby | mit | 5,290 |
<div class="container container-center">
<form action="">
<input type="text" placeholder="Text input" disabled>
<select disabled>
<option>Option 01</option>
<option>Option 02</option>
<option>Option 03</option>
</select>
<input type="text" class="form-danger" value="Danger">
<input type="text" class="form-success" value="Success">
<p><input type="text" class="form-large" placeholder=".form-large"></p>
<p><input type="text" placeholder="Default"></p>
<p><input type="text" class="form-small" placeholder=".form-small"></p>
<input type="text" placeholder="form-blank" class="form-blank">
<div class="form-row">
<input type="text" placeholder="Text input"> <span class="form-help-inline">The <code>.form-help-inline</code> class creates spacing to the left.</span>
</div>
<div class="form-row">
<textarea placeholder="Textarea"></textarea>
<p class="form-help-block">The <code>.form-help-block</code> class creates an associated paragraph.</p>
</div>
</form>
</div>
| CliqueStudios/Clique.UI-Docs | php/pages/tests/core/text-inputs.php | PHP | mit | 1,014 |
<?php
namespace Pronit\CoreBundle\Entity\Automatizacion\Secuencias;
use Doctrine\ORM\Mapping as ORM;
use Pronit\CoreBundle\Entity\Automatizacion\Secuencias\TablaCondicion;
use Pronit\CoreBundle\Entity\Automatizacion\EsquemasCalculo\ClaseCondicion;
use Pronit\CoreBundle\Entity\Automatizacion\Secuencias\RegistroCondicionMetadataValue;
use Bluegrass\Metadata\Bundle\MetadataBundle\Model\Metadata;
use Bluegrass\Metadata\Bundle\MetadataBundle\Model\IMetadataEntity;
/**
*
* @author ldelia
* @ORM\Entity
* @ORM\Table(name="core_registrocondicion")
*/
class RegistroCondicion implements IMetadataEntity
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Pronit\CoreBundle\Entity\Automatizacion\EsquemasCalculo\ClaseCondicion")
*/
protected $claseCondicion;
/**
* @ORM\ManyToOne(targetEntity="Pronit\CoreBundle\Entity\Automatizacion\Secuencias\TablaCondicion")
*/
protected $tablaCondicion;
/**
* @ORM\OneToMany(targetEntity="Pronit\CoreBundle\Entity\Automatizacion\Secuencias\RegistroCondicionMetadataValue", mappedBy="registroCondicion", cascade={"ALL"}, indexBy="metadataName", orphanRemoval=true)
*/
protected $claves;
public function __construct(ClaseCondicion $claseCondicion)
{
$this->claves = new \Doctrine\Common\Collections\ArrayCollection();
$this->claseCondicion = $claseCondicion;
}
public function getId()
{
return $this->id;
}
public function getTablaCondicion()
{
return $this->tablaCondicion;
}
public function getClaseCondicion()
{
return $this->claseCondicion;
}
public function setTablaCondicion(TablaCondicion $tablaCondicion)
{
$this->tablaCondicion = $tablaCondicion;
}
public function setClave( Metadata $metadata, $value )
{
$this->setMetadata($metadata, $value);
}
/**
* Determina si la entidad tiene un metadato asociado
* @param \Bluegrass\Metadata\Bundle\MetadataBundle\Model\Metadata $metadata
* @return boolean
*/
public function hasMetadata( Metadata $metadata )
{
/* Nota: El indice está dado por la annotation indexBy del mapping */
return isset( $this->claves[ $metadata->getName() ] );
}
/**
* Obtiene el valor asociado a un metadato de la entidad
* @param \Bluegrass\Metadata\Bundle\MetadataBundle\Model\Metadata $metadata
* @return \Pronit\CoreBundle\Entity\Automatizacion\Secuencias\RegistroCondicionMetadataValue
* @throws \Exception
*/
public function getMetadata( Metadata $metadata )
{
if ( ! $this->hasMetadata($metadata) ){
throw new \Exception("La tabla condición '{$this}' no tiene definido el metadato '{$metadata}'");
}
return $metadata->getValue( $this->claves[ $metadata->getName() ] );
}
/**
* Agrega el valor asociado a un metadato de la entidad
* @param \Bluegrass\Metadata\Bundle\MetadataBundle\Model\Metadata $metadata
* @param type $value
*/
public function setMetadata( Metadata $metadata, $value )
{
if ( $this->hasMetadata($metadata) ){
// Como se va a generar un nuevo MetadataValue, al antiguo lo descarto ( orphanremoval )
unset( $this->claves[$metadata->getName()] );
}
/* @var $metadataValue \Pronit\CoreBundle\Entity\Automatizacion\Secuencias\RegistroCondicionMetadataValue */
$metadataValue = $metadata->createValue($this, $value);
$this->claves[$metadata->getName()] = $metadataValue;
}
}
| pronit/pronit | src/Pronit/CoreBundle/Entity/Automatizacion/Secuencias/RegistroCondicion.php | PHP | mit | 3,968 |
<!DOCTYPE html>
<html lang="en">
<head prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article# website: http://ogp.me/ns/website#">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<meta name="description" content="">
<meta property="og:title" content="Find bad data using File-Aid">
<meta property="og:type" content="article">
<meta property="article:published_time" content="2012-01-20">
<meta property="og:description" content="">
<meta property="og:url" content="http://purusothaman.me/find-bad-data-using-file-aid/">
<meta property="og:site_name" content="Purusothaman Ramanujam">
<meta name="generator" content="Hugo 0.21" />
<title>Find bad data using File-Aid · Purusothaman Ramanujam</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="http://purusothaman.me/css/style.css">
<link href="http://purusothaman.me/index.xml" rel="alternate" type="application/rss+xml" title="Purusothaman Ramanujam" />
<link rel="icon" href="http://purusothaman.me/favicon.ico" />
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top visible-xs">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="http://purusothaman.me/">Purusothaman Ramanujam</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<div id="menu" class="hidden-xs col-sm-4 col-md-3">
<div id="menu-content" class="vertical-align">
<h1 class="text-center"><a href="http://purusothaman.me/">Purusothaman Ramanujam</a></h1>
<small class="text-center center-block">My Personal Flavour</small>
<img id="profile-pic" src="http://purusothaman.me//img/avatar.jpg" alt="My Picture" class="img-circle center-block">
<div id="social" class="text-center">
<a href="https://github.com/purus"><i class="fa fa-github fa-2x"></i></a>
<a href="mailto:[email protected]"><i class="fa fa-envelope-o fa-2x"></i></a>
</div>
<div id="links" class="text-center">
</div>
</div>
</div>
<div id="content" class="col-xs-12 col-sm-8 col-md-9">
<div class="row">
<div id="post" class="col-sm-offset-1 col-sm-10 col-md-10 col-lg-8">
<main>
<header>
<h1>Find bad data using File-Aid</h1>
</header>
<article>
<p>The Easiest and Coolest way to locate bad data is thru File-Aid’s FIND command.</p>
<ul>
<li>OPEN the file in FILE-AID (in either browse or edit mode).</li>
<li>XREF with COPYBOOK.</li>
<li>Use FMT mode.</li>
<li>Then issue the below command.</li>
</ul>
<blockquote>
<p>F /field-name INVALID</p>
</blockquote>
<p>or</p>
<blockquote>
<p>F /field-number INVALID</p>
</blockquote>
<p>The control will take you to the first invalid data record for the given field.</p>
<p>Example: The FILE has 3 fields namely NAME,AGE,COUNTRY. If you want to find the invalid data in the age field, then issue F /2 INVALID.</p>
</article>
</main>
<div id="bottom-nav" class="text-center center-block">
<a href=" http://purusothaman.me/" class="btn btn-default"><i class="fa fa-home"></i> Home</a>
</div>
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'purusothaman-ramanujam';
var disqus_identifier = 'http:\/\/purusothaman.me\/find-bad-data-using-file-aid\/';
var disqus_title = 'Find bad data using File-Aid';
var disqus_url = 'http:\/\/purusothaman.me\/find-bad-data-using-file-aid\/';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-42031335-1', 'auto');
ga('send', 'pageview');
window.baseURL = "http:\/\/purusothaman.me\/";
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="http://purusothaman.me//js/App.js"></script>
</body>
</html>
| Purus/Purus.github.io | find-bad-data-using-file-aid/index.html | HTML | mit | 5,676 |
/* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);
var _svgIcon = require('../../svg-icon');
var _svgIcon2 = _interopRequireDefault(_svgIcon);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var AvFiberNew = _react2.default.createClass({
displayName: 'AvFiberNew',
mixins: [_reactAddonsPureRenderMixin2.default],
render: function render() {
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zM8.5 15H7.3l-2.55-3.5V15H3.5V9h1.25l2.5 3.5V9H8.5v6zm5-4.74H11v1.12h2.5v1.26H11v1.11h2.5V15h-4V9h4v1.26zm7 3.74c0 .55-.45 1-1 1h-4c-.55 0-1-.45-1-1V9h1.25v4.51h1.13V9.99h1.25v3.51h1.12V9h1.25v5z'}));
}
});
exports.default = AvFiberNew;
module.exports = exports['default'];
| nayashooter/ES6_React-Bootstrap | public/jspm_packages/npm/[email protected]/lib/svg-icons/av/fiber-new.js | JavaScript | mit | 1,149 |
import MathF
def vectorTest():
vec = MathF.Vector2d(0, 1)
print vec
print vec.deg()
print vec.rad()
print vec.magnitude()
vec.deg(90.0)
print vec | FireFlyForLife/Python-Pong | pong/Tests.py | Python | mit | 174 |
# da-klingel – a doorbell powered by GPIO and Ruby
This is a simple ruby script playing a sound everytime a GPIO input is triggered. We use it as a doorbell for our office.
## Installation
You need a device with GPIO support running Ubuntu or a similar Linux distribution. We’re using an [RaspberryPi 3 Model B](https://www.raspberrypi.org/products/raspberry-pi-3-model-b/) running [Raspbian](http://www.raspbian.org). Playing sounds uses [`amixer` and `aplay`](https://www.raspberrypi-spy.co.uk/2013/06/raspberry-pi-command-line-audio/).
The script requires Ruby 2.3 and needs to be executed as root (because it has to access the GPIO ports).
To install, clone this repo and run `bundle install`. If you get an error installing `eventmachine`, you most likely are missing the OpenSSL header files. Try `sudo apt-get install libssl-dev`.
## Configuration
Rename `config.example.yml` to `config.yml` and edit as needed.
Apart from playing a sound file there are three more actions the script can trigger everytime someone rings the bell.
* __Snapshot__: Uses a webcam to take a snapshot image. The webcam must provide a URL to create a snapshot, returning a JSON response containing the URL of the snapshot: `{"url": "http://example.com/snapshots/123.jpg"}`. If available, the snapshot image will be used in the Flowdock and status screen actions below.
* __Campfire__: The script can post a message to your Campfire in Basecamp 3.
* __Status screen__: The script can trigger a specific screen in our [status screen app](https://github.com/die-antwort/status-screen).
* __Klingelblink__: The script can trigger our [klingelblink server](https://github.com/die-antwort/klingelblink).
To enable these actions just set `enabled:` to `true` and fill in the needed settings (API key, host, …)
## Usage
Simply run the script `da-klingel.rb`.
If the script is run as non-root user you may see a warning like `bcm2835 init: Unable to open /dev/mem: Permission denied`. This can safely be ignored.
### Run as a service
To run the script as a service (i.e. starting it automatically on boot), create a systemd configuration file `/etc/systemd/system/da-klingel.service` (adapt paths as needed):
```
[Unit]
Description=Doorbell script
[Service]
ExecStart=/home/pi/da-klingel/da-klingel.rb
WorkingDirectory=/home/pi/da-klingel
[Install]
WantedBy=multi-user.target
```
Test the service with `systemctl start da-klingel`. If everything works as expected, enable the service with `systemctl enable da-klingel`.
### Included Sounds
The following included sound files have been downloaded from [Freesound](http://www.freesound.org/) and slightly modified (trimmed):
* `doorbell.wav`: http://www.freesound.org/people/Corsica_S/sounds/163730/
* `old_phone.wav`: http://www.freesound.org/people/Razzvio/sounds/79568/
| die-antwort/da-klingel | README.md | Markdown | mit | 2,826 |
version https://git-lfs.github.com/spec/v1
oid sha256:6ec0812a628e11c3dab9d8c9d327cf4fa3049e3d839a3a4e848ca3488987b463
size 2598
| yogeshsaroya/new-cdnjs | ajax/libs/angular.js/1.4.0-beta.6/i18n/angular-locale_luo-ke.js | JavaScript | mit | 129 |
<?php namespace MovBizz\Turn;
class AnalyseChartsCommand {
/**
*/
public function __construct()
{
}
} | teruk/movbizz | app/MovBizz/Turn/AnalyseChartsCommand.php | PHP | mit | 125 |
// Saves options to chrome.storage
function save_options() {
let domain = document.getElementById('domain').value;
chrome.storage.sync.set({domain: domain});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
// Use default value domain = 'sci-hub.tw'
chrome.storage.sync.get({
domain: 'sci-hub.tw'
}, function(items) {
document.getElementById('domain').value = items.domain;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click', save_options);
// Detect cursor position for button ripple effect
(function (window, $) {
$(function() {
$('.ripple').on('click', function (event) {
event.preventDefault();
var $div = $('<div/>'),
btnOffset = $(this).offset(),
xPos = event.pageX - btnOffset.left,
yPos = event.pageY - btnOffset.top;
$div.addClass('ripple-effect');
var $ripple = $(".ripple-effect");
$ripple.css("height", $(this).height());
$ripple.css("width", $(this).height());
$div
.css({
top: yPos - ($ripple.height()/2),
left: xPos - ($ripple.width()/2),
background: $(this).data("ripple-color")
})
.appendTo($(this));
window.setTimeout(function(){
$div.remove();
}, 1000);
});
});
})(window, jQuery);
| allanino/sci-hub-fy | options.js | JavaScript | mit | 1,436 |
##AHKeychain
####Objective-c Class for managing OSX keychains and keychain items.
_This is project is a derivative of SSKeychain https://github.com/soffes/sskeychain/_
There are four enhancements of this project
1. It lets the user specify which keychain work with, such as the system keychain or a keychain on an external drive/SD card.
2. The other added feature is the ability to specify an Array of trusted apps granted access to the keychain item.
3. This also gives you the ability to change the __keychain's__ password .
4. The other minor improvement is that it actually updates the keychain item using SecItemUpdate(). SSKeychain actually deletes and re-adds the keychain item which can cause peculiar behavior when an app is not code signed and has proper entitlements.
##Working with a specific keychain.
#####To specify the default login keychain
```Objective-c
AHKeychain *keychain = [AHKeychain loginKeychain];
```
#####To specify the system keychain
_to write to this keychain you application must run as root_
```Objective-c
AHKeychain *keychain = [AHKeychain systemKeychain];
```
#####To specify a keychain at a particular path (external drive)
```Objective-c
AHKeychain *keychain = [AHKeychain keychainAtPath:@"/Volumes/MyExternalHD/Library/Keychains/myextkc.keychain"];
```
#####To create a new user keychain
```Objective-c
AHKeychain *keychain = [AHKeychain alloc]initCreatingNewKeychain:@"Test Keychain"
password:@"realfakepsswd"];
```
#####To remove the keychain file. It's Destructive!
_*calling this method on either the login keychain or the system keychain will fail_
```Objective-c
[keychain deleteKeychain];
```
##Modifying a keychain item.
#####To add/update an item
```Objective-c
AHKeychainItem *item = [AHkeychainItem alloc] init];
item.service = @"com.eeaapps.test";
item.account = @"myusername";
item.label = @"AHKeychain Test Keychain Item";
item.password = @"mysecretpass";
// also if you want to allow other app to access the keychain item
NSArray *trustedApps = [NSArray arrayWithObjects:@"/Applications/Mail.app",
@"/Applications/Preview.app",
nil];
item.trustedApplications = trustedApps;
[keychain saveItem:item error:&error];
```
#####To get an item's password
```Objective-c
AHKeychainItem *item = [AHkeychainItem alloc] init];
item.service = @"com.eeaapps.test";
item.account = @"myusername";
[keychain getItem:item error:&error];
NSLog(@"The Password is %@",item.password);
```
#####To remove a keychain item
```Objective-c
AHKeychainItem *item = [AHkeychainItem alloc] init];
item.service = @"com.eeaapps.test";
item.account = @"myusername";
[keychain deleteItem:item error:&error];
```
====
##Class Methods for convenience
_there are two keychain constants that refer to standard keychains_
```
kAHKeychainLoginKeychain
kAHKeychainSystemKeychain
```
_You can use either of these, or specify a full path to the keychain file in the following methods_
#####Setting a password
```Objective-c
[AHKeychain setPassword:@"mysecretpass"
service:@"com.eeaapps.testkc"
account:@"myusername"
keychain:kAHKeychainLoginKeychain
error:&error];
```
#####Getting a password
```
NSError *error;
NSString *password = [AHKeychain getPasswordForService:item.service
account:item.account
keychain:kAHKeychainLoginKeychain
error:&error];
NSLog(@"The Password is %@",item.password);
```
---
_See AHKeychain.h and AHKeychainItem.h for more info._
| eahrold/AHKeychain | README.md | Markdown | mit | 3,769 |
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v0.9.6] - 2021-11-15
### Added
- Adds support for functional analysis profiles as experimental feature
- Adds improved error messaging for `Sample` methods
### Changed
- Pin jupyter-client to version 6.1.12
### Fixed
- Fixes issue with credential file lock
### Removed
- Removes `Classifications.abundances` method
## [v0.9.5] - 2021-03-16
### Added
- Adds support for concatenating sequencing data from multiple lanes
- Adds support for faceting metadata plots
### Changed
- Upgrades minimum sentry-sdk version
- Adds explicit legend title on distance heatmaps
- Adds support for zero-abundance samples in normalization calculations
- Warns when empty boxes are present in faceted boxplots
- Supports more paired file naming schemes for automatic interleaving
- Improves `SampleCollection._collate_results` runtime
- Adds support for an empty domain in `interleave_palette`
- Improves error message handling for samples in an importing state
### Fixed
- Fixed a race condition when running multiple instances of the CLI
- Fixed issues handling symmetry and NaN's in beta diversity calculations
- Fixed beta diversity heatmap layout issues
- Fixed PCA/MDS/PCoA colouring issues
- Fixed broken taxa bargraph links
## [v0.9.4] - 2020-10-27
### Added
- Adds Aitchison distance and supports `manhattan` as a synonym for `cityblock`
### Changed
- Ignores vega-lite warning about boxplots not supporting selection
- Displays facet field name and values below x-axis for taxa barplot and heatmap
- Filters out NaNs from alpha diversity plots
### Fixed
- Improves support for networks with a custom CA
- Fixes support for responsive plots (`width=None` and `width="container"` in `plot_metadata`)
## [v0.9.3] - 2020-08-06
### Changed
- Replaces chao1 with observed_taxa
- Changes the experimental assembly download api to support async retry logic
- Upgrades from deprecated Raven library to sentry_sdk
## [v0.9.2] - 2020-07-23
### Fixed
- Fix bug preventing calculation of weighted Unifrac metric due to taxonomy structure assumptions in `scikit-bio`
## [v0.9.1] - 2020-07-10
### Fixed
- Include fonts for report generation in PyPI distribution
## [v0.9.0] - 2020-07-10
### Changed
- Overhaul styling of Jupyter notebook PDF exports
- Add One Codex theme for Altair plots (enabled by default)
- Refactor how `notebooks.report.references` helper works internally
- Improve upload command to display sample filenames on cancelation
- Bump Altair minimum required library version to 4.1.0
## [v0.8.2] - 2020-06-11
### Fixed
- Fix upload callback retry handling broken in v0.8.1 (c87eb76f0dea544b742c5eacf0a4dfcdcebb87bc)
## [v0.8.1] - 2020-06-08
### Changed
- Improved retry handling for confirm callback POSTs during Sample uploads
### Fixed
- Fix upload and export of PDF reports to One Codex documents portal
- Fix example notebook links to follow updated v0.8.0 plotting conventions
## [v0.8.0] - 2020-06-02
### Added
- Adds more pythonic support for truthy/falsey values to SampleCollection.filter()
- Adds support for passing lists to the various sort_x and sort_y plotting arguments
- Adds a property to SampleCollection to track whether we think the collection is all WGS/metagenomic data
- Adds support for specifying weighted_unifrac and unweighted_unifrac as metrics in the SampleCollection.beta_diversity() method
- Adds support for calculating alpha and beta diversities on normalized data. This is important since we'll now be using abundances by default for most datasets
- Adds support for specifying chart width and height directly in the plot\_\* functions
- Adds option to plot "Other" bars on bargraphs with normalized read counts and abundances
- Adds option to plot "No \<level\>" bars on bargraphs with abundances
- Adds abundance rollups so we can use abundances at all taxonomic ranks
- Adds a project column to the metadata DataFrame of a SampleCollection
### Changed
- Changes default alpha diversity metric from simpson to shannon, since shannon is generally a more appropriate default
- rank="auto" now defaults to species if the field="abundances" or the dataset is metagenomic, instead of genus
- Switches to using a normalized tree for Weighted Unifrac calculations, which gives us Unifrac values in a [0, 1] range
- Defaults to using abundances data for metagenomic datasets instead of readcount_w_children
### Deprecated
- The `field` kwarg on the `SampleCollection` constructor has been renamed to `metric`. We still support passing either, but show a `DeprecationWarning` when passing `field`
### Removed
- Removes support for just specifying `unifrac` as a metric
| onecodex/onecodex | CHANGELOG.md | Markdown | mit | 4,931 |
'use strict';
const isNil = require('lodash.isnil');
const {
util: { checkType }
} = require('../../core');
const SpanQueryBase = require('./span-query-base');
/**
* Matches spans near the beginning of a field. The span first query maps to Lucene `SpanFirstQuery`.
*
* [Elasticsearch reference](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-span-first-query.html)
*
* @example
* const spanQry = esb.spanFirstQuery()
* .match(esb.spanTermQuery('user', 'kimchy'))
* .end(3);
*
* @param {SpanQueryBase=} spanQry Any other span type query
*
* @extends SpanQueryBase
*/
class SpanFirstQuery extends SpanQueryBase {
// eslint-disable-next-line require-jsdoc
constructor(spanQry) {
super('span_first');
if (!isNil(spanQry)) this.match(spanQry);
}
/**
* Sets the `match` clause which can be any other span type query.
*
* @param {SpanQueryBase} spanQry
* @returns {SpanFirstQuery} returns `this` so that calls can be chained.
*/
match(spanQry) {
checkType(spanQry, SpanQueryBase);
this._queryOpts.match = spanQry;
return this;
}
/**
* Sets the maximum end position permitted in a match.
*
* @param {number} limit The maximum end position permitted in a match.
* @returns {SpanFirstQuery} returns `this` so that calls can be chained.
*/
end(limit) {
this._queryOpts.end = limit;
return this;
}
}
module.exports = SpanFirstQuery;
| sudo-suhas/elastic-builder | src/queries/span-queries/span-first-query.js | JavaScript | mit | 1,524 |
package jsimpleai.demo.tsp;
import com.google.common.base.Preconditions;
import jsimpleai.api.problem.UnidirectionalProblem;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Represents a TSP problem
*/
public class TSPProblem implements UnidirectionalProblem<TSPState> {
private CostMatrix costMatrix;
public TSPProblem(@Nonnull final CostMatrix costMatrix) {
this.costMatrix = Preconditions.checkNotNull(costMatrix);
}
@Override
@Nonnull
public TSPState getStartState() {
return new TSPState(0, costMatrix.getLength());
}
@Override
@Nonnull
public Collection<TSPState> getSuccessors(@Nonnull final TSPState state) {
final Collection<TSPState> successors = new ArrayList<>();
// Get the start city..
final int startCity = getStartState().getCurrentCity();
// If only one transition is left, then, go back to start city..
if (state.getNumVisitedCities() == costMatrix.getLength()) {
final int[] visited = state.getVisitedCities().clone();
visited[startCity] = 2;
final TSPState newState = new TSPState(startCity, costMatrix.getLength());
newState.setVisitedCities(visited);
successors.add(newState);
} else {
// Generate all possible states it can goto, obviously not the start
// city and the cities it has already visited..
final List<Integer> possibleCities = new ArrayList<>();
for (int i = 0; i < costMatrix.getLength(); i++) {
if (i != startCity && state.getVisitedCities()[i] == 0) {
possibleCities.add(i);
}
}
// Transition to possible cities..
for (int newCity : possibleCities) {
final TSPState newState = new TSPState(newCity, costMatrix.getLength());
newState.setVisitedCities(state.getVisitedCities().clone());
successors.add(newState);
}
}
return successors;
}
@Override
public double getCost(@Nonnull final TSPState oldState,
@Nonnull final TSPState newState) {
return costMatrix.getCost(oldState.getCurrentCity(), newState.getCurrentCity());
}
@Override
public boolean isGoalState(final TSPState state) {
return state.getNumVisitedCities() == costMatrix.getLength() + 1;
}
} | raghakot/jsimpleai | src/main/java/jsimpleai/demo/tsp/TSPProblem.java | Java | mit | 2,520 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2012 The Bitcoin developers
// Copyright (c) 2013-2014 GoldDiggercoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_UI_INTERFACE_H
#define BITCOIN_UI_INTERFACE_H
#include <string>
#include "util.h" // for int64
#include <boost/signals2/signal.hpp>
#include <boost/signals2/last_value.hpp>
class CBasicKeyStore;
class CWallet;
class uint256;
/** General change type (added, updated, removed). */
enum ChangeType
{
CT_NEW,
CT_UPDATED,
CT_DELETED
};
/** Signals for UI communication. */
class CClientUIInterface
{
public:
/** Flags for CClientUIInterface::ThreadSafeMessageBox */
enum MessageBoxFlags
{
ICON_INFORMATION = 0,
ICON_WARNING = (1U << 0),
ICON_ERROR = (1U << 1),
/**
* Mask of all available icons in CClientUIInterface::MessageBoxFlags
* This needs to be updated, when icons are changed there!
*/
ICON_MASK = (ICON_INFORMATION | ICON_WARNING | ICON_ERROR),
/** These values are taken from qmessagebox.h "enum StandardButton" to be directly usable */
BTN_OK = 0x00000400U, // QMessageBox::Ok
BTN_YES = 0x00004000U, // QMessageBox::Yes
BTN_NO = 0x00010000U, // QMessageBox::No
BTN_ABORT = 0x00040000U, // QMessageBox::Abort
BTN_RETRY = 0x00080000U, // QMessageBox::Retry
BTN_IGNORE = 0x00100000U, // QMessageBox::Ignore
BTN_CLOSE = 0x00200000U, // QMessageBox::Close
BTN_CANCEL = 0x00400000U, // QMessageBox::Cancel
BTN_DISCARD = 0x00800000U, // QMessageBox::Discard
BTN_HELP = 0x01000000U, // QMessageBox::Help
BTN_APPLY = 0x02000000U, // QMessageBox::Apply
BTN_RESET = 0x04000000U, // QMessageBox::Reset
/**
* Mask of all available buttons in CClientUIInterface::MessageBoxFlags
* This needs to be updated, when buttons are changed there!
*/
BTN_MASK = (BTN_OK | BTN_YES | BTN_NO | BTN_ABORT | BTN_RETRY | BTN_IGNORE |
BTN_CLOSE | BTN_CANCEL | BTN_DISCARD | BTN_HELP | BTN_APPLY | BTN_RESET),
/** Force blocking, modal message box dialog (not just OS notification) */
MODAL = 0x10000000U,
/** Predefined combinations for certain default usage cases */
MSG_INFORMATION = ICON_INFORMATION,
MSG_WARNING = (ICON_WARNING | BTN_OK | MODAL),
MSG_ERROR = (ICON_ERROR | BTN_OK | MODAL)
};
/** Show message box. */
boost::signals2::signal<bool (const std::string& message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeMessageBox;
/** Ask the user whether they want to pay a fee or not. */
boost::signals2::signal<bool (int64 nFeeRequired), boost::signals2::last_value<bool> > ThreadSafeAskFee;
/** Handle a URL passed at the command line. */
boost::signals2::signal<void (const std::string& strURI)> ThreadSafeHandleURI;
/** Progress message during initialization. */
boost::signals2::signal<void (const std::string &message)> InitMessage;
/** Translate a message to the native language of the user. */
boost::signals2::signal<std::string (const char* psz)> Translate;
/** Block chain changed. */
boost::signals2::signal<void ()> NotifyBlocksChanged;
/** Number of network connections changed. */
boost::signals2::signal<void (int newNumConnections)> NotifyNumConnectionsChanged;
/**
* New, updated or cancelled alert.
* @note called with lock cs_mapAlerts held.
*/
boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyAlertChanged;
};
extern CClientUIInterface uiInterface;
/**
* Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
* If no translation slot is registered, nothing is returned, and simply return the input.
*/
inline std::string _(const char* psz)
{
boost::optional<std::string> rv = uiInterface.Translate(psz);
return rv ? (*rv) : psz;
}
#endif
| golddiggercoin/golddiggercoin | src/ui_interface.h | C | mit | 4,244 |
Ti=Warranties
1.sec={_Licensor} warrants that it has the right and authority to grant the rights and licenses granted in this {_Agreement}.
2.sec={_Licensor} disclaims all other warranties, representations, and conditions, whether express, implied, or statutory, including, but not limited to, the warranties of merchantability, fitness for a particular purpose, or non-infringement.
3.0.sec=Without limiting the generality of the above disclaimer, {_Licensor} makes no representation or warranties that:
3.1.sec=it will prosecute or continue to prosecute, maintain, or defend any patent or patent application,
3.2.sec=it will bring an infringement suit, assert any claim against third parties accused of infringement, or otherwise enforce any patent or patent application,
3.3.sec=it will join as a party to any suit or legal action,
3.4.sec=it will provide {_Licensee} with know-how or assistance necessary or useful to practice the {_Licensed_Patent_Rights},
3.5.sec=the {_Licensed_Patent_Rights} are valid or enforceable, or
3.6.sec=the {_Licensed_Products} or {_Licensed_Processes} may be exploited or practiced without infringing third party patents.
3.=[G/Z/ol-a/s6]
=[G/Z/ol/s3]
| CommonAccord/Cmacc-Org | Doc/G/CreativeCommons/Model_Patent_License/Sec/Rep/0.md | Markdown | mit | 1,198 |
# This is a quick primer on BeautifulSoup and some of its key abilites. For
# more, see the docs: http://www.crummy.com/software/BeautifulSoup/bs4/doc/
from bs4 import BeautifulSoup
# The sequence of events with BeautifulSoup:
# 1. Get a file. Maybe you have requests playing web browser and it will hand
# you the file contents. Here we'll just read a file into a variable.
with open('table_example.html', 'rb') as infile:
example = infile.read()
# 2. Make a BeautifulSoup object out of HTML file contents. This makes the
# underlying HTML something BeautifulSoup can navigate and parse.
soup = BeautifulSoup(example, 'html.parser')
# 2a. Peek at the HTML that BS has gone to work on, if you'd like.
print soup.prettify()
# 3. Isolate the information that you want to collect. This is where BS
# really shines. This is an example of very simple criteria: HTML
# within <table> tags.
table = soup.find('table')
# 4. Start walking through this isolated information; for a table, the pattern
# generally dives into each row and then each cell.
for row in table.find_all('tr'):
extract = []
for cell in row.find_all('td'):
extract.append(cell.text)
print ', '.join(extract)
# for row in table:
# make empty list to hold cell text
# for cell in row:
# append cell text to list
# print the list contents joined together by commas
# This scraped information can then be written to a file or manipulated
# further.
| ireapps/coding-for-journalists | 2_web_scrape/completed/fun_with_bs_done.py | Python | mit | 1,481 |
import {View, Component} from 'angular2/angular2';
import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {CharactersComponent} from './components/character/characters.component';
import {DashboardComponent} from './components/dashboard/dashboard.component';
import {PriorityQueueComponent} from './components/priorityqueue/priorityqueue.component';
import {ChartComponent} from './components/chart/chart.component';
@Component({ selector: 'my-app' })
@View({
template: `
<a [router-link]="['./PriorityQueue']">PriorityQueue</a>
<a [router-link]="['./Dashboard']">Dashboard</a>
<a [router-link]="['./Characters']">Characters</a>
<a [router-link]="['./Chart']">Tasks</a>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{ path: '/', as: 'PriorityQueue', component: PriorityQueueComponent },
{ path: '/dashboard', as: 'Dashboard', component: DashboardComponent },
{ path: '/characters', as: 'Characters', component: CharactersComponent },
{ path: '/chart', as: 'Chart', component: ChartComponent },
])
export class AppComponent { }
| rtsjs/rts | src/app/app.component.ts | TypeScript | mit | 1,127 |
class NotesController < ApplicationController
def new
if not user_signed_in?
redirect_to root_path
end
@note = Note.new
if params.has_key?(:course)
@course = Course.find(params[:course])
end
end
def create
@note = Note.new(note_params)
@note.user_id = current_user.id
if user_signed_in? and current_user.id == @note.user_id
@note.course_id = params[:course_id]
if @note.save
redirect_to @note
else
redirect_to new_note_path
end
else
redirect_to root_path
end
end
def edit
@note = Note.find(params[:id])
if not user_signed_in? or current_user.id != @note.user_id
redirect_to root_path
end
end
def update
@note = Note.find(params[:id])
if user_signed_in? and current_user.id == @note.user_id
if @note.update(note_params)
redirect_to @note
else
render edit_note_path
end
else
redirect_to root_path
end
end
def destroy
@note = Note.find(params[:id])
if user_signed_in? and current_user.id == @note.user_id
@course = Course.where(["id = ?", @note.course_id])[0]
Note.delete(@note.id)
redirect_to course_path(@course)
else
redirect_to root_path
end
end
def show
@note = Note.find(params[:id])
if user_signed_in? and current_user.id == @note.user_id
@course = Course.where(["id = ?", @note.course_id])[0]
@author = User.where(["id = ?", @course.user_id])[0]
else
redirect_to root_path
end
end
def download
@note = Note.find(params[:id])
@course = Course.where(["id = ?", @note.course_id])[0]
@author = User.where(["id = ?", @course.user_id])[0]
render :pdf => "#{@note.name}",
javascript_delay:16000,
:header => {
:center => ""
},
:margin => { :bottom => 5 },
:footer => { :html => { :template => 'notes/download_footer.html.erb' } },
:disposition => 'attachment'
end
private
def note_params
params.require(:note).permit(:course_id, :name, :content)
end
end
| ihgann/brighid | app/controllers/notes_controller.rb | Ruby | mit | 2,117 |
const chai = require('chai');
const expect = chai.expect;
const Immutable = require('immutable');
const StateContainer = require('../lib/state/state.container');
describe('StateContainer', () => {
it('IntialState', () => {
let initialState = {
foo: 'bar'
};
let state_container = new StateContainer(initialState);
expect(state_container.state).to.deep.equal(initialState);
});
it('Rewrite', () => {
let state_container = new StateContainer({ foo: 'bar' });
let overrideState = {
foo: 'bar2000'
};
state_container.rewrite(overrideState);
expect(state_container.state).to.deep.equal(overrideState);
});
it('Get', () => {
let state = {
foo: 'bar2000',
deep: { json: 'data' }
};
let state_container = new StateContainer(state);
expect(state_container.get().toJS()).to.deep.equal(state);
expect(state_container.get('deep').toJS()).to.deep.equal(state.deep);
expect(state_container.get('foo')).to.equal(state.foo);
expect(state_container.get(['foo'])).to.equal(state.foo);
expect(state_container.get('deep.json')).to.equal(state.deep.json);
expect(state_container.get(['deep', 'json'])).to.equal(state.deep.json);
});
it('Set', () => {
let state = {
foo: 'bar2000',
deep: { json: 'data' },
array: []
};
let nextState = {
foo: 'bar3000',
deep: { json: 'stuff' },
array: [ 1 ]
};
let dot_state_container = new StateContainer(state);
let array_state_container = new StateContainer(state);
dot_state_container.set('foo', () => nextState.foo);
array_state_container.set(['foo'], () => nextState.foo);
dot_state_container.set('deep.json', () => nextState.deep.json);
array_state_container.set(['deep', 'json'], () => nextState.deep.json);
dot_state_container.set('array', (arr) => arr.push(nextState.array[0]));
array_state_container.set(['array'], (arr) => arr.push(nextState.array[0]));
expect(dot_state_container.state).to.deep.equal(nextState);
expect(array_state_container.state).to.deep.equal(nextState);
});
it('Remove', () => {
let state = {
foo: 'bar2000',
deep: { json: 'data' },
array: [1]
};
let nextState = {
deep: { },
array: []
};
let dot_state_container = new StateContainer(state);
let array_state_container = new StateContainer(state);
dot_state_container.remove('foo');
array_state_container.remove(['foo']);
dot_state_container.remove('deep.json');
array_state_container.remove(['deep', 'json']);
dot_state_container.remove('array.0');
array_state_container.remove(['array', '0']);
expect(dot_state_container.state).to.deep.equal(nextState);
expect(array_state_container.state).to.deep.equal(nextState);
expect(dot_state_container.remove).to.throw(Error);
expect(array_state_container.remove).to.throw(Error);
expect(() => dot_state_container.remove('')).to.throw(Error);
expect(() => array_state_container.remove([])).to.throw(Error);
});
}); | DmitryDodzin/fluctor | test/statecontainer.test.js | JavaScript | mit | 3,097 |
<?php
namespace Gabo\Generator\Generators\Common;
use Config;
use Gabo\Generator\CommandData;
use Gabo\Generator\Generators\GeneratorProvider;
use Gabo\Generator\Utils\GeneratorUtils;
class RequestGenerator implements GeneratorProvider
{
/** @var CommandData */
private $commandData;
/** @var string */
private $path;
public function __construct($commandData)
{
$this->commandData = $commandData;
$this->path = Config::get('generator.path_request', app_path('Http/Requests/'));
}
public function generate()
{
$this->generateCreateRequest();
$this->generateUpdateRequest();
}
private function generateCreateRequest()
{
$templateData = $this->commandData->templatesHelper->getTemplate('CreateRequest', 'scaffold/requests');
$templateData = GeneratorUtils::fillTemplate($this->commandData->dynamicVars, $templateData);
$fileName = 'Create'.$this->commandData->modelName.'Request.php';
$path = $this->path.$fileName;
$this->commandData->fileHelper->writeFile($path, $templateData);
$this->commandData->commandObj->comment("\nCreate Request created: ");
$this->commandData->commandObj->info($fileName);
}
private function generateUpdateRequest()
{
$templateData = $this->commandData->templatesHelper->getTemplate('UpdateRequest', 'scaffold/requests');
$templateData = GeneratorUtils::fillTemplate($this->commandData->dynamicVars, $templateData);
$fileName = 'Update'.$this->commandData->modelName.'Request.php';
$path = $this->path.$fileName;
$this->commandData->fileHelper->writeFile($path, $templateData);
$this->commandData->commandObj->comment("\nUpdate Request created: ");
$this->commandData->commandObj->info($fileName);
}
}
| gabrieljaime/laravel-api-generator-for-lteTemplate | src/Gabo/Generator/Generators/Common/RequestGenerator.php | PHP | mit | 1,852 |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
*T_User
*Description: model manage t_purpose
* @author quanhm
*/
Class T_admin extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
$this->table_name = 'admin';
}
public function get_data($user = null, $pass = null)
{
$this->db->select("*");
$this->db->from($this->table_name);
$this->db->where('username',$user);
$this->db->where('password',$pass);
$query = $this->db->get()->result_array();
return ($query);
}
public function get_data_by_id($id = null)
{
if ($id != null) {
$this->db->select("*");
$this->db->where('id', $id);
$this->db->from($this->table_name);
$query = $this->db->get()->result_array();
return ($query[0]);
} else {
return null;
}
}
function update_data_by_id($data = array(), $id)
{
if (is_null($data) || !is_array($data)) {
return null;
}
$this->db->where('id', $id);
$this->db->update($this->table_name, $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
} | xuanlinh91/hoctiengnhat | application/models/t_admin.php | PHP | mit | 1,350 |
<html><body>
<h4>Windows 10 x64 (18362.388)</h4><br>
<h2>_POP_POWER_PLANE</h2>
<font face="arial"> +0x000 PowerPlaneId : <a href="./_UNICODE_STRING.html">_UNICODE_STRING</a><br>
+0x010 Lock : Uint8B<br>
+0x018 OldIrql : UChar<br>
+0x01c DevicePowerMw : Int4B<br>
+0x020 PmaxHandle : Ptr64 Void<br>
+0x028 NotifyDevicePowerDraw : Ptr64 void <br>
+0x030 DeviceCount : Uint8B<br>
+0x038 Devices : Ptr64 Ptr64 <a href="./_POP_DEVICE_POWER_PROFILE.html">_POP_DEVICE_POWER_PROFILE</a><br>
</font></body></html> | epikcraw/ggool | public/Windows 10 x64 (18362.388)/_POP_POWER_PLANE.html | HTML | mit | 590 |
require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter
# Creates a new PostgreSQL text search configuration. You must provide
# either a parser_name or a source_config option as per the PostgreSQL
# text search docs.
def create_extension(name, options = {})
raise ActiveRecord::PostgreSQLExtensions::FeatureNotSupportedError.new('extensions') if
!ActiveRecord::PostgreSQLExtensions::Features.extensions?
sql = "CREATE EXTENSION "
sql << "IF NOT EXISTS " if options[:if_not_exists]
sql << quote_generic(name)
sql << " SCHEMA #{quote_generic(options[:schema])}" if options[:schema]
sql << " VERSION #{quote_generic(options[:version])}" if options[:version]
sql << " FROM #{quote_generic(options[:old_version])}" if options[:old_version]
execute("#{sql};")
end
# ==== Options
#
# * <tt>if_exists</tt> - adds IF EXISTS.
# * <tt>cascade</tt> - adds CASCADE.
def drop_extension(*args)
raise ActiveRecord::PostgreSQLExtensions::FeatureNotSupportedError.new('extensions') if
!ActiveRecord::PostgreSQLExtensions::Features.extensions?
options = args.extract_options!
sql = 'DROP EXTENSION '
sql << 'IF EXISTS ' if options[:if_exists]
sql << Array(args).collect { |name| quote_generic(name) }.join(', ')
sql << ' CASCADE' if options[:cascade]
execute("#{sql};")
end
def update_extension(name, new_version = nil)
raise ActiveRecord::PostgreSQLExtensions::FeatureNotSupportedError.new('extensions') if
!ActiveRecord::PostgreSQLExtensions::Features.extensions?
sql = "ALTER EXTENSION #{quote_generic(name)} UPDATE"
sql << " TO #{quote_generic(new_version)}" if new_version;
execute("#{sql};")
end
def alter_extension_schema(name, schema)
raise ActiveRecord::PostgreSQLExtensions::FeatureNotSupportedError.new('extensions') if
!ActiveRecord::PostgreSQLExtensions::Features.extensions?
execute "ALTER EXTENSION #{quote_generic(name)} SET SCHEMA #{quote_schema(schema)};"
end
# Alters an extension. Can be used with an options Hash or in a bloack.
# For instance, all of the following examples should produce the
# same output.
#
# # with options Hash
# alter_extension(:foo, :collation => 'en_CA.UTF-8')
# alter_extension(:foo, :add_collation => 'en_CA.UTF-8')
#
# # block mode
# alter_extension(:foo) do |e|
# e.collation 'en_CA.UTF-8'
# end
#
# alter_extension(:foo) do |e|
# e.add_collation 'en_CA.UTF-8'
# end
#
# # All produce
# #
# # ALTER EXTENSION "foo" ADD COLLATION "en_CA.UTF-8";
#
# Three versions of each option are available:
#
# * add_OPTION;
# * drop_OPTION; and
# * OPTION, which is equiavlent to add_OPTION.
#
# See the PostgreSQL docs for a list of all of the available extension
# options.
#
# ==== Per-Option, uh... Options
#
# <tt>:cast</tt>, <tt>:operator</tt>, <tt>:operator_class</tt> and
# <tt>:operator_family</tt> can be set their options as a Hash like so:
#
# # With the options Hash being the actual values:
# alter_extension(:foo, :cast => { :hello => :world })
#
# # With the options Hash containing key-values:
# alter_extension(:foo, :cast => {
# :source => :hello,
# :target => :world
# })
#
# # Or with an Array thusly:
# alter_extension(:foo, :cast => [ :source_type, :target_type ])
#
# # Or with arguments like this here:
# alter_extension(:foo) do |e|
# e.cast :source_type, :target_type
# end
#
# The options themselves even have options! It's options all the way
# down!
#
# * <tt>:aggregate</tt> - <tt>:name</tt> and <tt>:types</tt>.
#
# * <tt>:cast</tt> - <tt>:source</tt> and <tt>:target</tt>.
#
# * <tt>:function</tt> - <tt>:name</tt> and <tt>:arguments</tt>. The
# <tt>:arguments</tt> option is just a straight up String like in
# the other function manipulation methods.
#
# * <tt>:operator</tt> - <tt>:name</tt>, <tt>:left_type</tt> and
# <tt>:right_type</tt>.
#
# * <tt>:operator_class</tt> and <tt>:operator_family</tt> - <tt>:name</tt>
# and <tt>:indexing_method</tt>.
def alter_extension(name, options = {})
raise ActiveRecord::PostgreSQLExtensions::FeatureNotSupportedError.new('extensions') if
!ActiveRecord::PostgreSQLExtensions::Features.extensions?
alterer = PostgreSQLExtensionAlterer.new(self, name, options)
if block_given?
yield alterer
end
execute(alterer.to_s) unless alterer.empty?
end
end
class PostgreSQLExtensionAlterer
def initialize(base, name, options = {}) #:nodoc:
raise ActiveRecord::PostgreSQLExtensions::FeatureNotSupportedError.new('extensions') if
!ActiveRecord::PostgreSQLExtensions::Features.extensions?
@base, @name, @options = base, name, options
@sql = options.collect { |k, v| build_statement(k, v) }
end
def empty? #:nodoc:
@sql.empty?
end
def to_sql #:nodoc:
"#{@sql.join(";\n")};"
end
alias :to_s :to_sql
%w{
aggregate cast collation conversion domain foreign_data_wrapper
foreign_table function operator operator_class operator_family
language schema sequence server table
text_search_configuration text_search_dictionary text_search_parser text_search_template
type view
}.each do |f|
self.class_eval(<<-EOF, __FILE__, __LINE__ + 1)
def add_#{f}(*args)
@sql << build_statement(:add_#{f}, *args)
end
alias :#{f} :add_#{f}
def drop_#{f}(*args)
@sql << build_statement(:drop_#{f}, *args)
end
EOF
end
private
ACTIONS = %w{ add drop }.freeze
def build_statement(k, *args) #:nodoc:
option = k.to_s
if option =~ /^(add|drop)_/
action = $1
option = option.gsub(/^(add|drop)_/, '')
else
action = :add
end
sql = "ALTER EXTENSION #{@base.quote_generic(@name || name)} #{action.to_s.upcase} "
sql << case option
when 'aggregate'
name, types = case v = args[0]
when Hash
v.values_at(:name, :types)
else
[ args.shift, args ]
end
"AGGREGATE %s (%s)" % [
@base.quote_generic(name),
Array(types).collect { |t|
@base.quote_generic(t)
}.join(', ')
]
when 'cast'
source, target = extract_hash_or_array_options(args, :source, :target)
"CAST (#{@base.quote_generic(source)} AS #{@base.quote_generic(target)})"
when *%w{ collation conversion domain foreign_data_wrapper
foreign_table language schema sequence server table
text_search_configuration text_search_dictionary text_search_parser
text_search_template type view }
"#{option.upcase.gsub('_', ' ')} #{@base.quote_generic(args[0])}"
when 'function'
name, arguments = case v = args[0]
when Hash
v.values_at(:name, :arguments)
else
args.flatten!
[ args.shift, *args ]
end
"FUNCTION #{@base.quote_function(name)}(#{Array(arguments).join(', ')})"
when 'operator'
name, left_type, right_type =
extract_hash_or_array_options(args, :name, :left_type, :right_type)
"OPERATOR #{@base.quote_generic(name)} (#{@base.quote_generic(left_type)}, #{@base.quote_generic(right_type)})"
when 'operator_class', 'operator_family'
object_name, indexing_method =
extract_hash_or_array_options(args, :name, :indexing_method)
"#{option.upcase.gsub('_', ' ')} #{@base.quote_generic(object_name)} USING #{@base.quote_generic(indexing_method)})"
end
sql
end
def assert_valid_action(option) #:nodoc:
if !ACTIONS.include?(option.to_s.downcase)
raise ArgumentError.new("Excepted :add or :drop for PostgreSQLExtensionAlterer action.")
end unless option.nil?
end
def extract_hash_or_array_options(hash_or_array, *keys) #:nodoc:
case v = hash_or_array[0]
when Hash
if (keys - (sliced = v.slice(*keys)).keys).length == 0
keys.collect do |k|
sliced[k]
end
else
[ v.keys.first, v.values.first ]
end
else
v = hash_or_array.flatten
[ v.shift, *v ]
end
end
end
end
end
| AF83/activerecord-postgresql-extensions | lib/active_record/postgresql_extensions/extensions.rb | Ruby | mit | 9,410 |
/*
* MultiMonteCarloTreeSearch.h
* This file defines a Mont Carlo Tree Search implementation for AI player
* Created on: Feb 11, 2014
* Author: renewang
*/
#ifndef MULTIMONTECARLOTREESEARCH_H_
#define MULTIMONTECARLOTREESEARCH_H_
#include "Global.h"
#include "Player.h"
#include "HexBoard.h"
#include "MonteCarloTreeSearch.h"
#include <boost/thread/thread.hpp>
#ifndef NDEBUG
#include "gtest/gtest_prod.h"
#endif
/** MultiMonteCarloTreeSearch class defines a Parallelized version of Mont Carlo Tree Search implementation for AI player
* MultiMonteCarloTreeSearch class is the implementation of Parallelized Mont Carlo Tree Search which include four phases:
* select, expansion, play-out and back-propagation. <br/>
* This class depends on AbstractGameTree interface which provide tree data structure and methods for game tree construction.
* The constructors used to instantiate MultiMonteCarloTreeSearch instance are <br/>
* MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer): user defined constructor which takes pointer to
* a hex board object and pointer to AI player; while parameter used for the number of simulated games (numberoftrials) is
* set as default value (2048) and number of threads (numberofthreads) is set as default value (8)<br/>
* MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer, size_t numberofthreads): user defined constructor
* which takes pointer to a hex board object and pointer to AI player; while parameter used for the number of simulated games
* (numberoftrials) is set as default value (2048) and number of threads (numberofthreads) is given by user <br/>
* MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer, size_t numberofthreads, size_t numberoftrials):
* user defined constructor which takes pointer to a hex board object and pointer to AI player. Also parameter used for the number of simulated games
* (numberoftrials) and number of threads (numberofthreads) <br/>
* Sample Usage: Please see Strategy (similar way to instantiate)
*/
class MultiMonteCarloTreeSearch : public AbstractStrategyImpl {
private:
int numofhexgons; ///< the actual playing board in the game. Need to ensure it not to be modified during the simulation
MonteCarloTreeSearch mcstimpl; ///< the actual playing board in the game. Need to ensure it not to be modified during the simulation
const HexBoard* const ptrtoboard; ///< The actual playing board in the game. Need to ensure it not to be modified during the simulation
const Player* const ptrtoplayer; ///< the actual player computer plays. Need to ensure it not to be modified during the simulation
const std::size_t numberofthreads;///< The number of threads used in Parallelized Monte Carlo method. 8 by default
const std::size_t numberoftrials;///< The number of simulated games which affects the sampling size of Parallelized Monte Carlo method. 2048 by default
char babywatsoncolor; ///< The color of AI player which is represented as single character. For example, if color of AI player is RED, then character is 'R'. BLUE as 'B'
char oppoenetcolor; ///< The color of AI player's opponent which is represented as single character. For example, if color of AI player is RED, then character for opponent is 'B'. BLUE as 'R'
///delegating simulation method which is passed to each thread for execution
void task(const std::vector<int>& bwglobal, const std::vector<int>& oppglobal,
const hexgame::shared_ptr<bool>& emptyglobal, int currentempty,
AbstractGameTree& gametree);
#ifndef NDEBUG
//for google test framework
friend class MinMaxTest;
FRIEND_TEST(MinMaxTest,CompeteHexParallelGame);
#endif
public:
//constructor
///User defined constructor which takes pointer to a hex board object and pointer to AI player as parameters
MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer);
///User defined constructor which takes pointer to a hex board object, pointer to AI player and number of threads (numberofthreads) as parameters
MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer,
size_t numberofthreads);
///User defined constructor which takes pointer to a hex board object, pointer to AI player, number of threads (numberofthreads) and number of simulated games (numberoftrials) as parameters
MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer, size_t numberofthreads, size_t numberoftrials);
///destructor
virtual ~MultiMonteCarloTreeSearch() {
}
;
///return the meaningful class name as "MultiMonteCarloTreeSearch"
std::string name() {
return string("MultiMonteCarloTreeSearch");
}
;
///Overwritten simulation method. See AbstractStrategy
int simulation(int currentempty);
///Getter for retrieving number of threads
///@param NONE
///@return number of threads
std::size_t getNumberofthreads(){
return numberofthreads;
}
///Getter for retrieving number of simulated games
///@param NONE
///@return number of simulated games
std::size_t getNumberoftrials(){
return numberoftrials;
}
};
#endif /* MULTIMONTECARLOTREESEARCH_H_ */
| renewang/HexGame | src/MultiMonteCarloTreeSearch.h | C | mit | 5,215 |
namespace AjSharpure.Language
{
using System;
using System.Collections;
using System.Linq;
using System.Text;
public class ListEnumerator : IEnumerator
{
private IList original;
private IEnumerator enumerator;
private int offset;
public ListEnumerator(IList list, int offset)
{
this.original = list;
this.enumerator = list.GetEnumerator();
this.offset = offset;
this.AdjustOffset();
}
public object Current
{
get { return this.enumerator.Current; }
}
public bool MoveNext()
{
return this.enumerator.MoveNext();
}
public void Reset()
{
this.enumerator = this.original.GetEnumerator();
this.AdjustOffset();
}
private void AdjustOffset()
{
for (int k = 0; k < this.offset; k++)
this.enumerator.MoveNext();
}
}
}
| ajlopez/AjSharpure | Src/AjSharpure/Language/ListEnumerator.cs | C# | mit | 1,058 |
# vim: fileencoding=utf-8
import calc
print(calc.add(1, 2))
print(calc.sub(1, 2))
| yusabana-sandbox/python-practice | imports/calc_import.py | Python | mit | 83 |
# Berlin Anmeldung Scrapper
You're in berlin and you want to
[register as a citzen (anmeldung)?](https://service.berlin.de/dienstleistung/120686/)
Instead of going through the calendar and finding out that all the appointments
are damn far away, with this CLI you can easily find where and when to go.

Isn't this overkill? I wanted to try `tty` gem and...well `¯\_(ツ)_/¯`
## Installation and Usage
Add this line to your application's Gemfile:
```bash
$ gem install berlin_anmeldung_scrapper
$ berlin_anmeldung_scrapper
```
## Contributing
Issues and pull requests are welcome on GitHub at https://github.com/dgmora/berlin_anmeldung_scrapper.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
| dgmora/berlin_anmeldung_scrapper | README.md | Markdown | mit | 893 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import List from './List';
/**
* Main node - renders the main section of the app.
*
* @class
* @extends Component
*/
export default class Main extends Component {
static propTypes = {
count: PropTypes.number.isRequired,
areComplete: PropTypes.bool.isRequired,
todos: PropTypes.array.isRequired,
toggle: PropTypes.func.isRequired,
}
/**
* Constructs the component and sets its initial state.
* The 'mark all complete' checkbox will be checked if all todos are complete.
*
* @param {object} props
* @param {boolean} props.areComplete - bool to determine if all todos are complete
*/
constructor(props) {
super(props);
this.state = {
checked: props.areComplete,
};
}
/**
* Resets the state when new props are received.
*
* @augments this.state
* @param {object} props
* @return void
*/
componentWillReceiveProps(props) {
this.setState({
checked: props.areComplete,
});
}
/**
* Handles toggling all todos' complete status.
*
* @augments this.state
* @param {object} e - change event
* @return void
*/
handleToggle = (e) => {
const checked = e.target.checked;
this.setState({ checked: checked }, () => this.props.toggle(checked));
}
/**
* Renders the component there are todos.
*
* @return {null|object}
*/
render() {
return (!this.props.count) ? null : (
<section className="main">
<input
onChange={this.handleToggle}
className="toggle-all"
id="toggle-all"
name="toggle-all"
type="checkbox"
checked={this.state.checked}
/>
<label htmlFor="toggle-all">Mark all as complete</label>
<List todos={this.props.todos} />
</section>
);
}
}
| rohan-deshpande/trux | examples/react/todomvc/src/components/nodes/TodoApp/Main/index.js | JavaScript | mit | 1,881 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Drivers
| 4. Helper files
| 5. Custom config files
| 6. Language files
| 7. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packages
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'email', 'session');
|
| You can also supply an alternative library name to be assigned
| in the controller:
|
| $autoload['libraries'] = array('user_agent' => 'ua');
*/
$autoload['libraries'] = array('parser', 'form_validation');
/*
| -------------------------------------------------------------------
| Auto-load Drivers
| -------------------------------------------------------------------
| These classes are located in the system/libraries folder or in your
| application/libraries folder within their own subdirectory. They
| offer multiple interchangeable driver options.
|
| Prototype:
|
| $autoload['drivers'] = array('cache');
*/
$autoload['drivers'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('common', 'url', 'validate', 'form', 'string', 'html');
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
| Trankalinos/NCS | application/config/autoload.php | PHP | mit | 3,839 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>COGS - Convention-based Ontology Generation System</title>
<!-- Bootstrap Core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
<!-- Plugin CSS -->
<link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">
<!-- Theme CSS -->
<link href="css/creative.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top">
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="#page-top">COGS</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" href="#about">About</a>
</li>
<li>
<a class="page-scroll" href="#services">Output Formats</a>
</li>
<li>
<a class="page-scroll" href="/docs">Documentation</a>
</li>
<li>
<a class="page-scroll" href="http://www.github.com/colectica/cogs">GitHub</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<header>
<div class="header-content">
<div class="header-content-inner">
<h1 id="homeHeading">Specify your information model <br/> in plain text</h1>
<hr>
COGS lets you specify your information model in plain text. From this model, COGS generates rich documentation and multiple representations. Plain text specifications allow using industry-standard tools like git to manage collaboration.
<p></p>
<a href="#about" class="btn btn-primary btn-xl page-scroll">Find Out More</a>
</div>
</div>
</header>
<section class="bg-primary" id="about">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<h2 class="section-heading">Free and Open Source</h2>
<hr class="light">
<p class="text-faded">
The Convention-based Ontology Generation System (COGS)
gives you a powerful, patterns-based way to build
ontologies. COGS enables a clean separation of concerns
and gives you full control over markup for enjoyable,
agile development. COGS includes many features that
enable fast, test-driven development for publishing
sophisticated models in a variety of formats.
</p>
<p class="text-faded">
COGS is for domain experts and groups who value <strong>ease of collaboration</strong> and
<strong>low technical barriers</strong> for participation.
</p>
<p class="text-faded">
Develop your data model in a simple, transparent way
with COGS.
</p>
<a href="/docs" class="page-scroll btn btn-default btn-xl sr-button">Read the Documentation</a>
<a href="http://www.github.com/colectica/cogs" class="page-scroll btn btn-default btn-xl sr-button">Fork on GitHub</a>
</div>
</div>
</div>
</section>
<section id="services">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">One Specification. Many Representations.</h2>
<hr class="primary">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-code text-primary sr-icons"></i>
<h3>XML Schema</h3>
<p class="text-muted">No more hand-coding XML Schema</p>
</div>
</div>
<div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-paper-plane text-primary sr-icons"></i>
<h3>JSON Schema</h3>
<p class="text-muted">Generate an equivalent representation of your model in a web-native format</p>
</div>
</div>
<div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-book text-primary sr-icons"></i>
<h3>Rich Documentation</h3>
<p class="text-muted">Make your model clear to your users</p>
</div>
</div>
<div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-link text-primary sr-icons"></i>
<h3>GraphQL, UML, OWL 2 RDF, C#, ...</h3>
<p class="text-muted">Many more formats and visualizations are available</p>
</div>
</div>
</div>
</div>
</section>
<aside class="bg-dark">
<div class="container text-center">
<div class="call-to-action">
<h2>Get Started on Your Platform</h2>
<a href="/docs/quick-start/windows-quick-start" class="btn btn-default btn-xl sr-button">Windows Quick Start</a>
<a href="/docs/quick-start/linux-quick-start" class="btn btn-default btn-xl sr-button">Linux Quick Start</a>
<a href="/docs/quick-start/macos-quick-start" class="btn btn-default btn-xl sr-button">macOS Quick Start</a>
</div>
</div>
</aside>
<section id="contact">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<p align="center"><img src="/img/cogs-logo-800.png" alt="cogs"/></p>
<h2 class="section-heading">Let's Get In Touch</h2>
<hr class="primary">
<p>Want to suggest a feature or ask a question? Get in touch using <a href="https://github.com/Colectica/cogs/issues/new">GitHub Issues</a>.</p>
</div>
</div>
</div>
</section>
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="vendor/scrollreveal/scrollreveal.min.js"></script>
<script src="vendor/magnific-popup/jquery.magnific-popup.min.js"></script>
<!-- Theme JavaScript -->
<script src="js/creative.min.js"></script>
</body>
</html>
| Colectica/cogs-web | index.html | HTML | mit | 9,044 |
<?php
namespace CDI\EnfermeriaBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class TiposInsumoControllerTest extends WebTestCase
{
/*
public function testCompleteScenario()
{
// Create a new client to browse the application
$client = static::createClient();
// Create a new entry in the database
$crawler = $client->request('GET', '/tiposinsumo/');
$this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /tiposinsumo/");
$crawler = $client->click($crawler->selectLink('Create a new entry')->link());
// Fill in the form and submit it
$form = $crawler->selectButton('Create')->form(array(
'cdi_enfermeriabundle_tiposinsumo[field_name]' => 'Test',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check data in the show view
$this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")');
// Edit the entity
$crawler = $client->click($crawler->selectLink('Edit')->link());
$form = $crawler->selectButton('Update')->form(array(
'cdi_enfermeriabundle_tiposinsumo[field_name]' => 'Foo',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check the element contains an attribute with value equals "Foo"
$this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]');
// Delete the entity
$client->submit($crawler->selectButton('Delete')->form());
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
}
| ovelasquez/implantacion | src/CDI/EnfermeriaBundle/Tests/Controller/TiposInsumoControllerTest.php | PHP | mit | 1,966 |
<?php
if (!(defined('IN_IA'))) {
exit('Access Denied');
}
class Goods_EweiShopV2Model
{
/**
* 获取商品规格
* @param type $goodsid
* @param type $optionid
* @return type
*/
public function getOption($goodsid = 0, $optionid = 0)
{
global $_W;
return pdo_fetch('select * from ' . tablename('ewei_shop_goods_option') . ' where id=:id and goodsid=:goodsid and uniacid=:uniacid Limit 1', array(':id' => $optionid, ':uniacid' => $_W['uniacid'], ':goodsid' => $goodsid));
}
/**
* 获取商品规格的价格
* @param type $goodsid
* @param type $optionid
* @return type
*/
public function getOptionPirce($goodsid = 0, $optionid = 0)
{
global $_W;
return pdo_fetchcolumn('select marketprice from ' . tablename('ewei_shop_goods_option') . ' where id=:id and goodsid=:goodsid and uniacid=:uniacid', array(':id' => $optionid, ':uniacid' => $_W['uniacid'], ':goodsid' => $goodsid));
}
/**
* 获取宝贝
* @param type $page
* @param type $pagesize
*/
public function getList($args = array())
{
global $_W;
$openid = $_W['openid'];
$page = ((!(empty($args['page'])) ? intval($args['page']) : 1));
$pagesize = ((!(empty($args['pagesize'])) ? intval($args['pagesize']) : 10));
$random = ((!(empty($args['random'])) ? $args['random'] : false));
$displayorder = 'displayorder';
$merchid = ((!(empty($args['merchid'])) ? trim($args['merchid']) : ''));
if (!(empty($merchid))) {
$displayorder = 'merchdisplayorder';
}
$order = ((!(empty($args['order'])) ? $args['order'] : ' ' . $displayorder . ' desc,createtime desc'));
$orderby = ((empty($args['order']) ? '' : ((!(empty($args['by'])) ? $args['by'] : ''))));
$merch_plugin = p('merch');
$merch_data = m('common')->getPluginset('merch');
if ($merch_plugin && $merch_data['is_openmerch']) {
$is_openmerch = 1;
}
else {
$is_openmerch = 0;
}
$condition = ' and `uniacid` = :uniacid AND `deleted` = 0 and status=1';
$params = array(':uniacid' => $_W['uniacid']);
if (!(empty($merchid))) {
$condition .= ' and merchid=:merchid and checked=0';
$params[':merchid'] = $merchid;
}
else if ($is_openmerch == 0) {
$condition .= ' and `merchid` = 0';
}
else {
$condition .= ' and `checked` = 0';
}
if (empty($args['type'])) {
$condition .= ' and type !=10 ';
}
$ids = ((!(empty($args['ids'])) ? trim($args['ids']) : ''));
if (!(empty($ids))) {
$condition .= ' and id in ( ' . $ids . ')';
}
$isnew = ((!(empty($args['isnew'])) ? 1 : 0));
if (!(empty($isnew))) {
$condition .= ' and isnew=1';
}
$ishot = ((!(empty($args['ishot'])) ? 1 : 0));
if (!(empty($ishot))) {
$condition .= ' and ishot=1';
}
$isrecommand = ((!(empty($args['isrecommand'])) ? 1 : 0));
if (!(empty($isrecommand))) {
$condition .= ' and isrecommand=1';
}
$isdiscount = ((!(empty($args['isdiscount'])) ? 1 : 0));
if (!(empty($isdiscount))) {
$condition .= ' and isdiscount=1';
}
$issendfree = ((!(empty($args['issendfree'])) ? 1 : 0));
if (!(empty($issendfree))) {
$condition .= ' and issendfree=1';
}
$istime = ((!(empty($args['istime'])) ? 1 : 0));
if (!(empty($istime))) {
$condition .= ' and istime=1 ';
}
if (isset($args['nocommission'])) {
$condition .= ' AND `nocommission`=' . intval($args['nocommission']);
}
$keywords = ((!(empty($args['keywords'])) ? $args['keywords'] : ''));
if (!(empty($keywords))) {
$condition .= ' AND (`title` LIKE :keywords OR `keywords` LIKE :keywords)';
$params[':keywords'] = '%' . trim($keywords) . '%';
if (empty($merchid)) {
$condition .= ' AND nosearch=0';
}
}
if (!(empty($args['cate']))) {
$category = m('shop')->getAllCategory();
$catearr = array($args['cate']);
foreach ($category as $index => $row ) {
if ($row['parentid'] == $args['cate']) {
$catearr[] = $row['id'];
foreach ($category as $ind => $ro ) {
if ($ro['parentid'] == $row['id']) {
$catearr[] = $ro['id'];
}
}
}
}
$catearr = array_unique($catearr);
$condition .= ' AND ( ';
foreach ($catearr as $key => $value ) {
if ($key == 0) {
$condition .= 'FIND_IN_SET(' . $value . ',cates)';
}
else {
$condition .= ' || FIND_IN_SET(' . $value . ',cates)';
}
}
$condition .= ' <>0 )';
}
$member = m('member')->getMember($openid);
if (!(empty($member))) {
$levelid = intval($member['level']);
$groupid = intval($member['groupid']);
$condition .= ' and ( ifnull(showlevels,\'\')=\'\' or FIND_IN_SET( ' . $levelid . ',showlevels)<>0 ) ';
$condition .= ' and ( ifnull(showgroups,\'\')=\'\' or FIND_IN_SET( ' . $groupid . ',showgroups)<>0 ) ';
}
else {
$condition .= ' and ifnull(showlevels,\'\')=\'\' ';
$condition .= ' and ifnull(showgroups,\'\')=\'\' ';
}
$total = '';
if (!($random)) {
$sql = 'SELECT id,title,subtitle,thumb,marketprice,productprice,minprice,maxprice,isdiscount,isdiscount_time,isdiscount_discounts,sales,salesreal,total,description,bargain,`type`,ispresell,hasoption' . "\r\n" . ' FROM ' . tablename('ewei_shop_goods') . ' where 1 ' . $condition . ' ORDER BY ' . $order . ' ' . $orderby . ' LIMIT ' . (($page - 1) * $pagesize) . ',' . $pagesize;
$total = pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_goods') . ' where 1 ' . $condition . ' ', $params);
}
else {
$sql = 'SELECT id,title,thumb,marketprice,productprice,minprice,maxprice,isdiscount,isdiscount_time,isdiscount_discounts,sales,salesreal,total,description,bargain,`type`,ispresell,hasoption' . "\r\n" . ' FROM ' . tablename('ewei_shop_goods') . ' where 1 ' . $condition . ' ORDER BY rand() LIMIT ' . $pagesize;
$total = $pagesize;
}
$list = pdo_fetchall($sql, $params);
$list = set_medias($list, 'thumb');
return array('list' => $list, 'total' => $total);
}
/**
* 获取宝贝
* @param type $page
* @param type $pagesize
*/
public function getListbyCoupon($args = array())
{
global $_W;
$openid = $_W['openid'];
$page = ((!(empty($args['page'])) ? intval($args['page']) : 1));
$pagesize = ((!(empty($args['pagesize'])) ? intval($args['pagesize']) : 10));
$random = ((!(empty($args['random'])) ? $args['random'] : false));
$order = ((!(empty($args['order'])) ? $args['order'] : ' displayorder desc,createtime desc'));
$orderby = ((empty($args['order']) ? '' : ((!(empty($args['by'])) ? $args['by'] : ''))));
$couponid = ((empty($args['couponid']) ? '' : $args['couponid']));
$merch_plugin = p('merch');
$merch_data = m('common')->getPluginset('merch');
if ($merch_plugin && $merch_data['is_openmerch']) {
$is_openmerch = 1;
}
else {
$is_openmerch = 0;
}
$condition = ' and g.`uniacid` = :uniacid AND g.`deleted` = 0 and g.status=1';
$params = array(':uniacid' => $_W['uniacid']);
$merchid = ((!(empty($args['merchid'])) ? trim($args['merchid']) : ''));
if (!(empty($merchid))) {
$condition .= ' and g.merchid=:merchid and g.checked=0';
$params[':merchid'] = $merchid;
}
else if ($is_openmerch == 0) {
$condition .= ' and g.`merchid` = 0';
}
else {
$condition .= ' and g.`checked` = 0';
}
if (empty($args['type'])) {
$condition .= ' and g.type !=10 ';
}
$ids = ((!(empty($args['ids'])) ? trim($args['ids']) : ''));
if (!(empty($ids))) {
$condition .= ' and g.id in ( ' . $ids . ')';
}
$isnew = ((!(empty($args['isnew'])) ? 1 : 0));
if (!(empty($isnew))) {
$condition .= ' and g.isnew=1';
}
$ishot = ((!(empty($args['ishot'])) ? 1 : 0));
if (!(empty($ishot))) {
$condition .= ' and g.ishot=1';
}
$isrecommand = ((!(empty($args['isrecommand'])) ? 1 : 0));
if (!(empty($isrecommand))) {
$condition .= ' and g.isrecommand=1';
}
$isdiscount = ((!(empty($args['isdiscount'])) ? 1 : 0));
if (!(empty($isdiscount))) {
$condition .= ' and g.isdiscount=1';
}
$issendfree = ((!(empty($args['issendfree'])) ? 1 : 0));
if (!(empty($issendfree))) {
$condition .= ' and g.issendfree=1';
}
$istime = ((!(empty($args['istime'])) ? 1 : 0));
if (!(empty($istime))) {
$condition .= ' and g.istime=1 ';
}
if (isset($args['nocommission'])) {
$condition .= ' AND g.`nocommission`=' . intval($args['nocommission']);
}
$keywords = ((!(empty($args['keywords'])) ? $args['keywords'] : ''));
if (!(empty($keywords))) {
$condition .= ' AND (g.`title` LIKE :keywords OR g.`keywords` LIKE :keywords)';
$params[':keywords'] = '%' . trim($keywords) . '%';
}
if (!(empty($args['cate']))) {
$category = m('shop')->getAllCategory();
$catearr = array($args['cate']);
foreach ($category as $index => $row ) {
if ($row['parentid'] == $args['cate']) {
$catearr[] = $row['id'];
foreach ($category as $ind => $ro ) {
if ($ro['parentid'] == $row['id']) {
$catearr[] = $ro['id'];
}
}
}
}
$catearr = array_unique($catearr);
$condition .= ' AND ( ';
foreach ($catearr as $key => $value ) {
if ($key == 0) {
$condition .= 'FIND_IN_SET(' . $value . ',g.cates)';
}
else {
$condition .= ' || FIND_IN_SET(' . $value . ',g.cates)';
}
}
$condition .= ' <>0 )';
}
$member = m('member')->getMember($openid);
if (!(empty($member))) {
$levelid = intval($member['level']);
$groupid = intval($member['groupid']);
$condition .= ' and ( ifnull(g.showlevels,\'\')=\'\' or FIND_IN_SET( ' . $levelid . ',g.showlevels)<>0 ) ';
$condition .= ' and ( ifnull(g.showgroups,\'\')=\'\' or FIND_IN_SET( ' . $groupid . ',g.showgroups)<>0 ) ';
}
else {
$condition .= ' and ifnull(g.showlevels,\'\')=\'\' ';
$condition .= ' and ifnull(g.showgroups,\'\')=\'\' ';
}
$table = tablename('ewei_shop_goods') . ' g';
$distinct = '';
if (0 < $couponid) {
$data = pdo_fetch('select c.* from ' . tablename('ewei_shop_coupon_data') . ' cd inner join ' . tablename('ewei_shop_coupon') . ' c on cd.couponid = c.id where cd.id=:id and cd.uniacid=:uniacid and coupontype =0 limit 1', array(':id' => $couponid, ':uniacid' => $_W['uniacid']));
if (!(empty($data))) {
if (($data['limitgoodcatetype'] == 1) && !(empty($data['limitgoodcateids']))) {
$limitcateids = explode(',', $data['limitgoodcateids']);
if (0 < count($limitcateids)) {
$table = '(';
$i = 0;
foreach ($limitcateids as $cateid ) {
++$i;
if (1 < $i) {
$table .= ' union all ';
}
$table .= 'select * from ' . tablename('ewei_shop_goods') . ' where FIND_IN_SET(' . $cateid . ',cates)';
}
$table .= ') g ';
$distinct = 'distinct';
}
}
if (($data['limitgoodtype'] == 1) && !(empty($data['limitgoodids']))) {
$condition .= ' and g.id in (' . $data['limitgoodids'] . ') ';
}
}
}
if (!($random)) {
$sql = 'SELECT ' . $distinct . ' g.id,g.title,g.thumb,g.marketprice,g.productprice,g.minprice,g.maxprice,g.isdiscount,g.isdiscount_time,g.isdiscount_discounts,g.sales,g.total,g.description,g.bargain FROM ' . $table . ' where 1 ' . $condition . ' ORDER BY ' . $order . ' ' . $orderby . ' LIMIT ' . (($page - 1) * $pagesize) . ',' . $pagesize;
$total = pdo_fetchcolumn('select ' . $distinct . ' count(*) from ' . $table . ' where 1 ' . $condition . ' ', $params);
}
else {
$sql = 'SELECT ' . $distinct . ' g.id,g.title,g.thumb,g.marketprice,g.productprice,g.minprice,g.maxprice,g.isdiscount,g.isdiscount_time,g.isdiscount_discounts,g.sales,g.total,g.description,g.bargain FROM ' . $table . ' where 1 ' . $condition . ' ORDER BY rand() LIMIT ' . $pagesize;
$total = $pagesize;
}
$list = pdo_fetchall($sql, $params);
$list = set_medias($list, 'thumb');
return array('list' => $list, 'total' => $total);
}
public function getTotals()
{
global $_W;
return array('sale' => pdo_fetchcolumn('select count(1) from ' . tablename('ewei_shop_goods') . ' where status > 0 and checked=0 and deleted=0 and total>0 and uniacid=:uniacid', array(':uniacid' => $_W['uniacid'])), 'out' => pdo_fetchcolumn('select count(1) from ' . tablename('ewei_shop_goods') . ' where status > 0 and deleted=0 and total=0 and uniacid=:uniacid', array(':uniacid' => $_W['uniacid'])), 'stock' => pdo_fetchcolumn('select count(1) from ' . tablename('ewei_shop_goods') . ' where (status=0 or checked=1) and deleted=0 and uniacid=:uniacid', array(':uniacid' => $_W['uniacid'])), 'cycle' => pdo_fetchcolumn('select count(1) from ' . tablename('ewei_shop_goods') . ' where deleted=1 and uniacid=:uniacid', array(':uniacid' => $_W['uniacid'])));
}
/**
* 获取宝贝评价
* @param type $page
* @param type $pagesize
*/
public function getComments($goodsid = '0', $args = array())
{
global $_W;
$page = ((!(empty($args['page'])) ? intval($args['page']) : 1));
$pagesize = ((!(empty($args['pagesize'])) ? intval($args['pagesize']) : 10));
$condition = ' and `uniacid` = :uniacid AND `goodsid` = :goodsid and deleted=0';
$params = array(':uniacid' => $_W['uniacid'], ':goodsid' => $goodsid);
$sql = 'SELECT id,nickname,headimgurl,content,images FROM ' . tablename('ewei_shop_goods_comment') . ' where 1 ' . $condition . ' ORDER BY createtime desc LIMIT ' . (($page - 1) * $pagesize) . ',' . $pagesize;
$list = pdo_fetchall($sql, $params);
foreach ($list as &$row ) {
$row['images'] = set_medias(unserialize($row['images']));
}
unset($row);
return $list;
}
public function isFavorite($id = '')
{
global $_W;
$count = pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_member_favorite') . ' where goodsid=:goodsid and deleted=0 and openid=:openid and uniacid=:uniacid limit 1', array(':goodsid' => $id, ':openid' => $_W['openid'], ':uniacid' => $_W['uniacid']));
return 0 < $count;
}
public function addHistory($goodsid = 0)
{
global $_W;
pdo_query('update ' . tablename('ewei_shop_goods') . ' set viewcount=viewcount+1 where id=:id and uniacid=\'' . $_W[uniacid] . '\' ', array(':id' => $goodsid));
$history = pdo_fetch('select id,times from ' . tablename('ewei_shop_member_history') . ' where goodsid=:goodsid and uniacid=:uniacid and openid=:openid limit 1', array(':goodsid' => $goodsid, ':uniacid' => $_W['uniacid'], ':openid' => $_W['openid']));
if (empty($history)) {
$history = array('uniacid' => $_W['uniacid'], 'openid' => $_W['openid'], 'goodsid' => $goodsid, 'deleted' => 0, 'createtime' => time(), 'times' => 1);
pdo_insert('ewei_shop_member_history', $history);
}
else {
pdo_update('ewei_shop_member_history', array('deleted' => 0, 'times' => $history['times'] + 1), array('id' => $history['id']));
}
}
public function getCartCount()
{
global $_W;
global $_GPC;
$count = pdo_fetchcolumn('select sum(total) from ' . tablename('ewei_shop_member_cart') . ' where uniacid=:uniacid and openid=:openid and deleted=0 limit 1', array(':openid' => $_W['openid'], ':uniacid' => $_W['uniacid']));
return $count;
}
/**
* 获取商品规格图片
* @param type $specs
* @return type
*/
public function getSpecThumb($specs)
{
global $_W;
$thumb = '';
$cartspecs = explode('_', $specs);
$specid = $cartspecs[0];
if (!(empty($specid))) {
$spec = pdo_fetch('select thumb from ' . tablename('ewei_shop_goods_spec_item') . ' ' . ' where id=:id and uniacid=:uniacid limit 1 ', array(':id' => $specid, ':uniacid' => $_W['uniacid']));
if (!(empty($spec))) {
if (!(empty($spec['thumb']))) {
$thumb = $spec['thumb'];
}
}
}
return $thumb;
}
/**
* 获取商品规格图片
* @param type $specs
* @return type
*/
public function getOptionThumb($goodsid = 0, $optionid = 0)
{
global $_W;
$thumb = '';
$option = $this->getOption($goodsid, $optionid);
if (!(empty($option))) {
$specs = $option['specs'];
$thumb = $this->getSpecThumb($specs);
}
return $thumb;
}
public function getAllMinPrice($goods)
{
global $_W;
if (is_array($goods)) {
$openid = $_W['openid'];
$level = m('member')->getLevel($openid);
$member = m('member')->getMember($openid);
$levelid = $member['level'];
foreach ($goods as &$value ) {
$minprice = $value['minprice'];
$maxprice = $value['maxprice'];
if ($value['isdiscount'] && (time() <= $value['isdiscount_time'])) {
$value['oldmaxprice'] = $maxprice;
$isdiscount_discounts = json_decode($value['isdiscount_discounts'], true);
$prices = array();
if (!(isset($isdiscount_discounts['type'])) || empty($isdiscount_discounts['type'])) {
$prices_array = m('order')->getGoodsDiscountPrice($value, $level, 1);
$prices[] = $prices_array['price'];
}
else {
$goods_discounts = m('order')->getGoodsDiscounts($value, $isdiscount_discounts, $levelid);
$prices = $goods_discounts['prices'];
}
$minprice = min($prices);
$maxprice = max($prices);
}
$value['minprice'] = $minprice;
$value['maxprice'] = $maxprice;
}
unset($value);
}
else {
$goods = array();
}
return $goods;
}
public function getOneMinPrice($goods)
{
$goods = array($goods);
$res = $this->getAllMinPrice($goods);
return $res[0];
}
public function getMemberPrice($goods, $level)
{
global $_W;
if (!(empty($goods['isnodiscount']))) {
return;
}
if (!(empty($level['id']))) {
$level = pdo_fetch('select * from ' . tablename('ewei_shop_member_level') . ' where id=:id and uniacid=:uniacid and enabled=1 limit 1', array(':id' => $level['id'], ':uniacid' => $_W['uniacid']));
$level = ((empty($level) ? array() : $level));
}
$discounts = json_decode($goods['discounts'], true);
if (is_array($discounts)) {
$key = ((!(empty($level['id'])) ? 'level' . $level['id'] : 'default'));
if (!(isset($discounts['type'])) || empty($discounts['type'])) {
$memberprice = $goods['minprice'];
if (!(empty($discounts[$key]))) {
$dd = floatval($discounts[$key]);
if ((0 < $dd) && ($dd < 10)) {
$memberprice = round(($dd / 10) * $goods['minprice'], 2);
}
}
else {
$dd = floatval($discounts[$key . '_pay']);
$md = floatval($level['discount']);
if (!(empty($dd))) {
$memberprice = round($dd, 2);
}
else if ((0 < $md) && ($md < 10)) {
$memberprice = round(($md / 10) * $goods['minprice'], 2);
}
}
return $memberprice;
}
$options = m('goods')->getOptions($goods);
$marketprice = array();
foreach ($options as $option ) {
$discount = trim($discounts[$key]['option' . $option['id']]);
if ($discount == '') {
$discount = round(floatval($level['discount']) * 10, 2) . '%';
}
$optionprice = m('order')->getFormartDiscountPrice($discount, $option['marketprice']);
$marketprice[] = $optionprice;
}
$minprice = min($marketprice);
$maxprice = max($marketprice);
$memberprice = array('minprice' => (double) $minprice, 'maxprice' => (double) $maxprice);
if ($memberprice['minprice'] < $memberprice['maxprice']) {
$memberprice = $memberprice['minprice'] . '~' . $memberprice['maxprice'];
}
else {
$memberprice = $memberprice['minprice'];
}
return $memberprice;
}
}
public function getOptions($goods)
{
global $_W;
$id = $goods['id'];
$specs = false;
$options = false;
if (!(empty($goods)) && $goods['hasoption']) {
$specs = pdo_fetchall('select* from ' . tablename('ewei_shop_goods_spec') . ' where goodsid=:goodsid and uniacid=:uniacid order by displayorder asc', array(':goodsid' => $id, ':uniacid' => $_W['uniacid']));
foreach ($specs as &$spec ) {
$spec['items'] = pdo_fetchall('select * from ' . tablename('ewei_shop_goods_spec_item') . ' where specid=:specid order by displayorder asc', array(':specid' => $spec['id']));
}
unset($spec);
$options = pdo_fetchall('select * from ' . tablename('ewei_shop_goods_option') . ' where goodsid=:goodsid and uniacid=:uniacid order by displayorder asc', array(':goodsid' => $id, ':uniacid' => $_W['uniacid']));
}
if ((0 < $goods['ispresell']) && (($goods['preselltimeend'] == 0) || (time() < $goods['preselltimeend']))) {
$options['marketprice'] = $options['presellprice'];
}
return $options;
}
/**
* 商品访问权限
* @param array $goods
* @param array $member
* @return int
*/
public function visit($goods = array(), $member = array())
{
global $_W;
if (empty($goods)) {
return 1;
}
if (empty($member)) {
$member = m('member')->getMember($_W['openid']);
}
$showlevels = (($goods['showlevels'] != '' ? explode(',', $goods['showlevels']) : array()));
$showgroups = (($goods['showgroups'] != '' ? explode(',', $goods['showgroups']) : array()));
$showgoods = 0;
if (!(empty($member))) {
if ((!(empty($showlevels)) && in_array($member['level'], $showlevels)) || (!(empty($showgroups)) && in_array($member['groupid'], $showgroups)) || (empty($showlevels) && empty($showgroups))) {
$showgoods = 1;
}
}
else if (empty($showlevels) && empty($showgroups)) {
$showgoods = 1;
}
return $showgoods;
}
/**
*
* 是否已经有重复购买的商品
* @param $goods
* @return bool
*/
public function canBuyAgain($goods)
{
global $_W;
$condition = '';
$id = $goods['id'];
if (isset($goods['goodsid'])) {
$id = $goods['goodsid'];
}
if (empty($goods['buyagain_islong'])) {
$condition = ' AND canbuyagain = 1';
}
$order_goods = pdo_fetchall('SELECT id,orderid FROM ' . tablename('ewei_shop_order_goods') . ' WHERE uniacid=:uniaicd AND openid=:openid AND goodsid=:goodsid ' . $condition, array(':uniaicd' => $_W['uniacid'], ':openid' => $_W['openid'], ':goodsid' => $id), 'orderid');
if (empty($order_goods)) {
return false;
}
$order = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('ewei_shop_order') . ' WHERE uniacid=:uniaicd AND status>=:status AND id IN (' . implode(',', array_keys($order_goods)) . ')', array(':uniaicd' => $_W['uniacid'], ':status' => (empty($goods['buyagain_condition']) ? '1' : '3')));
return !(empty($order));
}
/**
* 使用掉重复购买的变量
* @param $goods
*/
public function useBuyAgain($orderid)
{
global $_W;
$order_goods = pdo_fetchall('SELECT id,goodsid FROM ' . tablename('ewei_shop_order_goods') . ' WHERE uniacid=:uniaicd AND openid=:openid AND canbuyagain = 1 AND orderid <> :orderid', array(':uniaicd' => $_W['uniacid'], ':openid' => $_W['openid'], 'orderid' => $orderid), 'goodsid');
if (empty($order_goods)) {
return false;
}
pdo_query('UPDATE ' . tablename('ewei_shop_order_goods') . ' SET `canbuyagain`=\'0\' WHERE uniacid=:uniacid AND goodsid IN (' . implode(',', array_keys($order_goods)) . ')', array(':uniacid' => $_W['uniacid']));
}
public function getTaskGoods($openid, $goodsid, $rank, $log_id = 0, $join_id = 0, $optionid = 0, $total = 0)
{
global $_W;
$is_task_goods = 0;
$is_task_goods_option = 0;
if (!(empty($join_id))) {
$task_plugin = p('task');
$flag = 1;
}
else if (!(empty($log_id))) {
$task_plugin = p('lottery');
$flag = 2;
}
$param = array();
$param['openid'] = $openid;
$param['goods_id'] = $goodsid;
$param['rank'] = $rank;
$param['join_id'] = $join_id;
$param['log_id'] = $log_id;
$param['goods_spec'] = $optionid;
$param['goods_num'] = $total;
if ($task_plugin && (!(empty($join_id)) || !(empty($log_id)))) {
$task_goods = $task_plugin->getGoods($param);
}
if (!(empty($task_goods)) && empty($total) && (!(empty($join_id)) || !(empty($log_id)))) {
if (!(empty($task_goods['spec']))) {
foreach ($task_goods['spec'] as $k => $v ) {
if (empty($v['total'])) {
unset($task_goods['spec'][$k]);
continue;
}
if (!(empty($optionid))) {
if ($k == $optionid) {
$task_goods['marketprice'] = $v['marketprice'];
$task_goods['total'] = $v['total'];
}
else {
unset($task_goods['spec'][$k]);
}
}
if (!(empty($optionid)) && ($k != $optionid)) {
unset($task_goods['spec'][$k]);
}
else if (!(empty($optionid)) && ($k != $optionid)) {
$task_goods['marketprice'] = $v['marketprice'];
$task_goods['total'] = $v['total'];
}
}
if (!(empty($task_goods['spec']))) {
$is_task_goods = $flag;
$is_task_goods_option = 1;
}
}
else if (!(empty($task_goods['total']))) {
$is_task_goods = $flag;
}
}
$data = array();
$data['is_task_goods'] = $is_task_goods;
$data['is_task_goods_option'] = $is_task_goods_option;
$data['task_goods'] = $task_goods;
return $data;
}
public function wholesaleprice($goods)
{
$goods2 = array();
foreach ($goods as $good ) {
if ($good['type'] == 4) {
if (empty($goods2[$good['goodsid']])) {
$intervalprices = array();
if (0 < $good['intervalfloor']) {
$intervalprices[] = array('intervalnum' => intval($good['intervalnum1']), 'intervalprice' => floatval($good['intervalprice1']));
}
if (1 < $good['intervalfloor']) {
$intervalprices[] = array('intervalnum' => intval($good['intervalnum2']), 'intervalprice' => floatval($good['intervalprice2']));
}
if (2 < $good['intervalfloor']) {
$intervalprices[] = array('intervalnum' => intval($good['intervalnum3']), 'intervalprice' => floatval($good['intervalprice3']));
}
$goods2[$good['goodsid']] = array('goodsid' => $good['goodsid'], 'total' => $good['total'], 'intervalfloor' => $good['intervalfloor'], 'intervalprice' => $intervalprices);
}
else {
$goods2[$good['goodsid']]['total'] += $good['total'];
}
}
}
foreach ($goods2 as $good2 ) {
$intervalprices2 = iunserializer($good2['intervalprice']);
$price = 0;
foreach ($intervalprices2 as $intervalprice ) {
if ($intervalprice['intervalnum'] <= $good2['total']) {
$price = $intervalprice['intervalprice'];
}
}
foreach ($goods as &$good ) {
if ($good['goodsid'] == $good2['goodsid']) {
$good['wholesaleprice'] = $price;
$good['goodsalltotal'] = $good2['total'];
}
}
unset($good);
}
return $goods;
}
}
?> | Broomspun/shanque | addons/ewei_shopv2/core/model/goods.php | PHP | mit | 26,300 |
---
title: 周末流水账
author: Paul
layout: post
categories:
- 生活
tags:
---

上周单位组织去了农庄采摘蔬菜,这周老婆计划带Nikki去千桃园喝茶。
早上10点不到出发去千桃园,结果到了发现那个车堵得完全动不了,好不容易到了地方,结果问了N家喝茶的地儿,都是没位置……
走了近十几二十分钟才找了家茶庄坐下喝茶吃饭。
下午回家,和女儿一起睡午觉,好爽。
晚上,去了爷爷家聚餐。 | Paulreina/p | _posts/2015-03-29-about-weekend.md | Markdown | mit | 563 |
package com.example.mytest.model;
public class Helper {
private GPSCoordinates location;
private String id;
public Helper(GPSCoordinates location, String id) {
this.location = location;
this.id = id;
}
public GPSCoordinates getLocation() {
return location;
}
public String getId() {
return id;
}
}
| ankur22/disrupt2014-android | MyTest/src/com/example/mytest/model/Helper.java | Java | mit | 321 |
#ifndef QUICK_SORT_H_
#define QUICK_SORT_H_
#include <algorithm>
namespace detail {
template <typename RandomIt>
void quick_sort_in_place(RandomIt first, RandomIt last) {
if (last - first < 2) return;
auto pivot = *first;
RandomIt last_lt = first;
RandomIt last_eq = first + 1;
RandomIt first_gt = last;
while (last_eq < first_gt) {
if (*last_eq < pivot) {
std::iter_swap(last_eq++, last_lt++);
} else if (pivot < *last_eq) {
std::iter_swap(last_eq, --first_gt);
} else {
++last_eq;
}
}
quick_sort_in_place(first, last_lt);
quick_sort_in_place(first_gt, last);
}
} // namespace detail
template <typename Container>
Container quick_sort(Container xs) {
#ifndef DEBUG
std::random_shuffle(std::begin(xs), std::end(xs));
#endif
detail::quick_sort_in_place(std::begin(xs), std::end(xs));
return xs;
}
#endif // QUICK_SORT_H_
| sun-zheng-an/algo | quick_sort/quick_sort.h | C | mit | 897 |
<?php
namespace coaching\siteBundle\Controller;
use coaching\siteBundle\Entity\Sportif;
use coaching\siteBundle\Entity\User;
use coaching\siteBundle\Entity\Coach;
use coaching\siteBundle\Entity\Training;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class CoachingController extends Controller
{
public function indexAction($name)
{
return $this->render('coachingBundle:coaching:index.html.twig', array('name' => $name));
}
public function accueilAction()
{
return $this->render('coachingBundle:coaching:accueil.html.twig');
}
public function sportifAction()
{
$user = $this->container->get('security.context')->getToken()->getUser();
$doctrine=$this->getDoctrine();
$manager=$doctrine->getManager();
$repository=$manager->getRepository("coachingBundle:User");
if($user!='anon.')
{
$temp=$repository->find($user->getId());
$repository=$manager->getRepository("coachingBundle:Sportif");
$deja=$repository->findByuser($user->getId());
if(empty($deja))
{
$sportif=new Sportif();
$formBuilder = $this->createFormBuilder($sportif);
$formBuilder
->add('taille','integer')
->add('poids','number')
->add('sexe','choice', array('choices' =>array('0'=>'Masculin','1'=>'Féminin'),'expanded' => 'true','data' => '0'))
->add('date_naissance','birthday',array('format'=>'d/M/y'))
->add('niveau','choice', array('choices' =>array('Débutant'=>'Debutant','Intermédiaire'=>'Intermediaire', 'Avancé'=>'Avancé','Professionnel'=>'Professionnel'),'expanded'=>'false'))
->add('training','entity',array('class'=>'coaching\siteBundle\Entity\Training','property'=>'type'));
$form = $formBuilder->getForm();
$request = $this->get('request');
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$sportif->setUser($temp);
$em = $this->getDoctrine()->getManager();
$em->persist($sportif);
$em->flush();
}
}
return $this->render('coachingBundle:coaching:sportif.html.twig', array('form'=> $form->createView()));
}
else
{
return $this->render('coachingBundle:coaching:sportif2.html.twig', array('sportif'=>$deja[0],'user'=>$user));
}
}
else
{
return $this->render('coachingBundle:coaching:wrong.html.twig');
}
}
public function coachAction()
{
$user = $this->container->get('security.context')->getToken()->getUser();
$doctrine=$this->getDoctrine();
$manager=$doctrine->getManager();
$repository=$manager->getRepository("coachingBundle:User");
if($user!='anon.')
{
$temp=$repository->find($user->getId());
$coach=new Coach();
$formBuilder = $this->createFormBuilder($coach);
$formBuilder
->add('tarif','number')
->add('sexe','choice', array('choices' =>array('0'=>'Masculin','1'=>'Féminin'),'expanded' => 'true','data' => '0'));
$form = $formBuilder->getForm();
$request = $this->get('request');
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$coach->setUser($temp);
$em = $this->getDoctrine()->getManager();
$em->persist($coach);
$em->flush();
}
}
return $this->render('coachingBundle:coaching:coach.html.twig', array('form'=> $form->createView()));
}
else
{
return $this->render('coachingBundle:coaching:wrong.html.twig');
}
}
public function forumAction()
{
return $this->render('coachingBundle:coaching:forum.html.twig', array());
}
public function boutiqueAction()
{
return $this->render('coachingBundle:coaching:boutique.html.twig', array());
}
public function sportifModifAction()
{
$user = $this->container->get('security.context')->getToken()->getUser();
$doctrine=$this->getDoctrine();
$manager=$doctrine->getManager();
$repository=$manager->getRepository("coachingBundle:User");
$temp=$repository->find($user->getId());
$repository=$manager->getRepository("coachingBundle:Sportif");
$deja=$repository->findByuser($user->getId());
// echo "<pre>".print_r($deja,true)."</pre>";
//$sportif=new Sportif();
$formBuilder = $this->createFormBuilder($deja);
if($deja[0]->getSexe()=='Masculin')
$sexe=1;
else
$sexe=0;
echo $deja[0]->getDateNaissance()->format('d/M/Y');
$formBuilder
->add('taille','integer',array('data' => $deja[0]->getTaille()))
->add('poids','number',array('data' => $deja[0]->getPoids()))
->add('sexe','choice', array('choices' =>array('0'=>'Masculin','1'=>'Féminin'),'expanded' => 'true','data' => $sexe))
->add('date_naissance','birthday',array('format'=>'d/M/y'),array('data'=>$deja[0]->getDateNaissance()))
->add('niveau','choice', array('choices' =>array('Débutant'=>'Debutant','Intermédiaire'=>'Intermediaire', 'Avancé'=>'Avancé','Professionnel'=>'Professionnel'),'expanded'=>'false','data'=> $deja[0]->getNiveau()))
->add('training','entity',array('class'=>'coaching\siteBundle\Entity\Training','property'=> 'type','preferred_choices'=>array($deja[0]->getTraining())));
$form = $formBuilder->getForm();
$request = $this->get('request');
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$deja[0]->setUser($temp);
//echo "<pre>".print_r($deja[0],true)."</pre>";
$em = $this->getDoctrine()->getManager();
$em->persist($deja[0]);
$em->flush();
}
}
return $this->render('coachingBundle:coaching:sportif_modif.html.twig', array('form'=> $form->createView()));
}
public function sportifSupprAction()
{
return $this->render('coachingBundle:coaching:sportif_suppr.html.twig', array());
}
}
| narbonneroland/coaching-express | src/coaching/siteBundle/Controller/CoachingController.php | PHP | mit | 7,103 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_60) on Thu Sep 17 00:14:27 EEST 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.commons.io.comparator</title>
<meta name="date" content="2015-09-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../org/apache/commons/io/comparator/package-summary.html" target="classFrame">org.apache.commons.io.comparator</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="CompositeFileComparator.html" title="class in org.apache.commons.io.comparator" target="classFrame">CompositeFileComparator</a></li>
<li><a href="DefaultFileComparator.html" title="class in org.apache.commons.io.comparator" target="classFrame">DefaultFileComparator</a></li>
<li><a href="DirectoryFileComparator.html" title="class in org.apache.commons.io.comparator" target="classFrame">DirectoryFileComparator</a></li>
<li><a href="ExtensionFileComparator.html" title="class in org.apache.commons.io.comparator" target="classFrame">ExtensionFileComparator</a></li>
<li><a href="LastModifiedFileComparator.html" title="class in org.apache.commons.io.comparator" target="classFrame">LastModifiedFileComparator</a></li>
<li><a href="NameFileComparator.html" title="class in org.apache.commons.io.comparator" target="classFrame">NameFileComparator</a></li>
<li><a href="PathFileComparator.html" title="class in org.apache.commons.io.comparator" target="classFrame">PathFileComparator</a></li>
<li><a href="SizeFileComparator.html" title="class in org.apache.commons.io.comparator" target="classFrame">SizeFileComparator</a></li>
</ul>
</div>
</body>
</html>
| pingzing/sonic-scream | libs/javadoc/org/apache/commons/io/comparator/package-frame.html | HTML | mit | 1,961 |
-- Path of Building
--
-- Class: Slider Control
-- Basic slider control.
--
local m_min = math.min
local m_max = math.max
local m_ceil = math.ceil
local SliderClass = newClass("SliderControl", "Control", "TooltipHost", function(self, anchor, x, y, width, height, changeFunc)
self.Control(anchor, x, y, width, height)
self.TooltipHost()
self.knobSize = height - 2
self.val = 0
self.changeFunc = changeFunc
end)
function SliderClass:IsMouseOver()
if not self:IsShown() then
return false
end
local x, y = self:GetPos()
local width, height = self:GetSize()
local cursorX, cursorY = GetCursorPos()
local mOver = cursorX >= x and cursorY >= y and cursorX < x + width and cursorY < y + height
local mOverComp
if mOver then
local relX = cursorX - x - 2
local knobX = self:GetKnobXForVal()
if relX >= knobX and relX < knobX + self.knobSize then
mOverComp = "KNOB"
else
mOverComp = "SLIDE"
end
end
return mOver, mOverComp
end
function SliderClass:GetKnobTravel()
local width, height = self:GetSize()
return width - self.knobSize - 2
end
function SliderClass:SetVal(newVal)
newVal = m_max(0, m_min(1, newVal))
if newVal ~= self.val then
self.val = newVal
if self.changeFunc then
self.changeFunc(self.val)
end
end
end
function SliderClass:GetDivVal(val)
val = val or self.val
if self.divCount and self.divCount > 1 then
local divIndex = m_max(m_ceil(val * self.divCount), 1)
return divIndex, val * self.divCount - divIndex + 1
else
return 1, val
end
end
function SliderClass:SetValFromKnobX(knobX)
self:SetVal(knobX / self:GetKnobTravel())
end
function SliderClass:GetKnobXForVal()
local knobTravel = self:GetKnobTravel()
return knobTravel * self.val
end
function SliderClass:Draw(viewPort)
local x, y = self:GetPos()
local width, height = self:GetSize()
local enabled = self:IsEnabled()
local knobTravel = self:GetKnobTravel()
if self.dragging and not IsKeyDown("LEFTBUTTON") then
self.dragging = false
end
if self.dragging then
local cursorX, cursorY = GetCursorPos()
self:SetValFromKnobX((cursorX - self.dragCX) + self.dragKnobX)
end
local mOver, mOverComp = self:IsMouseOver()
if not enabled then
SetDrawColor(0.33, 0.33, 0.33)
elseif self.dragging or mOver then
SetDrawColor(1, 1, 1)
else
SetDrawColor(0.5, 0.5, 0.5)
end
DrawImage(nil, x, y, width, height)
SetDrawColor(0, 0, 0)
DrawImage(nil, x + 1, y + 1, width - 2, height - 2)
if enabled then
if self.divCount then
SetDrawColor(0.33, 0.33, 0.33)
for d = 0, knobTravel + 0.5, knobTravel / self.divCount do
DrawImage(nil, x + self.knobSize/2 + d, y + 1, 2, height - 2)
end
end
if self.dragging or mOverComp == "KNOB" then
SetDrawColor(1, 1, 1)
else
SetDrawColor(0.5, 0.5, 0.5)
end
local knobX = self:GetKnobXForVal()
if self.divCount then
local arrowHeight = self.knobSize/2
main:DrawArrow(x + 1 + knobX + self.knobSize/2, y + height/2 - arrowHeight/2, self.knobSize, arrowHeight, "UP")
main:DrawArrow(x + 1 + knobX + self.knobSize/2, y + height/2 + arrowHeight/2, self.knobSize, arrowHeight, "DOWN")
else
DrawImage(nil, x + 2 + knobX, y + 2, self.knobSize - 2, self.knobSize - 2)
end
end
if enabled and (mOver or self.dragging) then
SetDrawLayer(nil, 100)
if self.dragging then
self:DrawTooltip(x, y, width, height, viewPort, self.val)
else
local cursorX, cursorY = GetCursorPos()
local val = (cursorX - x - 1 - self.knobSize / 2) / knobTravel
self:DrawTooltip(x, y, width, height, viewPort, m_max(0, m_min(1, val)))
end
SetDrawLayer(nil, 0)
end
end
function SliderClass:OnKeyDown(key)
if not self:IsShown() or not self:IsEnabled() then
return
end
if key == "LEFTBUTTON" then
local mOver, mOverComp = self:IsMouseOver()
if not mOver then
return
end
if not self.dragging then
self.dragging = true
local cursorX, cursorY = GetCursorPos()
self.dragCX = cursorX
if mOverComp == "SLIDE" then
local x, y = self:GetPos()
self:SetValFromKnobX(cursorX - x - 1 - self.knobSize / 2)
end
self.dragKnobX = self:GetKnobXForVal()
end
end
return self
end
function SliderClass:OnKeyUp(key)
if not self:IsShown() or not self:IsEnabled() then
return
end
if key == "LEFTBUTTON" then
if self.dragging then
self.dragging = false
local cursorX, cursorY = GetCursorPos()
self:SetValFromKnobX((cursorX - self.dragCX) + self.dragKnobX)
end
end
end
| Openarl/PathOfBuilding | Classes/SliderControl.lua | Lua | mit | 4,407 |
class Inspect::InputsController < Inspect::BaseController
layout 'application'
before_action :find_input, :only => [:show]
def index
@inputs = Input.all.sort_by(&:key)
end
def show
end
private
def find_input
@input = Input.get(params[:id]) || render_not_found('input')
end
end
| quintel/etengine | app/controllers/inspect/inputs_controller.rb | Ruby | mit | 308 |
/* eslint global-require:0 */
import path from 'path'
import {readFileSync} from 'fs'
function mockFindUpSync(packageJsonDestination) {
return file => {
if (file === 'package.json') {
return packageJsonDestination
}
throw new Error('Should not look for anything but package.json')
}
}
test('initialize JS normally', () => {
const packageScriptsDestination = fixture('package-scripts.js')
const packageJsonDestination = fixture('_package.json')
const expectedPackageScripts = readFileSync(
fixture('_package-scripts.js'),
'utf-8',
).replace(/\r?\n/g, '\n')
const mockWriteFileSync = jest.fn()
jest.resetModules()
jest.doMock('find-up', () => ({
sync: mockFindUpSync(packageJsonDestination),
}))
jest.mock('fs', () => ({writeFileSync: mockWriteFileSync}))
const initialize = require('../').default
initialize()
const [
[packageJsonDestinationResult, packageJsonStringResult],
[packageScriptsDestinationResult, packageScriptsStringResult],
] = mockWriteFileSync.mock.calls
const {scripts: packageJsonScripts} = JSON.parse(packageJsonStringResult)
expect(mockWriteFileSync).toHaveBeenCalledTimes(2)
expect(packageScriptsDestinationResult).toBe(packageScriptsDestination)
expect(packageScriptsStringResult).toBe(expectedPackageScripts)
expect(packageJsonDestinationResult).toBe(packageJsonDestination)
expect(packageJsonScripts).toEqual({
start: 'nps',
test: 'nps test',
})
})
test('initialize YML normally', () => {
const packageScriptsDestination = fixture('package-scripts.yml')
const packageJsonDestination = fixture('_package.json')
const expectedPackageScripts = readFileSync(
fixture('_package-scripts.yml'),
'utf-8',
).replace(/\r?\n/g, '\n')
const mockWriteFileSync = jest.fn()
jest.resetModules()
jest.doMock('find-up', () => ({
sync: mockFindUpSync(packageJsonDestination),
}))
jest.mock('fs', () => ({writeFileSync: mockWriteFileSync}))
const initialize = require('../').default
initialize('yml')
const [
[packageJsonDestinationResult, packageJsonStringResult],
[packageScriptsDestinationResult, packageScriptsStringResult],
] = mockWriteFileSync.mock.calls
const {scripts: packageJsonScripts} = JSON.parse(packageJsonStringResult)
expect(mockWriteFileSync).toHaveBeenCalledTimes(2)
expect(packageScriptsDestinationResult).toBe(packageScriptsDestination)
expect(packageScriptsStringResult).toBe(expectedPackageScripts)
expect(packageJsonDestinationResult).toBe(packageJsonDestination)
expect(packageJsonScripts).toEqual({
start: 'nps',
test: 'nps test',
})
})
test('initialize without a test script should not add a test to the package.json', () => {
const packageJsonDestination = fixture('_package-no-test.json')
const mockWriteFileSync = jest.fn()
jest.resetModules()
jest.doMock('find-up', () => ({
sync: mockFindUpSync(packageJsonDestination),
}))
jest.mock('fs', () => ({writeFileSync: mockWriteFileSync}))
const initialize = require('../').default
initialize()
const [[, packageJsonStringResult]] = mockWriteFileSync.mock.calls
const {scripts: packageJsonScripts} = JSON.parse(packageJsonStringResult)
expect(packageJsonScripts).toEqual({
start: 'nps',
})
})
test(`initialize without any scripts should successfully create an empty package-scripts.js file`, () => {
const packageJsonDestination = fixture('_package-no-scripts.json')
const mockWriteFileSync = jest.fn()
jest.resetModules()
jest.doMock('find-up', () => ({
sync: mockFindUpSync(packageJsonDestination),
}))
jest.mock('fs', () => ({writeFileSync: mockWriteFileSync}))
const initialize = require('../').default
initialize()
const [[, packageJsonStringResult]] = mockWriteFileSync.mock.calls
const {scripts: packageJsonScripts} = JSON.parse(packageJsonStringResult)
expect(packageJsonScripts).toEqual({
start: 'nps',
})
})
test('initialize without any core scripts and should not remove any core scripts from package.json', () => {
const packageJsonDestination = fixture('_package-core-scripts.json')
const mockWriteFileSync = jest.fn()
jest.resetModules()
jest.doMock('find-up', () => ({
sync: mockFindUpSync(packageJsonDestination),
}))
jest.mock('fs', () => ({writeFileSync: mockWriteFileSync}))
const initialize = require('../').default
initialize()
const [[, packageJsonStringResult]] = mockWriteFileSync.mock.calls
const {scripts: packageJsonScripts} = JSON.parse(packageJsonStringResult)
expect(packageJsonScripts).toEqual({
start: 'nps',
precommit: 'precommit hook',
postcommit: 'postcommit hook',
prepublish: 'prepublish hook',
preuninstall: 'preuninstall hook',
})
})
function fixture(name) {
return path.join(__dirname, 'fixtures', name)
}
| kentcdodds/p-s | src/bin-utils/initialize/__tests__/index.js | JavaScript | mit | 4,818 |
package com.studio4plus.homerplayer.events;
import com.studio4plus.homerplayer.model.LibraryContentType;
/**
* Posted when audio books are added or removed.
*/
public class AudioBooksChangedEvent {
public final LibraryContentType contentType;
public AudioBooksChangedEvent(LibraryContentType contentType) {
this.contentType = contentType;
}
}
| msimonides/homerplayer | app/src/main/java/com/studio4plus/homerplayer/events/AudioBooksChangedEvent.java | Java | mit | 369 |
package com.dieam.reactnativeconekta;
import com.dieam.reactnativeconekta.modules.RNConekta;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ReactNativeConektaPackage implements ReactPackage {
public ReactNativeConektaPackage() {}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new RNConekta(reactContext));
return modules;
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Arrays.asList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return new ArrayList<>();
}
}
| zo0r/react-native-conekta | android/src/main/java/com/dieam/reactnativeconekta/ReactNativeConektaPackage.java | Java | mit | 1,024 |
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>アニメペイント</title>
<link rel="stylesheet" href="main.css" type="text/css" media="all">
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="gif.js"></script>
<script type="text/javascript" src="draw.js"></script>
</head>
<body>
<canvas id="myCanvas" width="640" height="480">
HTML5 Canvasに対応したブラウザーを使用してください。
</canvas>
<div id="menu">
<button onclick="saveData()">保存</button>
<button onclick="saveAndAppend()">保存して追加</button>
<button onclick="clearCanvas()">全消し</button>
</div>
<div id="colorPalet">
<div id="black"></div>
<div id="blue"></div>
<div id="red"></div>
<div id="magenta"></div>
<div id="green"></div>
<div id="cyan"></div>
<div id="yellow"></div>
<div id="white"></div>
</div>
<div id="canvases">
</div>
<div id="canvases-tool">
<button onclick="getPrevCanvas()">上</button>
<button onclick="getNextCanvas()">下</button>
<button onclick="setNextCanvas()">追加</button>
<button onclick="deleteCurrentCanvas()">消去</button>
<button onclick="generateGIF()">GIF生成</button>
fps
<input id="fps" type="text" name="fps" size="5" maxlength="30">
秒
</div>
<div id="drop_zone">画像をここにドラッグして追加</div>
</body>
</html>
| gmcgsokdeuvmt/animepaint | index.html | HTML | mit | 1,618 |
\subsection{Discussion}
The quantative and qualitative data from iteration 2 shows that the app works for "validating the coaches' level of knowledge during their education", which was the main purpose of the master thesis (see section \ref{sec:research-questions}. Now, the app should be tested in Uganda as well, and there can be an increased focus on "distance training" and "certify all staff".
Iteration 2 has translated the theoretical understanding of answering research question 1, 2, 3 and 5 into practical experience. Now there are observable evidence for what the interactions from Iteration 1 showed:
\begin{itemize}
\item The purpose of the coach training should be to prepare the coach in having great youth sessions
\item Therefore, this is what the quizzes should assess
\item What it really means being a good YoungDrive coach, is having good youth sessions
\end{itemize}
\subsubsection{Validating the coaches' level of knowledge}
The quiz results data shows that a lecture is still currently more valuable than taking a quiz in the app two times to improve (15.0\% to 12.8\%). For iteration 2, work on answering research question 4 has started. While the teacher has appreciated the multiple-choice assessment, challenges of designing test questions to support entrepreneurial learning has been found. It is clear that the app is valuable for assessment, increasing coach self-awareness and being a valuable indicator for the teacher. However, the questions formulated scores low on Bloom's Revised Taxonomy \citep{krathwohl} compared with YoungDrive's educational objectives for the topics.
There are previously found issues with using multiple-choice for assessment and learning, but they seem to become especially relevant in the context of teaching entrepreneurship.
Either question formulation needs to be improved, or creative design solutions needs to be experimented with which can increase coach understanding and identify and reduce guessing. This needs to be further investigated for iteration 3.
Test with university student scored 100\% correct, means that common sense can go a long way, and that the results can't be 100\% trustworthy, and that multiple-choice questions has serious issues - this, we already knew during and before the coach training - but it needs to be taken care of. Similarly business and leadership experience for the coach seems to lead to a higher quiz average, while a low quiz average can't seem to be connected to any of the coach characteristics found during the interviews. This makes it hard to design the app for different types of coaches, without testing other parameters, which should be done in iteration 4 for the summative test.
\subsubsection{Distance Learning}
In addition to the formative app tests, workshop \# 2 heavily informs what is necessary when designing for use case 2, distance learning: preparing a session in regards to building confidence. The results from the workshop are somewhat surprising, factors not only those that relate to the four parameters from iteration 1 ("I am well prepared" and "I believe in myself"), but for some also "I believe in God" or "I am certified" (which relates to purpose 3 of the app). These should be considered for iteration 3.
Further, app tests expose how the app is currently not actively designed with learning in mind, and thus not distance learning. This is unfortunate, both because distance learning is important, and as the app test with refugee innovators shows that there is an opportunity doing entrepreneurship training in rural areas outside of YoungDrive's coverage area. In order for online coach-training to work for distance learning, learning and feedback, and not only assessment, is however essential.
While it may be technically possible, the teacher desires the app support her during the coach training, not replace her. Therefore, completely replacing the teacher with an app should be avoided. The teacher is very important for giving coaching and educating in a way that the app can't. But the teacher can also be empowered by the app. For the future, Josefina would have liked to be able to stop coaches from having taught, if they do not have 90-100 \% correct information on the subject. Today, Josefina can not assess this. This means that some coaches, are teaching incorrect information to hundreds of youth. Here, the quiz has a very good need to fill.
If wrong on an answer, the app today has no means of giving high pay-off tips to get to 100\%, or exposing you to deliberate practice or perceptual exposure. If the coach gets 9/10 correct answers reliably, or gets 5/10 answers with guesses, the coach still needs to retake all answers, not having learned the correct answer before taking the quiz again.
How to develop the app to solve these issues, is not obvious. Multiple strategies could and should be used. The app could benefit from introducing smart feedback encouraging a growth mindset ("You did not get 100\% \textit{yet}") \cite{dweck}.
\subsection{Next Iteration}
After the meeting with the partner and expert group, the following was concluded from iteration \#2:
\begin{itemize}
\item The app is partly working on assessment now, but not for learning. Are coaches really learning via the app, especially learning to be better coaches?
\begin{itemize}
\item Multiple-choice is flawed in its current form. How can guesses be identified and reduced in a multiple-choice format? How can answering questions improve confidence and encourage learning?
\item How can questions be formulated in a way that teaches entrepreneurship, which is so practical?
\end{itemize}
\item The need for a field app still feels relevant (especially for sessions long since the coach training)
\begin{itemize}
\item An app could be used, either before you start planning (to guide what you need to study the most on), or after you think you are ready (so you can assess and improve).
\item When designing the app, it is concluded that an app for coach training, and an app to use before a youth session, should be able to be the same app if possible, since the purpose of preparing the coach to be great with its youth session is the same.
\item Discussing the importance of self-reflection after a youth session with Josefina, led to asking more of such questions in coach quizzes. While Fun Atmosphere can be hard to assess using multiple-choice, can Correct Structure and Time Management be assessed?
\end{itemize}
\end{itemize}
After the partner and expert meeting, it was decided that the following needs to be done for iteration 3:
\begin{itemize}
\item Make sure that the coach actually learns the desired educational objectives
\begin{itemize}
\item Create a new quiz guided by Josefina, "Are you ready for Session 9?", also to test if Correct Structure and Time Management could be assessed using multiple-choice
\item See if design additions to multiple-choice can increase learning in-line with Bloom's revised taxonomy
\end{itemize}
\item Design quiz app for learning, focus on field app, and have a design that works stand-alone from the YoungDrive coach training in mind.
\begin{itemize}
\item Investigate the effect of giving growth mindset feedback in the app (The Power of Yet approach)
\end{itemize}
\item Test if the app created in Zambia could work also in Uganda
\begin{itemize}
\item This also means converting all the questions from the new (Zambia) manual to the old (Uganda) manual, since both structure and content of the manuals has changed.
\end{itemize}
\end{itemize}
| marcusnygren/YoungDriveMasterThesis | result/iteration2/iteration_2_together.tex | TeX | mit | 7,628 |
class UsersController < ApplicationController
load_and_authorize_resource
def show
@activities = PublicActivity::Activity.all.reverse
end
end
| rememberlenny/harlemreport | app/controllers/users_controller.rb | Ruby | mit | 153 |
n, m = map(int,input().split())
# List Comprehension for pattern
pattern = [('.|.'*(2*i + 1)).center(m, '-') for i in range(n//2)]
# List Comprehension for print out
print('\n'.join(pattern + ['WELCOME'.center(m, '-')] + pattern[::-1]))
| bluewitch/Code-Blue-Python | HR_pythonDesignerDoorMat.py | Python | mit | 238 |
<!-- http://www.w3.org/TR/offline-webapps/ -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang=en-US>
<head>
<title>Offline Web Applications</title>
<style type="text/css">
code { color:orangered }
</style>
<link href="http://www.w3.org/StyleSheets/TR/W3C-WG-NOTE" rel=stylesheet>
<body>
<div class=head>
<p><a href="http://www.w3.org/"><img alt=W3C height=48
src="http://www.w3.org/Icons/w3c_home" width=72></a></p>
<h1 id=offline-webapps>Offline Web Applications</h1>
<h2 class="no-num no-toc" id=w3c-doctype>W3C Working Group Note 30 May 2008</h2>
<dl>
<dt>This Version:
<dd><a
href="http://www.w3.org/TR/2008/NOTE-offline-webapps-20080530/">http://www.w3.org/TR/2008/NOTE-offline-webapps-20080530/</a>
<dt>Latest Version:
<dd><a
href="http://www.w3.org/TR/offline-webapps/">http://www.w3.org/TR/offline-webapps/</a>
<dt>Editors:
<dd><a href="http://annevankesteren.nl/">Anne van Kesteren</a> (<a
href="http://www.opera.com/">Opera Software ASA</a>) <<a
href="mailto:[email protected]">[email protected]</a>>
<dd><a href="mailto:[email protected]">Ian Hickson</a>, Google, Inc.
</dl>
<p class=copyright><a
href="http://www.w3.org/Consortium/Legal/ipr-notice#Copyright">Copyright</a>
© 2008 <a href="http://www.w3.org/"><abbr title="World Wide Web
Consortium">W3C</abbr></a><sup>®</sup> (<a
href="http://www.csail.mit.edu/"><abbr title="Massachusetts Institute of
Technology">MIT</abbr></a>, <a href="http://www.ercim.org/"><abbr
title="European Research Consortium for Informatics and
Mathematics">ERCIM</abbr></a>, <a
href="http://www.keio.ac.jp/">Keio</a>), All Rights Reserved. W3C <a
href="http://www.w3.org/Consortium/Legal/ipr-notice#Legal_Disclaimer">liability</a>,
<a
href="http://www.w3.org/Consortium/Legal/ipr-notice#W3C_Trademarks">trademark</a>
and <a
href="http://www.w3.org/Consortium/Legal/copyright-documents">document
use</a> rules apply.</p>
</div>
<hr>
<h2 class="no-num no-toc" id=abstract>Abstract</h2>
<p>HTML 5 contains several features that address the challenge of
building Web applications that work while offline. This document
highlights these features (SQL, offline application caching APIs as well
as <code>online</code>/<code>offline</code> events, status, and the
<code>localStorage</code> API) from HTML 5 and provides brief
tutorials on how these features might be used to create Web applications
that work offline. [<cite><a href="#ref-html5">HTML5</a></cite>]
<h2 class="no-num no-toc" id=sotd>Status of This Document</h2>
<p><em>This section describes the status of this document at the time of
its publication. Other documents may supersede this document. A list of
current W3C publications and the latest revision of this technical report
can be found in the <a href="http://www.w3.org/TR/">W3C technical reports
index</a> at http://www.w3.org/TR/.</em>
<p>Offline Web Applications is a Working Group Note produced by the <a
href="http://www.w3.org/html/wg/">HTML Working Group</a>, part of the <a
href="http://www.w3.org/MarkUp/Activity">HTML Activity</a>. Comments are
welcome on the <a
href="mailto:[email protected]">[email protected]</a>
mailing list which is <a
href="http://lists.w3.org/Archives/Public/public-html-comments/">publicly
archived</a>.
<p>Publication as a Working Group Note does not imply endorsement by the
W3C Membership. This is a draft document and may be updated, replaced or
obsoleted by other documents at any time. It is inappropriate to cite this
document as other than work in progress.
<p>This document was produced by a group operating under the <a
href="http://www.w3.org/Consortium/Patent-Policy-20040205/">5 February
2004 W3C Patent Policy</a>. The group does not expect this document to
become a W3C Recommendation. W3C maintains a <a
href="http://www.w3.org/2004/01/pp-impl/40318/status"
rel=disclosure>public list of any patent disclosures</a> made in
connection with the deliverables of the group; that page also includes
instructions for disclosing a patent. An individual who has actual
knowledge of a patent which the individual believes contains <a
href="http://www.w3.org/Consortium/Patent-Policy-20040205/#def-essential">Essential
Claim(s)</a> must disclose the information in accordance with <a
href="http://www.w3.org/Consortium/Patent-Policy-20040205/#sec-Disclosure">section
6 of the W3C Patent Policy</a>.
<h2 class="no-num no-toc" id=toc>Table of Contents</h2>
<!--begin-toc-->
<ul class=toc>
<li><a href="#introduction"><span class=secno>1. </span>Introduction</a>
<li><a href="#sql"><span class=secno>2. </span>SQL</a>
<li><a href="#offline"><span class=secno>3. </span>Offline Application
Caching APIs</a>
<li><a href="#related"><span class=secno>4. </span>Related APIs</a>
<li class=no-num><a href="#references">References</a>
<li class=no-num><a href="#acknowledgments">Acknowledgments</a>
</ul>
<!--end-toc-->
<h2 id=introduction><span class=secno>1. </span>Introduction</h2>
<p>Users of typical online Web applications are only able to use the
applications while they have a connection to the Internet. When they go
offline, they can no longer check their e-mail, browse their calendar
appointments, or prepare presentations with their online tools. Meanwhile,
native applications provide those features: e-mail clients cache folders
locally, calendars store their events locally, presentation packages store
their data files locally.
<p>In addition, while offline, users are dependent on their HTTP cache to
obtain the application at all, since they cannot contact the server to get
the latest copy.
<p>The HTML 5 specification provides two solutions to this: a <a
href="http://www.w3.org/html/wg/html5/#sql">SQL-based database API</a> for
storing data locally, and an <a
href="http://www.w3.org/html/wg/html5/#offline">offline application HTTP
cache</a> for ensuring applications are available even when the user is
not connected to their network.
<h2 id=sql><span class=secno>2. </span>SQL</h2>
<p>The client-side SQL database in HTML 5 enables structured data
storage. This can be used to store e-mails locally for an e-mail
application or for a cart in an online shopping site. The API to interact
with this database is asynchronous which ensures that the user interface
doesn't lock up. Because database interaction can occur in multiple
browser windows at the same time the API supports transactions.
<p>To create a database object you use the <code>openDatabase()</code>
method on the <code>Window</code> object. It takes four arguments: a
database name, a database version, a display name, and an estimated size,
in bytes, of the data to be stored in the database. For instance:
<pre>var db = openDatabase("notes", "", "The Example Notes App!", 1048576);</pre>
<p>Now on this database we can use the <code>transaction()</code> method.
The transaction method takes one to three arguments: a transaction
callback, an error callback, and a success callback. The transaction
callback gets passed a SQL transaction object on which you can use the
<code>executeSQL()</code> method. This method takes from one to four
arguments: a SQL statement, arguments, a SQL statement callback, and a SQL
statement error callback. The SQL statement callback gets passed the
transaction object and a SQL statement result object which gives access to
the rows, last inserted ID, et cetera.
<p>To complete the infrastructure for the notes application we'd add the
following code:
<pre>
function renderNote(row) {
// renders the note somewhere
}
function reportError(source, message) {
// report error
}
function renderNotes() {
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)',
[]);
tx.executeSql(‘SELECT * FROM Notes’, [], function(tx, rs) {
for(var i = 0; i < rs.rows.length; i++) {
renderNote(rs.rows[i]);
}
});
});
}
function insertNote(title, text) {
db.transaction(function(tx) {
tx.executeSql('INSERT INTO Notes VALUES(?, ?)', [ title, text ],
function(tx, rs) {
// …
},
function(tx, error) {
reportError('sql', error.message);
});
});
}</pre>
<h2 id=offline><span class=secno>3. </span>Offline Application Caching APIs</h2>
<p>The mechanism for ensuring Web applications are available even when the
user is not connected to their network is the <code
title=attr-html-manifest>manifest</code> attribute on the
<code>html</code> element.
<p>The attribute takes a URI to a manifest, which specifies which files are
to be cached. The manifest has a <code>text/cache-manifest</code> MIME
type. A typical file looks like this:
<pre>CACHE MANIFEST
index.html
help.html
style/default.css
images/logo.png
images/backgound.png
NETWORK:
server.cgi</pre>
<p>This file specifies several files to cache, and then specifies that
<code title="">server.cgi</code> should never be cached, so that any
attempt to access that file will bypass the cache.
<p>The manifest can then be linked to by declaring it in the (HTML)
application, like this:
<pre><!DOCTYPE HTML>
<html manifest="cache-manifest">
...</pre>
<p>The <code title="">server.cgi</code> file would be white-listed (put in
the <code title="">NETWORK:</code> section) so that it can be contacted to
get updates from the server, as in:
<pre><event-source src="server.cgi"></pre>
<p>(The <code>event-source</code> element is a new feature in HTML 5
that allows servers to continuously stream updates to a Web page.)
<p>The application cache mechanism also supports a way to opportunistically
cache (from the server) a group of files matching a common prefix, with
the ability to have a fallback page for rendering those pages when
offline. It also provides a way for scripts to add and remove entries from
the cache dynamically, and a way for applications to atomically update
their cache to new files, optionally presenting custom UI during the
update.
<h2 id=related><span class=secno>4. </span>Related APIs</h2>
<p>In addition to those APIs HTML 5 also defines an
<code>onLine</code> attribute on the <code>Navigator</code> object so you
can determine whether you are currently online:
<pre>var online = navigator.onLine;</pre>
<p>Changes to this attribute are indicated through the <code>online</code>
and <code>offline</code> events that are both dispatched on the
<code>Window</code> object.
<p>For simple synchronous storage access HTML 5 introduces the
<code>localStorage</code> attribute on the <code>Window</code> object:
<pre>localStorage["status"] = "Idling.";</pre>
<h2 class=no-num id=references>References</h2>
<dl>
<dt>[<dfn id=ref-html5>HTML5</dfn>] (work in progress)
<dd><cite><a
href="http://www.whatwg.org/specs/web-apps/current-work/">HTML 5</a></cite>,
I. Hickson, editor. WHATWG, 2008.
<dd><cite><a
href="http://www.whatwg.org/specs/web-forms/current-work/">Web Forms
2.0</a></cite>, I. Hickson, editor. WHATWG, October 2006.
<dd><cite><a
href="http://www.w3.org/html/wg/html5/">HTML 5</a></cite>, I.
Hickson, D. Hyatt, editors. W3C, 2008.
<dd><cite><a href="http://dev.w3.org/html5/web-forms-2/">Web Forms
2.0</a></cite>, I. Hickson, editor. W3C, October 2006.
</dl>
<h2 class=no-num id=acknowledgments>Acknowledgments</h2>
<p>The editors would like to thank Chris Wilson, Dion Almaer, James Graham,
Julian Reschke, Henri Sivonen, Patrick D. F. Ion, and Philip Taylor for
their contributions to this document. Also thanks to Dan Connolly for
talking us into writing it during the first HTML WG meeting (in Boston).
| azu/reference-promises-spec | _downloads/www.w3.org_tr_offline_webapps_.html | HTML | mit | 12,159 |
package net.devslash.easyauth.authflows;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AppEventsLogger;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import net.devslash.easyauth.AuthenticationCallbacks;
import net.devslash.easyauth.providers.FacebookProfileProvider;
import net.devslash.easyauth.providers.ProfileCallback;
import net.devslash.easyauth.providers.ProfileProvider;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Paul on 12/02/2015.
*/
public class FacebookAuthenticator {
private final String TAG = "FacebookReceiver";
private final Activity mActivity;
private final Set<AuthenticationCallbacks> mAuthCallbacks = new HashSet<>();
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState sessionState, Exception e) {
onSessionStateChange(session, sessionState, e);
}
};
public FacebookAuthenticator(Activity activity) {
uiHelper = new UiLifecycleHelper(activity, callback);
mActivity = activity;
}
private void onSessionStateChange(final Session session, SessionState sessionState, Exception exception) {
Log.i(TAG, "Logged about to come up");
if (sessionState.isOpened()) {
Log.i(TAG, "Logged in...");
FacebookProfileProvider.GenerateFacebookProvider(mActivity, session, new ProfileCallback() {
@Override
public void onReady(ProfileProvider instance) {
onLogin(instance);
}
@Override
public void fail(String s) {
onLogout();
}
});
} else if (sessionState.isClosed()) {
Log.i(TAG, "Logged out...");
onLogout();
}
}
private void onLogin(ProfileProvider instance) {
for (AuthenticationCallbacks callbacks : mAuthCallbacks) {
callbacks.onLogin(instance);
}
}
/* Below this line is fairly boiler plate stuff */
private void onLogout() {
for (AuthenticationCallbacks callbacks : mAuthCallbacks) {
callbacks.onLogout();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
uiHelper.onActivityResult(requestCode, resultCode, data);
}
public void onCreate(Bundle savedInstanceState) {
uiHelper.onCreate(savedInstanceState);
AppEventsLogger.activateApp(mActivity);
}
public void onDestroy() {
uiHelper.onDestroy();
}
public void onPause() {
uiHelper.onPause();
AppEventsLogger.deactivateApp(mActivity);
}
public void onResume() {
uiHelper.onResume();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
}
public void onSaveInstanceState(Bundle outState) {
uiHelper.onSaveInstanceState(outState);
}
public void onStop() {
uiHelper.onStop();
}
public void registerAuthenticatedCallback(AuthenticationCallbacks authenticationProvider) {
// If it's not been added then add it
mAuthCallbacks.add(authenticationProvider);
}
public void doLogout(boolean invalidateTokens) {
Session session = Session.getActiveSession();
if (session.isOpened()) {
if (invalidateTokens) {
session.closeAndClearTokenInformation();
} else {
session.close();
}
onLogout();
}
}
}
| paulthom12345/easy-auth | app/src/main/java/net/devslash/easyauth/authflows/FacebookAuthenticator.java | Java | mit | 3,921 |
<!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>V8 API Reference Guide for node.js v0.3.3: Class Members - Functions</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">V8 API Reference Guide for node.js v0.3.3
</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 Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</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><a href="examples.html"><span>Examples</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 List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li class="current"><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li><a href="functions.html"><span>All</span></a></li>
<li class="current"><a href="functions_func.html"><span>Functions</span></a></li>
<li><a href="functions_vars.html"><span>Variables</span></a></li>
<li><a href="functions_type.html"><span>Typedefs</span></a></li>
<li><a href="functions_enum.html"><span>Enumerations</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="functions_func.html#index_a"><span>a</span></a></li>
<li><a href="functions_func_c.html#index_c"><span>c</span></a></li>
<li><a href="functions_func_d.html#index_d"><span>d</span></a></li>
<li><a href="functions_func_e.html#index_e"><span>e</span></a></li>
<li><a href="functions_func_f.html#index_f"><span>f</span></a></li>
<li><a href="functions_func_g.html#index_g"><span>g</span></a></li>
<li class="current"><a href="functions_func_h.html#index_h"><span>h</span></a></li>
<li><a href="functions_func_i.html#index_i"><span>i</span></a></li>
<li><a href="functions_func_l.html#index_l"><span>l</span></a></li>
<li><a href="functions_func_m.html#index_m"><span>m</span></a></li>
<li><a href="functions_func_n.html#index_n"><span>n</span></a></li>
<li><a href="functions_func_o.html#index_o"><span>o</span></a></li>
<li><a href="functions_func_p.html#index_p"><span>p</span></a></li>
<li><a href="functions_func_r.html#index_r"><span>r</span></a></li>
<li><a href="functions_func_s.html#index_s"><span>s</span></a></li>
<li><a href="functions_func_t.html#index_t"><span>t</span></a></li>
<li><a href="functions_func_u.html#index_u"><span>u</span></a></li>
<li><a href="functions_func_w.html#index_w"><span>w</span></a></li>
<li><a href="functions_func_~.html#index_~"><span>~</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- 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 class="contents">
 
<h3><a class="anchor" id="index_h"></a>- h -</h3><ul>
<li>Handle()
: <a class="el" href="classv8_1_1_handle.html#aa7543a3d572565806a66e922634cc2f4">v8::Handle< T ></a>
</li>
<li>HasCaught()
: <a class="el" href="classv8_1_1_try_catch.html#a48f704fbf2b82564b5d2a4ff596e4137">v8::TryCatch</a>
</li>
<li>HasError()
: <a class="el" href="classv8_1_1_script_data.html#ab5cea77b299b7dd73b7024fb114fd7e4">v8::ScriptData</a>
</li>
<li>HasIndexedLookupInterceptor()
: <a class="el" href="classv8_1_1_object.html#afd36ea440a254335bde065a4ceafffb3">v8::Object</a>
</li>
<li>HasInstance()
: <a class="el" href="classv8_1_1_function_template.html#aa883e4ab6643498662f7873506098c98">v8::FunctionTemplate</a>
</li>
<li>HasNamedLookupInterceptor()
: <a class="el" href="classv8_1_1_object.html#ad0791109068a7816d65a06bbc9f6f870">v8::Object</a>
</li>
<li>HasOutOfMemoryException()
: <a class="el" href="classv8_1_1_context.html#aadec400a5da1e79e58a8770fd706b9a0">v8::Context</a>
</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Aug 11 2015 23:46:45 for V8 API Reference Guide for node.js v0.3.3 by  <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>
| v8-dox/v8-dox.github.io | 1a894b3/html/functions_func_h.html | HTML | mit | 6,883 |
<template>
<div class="component component-snackbar">
Snackbars provide brief feedback about an operation through a message.
<section>
<h2>basic</h2>
<button ssv-button="primary"
click.trigger="showBasic()">show snackbar!
</button>
<button ssv-button="primary"
click.delegate="showWithAction()">show with action!
</button>
</section>
<section>
<h2>api</h2>
<button ssv-button="primary"
click.trigger="dismissCurrent()">
dismiss current
</button>
<button ssv-button="primary"
click.trigger="dismissAll()">
dismiss all
</button>
</section>
<section class="snackbar-references">
<h2>references</h2>
<div repeat.for="item of items"
class="snackbar-references-item ${item === activeItem ? 'snackbar-references-item--active' : ''}">
<div class="message">
${item.message}
<ssv-badge color="info">${item.options.duration}</ssv-badge>
</div>
<button ssv-button="danger"
click.delegate="item.dismiss()">
dismiss
</button>
</div>
<p if.bind="!items.length">
No items added.
</p>
</section>
</div>
</template> | sketch7/ssv-au-ui-dojo | src/app/areas/components/snackbar/snackbar.html | HTML | mit | 1,129 |
#!/bin/sh -e
if [ "${1}" = --help ]; then
echo "Usage: ${0} [--ci-mode]"
exit 0
fi
CONCERN_FOUND=false
CONTINUOUS_INTEGRATION_MODE=false
if [ "${1}" = --ci-mode ]; then
shift
mkdir -p build/log
CONTINUOUS_INTEGRATION_MODE=true
fi
MARKDOWN_FILES=$(find . -name '*.md')
BLACKLIST=""
DICTIONARY=en_US
for FILE in ${MARKDOWN_FILES}; do
WORDS=$(hunspell -d "${DICTIONARY}" -p documentation/dictionary/debian-tools.dic -l "${FILE}" | sort | uniq)
if [ ! "${WORDS}" = "" ]; then
echo "${FILE}"
for WORD in ${WORDS}; do
BLACKLISTED=$(echo "${BLACKLIST}" | grep "${WORD}") || BLACKLISTED=false
if [ "${BLACKLISTED}" = false ]; then
if [ "${CONTINUOUS_INTEGRATION_MODE}" = true ]; then
grep --line-number "${WORD}" "${FILE}"
else
# The equals character is required.
grep --line-number --color=always "${WORD}" "${FILE}"
fi
else
echo "Blacklisted word: ${WORD}"
fi
done
echo
fi
done
TEX_FILES=$(find . -name '*.tex')
for FILE in ${TEX_FILES}; do
WORDS=$(hunspell -d "${DICTIONARY}" -p documentation/dictionary/debian-tools.dic -l -t "${FILE}")
if [ ! "${WORDS}" = "" ]; then
echo "${FILE}"
for WORD in ${WORDS}; do
STARTS_WITH_DASH=$(echo "${WORD}" | grep -q '^-') || STARTS_WITH_DASH=false
if [ "${STARTS_WITH_DASH}" = false ]; then
BLACKLISTED=$(echo "${BLACKLIST}" | grep "${WORD}") || BLACKLISTED=false
if [ "${BLACKLISTED}" = false ]; then
if [ "${CONTINUOUS_INTEGRATION_MODE}" = true ]; then
grep --line-number "${WORD}" "${FILE}"
else
# The equals character is required.
grep --line-number --color=always "${WORD}" "${FILE}"
fi
else
echo "Skip blacklisted: ${WORD}"
fi
else
echo "Skip invalid: ${WORD}"
fi
done
echo
fi
done
SYSTEM=$(uname)
if [ "${SYSTEM}" = Darwin ]; then
FIND='gfind'
else
FIND='find'
fi
INCLUDE_FILTER='^.*(\/bin\/[a-z]*|\.py)$'
EXCLUDE_FILTER='^.*\/(build|tmp|\.git|\.vagrant|\.idea|\.venv|\.tox)\/.*$'
if [ "${CONTINUOUS_INTEGRATION_MODE}" = true ]; then
FILES=$(${FIND} . -name '*.sh' -regextype posix-extended ! -regex "${EXCLUDE_FILTER}" -printf '%P\n')
for FILE in ${FILES}; do
FILE_REPLACED=$(echo "${FILE}" | sed 's/\//-/g')
shellcheck --format checkstyle "${FILE}" > "build/log/checkstyle-${FILE_REPLACED}.xml" || true
done
else
# shellcheck disable=SC2016
SHELL_SCRIPT_CONCERNS=$(${FIND} . -name '*.sh' -regextype posix-extended ! -regex "${EXCLUDE_FILTER}" -exec sh -c 'shellcheck ${1} || true' '_' '{}' \;)
if [ ! "${SHELL_SCRIPT_CONCERNS}" = "" ]; then
CONCERN_FOUND=true
echo "(WARNING) Shell script concerns:"
echo "${SHELL_SCRIPT_CONCERNS}"
fi
fi
EXCLUDE_FILTER_WITH_INIT='^.*\/((build|tmp|\.git|\.vagrant|\.idea|\.venv|\.tox)\/.*|__init__\.py)$'
# shellcheck disable=SC2016
EMPTY_FILES=$(${FIND} . -empty -regextype posix-extended ! -regex "${EXCLUDE_FILTER_WITH_INIT}")
if [ ! "${EMPTY_FILES}" = "" ]; then
CONCERN_FOUND=true
if [ "${CONTINUOUS_INTEGRATION_MODE}" = true ]; then
echo "${EMPTY_FILES}" > build/log/empty-files.txt
else
echo
echo "(WARNING) Empty files:"
echo
echo "${EMPTY_FILES}"
fi
fi
# shellcheck disable=SC2016
TO_DOS=$(${FIND} . -regextype posix-extended -type f -and ! -regex "${EXCLUDE_FILTER}" -exec sh -c 'grep -Hrn TODO "${1}" | grep -v "${2}"' '_' '{}' '${0}' \;)
if [ ! "${TO_DOS}" = "" ]; then
if [ "${CONTINUOUS_INTEGRATION_MODE}" = true ]; then
echo "${TO_DOS}" > build/log/to-dos.txt
else
echo
echo "(NOTICE) To dos:"
echo
echo "${TO_DOS}"
fi
fi
# shellcheck disable=SC2016
SHELLCHECK_IGNORES=$(${FIND} . -regextype posix-extended -type f -and ! -regex "${EXCLUDE_FILTER}" -exec sh -c 'grep -Hrn "# shellcheck" "${1}" | grep -v "${2}"' '_' '{}' '${0}' \;)
if [ ! "${SHELLCHECK_IGNORES}" = "" ]; then
if [ "${CONTINUOUS_INTEGRATION_MODE}" = true ]; then
echo "${SHELLCHECK_IGNORES}" > build/log/shellcheck-ignores.txt
else
echo
echo "(NOTICE) Shellcheck ignores:"
echo
echo "${SHELLCHECK_IGNORES}"
fi
fi
PYCODESTYLE_CONCERNS=$(pycodestyle --exclude=.git,.tox,.venv,__pycache__ --statistics .) || RETURN_CODE=$?
if [ "${CONTINUOUS_INTEGRATION_MODE}" = true ]; then
echo "${PYCODESTYLE_CONCERNS}" > build/log/pycodestyle.txt
else
if [ ! "${PYCODESTYLE_CONCERNS}" = "" ]; then
CONCERN_FOUND=true
echo
echo "(WARNING) PEP8 concerns:"
echo
echo "${PYCODESTYLE_CONCERNS}"
fi
fi
PYTHON_FILES=$(${FIND} . -type f -regextype posix-extended -regex "${INCLUDE_FILTER}" -and ! -regex "${EXCLUDE_FILTER}")
RETURN_CODE=0
# shellcheck disable=SC2086
PYLINT_OUTPUT=$(pylint ${PYTHON_FILES}) || RETURN_CODE=$?
SYSTEM=$(uname)
if [ "${SYSTEM}" = Darwin ]; then
TEE='gtee'
else
TEE='tee'
fi
if [ "${CONTINUOUS_INTEGRATION_MODE}" = true ]; then
echo | "${TEE}" build/log/pylint.txt
echo "(NOTICE) Pylint" | "${TEE}" --append build/log/pylint.txt
echo "${PYLINT_OUTPUT}" | "${TEE}" --append build/log/pylint.txt
else
echo
echo "(NOTICE) Pylint"
echo "${PYLINT_OUTPUT}"
fi
if [ ! "${RETURN_CODE}" = 0 ]; then
echo "Pylint return code: ${RETURN_CODE}"
fi
if [ "${CONCERN_FOUND}" = true ]; then
echo
echo "Concern(s) of category WARNING found." >&2
exit 2
fi
| FunTimeCoding/debian-tools | script/check.sh | Shell | mit | 5,833 |
#!/bin/bash
# need.reboot.sh
# A script to check whether reboot is required
# Copied from http://askubuntu.com/questions/164/how-can-i-tell-from-the-command-line-whether-the-machine-requires-a-reboot
if [ -f /var/run/reboot-required ]; then
echo 'Reboot required'
else
echo 'No reboot required'
fi
| evanchiu/dotfiles | bin/need.reboot.sh | Shell | mit | 310 |
<?php
/**
* This file is part of the Cubiche/Metadata component.
*
* Copyright (c) Cubiche
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cubiche\Core\Metadata\Tests\Units\Driver;
use Cubiche\Core\Metadata\ClassMetadata;
use Cubiche\Core\Metadata\Driver\MergeableDriver;
use Cubiche\Core\Metadata\Locator\DefaultFileLocator;
use Cubiche\Core\Metadata\Tests\Fixtures\Driver\XmlDriver;
use Cubiche\Core\Metadata\Tests\Fixtures\Driver\YamlDriver;
use Cubiche\Core\Metadata\Tests\Fixtures\User;
/**
* MergeableDriverTests class.
*
* Generated by TestGenerator on 2017-05-16 at 13:17:21.
*/
class MergeableDriverTests extends DriverTestCase
{
/**
* @return MergeableDriver
*/
protected function createDriver()
{
$mappingDirectory = __DIR__.'/../../Fixtures/mapping';
$ymlDriver = new YamlDriver(
new DefaultFileLocator([$mappingDirectory => 'Cubiche\Core\Metadata\Tests\Fixtures'])
);
$xmlDriver = new XmlDriver(
new DefaultFileLocator([$mappingDirectory => 'Cubiche\Core\Metadata\Tests'])
);
return new MergeableDriver([$ymlDriver, $xmlDriver]);
}
/**
* Test loadMetadataForClass method.
*/
public function testLoadMetadataForClass()
{
$this
->given($driver = $this->createDriver())
->then()
->variable($driver->loadMetadataForClass('Cubiche\Core\Metadata\Tests\Fixtures\Post'))
->isNull()
->variable($driver->loadMetadataForClass('Cubiche\Core\Metadata\Tests\Fixtures\Blog'))
->isNull()
;
$this
->given($driver = $this->createDriver())
->when($classMetadata = $driver->loadMetadataForClass(User::class))
->then()
->object($classMetadata)
->isInstanceOf(ClassMetadata::class)
->array($classMetadata->propertiesMetadata())
->hasSize(7)
->hasKey('id')
->hasKey('name')
->hasKey('username')
->hasKey('age')
->hasKey('email')
->hasKey('addresses')
->hasKey('friends')
->object($propertyMetadata = $classMetadata->propertyMetadata('id'))
->isNotNull()
->boolean($propertyMetadata->getMetadata('identifier'))
->isTrue()
->string($propertyMetadata->getMetadata('name'))
->isEqualTo('_id')
->string($classMetadata->propertyMetadata('name')->getMetadata('name'))
->isEqualTo('fullName')
->string($classMetadata->propertyMetadata('addresses')->getMetadata('type'))
->isEqualTo('ArraySet')
->string($classMetadata->propertyMetadata('addresses')->getMetadata('of'))
->isEqualTo('Cubiche\Core\Metadata\Tests\Fixtures\Address')
->and()
->when($classMetadata = $driver->loadMetadataForClass(User::class))
->then()
->object($classMetadata)
->isInstanceOf(ClassMetadata::class)
;
}
}
| cubiche/cubiche | src/Cubiche/Core/Metadata/Tests/Units/Driver/MergeableDriverTests.php | PHP | mit | 3,384 |
module App.Home {
export interface IHomeTab {
title: string;
description: string;
partial: string;
active?: boolean;
disabled?: boolean;
}
export interface IHomeController extends Main.IController {
selectedTab: IHomeTab;
tabs: IHomeTab[];
setSelectedTab(tab: IHomeTab): void;
}
export class HomeController implements IHomeController {
public static $inject = ["tabs"];
constructor( public tabs: IHomeTab[] ) {
var initiallyActiveTab: number;
initiallyActiveTab = 0;
this.tabs[initiallyActiveTab].active = true;
this.selectedTab = this.tabs[initiallyActiveTab];
}
public selectedTab: IHomeTab;
public getComponentType(): Main.ComponentType {
return Main.ComponentType.AngularController;
}
public setSelectedTab(tab: IHomeTab): void {
if (tab.disabled) {
return;
}
this.selectedTab = tab;
this.tabs.map(x => x.active = false);
tab.active = true;
}
}
}
| filimon-danopoulos/class-creator | src/app/public/scripts/home/controllers/HomeController.ts | TypeScript | mit | 1,145 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace Paradigm.CodeGen.Output.Models.Configuration
{
[DataContract]
public class OutputFileConfiguration
{
[IgnoreDataMember]
public string ExecutingFullPath => Path.GetDirectoryName(typeof(OutputFileConfiguration).GetTypeInfo().Assembly.Location);
[DataMember]
public string Name { get; set; }
[DataMember]
public string TemplatePath { get; set; }
[DataMember]
public string OutputPath { get; set; }
[DataMember]
public SummaryFileConfiguration Summary { get; set; }
[DataMember]
public List<NamingRuleConfiguration> NamingRules { get; set; }
[DataMember]
public List<TypeMatcherConfiguration> TypeMatchers { get; set; }
[DataMember]
public List<OutputConfigurationParameter> Parameters { get; set; }
public string this[string name]
{
get
{
var entry = this.Parameters.FirstOrDefault(x => x.Name == name);
if (entry == null)
throw new Exception($"Parameter {name} does not exist in output configuration.");
return entry.Value;
}
}
public OutputFileConfiguration()
{
this.NamingRules = new List<NamingRuleConfiguration>();
this.TypeMatchers = new List<TypeMatcherConfiguration>();
this.Parameters = new List<OutputConfigurationParameter>();
}
public void AddParameter(OutputConfigurationParameter parameter)
{
this.Parameters?.Add(parameter);
}
public void AddNamingRules(NamingRuleConfiguration namingRule)
{
this.NamingRules?.Add(namingRule);
}
public void AddTypeMatchers(TypeMatcherConfiguration typeMatcher)
{
this.TypeMatchers?.Add(typeMatcher);
}
}
} | MiracleDevs/Paradigm.CodeGen | src/Paradigm.CodeGen.Output.Models/Configuration/OutputFileConfiguration.cs | C# | mit | 2,061 |
#include <p24FJ128GB206.h>
#include <stdio.h>
#include <stdlib.h>
#include "config.h"
#include "common.h"
#include "pin.h"
#include "ui.h"
#include "timer.h"
#include "uart.h"
#include "usb.h"
#include "msgs.h"
#define SET_STATE 0 // Vendor request that receives 2 unsigned integer values
#define GET_VALS 1 // Vendor request that returns 2 unsigned integer values
#define GET_ROCKET_INFO 2 // Vendor request that returns rocket state, speed, and tilt
uint8_t RC_TXBUF[1024], RC_RXBUF[1024];
//Throttle and Orientation will be encoded in Value.
uint16_t rocket_state;
uint16_t rocket_speed, rocket_tilt;
uint8_t rec_msg[64], tx_msg[64];
void VendorRequests(void) {
WORD temp;
switch (USB_setup.bRequest) {
case SET_STATE:
// state = USB_setup.wValue.w;
BD[EP0IN].bytecount = 0; // set EP0 IN byte count to 0
BD[EP0IN].status = 0xC8; // send packet as DATA1, set UOWN bit
break;
case GET_VALS:
temp.w = rocket_tilt;
BD[EP0IN].address[0] = temp.b[0];
BD[EP0IN].address[1] = temp.b[1];
temp.w = uart1.TXbuffer.tail;
BD[EP0IN].address[2] = temp.b[0];
BD[EP0IN].address[3] = temp.b[1];
temp.w = uart1.TXbuffer.count;
BD[EP0IN].address[4] = temp.b[0];
BD[EP0IN].address[5] = temp.b[1];
temp.w = uart1.RXbuffer.head;
BD[EP0IN].address[6] = temp.b[0];
BD[EP0IN].address[7] = temp.b[1];
temp.w = uart1.RXbuffer.tail;
BD[EP0IN].address[8] = temp.b[0];
BD[EP0IN].address[9] = temp.b[1];
temp.w = uart1.RXbuffer.count;
BD[EP0IN].address[10] = temp.b[0];
BD[EP0IN].address[11] = temp.b[1];
BD[EP0IN].bytecount = 12; // set EP0 IN byte count to 4
BD[EP0IN].status = 0xC8; // send packet as DATA1, set UOWN bit
break;
case GET_ROCKET_INFO:
temp.w = rocket_tilt;
BD[EP0IN].address[0] = temp.b[0];
BD[EP0IN].address[1] = temp.b[1];
temp.w = rocket_speed;
BD[EP0IN].address[2] = temp.b[0];
BD[EP0IN].address[3] = temp.b[1];
temp.w = rocket_state;
BD[EP0IN].address[4] = temp.b[0];
BD[EP0IN].address[5] = temp.b[1];
BD[EP0IN].bytecount = 6; // set EP0 IN byte count to 4
BD[EP0IN].status = 0xC8; // send packet as DATA1, set UOWN bit
break;
default:
USB_error_flags |= 0x01; // set Request Error Flag
}
}
void VendorRequestsIn(void) {
switch (USB_request.setup.bRequest) {
default:
USB_error_flags |= 0x01; // set Request Error Flag
}
}
void VendorRequestsOut(void) {
switch (USB_request.setup.bRequest) {
default:
USB_error_flags |= 0x01; // set Request Error Flag
}
}
void UART_ctl(uint8_t cmd, uint8_t value) {
sprintf(tx_msg, "%01x%01x\r", value, cmd); // value could be state or command
uart_puts(&uart1, tx_msg);
if (cmd == GET_ROCKET_VALS) {
uart_gets(&uart1, rec_msg, 64);
led_toggle(&led3);
uint32_t decoded_msg = (uint32_t)strtol(rec_msg, NULL, 16);
rocket_speed = (uint16_t)((decoded_msg & 0xFF0000) >> 16);
rocket_tilt = (uint16_t)((decoded_msg & 0xFF00) >> 8);
rocket_state = decoded_msg & 0xFF;
}
}
void setup_uart() {
/*
Configures UART for communications.
Uses uart1 for inter-PIC communications. Rx on D[0], Tx on D[1].
Automatically uses uart2 for stdout, stderr to PC via audio jack.
*/
uart_open(&uart1, &D[1], &D[0], NULL, NULL, 19200., 'N', 1,
0, RC_TXBUF, 1024, RC_RXBUF, 1024);
}
void setup() {
timer_setPeriod(&timer1, 1); // Timer for LED operation/status blink
timer_setPeriod(&timer2, 0.5);
timer_start(&timer1);
timer_start(&timer2);
setup_uart();
rocket_tilt, rocket_speed = 0;
}
int16_t main(void) {
// printf("Starting Master Controller...\r\n");
init_clock();
init_ui();
init_timer();
init_uart();
setup();
uint16_t counter = 0;
uint8_t status_msg [64];
InitUSB();
U1IE = 0xFF; //setting up ISR for USB requests
U1EIE = 0xFF;
IFS5bits.USB1IF = 0; //flag
IEC5bits.USB1IE = 1; //enable
while (1) {
if (timer_flag(&timer1)) {
// Blink green light to show normal operation.
timer_lower(&timer1);
led_toggle(&led1);
}
if (timer_flag(&timer2)) {
// Transmit UART data
// UART_ctl(SEND_ROCKET_COMMANDS, 0b11);
// UART_ctl(SET_ROCKET_STATE, IDLE);
UART_ctl(GET_ROCKET_VALS, 0b0);
}
}
}
| RyanEggert/space-lander | tests/pic_uart_comms/master/main.c | C | mit | 4,659 |
(function(root, factory) {
if (typeof exports === 'object') {
// CommonJS
factory(require('../main'));
} else if (typeof define === 'function' && define.amd) {
// AMD
define(['sasl-external'], factory);
}
}(this, function(saslplain) {
describe('sasl-external', function() {
it('should export Mechanism', function() {
expect(saslplain.Mechanism).to.be.a('function');
});
it('should export Mechanism via module', function() {
expect(saslplain).to.equal(saslplain.Mechanism);
});
});
return { name: 'test.sasl-external' };
}));
| jaredhanson/js-sasl-external | test/sasl-external.test.js | JavaScript | mit | 603 |
module Searchkick
class RecordData
TYPE_KEYS = ["type", :type]
attr_reader :index, :record
def initialize(index, record)
@index = index
@record = record
end
def index_data
data = record_data
data[:data] = search_data
{index: data}
end
def update_data(method_name)
data = record_data
data[:data] = {doc: search_data(method_name)}
{update: data}
end
def delete_data
{delete: record_data}
end
# custom id can be useful for load: false
def search_id
id = record.respond_to?(:search_document_id) ? record.search_document_id : record.id
id.is_a?(Numeric) ? id : id.to_s
end
def document_type(ignore_type = false)
index.klass_document_type(record.class, ignore_type)
end
def record_data
data = {
_index: index.name,
_id: search_id
}
data[:routing] = record.search_routing if record.respond_to?(:search_routing)
data
end
private
def search_data(method_name = nil)
partial_reindex = !method_name.nil?
source = record.send(method_name || :search_data)
# conversions
index.conversions_fields.each do |conversions_field|
if source[conversions_field]
source[conversions_field] = source[conversions_field].map { |k, v| {query: k, count: v} }
end
end
# hack to prevent generator field doesn't exist error
if !partial_reindex
index.suggest_fields.each do |field|
if !source.key?(field) && !source.key?(field.to_sym)
source[field] = nil
end
end
end
# locations
index.locations_fields.each do |field|
if source[field]
if !source[field].is_a?(Hash) && (source[field].first.is_a?(Array) || source[field].first.is_a?(Hash))
# multiple locations
source[field] = source[field].map { |a| location_value(a) }
else
source[field] = location_value(source[field])
end
end
end
if index.options[:inheritance]
if !TYPE_KEYS.any? { |tk| source.key?(tk) }
source[:type] = document_type(true)
end
end
cast_big_decimal(source)
source
end
def location_value(value)
if value.is_a?(Array)
value.map(&:to_f).reverse
elsif value.is_a?(Hash)
{lat: value[:lat].to_f, lon: value[:lon].to_f}
else
value
end
end
# change all BigDecimal values to floats due to
# https://github.com/rails/rails/issues/6033
# possible loss of precision :/
def cast_big_decimal(obj)
case obj
when BigDecimal
obj.to_f
when Hash
obj.each do |k, v|
# performance
if v.is_a?(BigDecimal)
obj[k] = v.to_f
elsif v.is_a?(Enumerable)
obj[k] = cast_big_decimal(v)
end
end
when Enumerable
obj.map do |v|
cast_big_decimal(v)
end
else
obj
end
end
end
end
| ankane/searchkick | lib/searchkick/record_data.rb | Ruby | mit | 3,097 |
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<link href="normalize.css" rel="stylesheet"/>
<link href="index.css" rel="stylesheet"/>
</head>
<body>
<section>
<div><span>TempExchange API</span></div>
<!-- open a new window or tab for github page -->
<div><span onclick="window.open('https://github.com/dylandy/tempexchanger');">Github</span><span>Get Started</span></div>
</section>
<section>
<div><span>Get Started</span></div>
<div class="content">
<p>You can download the project to deploy yourself or you can simply use the api deploy by others :p</p>
<h3>How To Deploy</h3>
<p>
The programme can only deploy and use under Unix-like system (sorry windows) due to the gems (or libraries) used in the project.
The following requirement is essential for this project.
</p>
<h4>Requirements</h4>
<p>This project was developed and tested under the following elements. If you can deploy this project other than these elements, please let me know.</p>
<ul>
<li>Unix-like system</li>
<li>Ruby</li>
<li>Sinatra</li>
<li>Nokogiri</li>
</ul>
<p> After you install all the dependencies and you can download project <a href="https://github.com/dylandy/tempexchanger">here</a> and launch the service for temperature exchange service.</p>
<h4>How To Use</h4>
<p>
This api service support four different temperature formats to switch from each other. The current supported formats are "celsius", "fahrenheit", "kelvin" and "reaumur".
The return format could be with three different kinds in "plain text", "json" and "xml". Please follow the rule below to use get the data.
</p>
<ul>
<li class="demo">http://.../[:temperture-format]-to-[:temperture-format]/[:degree]/[:output-format]</li>
</ul>
<h4>Explanation</h4>
<table>
<tr><td>temperture-format</td><td>kelvin, fahrenheit, celsius, reaumur</td></tr>
<tr><td>degree</td><td>float or integer number</td></tr>
<tr><td>output-format</td><td>null, json, xml</td></tr>
</table>
<p> <b>Notice:If you want to output plain text, please just leave the output format blank.</b></p>
<h4>Demo</h4>
<p>transfer from:</p>
<select>
<option value="kelvin">kelvin</option>
<option value="celsius">celsius</option>
<option value="fahrenheit">fahrenheit</option>
<option value="reaumur">reaumur</option>
</select>
<p>transfer to:</p>
<select>
<option value="kelvin">kelvin</option>
<option value="celsius">celsius</option>
<option value="fahrenheit">fahrenheit</option>
<option value="reaumur">reaumur</option>
</select>
<p>original degree</p>
<input type="number">
<p>output format of:</p>
<select>
<option value="text">plain text</option>
<option value="json">json</option>
<option value="xml">xml</option>
</select>
<br>
<br>
<button>see the demo</button>
<br><br><br>
<iframe ></iframe>
<p><b>Noitce: xml format would be render into html in iframe, you can simply see all the elements in developer console.</b></p>
</div>
</section>
<section>
<p>All right reserved @Dylandy Chang 2015</p>
<p>This API is release under MIT LICENSE.</p>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="index.js"></script>
</body>
</html>
| dylandy/tempexchanger | public/index.html | HTML | mit | 4,030 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.