code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/**
* @license
* Copyright (c) 2011 NVIDIA Corporation. All rights reserved.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED
* *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS
* OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT,IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA
* OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, SPECIAL, INCIDENTAL, INDIRECT, OR
* CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS
* OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY
* OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
//This file is automatically rebuilt by the Cesium build process.
/*global define*/
define(function() {
'use strict';
return "#ifndef FXAA_PRESET\n\
#define FXAA_PRESET 3\n\
#endif\n\
#if (FXAA_PRESET == 3)\n\
#define FXAA_EDGE_THRESHOLD (1.0/8.0)\n\
#define FXAA_EDGE_THRESHOLD_MIN (1.0/24.0)\n\
#define FXAA_SEARCH_STEPS 16\n\
#define FXAA_SEARCH_THRESHOLD (1.0/4.0)\n\
#define FXAA_SUBPIX_CAP (3.0/4.0)\n\
#define FXAA_SUBPIX_TRIM (1.0/4.0)\n\
#endif\n\
#if (FXAA_PRESET == 4)\n\
#define FXAA_EDGE_THRESHOLD (1.0/8.0)\n\
#define FXAA_EDGE_THRESHOLD_MIN (1.0/24.0)\n\
#define FXAA_SEARCH_STEPS 24\n\
#define FXAA_SEARCH_THRESHOLD (1.0/4.0)\n\
#define FXAA_SUBPIX_CAP (3.0/4.0)\n\
#define FXAA_SUBPIX_TRIM (1.0/4.0)\n\
#endif\n\
#if (FXAA_PRESET == 5)\n\
#define FXAA_EDGE_THRESHOLD (1.0/8.0)\n\
#define FXAA_EDGE_THRESHOLD_MIN (1.0/24.0)\n\
#define FXAA_SEARCH_STEPS 32\n\
#define FXAA_SEARCH_THRESHOLD (1.0/4.0)\n\
#define FXAA_SUBPIX_CAP (3.0/4.0)\n\
#define FXAA_SUBPIX_TRIM (1.0/4.0)\n\
#endif\n\
#define FXAA_SUBPIX_TRIM_SCALE (1.0/(1.0 - FXAA_SUBPIX_TRIM))\n\
float FxaaLuma(vec3 rgb) {\n\
return rgb.y * (0.587/0.299) + rgb.x;\n\
}\n\
vec3 FxaaLerp3(vec3 a, vec3 b, float amountOfA) {\n\
return (vec3(-amountOfA) * b) + ((a * vec3(amountOfA)) + b);\n\
}\n\
vec4 FxaaTexOff(sampler2D tex, vec2 pos, ivec2 off, vec2 rcpFrame) {\n\
float x = pos.x + float(off.x) * rcpFrame.x;\n\
float y = pos.y + float(off.y) * rcpFrame.y;\n\
return texture2D(tex, vec2(x, y));\n\
}\n\
vec3 FxaaPixelShader(vec2 pos, sampler2D tex, vec2 rcpFrame)\n\
{\n\
vec3 rgbN = FxaaTexOff(tex, pos.xy, ivec2( 0,-1), rcpFrame).xyz;\n\
vec3 rgbW = FxaaTexOff(tex, pos.xy, ivec2(-1, 0), rcpFrame).xyz;\n\
vec3 rgbM = FxaaTexOff(tex, pos.xy, ivec2( 0, 0), rcpFrame).xyz;\n\
vec3 rgbE = FxaaTexOff(tex, pos.xy, ivec2( 1, 0), rcpFrame).xyz;\n\
vec3 rgbS = FxaaTexOff(tex, pos.xy, ivec2( 0, 1), rcpFrame).xyz;\n\
float lumaN = FxaaLuma(rgbN);\n\
float lumaW = FxaaLuma(rgbW);\n\
float lumaM = FxaaLuma(rgbM);\n\
float lumaE = FxaaLuma(rgbE);\n\
float lumaS = FxaaLuma(rgbS);\n\
float rangeMin = min(lumaM, min(min(lumaN, lumaW), min(lumaS, lumaE)));\n\
float rangeMax = max(lumaM, max(max(lumaN, lumaW), max(lumaS, lumaE)));\n\
float range = rangeMax - rangeMin;\n\
if(range < max(FXAA_EDGE_THRESHOLD_MIN, rangeMax * FXAA_EDGE_THRESHOLD))\n\
{\n\
return rgbM;\n\
}\n\
vec3 rgbL = rgbN + rgbW + rgbM + rgbE + rgbS;\n\
float lumaL = (lumaN + lumaW + lumaE + lumaS) * 0.25;\n\
float rangeL = abs(lumaL - lumaM);\n\
float blendL = max(0.0, (rangeL / range) - FXAA_SUBPIX_TRIM) * FXAA_SUBPIX_TRIM_SCALE;\n\
blendL = min(FXAA_SUBPIX_CAP, blendL);\n\
vec3 rgbNW = FxaaTexOff(tex, pos.xy, ivec2(-1,-1), rcpFrame).xyz;\n\
vec3 rgbNE = FxaaTexOff(tex, pos.xy, ivec2( 1,-1), rcpFrame).xyz;\n\
vec3 rgbSW = FxaaTexOff(tex, pos.xy, ivec2(-1, 1), rcpFrame).xyz;\n\
vec3 rgbSE = FxaaTexOff(tex, pos.xy, ivec2( 1, 1), rcpFrame).xyz;\n\
rgbL += (rgbNW + rgbNE + rgbSW + rgbSE);\n\
rgbL *= vec3(1.0/9.0);\n\
float lumaNW = FxaaLuma(rgbNW);\n\
float lumaNE = FxaaLuma(rgbNE);\n\
float lumaSW = FxaaLuma(rgbSW);\n\
float lumaSE = FxaaLuma(rgbSE);\n\
float edgeVert =\n\
abs((0.25 * lumaNW) + (-0.5 * lumaN) + (0.25 * lumaNE)) +\n\
abs((0.50 * lumaW ) + (-1.0 * lumaM) + (0.50 * lumaE )) +\n\
abs((0.25 * lumaSW) + (-0.5 * lumaS) + (0.25 * lumaSE));\n\
float edgeHorz =\n\
abs((0.25 * lumaNW) + (-0.5 * lumaW) + (0.25 * lumaSW)) +\n\
abs((0.50 * lumaN ) + (-1.0 * lumaM) + (0.50 * lumaS )) +\n\
abs((0.25 * lumaNE) + (-0.5 * lumaE) + (0.25 * lumaSE));\n\
bool horzSpan = edgeHorz >= edgeVert;\n\
float lengthSign = horzSpan ? -rcpFrame.y : -rcpFrame.x;\n\
if(!horzSpan)\n\
{\n\
lumaN = lumaW;\n\
lumaS = lumaE;\n\
}\n\
float gradientN = abs(lumaN - lumaM);\n\
float gradientS = abs(lumaS - lumaM);\n\
lumaN = (lumaN + lumaM) * 0.5;\n\
lumaS = (lumaS + lumaM) * 0.5;\n\
if (gradientN < gradientS)\n\
{\n\
lumaN = lumaS;\n\
lumaN = lumaS;\n\
gradientN = gradientS;\n\
lengthSign *= -1.0;\n\
}\n\
vec2 posN;\n\
posN.x = pos.x + (horzSpan ? 0.0 : lengthSign * 0.5);\n\
posN.y = pos.y + (horzSpan ? lengthSign * 0.5 : 0.0);\n\
gradientN *= FXAA_SEARCH_THRESHOLD;\n\
vec2 posP = posN;\n\
vec2 offNP = horzSpan ? vec2(rcpFrame.x, 0.0) : vec2(0.0, rcpFrame.y);\n\
float lumaEndN = lumaN;\n\
float lumaEndP = lumaN;\n\
bool doneN = false;\n\
bool doneP = false;\n\
posN += offNP * vec2(-1.0, -1.0);\n\
posP += offNP * vec2( 1.0, 1.0);\n\
for(int i = 0; i < FXAA_SEARCH_STEPS; i++) {\n\
if(!doneN)\n\
{\n\
lumaEndN = FxaaLuma(texture2D(tex, posN.xy).xyz);\n\
}\n\
if(!doneP)\n\
{\n\
lumaEndP = FxaaLuma(texture2D(tex, posP.xy).xyz);\n\
}\n\
doneN = doneN || (abs(lumaEndN - lumaN) >= gradientN);\n\
doneP = doneP || (abs(lumaEndP - lumaN) >= gradientN);\n\
if(doneN && doneP)\n\
{\n\
break;\n\
}\n\
if(!doneN)\n\
{\n\
posN -= offNP;\n\
}\n\
if(!doneP)\n\
{\n\
posP += offNP;\n\
}\n\
}\n\
float dstN = horzSpan ? pos.x - posN.x : pos.y - posN.y;\n\
float dstP = horzSpan ? posP.x - pos.x : posP.y - pos.y;\n\
bool directionN = dstN < dstP;\n\
lumaEndN = directionN ? lumaEndN : lumaEndP;\n\
if(((lumaM - lumaN) < 0.0) == ((lumaEndN - lumaN) < 0.0))\n\
{\n\
lengthSign = 0.0;\n\
}\n\
float spanLength = (dstP + dstN);\n\
dstN = directionN ? dstN : dstP;\n\
float subPixelOffset = (0.5 + (dstN * (-1.0/spanLength))) * lengthSign;\n\
vec3 rgbF = texture2D(tex, vec2(\n\
pos.x + (horzSpan ? 0.0 : subPixelOffset),\n\
pos.y + (horzSpan ? subPixelOffset : 0.0))).xyz;\n\
return FxaaLerp3(rgbL, rgbF, blendL);\n\
}\n\
uniform sampler2D u_texture;\n\
uniform vec2 u_step;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
gl_FragColor = vec4(FxaaPixelShader(v_textureCoordinates, u_texture, u_step), 1.0);\n\
}\n\
";
}); | denverpierce/denverpierce.github.io | Cesium/Source/Shaders/PostProcessFilters/FXAA.js | JavaScript | mit | 6,619 |
//
// Created by Amrik Sadhra on 25/10/2017.
//
#include "Model.h"
#include <utility>
Model::Model(std::string name, std::vector<glm::vec3> verts, std::vector<glm::vec2> uvs, std::vector<glm::vec3> norms, std::vector<unsigned int> indices, bool removeVertexIndexing, glm::vec3 center_position) {
m_name = std::move(name);
m_uvs = std::move(uvs);
m_vertex_indices = std::move(indices);
m_normals = std::move(norms);
if (removeVertexIndexing) {
for (unsigned int m_vertex_index : m_vertex_indices) {
m_vertices.push_back(verts[m_vertex_index]);
}
} else {
m_vertices = std::move(verts);
}
position = center_position;
initialPosition = center_position;
orientation_vec = glm::vec3(0,0,0);
orientation = glm::normalize(glm::quat(orientation_vec));
}
void Model::enable() {
enabled = true;
}
| AmrikSadhra/FCE-to-OBJ | src/Scene/Model.cpp | C++ | mit | 877 |
package com.farwolf.reader;
import android.util.Log;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EBean;
import com.farwolf.base.ServiceBase;
import com.farwolf.json.JsonListener;
import com.farwolf.json.JsonReader;
import com.farwolf.view.progress.DialogProgress;
import com.farwolf.view.progress.IProgress;
@EBean
public abstract class HttpServiceBase <T extends JsonReader> extends ServiceBase implements JsonListener<T>{
@Bean
protected DialogProgress progress;
public IProgress getProgress()
{
progress.init(getTitle(), getContent());
return progress;
}
public String getTitle()
{
return "加载中";
}
public String getContent()
{
return "请稍候...";
}
@Override
public void start() {
// TODO Auto-generated method stub
getProgress().show();
}
@Override
public void compelete() {
// TODO Auto-generated method stub
getProgress().dismiss();
}
@Override
public void fail(T j, String code, String msg) {
// TODO Auto-generated method stub
toast(msg);
}
@Override
public void exception(Object o) {
// TODO Auto-generated method stub
Log.e("网络异常!",this.getClass()+"");
toast("网络异常!");
}
}
| evildoerX/weex-ouikit | platforms/android/farwolf.business/src/main/java/com/farwolf/reader/HttpServiceBase.java | Java | mit | 1,255 |
<?php echo form_open('','class="form-sign"'); ?>
<div class=" my-reg-2 w3-animate-opacity">
<div class="container">
<div class="row size_4">
<div class="col-lg-2"></div>
<div class="col-lg-8 reg-box">
<h2 class="name">Step 4: Personal Information</h2>
<div class="spacer_2"></div>
<div class="spacer_2"></div>
<div class=" divisions">
<div class="form-group required-red">
<?php echo form_label('Street:','street'); ?><br>
<span class="error-red"> <?php echo form_error('street','Required Input: '); ?></span>
<?php echo form_input('street',$street,'class="form-control" placeholder="ex: 0487 San Lucas" id="street"'); ?>
</div>
<div class="form-group required-red">
<?php echo form_label('Baranggay:','brgy'); ?><br>
<span class="error-red"> <?php echo form_error('brgy','Required Input: '); ?></span>
<?php echo form_input('brgy',$brgy,'class="form-control" placeholder="ex: 0487 San Lucas" id="brgy"'); ?>
</div>
<div class="form-group required-red">
<?php echo form_label('City/Town:','city'); ?><br>
<span class="error-red"> <?php echo form_error('city','Required Input: '); ?></span>
<?php echo form_input('city',$city,'class="form-control" placeholder="ex: 0487 San Lucas" id="city"'); ?>
</div>
<div class="form-group required-red">
<?php echo form_label('Province:','province'); ?><br>
<span class="error-red"> <?php echo form_error('province','Required Input: '); ?></span>
<?php echo form_input('province',$province,'class="form-control" placeholder="ex: 0487 San Lucas" id="province"'); ?>
</div>
<div class="form-group required-red">
<?php echo form_label('Country:','country'); ?><br>
<span class="error-red"> <?php echo form_error('country','Required Input: '); ?></span>
<?php echo form_input('country',$country,'class="form-control" placeholder="ex: 0487 San Lucas" id="country"'); ?>
</div>
</div>
<div class=" divisions">
<div class="form-group required-red">
<?php echo form_label('Zip Code:','zip'); ?><br>
<span class="error-red"> <?php echo form_error('zip','Required Input: '); ?></span>
<?php echo form_input('zip',$zip,'class="form-control" placeholder="ex: 0487 San Lucas" id="zip"'); ?>
</div>
<div class="form-group required-red">
<?php echo form_label('Birthday:','birthday'); ?><br>
<span class="error-red"><?php echo form_error('birthday','Required Input: '); ?></span>
<input type="date" class="form-control" name="birthday" min="1900-01-02" id="birthday" placeholder="Select from the table below."><!--
<?php echo form_input('birthday',$birthday,' type="date" placeholder="Select " id="birthday"'); ?> -->
</div>
<div class="form-group required-red">
<?php echo form_label('Citizenship:','citizenship'); ?><br>
<span class="error-red"> <?php echo form_error('citizenship','Required Input: '); ?></span>
<?php echo form_input('citizenship',$citizenship,'class="form-control" placeholder="ex: 0487 San Lucas" id="zip"'); ?>
</div>
<div class="form-group required-red">
<?php echo form_label('Status:','status'); ?><br/>
<span class="error-red"><?php echo form_error('status','Rerqured Input: '); ?></span>
<input id="status" name="status" class="form-control" placeholder="Select from the list" type="text" list="personstatus"/>
<datalist id="personstatus">
<?php foreach($personstatusList as $row): ?>
<option><?php echo($row->status); ?></option>
<?php endforeach; ?>
</datalist>
</div>
<div class="form-group required-red">
<?php echo form_label('Gender:','gender'); ?><br/>
<span class="error-red"><?php echo form_error('gender','Rerqured Input: '); ?></span>
<input id="gender" name="gender" class="form-control" placeholder="Select from the list" type="text" list="genders"/>
<datalist id="genders">
<?php foreach($genderList as $row): ?>
<option><?php echo($row->gender); ?></option>
<?php endforeach; ?>
</datalist>
</div>
</div>
<div class="spacer_3"></div>
<button type="submit" name="submit" class="btn btn-mycustom-login" style="margin-top:30px;" value="1"><h4>Next</h4></button>
</div>
<div class="col-lg-2"></div>
</div>
</div>
</div>
<?php echo form_close(); ?>
| 11Receli/ISEE | application/modules/page/views/personalinfo.php | PHP | mit | 5,099 |
<?php
class SomethingDigital_EnterpriseIndexPerf_Model_Observer_Pagecache
{
/**
* Clean cache for affected products
*
* @param Varien_Event_Observer $observer Event data
*/
public function cleanProductsCacheAfterPartialReindex(Varien_Event_Observer $observer)
{
// Only if the PageCache is enabled.
if (!Mage::helper('core')->isModuleEnabled('Enterprise_PageCache')) {
return;
}
$entityIds = $observer->getEvent()->getProductIds();
if (is_array($entityIds) && !empty($entityIds)) {
$this->_cleanProductsCache(Mage::getModel('catalog/product'), $entityIds);
}
}
/**
* Clean cache by specified product and its ids
*
* @param Mage_Catalog_Model_Product $entity Base entity model
* @param int[] $ids Product IDs
*/
protected function _cleanProductsCache(Mage_Catalog_Model_Product $entity, array $ids)
{
$cacheTags = array();
$ids = array_unique($ids);
foreach ($ids as $entityId) {
$entity->setId($entityId);
$productTags = $entity->getCacheIdTagsWithCategories();
foreach ($productTags as $tag) {
$cacheTags[$tag] = $tag;
}
}
if (!empty($cacheTags)) {
$cacheTags = array_values($cacheTags);
Enterprise_PageCache_Model_Cache::getCacheInstance()->clean($cacheTags);
}
}
}
| sdinteractive/SomethingDigital_EnterpriseIndexPerf | app/code/community/SomethingDigital/EnterpriseIndexPerf/Model/Observer/Pagecache.php | PHP | mit | 1,456 |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// appleseed.foundation headers.
#include "foundation/math/rng/distribution.h"
#include "foundation/math/rng/mersennetwister.h"
#include "foundation/math/scalar.h"
#include "foundation/platform/arch.h"
#include "foundation/platform/types.h"
#include "foundation/utility/iostreamop.h"
#include "foundation/utility/makevector.h"
#include "foundation/utility/string.h"
#include "foundation/utility/test.h"
// Standard headers.
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
using namespace foundation;
using namespace std;
TEST_SUITE(Foundation_Utility_String)
{
TEST_CASE(ToString_GivenZeroAsInt_ReturnsCorrespondingString)
{
const int n = 0;
EXPECT_EQ("0", to_string(n));
}
TEST_CASE(ToString_GivenBoolValues_ReturnsCorrespondingStrings)
{
EXPECT_EQ("true", to_string(true));
EXPECT_EQ("false", to_string(false));
}
TEST_CASE(ToString_GivenInt8Values_ReturnsCorrespondingStrings)
{
EXPECT_EQ("0", to_string<int8>(0));
EXPECT_EQ("42", to_string<int8>(42));
EXPECT_EQ("-1", to_string<int8>(-1));
}
TEST_CASE(ToString_GivenInt16Values_ReturnsCorrespondingStrings)
{
EXPECT_EQ("0", to_string<int16>(0));
EXPECT_EQ("42", to_string<int16>(42));
EXPECT_EQ("-1", to_string<int16>(-1));
}
TEST_CASE(ToString_GivenInt32Values_ReturnsCorrespondingStrings)
{
EXPECT_EQ("0", to_string<int32>(0));
EXPECT_EQ("42", to_string<int32>(42));
EXPECT_EQ("-1", to_string<int32>(-1));
}
TEST_CASE(ToString_GivenInt64Values_ReturnsCorrespondingStrings)
{
EXPECT_EQ("0", to_string<int64>(0));
EXPECT_EQ("42", to_string<int64>(42));
EXPECT_EQ("-1", to_string<int64>(-1));
}
TEST_CASE(ToString_GivenUInt8Values_ReturnsCorrespondingStrings)
{
EXPECT_EQ("0", to_string<uint8>(0));
EXPECT_EQ("42", to_string<uint8>(42));
}
TEST_CASE(ToString_GivenUInt16Values_ReturnsCorrespondingStrings)
{
EXPECT_EQ("0", to_string<uint16>(0));
EXPECT_EQ("42", to_string<uint16>(42));
}
TEST_CASE(ToString_GivenUInt32Values_ReturnsCorrespondingStrings)
{
EXPECT_EQ("0", to_string<uint32>(0));
EXPECT_EQ("42", to_string<uint32>(42));
}
TEST_CASE(ToString_GivenUInt64Values_ReturnsCorrespondingStrings)
{
EXPECT_EQ("0", to_string<uint64>(0));
EXPECT_EQ("42", to_string<uint64>(42));
}
#if defined APPLESEED_ARCH32
#define ZERO_PTR 0x00000000
#define ZERO_PTR_STR "0x00000000"
#define DEADBEEF_PTR 0xDEADBEEF
#define DEADBEEF_PTR_STR "0xDEADBEEF"
#elif defined APPLESEED_ARCH64
#define ZERO_PTR 0x0000000000000000
#define ZERO_PTR_STR "0x0000000000000000"
#define DEADBEEF_PTR 0xDEADBEEFDEAFBABE
#define DEADBEEF_PTR_STR "0xDEADBEEFDEAFBABE"
#else
#error Cannot determine machine architecture.
#endif
TEST_CASE(ToString_GivenNonNullVoidPointer_ReturnsCorrespondingString)
{
void* ptr = reinterpret_cast<void*>(DEADBEEF_PTR);
EXPECT_EQ(DEADBEEF_PTR_STR, to_string(ptr));
}
TEST_CASE(ToString_GivenNonNullConstVoidPointer_ReturnsCorrespondingString)
{
const void* ptr = reinterpret_cast<const void*>(DEADBEEF_PTR);
EXPECT_EQ(DEADBEEF_PTR_STR, to_string(ptr));
}
TEST_CASE(ToString_GivenNullVoidPointer_ReturnsCorrespondingString)
{
void* ptr = ZERO_PTR;
EXPECT_EQ(ZERO_PTR_STR, to_string(ptr));
}
TEST_CASE(ToString_GivenNullConstVoidPointer_ReturnsCorrespondingString)
{
const void* ptr = ZERO_PTR;
EXPECT_EQ(ZERO_PTR_STR, to_string(ptr));
}
struct Foo { int dummy; };
TEST_CASE(ToString_GivenNonNullClassPointer_ReturnsCorrespondingString)
{
Foo* ptr = reinterpret_cast<Foo*>(DEADBEEF_PTR);
EXPECT_EQ(DEADBEEF_PTR_STR, to_string(ptr));
}
TEST_CASE(ToString_GivenNonNullConstClassPointer_ReturnsCorrespondingString)
{
const Foo* ptr = reinterpret_cast<const Foo*>(DEADBEEF_PTR);
EXPECT_EQ(DEADBEEF_PTR_STR, to_string(ptr));
}
TEST_CASE(ToString_GivenNullClassPointer_ReturnsCorrespondingString)
{
Foo* ptr = ZERO_PTR;
EXPECT_EQ(ZERO_PTR_STR, to_string(ptr));
}
TEST_CASE(ToString_GivenNullConstClassPointer_ReturnsCorrespondingString)
{
const Foo* ptr = ZERO_PTR;
EXPECT_EQ(ZERO_PTR_STR, to_string(ptr));
}
#undef ZERO_PTR
#undef ZERO_PTR_STR
#undef DEADBEEF_PTR
#undef DEADBEEF_PTR_STR
TEST_CASE(ToString_GivenNonNullCString_ReturnsCorrespondingString)
{
char s[] = "bunny";
EXPECT_EQ("bunny", to_string(s));
}
TEST_CASE(ToString_GivenNonNullConstCString_ReturnsCorrespondingString)
{
const char* s = "bunny";
EXPECT_EQ("bunny", to_string(s));
}
TEST_CASE(ToString_GivenNullCString_ReturnsCorrespondingString)
{
char* s = 0;
EXPECT_EQ("<null>", to_string(s));
}
TEST_CASE(ToString_GivenNullConstCString_ReturnsCorrespondingString)
{
const char* s = 0;
EXPECT_EQ("<null>", to_string(s));
}
TEST_CASE(ToString_GivenEmptyArray_ReturnsEmptyString)
{
const int array[3] = { 1, 2, 3 };
EXPECT_EQ("", to_string(array, 0));
}
TEST_CASE(ToString_GivenEmptyArrayWithCustomSeparator_ReturnsEmptyString)
{
const int array[3] = { 1, 2, 3 };
EXPECT_EQ("", to_string(array, 0, ";"));
}
TEST_CASE(ToString_GivenNonEmptyArray_ReturnsCorrespondingString)
{
const int array[3] = { 1, 2, 3 };
EXPECT_EQ("1 2 3", to_string(array, 3));
}
TEST_CASE(ToString_GivenNonEmptyArrayWithCustomSeparator_ReturnsCorrespondingString)
{
const int array[3] = { 1, 2, 3 };
EXPECT_EQ("1;2;3", to_string(array, 3, ";"));
}
TEST_CASE(FromString_GivenEmptyString_ThrowsExceptionStringConversionError)
{
EXPECT_EXCEPTION(ExceptionStringConversionError,
{
from_string<int>("");
});
}
TEST_CASE(FromString_GivenStrings_ReturnsCorrespondingInt8Values)
{
EXPECT_EQ(0, from_string<int8>("0"));
EXPECT_EQ(42, from_string<int8>("42"));
EXPECT_EQ(-1, from_string<int8>("-1"));
}
TEST_CASE(FromString_GivenStrings_ReturnsCorrespondingInt16Values)
{
EXPECT_EQ(0, from_string<int16>("0"));
EXPECT_EQ(42, from_string<int16>("42"));
EXPECT_EQ(-1, from_string<int16>("-1"));
}
TEST_CASE(FromString_GivenStrings_ReturnsCorrespondingInt32Values)
{
EXPECT_EQ(0, from_string<int32>("0"));
EXPECT_EQ(42, from_string<int32>("42"));
EXPECT_EQ(-1, from_string<int32>("-1"));
}
TEST_CASE(FromString_GivenStrings_ReturnsCorrespondingInt64Values)
{
EXPECT_EQ(0, from_string<int64>("0"));
EXPECT_EQ(42, from_string<int64>("42"));
EXPECT_EQ(-1, from_string<int64>("-1"));
}
TEST_CASE(FromString_GivenStrings_ReturnsCorrespondingUInt8Values)
{
EXPECT_EQ(0, from_string<uint8>("0"));
EXPECT_EQ(42, from_string<uint8>("42"));
}
TEST_CASE(FromString_GivenStrings_ReturnsCorrespondingUInt16Values)
{
EXPECT_EQ(0, from_string<uint16>("0"));
EXPECT_EQ(42, from_string<uint16>("42"));
}
TEST_CASE(FromString_GivenStrings_ReturnsCorrespondingUInt32Values)
{
EXPECT_EQ(0, from_string<uint32>("0"));
EXPECT_EQ(42, from_string<uint32>("42"));
}
TEST_CASE(FromString_GivenStrings_ReturnsCorrespondingUInt64Values)
{
EXPECT_EQ(0, from_string<uint64>("0"));
EXPECT_EQ(42, from_string<uint64>("42"));
}
TEST_CASE(FromString_GivenIntegerPrecededBySpace_IgnoresSpaceAndReturnsIntegerValue)
{
EXPECT_EQ(42, from_string<int>(" 42"));
}
TEST_CASE(FromString_GivenIntegerFollowedBySpace_ThrowsExceptionStringConversionError)
{
EXPECT_EXCEPTION(ExceptionStringConversionError,
{
from_string<int>("42 ");
});
}
TEST_CASE(StrcmpNoCaseHandlesEmptyString)
{
EXPECT_EQ(0, strcmp_nocase("", ""));
}
TEST_CASE(TestStrCmpNoCase)
{
EXPECT_EQ(0, strcmp_nocase("seal", "SEAL"));
EXPECT_EQ(0, strcmp_nocase("HeLLo", "hEllO"));
EXPECT_EQ(-1, strcmp_nocase("a", "b"));
EXPECT_EQ(-1, strcmp_nocase("A", "b"));
EXPECT_EQ(-1, strcmp_nocase("a", "B"));
EXPECT_EQ(-1, strcmp_nocase("A", "B"));
EXPECT_EQ(1, strcmp_nocase("b", "a"));
EXPECT_EQ(1, strcmp_nocase("B", "a"));
EXPECT_EQ(1, strcmp_nocase("b", "A"));
EXPECT_EQ(1, strcmp_nocase("B", "A"));
}
TEST_CASE(TrimLeftHandlesEmptyString)
{
EXPECT_EQ("", trim_left(""));
}
TEST_CASE(TrimLeftHandlesBlankStrings)
{
EXPECT_EQ("", trim_left(" "));
EXPECT_EQ("", trim_left(" \t\n\v\f\r "));
}
TEST_CASE(TrimLeftHandlesRealStrings)
{
EXPECT_EQ("hello ", trim_left("hello "));
EXPECT_EQ("hello", trim_left(" \t\n\v\f\r hello"));
EXPECT_EQ("hello ", trim_left(" \t\n\v\f\r hello "));
}
TEST_CASE(TrimRightHandlesEmptyString)
{
EXPECT_EQ(trim_right(""), "");
}
TEST_CASE(TrimRightHandlesBlankStrings)
{
EXPECT_EQ(trim_right(" "), "");
EXPECT_EQ(trim_right(" \t\n\v\f\r "), "");
}
TEST_CASE(TrimRightHandlesRealStrings)
{
EXPECT_EQ(" hello", trim_right(" hello"));
EXPECT_EQ("hello", trim_right("hello \t\n\v\f\r "));
EXPECT_EQ(" hello", trim_right(" hello \t\n\v\f\r "));
}
TEST_CASE(TrimBothHandlesEmptyString)
{
EXPECT_EQ("", trim_both(""));
}
TEST_CASE(TrimBothHandlesBlankStrings)
{
EXPECT_EQ("", trim_both(" "));
EXPECT_EQ("", trim_both(" \t\n\v\f\r "));
}
TEST_CASE(TrimBothHandlesRealStrings)
{
EXPECT_EQ("hello", trim_both("hello \t\n\v\f\r "));
EXPECT_EQ("hello", trim_both(" \t\n\v\f\r hello"));
EXPECT_EQ("hello", trim_both(" \t\n\v\f\r hello \t\n\v\f\r "));
}
vector<string> tokenize_wrapper(
const string& s,
const string& delimiters)
{
vector<string> vec;
tokenize(s, delimiters, vec);
return vec;
}
TEST_CASE(TestTokenize)
{
EXPECT_EQ(vector<string>(), tokenize_wrapper("", "\n"));
EXPECT_EQ(vector<string>(), tokenize_wrapper("\n", "\n"));
EXPECT_EQ(vector<string>(), tokenize_wrapper("\n\n", "\n"));
EXPECT_EQ(vector<string>(), tokenize_wrapper("\n\n\n", "\n"));
EXPECT_EQ(make_vector("hello"), tokenize_wrapper("hello", "\n"));
EXPECT_EQ(make_vector("hello"), tokenize_wrapper("hello\n", "\n"));
EXPECT_EQ(make_vector("hello"), tokenize_wrapper("hello\n\n", "\n"));
EXPECT_EQ(make_vector("hello"), tokenize_wrapper("\nhello", "\n"));
EXPECT_EQ(make_vector("hello"), tokenize_wrapper("\n\nhello", "\n"));
EXPECT_EQ(make_vector("hello"), tokenize_wrapper("\n\nhello\n\n", "\n"));
EXPECT_EQ(make_vector("hello", "world"), tokenize_wrapper("hello\nworld", "\n"));
EXPECT_EQ(make_vector("hello", "world"), tokenize_wrapper("hello\n\nworld", "\n"));
EXPECT_EQ(make_vector("hello", "world", "bunny"), tokenize_wrapper("helloXworld\nbunny", "X\n"));
EXPECT_EQ(make_vector("1", "2", "3"), tokenize_wrapper(" [1, 2 ,3 ] ", ",[] "));
}
vector<string> split_wrapper(
const string& s,
const string& delimiters)
{
vector<string> vec;
split(s, delimiters, vec);
return vec;
}
TEST_CASE(TestSplit)
{
EXPECT_EQ(make_vector(""), split_wrapper("", "\n"));
EXPECT_EQ(make_vector("", ""), split_wrapper("\n", "\n"));
EXPECT_EQ(make_vector("", "", ""), split_wrapper("\n\n", "\n"));
EXPECT_EQ(make_vector("", "", "", ""), split_wrapper("\n\n\n", "\n"));
EXPECT_EQ(make_vector("hello"), split_wrapper("hello", "\n"));
EXPECT_EQ(make_vector("hello", ""), split_wrapper("hello\n", "\n"));
EXPECT_EQ(make_vector("hello", "", ""), split_wrapper("hello\n\n", "\n"));
EXPECT_EQ(make_vector("", "hello"), split_wrapper("\nhello", "\n"));
EXPECT_EQ(make_vector("", "hello", ""), split_wrapper("\nhello\n", "\n"));
EXPECT_EQ(make_vector("", "hello", "", ""), split_wrapper("\nhello\n\n", "\n"));
EXPECT_EQ(make_vector("", "", "hello"), split_wrapper("\n\nhello", "\n"));
EXPECT_EQ(make_vector("", "", "hello", ""), split_wrapper("\n\nhello\n", "\n"));
EXPECT_EQ(make_vector("", "", "hello", "", ""), split_wrapper("\n\nhello\n\n", "\n"));
}
TEST_CASE(Replace_GivenEmptyString_ReturnsEmptyString)
{
const string result = replace("", "aa", "bbb");
EXPECT_EQ("", result);
}
TEST_CASE(Replace_GivenNonMatchingString_ReturnsInputString)
{
const string result = replace("xyz", "aa", "bbb");
EXPECT_EQ("xyz", result);
}
TEST_CASE(Replace_GivenPartiallyMatchingString_ReturnsInputString)
{
const string result = replace("axyz", "aa", "bbb");
EXPECT_EQ("axyz", result);
}
TEST_CASE(Replace_GivenStringWithSingleMatch_ReplacesMatch)
{
const string result = replace("xyaaz", "aa", "bbb");
EXPECT_EQ("xybbbz", result);
}
TEST_CASE(Replace_GivenStringWithMultipleMatches_ReplacesMatches)
{
const string result = replace("xaayaaz", "aa", "bbb");
EXPECT_EQ("xbbbybbbz", result);
}
TEST_CASE(Replace_GivenStringWithMatchAtTheBeginning_ReplacesMatch)
{
const string result = replace("aaxyz", "aa", "bbb");
EXPECT_EQ("bbbxyz", result);
}
TEST_CASE(Replace_GivenStringWithMatchAtTheEnd_ReplacesMatch)
{
const string result = replace("xyzaa", "aa", "bbb");
EXPECT_EQ("xyzbbb", result);
}
TEST_CASE(GetNumberedStringMaxValue_GivenEmptyPattern_ReturnsZero)
{
const size_t max_value = get_numbered_string_max_value("");
EXPECT_EQ(0, max_value);
}
TEST_CASE(GetNumberedStringMaxValue_GivenPatternWithoutHashes_ReturnsZero)
{
const size_t max_value = get_numbered_string_max_value("hello");
EXPECT_EQ(0, max_value);
}
TEST_CASE(GetNumberedStringMaxValue_GivenPatternWithThreeHashesAtTheBeginning_Returns999)
{
const size_t max_value = get_numbered_string_max_value("###hello");
EXPECT_EQ(999, max_value);
}
TEST_CASE(GetNumberedStringMaxValue_GivenPatternWithThreeHashesInTheMiddle_Returns999)
{
const size_t max_value = get_numbered_string_max_value("he###llo");
EXPECT_EQ(999, max_value);
}
TEST_CASE(GetNumberedStringMaxValue_GivenPatternWithThreeHashesAtTheEnd_Returns999)
{
const size_t max_value = get_numbered_string_max_value("hello###");
EXPECT_EQ(999, max_value);
}
TEST_CASE(GetNumberedString_GivenEmptyPattern_ReturnsEmptyString)
{
const string result = get_numbered_string("", 12);
EXPECT_EQ("", result);
}
TEST_CASE(GetNumberedString_GivenPatternWithoutHashes_ReturnsPatternUnmodified)
{
const string result = get_numbered_string("hello", 12);
EXPECT_EQ("hello", result);
}
TEST_CASE(GetNumberedString_GivenPatternWithSingleHashAtTheBeginning_GivenSingleDigitValue_ReplacesHashByValue)
{
const string result = get_numbered_string("#hello", 5);
EXPECT_EQ("5hello", result);
}
TEST_CASE(GetNumberedString_GivenPatternWithSingleHashInTheMiddle_GivenSingleDigitValue_ReplacesHashByValue)
{
const string result = get_numbered_string("he#llo", 5);
EXPECT_EQ("he5llo", result);
}
TEST_CASE(GetNumberedString_GivenPatternWithSingleHashAtTheEnd_GivenSingleDigitValue_ReplacesHashByValue)
{
const string result = get_numbered_string("hello#", 5);
EXPECT_EQ("hello5", result);
}
TEST_CASE(GetNumberedString_GivenPatternWithThreeHashes_GivenSingleDigitValue_ReplacesHashesByValue)
{
const string result = get_numbered_string("hel###lo", 5);
EXPECT_EQ("hel005lo", result);
}
TEST_CASE(GetNumberedString_GivenPatternWithThreeHashes_GivenTwoDigitsValue_ReplacesHashesByValue)
{
const string result = get_numbered_string("hello###", 12);
EXPECT_EQ("hello012", result);
}
TEST_CASE(GetNumberedString_GivenPatternWithThreeHashes_GivenFourDigitsValue_ReplacesHashesByValue)
{
const string result = get_numbered_string("hello###", 1234);
EXPECT_EQ("hello1234", result);
}
TEST_CASE(ReplaceSpecialXMLCharacters_GivenEmptyString_ReturnsEmptyString)
{
const string result = replace_special_xml_characters("");
EXPECT_EQ("", result);
}
TEST_CASE(ReplaceSpecialXMLCharacters_GivenStringWithAmpersand_ReplacesAmpersandByEntity)
{
const string result = replace_special_xml_characters("aa&bb");
EXPECT_EQ("aa&bb", result);
}
TEST_CASE(ReplaceSpecialXMLCharacters_GivenStringWithQuoteThenAmpersand_ReplacesQuoteAndAmpersandByEntities)
{
const string result = replace_special_xml_characters("aa\"&bb");
EXPECT_EQ("aa"&bb", result);
}
TEST_CASE(ReplaceSpecialXMLCharacters_GivenStringWithXMLEntity_ReplacesAmpersandByEntity)
{
const string result = replace_special_xml_characters("aa&bb");
EXPECT_EQ("aa&amp;bb", result);
}
bool fast_strtod_ok(const char* str)
{
const double ref = strtod(str, 0);
const double val = fast_strtod(str, 0);
return feq(ref, val, 1.0e-14);
}
TEST_CASE(FastStrtod)
{
EXPECT_TRUE(fast_strtod_ok("1"));
EXPECT_TRUE(fast_strtod_ok("+1"));
EXPECT_TRUE(fast_strtod_ok("-1"));
EXPECT_TRUE(fast_strtod_ok("1."));
EXPECT_TRUE(fast_strtod_ok("+1."));
EXPECT_TRUE(fast_strtod_ok("-1."));
EXPECT_TRUE(fast_strtod_ok(".1"));
EXPECT_TRUE(fast_strtod_ok("+.1"));
EXPECT_TRUE(fast_strtod_ok("-.1"));
EXPECT_TRUE(fast_strtod_ok("1.0"));
EXPECT_TRUE(fast_strtod_ok("+1.0"));
EXPECT_TRUE(fast_strtod_ok("-1.0"));
EXPECT_TRUE(fast_strtod_ok("1e8"));
EXPECT_TRUE(fast_strtod_ok("1e-8"));
EXPECT_TRUE(fast_strtod_ok("1e+8"));
EXPECT_TRUE(fast_strtod_ok("1E8"));
EXPECT_TRUE(fast_strtod_ok("1E-8"));
EXPECT_TRUE(fast_strtod_ok("1E+8"));
EXPECT_TRUE(fast_strtod_ok("+1e8"));
EXPECT_TRUE(fast_strtod_ok("+1e-8"));
EXPECT_TRUE(fast_strtod_ok("+1e+8"));
EXPECT_TRUE(fast_strtod_ok("+1E8"));
EXPECT_TRUE(fast_strtod_ok("+1E-8"));
EXPECT_TRUE(fast_strtod_ok("+1E+8"));
EXPECT_TRUE(fast_strtod_ok("-1e8"));
EXPECT_TRUE(fast_strtod_ok("-1e-8"));
EXPECT_TRUE(fast_strtod_ok("-1e+8"));
EXPECT_TRUE(fast_strtod_ok("-1E8"));
EXPECT_TRUE(fast_strtod_ok("-1E-8"));
EXPECT_TRUE(fast_strtod_ok("-1E+8"));
EXPECT_TRUE(fast_strtod_ok("1.e8"));
EXPECT_TRUE(fast_strtod_ok("1.e-8"));
EXPECT_TRUE(fast_strtod_ok("1.e+8"));
EXPECT_TRUE(fast_strtod_ok("1.E8"));
EXPECT_TRUE(fast_strtod_ok("1.E-8"));
EXPECT_TRUE(fast_strtod_ok("1.E+8"));
EXPECT_TRUE(fast_strtod_ok("+1.e8"));
EXPECT_TRUE(fast_strtod_ok("+1.e-8"));
EXPECT_TRUE(fast_strtod_ok("+1.e+8"));
EXPECT_TRUE(fast_strtod_ok("+1.E8"));
EXPECT_TRUE(fast_strtod_ok("+1.E-8"));
EXPECT_TRUE(fast_strtod_ok("+1.E+8"));
EXPECT_TRUE(fast_strtod_ok("-1.e8"));
EXPECT_TRUE(fast_strtod_ok("-1.e-8"));
EXPECT_TRUE(fast_strtod_ok("-1.e+8"));
EXPECT_TRUE(fast_strtod_ok("-1.E8"));
EXPECT_TRUE(fast_strtod_ok("-1.E-8"));
EXPECT_TRUE(fast_strtod_ok("-1.E+8"));
EXPECT_TRUE(fast_strtod_ok(".1e8"));
EXPECT_TRUE(fast_strtod_ok(".1e-8"));
EXPECT_TRUE(fast_strtod_ok(".1e+8"));
EXPECT_TRUE(fast_strtod_ok(".1E8"));
EXPECT_TRUE(fast_strtod_ok(".1E-8"));
EXPECT_TRUE(fast_strtod_ok(".1E+8"));
EXPECT_TRUE(fast_strtod_ok("+.1e8"));
EXPECT_TRUE(fast_strtod_ok("+.1e-8"));
EXPECT_TRUE(fast_strtod_ok("+.1e+8"));
EXPECT_TRUE(fast_strtod_ok("+.1E8"));
EXPECT_TRUE(fast_strtod_ok("+.1E-8"));
EXPECT_TRUE(fast_strtod_ok("+.1E+8"));
EXPECT_TRUE(fast_strtod_ok("-.1e8"));
EXPECT_TRUE(fast_strtod_ok("-.1e-8"));
EXPECT_TRUE(fast_strtod_ok("-.1e+8"));
EXPECT_TRUE(fast_strtod_ok("-.1E8"));
EXPECT_TRUE(fast_strtod_ok("-.1E-8"));
EXPECT_TRUE(fast_strtod_ok("-.1E+8"));
EXPECT_TRUE(fast_strtod_ok("1.2e8"));
EXPECT_TRUE(fast_strtod_ok("1.2e-8"));
EXPECT_TRUE(fast_strtod_ok("1.2e+8"));
EXPECT_TRUE(fast_strtod_ok("1.2E8"));
EXPECT_TRUE(fast_strtod_ok("1.2E-8"));
EXPECT_TRUE(fast_strtod_ok("1.2E+8"));
EXPECT_TRUE(fast_strtod_ok("+1.2e8"));
EXPECT_TRUE(fast_strtod_ok("+1.2e-8"));
EXPECT_TRUE(fast_strtod_ok("+1.2e+8"));
EXPECT_TRUE(fast_strtod_ok("+1.2E8"));
EXPECT_TRUE(fast_strtod_ok("+1.2E-8"));
EXPECT_TRUE(fast_strtod_ok("+1.2E+8"));
EXPECT_TRUE(fast_strtod_ok("-1.2e8"));
EXPECT_TRUE(fast_strtod_ok("-1.2e-8"));
EXPECT_TRUE(fast_strtod_ok("-1.2e+8"));
EXPECT_TRUE(fast_strtod_ok("-1.2E8"));
EXPECT_TRUE(fast_strtod_ok("-1.2E-8"));
EXPECT_TRUE(fast_strtod_ok("-1.2E+8"));
}
TEST_CASE(TestFastStrtodPrecision)
{
MersenneTwister rng;
for (size_t i = 0; i < 1000; ++i)
{
const double mantissa = rand_double1(rng, -1.0, 1.0);
const int exponent = rand_int1(rng, -300, 300);
const double value = ldexp(mantissa, exponent);
char str[1000];
sprintf(str, "%.16e", value);
EXPECT_TRUE(fast_strtod_ok(str));
}
}
TEST_CASE(MakeSafeFilename_GivenSafeFilename_ReturnsFilenameUnchanged)
{
const string result = make_safe_filename("hello-world_42.txt");
EXPECT_EQ("hello-world_42.txt", result);
}
TEST_CASE(MakeSafeFilename_GivenUnsafeFilename_ReturnsSafeFilename)
{
const string result = make_safe_filename("hello/world !.txt");
EXPECT_EQ("hello_world__.txt", result);
}
TEST_CASE(Capitalize_GivenEmptyString_ReturnsEmptyString)
{
const string result = capitalize("");
EXPECT_EQ("", result);
}
TEST_CASE(Capitalize_GivenBlankString_ReturnsInputString)
{
const string result = capitalize(" ");
EXPECT_EQ(" ", result);
}
TEST_CASE(Capitalize_GivenSingleWord_ReturnsCapitalizedWord)
{
const string result = capitalize("aB");
EXPECT_EQ("Ab", result);
}
TEST_CASE(Capitalize_GivenTwoWords_ReturnsCapitalizedWords)
{
const string result = capitalize("aB c");
EXPECT_EQ("Ab C", result);
}
TEST_CASE(Capitalize_GivenSingleWordSurroundedByBlanks_ReturnsInputStringWithCapitalizedWord)
{
const string result = capitalize(" heLLo ");
EXPECT_EQ(" Hello ", result);
}
TEST_CASE(Capitalize_GivenTwoWordsSurroundedByBlanks_ReturnsInputStringWithCapitalizedWords)
{
const string result = capitalize(" hello CUTE carrot ");
EXPECT_EQ(" Hello Cute Carrot ", result);
}
TEST_CASE(TestPrettyUInt)
{
EXPECT_EQ("0", pretty_uint(0));
EXPECT_EQ("1", pretty_uint(1));
EXPECT_EQ("10", pretty_uint(10));
EXPECT_EQ("100", pretty_uint(100));
EXPECT_EQ("1,000", pretty_uint(1000));
EXPECT_EQ("10,000", pretty_uint(10000));
EXPECT_EQ("100,000", pretty_uint(100000));
EXPECT_EQ("1,000,000", pretty_uint(1000000));
}
TEST_CASE(PrettyIntHandlesPositiveValues)
{
EXPECT_EQ("0", pretty_int(0));
EXPECT_EQ("1", pretty_int(1));
EXPECT_EQ("10", pretty_int(10));
EXPECT_EQ("100", pretty_int(100));
EXPECT_EQ("1,000", pretty_int(1000));
EXPECT_EQ("10,000", pretty_int(10000));
EXPECT_EQ("100,000", pretty_int(100000));
EXPECT_EQ("1,000,000", pretty_int(1000000));
}
TEST_CASE(PrettyIntHandlesNegativeValues)
{
EXPECT_EQ("0", pretty_int(-0));
EXPECT_EQ("-1", pretty_int(-1));
EXPECT_EQ("-10", pretty_int(-10));
EXPECT_EQ("-100", pretty_int(-100));
EXPECT_EQ("-1,000", pretty_int(-1000));
EXPECT_EQ("-10,000", pretty_int(-10000));
EXPECT_EQ("-100,000", pretty_int(-100000));
EXPECT_EQ("-1,000,000", pretty_int(-1000000));
}
TEST_CASE(PrettyScalarHandlesPositiveValues)
{
EXPECT_EQ("0.0", pretty_scalar(0));
EXPECT_EQ("1.0", pretty_scalar(1));
EXPECT_EQ("3.1", pretty_scalar(3.1));
EXPECT_EQ("3.1", pretty_scalar(3.14));
EXPECT_EQ("3.14", pretty_scalar(3.14, 2));
EXPECT_EQ("3.142", pretty_scalar(3.1415, 3));
}
TEST_CASE(PrettyScalarHandlesNegativeValues)
{
EXPECT_EQ("0.0", pretty_scalar(-0));
EXPECT_EQ("-1.0", pretty_scalar(-1));
EXPECT_EQ("-3.1", pretty_scalar(-3.1));
EXPECT_EQ("-3.1", pretty_scalar(-3.14));
EXPECT_EQ("-3.14", pretty_scalar(-3.14, 2));
EXPECT_EQ("-3.142", pretty_scalar(-3.1415, 3));
}
TEST_CASE(TestPrettyTime)
{
const double S = 1.0;
const double M = 60.0 * S;
const double H = 60.0 * M;
const double D = 24.0 * H;
const double W = 7.0 * D;
EXPECT_EQ("0 ms", pretty_time(0.0));
EXPECT_EQ("1 ms", pretty_time(0.001));
EXPECT_EQ("500 ms", pretty_time(0.5));
EXPECT_EQ("999 ms", pretty_time(0.999));
EXPECT_EQ("1.0 second", pretty_time(1 * S));
EXPECT_EQ("1.5 second", pretty_time(1 * S + 0.500));
EXPECT_EQ("1.001 second", pretty_time(1 * S + 0.001, 3));
EXPECT_EQ("1 minute 0.0 second", pretty_time(1 * M));
EXPECT_EQ("2 minutes 0.0 second", pretty_time(2 * M));
EXPECT_EQ("2 minutes 30.0 seconds", pretty_time(2 * M + 30 * S));
EXPECT_EQ("2 minutes 30.001 seconds", pretty_time(2 * M + 30 * S + 0.001, 3));
EXPECT_EQ("1 hour 0 minute 0.0 second", pretty_time(1 * H));
EXPECT_EQ("2 hours 0 minute 0.0 second", pretty_time(2 * H));
EXPECT_EQ("2 hours 30 minutes 0.0 second", pretty_time(2 * H + 30 * M));
EXPECT_EQ("2 hours 30 minutes 15.0 seconds", pretty_time(2 * H + 30 * M + 15 * S));
EXPECT_EQ("2 hours 30 minutes 15.001 seconds", pretty_time(2 * H + 30 * M + 15 * S + 0.001, 3));
EXPECT_EQ("1 day 0 hour 0 minute 0.0 second", pretty_time(1 * D));
EXPECT_EQ("2 days 0 hour 0 minute 0.0 second", pretty_time(2 * D));
EXPECT_EQ("2 days 12 hours 0 minute 0.0 second", pretty_time(2 * D + 12 * H));
EXPECT_EQ("2 days 12 hours 30 minutes 0.0 second", pretty_time(2 * D + 12 * H + 30 * M));
EXPECT_EQ("2 days 12 hours 30 minutes 15.0 seconds", pretty_time(2 * D + 12 * H + 30 * M + 15 * S));
EXPECT_EQ("2 days 12 hours 30 minutes 15.001 seconds", pretty_time(2 * D + 12 * H + 30 * M + 15 * S + 0.001, 3));
EXPECT_EQ("1 week 0 day 0 hour 0 minute 0.0 second", pretty_time(1 * W));
EXPECT_EQ("2 weeks 0 day 0 hour 0 minute 0.0 second", pretty_time(2 * W));
EXPECT_EQ("2 weeks 3 days 0 hour 0 minute 0.0 second", pretty_time(2 * W + 3 * D));
EXPECT_EQ("2 weeks 3 days 12 hours 0 minute 0.0 second", pretty_time(2 * W + 3 * D + 12 * H));
EXPECT_EQ("2 weeks 3 days 12 hours 30 minutes 0.0 second", pretty_time(2 * W + 3 * D + 12 * H + 30 * M));
EXPECT_EQ("2 weeks 3 days 12 hours 30 minutes 15.0 seconds", pretty_time(2 * W + 3 * D + 12 * H + 30 * M + 15 * S));
EXPECT_EQ("2 weeks 3 days 12 hours 30 minutes 15.001 seconds", pretty_time(2 * W + 3 * D + 12 * H + 30 * M + 15 * S + 0.001, 3));
}
TEST_CASE(TestPrettyTimeWithPrecisionSetToZero)
{
EXPECT_EQ("1 second", pretty_time(1.001, 0));
EXPECT_EQ("1 second", pretty_time(1.999, 0));
EXPECT_EQ("1 minute 59 seconds", pretty_time(119.9, 0));
}
TEST_CASE(TestPrettyTimeWithTimeValueSmallerThanOneSecond)
{
EXPECT_EQ("10 ms", pretty_time(0.01, 0));
EXPECT_EQ("10 ms", pretty_time(0.01, 3));
EXPECT_EQ("10.0 ms", pretty_time(0.01, 4));
}
}
| Vertexwahn/appleseed | src/appleseed/foundation/meta/tests/test_string.cpp | C++ | mit | 30,223 |
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
"os"
"math/rand"
"time"
scalarmWorker "github.com/scalarm/scalarm_simulation_manager_go/scalarmWorker"
)
// VERSION current version of the app
const VERSION string = "17.04"
// Fatal utility function to log a fatal error
func Fatal(err error) {
fmt.Printf("[Fatal error] %v\n", err)
os.Exit(1)
}
func main() {
fmt.Printf("[SiM] Scalarm Simulation Manager, version: %s\n", VERSION)
rand.Seed(time.Now().UTC().UnixNano())
// 0. remember current location
rootDirPath, _ := os.Getwd()
fmt.Printf("[SiM] working directory: %s\n", rootDirPath)
// 1. load config file
config, err := scalarmWorker.CreateSimulationManagerConfig("config.json")
if err != nil {
Fatal(err)
}
// 2. prepare HTTP client
var client *http.Client
tlsConfig := tls.Config{InsecureSkipVerify: config.InsecureSSL}
if config.ScalarmCertificatePath != "" {
CAPool := x509.NewCertPool()
severCert, err := ioutil.ReadFile(config.ScalarmCertificatePath)
if err != nil {
Fatal(fmt.Errorf("Could not load Scalarm certificate"))
}
CAPool.AppendCertsFromPEM(severCert)
tlsConfig.RootCAs = CAPool
}
client = &http.Client{Transport: &http.Transport{TLSClientConfig: &tlsConfig}}
// 3. create simulation manager instance and run it
sim := scalarmWorker.SimulationManager{
Config: config,
HttpClient: client,
RootDirPath: rootDirPath,
}
sim.Run()
}
| Scalarm/scalarm_simulation_manager_go | scalarmSimulationManager.go | GO | mit | 1,451 |
<?php
/******************************************************************************
Project: Fram3w0rk PHP 0.5 [Alpha]
Website: http://LawtonSoft.com/projects/fram3w0rk
Author: Jonathan Lawton (wanathan101@gmail.com)
Contributers: none, yet :-( (Come join in!)
Copyright (c) 2012+, LawtonSoft. All rights reserved.
TERMS AND CONDITIONS
Revised: Oct 1, 2013
"Source" includes all files and processes included in previous, current and
future versions of this project except where 3rd party source may also be
included. You must follow the terms and conditions of individual 3rd party
sources as stated by their own accord.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Jonathan Lawton nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
* These Terms and Conditions may change at any time without given
notice at which point these will become replaced and inherited by the
newest copy included in the source or at:
[http://www.fram3w0rk.com/software/terms/].
WARRANTY
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright owner or contributors of this
Source be liable for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of substitute
goods or services; loss of use, data, or profits; or business interruption)
however caused and on any theory of liability, whether in contract, strict
liability, or tort (including negligence or otherwise) arising in any way out
of the use of this software, even if advised of the possibility of such damage.
3rd party sources must be treated separately. Source used within the project
but owned separately is void of this project and provided "as is" with
attribution.
*******************************************************************************
Now that we're past all the boring stuff...
Welcome to Fram3w0rk! Fram3w0rk is an open-source framework designed to connect
and unify code across programming languages, making it easier to learn, retain,
and code.
Fram3w0rk PHP is the respective PHP framework for building PHP website
applications.
******************************************************************************/
// Initite Fram3w0rk
Instance::initiate();
// Create instances for classes
class Instance {
// -- INITIATE FRAM3W0RK --
public static function initiate() {
error_reporting(E_ALL ^ E_NOTICE);
define(__ROOT__, $_SERVER[HTTP_HOST]);
self::$import = array(
'log/index.php',
'curl/index.php',
'dbi/index.php',
'ftp/index.php',
'session/index.php'
);
self::load();
}
// -- LOAD FILES --
// Use the following list to include additional classes
public static $import = array();
public static function load() {
$args = func_get_args();
if(isset(self::$import) && !empty(self::$import)) {
$import = self::$import;
foreach(self::$import as $file) {
$file = (isset($args[0]) && !empty($args[0]) ? $args[0] : '') . $file;
require_once($file);
}
}
}
// -- INSTANCES --
private static $constructor = array();
public static function get($class = null, $id = 0) {
if(!isset($class::$instance[$id])) $class::$instance[$id] = new $class($constructor);
return $class::$instance[$id];
}
}
// If user loads in page.
if(strtolower(realpath(__FILE__)) == strtolower(realpath($_SERVER['SCRIPT_FILENAME']))):
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fram3w0rk</title>
<!-- Latest compiled and minified jQuery -->
<script src="//code.jquery.com/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="navbar navbar-default navbar-static-top navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-header">
<a class="navbar-brand" href="#">Fram3w0rk</a>
</div>
<div class="collapse navbar-collapse bs-js-navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>
<li><a href="#about" data-toggle="tab">About</a></li>
<li><a href="#faq" data-toggle="tab">FAQ</a></li>
<li><a href="#getting-started" data-toggle="tab">Getting Started</a></li>
<li class="dropdown">
<a id="drop1" href="#" role="button" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
<ul class="dropdown-menu" role="menu" aria-labelledby="drop1">
<?php
$files = scandir('.');
foreach($files as $file) {
if(!in_array($file, array('.', '..')) && file_exists($file . '/index.php')) echo "\t\t\t\t\t\t\t" . '<li><a href="#classes-' . $file . '" data-toggle="tab">' . strToUpper($file) . '</a></li>' . "\n";
}
?>
</ul>
</li>
<li><a href="#other-resources" data-toggle="tab">Other Resources</a></li>
<li><a href="#credits" data-toggle="tab">Credits</a></li>
</ul>
<a class="nav navbar-nav navbar-right navbar-brand" href="#">PHP v0.5 [Alpha]</a>
</div><!--/.nav-collapse -->
</div>
<div class="container" style="padding-top: 50px">
<div class="tab-content">
<div class="tab-pane active" id="home">
<article>
<h1>Welcome to Fram3w0rk PHP!</h1>
<p>Fram3w0rk is an open-source framework designed to connect and unify code across programming languages, making it easier to learn, retain, and code. Fram3w0rk PHP is the respective PHP framework for building PHP website applications.</p>
</article>
</div>
<div class="tab-pane" id="about">
<h1>About</h1>
</div>
<div class="tab-pane" id="faq">
<h1>FAQ</h1>
</div>
<div class="tab-pane" id="getting-started">
<h1>Getting Started</h1>
<h2>Implementing Fram3w0rk</h2>
<p>Fram3w0rk is based on the singleton pattern logic. The first thing you will need to do is impliment this file into your PHP script. Start with <code><?php> require_once('{directory to Fram3w0rk}/index.php'); ?></code>. That is all that you need to do to start using Fram3w0rk!</p>
<h2>Instantiating Class Instances</h2>
<p>One core class will be implimented immediately upon implimentation. All others will need to be instantiated. Let's dig in. . .</p>
<p>Upon implimenting the core Fram3w0rk PHP file into your code (as shown above), the <code>Log</code> class will be made immediately available. <a href="#classes-log" data-toggle="tab">This class</a> records logs for errors and successes used within other classes and can be used in other code such as your own. Read the documentation for more info.</p>
<p>To impliment any class, use the static method <code>$className = Instance::get('className');</code> to return a new object instance of a class.</p>
</div>
<?php
$files = scandir('.');
foreach($files as $file) {
if(!in_array($file, array('.', '..')) && file_exists($file . '/index.php')) {
?>
<div class="tab-pane" id="classes-<?php echo $file; ?>">
<h1>Classes</h1>
<h2><?php echo strToUpper($file); ?></h2>
<?php
$handle = fopen($file . '/index.php', 'r');
echo fread($handle, filesize($file . '/index.php'));
fclose($handle);
?>
</div>
<?php
}
}
?>
<div class="tab-pane" id="other-resources">
<h1>Other Resources</h1>
<h6><a target="_blank" href="http://www.lawtonsoft.com/fram3work">Fram3w0rk</a></h6>
<h6><a target="_blank" href="http://php.net/">PHP.net</a></h6>
</div>
<div class="tab-pane" id="credits">
<h1>Credits</h1>
<p>We would like to acknowledge the help of those who have contibuted to Fram3w0rk.</p>
<dl>
<dt>Created By</dt>
<dd>Jonathan Lawton</dd>
<dt>Project Manager</dt>
<dd>Jonathan Lawton</dd>
<dt>Lead Developer</dt>
<dd>Jonathan Lawton</dd>
<dt>Developers</dt>
<dd></dd>
<dd></dd>
<dd><a target="_blank" href="http://lawtonsoft.com/projects/fram3w0rk/">Get involved today!</a></dd>
<dt>Sponsored By</dt>
<dd></dd>
<dt>Special Thanks & Acknowledgement</dt>
<dd><a target="_blank" href="http://php.net/">The PHP Group</a></dd>
<dd><a target="_blank" href="http://jquery.com/">The jQuery Foundation</a></dd>
<dd><a target="_blank" href="http://getbootstrap.com/">Bootstrap</a></dd>
</dl>
</div>
</div>
<footer>
<p>Copyright (c) 2012+, Jonathan Lawton. All Rights reserved.</p>
</footer>
</div>
</body>
</html>
<?php endif; ?>
| LawtonSoft/Fram3w0rk-PHP | index.php | PHP | mit | 9,806 |
class Hamming
VERSION = 1.freeze
def self.compute strand_1, strand_2
distance = 0
if not (strand_1 || strand_2)
raise ArgumentError
elsif strand_1.length != strand_2.length
raise ArgumentError
else
strand_1.split("").each_with_index do |strand, index|
if strand_2[index] != strand
distance += 1
end
end
end
distance
end
end
| alexggordon/exercism | ruby/hamming/hamming.rb | Ruby | mit | 405 |
/**
* MIT License
*
* Copyright (c) 2016 Derek Goslin < http://corememorydump.blogspot.ie/ >
*
* 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 Newtonsoft.Json;
namespace DDPAIDash.Core.Types
{
public class DeviceInfo
{
[JsonProperty("nickname")]
public string Nickname { get; private set; }
[JsonProperty("ordernum")]
public string OrderNumber { get; private set; }
[JsonProperty("model")]
public string Model { get; private set; }
[JsonProperty("version")]
public string Version { get; private set; }
[JsonProperty("uuid")]
public string Uuid { get; private set; }
[JsonProperty("macaddr")]
public string MacAddr { get; private set; }
[JsonProperty("chipsn")]
public string ChipSerialNumber { get; private set; }
[JsonProperty("legalret")]
public int LegalRet { get; private set; }
[JsonProperty("btnver")]
public int ButtonVersion { get; private set; }
[JsonProperty("totalruntime")]
public int TotalRuntime { get; private set; }
[JsonProperty("sdcapacity")]
public int SdCapacity { get; private set; }
[JsonProperty("sdspare")]
public int SdSpare { get; private set; }
[JsonProperty("hbbitrate")]
public int HbBitrate { get; private set; }
[JsonProperty("hsbitrate")]
public int HsBitrate { get; private set; }
[JsonProperty("mbbitrate")]
public int MbBitrate { get; private set; }
[JsonProperty("msbitrate")]
public int MsBitrate { get; private set; }
[JsonProperty("lbbitrate")]
public int LbBitrate { get; private set; }
[JsonProperty("lsbitrate")]
public int LsBitrate { get; private set; }
[JsonProperty("default_user")]
public string DefaultUser { get; private set; }
[JsonProperty("is_neeed_update")]
public bool IsNeeedUpdate { get; private set; }
[JsonProperty("edog_model")]
public string EdogModel { get; private set; }
[JsonProperty("edog_version")]
public string EDogVersion { get; private set; }
[JsonProperty("edog_status")]
public bool EDogStatus { get; private set; }
}
} | DerekGn/DDPAIDash | DDPAIDash.Core/Types/DeviceInfo.cs | C# | mit | 3,314 |
import React from 'react';
import Example from './Example';
import Tooltip from '../../src/Tooltip';
import Icon from '../../src/Icon';
export default ( props ) => (
<section { ...props }>
<h3>Tooltips</h3>
<Example>
<Tooltip label="Follow">
<Icon name="add" />
</Tooltip>
<Tooltip large label="Print">
<Icon name="print" />
</Tooltip>
</Example>
<Example>
<Tooltip
label={
<span>
Upload <strong>file.zip</strong>
</span>
}
>
<Icon name="cloud_upload" />
</Tooltip>
<Tooltip label={
<span>
Share your content<br />
via social media
</span>
}>
<Icon name="share" />
</Tooltip>
</Example>
</section>
);
| joshq00/react-mdl | demo/sections/Tooltips.js | JavaScript | mit | 1,004 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\Question */
$this->title = 'Update: ' . $model->question;
$this->params['breadcrumbs'][] = ['label' => 'Questions', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->question, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="question-update">
<h1><span class="glyphicon glyphicon-question-sign"></span> <?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| umbalaconmeogia/brse-interview | src/app/views/question/update.php | PHP | mit | 586 |
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { firestore } from 'firebase/app';
import { AppService } from '../../app.service';
import { environment } from '../../../environments/environment';
@Component({
selector: 'app-list-access',
templateUrl: './list-access.component.html',
styleUrls: ['./list-access.component.css']
})
export class ListAccessComponent implements OnInit, OnDestroy {
lists: Observable<any[]>;
members: any[];
selected: boolean;
erro: string;
listname: string;
listkey: string;
email: string;
len: number = 0;
sub: any;
title: string = this.appService.language["t5"];
constructor(
private appService: AppService
) { }
ngOnInit() {
this.lists = this.appService.afs.collection('lists', ref => ref.where('access.'+this.appService.user.email.replace(/\./g,'´'),'==',true))
.snapshotChanges()
.pipe(map(lists => {
this.len = lists.length;
if (localStorage.getItem('lastList')) {
let result = lists.find(list => list.payload.doc.id == localStorage.getItem('lastList'));
if (result != undefined) {
const data = result.payload.doc.data();
const id = result.payload.doc.id;
this.onSelectList({ id, ...(data as {}) });
}
}
return lists
.sort(
(a,b) => a.payload.doc.data()["listname"].localeCompare(b.payload.doc.data()["listname"]))
.map(list => {
const data = list.payload.doc.data();
const id = list.payload.doc.id;
return { id, ...(data as {}) };
})
}));
}
ngOnDestroy() {
if (this.sub != undefined)
this.sub.unsubscribe();
}
onSelectList(l): void {
this.selected = true;
this.erro = '';
this.listname = l.listname;
this.listkey = l.id;
this.title = l.listname;
localStorage.setItem('lastList', l.id);
this.sub = this.appService.afs.collection('lists').doc(this.listkey)
.snapshotChanges()
.subscribe(list => {
let temp = [];
try {
for (let key in list.payload.data()["access"]) {
temp.push({
email: key.replace(/´/g,'.')
});
}
} catch {}
this.members = temp;
});
}
Include() {
let email = this.email;
if (this.members && this.members.length >= environment.limit_access)
this.erro = this.appService.language.e18;
else if (!navigator.onLine)
this.erro = this.appService.language.e12;
else if (!email || email == '') {
this.erro = this.appService.language.e14;
navigator.vibrate([500]);
} else {
this.appService.afs.collection('lists').doc(this.listkey).update({
['access.'+email.toLowerCase().replace(/\./g,'´')]: true
});
this.erro = '';
this.email = '';
}
}
onRemove(member): void {
if (!navigator.onLine)
this.erro = this.appService.language.e12;
else if (this.members.length > 1) {
if (confirm(this.appService.language.m7))
this.appService.afs.collection('lists').doc(this.listkey).update({
['access.'+member.email.replace(/\./g,'´')]: firestore.FieldValue.delete()
});
} else {
this.erro = this.appService.language.e10;
}
}
}
| felipecota/realtimeapp | src/app/app-list/list-access/list-access.component.ts | TypeScript | mit | 3,523 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Model_cadospres extends CI_Model {
public $table = 'dospres_calon_dosen_berprestasi';
public $id = 'id_calon_dospres';
public function data()
{
$query = $this->db->get('dospres_calon_dosen_berprestasi');
return $query->result_array();
}
public function findData($id)
{
$hasil = $this->db->where('id_calon_dospres', $id)
->limit(1)
->get('dospres_calon_dosen_berprestasi');
if ($hasil->num_rows() > 0) {
return $hasil->row();
} else {
return array();
}
}
public function addData($data)
{
$this->db->insert('dospres_calon_dosen_berprestasi', $data);
return TRUE;
}
public function deleteData($id)
{
$this->db->where('id_calon_dospres', $id)
->delete('dospres_calon_dosen_berprestasi');
}
public function updateData($id, $data_cadospres)
{
$this->db->where('id_calon_dospres', $id)
->update('dospres_calon_dosen_berprestasi', $data_cadospres);
}
}
| Lective/newdospres | application/modules/lv_webmin/models/Model_cadospres.php | PHP | mit | 1,092 |
<?php
return [
'welcome' => 'Bienvenido a apiato',
];
| Drummer01/ForestChat | app/Containers/Localization/Resources/Languages/es/messages.php | PHP | mit | 61 |
package net.creeperhost.chtweaks;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import java.util.Random;
public class ModEvents {
private static final int SPAWN_RATIO = 8;
@SubscribeEvent
public void onLivingDeathEvent(LivingDeathEvent event) {
if (isServer(event.entity.worldObj) && event.entity != null && isHostile(event.entity)) {
Random randomGenerator = new Random();
if(randomGenerator.nextInt(100) > 80) {
int amount = ((int) event.entityLiving.getMaxHealth() / SPAWN_RATIO);
if(amount > 0) spawnStackAtEntity(event, new ItemStack(Items.gold_nugget, randInt(1, amount)));
}
}
}
private boolean isServer(World world) {
return !world.isRemote;
}
private boolean isHostile(Entity entity) {
return entity instanceof EntityMob;
}
private void spawnStackAtEntity(LivingDeathEvent event, ItemStack stack) {
World world = event.entity.worldObj;
EntityItem item = new EntityItem(world, event.entity.posX, event.entity.posY, event.entity.posZ, stack);
world.spawnEntityInWorld(item);
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
| CreeperHost/CH-Tweaks | src/main/java/net/creeperhost/chtweaks/ModEvents.java | Java | mit | 1,503 |
module Compass::Magick
module Plugins
# Applies rounded corners around the {Canvas}.
#
# @param [Sass::Script::Number] radius The corner radius.
# @param [Sass::Script::Bool] top_left Controls the top-left corner
# radius effect (default <tt>true</tt>)
# @param [Sass::Script::Bool] top_right Controls the top-right corner
# radius effect (default <tt>true</tt>)
# @param [Sass::Script::Bool] bottom_right Controls the bottom-right
# corner radius effect (default <tt>true</tt>)
# @param [Sass::Script::Bool] bottom_left Controls the bottom-left
# corner radius effect (default <tt>true</tt>)
# @return {Command} A command(-set) which applies the corners on the
# canvas.
def magick_corners(radius, top_left = nil, top_right = nil, bottom_right = nil, bottom_left = nil)
Command.new do |canvas|
Canvas.new(canvas, magick_mask(
magick_canvas(
Sass::Script::Number.new(canvas.width),
Sass::Script::Number.new(canvas.height),
magick_fill(Sass::Script::Color.new([0, 0, 0])),
magick_border(Sass::Script::Color.new([255, 255, 255]), radius, nil, top_left, top_right, bottom_right, bottom_left)
)
))
end
end
end
end
| StanAngeloff/compass-magick | lib/plugins/corners.rb | Ruby | mit | 1,284 |
<?php
require "help-head.php";
?>
<style>
a.r:hover{color:#009900}
a.r{color:#ff3333}
</style>
<div align="center">
<img src="../imgb/title-8.jpg" hspace="10" vspace="10" border="1">
</div>
<div class="c4">
System of astrometric databases of Pulkovo observatory.
</div>
<hr width="90%">
<div align="center">
<a href="ds.php" class="r">
To database request form
</a>
<?php echo HB; echo EM; echo MP; ?>
</div>
<hr width="90%">
<!--********************************************************************-->
<div class="c4">
Pulkovo database of observations of visual double stars
</div>
<br>
<!--********************************************************************-->
<? echo TAB1 ?>
<td class='img'>
<img src="http://www.puldb.ru/imgb/61cyg.jpg" title="61 Cygni">
<br clear='left'>
<center>61 Cygni</center>
<!--********************************************************************-->
<br><br><br>
<img src="http://www.puldb.ru/imgb/orbita61.jpg" title="61 Cygni">
<br clear='left'>
<center>Orbit of 61Cyg</center>
</td>
<!--********************************************************************-->
<td>
Observations of visual double stars at Pulkovo continue stellar astronomy
studies, which were started by F. Struve in 19 century and have become traditional
for Pulkovo observatory.
The scientific purpose of Pulkovo program of complex study of
visual double stars is the determination of basic kinematic and dynamic
properties of double and multiple stars located in neighbourhood of the Sun.
The first goal of this program is to find close (up to 100 parsec) double stars,
which have significate proper motion.
The next goal is to obtain dense homogeneous series of relative positions
of double star components for the determination of their orbits and masses,
and for revelation of possible invisible satellites.
<br>
Till 1941 observations of double stars were performed, mostly, on the Normal
Astrograph, and since 1960 and till present time they have been performed on
26-inch refractor of Pulkovo observatory.
Till 1995 there were only photographical observations, and since autumn of
1995 - photographical and CCD observations.
<hr width="30%">
The 3rd database contains relative positions of selected double and multiple
stars, and stars with possible invisible satellites.
The database requires catalog of relative positions of visual double stars,
based on photographic observations performed since 1960 on Pulkovo 26-inch
refractor, and similar catalog based on CCD observations, obtained since 1995.
The database also requires results if long-term observation series of ADS7251
and 61 Cygni.
Presented material makes it possible to determine orbits and masses of double
stars, and to perform various studies in stellar astronomy.
<br>
<a href='http://www.puldb.ru/pulcat/double_pub.html'>Publications</a>
</td>
<? echo TAB2 ?>
<!--********************************************************************-->
</body>
</html>
| NordWest/puldbru | help9.php | PHP | mit | 3,134 |
import { VNode } from "@cycle/dom";
let counter = 0;
export function getScope(): string {
return `cs-ui${++counter}`;
}
export function capitalize(string: string): string {
return string ? string.charAt(0).toUpperCase() + string.slice(1) : string;
}
export function patchClassList(target: VNode, classes: string[], classesToAdd: string) {
let className = "";
if (target.data) {
let props = target.data.props ? target.data.props : { className: target.sel.split(".").join(" ") };
let classList = props.className.split(" ") as Array<string>;
classList.forEach(item => {
if (classes.indexOf(item) === -1) {
className += item + " ";
}
});
}
className += classesToAdd;
return Object.assign({}, target.data, {
"props": {
className
}
});
}
/**
* Adds one VNode to another and handles updates for stream by replacing based on the identifier class.
* @param {VNode} element The element to be added.
* @param {VNode} target The target for the element
* @param {string} identifier The identifying class for the element to be added.
* @return {Array} The target element's children with the element added.
*/
export function addElement(element: VNode, target: VNode, identifier: string): Array<VNode> {
let c = [];
if (target.children) {
c = target.children;
}
if (target.text) {
c.push(target.text);
}
for (let i = 0; i < c.length; i++) {
let child = c[i];
let cProps = child.data ? child.data.props ? child.data.props : {} : {};
if (typeof (child) !== "undefined" && typeof (cProps.className) !== "undefined") {
let classList = child.data.props.className.split(" ") as Array<string>;
for (let s of classList) {
if (s === identifier) {
c.splice(i, 1);
}
}
}
}
c.push(element);
return c;
}
/**
* Converts a natural number between 1-16 to text.
* @param {number} num The number to convert.
* @return {string} That number as text.
*/
export function numToText(num: number): string {
switch (num) {
case 1: return " one";
case 2: return " two";
case 3: return " three";
case 4: return " four";
case 5: return " five";
case 6: return " six";
case 7: return " seven";
case 8: return " eight";
case 9: return " nine";
case 10: return " ten";
case 11: return " eleven";
case 12: return " twelve";
case 13: return " thirteen";
case 14: return " fourteen";
case 15: return " fifteen";
case 16: return " sixteen";
default: return " one";
}
}
export function deepArrayCopy(obj: any[])
{
return JSON.parse(JSON.stringify(obj));
}
| Steelfish/cycle-semantic-ui | src/utils/index.ts | TypeScript | mit | 2,665 |
package gruppe087.coursetracker;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;
public class MissedFragment extends Fragment {
ListView missedListView;
ArrayList<String> listItems;
HttpGetRequest getRequest;
UserCourseAdapter userCourseAdapter;
SharedPreferences settings;
MissedListAdapter<String> arrayAdapter;
View rootView;
LectureAdapter lectureAdapter;
UserLectureAdapter userLectureAdapter;
private Boolean active;
private Boolean missed;
Date dNow;
DateFormat timeFormat;
DateFormat dateFormat;
Boolean elementRemoved = false;
public void setMissed(Boolean missed){
this.missed = missed;
}
public boolean getMissed(){
return this.missed;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_missed, container, false);
timeFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dNow = new Date();
missedListView = (ListView) rootView.findViewById(R.id.missed_lv);
settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
active = true;
missedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(getActivity(), MissedLectureCurriculum.class);
String text = missedListView.getItemAtPosition(position).toString();
String courseId = text.split("\n|\t")[0];
String time = text.split("\n|\t")[3];
time = time + ":00";
time = time.substring(0,8);
String date = dateFormat.format(dNow);
updateCurriculum(courseId, date);
String curriculum = lectureAdapter.getCurriculum(courseId, date, time);
myIntent.putExtra("curriculum", curriculum);
getActivity().startActivity(myIntent);
}
});
listItems = createMissedList();
arrayAdapter = new MissedListAdapter<String>(getActivity().getApplicationContext(), R.layout.listitem, R.id.textview, listItems);
// DataBind ListView with items from SelectListAdapter
missedListView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
initListPrompt(0);
//initList();
return rootView;
}
private void updateCurriculum(String courseID, String date){
String result;
getRequest = new HttpGetRequest("getLecture.php");
try {
result = getRequest.execute("courseID", courseID, "date", date).get();
} catch (InterruptedException e) {
e.printStackTrace();
result=null;
} catch (ExecutionException e) {
e.printStackTrace();
result=null;
}
lectureAdapter.open();
userLectureAdapter.open();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
courseID = jsonObject.getString("courseID");
String time = jsonObject.getString("time");
String room = jsonObject.getString("room");
String curriculum = jsonObject.getString("curriculum");
time = time + ":00";
lectureAdapter.addCurriculum(courseID, date, time, room, curriculum);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
arrayAdapter.notifyDataSetChanged();
}
private ArrayList<String> createMissedList(){
ArrayList<String> returnList = new ArrayList<String>();
userCourseAdapter = new UserCourseAdapter(getContext());
userCourseAdapter.open();
ArrayList<String> courses = userCourseAdapter.getCoursesForUser(settings.getString("username", "default"));
TreeMap<Integer, String> sortMap = new TreeMap<Integer, String>();
lectureAdapter = new LectureAdapter(getContext());
userLectureAdapter = new UserLectureAdapter(getContext(), settings.getString("username", "default"));
lectureAdapter.open();
userLectureAdapter.open();
for (String courseID : courses){
String result;
getRequest = new HttpGetRequest("getTodayLecturesForCourse.php");
try {
result = getRequest.execute("courseID", courseID).get();
} catch (InterruptedException e) {
e.printStackTrace();
result=null;
} catch (ExecutionException e) {
e.printStackTrace();
result=null;
}
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
courseID = jsonObject.getString("courseID");
final String courseID2 = courseID;
final String courseName = jsonObject.getString("courseName");
final String time = jsonObject.getString("time");
final String room = jsonObject.getString("room");
final String date = jsonObject.getString("date");
String row = courseID + "\n" + courseName + "\nTid:\t" + time + "\nRom:\t" + room;
Integer hour = Integer.parseInt(time.split(":")[0]);
int timeValueLecture = Toolbox.timeToInt(time);
String time2 = time + ":00";
//timeValueLecture = timeValueLecture + 90;
sortMap.put(hour,row);
}
} catch (JSONException e) {
}
}
for (Map.Entry<Integer, String> entry : sortMap.entrySet()){
returnList.add(entry.getValue());
}
return returnList;
}
private void missedPrompt(int timeValueLecture, final int lectureID, String courseID, String time, final int index){
String timeNow = timeFormat.format(dNow);
int timeValueNow = Toolbox.timeToInt(timeNow);
if (timeValueNow > timeValueLecture && !userLectureAdapter.isAsked(lectureID)){
//lectureAdapter.setMissed(courseID, time, date, 0);
new AlertDialog.Builder(getActivity())
.setTitle("Attendance")
.setMessage("Did you attend the class in " + courseID + "\nat " + time.substring(0,5) + "?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// set the lecture to attended
userLectureAdapter.setMissed(lectureID, 0);
userLectureAdapter.setAsked(lectureID, 1);
listItems.remove(index);
elementRemoved = true;
arrayAdapter.notifyDataSetChanged();
arrayAdapter.notifyDataSetInvalidated();
if (index < listItems.size()){
initListPrompt(index);
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// set the lecture to be missed
userLectureAdapter.setMissed(lectureID, 1);
userLectureAdapter.setAsked(lectureID, 1);
elementRemoved = false;
arrayAdapter.notifyDataSetChanged();
arrayAdapter.notifyDataSetInvalidated();
if (index + 1 < listItems.size()){
initListPrompt(index + 1);
}
}
})
.show();
}
}
private void initListPrompt(int i){
int timeValueNow;
int timeValueLecture;
int lectureId;
String courseId;
String time;
Date dNow = new Date();
DateFormat dateValueFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
String thisTime = timeFormat.format(dNow);
timeValueNow = Toolbox.timeToInt(thisTime);
String thisDate = dateValueFormat.format(dNow);
if (listItems.size() == 0){
return;
}
courseId = listItems.get(i).split("\n|\t")[0];
time = listItems.get(i).split("\n|\t")[3];
String room = listItems.get(i).split("\n|\t")[5];
timeValueLecture = Toolbox.timeToInt(time);
time = time + ":00";
lectureId = lectureAdapter.getLectureID(courseId, thisDate, time, room);
if (lectureId == -1){
updateCurriculum(courseId, thisDate);
lectureId = lectureAdapter.getLectureID(courseId, thisDate, time, room);
}
if (timeValueNow < timeValueLecture){
listItems.remove(i);
if (i < listItems.size()){
initListPrompt(i);
}
}
if(userLectureAdapter.isAsked(lectureId)){
if (!userLectureAdapter.isMissed(lectureId)){
listItems.remove(i);
if (i < listItems.size()){
initListPrompt(i);
}
} else {
i++;
if (i < listItems.size()) {
initListPrompt(i);
}
}
}
missedPrompt(timeValueLecture, lectureId, courseId, time, i);
}
@Override
public void onStart() {
super.onStart();
active = true;
}
@Override
public void onPause() {
super.onPause();
active = false;
}
@Override
public void onStop() {
super.onStop();
active = false;
}
@Override
public void onResume() {
super.onResume();
arrayAdapter.notifyDataSetChanged();
active = true;
}
}
| henrikbossart/courseTracker | CourseTracker/app/src/main/java/gruppe087/coursetracker/MissedFragment.java | Java | mit | 11,686 |
#include "SpriteSheetRenderer.h"
#include "Utils.h"
namespace Cog {
SpriteSheetRenderer::SpriteSheetRenderer() {
buffers = map<string, SpriteLayer*>();
actualBuffer = nullptr;
}
SpriteSheetRenderer::~SpriteSheetRenderer() {
for (auto& buf : buffers) {
delete buf.second;
}
}
void SpriteSheetRenderer::LoadTexture(ofTexture * texture, string sheetName, int bufferSize, int zIndex, bool isExternal) {
if (buffers.count(sheetName) == 0) {
buffers[sheetName] = new SpriteLayer(zIndex);
}
ClearCounters(sheetName);
ClearTexture(sheetName);
ReallocateBuffer(sheetName, bufferSize);
actualBuffer->textureIsExternal = isExternal;
actualBuffer->texture = texture;
SetTexCoeffs(texture->getWidth(), texture->getHeight());
}
void SpriteSheetRenderer::ReallocateBuffer(string sheetName, int bufferSize) {
SetActualBuffer(sheetName);
actualBuffer->bufferSize = bufferSize;
if (actualBuffer->verts != nullptr)
delete[] actualBuffer->verts;
if (actualBuffer->coords != nullptr)
delete[] actualBuffer->coords;
if (actualBuffer->colors != nullptr)
delete[] actualBuffer->colors;
// 18 vertices for one quad (2 triangles and 3 axis -> 2*3*3)
actualBuffer->verts = new float[actualBuffer->bufferSize * 18];
// 12 texture coordinates for one quad (2 triangles and 2 axis -> 2*3*2)
actualBuffer->coords = new float[actualBuffer->bufferSize * 12];
// 24 colors for one quad (2 triangles and 4 channels -> 2*3*4)
actualBuffer->colors = new unsigned char[actualBuffer->bufferSize * 24];
actualBuffer->numSprites = 0;
ClearCounters(sheetName);
ClearTexture(sheetName);
}
bool SpriteSheetRenderer::AddTile(SpriteTile& tile) {
if (actualBuffer == nullptr || actualBuffer->texture == nullptr) {
ofLogError("Cannot add tile since there is no texture loaded");
return false;
}
if (actualBuffer->numSprites >= actualBuffer->bufferSize) {
ofLogError(string_format("Texture buffer overflown! Maximum number of sprites is set to %d", actualBuffer->bufferSize));
return false;
}
int vertexOffset = GetVertexOffset();
int colorOffset = GetColorOffset();
AddTexCoords(tile);
MakeQuad(vertexOffset, tile);
MakeColorQuad(colorOffset, tile.col);
actualBuffer->numSprites++;
return true;
}
bool SpriteSheetRenderer::AddRect(float x, float y, float z, float w, float h, float scale, float rot, ofColor& col) {
if (actualBuffer == nullptr || actualBuffer->texture == nullptr) {
ofLogError("Cannot add tile since there is no texture loaded");
return false;
}
if (actualBuffer->numSprites >= actualBuffer->bufferSize) {
ofLogError(string_format("Texture buffer overflown! Maximum number of sprites is set to %d", actualBuffer->bufferSize));
return false;
}
int vertexOffset = GetVertexOffset();
int colorOffset = GetColorOffset();
int coordOffset = GetCoordOffset();
w = w*scale / 2;
h = h*scale / 2;
// create vertices
MakeQuad(vertexOffset, x + GetX(-w, -h, rot), y + GetY(-w, -h, rot), z,
x + GetX(w, -h, rot), y + GetY(w, -h, rot), z,
x + GetX(-w, h, rot), y + GetY(-w, h, rot), z,
x + GetX(w, h, rot), y + GetY(w, h, rot), z);
MakeColorQuad(colorOffset, col);
int halfBrushSize = actualBuffer->textureCoeffX / 2;
AddTexCoords(coordOffset, brushX + halfBrushSize, brushY + halfBrushSize, brushX + halfBrushSize, brushY + halfBrushSize);
actualBuffer->numSprites++;
return true;
}
void SpriteSheetRenderer::ClearCounters(string sheetName) {
SetActualBuffer(sheetName);
actualBuffer->numSprites = 0;
}
void SpriteSheetRenderer::ClearTexture(string sheetName) {
SetActualBuffer(sheetName);
if (actualBuffer->texture != nullptr) {
if (actualBuffer->textureIsExternal)
actualBuffer->texture = nullptr;
else {
delete actualBuffer->texture;
actualBuffer->texture = nullptr;
}
}
}
void SpriteSheetRenderer::SetActualBuffer(string sheetName) {
auto buff = buffers.find(sheetName);
if (buff != buffers.end()) actualBuffer = buff->second;
else actualBuffer = nullptr;
}
void SpriteSheetRenderer::Draw() {
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// copy layers into vector and sort it by z-index
vector<SpriteLayer*> buffs;
for (auto& it : buffers) {
buffs.push_back(it.second);
}
sort(buffs.begin(), buffs.end(),
[](const SpriteLayer* a, const SpriteLayer* b) -> bool {
return a->zIndex < b->zIndex;
});
// draw layers one by one
for (auto it = buffs.begin(); it != buffs.end(); ++it) {
SpriteLayer* buff = (*it);
if (buff->numSprites > 0) {
glVertexPointer(3, GL_FLOAT, 0, &buff->verts[0]);
glColorPointer(4, GL_UNSIGNED_BYTE, 0, &buff->colors[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &buff->coords[0]);
buff->texture->bind();
glDrawArrays(GL_TRIANGLES, 0, buff->numSprites * 6);
buff->texture->unbind();
}
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
void SpriteSheetRenderer::AddTexCoords(SpriteTile& tile) {
int coordOffset = GetCoordOffset();
float x1, y1, x2, y2;
switch (tile.dir) {
case NONE:
// rounding errors elimination
x1 = tile.offsetX + 0.5f;
y1 = tile.offsetY + 0.5f;
x2 = tile.offsetX + tile.width - 0.5f;
y2 = tile.offsetY + tile.height - 0.5f;
break;
case HORIZONTALLY:
x1 = tile.offsetX + tile.width;
y1 = tile.offsetY;
x2 = tile.offsetX;
y2 = tile.offsetY + tile.height;
break;
case VERTICALLY:
x1 = tile.offsetX;
y1 = tile.offsetY + tile.height;
x2 = tile.offsetX + tile.width;
y2 = tile.offsetY;
break;
case HORIZ_VERT:
x1 = tile.offsetX + tile.width;
y1 = tile.offsetY + tile.height;
x2 = tile.offsetX;
y2 = tile.offsetY;
break;
default:
break;
}
float* coords = actualBuffer->coords;
coords[coordOffset] = coords[coordOffset + 4] = coords[coordOffset + 8] = x1*actualBuffer->textureCoeffX;
coords[coordOffset + 1] = coords[coordOffset + 3] = coords[coordOffset + 7] = y1*actualBuffer->textureCoeffY;
coords[coordOffset + 2] = coords[coordOffset + 6] = coords[coordOffset + 10] = x2*actualBuffer->textureCoeffX;
coords[coordOffset + 5] = coords[coordOffset + 9] = coords[coordOffset + 11] = y2*actualBuffer->textureCoeffY;
}
void SpriteSheetRenderer::AddTexCoords(FlipDirection f, float posX, float posY, float w, float h) {
int coordOffset = GetCoordOffset();
// for OPENGL-ES, the coefficients will clamp the w and h to range <0-1>
w *= actualBuffer->textureCoeffX;
h *= actualBuffer->textureCoeffY;
switch (f) {
case NONE:
AddTexCoords(coordOffset, posX, posY, posX + w, posY + h);
break;
case HORIZONTALLY:
AddTexCoords(coordOffset, posX + w, posY, posX, posY + h);
break;
case VERTICALLY:
AddTexCoords(coordOffset, posX, posY + h, posX + w, posY);
break;
case HORIZ_VERT:
AddTexCoords(coordOffset, posX + w, posY + h, posX, posY);
break;
default:
break;
}
}
void SpriteSheetRenderer::AddTexCoords(int offset, float x1, float y1, float x2, float y2) {
float* coords = actualBuffer->coords;
coords[offset] = coords[offset + 4] = coords[offset + 8] = x1;
coords[offset + 1] = coords[offset + 3] = coords[offset + 7] = y1;
coords[offset + 2] = coords[offset + 6] = coords[offset + 10] = x2;
coords[offset + 5] = coords[offset + 9] = coords[offset + 11] = y2;
}
void SpriteSheetRenderer::SetTexCoeffs(int textureWidth, int textureHeight) {
actualBuffer->textureCoeffX = actualBuffer->textureCoeffY = 1;
// if there is no ARB, all textures must be power of 2
#ifdef TARGET_OPENGLES
actualBuffer->textureCoeffX = 1.0f / textureWidth;
actualBuffer->textureCoeffY = 1.0f / textureHeight;
#endif
}
void SpriteSheetRenderer::MakeQuad(int offset, SpriteTile& tile) {
float w = tile.width*tile.scaleX / 2.0f;
float h = tile.height*tile.scaleY / 2.0f;
float x = tile.posX;
float y = tile.posY;
float rot = tile.rotation;
float* verts = actualBuffer->verts;
verts[offset + 2] = verts[offset + 5] = verts[offset + 11] = verts[offset + 8] = verts[offset + 14] = verts[offset + 17] = tile.posZ;
if (rot == 0) {
// no rotation
verts[offset] = x + -w;
verts[offset + 1] = y + -h;
verts[offset + 3] = verts[offset + 9] = x + w;
verts[offset + 4] = verts[offset + 10] = y + -h;
verts[offset + 6] = verts[offset + 12] = x + -w;
verts[offset + 7] = verts[offset + 13] = y + h;
verts[offset + 15] = x + w;
verts[offset + 16] = y + h;
}
else {
// calc with rotation
verts[offset] = x + GetX(-w, -h, rot);
verts[offset + 1] = y + GetY(-w, -h, rot);
verts[offset + 3] = verts[offset + 9] = x + GetX(w, -h, rot);
verts[offset + 4] = verts[offset + 10] = y + GetY(w, -h, rot);
verts[offset + 6] = verts[offset + 12] = x + GetX(-w, h, rot);
verts[offset + 7] = verts[offset + 13] = y + GetY(-w, h, rot);
verts[offset + 15] = x + GetX(w, h, rot);
verts[offset + 16] = y + GetY(w, h, rot);
}
}
void SpriteSheetRenderer::MakeQuad(int offset, float x1, float y1, float z1,
float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) {
float* verts = actualBuffer->verts;
verts[offset] = x1;
verts[offset + 1] = y1;
verts[offset + 2] = z1;
verts[offset + 3] = verts[offset + 9] = x2;
verts[offset + 4] = verts[offset + 10] = y2;
verts[offset + 5] = verts[offset + 11] = z2;
verts[offset + 6] = verts[offset + 12] = x3;
verts[offset + 7] = verts[offset + 13] = y3;
verts[offset + 8] = verts[offset + 14] = z3;
verts[offset + 15] = x4;
verts[offset + 16] = y4;
verts[offset + 17] = z4;
}
void SpriteSheetRenderer::MakeColorQuad(int offset, ofColor& col) {
unsigned char* colors = actualBuffer->colors;
colors[offset] = colors[offset + 4] = colors[offset + 8] = colors[offset + 12] = colors[offset + 16] = colors[offset + 20] = col.r;
colors[offset + 1] = colors[offset + 5] = colors[offset + 9] = colors[offset + 13] = colors[offset + 17] = colors[offset + 21] = col.g;
colors[offset + 2] = colors[offset + 6] = colors[offset + 10] = colors[offset + 14] = colors[offset + 18] = colors[offset + 22] = col.b;
colors[offset + 3] = colors[offset + 7] = colors[offset + 11] = colors[offset + 15] = colors[offset + 19] = colors[offset + 23] = col.a;
}
} // namespace | dormantor/ofxCogEngine | COGengine/src/Graphics/SpriteSheetRenderer.cpp | C++ | mit | 10,430 |
<?PHP
/**
* supplemental selection view.
*
* through ajax will reorder supplemental selections
*/
d($this->_ci_cached_vars);
//$this->output->enable_profiler(TRUE);
?>
<script type="text/javascript" src="<? echo base_url(); ?>assets/js/jquery-ui.min.js"></script>
<script src="<? echo base_url(); ?>assets/js/jquery.ui.touch-punch.min.js"></script>
<link rel="stylesheet" href="<? echo base_url(); ?>assets/css/jquery-ui.min.css" />
<script type="text/javascript">
$('.gow_radio').on('click', function(){
var gow_a_team = $(this).attr("data-gow_a");
var gow_b_team = $(this).attr("data-gow_b");
//change order in the database using Ajax
$.ajax({
url: "<?php echo base_url(); ?>Admin/set_gow/",
type: 'POST',
data: {gow_a:gow_a_team,gow_b:gow_b_team},
success: function(data) {
}
})
});
</script>
<div id="test_area"></div>
<div id="selections" class="col-xs-24 " >
<div class="panel panel-primary blue_panel-primary " >
<div class="panel-heading blue_panel-heading">
<h3 class="panel-title blue_panel-title">
<strong>Week <? echo $games['0']['week']; ?> Games</strong>
</h3>
</div>
<div class="panel-body">
<form>
<?php
$priority = 0;
foreach ($games as $data) {
$priority++;
if($priority==1){ $selected = 'checked'; } else { $selected = ''; }
?>
<div class="row">
<input type="radio" class="col-xs-2 gow_radio" data-gow_a="<? echo $data['opponent_a']; ?>" data-gow_b="<? echo $data['opponent_b']; ?>" <? echo $selected; ?> name="gow" >
</input>
<label style="font-family:Arial, Helvetica, sans-serif;display:inline"><small><strong>
<?
echo team_name_no_link($data['opponent_a']).' vs '.team_name_no_link($data['opponent_b']); ?>
</strong></small>
</label>
</div>
<?php
}
?>
</form>
</div>
</div>
</div>
</div>
<?PHP
/*End of file login.php*/
/*Location: ./application/veiws/Account/login.php*/ | rshanecole/TheFFFL | views/admin/set_gow.php | PHP | mit | 2,923 |
// Generated by CoffeeScript 1.6.3
(function() {
this.Position = (function() {
function Position(id, top, left) {
this.id = id;
this.top = top;
this.left = left;
}
return Position;
})();
this.Postit = (function() {
function Postit() {
this.id = new Date().getTime();
this.position = new Position(this.id, 0, 0);
this.identify = {};
this.contents = [];
this.isDelete = false;
}
Postit.getIndexById = function(postits, id) {
var findout, index, p, _i, _len;
index = 0;
findout = false;
for (_i = 0, _len = postits.length; _i < _len; _i++) {
p = postits[_i];
if (id.toString() === p.id.toString()) {
findout = true;
break;
}
index++;
}
if (findout) {
return index;
} else {
return -1;
}
};
Postit.prototype.getIndex = function(postits) {
return Postit.getIndexById(postits, this.id);
};
Postit.prototype.toSend = function(method, sender) {
var p;
p = new Postit(sender.id);
switch (method) {
case MethodType.Move:
p.position = sender.position;
break;
case MethodType.Save:
p.position = sender.position;
p.contents = sender.contents;
break;
case MethodType.Delete:
p.isDelete = true;
}
return p;
};
return Postit;
})();
this.MethodType = (function() {
function MethodType(index) {
this.index = index;
}
MethodType.Move = 0;
MethodType.Save = 1;
MethodType.Delete = 2;
MethodType.prototype.valueOf = function() {
return this.index;
};
return MethodType;
})();
this.ContentType = (function() {
function ContentType(index) {
this.index = index;
}
ContentType.Document = 0;
ContentType.Link = 1;
ContentType.Image = 2;
ContentType.prototype.valueOf = function() {
return this.index;
};
return ContentType;
})();
this.Content = (function() {
function Content(type, value) {
this.type = type;
this.value = value;
}
return Content;
})();
}).call(this);
| icoxfog417/whitewall | public/javascripts/postit.js | JavaScript | mit | 2,232 |
/*
Install the specified SalsaFlow release.
Description
This command can be used to download and install the specified SalsaFlow release.
The pre-built packages are fetched from GitHub. They are expected to be appended
as release assets to the GitHub release specified by the given version.
The repository that the assets are fetched from can be specified using
the available command line flags. By default it is github.com/salsaflow/salsaflow.
Release Assets
To make a GitHub release compatible with pkg, it is necessary to
append a few zip archives to the release. These archives are expected to
contain the pre-built binaries of SalsaFlow.
The binaries that are to be packed into the archive can be found in the
bin directory of your Go workspace after running make.
It is necessary to create packages for all supported platforms and architectures.
To make it possible for pkg to choose the right archive, the archive must
be named in the following way:
salsaflow-<version>-<platform>-<architecture>.zip
For example it can be
salsaflow-0.4.0-darwin-amd64.zip
*/
package installCmd
| salsaflow/salsaflow | commands/pkg/install/doc.go | GO | mit | 1,098 |
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using DungeonMart.Data.DAL;
using DungeonMart.Data.Repositories;
using DungeonMart.Models;
using DungeonMart.Services;
using DungeonMart.Services.Interfaces;
namespace DungeonMart.ApiControllers.v3_5
{
/// <summary>
/// REST service for Powers
/// </summary>
[RoutePrefix("api/v3.5/power")]
public class PowerController : ApiController
{
private readonly IPowerService _powerService;
public PowerController() : this(new PowerService(new PowerRepository(new DungeonMartContext())))
{
}
public PowerController(IPowerService powerService)
{
_powerService = powerService;
}
/// <summary>
/// Gets a list of powers
/// </summary>
/// <returns></returns>
[Route("")]
[ResponseType(typeof(PowerViewModel))]
public async Task<IHttpActionResult> Get()
{
var powerList = await Task.Run(() => _powerService.GetPowers());
return Ok(powerList);
}
/// <summary>
/// Gets a single power by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[Route("{id}", Name = "GetPowerById")]
[ResponseType(typeof(PowerViewModel))]
public async Task<IHttpActionResult> Get(int id)
{
var power = await Task.Run(() => _powerService.GetPowerById(id));
return Ok(power);
}
/// <summary>
/// Adds a power
/// </summary>
/// <param name="power"></param>
/// <returns></returns>
[Route("")]
[ResponseType(typeof(PowerViewModel))]
public async Task<IHttpActionResult> Post([FromBody]PowerViewModel power)
{
var newPower = await Task.Run(() => _powerService.AddPower(power));
return CreatedAtRoute("GetPowerById", new {id = newPower.Id}, newPower);
}
/// <summary>
/// Updates a power
/// </summary>
/// <param name="id"></param>
/// <param name="power"></param>
/// <returns></returns>
[Route("{id}")]
[ResponseType(typeof(PowerViewModel))]
public async Task<IHttpActionResult> Put(int id, [FromBody]PowerViewModel power)
{
var updatedPower = await Task.Run(() => _powerService.UdpatePower(id, power));
return Ok(updatedPower);
}
/// <summary>
/// Deletes a power
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[Route("{id}")]
public async Task<IHttpActionResult> Delete(int id)
{
await Task.Run(() => _powerService.DeletePower(id));
return Ok();
}
/// <summary>
/// Re-seeds the Power table from the json file
/// </summary>
/// <returns></returns>
[Route("0/Seed")]
public async Task<IHttpActionResult> Seed()
{
var seedDataPath = HttpContext.Current.Server.MapPath("~/SeedData");
await Task.Run(() => _powerService.SeedPowers(seedDataPath));
return Ok();
}
}
}
| qanwi1970/dungeon-mart | DungeonMart/ApiControllers/v3_5/PowerController.cs | C# | mit | 3,297 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TV.TiskarnaVosahlo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TV.TiskarnaVosahlo")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bb00a07a-d6d0-41f2-884f-b3ce4b6ad116")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| jruncik/Tiskarna | TV.TiskarnaVosahlo/Properties/AssemblyInfo.cs | C# | mit | 1,372 |
package pongimme.logic;
import java.util.*;
import java.util.concurrent.*;
import javax.swing.*;
import org.jbox2d.collision.*;
import org.jbox2d.collision.shapes.*;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.*;
import pongimme.CustomCanvas;
import pongimme.entities.*;
public class Game {
private List<Entity> cups;
private Ball ball;
private Table table;
private World world;
public Game() {
cups = new ArrayList();
world = new World(new Vec2(0, -10));
table = new Table(world);
ball = new Ball(world);
}
public List getCups() {
return this.cups;
}
public Table getTable() {
return this.table;
}
public Ball getBall() {
return this.ball;
}
public World getWorld() {
return this.world;
}
public void addBall(Ball ball) {
this.ball = ball;
}
public void addCup(Cup cup) {
cups.add(cup);
}
public void removeCup(Cup cup) {
cups.remove(cup);
}
private final ScheduledExecutorService scheduler
= Executors.newScheduledThreadPool(1);
public void update() {
CustomCanvas p = new CustomCanvas();
JFrame frame = new JFrame();
frame.add(p);
final Runnable pongi = new Runnable() {
public void run() {
for (Entity e : cups) {
e.update();
}
ball.update();
table.update();
}
};
final ScheduledFuture<?> pongiHandle
= scheduler.scheduleAtFixedRate(pongi, 0, 1 / 60, TimeUnit.SECONDS);
}
}
| mattikan/pongimme | pongimme/src/main/java/pongimme/logic/Game.java | Java | mit | 1,667 |
package io.njlr.lockstep.sample;
import io.njlr.bytes.Bytes;
import io.njlr.lockstep.state.SimulationAction;
/**
* Action that flips the counter direction.
*
*/
public final class FlipAction implements SimulationAction<StrangeSimulation> {
public static final byte leadingByte = (byte)102;
public FlipAction() {
super();
}
public void execute(final StrangeSimulation simulation) {
simulation.flip();
}
@Override
public Bytes encode() {
return Bytes.of(leadingByte);
}
@Override
public int hashCode() {
return 61;
}
@Override
public boolean equals(final Object that) {
return (this == that) || (that instanceof FlipAction);
}
@Override
public String toString() {
return "FlipAction{}";
}
public static FlipAction decode(final Bytes bytes) {
return new FlipAction();
}
}
| nlr/Lockstep | LockstepSample/src/io/njlr/lockstep/sample/FlipAction.java | Java | mit | 901 |
<?php
namespace Smartkill\APIBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class SmartkillAPIExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
| minchal/smartkill-server | src/Smartkill/APIBundle/DependencyInjection/SmartkillAPIExtension.php | PHP | mit | 883 |
import {AfterViewInit, ChangeDetectorRef, Component, ElementRef, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {
PopupInfo, PopupOptions, PopupPoint, PopupPositionOffset,
PopupPositionType, PopupService
} from "jigsaw/public_api";
@Component({
templateUrl: './demo.component.html',
styleUrls: ['./demo.component.css']
})
export class DialogPopOptionDemo implements OnInit, AfterViewInit {
dialogInfo: PopupInfo;
option: PopupOptions;
popPositionTypes: any[];
selectedPositionType: any;
poses: object[];
selectedPos: any;
detailPos: PopupPoint;
offset: PopupPositionOffset;
@ViewChild("left") left: ElementRef;
@ViewChild("middle") middle: ElementRef;
@ViewChild("right") right: ElementRef;
constructor(private popupService: PopupService, private _cdr: ChangeDetectorRef) {
}
ngOnInit() {
this.generatePopPosition();
this.detailPos = {x: null, y: null};
this.offset = {top: 10, left: 10, right: null, bottom: null};
this.option = {
modal: false,
posType: PopupPositionType.absolute
};
}
ngAfterViewInit(): void {
this.generatePopPos();
}
close() {
this.dialogInfo.dispose();
}
generatePopPos() {
this.poses = [];
this.poses.push({label: "red box", ele: this.left});
this.poses.push({label: "blue box", ele: this.middle});
this.poses.push({label: "green box", ele: this.right});
this.poses.push({label: "no reference"});
this.poses.push({label: "point"});
this.selectedPos = this.poses[0];
this._cdr.detectChanges();
}
generatePopPosition() {
this.popPositionTypes = [];
for (let prop in PopupPositionType) {
if (typeof PopupPositionType[prop] === 'number')
this.popPositionTypes.push({label: prop, id: PopupPositionType[prop]});
}
this.selectedPositionType = this.popPositionTypes[1];
}
popupDialog1(ele: TemplateRef<any>) {
this.option.posOffset = {
top: this.offset.top === null ? this.offset.top : Number(this.offset.top),
left: this.offset.left === null ? this.offset.left : Number(this.offset.left),
right: this.offset.right === null ? this.offset.right : Number(this.offset.right),
bottom: this.offset.bottom === null ? this.offset.bottom : Number(this.offset.bottom)
};
if (this.selectedPos.label != "point") {
this.option.pos = this.selectedPos.ele;
} else {
this.option.pos = {
x: this.detailPos.x === null ? this.detailPos.x : Number(this.detailPos.x),
y: this.detailPos.y === null ? this.detailPos.y : Number(this.detailPos.y),
};
}
this.option.posType = this.selectedPositionType.id;
if (this.dialogInfo) {
this.dialogInfo.dispose();
}
console.log(this.option);
this.dialogInfo = this.popupService.popup(ele, this.option);
}
// ====================================================================
// ignore the following lines, they are not important to this demo
// ====================================================================
summary: string = '';
description: string = '';
}
| rdkmaster/jigsaw | src/app/demo/pc/dialog/popup-option/demo.component.ts | TypeScript | mit | 3,381 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.securityinsights.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for PollingFrequency. */
public final class PollingFrequency extends ExpandableStringEnum<PollingFrequency> {
/** Static value OnceAMinute for PollingFrequency. */
public static final PollingFrequency ONCE_AMINUTE = fromString("OnceAMinute");
/** Static value OnceAnHour for PollingFrequency. */
public static final PollingFrequency ONCE_AN_HOUR = fromString("OnceAnHour");
/** Static value OnceADay for PollingFrequency. */
public static final PollingFrequency ONCE_ADAY = fromString("OnceADay");
/**
* Creates or finds a PollingFrequency from its string representation.
*
* @param name a name to look for.
* @return the corresponding PollingFrequency.
*/
@JsonCreator
public static PollingFrequency fromString(String name) {
return fromString(name, PollingFrequency.class);
}
/** @return known PollingFrequency values. */
public static Collection<PollingFrequency> values() {
return values(PollingFrequency.class);
}
}
| Azure/azure-sdk-for-java | sdk/securityinsights/azure-resourcemanager-securityinsights/src/main/java/com/azure/resourcemanager/securityinsights/models/PollingFrequency.java | Java | mit | 1,386 |
var utils = require('./utils');
exports.setItemDetails = function(item, description) {
return {
"author": {
"name": "Santiago",
"lastname": "Alurralde"
},
"item": {
"id": item.id,
"title": item.title,
"price": {
"currency": item.currency_id,
"amount": utils.getPriceAmount(item),
"decimals": utils.getPriceDecimals(item)
},
"picture": item.pictures[0].url,
"condition": utils.getItemCondition(item),
"free_shipping": item.shipping.free_shipping,
"sold_quantity": item.sold_quantity,
"description": description.text,
"category": item.category_id
}
};
}; | santalurr/mercadolibre | api/item.js | JavaScript | mit | 611 |
/* -*-C-*-
********************************************************************************
*
* File: metrics.c (Formerly metrics.c)
* Description:
* Author: Mark Seaman, OCR Technology
* Created: Fri Oct 16 14:37:00 1987
* Modified: Tue Jul 30 17:02:07 1991 (Mark Seaman) marks@hpgrlt
* Language: C
* Package: N/A
* Status: Reusable Software Component
*
* (c) Copyright 1987, Hewlett-Packard Company.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
*********************************************************************************/
/*----------------------------------------------------------------------
I n c l u d e s
----------------------------------------------------------------------*/
#include "metrics.h"
#include "bestfirst.h"
#include "associate.h"
#include "tally.h"
#include "plotseg.h"
#include "globals.h"
#include "wordclass.h"
#include "intmatcher.h"
#include "freelist.h"
#include "callcpp.h"
#include "ndminx.h"
#include "wordrec.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
/*----------------------------------------------------------------------
V a r i a b l e s
----------------------------------------------------------------------*/
static int states_timed_out1; /* Counters */
static int states_timed_out2;
static int words_segmented1;
static int words_segmented2;
static int segmentation_states1;
static int segmentation_states2;
static int save_priorities;
int words_chopped1;
int words_chopped2;
int chops_attempted1;
int chops_performed1;
int chops_attempted2;
int chops_performed2;
int character_count;
int word_count;
int chars_classified;
MEASUREMENT num_pieces;
MEASUREMENT width_measure;
MEASUREMENT width_priority_range;/* Help to normalize */
MEASUREMENT match_priority_range;
TALLY states_before_best;
TALLY best_certainties[2];
TALLY character_widths; /* Width histogram */
FILE *priority_file_1; /* Output to cluster */
FILE *priority_file_2;
FILE *priority_file_3;
STATE *known_best_state = NULL; /* The right answer */
/*----------------------------------------------------------------------
M a c r o s
----------------------------------------------------------------------*/
#define CERTAINTY_BUCKET_SIZE -0.5
#define CERTAINTY_BUCKETS 40
/*----------------------------------------------------------------------
F u n c t i o n s
----------------------------------------------------------------------*/
/**********************************************************************
* init_metrics
*
* Set up the appropriate variables to record information about the
* OCR process. Later calls will log the data and save a summary.
**********************************************************************/
void init_metrics() {
words_chopped1 = 0;
words_chopped2 = 0;
chops_performed1 = 0;
chops_performed2 = 0;
chops_attempted1 = 0;
chops_attempted2 = 0;
words_segmented1 = 0;
words_segmented2 = 0;
states_timed_out1 = 0;
states_timed_out2 = 0;
segmentation_states1 = 0;
segmentation_states2 = 0;
save_priorities = 0;
character_count = 0;
word_count = 0;
chars_classified = 0;
permutation_count = 0;
end_metrics();
states_before_best = new_tally (MIN (100, wordrec_num_seg_states));
best_certainties[0] = new_tally (CERTAINTY_BUCKETS);
best_certainties[1] = new_tally (CERTAINTY_BUCKETS);
reset_width_tally();
}
void end_metrics() {
if (states_before_best != NULL) {
memfree(states_before_best);
memfree(best_certainties[0]);
memfree(best_certainties[1]);
memfree(character_widths);
states_before_best = NULL;
best_certainties[0] = NULL;
best_certainties[1] = NULL;
character_widths = NULL;
}
}
/**********************************************************************
* record_certainty
*
* Maintain a record of the best certainty values achieved on each
* word recognition.
**********************************************************************/
void record_certainty(float certainty, int pass) {
int bucket;
if (certainty / CERTAINTY_BUCKET_SIZE < MAX_INT32)
bucket = (int) (certainty / CERTAINTY_BUCKET_SIZE);
else
bucket = MAX_INT32;
inc_tally_bucket (best_certainties[pass - 1], bucket);
}
/**********************************************************************
* record_search_status
*
* Record information about each iteration of the search. This data
* is kept in global memory and accumulated over multiple segmenter
* searches.
**********************************************************************/
void record_search_status(int num_states, int before_best, float closeness) {
inc_tally_bucket(states_before_best, before_best);
if (first_pass) {
if (num_states == wordrec_num_seg_states + 1)
states_timed_out1++;
segmentation_states1 += num_states;
words_segmented1++;
}
else {
if (num_states == wordrec_num_seg_states + 1)
states_timed_out2++;
segmentation_states2 += num_states;
words_segmented2++;
}
}
/**********************************************************************
* save_summary
*
* Save the summary information into the file "file.sta".
**********************************************************************/
namespace tesseract {
void Wordrec::save_summary(inT32 elapsed_time) {
#ifndef SECURE_NAMES
STRING outfilename;
FILE *f;
int x;
int total;
outfilename = imagefile + ".sta";
f = open_file (outfilename.string(), "w");
fprintf (f, INT32FORMAT " seconds elapsed\n", elapsed_time);
fprintf (f, "\n");
fprintf (f, "%d characters\n", character_count);
fprintf (f, "%d words\n", word_count);
fprintf (f, "\n");
fprintf (f, "%d permutations performed\n", permutation_count);
fprintf (f, "%d characters classified\n", chars_classified);
fprintf (f, "%4.0f%% classification overhead\n",
(float) chars_classified / character_count * 100.0 - 100.0);
fprintf (f, "\n");
fprintf (f, "%d words chopped (pass 1) ", words_chopped1);
fprintf (f, " (%0.0f%%)\n", (float) words_chopped1 / word_count * 100);
fprintf (f, "%d chops performed\n", chops_performed1);
fprintf (f, "%d chops attempted\n", chops_attempted1);
fprintf (f, "\n");
fprintf (f, "%d words joined (pass 1)", words_segmented1);
fprintf (f, " (%0.0f%%)\n", (float) words_segmented1 / word_count * 100);
fprintf (f, "%d segmentation states\n", segmentation_states1);
fprintf (f, "%d segmentations timed out\n", states_timed_out1);
fprintf (f, "\n");
fprintf (f, "%d words chopped (pass 2) ", words_chopped2);
fprintf (f, " (%0.0f%%)\n", (float) words_chopped2 / word_count * 100);
fprintf (f, "%d chops performed\n", chops_performed2);
fprintf (f, "%d chops attempted\n", chops_attempted2);
fprintf (f, "\n");
fprintf (f, "%d words joined (pass 2)", words_segmented2);
fprintf (f, " (%0.0f%%)\n", (float) words_segmented2 / word_count * 100);
fprintf (f, "%d segmentation states\n", segmentation_states2);
fprintf (f, "%d segmentations timed out\n", states_timed_out2);
fprintf (f, "\n");
total = 0;
iterate_tally (states_before_best, x)
total += (tally_entry (states_before_best, x) * x);
fprintf (f, "segmentations (before best) = %d\n", total);
if (total != 0.0)
fprintf (f, "%4.0f%% segmentation overhead\n",
(float) (segmentation_states1 + segmentation_states2) /
total * 100.0 - 100.0);
fprintf (f, "\n");
print_tally (f, "segmentations (before best)", states_before_best);
iterate_tally (best_certainties[0], x)
cprintf ("best certainty of %8.4f = %4d %4d\n",
x * CERTAINTY_BUCKET_SIZE,
tally_entry (best_certainties[0], x),
tally_entry (best_certainties[1], x));
PrintIntMatcherStats(f);
dj_statistics(f);
fclose(f);
#endif
}
} // namespace tesseract
/**********************************************************************
* record_priorities
*
* If the record mode is set then record the priorities returned by
* each of the priority voters. Save them in a file that is set up for
* doing clustering.
**********************************************************************/
void record_priorities(SEARCH_RECORD *the_search,
FLOAT32 priority_1,
FLOAT32 priority_2) {
record_samples(priority_1, priority_2);
}
/**********************************************************************
* record_samples
*
* Remember the priority samples to summarize them later.
**********************************************************************/
void record_samples(FLOAT32 match_pri, FLOAT32 width_pri) {
ADD_SAMPLE(match_priority_range, match_pri);
ADD_SAMPLE(width_priority_range, width_pri);
}
/**********************************************************************
* reset_width_tally
*
* Create a tally record and initialize it.
**********************************************************************/
void reset_width_tally() {
character_widths = new_tally (20);
new_measurement(width_measure);
width_measure.num_samples = 158;
width_measure.sum_of_samples = 125.0;
width_measure.sum_of_squares = 118.0;
}
#ifndef GRAPHICS_DISABLED
/**********************************************************************
* save_best_state
*
* Save this state away to be compared later.
**********************************************************************/
void save_best_state(CHUNKS_RECORD *chunks_record) {
STATE state;
SEARCH_STATE chunk_groups;
int num_joints;
if (save_priorities) {
num_joints = chunks_record->ratings->dimension() - 1;
state.part1 = 0xffffffff;
state.part2 = 0xffffffff;
chunk_groups = bin_to_chunks (&state, num_joints);
display_segmentation (chunks_record->chunks, chunk_groups);
memfree(chunk_groups);
cprintf ("Enter the correct segmentation > ");
fflush(stdout);
state.part1 = 0;
scanf ("%x", &state.part2);
chunk_groups = bin_to_chunks (&state, num_joints);
display_segmentation (chunks_record->chunks, chunk_groups);
memfree(chunk_groups);
window_wait(segm_window); /* == 'n') */
if (known_best_state)
free_state(known_best_state);
known_best_state = new_state (&state);
}
}
#endif
/**********************************************************************
* start_record
*
* Set up everything needed to record the priority voters.
**********************************************************************/
void start_recording() {
if (save_priorities) {
priority_file_1 = open_file ("Priorities1", "w");
priority_file_2 = open_file ("Priorities2", "w");
priority_file_3 = open_file ("Priorities3", "w");
}
}
/**********************************************************************
* stop_recording
*
* Put an end to the priority recording mechanism.
**********************************************************************/
void stop_recording() {
if (save_priorities) {
fclose(priority_file_1);
fclose(priority_file_2);
fclose(priority_file_3);
}
}
| danauclair/CardScan | tesseract-ocr/wordrec/metrics.cpp | C++ | mit | 11,659 |
'use strict';
var isString = require('lodash/isString');
var each = require('lodash/each');
var last = require('lodash/last');
var uuid = require('../util/uuid');
var EditingBehavior = require('../model/EditingBehavior');
var insertText = require('../model/transform/insertText');
var copySelection = require('../model/transform/copySelection');
var deleteSelection = require('../model/transform/deleteSelection');
var breakNode = require('../model/transform/breakNode');
var insertNode = require('../model/transform/insertNode');
var switchTextType = require('../model/transform/switchTextType');
var paste = require('../model/transform/paste');
var Surface = require('./Surface');
var RenderingEngine = require('./RenderingEngine');
/**
Represents a flow editor that manages a sequence of nodes in a container. Needs to be
instantiated inside a {@link ui/Controller} context.
@class ContainerEditor
@component
@extends ui/Surface
@prop {String} name unique editor name
@prop {String} containerId container id
@prop {Object[]} textTypes array of textType definition objects
@prop {ui/SurfaceCommand[]} commands array of command classes to be available
@example
Create a full-fledged `ContainerEditor` for the `body` container of a document.
Allow Strong and Emphasis annotations and to switch text types between paragraph
and heading at level 1.
```js
$$(ContainerEditor, {
name: 'bodyEditor',
containerId: 'body',
textTypes: [
{name: 'paragraph', data: {type: 'paragraph'}},
{name: 'heading1', data: {type: 'heading', level: 1}}
],
commands: [StrongCommand, EmphasisCommand, SwitchTextTypeCommand],
})
```
*/
function ContainerEditor() {
Surface.apply(this, arguments);
this.containerId = this.props.containerId;
if (!isString(this.props.containerId)) {
throw new Error("Illegal argument: Expecting containerId.");
}
var doc = this.getDocument();
this.container = doc.get(this.containerId);
if (!this.container) {
throw new Error('Container with id ' + this.containerId + ' does not exist.');
}
this.editingBehavior = new EditingBehavior();
}
ContainerEditor.Prototype = function() {
var _super = Object.getPrototypeOf(this);
// Note: this component is self managed
this.shouldRerender = function() {
// TODO: we should still detect when the document has changed,
// see https://github.com/substance/substance/issues/543
return false;
};
this.render = function($$) {
var el = _super.render.apply(this, arguments);
var doc = this.getDocument();
var containerId = this.props.containerId;
var containerNode = doc.get(this.props.containerId);
if (!containerNode) {
console.warn('No container node found for ', this.props.containerId);
}
var isEditable = this.isEditable();
el.addClass('sc-container-editor container-node ' + containerId)
.attr({
spellCheck: false,
"data-id": containerId,
"contenteditable": isEditable
});
if (this.isEmpty()) {
el.append(
$$('a').attr('href', '#').append('Start writing').on('click', this.onCreateText)
);
} else {
// node components
each(containerNode.nodes, function(nodeId) {
el.append(this._renderNode($$, nodeId));
}.bind(this));
}
return el;
};
// Used by Clipboard
this.isContainerEditor = function() {
return true;
};
/**
Returns the containerId the editor is bound to
*/
this.getContainerId = function() {
return this.props.containerId;
};
// TODO: do we really need this in addition to getContainerId?
this.getContainer = function() {
return this.getDocument().get(this.getContainerId());
};
this.isEmpty = function() {
var doc = this.getDocument();
var containerNode = doc.get(this.props.containerId);
return (containerNode && containerNode.nodes.length === 0);
};
this.isEditable = function() {
return _super.isEditable.call(this) && !this.isEmpty();
};
/*
TODO: Select first content to be found
*/
this.selectFirst = function() {
console.warn('TODO: Implement selection of first content to be found.');
};
/*
Register custom editor behavior using this method
*/
this.extendBehavior = function(extension) {
extension.register(this.editingBehavior);
};
this.getTextTypes = function() {
return this.textTypes || [];
};
// Used by TextTool
// TODO: Filter by enabled commands for this Surface
this.getTextCommands = function() {
var textCommands = {};
this.commandRegistry.each(function(cmd) {
if (cmd.constructor.static.textTypeName) {
textCommands[cmd.getName()] = cmd;
}
});
return textCommands;
};
this.enable = function() {
// As opposed to a ContainerEditor, a regular Surface
// is not a ContentEditable -- but every contained TextProperty
this.attr('contentEditable', true);
this.enabled = true;
};
this.disable = function() {
this.removeAttr('contentEditable');
this.enabled = false;
};
/* Editing behavior */
/**
Performs a {@link model/transform/deleteSelection} transformation
*/
this.delete = function(tx, args) {
this._prepareArgs(args);
return deleteSelection(tx, args);
};
/**
Performs a {@link model/transform/breakNode} transformation
*/
this.break = function(tx, args) {
this._prepareArgs(args);
if (args.selection.isPropertySelection() || args.selection.isContainerSelection()) {
return breakNode(tx, args);
}
};
/**
Performs an {@link model/transform/insertNode} transformation
*/
this.insertNode = function(tx, args) {
this._prepareArgs(args);
if (args.selection.isPropertySelection() || args.selection.isContainerSelection()) {
return insertNode(tx, args);
}
};
/**
* Performs a {@link model/transform/switchTextType} transformation
*/
this.switchType = function(tx, args) {
this._prepareArgs(args);
if (args.selection.isPropertySelection()) {
return switchTextType(tx, args);
}
};
/**
Selects all content in the container
*/
this.selectAll = function() {
var doc = this.getDocument();
var container = doc.get(this.getContainerId());
if (container.nodes.length === 0) {
return;
}
var firstNodeId = container.nodes[0];
var lastNodeId = last(container.nodes);
var sel = doc.createSelection({
type: 'container',
containerId: container.id,
startPath: [firstNodeId],
startOffset: 0,
endPath: [lastNodeId],
endOffset: 1
});
this.setSelection(sel);
};
this.selectFirst = function() {
var doc = this.getDocument();
var nodes = this.getContainer().nodes;
if (nodes.length === 0) {
console.info('ContainerEditor.selectFirst(): Container is empty.');
return;
}
var node = doc.get(nodes[0]);
var sel;
if (node.isText()) {
sel = doc.createSelection(node.getTextPath(), 0);
} else {
sel = doc.createSelection(this.getContainerId(), [node.id], 0, [node.id], 1);
}
this.setSelection(sel);
};
/**
Performs a {@link model/transform/paste} transformation
*/
this.paste = function(tx, args) {
this._prepareArgs(args);
if (args.selection.isPropertySelection() || args.selection.isContainerSelection()) {
return paste(tx, args);
}
};
/**
Performs an {@link model/transform/insertText} transformation
*/
this.insertText = function(tx, args) {
if (args.selection.isPropertySelection() || args.selection.isContainerSelection()) {
return insertText(tx, args);
}
};
/**
Inserts a soft break
*/
this.softBreak = function(tx, args) {
args.text = "\n";
return this.insertText(tx, args);
};
/**
Copy the current selection. Performs a {@link model/transform/copySelection}
transformation.
*/
this.copy = function(doc, selection) {
var result = copySelection(doc, { selection: selection });
return result.doc;
};
this.onDocumentChange = function(change) {
// first update the container
var renderContext = RenderingEngine.createContext(this);
if (change.isAffected([this.props.containerId, 'nodes'])) {
for (var i = 0; i < change.ops.length; i++) {
var op = change.ops[i];
if (op.type === "update" && op.path[0] === this.props.containerId) {
var diff = op.diff;
if (diff.type === "insert") {
var nodeEl = this._renderNode(renderContext.$$, diff.getValue());
this.insertAt(diff.getOffset(), nodeEl);
} else if (diff.type === "delete") {
this.removeAt(diff.getOffset());
}
}
}
}
// do other stuff such as rerendering text properties
_super.onDocumentChange.apply(this, arguments);
};
// Create a first text element
this.onCreateText = function(e) {
e.preventDefault();
var newSel;
this.transaction(function(tx) {
var container = tx.get(this.props.containerId);
var textType = tx.getSchema().getDefaultTextType();
var node = tx.create({
id: uuid(textType),
type: textType,
content: ''
});
container.show(node.id);
newSel = tx.createSelection({
type: 'property',
path: [ node.id, 'content'],
startOffset: 0,
endOffset: 0
});
}.bind(this));
this.rerender();
this.setSelection(newSel);
};
this._prepareArgs = function(args) {
args.containerId = this.getContainerId();
args.editingBehavior = this.editingBehavior;
};
};
Surface.extend(ContainerEditor);
module.exports = ContainerEditor;
| TypesetIO/substance | ui/ContainerEditor.js | JavaScript | mit | 9,737 |
"use strict"
const path = require('path')
class Helpers {
static getPageIdFromFilenameOrLink(filename) {
var base = path.basename(filename)
if (base.substr(-3) === '.md') {
base = base.substr(0, base.length - 3)
}
return base.replace(/([^a-z0-9\-_~]+)/gi, '')
}
}
module.exports = Helpers
| limedocs/limedocs-wiki-converter | src/helpers.js | JavaScript | mit | 320 |
import { vec3, mat4, quat } from 'gl-matrix';
import Vector3 from './vector3';
let uuid = 0;
let axisAngle = 0;
const quaternionAxisAngle = vec3.create();
class Object3 {
constructor() {
this.uid = uuid++;
this.position = new Vector3();
this.rotation = new Vector3();
this.scale = new Vector3(1, 1, 1);
this.quaternion = quat.create();
this.target = vec3.create();
this.up = vec3.fromValues(0, 1, 0);
this.parent = null;
this.children = [];
this.parentMatrix = mat4.create();
this.modelMatrix = mat4.create();
this.lookAtMatrix = mat4.create();
// use mat4.targetTo rotation when set to true
this.lookToTarget = false; // use lookAt rotation when set to true
// enable polygonOffset (z-fighting)
this.polygonOffset = false;
this.polygonOffsetFactor = 0;
this.polygonOffsetUnits = 1;
}
addModel(model) {
model.parent = this; // eslint-disable-line
this.children.push(model);
}
removeModel(model) {
const index = this.children.indexOf(model);
if (index !== -1) {
model.destroy();
this.children.splice(index, 1);
}
}
updateMatrices() {
mat4.identity(this.parentMatrix);
mat4.identity(this.modelMatrix);
mat4.identity(this.lookAtMatrix);
quat.identity(this.quaternion);
if (this.parent) {
mat4.copy(this.parentMatrix, this.parent.modelMatrix);
mat4.multiply(this.modelMatrix, this.modelMatrix, this.parentMatrix);
}
if (this.lookToTarget) {
mat4.targetTo(this.lookAtMatrix, this.position.data, this.target, this.up);
mat4.multiply(this.modelMatrix, this.modelMatrix, this.lookAtMatrix);
} else {
mat4.translate(this.modelMatrix, this.modelMatrix, this.position.data);
quat.rotateX(this.quaternion, this.quaternion, this.rotation.x);
quat.rotateY(this.quaternion, this.quaternion, this.rotation.y);
quat.rotateZ(this.quaternion, this.quaternion, this.rotation.z);
axisAngle = quat.getAxisAngle(quaternionAxisAngle, this.quaternion);
mat4.rotate(this.modelMatrix, this.modelMatrix, axisAngle, quaternionAxisAngle);
}
mat4.scale(this.modelMatrix, this.modelMatrix, this.scale.data);
}
}
export default Object3;
| andrevenancio/engine | src/core/object3.js | JavaScript | mit | 2,458 |
package com.github.dcoric.demonico.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "user")
public class User {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name = "username", nullable = false)
private String username;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "first_name", nullable = true)
private String firstName;
@Column(name = "last_name", nullable = true)
private String lastName;
@Column(name = "birth_date", nullable = true)
private Date birthDate;
@Column(name = "insertion_date", nullable = false)
private Date insertionDate;
@Transient
private Long age;
public Long getAge() {
Date today = new Date();
return (birthDate!=null?today.getTime() - birthDate.getTime() : null);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Date getInsertionDate() {
return insertionDate;
}
public void setInsertionDate(Date insertionDate) {
this.insertionDate = insertionDate;
}
}
| dcoric/Maven | demonico/src/main/java/com/github/dcoric/demonico/model/User.java | Java | mit | 2,012 |
<?php
namespace App\Common\Models\Company\Mysql;
use App\Common\Models\Base\Mysql\Base;
class TeamUser extends Base
{
/**
* 公司-团队用户管理
* This model is mapped to the table icompany_team_user
*/
public function getSource()
{
return 'icompany_team_user';
}
public function reorganize(array $data)
{
$data = parent::reorganize($data);
$data['is_team_manager'] = $this->changeToBoolean($data['is_team_manager']);
return $data;
}
}
| handsomegyr/models | lib/App/Common/Models/Company/Mysql/TeamUser.php | PHP | mit | 520 |
<h2>Dar de alta un nuevo <span class='muted'>banco</span> en el sistema</h2>
<br/>
<?php echo render('banco/_form'); ?>
<p><?php echo Html::anchor('banco', 'Volver al listado',array('class'=>'btn btn-danger')); ?></p>
| fjcarreterox/gestion-entregas-AC | fuel/app/views/banco/create.php | PHP | mit | 218 |
module MagentoApiWrapper::Requests
class InvoiceInfo
attr_accessor :data
def initialize(data = {})
@data = data
end
def body
#TODO: Check this out
merge_filters(invoice_info_hash) unless self.order_id.nil?
end
def invoice_info_hash
{
session_id: self.session_id
}
end
def session_id
data[:session_id]
end
def order_id
data[:order_id]
end
def merge_filters(invoice_info_hash)
filters = {
filters: {
"complex_filter" => {
complex_object_array: {
key: "order_increment_id",
value: order_id_hash
},
}
}
}
return invoice_info_hash.merge!(filters)
end
def order_id_hash
order = {}
order["key"] = "eq"
order["value"] = order_id
order
end
end
end
| rebyn/magento_api_wrapper | lib/magento_api_wrapper/requests/invoice_info.rb | Ruby | mit | 892 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace posh.visu
{
public partial class CProperties : UserControl
{
public CProperties()
{
InitializeComponent();
}
private void name_TextChanged(object sender, EventArgs e)
{
}
private void timeout_ValueChanged(object sender, EventArgs e)
{
}
private void time_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
| suegy/ReActIDE | visu/gui/properties/CProperties.cs | C# | mit | 636 |
package com.drumonii.loltrollbuild.routing;
import com.drumonii.loltrollbuild.model.Build;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Controller for {@link Build}s to forward requests to Angular so it can resolve the route.
*/
@Controller
@RequestMapping("/builds")
public class BuildsController {
@GetMapping
public String builds() {
return "forward:/troll-build/index.html";
}
@GetMapping("/{id}")
public String build(@PathVariable int id) {
return "forward:/troll-build/index.html";
}
}
| drumonii/LeagueTrollBuild | backend/src/main/java/com/drumonii/loltrollbuild/routing/BuildsController.java | Java | mit | 703 |
import { CodeExtractionInstructions } from '@webpack-ext/tdm-code-sample';
module.exports = [
{
file: './render-state-event.component.ts',
autoRender: true,
title: 'Component'
},
{
file: './render-state-event.component.html',
autoRender: true,
title: 'Template',
section: 'TDM-DEMO'
},
{
file: './render-state-event.component.scss',
autoRender: true,
title: 'Style'
},
{
file: '../../4-element-metadata/model.ts',
autoRender: true,
title: 'Model'
},
{
file: './README.md',
autoRender: true
}
] as CodeExtractionInstructions[];
| shlomiassaf/tdm | apps/demo/src/modules/@forms/tutorials/events/render-state-event/__tdm-code__.ts | TypeScript | mit | 608 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="<?=$conf['description']?>">
<meta name="keywords" content="<?=$conf['keywords']?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?=$conf['title']?></title>
<link rel="shortcut icon" href="<?=$conf['uri']?>/tpl/<?=$conf['tpl']?>/img/favicon.ico">
<link rel="stylesheet" href="<?=$conf['uri']?>/tpl/<?=$conf['tpl']?>/css/styles.css">
</head>
<body>
<div class="container">
<div class="row">
<form>
<div class="column-5">
<div class="form-group">
<div class="form-control" name="input" data-placeholder="Hash or Text" contenteditable="true" spellcheck="false"></div>
</div>
</div>
<div class="column-2 control">
<div class="form-group">
<select class="btn">
</select>
</div>
<div class="form-group text-center ext-db">
<span><label><input type="checkbox" checked> Include external db</label></span>
</div>
<div class="form-group">
<button type="submit" class="btn" name="tohash">Convert to Hash</button>
</div>
<div class="form-group">
<button type="submit" class="btn" name="totext">Convert to Text</button>
</div>
<div class="form-group text-center control-counter">
<span><span name="counter">0</span> hashes in the database</span>
</div>
<div class="form-group text-center control-api">
<span>You can use <a href="https://github.com/ziggi/deHasher/blob/master/README.md#using-external-api">API</a></span>
</div>
<div class="form-group text-center control-links">
<span>
<a href="https://ziggi.org/">
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path fill="#000000" d="M10,20V14H14V20H19V12H22L12,3L2,12H5V20H10Z" />
</svg>
</a>
</span>
<span>
<a href="https://github.com/ziggi/deHasher">
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path fill="#000000" d="M12,2A10,10 0 0,0 2,12C2,16.42 4.87,20.17 8.84,21.5C9.34,21.58 9.5,21.27 9.5,21C9.5,20.77 9.5,20.14 9.5,19.31C6.73,19.91 6.14,17.97 6.14,17.97C5.68,16.81 5.03,16.5 5.03,16.5C4.12,15.88 5.1,15.9 5.1,15.9C6.1,15.97 6.63,16.93 6.63,16.93C7.5,18.45 8.97,18 9.54,17.76C9.63,17.11 9.89,16.67 10.17,16.42C7.95,16.17 5.62,15.31 5.62,11.5C5.62,10.39 6,9.5 6.65,8.79C6.55,8.54 6.2,7.5 6.75,6.15C6.75,6.15 7.59,5.88 9.5,7.17C10.29,6.95 11.15,6.84 12,6.84C12.85,6.84 13.71,6.95 14.5,7.17C16.41,5.88 17.25,6.15 17.25,6.15C17.8,7.5 17.45,8.54 17.35,8.79C18,9.5 18.38,10.39 18.38,11.5C18.38,15.32 16.04,16.16 13.81,16.41C14.17,16.72 14.5,17.33 14.5,18.26C14.5,19.6 14.5,20.68 14.5,21C14.5,21.27 14.66,21.59 15.17,21.5C19.14,20.16 22,16.42 22,12A10,10 0 0,0 12,2Z" />
</svg>
</a>
</span>
</div>
</div>
<div class="column-5">
<div class="form-group">
<div class="form-control" name="output" data-placeholder="Result"></div>
</div>
</div>
</form>
</div>
</div>
<script src="<?=$conf['uri']?>/tpl/<?=$conf['tpl']?>/js/scripts.js"></script>
<script src="<?=$conf['uri']?>/js/scripts.js"></script>
</body>
</html>
| ziggi/deHasher | tpl/default/index.php | PHP | mit | 3,621 |
import React from 'react';
import PropTypes from 'prop-types';
import Logo from './Logo';
import SearchBar from './SearchBar';
import { CSSTransitionGroup } from 'react-transition-group';
class Header extends React.Component {
render() {
let header = window.scrollY > 170 && window.innerWidth > 800
? <div key={this.props.path} className='app-header'>
<Logo/>
<SearchBar
path={this.props.path}
history={this.props.history}
setResults={this.props.setResults}
toggleFetch={this.props.toggleFetch}
isBookMenuActive={this.props.isBookMenuActive} />
</div>
: null;
return (
<CSSTransitionGroup
transitionName="header"
transitionEnterTimeout={200}
transitionLeaveTimeout={200}>
{header}
</CSSTransitionGroup>
)
}
}
Header.propTypes = {
setResults: PropTypes.func.isRequired,
toggleFetch: PropTypes.func.isRequired,
history: PropTypes.object.isRequired,
path: PropTypes.string.isRequired,
isBookMenuActive: PropTypes.bool.isRequired
};
export default Header;
| pixel-glyph/better-reads | src/components/Header.js | JavaScript | mit | 1,137 |
<?php
namespace Ekyna\Component\Commerce\Customer\Model;
use Ekyna\Component\Commerce\Common\Model\NotificationTypes;
/**
* Trait NotificationsTrait
* @package Ekyna\Component\Commerce\Customer\Model
* @author Etienne Dauvergne <contact@ekyna.com>
*/
trait NotificationsTrait
{
/**
* @var string[]
*/
protected $notifications;
/**
* Returns the notifications.
*
* @return string[]
*/
public function getNotifications(): array
{
return $this->notifications;
}
/**
* Sets the notifications.
*
* @param string[] $notifications
*
* @return $this|NotificationsInterface
*/
public function setNotifications(array $notifications = []): NotificationsInterface
{
$this->notifications = [];
foreach (array_unique($notifications) as $notification) {
if (!NotificationTypes::isValid($notification, false)) {
continue;
}
$this->notifications[] = $notification;
}
return $this;
}
}
| ekyna/Commerce | Customer/Model/NotificationsTrait.php | PHP | mit | 1,074 |
package parser
import (
"github.com/stretchr/testify/assert"
"testing"
)
func Test_tokenize_OpeningBracket(t *testing.T) {
data := []byte("(somestuff)")
advance, token, err := tokenize(data, false)
assert.NoError(t, err)
assert.Equal(t, 1, advance)
assert.Equal(t, []byte("("), token)
}
func Test_tokenize_WordFollowedClosingBracket(t *testing.T) {
data := []byte("somestuff)")
advance, token, err := tokenize(data, false)
assert.NoError(t, err)
assert.Equal(t, 9, advance)
assert.Equal(t, []byte("somestuff"), token)
}
func Test_tokenize_WordFollowedByAnArgument(t *testing.T) {
data := []byte("somestuff 1 1)")
advance, token, err := tokenize(data, false)
assert.NoError(t, err)
assert.Equal(t, 9, advance)
assert.Equal(t, []byte("somestuff"), token)
}
func Test_tokenize_ClosingBracket(t *testing.T) {
data := []byte("))")
advance, token, err := tokenize(data, false)
assert.NoError(t, err)
assert.Equal(t, 1, advance)
assert.Equal(t, []byte(")"), token)
}
func Test_tokenize_OpeningVector(t *testing.T) {
data := []byte("[]")
advance, token, err := tokenize(data, false)
assert.NoError(t, err)
assert.Equal(t, 1, advance)
assert.Equal(t, []byte("["), token)
}
func Test_tokenize_ClosingVector(t *testing.T) {
data := []byte("]")
advance, token, err := tokenize(data, false)
assert.NoError(t, err)
assert.Equal(t, 1, advance)
assert.Equal(t, []byte("]"), token)
}
func Test_tokenize_ClosingBracketAtEndOfReader(t *testing.T) {
data := []byte(")")
advance, token, err := tokenize(data, true)
assert.NoError(t, err)
assert.Equal(t, 1, advance)
assert.Equal(t, []byte(")"), token)
}
func Test_tokenize_OpeningBracketAfterSpace(t *testing.T) {
data := []byte(" (")
advance, token, err := tokenize(data, true)
assert.NoError(t, err)
assert.Equal(t, 2, advance)
assert.Equal(t, []byte("("), token)
}
func Test_tokenize_QuotedStringWithSpaces(t *testing.T) {
data := []byte("\"hello world\" ")
advance, token, err := tokenize(data, true)
assert.NoError(t, err)
assert.Equal(t, 13, advance)
assert.Equal(t, []byte("\"hello world\""), token)
}
func Test_tokenize_Error_UnclosedString(t *testing.T) {
data := []byte("\"hello world ")
_, _, err := tokenize(data, true)
assert.EqualError(t, err, "string not closed")
}
func Test_tokenize_QuotedStringContainingEscapedQuote(t *testing.T) {
data := []byte(`"quote \" here" `)
advance, token, err := tokenize(data, true)
assert.NoError(t, err)
assert.Equal(t, 15, advance)
assert.Equal(t, []byte(`"quote \" here"`), token)
}
| mikeyhu/glipso | parser/lexer_test.go | GO | mit | 2,530 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<?php
session_start(); // Start/resume THIS session
// PAGE SECURITY
if (!isset($_SESSION['isAdmin']))
{
echo '<script type="text/javascript">history.back()</script>';
die();
}
$_SESSION['title'] = "Event Registration | MegaLAN"; // Declare this page's Title
include("../includes/template.php"); // Include the template page
include("../includes/conn.php"); // Include the db connection
// IF [this] USER BOOKS FOR AN EVENT
if (isset($_POST['bookID']) && isset($_POST['subject']))
{
if ($_POST['subject'] == 'bookEvent')
{
// CHECK IF USER HAS BOOKED THIS EVENT
$check = "SELECT * FROM attendee WHERE clientID='".$_SESSION['userID']."' AND eventID='".$_POST['bookID']."'";
$result = $db->query($check);
// IF THEY HAVE BOOKED [this] EVENT, DEFER THEM
if ($result->num_rows > 0)
{
// SEE IF THEY HAVE BOOKED 'this' EVENT
$row = $result->fetch_assoc();
if ($row['eventID'] == $_POST['bookID'])
{
$_SESSION['errMsg'] = '<font class="error">Sorry you have already booked this event</font>';
}
}
// BOOK [this] EVENT
else
{
$book = "INSERT INTO attendee (eventID, clientID, paid) VALUES (".$_POST['bookID'].", ".$_SESSION['userID'].", 0)";
$result = $db->query($book);
/*
* AT THIS STAGE, THIS USER HAS BOOKED AN EVENT
* THE USER YET HAS TO:
* -BOOK A TOURNAMENT
* -BOOK A SEAT
* -BOOK PIZZA (optional)
*/
}
}
}
// IF [this] USER CANCELS A SEAT
if (isset($_POST['seatID']))
{
$cancel = "UPDATE attendee SET seatID=NULL WHERE attendeeID='".$_POST['attendeeID']."' AND clientID='".$_SESSION['userID']."'";
$result = $db->query($cancel);
$cancel = "UPDATE seat SET status='1' WHERE seatID='".$_POST['seatID']."'";
$result = $db->query($cancel);
/*
* AT THIS STAGE, THIS USER HAS BOOKED AN EVENT
* THE USER YET HAS TO:
* -BOOK A TOURNAMENT
* -BOOK A SEAT
* -BOOK PIZZA (optional)
*/
}
// CHECK IF A CURRENT EVENT EXISTS
// GET ALL CURRENT EVENTS
$query = "SELECT * FROM event WHERE startDate >= CURDATE() AND event_completed=0 ORDER BY startDate ASC";
$result = $db->query($query);
if ($result->num_rows == 0)
{
$eventStatus = 0;
}
else
{
$eventStatus = 1;
}
?>
<!-- //******************************************************
// Name of File: eventRegister.php
// Revision: 1.0
// Date: 14/05/2012
// Author: Quintin
// Modified:
//***********************************************************
//********** Start of EVENT REGISTRATION PAGE ************** -->
<head>
<script type='text/javascript'>
// DISPLAY EVENT DETAILS FIRST
function getEvent(params)
{
if (window.XMLHttpRequest)
{
// code for mainstream browsers
xmlhttp=new XMLHttpRequest();
}
else
{
// code for earlier IE versions
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajaxDIV").innerHTML=xmlhttp.responseText;
}
}
//Now we have the xmlhttp object, get the data using AJAX.
xmlhttp.open("POST","ajaxEvent.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
// BOOK EVENT
function book(id)
{
var answer = confirm("Please confirm to book this Event");
if (answer == true)
{
document.getElementById('bookID').value = id;
document.getElementById('subject').value = "bookEvent";
document.bookEvent.submit();
}
}
// CANCEL EVENT
function cancel(id, attendeeID)
{
var answer = confirm("Please confirm to cancel this Event");
if (answer == true)
{
var params = "eventID=" + id + "&attendeeID=" + attendeeID + "&subject=cancelEvent";
//alert(params);
getEvent(params);
}
}
// BOOK TOURNAMENT
function bookTournament(tournID, attendeeID)
{
var answer = confirm("Please confirm to book this Tournament");
if (answer == true)
{
var params = "tournID=" + tournID + "&attendeeID=" + attendeeID + "&subject=book";
getEvent(params);
}
}
// CANCEL TOURNAMENT
function cancelTournament(tournID, attendeeID)
{
var answer = confirm("Please confirm to cancel this Tournament");
if (answer == true)
{
var params = "tournID=" + tournID + "&attendeeID=" + attendeeID + "&subject=cancel";
getEvent(params);
}
}
// CANCEL SEAT
function cancelSeat(seatID, attendeeID)
{
var answer = confirm("Please confirm to cancel this Seat");
if (answer == true)
{
document.getElementById('seatID').value = seatID;
document.getElementById('attendeeID').value = attendeeID;
document.cancelThisSeat.submit();
}
}
// BOOK PIZZA
function bookPizza(pizzaID, row, attendeeID, menuID)
{
var answer = confirm("Please confirm to order this pizza");
if (answer == true)
{
var pizzaQTY = document.getElementById("pizzaQTY_"+row).selectedIndex;
var params = "pizzaID=" + pizzaID + "&qty=" + pizzaQTY + "&attendeeID=" + attendeeID + "&menuID=" + menuID + "&subject=order";
getEvent(params);
}
}
// CANCEL PIZZA
function cancelPizza(pizzaID, attendeeID, menuID)
{
var answer = confirm("Please confirm to cancel this pizza order");
if (answer == true)
{
var params = "pizzaID=" + pizzaID + "&attendeeID=" + attendeeID + "&menuID=" + menuID + "&subject=cancelOrder";
getEvent(params);
}
}
</script>
</head>
<body onload='getEvent("t=<?php if(isset($_GET['t'])){echo $_GET['t'];}else{echo "1";}?>");'>
<center>
<div id='shell'>
<!-- Main Content [left] -->
<div id="content">
<h2>
Event Registration For:
<font size="4" style='font-family: Segoe Print;'><?php echo $_SESSION['fullName']; ?></font>
</h2>
<br />
<!-- GET [this] USERS BOOKED EVENT -->
<?php
// [current] EVENT ID
$eventID = getThisEvent($db);
// GET ATTENDEE EVENT DETAILS
$get = "SELECT * FROM attendee WHERE clientID='".$_SESSION['userID']."' AND eventID='".$eventID."'";
$result = $db->query($get);
if ($result->num_rows == 0)
{
$rowEvent = 'No';
$tournID = 'No';
$seatID = 'No';
$pizzaID = 'No';
$eventStatus = 0;
}
else
{
for ($i=0; $i<$result->num_rows; $i++)
{
$row = $result->fetch_assoc();
// CHECK IF USER HAS BOOKED IN [this current] EVENT
$check = "SELECT * FROM event WHERE startDate >= CURDATE() AND event_completed = 0 AND eventID='".$eventID."'";
$resultCheck = $db->query($check);
// [this] attendee has not booked into [this] event
if ($resultCheck->num_rows == 0)
{
$rowEvent = 'No';
$tournID = 'No';
$seatID = 'No';
$pizzaID = 'No';
}
else
{
$thisEventRow = $resultCheck->fetch_assoc();
$rowEvent = 'Yes';
// GET TOURNAMENT DETAILS
// Get [this] event's tournaments
$check = "SELECT * FROM tournament WHERE eventID='".$eventID."'";
$resultCheck = $db->query($check);
if ($resultCheck->num_rows != 0)
{
for ($i=0; $i<$resultCheck->num_rows; $i++)
{
$rowTournament = $resultCheck->fetch_assoc();
$rowTournID = $rowTournament['tournID'];
$getT = "SELECT * FROM attendee_tournament WHERE attendeeID='".$row['attendeeID']."' AND tournID='".$rowTournID."'";
$resultT = $db->query($getT);
if ($resultT->num_rows != 0)
{
// User is booked into one of this events tournaments
$tournID = 'Yes';
$i = $resultCheck->num_rows;
}
else
{
// Tournament == False
$tournID = 'No';
}
}
}
else
{
$tournID = 'No';
}
// GET SEAT DETAILS
if ($row['seatID'] == '' || empty($row['seatID'])) { $seatID = 'No'; } else { $seatID = 'Yes'; }
// GET PIZZA DETAILS
// Get [this] event's menu
$check = "SELECT * FROM pizza_menu WHERE eventID='".$eventID."'";
$result = $db->query($check);
if ($result->num_rows == 0)
{
$pizzaID = 'No';
}
else
{
$rowMenu = $result->fetch_assoc();
$menuID = $rowMenu['menuID'];
// Check if user has ordered a pizza for [this] menu
$get = "SELECT * FROM pizza_order WHERE attendeeID = '".$row['attendeeID']."' AND menuID='".$menuID."'";
$result = $db->query($get);
if ($result->num_rows == 0) { $pizzaID = 'No'; } else { $pizzaID = 'Yes'; }
}
}
}
}
?>
<div class='eventSlider' align='center'>
<!-- AJAX DYNAMIC DIV -->
<div class='event'><div id='ajaxDIV'></div></div>
<?php
// SETUP MOUSE CLICK CLASSES
$onclick =
'document.getElementById("eventBUT").className="eBAR pointer"; document.getElementById("tournBUT").className="eBAR pointer"; document.getElementById("seatBUT").className="eBAR pointer"; document.getElementById("pizzaBUT").className="eBAR pointer"; this.className="eBAR_ON pointer";';
$imgTick = "<div class='eSTATUS'><img src='/cassa/images/layers/tick.png' /></div>";
$imgCross = "<div class='eSTATUS'><img src='/cassa/images/layers/cross.png' /></div>";
// CHECK IF OUTSIDE PAGE IS TRYING TO ACCESS A CERTAIN MENU BAR
// 1 = EVENT
// 2 = TOURNAMENT
// 3 = SEAT
// 4 = PIZZA
// DEFAULT = 1
$eBAR1 = 'eBAR_ON'; $eBAR2 = 'eBAR'; $eBAR3 = 'eBAR'; $eBAR4 = 'eBAR';
if(isset($_GET['t']))
{
if ($_GET['t'] == 1){$eBAR1 = 'eBAR_ON';}else{$eBAR1 = 'eBAR';}
if ($_GET['t'] == 2){$eBAR2 = 'eBAR_ON';}else{$eBAR2 = 'eBAR';}
if ($_GET['t'] == 3){$eBAR3 = 'eBAR_ON';}else{$eBAR3 = 'eBAR';}
if ($_GET['t'] == 4){$eBAR4 = 'eBAR_ON';}else{$eBAR4 = 'eBAR';}
}
?>
<!-- LEFT CONTROL PANEL -->
<div class='eventBAR'>
<div id='eventBUT'
class='pointer; <?php echo $eBAR1; ?>'
<?php if ($eventStatus == 1) { ?> onclick='getEvent("t=1"); <?php echo $onclick; }?>'>
<div class='eFONT'><font size='2'>1-</font> EVENT</div>
<?php if ($rowEvent == 'No') { echo $imgCross; } else { echo $imgTick; } ?>
</div>
<div id='tournBUT'
class='pointer; <?php echo $eBAR2; ?>'
<?php if ($eventStatus == 1) { ?> onclick='getEvent("t=2"); <?php echo $onclick; }?>'>
<div class='eFONT'><font size='2'>2-</font> TOURNAMENT</div>
<?php if ($tournID == 'No') { echo $imgCross; } else { echo $imgTick; } ?>
</div>
<div id='seatBUT'
class='pointer; <?php echo $eBAR3; ?>'
<?php if ($eventStatus == 1) { ?> onclick='getEvent("t=3"); <?php echo $onclick; }?>'>
<div class='eFONT'><font size='2'>3-</font> SEAT</div>
<?php if ($seatID == 'No') { echo $imgCross; } else { echo $imgTick; } ?>
</div>
<div id='pizzaBUT'
class='pointer; <?php echo $eBAR4; ?>'
<?php if ($eventStatus == 1) { ?> onclick='getEvent("t=4"); <?php echo $onclick; }?>'>
<div class='eFONT'><font size='2'>4-</font> PIZZA</div>
<?php if ($pizzaID == 'No') { echo $imgCross; } else { echo $imgTick; } ?>
</div>
</div>
</div>
<!-- INCLUDE THIS AFTER 'MAIN CONTENT' -->
<!--**************************************** -->
<br /><br /><br /><br />
</div><!-- end of: Content -->
<!-- INSERT: footer -->
<div id="footer">
<?php include('../includes/footer.html'); ?>
</div>
</div><!-- end of: Shell -->
</center>
</body>
</html>
<!-- ********************************* -->
<!-- INCLUDE THIS AFTER 'MAIN CONTENT' --> | cassa/megalansystem | management/eventRegistration.php | PHP | mit | 11,349 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Blogs.EfAndSprocfForCqrs.ReadModel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Blogs.EfAndSprocfForCqrs.ReadModel")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b2c68e2e-b3bd-4ff0-a856-08dd7dfb7646")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| dibley1973/Blogs.UsingEFAndSprocFToAcheiveCQRS | Code/03.QueryStack/Blogs.EfAndSprocfForCqrs.ReadModel/Properties/AssemblyInfo.cs | C# | mit | 1,444 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2013 futurecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "wallet.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
// These are all in bitcoinrpc.cpp:
extern Object JSONRPCError(int code, const string& message);
extern int64 AmountFromValue(const Value& value);
extern Value ValueFromAmount(int64 amount);
extern std::string HelpRequiringPassphrase();
extern void EnsureWalletIsUnlocked();
void
ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void
TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is non-zero, returns an Object\n"
"with information about <txid>.");
uint256 hash;
hash.SetHex(params[0].get_str());
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock))
throw JSONRPCError(-5, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listunspent [minconf=1] [maxconf=999999]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
RPCTypeCheck(params, list_of(int_type)(int_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
Array results;
vector<COutput> vecOutputs;
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
int64 nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
"sending to given address(es).\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(-8, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(-8, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(-8, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(-8, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(uint256(txid), nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(-5, string("Invalid Bitcoin address:")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
RPCTypeCheck(params, list_of(str_type));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(-22, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the blockchain.\n"
"Third optional argument is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth option is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
if (params.size() < 3)
EnsureWalletIsUnlocked();
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(-22, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(-22, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
map<COutPoint, CScript> mapPrevOut;
{
MapPrevTx mapPrevTx;
CTxDB txdb("r");
map<uint256, CTxIndex> unused;
bool fInvalid;
mergedTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid);
// Copy results into mapPrevOut:
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin)
{
const uint256& prevHash = txin.prevout.hash;
if (mapPrevTx.count(prevHash))
mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey;
}
}
// Add previous txouts given in the RPC call:
if (params.size() > 1)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(-22, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
string txidHex = find_value(prevOut, "txid").get_str();
if (!IsHex(txidHex))
throw JSONRPCError(-22, "txid must be hexadecimal");
uint256 txid;
txid.SetHex(txidHex);
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(-22, "vout must be positive");
string pkHex = find_value(prevOut, "scriptPubKey").get_str();
if (!IsHex(pkHex))
throw JSONRPCError(-22, "scriptPubKey must be hexadecimal");
vector<unsigned char> pkData(ParseHex(pkHex));
CScript scriptPubKey(pkData.begin(), pkData.end());
COutPoint outpoint(txid, nOut);
if (mapPrevOut.count(outpoint))
{
// Complain if scriptPubKey doesn't match
if (mapPrevOut[outpoint] != scriptPubKey)
{
string err("Previous output scriptPubKey mismatch:\n");
err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(-22, err);
}
}
else
mapPrevOut[outpoint] = scriptPubKey;
}
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(-5,"Invalid private key");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
tempKeystore.AddKey(key);
}
}
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(-8, "Invalid sighash param");
}
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
if (mapPrevOut.count(txin.prevout) == 0)
{
fComplete = false;
continue;
}
const CScript& prevPubKey = mapPrevOut[txin.prevout];
txin.scriptSig.clear();
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, true, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"sendrawtransaction <hex string>\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
RPCTypeCheck(params, list_of(str_type));
// parse hex string from parameter
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(-22, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
// See if the transaction is already in a block
// or in the memory pool:
CTransaction existingTx;
uint256 hashBlock = 0;
if (GetTransaction(hashTx, existingTx, hashBlock))
{
if (hashBlock != 0)
throw JSONRPCError(-5, string("transaction already in block ")+hashBlock.GetHex());
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
}
else
{
// push to local node
CTxDB txdb("r");
if (!tx.AcceptToMemoryPool(txdb))
throw JSONRPCError(-22, "TX rejected");
SyncWithWallets(tx, NULL, true);
}
RelayMessage(CInv(MSG_TX, hashTx), tx);
return hashTx.GetHex();
}
| wire306/futurecoin | src/rpcrawtransaction.cpp | C++ | mit | 17,383 |
<?php
/**
* For the full copyright and license information, please view
* the file license.txt that was distributed with this source code.
*
* @author Martin Štekl <martin.stekl@gmail.com>
* @since 2011.06.26
* @license MIT
* @copyright Copyright (c) 2011, 2012 Martin Štekl <martin.stekl@gmail.com>
*/
namespace stekycz\gallery\Model;
use \Nette\InvalidStateException;
use \Nette\InvalidArgumentException;
/**
* Contains basic implementation for group model.
*/
class Group extends AGroup {
/**
* Creates new group.
*
* @param array $data Data for new group
* @return int|string GroupID
* @throws \Nette\InvalidArgumentException|\Nette\InvalidStateException
*/
public function create(array $data) {
$insert_data = array(
'is_active' => true, 'namespace_id' => static::DEFAULT_NAMESPACE_ID,
);
foreach ($data as $key => $value) {
if (!$value) {
unset($data[$key]);
} elseif ($key != static::FORM_FILES_KEY) {
$insert_data[$key] = $value;
}
}
if (!($difference = array_diff(static::$basicColumns, array_keys($insert_data)))) {
throw new InvalidStateException('Missing required fields [' . implode(', ', $difference) . '].');
}
if ($this->namespace_id != static::DEFAULT_NAMESPACE_ID) {
$insert_data['namespace_id'] = $this->namespace_id;
}
if (isset($data[static::FORM_FILES_KEY])) {
$files = $data[static::FORM_FILES_KEY];
} else {
throw new InvalidArgumentException('You should not inicialize gallery without any photos.');
}
$gallery_id = $this->dataProvider->createGroup($insert_data);
$this->insertFiles($files, $gallery_id);
return $gallery_id;
}
/**
* Updates group. It means add photos and change extended info. If extended
* info does not exist it will be inserted.
*
* @param array $data
* @return int|string
* @throws \Nette\InvalidArgumentException
*/
public function update(array $data) {
if (!array_key_exists('gallery_id', $data)) {
throw new InvalidArgumentException('Given data do not contain gallery_id.');
}
$gallery_id = $data['gallery_id'];
$previous_data = $this->getById($gallery_id);
$update_data = array();
foreach ($data as $key => $value) {
if ($key != static::FORM_FILES_KEY && $previous_data[$key] != $value) {
$update_data[$key] = $value;
}
}
$files = array();
if (isset($data[static::FORM_FILES_KEY])) {
$files = $data[static::FORM_FILES_KEY];
}
$this->dataProvider->updateGroup($gallery_id, $update_data);
if ($files) {
$this->insertFiles($files, $gallery_id);
}
return $gallery_id;
}
/**
* Inserts given files into group by group_id.
*
* @param \Nette\Http\FileUpload[] $files
* @param int $group_id
*/
protected function insertFiles(array $files, $group_id) {
$files_data = array(
'gallery_id' => $group_id,
);
$itemModel = new Item($this->dataProvider, $this->basePath);
foreach ($files as $file) {
$files_data[AItem::FILE_KEY] = $file;
$itemModel->create($files_data);
}
}
/**
* @param int $id
*/
public function toggleActive($id) {
$this->dataProvider->toggleActiveGroup($id);
}
/**
* @param int $id
*/
public function delete($id) {
$this->deleteFolder($id);
$this->dataProvider->deleteGroup($id);
}
/**
* Deletes whole folder of group.
*
* @param int $id Gallery ID
*/
protected function deleteFolder($id) {
$itemModel = new Item($this->dataProvider, $this->basePath);
$photos = $itemModel->getByGallery($id, true);
foreach ($photos as $photo) {
$itemModel->delete($photo['photo_id']);
}
$regular_dir_path = $this->getPathGallery($id);
if (is_dir($regular_dir_path)) {
rmdir($regular_dir_path);
}
}
/**
* @return string
*/
public function getPathNamespace() {
return $this->basePath . '/' . $this->getCurrentNamespaceName();
}
/**
* @return string
*/
protected function getCurrentNamespaceName() {
return $this->dataProvider->namespaces[$this->namespace_id];
}
/**
* @param int $id GroupID
* @return string
*/
public function getPathGallery($id) {
return $this->getPathNamespace() . '/' . $id;
}
/**
* @param bool $admin
* @return int
*/
public function getCount($admin = false) {
return $this->dataProvider->countGroups($this->namespace_id, $admin);
}
/**
* @param int $page
* @param int $itemPerPage
* @param bool $admin
* @return array
*/
public function getAll($page = 1, $itemPerPage = 25, $admin = false) {
return $this->dataProvider->getAllGroups($this->namespace_id, $admin, $page, $itemPerPage);
}
/**
* @param int $id
* @return array
*/
public function getById($id) {
return $this->dataProvider->getGroupById($id);
}
}
| stekycz/gallery-nette-plugin | Model/Group.php | PHP | mit | 4,695 |
<?php
namespace aplicacion\EmisionesBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RevisionType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('numeroOrden','text',array('attr'=>array('class' => 'form-control input-sm','readOnly'=>true)))
->add('tarjet','text',array('attr'=>array('class' => 'form-control input-sm','readOnly'=>true)))
->add('agente', 'entity', array(
'class' => 'EmisionesBundle:Agente',
'property'=>'getNombreCompleto',
'attr'=> array('class' => 'form-control input-sm')
))
->add('gds', 'entity', array(
'class' => 'EmisionesBundle:Gds',
'property'=>'nombre',
'attr'=> array('class' => 'form-control input-sm')
))
->add('tipoBoleto','text',array('attr'=>array('class' => 'form-control input-sm')))
->add('estado', 'entity', array(
'class' => 'EmisionesBundle:Estadoorden',
'property'=>'nombre',
'attr'=> array('class' => 'form-control input-sm','size'=>7,'style'=>'height:70px;')
))
->add('ciudadDestino', 'entity', array(
'class' => 'EmisionesBundle:Ciudad',
'property'=>'nombre',
'attr'=> array('class' => 'form-control input-sm')
))
->add('recordGds','text',array('attr'=>array('class' => 'form-control input-sm ','readOnly'=>true)))
->add('recordNew','text',array('required'=>true,'attr'=>array('class' => 'form-control input-sm ')))
->add('tourcode','text',array('required'=>false,'attr'=>array('class' => 'form-control input-sm','readOnly'=>true)))
->add('feeServicios','text',array('attr'=>array('class' => 'form-control input-sm')))
->add('fecha','datetime',array('widget'=>'single_text', 'format' => 'dd-MM-yyyy -- H:m:s','attr'=>array('class' => 'form-control input-sm')))
->add('reservaPnr','textarea',array('attr'=>array('id'=>'reservapnr','class'=>'form-control','cols'=>80,'readonly'=>true,'style'=>'height:370px;')))
->add('tarifaReserva','textarea',array('attr'=>array('id'=>'tarifareserva','class'=>'form-control','cols'=>80,'readonly'=>true,'style'=>'height:240px;')))
->add('observaciones','textarea',array('required'=>false,'attr'=>array('id'=>'observaciones','class'=>'form-control','readonly'=>true,'style'=>'height:100px;')))
->add('comentario','textarea',array('required'=>false,'attr'=>array('id'=>'comentario','class'=>'form-control','style'=>'height:100px;')))
// ->add('reservaPnr')
// ->add('tarifaReserva')
->add('datosBoleto','textarea',array('attr'=>array('id'=>'datosBoleto','class'=>'form-control','readonly'=>true,'style'=>'height:100px;')))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'aplicacion\EmisionesBundle\Entity\Revision'
));
}
/**
* @return string
*/
public function getName()
{
return 'aplicacion_emisionesbundle_revision';
}
}
| angelquin1986/kobra | src/aplicacion/EmisionesBundle/Form/RevisionType.php | PHP | mit | 3,637 |
using System;
using System.Threading;
using DeployService.Common.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace DeploymentJobs.DataAccess
{
public interface IDeploymentJobsCleaner
{
void Start();
void Stop();
}
public class DeploymentJobsCleaner : IDeploymentJobsCleaner
{
private readonly ILogger<DeploymentJobsCleaner> _logger;
private IDeploymentJobDataAccess _jobDataAccess;
private readonly Timer _cleanerTimer;
private TimeSpan _timerPeriod;
public DeploymentJobsCleaner(
ILogger<DeploymentJobsCleaner> logger,
IDeploymentJobDataAccess jobDataAccess,
IOptions<DeploymentJobsCleanerOptions> options)
{
_jobDataAccess = jobDataAccess;
_logger = logger;
_timerPeriod = options.Value.JobCleanupTimespan;
_cleanerTimer = new Timer(
this.CleanupEventHandler,
null,
Timeout.Infinite,
Timeout.Infinite);
}
public void Start()
{
_cleanerTimer.Change(TimeSpan.Zero, _timerPeriod);
_logger.LogInformation($"Deployment jobs cleaner started at {DateTime.Now}");
}
public void Stop()
{
_cleanerTimer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1));
_logger.LogInformation($"Deployment jobs cleaner stopped at {DateTime.Now}");
}
private void CleanupEventHandler(object state)
{
try
{
_jobDataAccess.DeleteAllFinished();
_logger.LogInformation($"Cleaned jobs at {DateTime.Now}");
}
catch(Exception ex)
{
_logger.LogError("Exception occured when removing deployment jobd.", ex);
}
}
}
} | MargaretKrutikova/deploy-script-runner-web-api | DeployService/DeploymentJobs.DataAccess/DeploymentJobsCleaner.cs | C# | mit | 1,936 |
<?php
namespace Concise\Mock;
use Concise\Core\TestCase;
class ArgumentMatcherTest extends TestCase
{
/**
* @var ArgumentMatcher
*/
protected $matcher;
public function setUp()
{
parent::setUp();
$this->matcher = new ArgumentMatcher();
}
public function testMatchingZeroArgumentsReturnsTrue()
{
$this->assert($this->matcher->match(array(), array()))->isTrue;
}
public function testMatchingArraysOfDifferentSizesReturnsFalse()
{
$this->assert($this->matcher->match(array(), array('a')))->isFalse;
}
public function testMatchingWithOneValueThatIsDifferentReturnsFalse()
{
$this->assert($this->matcher->match(array('b'), array('a')))->isFalse;
}
public function testMatchingIsNotExact()
{
$this->assert($this->matcher->match(array(0), array(false)))->isTrue;
}
public function testMatchingMoreThanOneItemWhereOnlyOneIsDifferentReturnsFalse()
{
$this->assert(
$this->matcher->match(array('a', 'b'), array('a', 'a'))
)->isFalse;
}
public function testExpectedIsAllowedToContainAnythingConstant()
{
$this->assert(
$this->matcher->match(array('a', self::ANYTHING), array('a', 'a'))
)->isTrue;
}
}
| elliotchance/concise | tests/Concise/Mock/ArgumentMatcherTest.php | PHP | mit | 1,305 |
// TInjector: TInjector
// ScopeType.cs
// Created: 2015-10-17 5:54 PM
namespace TInjector
{
/// <summary>
/// Represents the supported scope types.
/// </summary>
public enum Scope
{
/// <summary>
/// A new instance is created each time the service is requested.
/// </summary>
Transient = 0,
/// <summary>
/// A new instance is created once per root, after that no new instances are ever created by that root.
/// </summary>
Singleton = 1,
/// <summary>
/// A new instance is created for each object graph.
/// The instance will be shared by all objects created as a result of the call to the root.
/// </summary>
Graph = 2
}
} | bungeemonkee/TInjector | TInjector/Scope.cs | C# | mit | 783 |
#pragma once
#include "variant.hh"
namespace drift
{
namespace schemy
{
namespace lib
{
variant_ptr print(const list&);
variant_ptr println(const list&);
variant_ptr readln(const list&);
variant_ptr foreach(const list&);
}
}
} | Racinettee/drift-scheme | lib.hh | C++ | mit | 247 |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { Routes,RouterModule } from '@angular/router';
import {MaterialModule} from '@angular/material';
import 'hammerjs';
import { MainframeComponent } from './mainframe.component';
import { dashBoardComponent } from './dashboard/dashboard.component';
import { NavbarComponent} from '../mainframe/navbar/navbar.component';
import { SideNav } from './side_nav/side-nav.component';
import { ContentModule } from '../content/content.module';
import { NotificationComponent } from './left-nav-msg/notification.component';
import { SharedModule } from '@teds2/shared.module';
import { Teds2ChartModule } from '@teds2/Chart';
import { DirectiveModule } from '../main_modules/Directives/directive.module';
//import { LoginService } from '../content/login-panel/login.service';
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
SharedModule,
Teds2ChartModule,
ContentModule,
DirectiveModule,
RouterModule.forChild([
{
path:'teds',
component:MainframeComponent,
children:[
{
path:'dashboard',
component:dashBoardComponent
},
{
path:'content',
loadChildren:'client/app/content/content.module#ContentModule'
},
{
path:'/teds',
redirectTo:'teds/dashboard',
pathMatch:'full'
},
]
},
// ContentModule,
]),
MaterialModule.forRoot()
],
declarations: [
MainframeComponent,
NavbarComponent,
SideNav,
NotificationComponent,
dashBoardComponent
],
exports: [ RouterModule ],
providers: [ ]
})
export class MainFrameModule { }
| sayanuIT/teds2 | src/client/app/mainframe/mainframe.module.ts | TypeScript | mit | 2,120 |
/**
* Grunt Project
* https://github.com/sixertoy/generator-grunt-project
*
* Copyright (c) 2014 Matthieu Lassalvy
* Licensed under the MIT license.
*
* Generate folder and files for a grunt project
* with grunt basic tasks, jasmine unit testing, istanbul coverage and travis deployement
*
* @insatll npm install grunt-cli yo bower -g
* @usage yo grunt-project
*
*
*/
/*global require, process, module */
(function () {
'use strict';
var eZHTMLGenerator,
Q = require('q'),
path = require('path'),
yosay = require('yosay'),
lodash = require('lodash'),
slugify = require('slugify'),
AppBones = require('appbones'),
pkg = require('../../package.json'),
generators = require('yeoman-generator');
eZHTMLGenerator = generators.Base.extend({
constructor: function () {
generators.Base.apply(this, arguments);
this.option('skip-install', {
desc: 'Skip the bower and node installations',
defaults: false
});
},
initializing: function () {
// custom templates delimiter
this.config.set('rdim', '%>');
this.config.set('ldim', '<%=');
this.log(yosay('Hello sir, welcome to the awesome ezhtml generator v' + pkg.version));
},
prompting: function () {
var $this = this,
prompts = [],
done = this.async();
// project name
prompts.push({
type: 'input',
name: 'projectname',
message: 'Project name',
default: slugify(this.determineAppname())
});
prompts.push({
type: 'input',
name: 'username',
message: 'Repository user name',
default: this.user.git.name() || process.env.user || process.env.username
});
prompts.push({
type: 'input',
name: 'useremail',
message: 'Repository user email',
default: this.user.git.email() || 'you@mail.com'
});
// project name
prompts.push({
type: 'input',
name: 'projectdescription',
message: 'Project description',
default: 'Project generated with Yeoman generator-ezhtml v' + pkg.version
});
prompts.push({
type: 'input',
name: 'projectrepository',
message: 'Project repository url',
default: function (values) {
return 'https://github.com' + '/' + values.username + '/' + values.projectname;
}
});
this.prompt(prompts, function (values) {
this.config.set('author', {
name: values.username,
email: values.useremail
});
this.config.set('project', {
name: values.projectname,
repository: values.projectrepository,
description: values.projectdescription
});
done();
}.bind(this));
},
configuring: function () {
// this.composeWith('ezhtml:conditionnals', {});
if (!this.options['skip-install']) {
this.composeWith('ezhtml:scripts', {});
this.composeWith('ezhtml:styles', {});
}
},
writing: function () {
var $this = this,
done = this.async(),
data = this.config.getAll(),
bones = path.resolve(this.templatePath(), '../bones.yml'),
appbones = new AppBones(this.templatePath(), this.destinationPath());
Q.delay((function () {
appbones.build(bones, data);
}()), 1500).then((function () {
done();
}()));
},
install: function () {
if (!this.options['skip-install']) {
this.npmInstall();
}
},
end: function () {}
});
module.exports = eZHTMLGenerator;
}());
| sixertoy/generator-ezhtml | generators/app/index.js | JavaScript | mit | 4,305 |
require 'bundler'
Bundler.setup
require 'minitest/pride'
require 'minitest/spec'
require 'minitest/autorun'
require 'tmpdir'
$: << File.expand_path('../../lib', __FILE__)
require 'todo'
| benpickles/todo | test/helper.rb | Ruby | mit | 189 |
<?php
namespace Anax\MVC;
/**
* Model for Users.
*
*/
class CDatabaseModel implements \Anax\DI\IInjectionAware
{
use \Anax\DI\TInjectable;
/**
* Find and return all.
*
* @return array
*/
public function findAll($tableName = null)
{
$source = $this->getSource();
if($tableName != null){
$source = $tableName;
}
$this->db->select()
->from($source);
$this->db->execute();
$this->db->setFetchModeClass(__CLASS__);
return $this->db->fetchAll();
}
/**
* Find and return specific.
*
* @return this
*/
public function find($id)
{
$this->db->select()
->from($this->getSource())
->where("id = ?");
$this->db->execute([$id]);
return $this->db->fetchInto($this);
}
/**
* Find and return specific.
*
* @return this
*/
public function findUser($acronym, $password)
{
$this->db->select('id, acronym, medlemsTyp')
->from('users')
->where("acronym = '".$acronym."'")
->andWhere('password = md5(concat("'.$password.'", salt))');
$this->db->execute();
return $this->db->fetchAll();
}
/**
* Find and return specific.
*
* @return this
*/
public function getSearch($textField, $table)
{
if($textField == null || empty($textField)){
$this->db->select(' q.*,
u.acronym as user,
GROUP_CONCAT(DISTINCT t.name ORDER BY t.name) as tags
from questions as q')
->join('questions2tags as Q2T', 'q.id = Q2T.idQuestions')
->join('users as u', 'q.user = u.id')
->join('tags as t', 'Q2T.idTags = t.id')
->where('q.titel LIKE "%'.$textField.'%" OR t.name LIKE "%'.$textField.'%"')
->groupBy('q.id')
->orderBy('q.created DESC')
->execute();
return $this->db->fetchAll();
}
else{
$this->db
->select('
q.*,
u.acronym as user,
GROUP_CONCAT(DISTINCT t.name ORDER BY t.name) as tags
from questions as q')
->join('questions2tags as Q2T', 'q.id = Q2T.idQuestions')
->join('users as u', 'q.user = u.id')
->join('tags as t', 'Q2T.idTags = t.id')
->groupBy('q.id')
->orderBy('q.created DESC')
->execute();
return $this->db->fetchAll();
}
}
/**
* Find and return specific.
*
* @return this
*/
public function updateUser($id, $array, $table, $password)
{
if($password){
$this->db->update(
$table,
[
'email' => '?',
'lastName' => '?',
'firstName' => '?',
'password' => '?',
],
"id = ?"
);
}
else{
$this->db->update(
$table,
[
'email' => '?',
'lastName' => '?',
'firstName' => '?',
],
"id = ?"
);
}
return $this->db->execute(array_merge($array, [$id]));
}
/**
* Save current object/row.
*
* @param array $values key/values to save or empty to use object properties.
*
* @return boolean true or false if saving went okey.
*/
public function save($values = [], $tableName = null)
{
if (isset($values['id'])) {
$this->setProperties($values);
$values = $this->getProperties();
}
if (isset($values['id'])) {
return $this->update($values, $tableName);
} else {
return $this->create($values, $tableName);
}
}
/**
* Create new row.
*
* @param array $values key/values to save.
*
* @return boolean true or false if saving went okey.
*/
public function create($values, $tableName = null)
{
$keys = array_keys($values);
$values = array_values($values);
if($tableName == null){
$this->db->insert(
$this->getSource(),
$keys
);
}
else{
$this->db->insert(
$tableName,
$keys
);
}
$res = $this->db->execute($values);
$this->id = $this->db->lastInsertId();
return $res;
}
/**
* Update row.
*
* @param array $values key/values to save.
*
* @return boolean true or false if saving went okey.
*/
public function update($values, $tableName = null)
{
$keys = array_keys($values);
$values = array_values($values);
// Its update, remove id and use as where-clause
unset($keys['id']);
$values[] = $this->id;
if($tableName == null){
$this->db->update(
$this->getSource(),
$keys,
"id = ?"
);
}
else{
$this->db->update(
$tableName,
$keys,
"id = ?"
);
}
return $this->db->execute($values);
}
/**
* Delete row.
*
* @param integer $id to delete.
*
* @return boolean true or false if deleting went okey.
*/
public function delete($id)
{
$this->db->delete(
$this->getSource(),
'id = ?'
);
return $this->db->execute([$id]);
}
/**
* Delete row.
*
* @param integer $id to delete.
*
* @return boolean true or false if deleting went okey.
*/
public function softDelete($id)
{
$this->db->delete(
$this->getSource(),
'id = ?'
);
return $this->db->execute([$id]);
}
/**
* Set object properties.
*
* @param array $properties with properties to set.
*
* @return void
*/
public function setProperties($properties)
{
// Update object with incoming values, if any
if (!empty($properties)) {
foreach ($properties as $key => $val) {
$this->$key = $val;
}
}
}
/**
* Get object properties.
*
* @return array with object properties.
*
* Jag skapar även metoden getProperties() som returnerar de properties som har med modellens databastabell att göra.
* Jag använder metoden get_object_vars() för att hämta objektets properties. Sedan tar jag bort de properties som jag inte vill visa, i detta fallet $di och $db
*/
public function getProperties()
{
$properties = get_object_vars($this);
unset($properties['di']);
unset($properties['db']);
return $properties;
}
/**
* Get the table name.
*
* @return string with the table name.
*
* Detta är en metod som hämtar klassens namn och strippar bort eventuellt namespace. Kvar bli User som är modell-klassens namn och namnet på tabellen i databasen, som döpts till user.
*/
public function getSource()
{
return strtolower(implode('', array_slice(explode('\\', get_class($this)), -1)));
}
/**
* Build a select-query.
*
* @param string $columns which columns to select.
*
* @return $this
*/
public function query($columns = '*')
{
$this->db->select($columns)
->from($this->getSource());
return $this;
}
/**
* Build the where part.
*
* @param string $condition for building the where part of the query.
*
* @return $this
*/
public function where($condition)
{
$this->db->where($condition);
return $this;
}
/**
* Build the where part.
*
* @param string $condition for building the where part of the query.
*
* @return $this
*/
public function andWhere($condition)
{
$this->db->andWhere($condition);
return $this;
}
/**
* Build the where part.
*
* @param string $condition for building the where part of the query.
*
* @return $this
*/
public function orderBy($condition)
{
$this->db->orderBy($condition);
return $this;
}
/**
* Execute the query built.
*
* @param string $query custom query.
*
* @return $this
*/
public function execute($params = [])
{
$this->db->execute($this->db->getSQL(), $params);
$this->db->setFetchModeClass(__CLASS__);
return $this->db->fetchAll();
}
}
| phphille/aab | src/MVC/CDatabaseModel.php | PHP | mit | 9,267 |
const debug = require('ghost-ignition').debug('importer:posts'),
_ = require('lodash'),
uuid = require('uuid'),
BaseImporter = require('./base'),
converters = require('../../../../lib/mobiledoc/converters'),
validation = require('../../../validation');
class PostsImporter extends BaseImporter {
constructor(allDataFromFile) {
super(allDataFromFile, {
modelName: 'Post',
dataKeyToImport: 'posts',
requiredFromFile: ['posts', 'tags', 'posts_tags', 'posts_authors'],
requiredImportedData: ['tags'],
requiredExistingData: ['tags']
});
}
sanitizeAttributes() {
_.each(this.dataToImport, (obj) => {
if (!validation.validator.isUUID(obj.uuid || '')) {
obj.uuid = uuid.v4();
}
});
}
/**
* Naive function to attach related tags and authors.
*/
addNestedRelations() {
this.requiredFromFile.posts_tags = _.orderBy(this.requiredFromFile.posts_tags, ['post_id', 'sort_order'], ['asc', 'asc']);
this.requiredFromFile.posts_authors = _.orderBy(this.requiredFromFile.posts_authors, ['post_id', 'sort_order'], ['asc', 'asc']);
/**
* from {post_id: 1, tag_id: 2} to post.tags=[{id:id}]
* from {post_id: 1, author_id: 2} post.authors=[{id:id}]
*/
const run = (relations, target, fk) => {
_.each(relations, (relation) => {
if (!relation.post_id) {
return;
}
let postToImport = _.find(this.dataToImport, {id: relation.post_id});
// CASE: we won't import a relation when the target post does not exist
if (!postToImport) {
return;
}
if (!postToImport[target] || !_.isArray(postToImport[target])) {
postToImport[target] = [];
}
// CASE: detect duplicate relations
if (!_.find(postToImport[target], {id: relation[fk]})) {
postToImport[target].push({
id: relation[fk]
});
}
});
};
run(this.requiredFromFile.posts_tags, 'tags', 'tag_id');
run(this.requiredFromFile.posts_authors, 'authors', 'author_id');
}
/**
* Replace all identifier references.
*/
replaceIdentifiers() {
const ownerUserId = _.find(this.requiredExistingData.users, (user) => {
if (user.roles[0].name === 'Owner') {
return true;
}
}).id;
const run = (postToImport, postIndex, targetProperty, tableName) => {
if (!postToImport[targetProperty] || !postToImport[targetProperty].length) {
return;
}
let indexesToRemove = [];
_.each(postToImport[targetProperty], (object, index) => {
// this is the original relational object (old id)
let objectInFile = _.find(this.requiredFromFile[tableName], {id: object.id});
if (!objectInFile) {
let existingObject = _.find(this.requiredExistingData[tableName], {id: object.id});
// CASE: is not in file, is not in db
if (!existingObject) {
indexesToRemove.push(index);
return;
} else {
this.dataToImport[postIndex][targetProperty][index].id = existingObject.id;
return;
}
}
// CASE: search through imported data.
// EDGE CASE: uppercase tag slug was imported and auto modified
let importedObject = _.find(this.requiredImportedData[tableName], {originalSlug: objectInFile.slug});
if (importedObject) {
this.dataToImport[postIndex][targetProperty][index].id = importedObject.id;
return;
}
// CASE: search through existing data by unique attribute
let existingObject = _.find(this.requiredExistingData[tableName], {slug: objectInFile.slug});
if (existingObject) {
this.dataToImport[postIndex][targetProperty][index].id = existingObject.id;
} else {
indexesToRemove.push(index);
}
});
this.dataToImport[postIndex][targetProperty] = _.filter(this.dataToImport[postIndex][targetProperty], ((object, index) => {
return indexesToRemove.indexOf(index) === -1;
}));
// CASE: we had to remove all the relations, because we could not match or find the relation reference.
// e.g. you import a post with multiple authors. Only the primary author is assigned.
// But the primary author won't be imported and we can't find the author in the existing database.
// This would end in `post.authors = []`, which is not allowed. There must be always minimum one author.
// We fallback to the owner user.
if (targetProperty === 'authors' && !this.dataToImport[postIndex][targetProperty].length) {
this.dataToImport[postIndex][targetProperty] = [{
id: ownerUserId
}];
}
};
_.each(this.dataToImport, (postToImport, postIndex) => {
run(postToImport, postIndex, 'tags', 'tags');
run(postToImport, postIndex, 'authors', 'users');
});
return super.replaceIdentifiers();
}
beforeImport() {
debug('beforeImport');
this.sanitizeAttributes();
this.addNestedRelations();
_.each(this.dataToImport, (model) => {
// NOTE: we remember the original post id for disqus
// (see https://github.com/TryGhost/Ghost/issues/8963)
// CASE 1: you import a 1.0 export (amp field contains the correct disqus id)
// CASE 2: you import a 2.0 export (we have to ensure we use the original post id as disqus id)
if (model.id && model.amp) {
model.comment_id = model.amp;
delete model.amp;
} else {
if (!model.comment_id) {
model.comment_id = model.id;
}
}
// CASE 1: you are importing old editor posts
// CASE 2: you are importing Koenig Beta posts
if (model.mobiledoc || (model.mobiledoc && model.html && model.html.match(/^<div class="kg-card-markdown">/))) {
let mobiledoc;
try {
mobiledoc = JSON.parse(model.mobiledoc);
if (!mobiledoc.cards || !_.isArray(mobiledoc.cards)) {
model.mobiledoc = converters.mobiledocConverter.blankStructure();
mobiledoc = model.mobiledoc;
}
} catch (err) {
mobiledoc = converters.mobiledocConverter.blankStructure();
}
mobiledoc.cards.forEach((card) => {
if (card[0] === 'image') {
card[1].cardWidth = card[1].imageStyle;
delete card[1].imageStyle;
}
});
model.mobiledoc = JSON.stringify(mobiledoc);
model.html = converters.mobiledocConverter.render(JSON.parse(model.mobiledoc));
}
});
// NOTE: We only support removing duplicate posts within the file to import.
// For any further future duplication detection, see https://github.com/TryGhost/Ghost/issues/8717.
let slugs = [];
this.dataToImport = _.filter(this.dataToImport, (post) => {
if (slugs.indexOf(post.slug) !== -1) {
this.problems.push({
message: 'Entry was not imported and ignored. Detected duplicated entry.',
help: this.modelName,
context: JSON.stringify({
post: post
})
});
return false;
}
slugs.push(post.slug);
return true;
});
// NOTE: do after, because model properties are deleted e.g. post.id
return super.beforeImport();
}
doImport(options, importOptions) {
return super.doImport(options, importOptions);
}
}
module.exports = PostsImporter;
| tannermares/ghost | core/server/data/importer/importers/data/posts.js | JavaScript | mit | 8,682 |
mod rewrite
<?php
echo in_array('mod_rewrite', apache_get_modules());
?> | DanielHirunrusme/so-il | test.php | PHP | mit | 76 |
require 'awesome_nested_set'
module DatabaseI18n
class Key < ::ActiveRecord::Base
self.table_name = 'translation_keys'
acts_as_nested_set dependent: :destroy, counter_cache: :children_count
has_one :value, class_name: 'DatabaseI18n::Value', dependent: :destroy
def path
self_and_ancestors.pluck(:name).join('.')
end
end
end
| kogulko/database-i18n | lib/database_i18n/models/key.rb | Ruby | mit | 358 |
namespace ZeroLog
{
internal unsafe class UnpooledLogEvent : LogEvent
{
public UnpooledLogEvent(BufferSegment bufferSegment, int argCapacity)
: base(bufferSegment, argCapacity)
{
}
public override bool IsPooled => false;
public override string ToString()
{
return $"buffer length: {_endOfBuffer - _startOfBuffer}, data length: {_dataPointer - _startOfBuffer}, first arg type: {(ArgumentType)(*_startOfBuffer)}";
}
}
}
| Abc-Arbitrage/ZeroLog | src/ZeroLog/UnpooledLogEvent.cs | C# | mit | 512 |
/*
The MIT License (MIT)
Copyright (c) 2014 Robert C. Robinson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.ravenmistmedia.MyHealthRecords;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import com.ravenmistmedia.MyHealthRecords.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
public class DBAdminActivity extends Activity {
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//MyHealthRecords//");
private String mChosenFile;
private static final String FTYPE = ".txt";
private static final int DIALOG_LOAD_FILE = 1000;
private ProgressDialog dPleaseWait;
String s = "Blue";
protected void onResume() {
Common.CheckLogin(this);
super.onResume();
try {
LinearLayout l = (LinearLayout) findViewById( R.id.LayoutDBAdmin );
final DBAdapter db = new DBAdapter(this);
db.open();
s = db.getSetting("BackgroundColor");
db.close();
if(s.equals("")|| s.equals("Blue")){
l.setBackgroundResource(R.drawable.backrepeat);
} else if (s.equals("Lavender")){
l.setBackgroundResource(R.drawable.backrepeat2);
} else if (s.equals("Peach")){
l.setBackgroundResource(R.drawable.backrepeat3);
} else if (s.equals("Green")){
l.setBackgroundResource(R.drawable.backrepeat4);
}
l = (LinearLayout) findViewById( R.id.LayoutButtons );
if(s.equals("")|| s.equals("Blue")){
l.setBackgroundResource(R.drawable.backrepeat);
} else if (s.equals("Lavender")){
l.setBackgroundResource(R.drawable.backrepeat2);
} else if (s.equals("Peach")){
l.setBackgroundResource(R.drawable.backrepeat3);
} else if (s.equals("Green")){
l.setBackgroundResource(R.drawable.backrepeat4);
}
} catch (Exception e){}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Common.CheckLogin(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.dbadmin);
String[] menuitems = getResources().getStringArray(R.array.optionsmenu_array);
this.setTitle(menuitems[1]);
}
public void dbReset(View v){
final DBAdapter db = new DBAdapter(this);
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.warning)
.setMessage(R.string.warningMessage)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dPleaseWait = ProgressDialog.show(DBAdminActivity.this, "","Please wait...", true);
db.open();
db.dropAndCreateTables();
db.close();
dPleaseWait.dismiss();
Toast t = Toast.makeText(DBAdminActivity.this, "The database has been reset.", Toast.LENGTH_SHORT);
t.show();
}
})
.setNegativeButton(R.string.no, null)
.show();
}
public void dbExport(View v)
{
final Dialog dialog = new Dialog(DBAdminActivity.this);
dialog.setContentView(R.layout.dbadminexport);
dialog.setTitle(getResources().getString(R.string.inputTitle));
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
LinearLayout l = (LinearLayout) dialog.findViewById( R.id.LayoutDBAdminExport);
if(s.equals("")|| s.equals("Blue")){
l.setBackgroundResource(R.drawable.backrepeat);
} else if (s.equals("Lavender")){
l.setBackgroundResource(R.drawable.backrepeat2);
} else if (s.equals("Peach")){
l.setBackgroundResource(R.drawable.backrepeat3);
} else if (s.equals("Green")){
l.setBackgroundResource(R.drawable.backrepeat4);
}
final DBAdapter db = new DBAdapter(this);
final Spinner spnTableName = (Spinner) dialog.findViewById(R.id.spnTableName);
String[] tablenames = getResources().getStringArray(R.array.tablenames_array);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, tablenames);
spnTableName.setAdapter(spinnerArrayAdapter);
Button dialogmExport = (Button) dialog.findViewById(R.id.btnDBExport);
final RadioButton radXML = (RadioButton) dialog.findViewById(R.id.btnXMLOutput);
final RadioButton radTXT= (RadioButton) dialog.findViewById(R.id.btnTXTOutput);
final EditText edtOutputFile = (EditText) dialog.findViewById(R.id.edtLocationToExport);
radXML.setChecked(true);
radXML.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edtOutputFile.setText(R.string.ExportLocation);
}
});
radTXT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edtOutputFile.setText(R.string.ExportLocation2);
}
});
dialogmExport.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dPleaseWait = ProgressDialog.show(v.getContext(), "","Please wait...", true);
final String outputFile = edtOutputFile.getText().toString();
final String tableName = spnTableName.getSelectedItem().toString();
if (radXML.isChecked()){
db.ExportXML(outputFile, tableName);
}
if (radTXT.isChecked())
{
db.ExportTXT(outputFile, tableName);
}
dPleaseWait.dismiss();
dialog.dismiss();
Toast t = Toast.makeText(DBAdminActivity.this, "All records have been exported.", Toast.LENGTH_SHORT);
t.show();
};
});
dialog.show();
}
public void dbImport(View v)
{
final Dialog dialog = new Dialog(DBAdminActivity.this);
dialog.setContentView(R.layout.dbadminimport);
dialog.setTitle(getResources().getString(R.string.inputTitle));
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
LinearLayout l = (LinearLayout) dialog.findViewById( R.id.LayoutDBAdminImport);
if(s.equals("")|| s.equals("Blue")){
l.setBackgroundResource(R.drawable.backrepeat);
} else if (s.equals("Lavender")){
l.setBackgroundResource(R.drawable.backrepeat2);
} else if (s.equals("Peach")){
l.setBackgroundResource(R.drawable.backrepeat3);
} else if (s.equals("Green")){
l.setBackgroundResource(R.drawable.backrepeat4);
}
final DBAdapter db = new DBAdapter(this);
final Spinner spnTableName = (Spinner) dialog.findViewById(R.id.spnTableNameI);
String[] tablenames = getResources().getStringArray(R.array.tablenames_array);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, tablenames);
spnTableName.setAdapter(spinnerArrayAdapter);
final Spinner spnInputFile = (Spinner) dialog.findViewById(R.id.spnFileToImport);
List<String> filenames = new ArrayList<String>();
File sdDir = Environment.getExternalStorageDirectory();
String sSdDir = sdDir.toString();
String mhrFolder = sSdDir + "/MyHealthRecords/";
File f = new File(mhrFolder);
File file[] = f.listFiles();
for (int i=0; i < file.length; i++)
{
String filename = file[i].getName();
if (filename.toUpperCase().contains(".XML")) {
filenames.add(file[i].getName());
}
}
ArrayAdapter<String> spinnerArrayAdapter2 = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, filenames);
spinnerArrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnInputFile.setAdapter(spinnerArrayAdapter2);
Button dialogmImport = (Button) dialog.findViewById(R.id.btnDBImport);
dialogmImport.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dPleaseWait = ProgressDialog.show(v.getContext(), "","Please wait...", true);
final String inputFile = spnInputFile.getSelectedItem().toString();
final String tableName = spnTableName.getSelectedItem().toString();
db.open();
boolean b = db.ImportXML(inputFile, tableName);
db.close();
dPleaseWait.dismiss();
if (b){
dialog.dismiss();
Toast t = Toast.makeText(DBAdminActivity.this, "All records have been imported.", Toast.LENGTH_SHORT);
t.show();
} else {
Toast t = Toast.makeText(DBAdminActivity.this, "The XML file is not in the correct format for the selected table.", Toast.LENGTH_LONG);
t.show();
}
};
});
dialog.show();
}
public void dbBackup(View v)
{
String[] dbList = getApplicationContext().databaseList();
File dbFolder = getApplicationContext().getDatabasePath(dbList[0]);
dPleaseWait = ProgressDialog.show(v.getContext(), "","Please wait...", true);
final DBAdapter db = new DBAdapter(this);
String filename = db.BackupDatabase(dbFolder);
dPleaseWait.dismiss();
if (filename.contains("does not exist")){
Toast t = Toast.makeText(DBAdminActivity.this, "The database does not exist at \r\n" + filename + ".", Toast.LENGTH_SHORT);
t.show();
} else {
Toast t = Toast.makeText(DBAdminActivity.this, "The database has been backed up to \r\n" + filename + ".", Toast.LENGTH_SHORT);
t.show();
}
}
public void dbRestore(View v)
{
String[] dbList = getApplicationContext().databaseList();
File dbFolder = getApplicationContext().getDatabasePath(dbList[0]);
dPleaseWait = ProgressDialog.show(v.getContext(), "","Please wait...", true);
final DBAdapter db = new DBAdapter(this);
String filename = db.RestoreDatabase(dbFolder);
dPleaseWait.dismiss();
if (filename.contains("does not exist")){
Toast t = Toast.makeText(DBAdminActivity.this, "The database does not exist at \r\n" + filename + ".", Toast.LENGTH_SHORT);
t.show();
} else {
Toast t = Toast.makeText(DBAdminActivity.this, "The database has been restored from \r\n" + filename + ".", Toast.LENGTH_SHORT);
t.show();
}
}
}
| RobCRobinson/MyHealthRecords | src/src/com/ravenmistmedia/MyHealthRecords/DBAdminActivity.java | Java | mit | 12,471 |
<?php
namespace Papyrillio\BeehiveBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class PapyrillioBeehiveBundle extends Bundle
{
}
| Edelweiss/beehive | src/Papyrillio/BeehiveBundle/PapyrillioBeehiveBundle.php | PHP | mit | 142 |
var path = require('path');
var expect = require('expect.js');
var _s = require('underscore.string');
var apellaJson = require('../lib/json');
var request = require('request');
describe('.find', function () {
it('should find the apella.json file', function (done) {
apellaJson.find(__dirname + '/pkg-apella-json', function (err, file) {
if (err) {
return done(err);
}
expect(file).to.equal(path.resolve(__dirname + '/pkg-apella-json/apella.json'));
done();
});
});
it('should fallback to the component.json file', function (done) {
apellaJson.find(__dirname + '/pkg-component-json', function (err, file) {
if (err) {
return done(err);
}
expect(file).to.equal(path.resolve(__dirname + '/pkg-component-json/component.json'));
done();
});
});
it('should not fallback to the component.json file if it\'s a component(1) file', function (done) {
apellaJson.find(__dirname + '/pkg-component(1)-json', function (err) {
expect(err).to.be.an(Error);
expect(err.code).to.equal('ENOENT');
expect(err.message).to.equal('None of apella.json, component.json, .apella.json were found in ' + __dirname + '/pkg-component(1)-json');
done();
});
});
it('should fallback to the .apella.json file', function (done) {
apellaJson.find(__dirname + '/pkg-dot-apella-json', function (err, file) {
if (err) {
return done(err);
}
expect(file).to.equal(path.resolve(__dirname + '/pkg-dot-apella-json/.apella.json'));
done();
});
});
it('should error if no component.json / apella.json / .apella.json is found', function (done) {
apellaJson.find(__dirname, function (err) {
expect(err).to.be.an(Error);
expect(err.code).to.equal('ENOENT');
expect(err.message).to.equal('None of apella.json, component.json, .apella.json were found in ' + __dirname);
done();
});
});
});
describe('.findSync', function () {
it('should find the apella.json file', function (done) {
var file = apellaJson.findSync(__dirname + '/pkg-apella-json');
expect(file).to.equal(path.resolve(__dirname + '/pkg-apella-json/apella.json'));
done();
});
it('should fallback to the component.json file', function (done) {
var file = apellaJson.findSync(__dirname + '/pkg-component-json');
expect(file).to.equal(path.resolve(__dirname + '/pkg-component-json/component.json'));
done();
});
it('should fallback to the .apella.json file', function (done) {
var file = apellaJson.findSync(__dirname + '/pkg-dot-apella-json');
expect(file).to.equal(path.resolve(__dirname + '/pkg-dot-apella-json/.apella.json'));
done();
});
it('should error if no component.json / apella.json / .apella.json is found', function (done) {
var err = apellaJson.findSync(__dirname);
expect(err).to.be.an(Error);
expect(err.code).to.equal('ENOENT');
expect(err.message).to.equal('None of apella.json, component.json, .apella.json were found in ' + __dirname);
done();
});
});
describe('.read', function () {
it('should give error if file does not exists', function (done) {
apellaJson.read(__dirname + '/willneverexist', function (err) {
expect(err).to.be.an(Error);
expect(err.code).to.equal('ENOENT');
done();
});
});
it('should give error if when reading an invalid json', function (done) {
apellaJson.read(__dirname + '/pkg-apella-json-malformed/apella.json', function (err) {
expect(err).to.be.an(Error);
expect(err.code).to.equal('EMALFORMED');
expect(err.file).to.equal(path.resolve(__dirname + '/pkg-apella-json-malformed/apella.json'));
done();
});
});
it('should read the file and give an object', function (done) {
apellaJson.read(__dirname + '/pkg-apella-json/apella.json', function (err, json) {
if (err) {
return done(err);
}
expect(json).to.be.an('object');
expect(json.name).to.equal('some-pkg');
expect(json.version).to.equal('0.0.0');
done();
});
});
it('should give the json file that was read', function (done) {
apellaJson.read(__dirname + '/pkg-apella-json', function (err, json, file) {
if (err) {
return done(err);
}
expect(file).to.equal(__dirname + '/pkg-apella-json/apella.json');
done();
});
});
it('should find for a json file if a directory is given', function (done) {
apellaJson.read(__dirname + '/pkg-component-json', function (err, json, file) {
if (err) {
return done(err);
}
expect(json).to.be.an('object');
expect(json.name).to.equal('some-pkg');
expect(json.version).to.equal('0.0.0');
expect(file).to.equal(path.resolve(__dirname + '/pkg-component-json/component.json'));
done();
});
});
it('should validate the returned object unless validate is false', function (done) {
apellaJson.read(__dirname + '/pkg-apella-json-invalid/apella.json', function (err) {
expect(err).to.be.an(Error);
expect(err.message).to.contain('name');
expect(err.file).to.equal(path.resolve(__dirname + '/pkg-apella-json-invalid/apella.json'));
apellaJson.read(__dirname + '/pkg-apella-json-invalid/apella.json', { validate: false }, function (err) {
done(err);
});
});
});
it('should normalize the returned object if normalize is true', function (done) {
apellaJson.read(__dirname + '/pkg-apella-json/apella.json', function (err, json) {
if (err) {
return done(err);
}
expect(json.main).to.equal('foo.js');
apellaJson.read(__dirname + '/pkg-apella-json/apella.json', { normalize: true }, function (err, json) {
if (err) {
return done(err);
}
expect(json.main).to.eql(['foo.js']);
done();
});
});
});
});
describe('.readSync', function () {
it('should give error if file does not exists', function (done) {
var err = apellaJson.readSync(__dirname + '/willneverexist');
expect(err).to.be.an(Error);
expect(err.code).to.equal('ENOENT');
done();
});
it('should give error if when reading an invalid json', function (done) {
var err = apellaJson.readSync(__dirname + '/pkg-apella-json-malformed/apella.json');
expect(err).to.be.an(Error);
expect(err.code).to.equal('EMALFORMED');
expect(err.file).to.equal(path.resolve(__dirname + '/pkg-apella-json-malformed/apella.json'));
done();
});
it('should read the file and give an object', function (done) {
var json = apellaJson.readSync(__dirname + '/pkg-apella-json/apella.json');
expect(json).to.be.an('object');
expect(json.name).to.equal('some-pkg');
expect(json.version).to.equal('0.0.0');
done();
});
it('should find for a json file if a directory is given', function (done) {
var json = apellaJson.readSync(__dirname + '/pkg-component-json');
expect(json).to.be.an('object');
expect(json.name).to.equal('some-pkg');
expect(json.version).to.equal('0.0.0');
done();
});
it('should validate the returned object unless validate is false', function (done) {
var err = apellaJson.readSync(__dirname + '/pkg-apella-json-invalid/apella.json');
expect(err).to.be.an(Error);
expect(err.message).to.contain('name');
expect(err.file).to.equal(path.resolve(__dirname + '/pkg-apella-json-invalid/apella.json'));
err = apellaJson.readSync(__dirname + '/pkg-apella-json-invalid/apella.json', { validate: false });
expect(err).to.not.be.an(Error);
done();
});
it('should normalize the returned object if normalize is true', function (done) {
var json = apellaJson.readSync(__dirname + '/pkg-apella-json/apella.json');
expect(json.main).to.equal('foo.js');
json = apellaJson.readSync(__dirname + '/pkg-apella-json/apella.json', { normalize: true });
expect(json.main).to.eql(['foo.js']);
done();
});
});
describe('.parse', function () {
it('should return the same object, unless clone is true', function () {
var json = { name: 'foo' };
expect(apellaJson.parse(json)).to.equal(json);
expect(apellaJson.parse(json, { clone: true })).to.not.equal(json);
expect(apellaJson.parse(json, { clone: true })).to.eql(json);
});
it('should validate the passed object, unless validate is false', function () {
expect(function () {
apellaJson.parse({});
}).to.throwException(/name/);
expect(function () {
apellaJson.parse({}, { validate: false });
}).to.not.throwException();
});
it('should not normalize the passed object unless normalize is true', function () {
var json = { name: 'foo', main: 'foo.js' };
apellaJson.parse(json);
expect(json.main).to.eql('foo.js');
apellaJson.parse(json, { normalize: true });
expect(json.main).to.eql(['foo.js']);
});
});
describe('.getIssues', function () {
it('should print no errors even for weird package names', function () {
var json = { name: '@gruNt/my dependency' };
expect(apellaJson.getIssues(json).errors).to.be.empty();
});
it('should validate the name length', function () {
var json = { name: 'a_123456789_123456789_123456789_123456789_123456789_z' };
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "name" is too long, the limit is 50 characters'
);
});
it('should validate the name is lowercase', function () {
var json = { name: 'gruNt' };
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "name" is recommended to be lowercase, can contain digits, dots, dashes'
);
});
it('should validate the name starts with lowercase', function () {
var json = { name: '-runt' };
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "name" cannot start with dot or dash'
);
});
it('should validate the name starts with lowercase', function () {
var json = { name: '.grunt' };
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "name" cannot start with dot or dash'
);
});
it('should validate the name ends with lowercase', function () {
var json = { name: 'grun-' };
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "name" cannot end with dot or dash'
);
});
it('should validate the name ends with lowercase', function () {
var json = { name: 'grun.' };
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "name" cannot end with dot or dash'
);
});
it('should validate the name is valid', function () {
var json = { name: 'gru.n-t' };
expect(apellaJson.getIssues(json).warnings).to.eql([]);
});
it('should validate the description length', function () {
var json = {
name: 'foo',
description: _s.repeat('æ', 141)
};
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "description" is too long, the limit is 140 characters'
);
});
it('should validate the description is valid', function () {
var json = {
name: 'foo',
description: _s.repeat('æ', 140)
};
expect(apellaJson.getIssues(json).warnings).to.eql([]);
});
it('should validate that main does not contain globs', function () {
var json = {
name: 'foo',
main: ['js/*.js']
};
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "main" field cannot contain globs (example: "*.js")'
);
});
it('should validate that main does not contain minified files', function () {
var json = {
name: 'foo',
main: ['foo.min.css']
};
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "main" field cannot contain minified files'
);
});
it('should validate that main does not contain fonts', function () {
var json = {
name: 'foo',
main: ['foo.woff']
};
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "main" field cannot contain font, image, audio, or video files'
);
});
it('should validate that main does not contain images', function () {
var json = {
name: 'foo',
main: ['foo.png']
};
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "main" field cannot contain font, image, audio, or video files'
);
});
it('should validate that main does not contain multiple files of the same filetype', function () {
var json = {
name: 'foo',
main: ['foo.js', 'bar.js']
};
expect(apellaJson.getIssues(json).warnings).to.contain(
'The "main" field has to contain only 1 file per filetype; found multiple .js files: ["foo.js","bar.js"]'
);
});
});
describe('.validate', function () {
it('should validate the name property', function () {
expect(function () {
apellaJson.validate({});
}).to.throwException(/name/);
});
it('should validate the type of main', function () {
var json = {
name: 'foo',
main: {}
};
expect(function () {
apellaJson.validate(json);
}).to.throwException();
});
it('should validate the type of items of an Array main', function () {
var json = {
name: 'foo',
main: [{}]
};
expect(function () {
apellaJson.validate(json);
}).to.throwException();
});
});
describe('.normalize', function () {
it('should normalize the main property', function () {
var json = { name: 'foo', main: 'foo.js' };
apellaJson.normalize(json);
expect(json.main).to.eql(['foo.js']);
});
});
describe('packages from apella registry', function () {
var packageList,
packageListUrl = 'http://apella.herokuapp.com/packages';
this.timeout(60000);
it('can be downloaded from online source ' + packageListUrl, function(done) {
request({
url: packageListUrl,
json: true
}, function(error, response, body) {
if(error) {
throw error;
}
expect(body).to.be.an('array');
expect(body).to.not.be.empty();
packageList = body;
done();
});
});
it('should validate each listed package', function (done) {
expect(packageList).to.be.an('array');
var invalidPackageCount = 0;
packageList.forEach(function(package) {
try {
apellaJson.validate(package);
} catch(e) {
invalidPackageCount++;
console.error('validation of "' + package.name + '" failed: ' + e.message);
}
});
if(invalidPackageCount) {
throw new Error(invalidPackageCount + '/' + packageList.length + ' package names do not validate');
}
done();
});
});
| apellajs/apella | packages/bower-json/test/test.js | JavaScript | mit | 16,224 |
"""Implementations of locale abstract base class objects."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces are specified as 'markers' and include no methods.
# pylint: disable=too-many-public-methods
# Number of methods are defined in specification
# pylint: disable=too-many-ancestors
# Inheritance defined in specification
# pylint: disable=too-many-arguments
# Argument signature defined in specification.
# pylint: disable=duplicate-code
# All apparent duplicates have been inspected. They aren't.
import abc
class CalendarInfo:
"""This interface defines methods to examine a calendar.
A calendar is organized into "years," "months," and "days." A
calendar system may offer a diffreent designation for these
divisions which may or may not vary in duration.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_calendar_type(self):
"""Gets the calendar type.
:return: the calendar type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
calendar_type = property(fget=get_calendar_type)
@abc.abstractmethod
def get_display_name(self):
"""Gets the display name for this calendar.
:return: the display name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
display_name = property(fget=get_display_name)
@abc.abstractmethod
def get_description(self):
"""Gets a description of this calendar.
:return: the description
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
description = property(fget=get_description)
@abc.abstractmethod
def get_common_era_name(self):
"""Gets the string for the common era in which years are positive.
:return: the common era label
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
common_era_name = property(fget=get_common_era_name)
@abc.abstractmethod
def get_common_era_abbrev(self):
"""Gets the abbreviation for the common era in which years are positive.
:return: the common era label
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
common_era_abbrev = property(fget=get_common_era_abbrev)
@abc.abstractmethod
def get_before_common_era_name(self):
"""Gets the string for before the common era in which years are negative.
:return: the before common era label
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
before_common_era_name = property(fget=get_before_common_era_name)
@abc.abstractmethod
def get_before_common_era_abbrev(self):
"""Gets the abbreviation for before the common era in which years are negative.
:return: the before common era label
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
before_common_era_abbrev = property(fget=get_before_common_era_abbrev)
@abc.abstractmethod
def get_first_year_in_common_era(self):
"""Gets the year number for the first year.
:return: the first year
:rtype: ``integer``
*compliance: mandatory -- This method must be implemented.*
"""
return # integer
first_year_in_common_era = property(fget=get_first_year_in_common_era)
@abc.abstractmethod
def get_last_year_before_common_era(self):
"""Gets the year number for the year before the common era.
:return: the last bce year
:rtype: ``integer``
*compliance: mandatory -- This method must be implemented.*
"""
return # integer
last_year_before_common_era = property(fget=get_last_year_before_common_era)
@abc.abstractmethod
def get_year_name(self):
"""Gets the display name for a calendar "year.
"
:return: the name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
year_name = property(fget=get_year_name)
@abc.abstractmethod
def get_month_name(self):
"""Gets the display name for a calendar "month.
"
:return: the name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
month_name = property(fget=get_month_name)
@abc.abstractmethod
def has_variable_months(self):
"""Tests if this calendar has a variable number of months in a year.
:return: ``true`` if the number of months varies, ``false`` if the number of months is constant
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_num_months(self):
"""Gets the number of months of the year.
For a variable month calendar, the number of all defined months
are returned. If there are no "months" in this calendar system
then this value may be zero.
:return: the number of months
:rtype: ``cardinal``
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
num_months = property(fget=get_num_months)
@abc.abstractmethod
def get_num_months_for_year(self, year):
"""Gets the number of months in the given year.
:param year: a year
:type year: ``integer``
:return: the number of months
:rtype: ``cardinal``
:raise: ``IllegalState`` -- ``year`` is greater than ``get_last_year_before_common_era()`` and less then ``get_first_year_in_common_era()``
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
@abc.abstractmethod
def get_months(self):
"""Gets the months of the year in order of the calendar.
For a variable month calendar, all defined months are returned.
If there are no "months" in this calendar system then the list
may be empty.
:return: the months
:rtype: ``osid.locale.CalendarUnit``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.CalendarUnit
months = property(fget=get_months)
@abc.abstractmethod
def get_months_for_year(self, year):
"""Gets the months of the year in order of the calendar.
:param year: a year
:type year: ``integer``
:return: the months
:rtype: ``osid.locale.CalendarUnit``
:raise: ``IllegalState`` -- ``year`` is greater than ``get_last_year_before_common_era()`` and less then ``get_first_year_in_common_era()``
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.CalendarUnit
@abc.abstractmethod
def get_day_name(self):
"""Gets the display name for a calendar "day.
"
:return: the name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
day_name = property(fget=get_day_name)
@abc.abstractmethod
def has_variable_days(self):
"""Tests if this calendar has a variable number of days in a month.
:return: ``true`` if the number of days per month varies, ``false`` if the number of days is constant
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_num_days(self):
"""Gets the number of days in a year.
For a variable day calendar, the number of all defined days are
returned. If there are no "days" in this calendar system then
this value may be zero. If there are no "months" defined then
the number of days is the number of days in a year.
:return: the number of days
:rtype: ``cardinal``
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
num_days = property(fget=get_num_days)
@abc.abstractmethod
def get_num_days_for_month(self, year, month):
"""Gets the number of days in the given month.
:param year: a year
:type year: ``integer``
:param month: a ``DateTime`` month code
:type month: ``cardinal``
:return: the number of days
:rtype: ``cardinal``
:raise: ``IllegalState`` -- ``year`` is greater than ``get_last_year_before_common_era()`` and less then ``get_first_year_in_common_era()`` , or ``month`` is greater than ``get_months_for_year(year)``
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
@abc.abstractmethod
def get_days(self):
"""Gets the days of the month in order of the calendar.
For a variable day calendar, all defined days are returned. If
there are no "days" in this time system then this value may be
zero. If there are no "months" defined then the number of days
applies to the entire year.
:return: the days
:rtype: ``osid.locale.CalendarUnit``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.CalendarUnit
days = property(fget=get_days)
@abc.abstractmethod
def get_days_for_month(self, year, month):
"""Gets the days of the given month in order of the calendar.
:param year: a year
:type year: ``integer``
:param month: a ``DateTime`` month code
:type month: ``cardinal``
:return: the days
:rtype: ``osid.locale.CalendarUnit``
:raise: ``IllegalState`` -- ``year`` is greater than ``get_last_year_before_common_era()`` and less then ``get_first_year_in_common_era()`` , or ``month`` is greater than or equal to than ``get_months_for_year(year)``
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.CalendarUnit
@abc.abstractmethod
def get_first_day_of_year(self):
"""Gets the first day of the calendar year.
:return: the first day of the year
:rtype: ``osid.calendaring.DateTime``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.calendaring.DateTime
first_day_of_year = property(fget=get_first_day_of_year)
@abc.abstractmethod
def get_end_of_days_name(self):
"""Gets the display name for the end of the calendar.
:return: the name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
end_of_days_name = property(fget=get_end_of_days_name)
@abc.abstractmethod
def get_origin(self):
"""Gets the start of the "common era" for this calendar.
:return: start of the calendar
:rtype: ``osid.calendaring.DateTime``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.calendaring.DateTime
origin = property(fget=get_origin)
@abc.abstractmethod
def get_end_of_days(self):
"""Gets the end of the world as specified by this calendar.
:return: end of days
:rtype: ``osid.calendaring.DateTime``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.calendaring.DateTime
end_of_days = property(fget=get_end_of_days)
@abc.abstractmethod
def get_weekdays(self):
"""Gets the days of the week in order of the calendar.
:return: the week days
:rtype: ``osid.locale.CalendarUnit``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.CalendarUnit
weekdays = property(fget=get_weekdays)
class TimeInfo:
"""This interface defines methods to examine a time.
Time is organized intro "hours," "minutes," and "seconds." A time
system may offer a different designation for these divisions which
may or may not vary in duration.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_time_type(self):
"""Gets the time type.
:return: the time type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
time_type = property(fget=get_time_type)
@abc.abstractmethod
def get_display_name(self):
"""Gets the display name for this time system.
:return: the display name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
display_name = property(fget=get_display_name)
@abc.abstractmethod
def get_display_label(self):
"""Gets a short label for this time system.
:return: the label
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
display_label = property(fget=get_display_label)
@abc.abstractmethod
def get_description(self):
"""Gets a description of this time system.
:return: the description
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
description = property(fget=get_description)
@abc.abstractmethod
def get_hour_name(self):
"""Gets the display name for "hours.
"
:return: the name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
hour_name = property(fget=get_hour_name)
@abc.abstractmethod
def get_hour_abbrev(self):
"""Gets the abbreviation for "hours.
"
:return: the abbreviation
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
hour_abbrev = property(fget=get_hour_abbrev)
@abc.abstractmethod
def get_hour_initial(self):
"""Gets the initial for "hours.
"
:return: the initial
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
hour_initial = property(fget=get_hour_initial)
@abc.abstractmethod
def has_variable_hours(self):
"""Tests if this time system has a variable number of hours in a day.
:return: ``true`` if the number of hours per day varies, ``false`` if the number of hours per day is constant
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_num_hours(self):
"""Gets the number of hours in a day.
For a variable hour time system, the number of hours defined is
returned. If there are no "hours" in this time system then this
value may be zero.
:return: the number of hours
:rtype: ``cardinal``
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
num_hours = property(fget=get_num_hours)
@abc.abstractmethod
def get_num_hours_for_day(self, year, month, day):
"""Gets the number of hours for a given day.
:param year: a year
:type year: ``integer``
:param month: a ``DateTime`` month code
:type month: ``cardinal``
:param day: a ``DateTime`` day code
:type day: ``cardinal``
:return: the number of hours
:rtype: ``cardinal``
:raise: ``IllegalState`` -- ``year`` is greater than ``CalendarInfo.getLastYearBeforeCommonEra()`` and less then ``CalendarInfo.getFirstYearInCommonEra()`` , or ``month`` is greater than or equal to
``CalendarInfo.getNumMonthsForYear(year)`` , or ``day`` is greater than or equal to ``CalendarInfo.getDaysInMonth(year, month)``
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
@abc.abstractmethod
def get_minute_name(self):
"""Gets the display name for "minutes.
"
:return: the name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
minute_name = property(fget=get_minute_name)
@abc.abstractmethod
def get_minute_abbrev(self):
"""Gets the abbreviation for "minutes.
"
:return: the abbreviation
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
minute_abbrev = property(fget=get_minute_abbrev)
@abc.abstractmethod
def get_minute_initial(self):
"""Gets the initial for "minutes.
"
:return: the initial
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
minute_initial = property(fget=get_minute_initial)
@abc.abstractmethod
def has_variable_minutes(self):
"""Tests if this time system has a variable number of minutes in an hour.
:return: ``true`` if the number of minutes per hour varies, ``false`` if the number of minutes per hour is constant
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_num_minutes(self):
"""Gets the number of minutes in an hour.
For a variable minute time system, the number of minutes defined
is returned. If there are no "minutes" in this time system then
this value may be zero. If there are no "hours" defined then the
number of minutes is the number of minutes in a day.
:return: the number of minutes
:rtype: ``cardinal``
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
num_minutes = property(fget=get_num_minutes)
@abc.abstractmethod
def get_num_minutes_for_hour(self, year, month, day, hour):
"""Gets the minutes for a given hour.
:param year: a year
:type year: ``integer``
:param month: a ``DateTime`` month code
:type month: ``cardinal``
:param day: a ``DateTime`` day code
:type day: ``cardinal``
:param hour: an hour
:type hour: ``cardinal``
:return: the number of minutes
:rtype: ``cardinal``
:raise: ``IllegalState`` -- ``year`` is greater than ``CalendarInfo.getLastYearBeforeCommonEra()`` and less then ``CalendarInfo.getFirstYearInCommonEra(),`` or ``month`` is greater than or equal to
``CalendarInfo.getNumMonthsForYear(year)`` , or ``day`` is greater than or equal to ``CalendarInfo.getDaysInMonth(year, month)`` , or ``hour`` is greater than or equal to ``get_num_hours_in_day(year,
month, day)``
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
@abc.abstractmethod
def get_second_name(self):
"""Gets the display name for "seconds.
"
:return: the name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
second_name = property(fget=get_second_name)
@abc.abstractmethod
def get_second_abbrev(self):
"""Gets the abbreviation for "seconds.
"
:return: the abbreviation
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
second_abbrev = property(fget=get_second_abbrev)
@abc.abstractmethod
def get_second_initial(self):
"""Gets the initial for "seconds.
"
:return: the initial
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
second_initial = property(fget=get_second_initial)
@abc.abstractmethod
def has_variable_seconds(self):
"""Tests if this time system has a variable number of seconds in a minute.
:return: ``true`` if the number of seconds per minute varies, ``false`` if the number of seconds per minute is constant
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def get_num_seconds(self):
"""Gets the number of seconds in a minute.
For a variable second time system, the number of seconds defined
is returned. If there are no "seconds" in this time system then
this value may be zero. If there are no "minutes" defined then
the number of seconds is the number of seconds in an hour.
:return: the number of seconds
:rtype: ``cardinal``
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
num_seconds = property(fget=get_num_seconds)
@abc.abstractmethod
def get_num_seconds_for_minute(self, year, month, day, hour, minute):
"""Gets the seconds for a given minute.
:param year: a year
:type year: ``integer``
:param month: a ``DateTime`` month code
:type month: ``cardinal``
:param day: a ``DateTime`` day code
:type day: ``cardinal``
:param hour: an hour
:type hour: ``cardinal``
:param minute: a minute
:type minute: ``cardinal``
:return: the number of seconds
:rtype: ``cardinal``
:raise: ``IllegalState`` -- ``year`` is greater than ``get_last_year_before_common_era()`` and less then ``get_first_year_in_common_era()`` , or ``month`` is greater than or equal to ``CalendarInfo.getNumMonthsForYear(year)`` ,
or ``day`` is greater than or equal to ``CalendarInfo.getDaysInMonth(year, month)`` , or ``hour`` is greater than or equal to ``get_num_hours_in_day(year, month, day)`` , or ``minute`` is greater than
or equal to ``get_num_minutes_inhour(year, month, day, hour)``
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
class CalendarUnit:
"""A description of a calendar unit."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_name(self):
"""Gets the full name of this unit.
:return: the name
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
name = property(fget=get_name)
@abc.abstractmethod
def get_abbrev3(self):
"""Gets a 3-letter abbreviation for this unit.
:return: the abbreviation
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
abbrev3 = property(fget=get_abbrev3)
@abc.abstractmethod
def get_abbrev2(self):
"""Gets a 2-letter abbreviation for this unit.
:return: the abbreviation
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
abbrev2 = property(fget=get_abbrev2)
@abc.abstractmethod
def get_initial(self):
"""Gets a single letter abbreviation for this unit.
:return: the initial
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
initial = property(fget=get_initial)
@abc.abstractmethod
def get_date_time_code(self):
"""Gets the number of this unit used in ``DateTime``.
:return: the code
:rtype: ``cardinal``
*compliance: mandatory -- This method must be implemented.*
"""
return # cardinal
date_time_code = property(fget=get_date_time_code)
@abc.abstractmethod
def get_description(self):
"""Gets a description of this unit.
:return: the description
:rtype: ``osid.locale.DisplayText``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.DisplayText
description = property(fget=get_description)
class Locale:
"""A locale is a collection of types.
``Locale`` defines a set of types that together define the
formatting, language, calendaring, and currency for a locale or
culture.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_language_type(self):
"""Gets the language ``Type``.
:return: the language type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
language_type = property(fget=get_language_type)
@abc.abstractmethod
def get_script_type(self):
"""Gets the script ``Type``.
:return: the script type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
script_type = property(fget=get_script_type)
@abc.abstractmethod
def get_calendar_type(self):
"""Gets the calendar ``Type``.
:return: the calendar type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
calendar_type = property(fget=get_calendar_type)
@abc.abstractmethod
def get_time_type(self):
"""Gets the time ``Type``.
:return: the time type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
time_type = property(fget=get_time_type)
@abc.abstractmethod
def get_currency_type(self):
"""Gets the currency ``Type``.
:return: the currency type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
currency_type = property(fget=get_currency_type)
@abc.abstractmethod
def get_unit_system_type(self):
"""Gets the unit system ``Type``.
:return: the unit system type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
unit_system_type = property(fget=get_unit_system_type)
@abc.abstractmethod
def get_numeric_format_type(self):
"""Gets the numeric format ``Type``.
:return: the numeric format type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
numeric_format_type = property(fget=get_numeric_format_type)
@abc.abstractmethod
def get_calendar_format_type(self):
"""Gets the calendar format ``Type``.
:return: the calendar format type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
calendar_format_type = property(fget=get_calendar_format_type)
@abc.abstractmethod
def get_time_format_type(self):
"""Gets the time format ``Type``.
:return: the time format type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
time_format_type = property(fget=get_time_format_type)
@abc.abstractmethod
def get_currency_format_type(self):
"""Gets the currency format ``Type``.
:return: the currency format type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
currency_format_type = property(fget=get_currency_format_type)
@abc.abstractmethod
def get_coordinate_format_type(self):
"""Gets the coordinate format ``Type``.
:return: the coordinate format type
:rtype: ``osid.type.Type``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.Type
coordinate_format_type = property(fget=get_coordinate_format_type)
class LocaleList:
"""Like all ``OsidLists,`` ``LocaleList`` provides a means for accessing ``Locale`` elements sequentially either one at a time or many at a time.
Examples: while (ll.hasNext()) { Locale locale = ll.getNextLocale();
}
or
while (ll.hasNext()) {
Locale[] locales = ll.getNextLocales(ll.available());
}
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_next_locale(self):
"""Gets the next ``Locale`` in this list.
:return: the next ``Locale`` in this list. The ``has_next()`` method should be used to test that a next ``Locale`` is available before calling this method.
:rtype: ``osid.locale.Locale``
:raise: ``IllegalState`` -- no more elements available in this list
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.Locale
next_locale = property(fget=get_next_locale)
@abc.abstractmethod
def get_next_locales(self, n):
"""Gets the next set of ``Locale`` elements in this list.
The specified amount must be less than or equal to the return
from ``available()``.
:param n: the number of ``Locale`` elements requested which must be less than or equal to ``available()``
:type n: ``cardinal``
:return: an array of ``Locale`` elements.The length of the array is less than or equal to the number specified.
:rtype: ``osid.locale.Locale``
:raise: ``IllegalState`` -- no more elements available in this list
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.locale.Locale
| mitsei/dlkit | dlkit/abstract_osid/locale/objects.py | Python | mit | 32,414 |
require 'spec_helper'
EM.describe EmModbus::ModbusProtocol do
it 'should fail fast when the server is not running'
it 'should accept the slave address option'
end
| tallakt/em-modbus | spec/device_spec.rb | Ruby | mit | 166 |
<body>
<!-- Main Navigation
================================================== -->
<nav id="tf-menu" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!-- 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>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="img/logo.png" alt="..."></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 href="#tf-home" class="scroll">Home</a></li>
<li><a href="#tf-services" class="scroll">Services</a></li>
<li><a href="#tf-about" class="scroll">About</a></li>
<li><a href="#tf-works" class="scroll">Works</a></li>
<li><a href="#tf-process" class="scroll">Process</a></li>
<li><a href="#tf-pricing" class="scroll">Pricing</a></li>
<li><a href="#tf-blog" class="scroll">Blog</a></li>
<li><a href="#tf-contact" class="scroll">Contact</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<!-- Home Section
================================================== -->
<div id="tf-home">
<div class="overlay"> <!-- Overlay Color -->
<div class="container"> <!-- container -->
<div class="content-heading text-center"> <!-- Input Your Home Content Here -->
<h1>Websites / Branding / Interactive</h1>
<p class="lead">We create beautiful, innovative and effective handcrafted brands & website.</p>
<a href="#tf-works" class="scroll goto-btn text-uppercase">View Our Works</a> <!-- Link to your portfolio section -->
</div><!-- End Input Your Home Content Here -->
</div> <!-- end container -->
</div><!-- End Overlay Color -->
</div>
<!-- Intro Section
================================================== -->
<div id="tf-intro">
<div class="container"> <!-- container -->
<div class="row"> <!-- row -->
<div class="col-md-8 col-md-offset-2">
<img src="img/logo-w.png" class="intro-logo img-responsive" alt="free-template"> <!-- Your company logo in white -->
<p>Ethanol Portfolio Template is a clean and simple website designed layout for multi-purpose options, this is perfect for any web works. This Template built with bootstrap 3.3.2 and it is totally mobile resposnive. Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus..</p>
</div>
</div><!-- end row -->
</div><!-- end container -->
</div>
<!-- Service Section
================================================== -->
<div id="tf-services">
<div class="container"> <!-- container -->
<div class="section-header">
<h2>What We Do With <span class="highlight"><strong>Love</strong></span></h2>
<h5><em>We design and build functional and beautiful websites</em></h5>
<div class="fancy"><span><img src="img/favicon.ico" alt="..."></span></div>
</div>
<div class="row"> <!-- row -->
<div class="col-md-6 text-right"> <!-- Left Content Col 6 -->
<div class="media service"> <!-- Service #1 -->
<div class="media-body">
<h4 class="media-heading">Brand Identity</h4>
<p>Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
</div>
<div class="media-right media-middle">
<i class="fa fa-venus-mars"></i>
</div>
</div><!-- End Service #1 -->
<div class="media service"> <!-- Service #2 -->
<div class="media-body">
<h4 class="media-heading">Graphics Design</h4>
<p>Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
</div>
<div class="media-right media-middle">
<i class="fa fa-magic"></i>
</div>
</div><!-- End Service #2 -->
<div class="media service"> <!-- Service #3 -->
<div class="media-body">
<h4 class="media-heading">Videography</h4>
<p>Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
</div>
<div class="media-right media-middle">
<i class="fa fa-camera-retro"></i>
</div>
</div> <!-- End Service #3 -->
</div> <!-- End Left Content Col 6 -->
<div class="col-md-6"> <!-- Right Content Col 6 -->
<div class="media service"> <!-- Service #4 -->
<div class="media-left media-middle">
<i class="fa fa-bicycle"></i>
</div>
<div class="media-body">
<h4 class="media-heading">UI/UX Design</h4>
<p>Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
</div>
</div><!-- end Service #4 -->
<div class="media service"> <!-- Service #5 -->
<div class="media-left media-middle">
<i class="fa fa-android"></i>
</div>
<div class="media-body">
<h4 class="media-heading">Application</h4>
<p>Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
</div>
</div> <!-- end Service #5 -->
<div class="media service"> <!-- Service #6 -->
<div class="media-left media-middle">
<i class="fa fa-line-chart"></i>
</div>
<div class="media-body">
<h4 class="media-heading">SEO/Online Marketing</h4>
<p>Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
</div>
</div> <!-- end Service #6 -->
</div><!-- end Right Content Col 6 -->
</div><!-- end row -->
</div><!-- end container -->
</div>
<!-- About Us Section
================================================== -->
<div id="tf-about">
<div class="container"> <!-- container -->
<div class="section-header">
<h2>What To Know Us <span class="highlight"><strong>Better</strong></span></h2>
<h5><em>We design and build functional and beautiful websites</em></h5>
<div class="fancy"><span><img src="img/favicon.ico" alt="..."></span></div>
</div>
</div><!-- end container -->
<div class="gray-bg"> <!-- fullwidth gray background -->
<div class="container"><!-- container -->
<div class="row"> <!-- row -->
<div class="col-md-6"> <!-- left content col 6 -->
<div class="about-left-content text-center">
<div class="img-wrap"> <!-- profile image wrap -->
<div class="profile-img"> <!-- company profile details -->
<img src="http://placehold.it/800x650" class="img-responsive" alt="Image"> <!-- change link to your image for your company profile -->
<ul class="list-inline social">
<li><a href="#" class="fa fa-facebook"></a></li> <!-- facebook link here -->
<li><a href="#" class="fa fa-twitter"></a></li> <!-- twitter link here -->
<li><a href="#" class="fa fa-google-plus"></a></li> <!-- google plus link here -->
</ul>
</div>
</div><!-- end profile image wrap -->
<h2><span class="small">Developing</span> Amazing Things <br><span class="small">with Passion since 2012.</span></h2>
</div>
</div><!-- end left content col 6 -->
<div class="col-md-6"><!-- right content col 6 -->
<div class="about-right-content"> <!-- right content wrapper -->
<h4><strong>Professional Profile</strong></h4>
<p>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec, tempor cursus vitae sit aliquet neque purus. Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent.</p>
<div class="skills"> <!-- skills progress bar -->
<div class="skillset"> <!-- skill #1 -->
<p>UI/UX Design</p>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100" style="width: 90%;">
<span class="sr-only">90% Complete</span>
</div>
</div>
</div><!-- end skill #1 -->
<div class="skillset"> <!-- skill #2 -->
<p>HTML5, CSS3, SASS</p>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100" style="width: 85%;">
<span class="sr-only">85% Complete</span>
</div>
</div>
</div><!-- end skill #2 -->
<div class="skillset"> <!-- skill #3 -->
<p>WordPress</p>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="99" aria-valuemin="0" aria-valuemax="100" style="width: 99%;">
<span class="sr-only">99% Complete</span>
</div>
</div>
</div> <!-- end skill #3 -->
<div class="skillset"> <!-- skill #4 -->
<p>Graphic Design</p>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width: 70%;">
<span class="sr-only">70% Complete</span>
</div>
</div>
</div> <!-- end skill #4 -->
<div class="skillset"> <!-- skill #5 -->
<p>Marketing</p>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width: 50%;">
<span class="sr-only">50% Complete</span>
</div>
</div>
</div><!-- end skill #4 -->
</div> <!-- end skills progress bar -->
</div><!-- end right content wrapper -->
</div><!-- end right content col 6 -->
</div> <!-- end row -->
</div><!-- end container -->
<div id="tf-counter" class="text-center">
<div class="container">
<div class="row"> <!-- Row -->
<div class="counter">
<div class="col-xs-6 col-sm-4 col-md-2 col-md-2 col-md-offset-1 facts"><!-- counter #1 -->
<div class="count-box">
<i class="fa fa-thumbs-up"></i>
<h4 class="count">720</h4>
<p class="small">Happy Customers</p>
</div>
</div><!-- end counter #1 -->
<div class="col-xs-6 col-sm-4 col-md-2 facts"><!-- counter #2 -->
<div class="count-box">
<i class="fa fa-user"></i>
<h4 class="count">480</h4>
<p class="small">People Donated</p>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-2 facts"> <!-- counter #3 -->
<div class="count-box">
<i class="fa fa-desktop"></i>
<h4 class="count">1253</h4>
<p class="small">People Participated</p>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-2 facts"> <!-- counter #4 -->
<div class="count-box">
<i class="fa fa-dollar"></i>
<h4 class="count">4580</h4>
<p class="small">Donation Collected</p>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-2 facts"> <!-- counter #5 -->
<div class="count-box last">
<i class="fa fa-line-chart"></i>
<h4 class="count">12853</h4>
<p class="small">Total Hits</p>
</div>
</div>
</div>
</div> <!-- End Row -->
</div>
</div>
</div> <!-- end fullwidth gray background -->
</div>
<!-- Team Section
================================================== -->
<div id="tf-team">
<div class="container"> <!-- container -->
<div class="section-header">
<h2>Awesome People Behind <span class="highlight"><strong>ethanol</strong></span></h2>
<h5><em>We design and build functional and beautiful websites</em></h5>
<div class="fancy"><span><img src="img/favicon.ico" alt="..."></span></div>
</div>
<div id="team" class="owl-carousel owl-theme text-center"> <!-- team carousel wrapper -->
<div class="item"><!-- Team #1 -->
<div class="hover-bg"> <!-- Team Wrapper -->
<div class="hover-text off"> <!-- Hover Description -->
<p>Aliquet rutrum dui a varius. Mauris ornare tortor in eleifend blanditullam ut ligula et neque. Quis placerat dui. Duis lacinia nisi sit ansequat lorem nunc, nec bibendum erat volutpat ultricies.</p>
</div><!-- End Hover Description -->
<img src="img/team/01.jpg" alt="..." class="img-responsive"> <!-- Team Image -->
<div class="team-detail text-center">
<h3>Maria Shara</h3>
<p class="text-uppercase">Founder / CEO</p>
<ul class="list-inline social">
<li><a href="#" class="fa fa-facebook"></a></li> <!-- facebook link here -->
<li><a href="#" class="fa fa-twitter"></a></li> <!-- twitter link here -->
<li><a href="#" class="fa fa-google-plus"></a></li> <!-- google plus link here -->
</ul>
</div>
</div><!-- End Team Wrapper -->
</div><!-- End Team #1 -->
<div class="item"> <!-- Team #2 -->
<div class="hover-bg"> <!-- Team Wrapper -->
<div class="hover-text off"> <!-- Hover Description -->
<p>Praesent eget bibendum purus, quis placerat dui. Duis lacinia nisi sit ansequat lorem nunc, nec bibendum erat volutpat ultricies. Aliquet rutrum dui a varius. Mauris ornare tortor.</p>
</div> <!-- End Hover Description -->
<img src="img/team/02.jpg" alt="..." class="img-responsive"><!-- Team Image -->
<div class="team-detail text-center">
<h3>Jenn Pereira</h3>
<p class="text-uppercase">Senior Creative Director</p>
<ul class="list-inline social">
<li><a href="#" class="fa fa-facebook"></a></li> <!-- facebook link here -->
<li><a href="#" class="fa fa-twitter"></a></li> <!-- twitter link here -->
<li><a href="#" class="fa fa-google-plus"></a></li> <!-- google plus link here -->
</ul>
</div>
</div> <!-- End Team Wrapper -->
</div><!-- End Team #2 -->
<div class="item"> <!-- Team #3 -->
<div class="hover-bg"> <!-- Team Wrapper -->
<div class="hover-text off"> <!-- Hover Description -->
<p>Vivamus aliquet rutrum dui a varius. Mauris ornare tortor in eleifend blanditullam ut ligula et neque. Nec bibendum erat volutpat ultricies. Aliquet rutrum dui a varius. Mauris ornare tortor. </p>
</div> <!-- End Hover Description -->
<img src="img/team/01.jpg" alt="..." class="img-responsive"><!-- Team Image -->
<div class="team-detail text-center">
<h3>Serena William</h3>
<p class="text-uppercase">Senior Designer</p>
<ul class="list-inline social">
<li><a href="#" class="fa fa-facebook"></a></li> <!-- facebook link here -->
<li><a href="#" class="fa fa-twitter"></a></li> <!-- twitter link here -->
<li><a href="#" class="fa fa-google-plus"></a></li> <!-- google plus link here -->
</ul>
</div>
</div><!-- End Team Wrapper -->
</div><!-- End Team #3 -->
<div class="item"><!-- Team #4 -->
<div class="hover-bg"> <!-- Team Wrapper -->
<div class="hover-text off"> <!-- Hover Description -->
<p>Aliquet rutrum dui a varius. Mauris ornare tortor in eleifend blanditullam ut ligula et neque. Quis placerat dui. Duis lacinia nisi sit ansequat lorem nunc, nec bibendum erat volutpat ultricies.</p>
</div> <!-- End Hover Description -->
<img src="img/team/01.jpg" alt="..." class="img-responsive"> <!-- Team Image -->
<div class="team-detail text-center">
<h3>Maria Shara</h3>
<p class="text-uppercase">Founder / CEO</p>
<ul class="list-inline social">
<li><a href="#" class="fa fa-facebook"></a></li> <!-- facebook link here -->
<li><a href="#" class="fa fa-twitter"></a></li> <!-- twitter link here -->
<li><a href="#" class="fa fa-google-plus"></a></li> <!-- google plus link here -->
</ul>
</div>
</div> <!-- End Team Wrapper -->
</div><!-- End Team #4 -->
<div class="item"><!-- Team #5 -->
<div class="hover-bg"> <!-- Team Wrapper -->
<div class="hover-text off"> <!-- Hover Description -->
<p>Praesent eget bibendum purus, quis placerat dui. Duis lacinia nisi sit ansequat lorem nunc, nec bibendum erat volutpat ultricies. Aliquet rutrum dui a varius. Mauris ornare tortor.</p>
</div> <!-- End Hover Description -->
<img src="img/team/02.jpg" alt="..." class="img-responsive"> <!-- Team Image -->
<div class="team-detail text-center">
<h3>Jenn Pereira</h3>
<p class="text-uppercase">Senior Creative Director</p>
<ul class="list-inline social">
<li><a href="#" class="fa fa-facebook"></a></li> <!-- facebook link here -->
<li><a href="#" class="fa fa-twitter"></a></li> <!-- twitter link here -->
<li><a href="#" class="fa fa-google-plus"></a></li> <!-- google plus link here -->
</ul>
</div>
</div> <!-- End Team Wrapper -->
</div><!-- End Team #5 -->
</div> <!-- end team carousel wrapper -->
</div> <!-- container -->
</div>
<!-- Why Us/Features Section
================================================== -->
<div id="tf-features">
<div class="container">
<div class="section-header">
<h2>Great Products and <span class="highlight"><strong>Features</strong></span></h2>
<h5><em>We design and build functional and beautiful websites</em></h5>
<div class="fancy"><span><img src="img/favicon.ico" alt="..."></span></div>
</div>
</div>
<div id="feature" class="gray-bg"> <!-- fullwidth gray background -->
<div class="container"> <!-- container -->
<div class="row" role="tabpanel"> <!-- row -->
<div class="col-md-4 col-md-offset-1"> <!-- tab menu col 4 -->
<ul class="features nav nav-pills nav-stacked" role="tablist">
<li role="presentation" class="active"> <!-- feature tab menu #1 -->
<a href="#f1" aria-controls="f1" role="tab" data-toggle="tab">
<span class="fa fa-desktop"></span>
Internet Communication<br><small>sub title here</small>
</a>
</li>
<li role="presentation"> <!-- feature tab menu #2 -->
<a href="#f2" aria-controls="f2" role="tab" data-toggle="tab">
<span class="fa fa-pencil"></span>
Branding and Development<br><small>sub title here</small>
</a>
</li>
<li role="presentation"> <!-- feature tab menu #3 -->
<a href="#f3" aria-controls="f3" role="tab" data-toggle="tab">
<span class="fa fa-space-shuttle"></span>
Motion Graphics<br><small>sub title here</small>
</a>
</li>
<li role="presentation"> <!-- feature tab menu #4 -->
<a href="#f4" aria-controls="f4" role="tab" data-toggle="tab">
<span class="fa fa-automobile"></span>
Mobile Application<br><small>sub title here</small>
</a>
</li>
<li role="presentation"> <!-- feature tab menu #5 -->
<a href="#f5" aria-controls="f5" role="tab" data-toggle="tab">
<span class="fa fa-institution"></span>
Relaible Company Analysis<br><small>sub title here</small>
</a>
</li>
</ul>
</div><!-- end tab menu col 4 -->
<div class="col-md-6"> <!-- right content col 6 -->
<!-- Tab panes -->
<div class="tab-content features-content"> <!-- tab content wrapper -->
<div role="tabpanel" class="tab-pane fade in active" id="f1"> <!-- feature #1 content open -->
<h4>Internet Communication</h4>
<p>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec, tempor cursus vitae sit aliquet neque purus. Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent.</p>
<img src="img/tab01.png" class="img-responsive" alt="...">
</div>
<div role="tabpanel" class="tab-pane fade" id="f2"> <!-- feature #2 content -->
<h4>Branding and Development</h4>
<p>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec, tempor cursus vitae sit aliquet neque purus. Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent.</p>
<img src="img/tab02.png" class="img-responsive" alt="...">
</div>
<div role="tabpanel" class="tab-pane fade" id="f3"> <!-- feature #3 content -->
<h4>Motion Graphics</h4>
<p>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec, tempor cursus vitae sit aliquet neque purus. Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent.</p>
<img src="img/tab03.png" class="img-responsive" alt="...">
</div>
<div role="tabpanel" class="tab-pane fade" id="f4"> <!-- feature #4 content -->
<h4>Mobile Application</h4>
<p>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec, tempor cursus vitae sit aliquet neque purus. Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent.</p>
<img src="img/tab04.png" class="img-responsive" alt="...">
</div>
<div role="tabpanel" class="tab-pane fade" id="f5"> <!-- feature #5 content -->
<h4>Relaible Company Analysis</h4>
<p>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec, tempor cursus vitae sit aliquet neque purus. Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent.</p>
<img src="img/tab05.png" class="img-responsive" alt="...">
</div>
</div> <!-- end tab content wrapper -->
</div><!-- end right content col 6 -->
</div> <!-- end row -->
</div> <!-- end container -->
</div><!-- end fullwidth gray background -->
</div>
<!-- Works Section
================================================== -->
<div id="tf-works">
<div class="container">
<div class="section-header">
<h2>Our Work is <span class="highlight"><strong>Incredible</strong></span></h2>
<h5><em>We design and build functional and beautiful websites</em></h5>
<div class="fancy"><span><img src="img/favicon.ico" alt="..."></span></div>
</div>
<div class="text-center">
<ul class="list-inline cat"> <!-- Portfolio Filter Categories -->
<li><a href="#" data-filter="*" class="active">All</a></li>
<li><a href="#" data-filter=".web">Web</a></li>
<li><a href="#" data-filter=".brand">Branding</a></li>
<li><a href="#" data-filter=".app">Apps</a></li>
<li><a href="#" data-filter=".others">Others</a></li>
</ul><!-- End Portfolio Filter Categories -->
</div>
</div><!-- End Container -->
<div class="container-fluid"> <!-- fluid container -->
<div id="itemsWork" class="row text-center"> <!-- Portfolio Wrapper Row -->
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 nopadding brand others"> <!-- Works #1 col 3 -->
<div class="box">
<div class="hover-bg">
<div class="hover-text off">
<a title="Logo Identity Design" href="img/portfolio/01@2x.jpg" data-lightbox-gallery="gallery1" data-lightbox-hidpi="img/portfolio/01@2x.jpg">
<i class="fa fa-expand"></i>
</a>
<a href="#"><i class="fa fa-chain"></i></a> <!-- change # with your url to link it to another page -->
</div>
<img src="img/portfolio/01.jpg" class="img-responsive" alt="Image"> <!-- Portfolio Image -->
</div>
</div>
</div><!-- end Works #1 col 3 -->
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 nopadding apps"> <!-- Works #2 col 3 -->
<div class="box">
<div class="hover-bg">
<div class="hover-text off">
<a title="Mobile Application" href="img/portfolio/02@2x.jpg" data-lightbox-gallery="gallery1" data-lightbox-hidpi="img/portfolio/02@2x.jpg">
<i class="fa fa-expand"></i>
</a>
<a href="#"><i class="fa fa-chain"></i></a><!-- change # with your url to link it to another page -->
</div>
<img src="img/portfolio/02.jpg" class="img-responsive" alt="Image"> <!-- Portfolio Image -->
</div>
</div>
</div><!-- end Works #2 col 3 -->
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 nopadding others brand"><!-- Works #3 col 3 -->
<div class="box">
<div class="hover-bg">
<div class="hover-text off">
<a title="Freedom Project #1" href="img/portfolio/03@2x.jpg" data-lightbox-gallery="gallery1" data-lightbox-hidpi="img/portfolio/03@2x.jpg">
<i class="fa fa-expand"></i>
</a>
<a href="#"><i class="fa fa-chain"></i></a><!-- change # with your url to link it to another page -->
</div>
<img src="img/portfolio/03.jpg" class="img-responsive" alt="Image"> <!-- Portfolio Image -->
</div>
</div>
</div><!-- end Works #3 col 3 -->
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 nopadding others web"> <!-- Works #4 col 3 -->
<div class="box">
<div class="hover-bg">
<div class="hover-text off">
<a title="Freedom Project #1" href="img/portfolio/04@2x.jpg" data-lightbox-gallery="gallery1" data-lightbox-hidpi="img/portfolio/04@2x.jpg">
<i class="fa fa-expand"></i>
</a>
<a href="#"><i class="fa fa-chain"></i></a><!-- change # with your url to link it to another page -->
</div>
<img src="img/portfolio/04.jpg" class="img-responsive" alt="Image"> <!-- Portfolio Image -->
</div>
</div>
</div> <!-- end Works #4 col 3 -->
<div class="col-xs-12 col-sm-6 col-md-3 nopadding web others"> <!-- Works #5 col 3 -->
<div class="box">
<div class="hover-bg">
<div class="hover-text off">
<a title="Freedom Project #1" href="img/portfolio/05@2x.jpg" data-lightbox-gallery="gallery1" data-lightbox-hidpi="img/portfolio/05@2x.jpg">
<i class="fa fa-expand"></i>
</a>
<a href="#"><i class="fa fa-chain"></i></a><!-- change # with your url to link it to another page -->
</div>
<img src="img/portfolio/05.jpg" class="img-responsive" alt="Image"> <!-- Portfolio Image -->
</div>
</div>
</div> <!-- end Works #5 col 3 -->
<div class="col-xs-12 col-sm-6 col-md-3 nopadding app"> <!-- Works #6 col 3 -->
<div class="box">
<div class="hover-bg">
<div class="hover-text off">
<a title="Freedom Project #1" href="img/portfolio/06@2x.jpg" data-lightbox-gallery="gallery1" data-lightbox-hidpi="img/portfolio/06@2x.jpg">
<i class="fa fa-expand"></i>
</a>
<a href="#"><i class="fa fa-chain"></i></a><!-- change # with your url to link it to another page -->
</div>
<img src="img/portfolio/06.jpg" class="img-responsive" alt="Image"> <!-- Portfolio Image -->
</div>
</div>
</div><!-- end Works #6 col 3 -->
<div class="col-xs-12 col-sm-6 col-md-3 nopadding web brand"><!-- Works #7 col 3 -->
<div class="box">
<div class="hover-bg">
<div class="hover-text off">
<a title="Freedom Project #1" href="img/portfolio/07@2x.jpg" data-lightbox-gallery="gallery1" data-lightbox-hidpi="img/portfolio/07@2x.jpg">
<i class="fa fa-expand"></i>
</a>
<a href="#"><i class="fa fa-chain"></i></a><!-- change # with your url to link it to another page -->
</div>
<img src="img/portfolio/07.jpg" class="img-responsive" alt="Image"> <!-- Portfolio Image -->
</div>
</div>
</div><!-- end Works #7 col 3 -->
<div class="col-xs-12 col-sm-6 col-md-3 nopadding app"> <!-- Works #8 col 3 -->
<div class="box">
<div class="hover-bg">
<div class="hover-text off">
<a title="Freedom Project #1" href="img/portfolio/08@2x.jpg" data-lightbox-gallery="gallery1" data-lightbox-hidpi="img/portfolio/08@2x.jpg">
<i class="fa fa-expand"></i>
</a>
<a href="#"><i class="fa fa-chain"></i></a><!-- change # with your url to link it to another page -->
</div>
<img src="img/portfolio/08.jpg" class="img-responsive" alt="Image"> <!-- Portfolio Image -->
</div>
</div>
</div> <!-- end Works #8 col 3 -->
</div> <!-- End Row -->
</div> <!-- End Container-Fluid -->
</div>
<!-- Process Section
================================================== -->
<div id="tf-process">
<div class="container"> <!-- container -->
<div class="section-header">
<h2>Our Best <span class="highlight"><strong>WorkFlow</strong></span></h2>
<h5><em>We design and build functional and beautiful websites</em></h5>
<div class="fancy"><span><img src="img/favicon.ico" alt="..."></span></div>
</div>
</div><!-- end container -->
<div class="gray-bg"> <!-- fullwidth gray background -->
<div class="container"><!-- container -->
<div class="vline"></div> <!-- Vertical Line -->
<div id="process" class="row"> <!-- row -->
<div class="col-md-10 col-md-offset-1">
<div class="media process"> <!-- Process #1 -->
<div class="media-right media-middle">
<i class="fa fa-search-plus"></i>
</div>
<div class="media-body">
<h4 class="media-heading">Research</h4>
<p>Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent, pede etiam. Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio.</p>
</div>
</div><!-- Process #1 -->
<div class="media process"> <!-- Process #2 -->
<div class="media-right media-middle">
<i class="fa fa-wrench"></i>
</div>
<div class="media-body">
<h4 class="media-heading">Design and Develop</h4>
<p>Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent, pede etiam. Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio.</p>
</div>
</div><!-- Process #2 -->
<div class="media process"> <!-- Process #3 -->
<div class="media-right media-middle">
<i class="fa fa-flask"></i>
</div>
<div class="media-body">
<h4 class="media-heading">Testing and Refine</h4>
<p>Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent, pede etiam. Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio.</p>
</div>
</div><!-- Process #3 -->
<div class="media process"> <!-- Process #4 -->
<div class="media-right media-middle">
<i class="fa fa-truck"></i>
</div>
<div class="media-body">
<h4 class="media-heading">Launch</h4>
<p>Ultrices lacus proin conubia dictum tempus, tempor pede vitae faucibus, sem auctor, molestie diam dictum aliquam. Dolor leo, ridiculus est ut cubilia nec, fermentum arcu praesent, pede etiam. Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio.</p>
</div>
</div><!-- Process #4 -->
</div>
</div> <!-- end row -->
</div><!-- end container -->
</div> <!-- end fullwidth gray background -->
</div>
<!-- Pricing Section
================================================== -->
<div id="tf-pricing">
<div class="container"> <!-- container -->
<div class="section-header">
<h2>Choose The Best <span class="highlight"><strong>Pricing</strong></span></h2>
<h5><em>We design and build functional and beautiful websites</em></h5>
<div class="fancy"><span><img src="img/favicon.ico" alt="..."></span></div>
</div>
<div class="row"> <!-- outer row -->
<div class="col-md-10 col-md-offset-1"> <!-- col 10 with offset 1 to centered -->
<div class="row"> <!-- nested row -->
<div class="col-md-4 nopadding"><!-- Price table #1 -->
<div class="panel panel-default price"> <!-- pricing table wrapper -->
<div class="panel-heading">Basic Plan</div>
<div class="panel-body">
<h1><sup>$</sup>25<small>/mon</small></h1> <!-- Plan Price -->
</div>
<!-- Plan Feature Lists -->
<ul class="list-unstyled">
<li>60 Users</li>
<li>Unlimited Forums</li>
<li>Unlimited Reports</li>
<li>3,000 Entries per Month</li>
<li>200 MB Storage</li>
<li>
<button type="button" class="btn btn-primary btn-block tf-btn">Get Started Now</button>
<small class="text-uppercase">30 Days Free Trial</small>
</li>
</ul><!-- end Plan Feature Lists -->
</div><!-- end pricing table wrapper -->
</div><!-- end Price table #1 -->
<div class="col-md-4 nopadding"><!-- Price table #2 -->
<div class="panel panel-default price featured"><!-- pricing table wrapper -->
<div class="panel-heading">Best Plan</div>
<div class="panel-body">
<h1><sup>$</sup>49<small>/mon</small></h1><!-- Plan Price -->
</div>
<!-- Plan Feature Lists -->
<ul class="list-unstyled">
<li>60 Users</li>
<li>Unlimited Forums</li>
<li>Unlimited Reports</li>
<li>3,000 Entries per Month</li>
<li>200 MB Storage</li>
<li>
<button type="button" class="btn btn-primary btn-block tf-btn color">Get Started Now</button>
<small class="text-uppercase">30 Days Free Trial</small>
</li>
</ul><!-- end Plan Feature Lists -->
</div><!-- end pricing table wrapper -->
</div><!-- end Price table #2 -->
<div class="col-md-4 nopadding"> <!-- Price table #3 -->
<div class="panel panel-default price"> <!-- pricing table wrapper -->
<div class="panel-heading">Premium Plan</div>
<div class="panel-body">
<h1><sup>$</sup>99<small>/mon</small></h1><!-- Plan Price -->
</div>
<!-- Plan Feature Lists -->
<ul class="list-unstyled">
<li>60 Users</li>
<li>Unlimited Forums</li>
<li>Unlimited Reports</li>
<li>3,000 Entries per Month</li>
<li>200 MB Storage</li>
<li>
<button type="button" class="btn btn-primary btn-block tf-btn">Get Started Now</button>
<small class="text-uppercase">30 Days Free Trial</small>
</li>
</ul><!-- end Plan Feature Lists -->
</div><!-- end pricing table wrapper -->
</div><!-- end Price table #3 -->
</div> <!-- end nested row -->
</div> <!-- end col 10 with offset 1 to centered -->
</div> <!-- end outer row -->
</div><!-- end container -->
</div>
<!-- Blog Section
================================================== -->
<div id="tf-blog">
<div class="container"> <!-- container -->
<div class="section-header">
<h2>Latest from the <span class="highlight"><strong>Blog</strong></span></h2>
<h5><em>We design and build functional and beautiful websites</em></h5>
<div class="fancy"><span><img src="img/favicon.ico" alt="..."></span></div>
</div>
</div>
<div id="blog-post" class="gray-bg"> <!-- fullwidth gray background -->
<div class="container"><!-- container -->
<div class="row"> <!-- row -->
<div class="col-md-6"> <!-- Left content col 6 -->
<div class="post-wrap"> <!-- Post Wrapper -->
<div class="media post"> <!-- post wrap -->
<div class="media-left">
<a href="#"> <!-- link to your post single page -->
<img class="media-object" src="http://placehold.it/120x150" alt="..."> <!-- Your Post Image -->
</a>
</div>
<div class="media-body">
<p class="small">January 14, 2015</p>
<a href="#">
<h5 class="media-heading"><strong>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec</strong></h5>
</a>
<p>Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio. Diam nibh diam, quam elit, libero nostra ut. Pellentesque vehicula. Eget sed, dapibus </p>
</div>
</div><!-- end post wrap -->
<div class="post-meta"> <!-- Meta details -->
<ul class="list-inline metas pull-left"> <!-- post metas -->
<li><a href="#">by Rudhi Design</a></li> <!-- meta author -->
<li><a href="#">20 Comments</a></li> <!-- meta comments -->
<li><a href="#">Read More</a></li> <!-- read more link -->
</ul>
<ul class="list-inline meta-detail pull-right"> <!-- user meta interaction -->
<li><a href="#"><i class="fa fa-heart"></i></a> 50</li> <!-- like button -->
<li><i class="fa fa-eye"></i> 110</li> <!-- no. of views -->
</ul>
</div><!-- end Meta details -->
</div><!-- end Post Wrapper -->
<div class="post-wrap"> <!-- Post Wrapper -->
<div class="media post"> <!-- post wrap -->
<div class="media-left">
<a href="#"> <!-- link to your post single page -->
<img class="media-object" src="http://placehold.it/120x150" alt="..."> <!-- Your Post Image -->
</a>
</div>
<div class="media-body">
<p class="small">January 14, 2015</p>
<a href="#">
<h5 class="media-heading"><strong>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec</strong></h5>
</a>
<p>Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio. Diam nibh diam, quam elit, libero nostra ut. Pellentesque vehicula. Eget sed, dapibus </p>
</div>
</div><!-- end post wrap -->
<div class="post-meta"> <!-- Meta details -->
<ul class="list-inline metas pull-left"> <!-- post metas -->
<li><a href="#">by Rudhi Design</a></li> <!-- meta author -->
<li><a href="#">20 Comments</a></li> <!-- meta comments -->
<li><a href="#">Read More</a></li> <!-- read more link -->
</ul>
<ul class="list-inline meta-detail pull-right"> <!-- user meta interaction -->
<li><a href="#"><i class="fa fa-heart"></i></a> 50</li> <!-- like button -->
<li><i class="fa fa-eye"></i> 110</li> <!-- no. of views -->
</ul>
</div><!-- end Meta details -->
</div><!-- end Post Wrapper -->
<div class="post-wrap"> <!-- Post Wrapper -->
<div class="media post"> <!-- post wrap -->
<div class="media-left">
<a href="#"> <!-- link to your post single page -->
<img class="media-object" src="http://placehold.it/120x150" alt="..."> <!-- Your Post Image -->
</a>
</div>
<div class="media-body">
<p class="small">January 14, 2015</p>
<a href="#">
<h5 class="media-heading"><strong>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec</strong></h5>
</a>
<p>Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio. Diam nibh diam, quam elit, libero nostra ut. Pellentesque vehicula. Eget sed, dapibus </p>
</div>
</div><!-- end post wrap -->
<div class="post-meta"> <!-- Meta details -->
<ul class="list-inline metas pull-left"> <!-- post metas -->
<li><a href="#">by Rudhi Design</a></li> <!-- meta author -->
<li><a href="#">20 Comments</a></li> <!-- meta comments -->
<li><a href="#">Read More</a></li> <!-- read more link -->
</ul>
<ul class="list-inline meta-detail pull-right"> <!-- user meta interaction -->
<li><a href="#"><i class="fa fa-heart"></i></a> 50</li> <!-- like button -->
<li><i class="fa fa-eye"></i> 110</li> <!-- no. of views -->
</ul>
</div><!-- end Meta details -->
</div><!-- end Post Wrapper -->
</div> <!-- end Left content col 6 -->
<div class="col-md-6"> <!-- right content col 6 -->
<div class="post-wrap"> <!-- Post Wrapper -->
<div class="media post"> <!-- post wrap -->
<div class="media-left">
<a href="#"> <!-- link to your post single page -->
<img class="media-object" src="http://placehold.it/120x150" alt="..."> <!-- Your Post Image -->
</a>
</div>
<div class="media-body">
<p class="small">January 14, 2015</p>
<a href="#">
<h5 class="media-heading"><strong>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec</strong></h5>
</a>
<p>Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio. Diam nibh diam, quam elit, libero nostra ut. Pellentesque vehicula. Eget sed, dapibus </p>
</div>
</div><!-- end post wrap -->
<div class="post-meta"> <!-- Meta details -->
<ul class="list-inline metas pull-left"> <!-- post metas -->
<li><a href="#">by Rudhi Design</a></li> <!-- meta author -->
<li><a href="#">20 Comments</a></li> <!-- meta comments -->
<li><a href="#">Read More</a></li> <!-- read more link -->
</ul>
<ul class="list-inline meta-detail pull-right"> <!-- user meta interaction -->
<li><a href="#"><i class="fa fa-heart"></i></a> 50</li> <!-- like button -->
<li><i class="fa fa-eye"></i> 110</li> <!-- no. of views -->
</ul>
</div><!-- end Meta details -->
</div><!-- end Post Wrapper -->
<div class="post-wrap"> <!-- Post Wrapper -->
<div class="media post"> <!-- post wrap -->
<div class="media-left">
<a href="#"> <!-- link to your post single page -->
<img class="media-object" src="http://placehold.it/120x150" alt="..."> <!-- Your Post Image -->
</a>
</div>
<div class="media-body">
<p class="small">January 14, 2015</p>
<a href="#">
<h5 class="media-heading"><strong>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec</strong></h5>
</a>
<p>Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio. Diam nibh diam, quam elit, libero nostra ut. Pellentesque vehicula. Eget sed, dapibus </p>
</div>
</div><!-- end post wrap -->
<div class="post-meta"> <!-- Meta details -->
<ul class="list-inline metas pull-left"> <!-- post metas -->
<li><a href="#">by Rudhi Design</a></li> <!-- meta author -->
<li><a href="#">20 Comments</a></li> <!-- meta comments -->
<li><a href="#">Read More</a></li> <!-- read more link -->
</ul>
<ul class="list-inline meta-detail pull-right"> <!-- user meta interaction -->
<li><a href="#"><i class="fa fa-heart"></i></a> 50</li> <!-- like button -->
<li><i class="fa fa-eye"></i> 110</li> <!-- no. of views -->
</ul>
</div><!-- end Meta details -->
</div><!-- end Post Wrapper -->
<div class="post-wrap"> <!-- Post Wrapper -->
<div class="media post"> <!-- post wrap -->
<div class="media-left">
<a href="#"> <!-- link to your post single page -->
<img class="media-object" src="http://placehold.it/120x150" alt="..."> <!-- Your Post Image -->
</a>
</div>
<div class="media-body">
<p class="small">January 14, 2015</p>
<a href="#">
<h5 class="media-heading"><strong>Vel donec et scelerisque vestibulum. Condimentum aliquam, mollit magna velit nec</strong></h5>
</a>
<p>Tempor vestibulum turpis id ligula mi mattis. Eget arcu vitae mauris amet odio. Diam nibh diam, quam elit, libero nostra ut. Pellentesque vehicula. Eget sed, dapibus </p>
</div>
</div><!-- end post wrap -->
<div class="post-meta"> <!-- Meta details -->
<ul class="list-inline metas pull-left"> <!-- post metas -->
<li><a href="#">by Rudhi Design</a></li> <!-- meta author -->
<li><a href="#">20 Comments</a></li> <!-- meta comments -->
<li><a href="#">Read More</a></li> <!-- read more link -->
</ul>
<ul class="list-inline meta-detail pull-right"> <!-- user meta interaction -->
<li><a href="#"><i class="fa fa-heart"></i></a> 50</li> <!-- like button -->
<li><i class="fa fa-eye"></i> 110</li> <!-- no. of views -->
</ul>
</div><!-- end Meta details -->
</div><!-- end Post Wrapper -->
</div><!-- end right content col 6 -->
</div><!-- end row -->
<div class="text-center">
<a href="#" class="btn btn-primary tf-btn color">Load More</a>
</div>
</div><!-- end container -->
</div> <!-- end fullwidth gray background -->
</div>
<!-- Contact Section
================================================== -->
<div id="tf-contact">
<div class="container"> <!-- container -->
<div class="section-header">
<h2>Feel Free to <span class="highlight"><strong>Contact Us</strong></span></h2>
<h5><em>We design and build functional and beautiful websites</em></h5>
<div class="fancy"><span><img src="img/favicon.ico" alt="..."></span></div>
</div>
</div><!-- end container -->
<div id="map"></div> <!-- google map -->
<div class="container"><!-- container -->
<div class="row"> <!-- outer row -->
<div class="col-md-10 col-md-offset-1"> <!-- col 10 with offset 1 to centered -->
<div class="row"> <!-- nested row -->
<!-- contact detail using col 4 -->
<div class="col-md-4">
<div class="contact-detail">
<i class="fa fa-map-marker"></i>
<h4>Jl. Pahlawan VII No.247-D Sidoarjo-Surabaya-Indonesia</h4> <!-- address -->
</div>
</div>
<!-- contact detail using col 4 -->
<div class="col-md-4">
<div class="contact-detail">
<i class="fa fa-envelope-o"></i>
<h4>rudhisasmito@gmail.com</h4><!-- email add -->
</div>
</div>
<!-- contact detail using col 4 -->
<div class="col-md-4">
<div class="contact-detail">
<i class="fa fa-phone"></i>
<h4>+613 0000 0000</h4> <!-- phone no. -->
</div>
</div>
</div> <!-- end nested row -->
</div> <!-- end col 10 with offset 1 to centered -->
</div><!-- end outer row -->
<div class="row text-center"> <!-- contact form outer row with centered text-->
<div class="col-md-10 col-md-offset-1"> <!-- col 10 with offset 1 to centered -->
<form id="contact-form" class="form" name="sentMessage" novalidate> <!-- form wrapper -->
<div class="row"> <!-- nested inner row -->
<!-- Input your name -->
<div class="col-md-4">
<div class="form-group"> <!-- Your name input -->
<input type="text" autocomplete="off" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<!-- Input your email -->
<div class="col-md-4">
<div class="form-group"> <!-- Your email input -->
<input type="email" autocomplete="off" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<!-- Input your Phone no. -->
<div class="col-md-4">
<div class="form-group"> <!-- Your email input -->
<input type="text" autocomplete="off" class="form-control" placeholder="Your Phone No. *" id="phone" required data-validation-required-message="Please enter your phone no.">
<p class="help-block text-danger"></p>
</div>
</div>
</div><!-- end nested inner row -->
<!-- Message Text area -->
<div class="form-group"> <!-- Your email input -->
<textarea class="form-control" rows="7" placeholder="Tell Us Something..." id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
<div id="success"></div>
</div>
<button type="submit" class="btn btn-primary tf-btn color">Send Message</button> <!-- Send button -->
</form><!-- end form wrapper -->
</div><!-- end col 10 with offset 1 to centered -->
</div> <!-- end contact form outer row with centered text-->
</div><!-- end container -->
</div>
<!-- Footer
================================================== -->
<div id="tf-footer">
<div class="container"><!-- container -->
<p class="pull-left">© 2015 ethanol. All rights reserved. Theme by Rudhi Sasmito.</p> <!-- copyright text here-->
<ul class="list-inline social pull-right">
<li><a href="#"><i class="fa fa-facebook"></i></a></li> <!-- Change # With your FB Link -->
<li><a href="#"><i class="fa fa-twitter"></i></a></li> <!-- Change # With your Twitter Link -->
<li><a href="#"><i class="fa fa-google-plus"></i></a></li> <!-- Change # With your Google Plus Link -->
<li><a href="#"><i class="fa fa-dribbble"></i></a></li> <!-- Change # With your Dribbble Link -->
<li><a href="#"><i class="fa fa-behance"></i></a></li> <!-- Change # With your Behance Link -->
<li><a href="#"><i class="fa fa-linkedin"></i></a></li> <!-- Change # With your LinkedIn Link -->
<li><a href="#"><i class="fa fa-youtube"></i></a></li> <!-- Change # With your Youtube Link -->
<li><a href="#"><i class="fa fa-pinterest"></i></a></li> <!-- Change # With your Pinterest Link -->
</ul>
</div><!-- end container -->
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.1.11.1.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript" src="js/owl.carousel.js"></script><!-- Owl Carousel Plugin -->
<script type="text/javascript" src="js/SmoothScroll.js"></script>
<!-- Google Map -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyASm3CwaK9qtcZEWYa-iQwHaGi3gcosAJc&sensor=false"></script>
<script type="text/javascript" src="js/map.js"></script>
<!-- Parallax Effects -->
<script type="text/javascript" src="js/skrollr.js"></script>
<script type="text/javascript" src="js/imagesloaded.js"></script>
<!-- Portfolio Filter -->
<script type="text/javascript" src="js/jquery.isotope.js"></script>
<!-- LightBox Nivo -->
<script type="text/javascript" src="js/nivo-lightbox.min.js"></script>
<!-- Contact page-->
<script type="text/javascript" src="js/jqBootstrapValidation.js"></script>
<script type="text/javascript" src="js/contact.js"></script>
<!-- Javascripts
================================================== -->
<script type="text/javascript" src="js/main.js"></script>
</body>
</html> | AnnaDrive/StudentActivitySystem | application/views/index.php | PHP | mit | 70,565 |
from django.contrib import admin
from feedhoos.worker.models.entry import EntryModel
from feedhoos.finder.models.feed import FeedModel
from feedhoos.reader.models.bookmark import BookmarkModel
from feedhoos.folder.models.folder import FolderModel
class EntryModelAdmin(admin.ModelAdmin):
list_display = ('id', "feed_id", "updated", 'url', 'title')
admin.site.register(EntryModel, EntryModelAdmin)
class FeedModelAdmin(admin.ModelAdmin):
list_display = ('id', "title", "etag", "modified", "url", "link", "last_access")
admin.site.register(FeedModel, FeedModelAdmin)
class BookmarkModelAdmin(admin.ModelAdmin):
list_display = ('id', "feed_id", "last_updated", "rating", "folder_id")
admin.site.register(BookmarkModel, BookmarkModelAdmin)
class FolderModelAdmin(admin.ModelAdmin):
list_display = ('id', "title", "rating")
admin.site.register(FolderModel, FolderModelAdmin)
| 38elements/feedhoos | feedhoos/worker/admin.py | Python | mit | 894 |
'use strict';
angular.module('myApp.contact', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/contact', {
templateUrl: 'contact/contact.html',
controller: 'ContactCtrl',
animation: 'page-fadein'
});
}])
.controller('ContactCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.pageClass = 'page-contact';
myService.set();
$scope.hoveringHuh = false;
$scope.copied = false;
$scope.hover = function() {
return $scope.hoveringHuh = ! $scope.hoveringHuh;
};
$scope.click = function() {
return $scope.copied = true;
};
// copy e-mail address
var clientText = new ZeroClipboard( $("#text-to-copy"), {
moviePath: "ZeroClipboard.swf",
debug: false
} );
clientText.on( "ready", function( readyEvent ) {
clientText.on( "aftercopy", function( event ) {
// $('#copied').fadeIn(2000).delay(3000).fadeOut(3000);
// $scope.copied = true;
} );
} );
}]); | ctong1124/portfolio2016 | app/contact/contact.js | JavaScript | mit | 968 |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributesLocation. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ThreeCs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ThreeCs")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0fe3836c-5a46-4702-a6e1-94c0961e99f1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("69.0.*")]
[assembly: AssemblyFileVersion("69.0.0.0")]
| lathoub/three.cs | ThreeCs/Properties/AssemblyInfo.cs | C# | mit | 1,360 |
<?php
namespace Enigmatic\CRMBundle\Form;
use Enigmatic\CRMBundle\Entity\ContactPhone;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ContactPhoneType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', 'genemu_jqueryselect2_choice', array(
'choices' => array(
ContactPhone::WORK => 'enigmatic.crm.contact.form.field.phones.type.work.label',
ContactPhone::MOBILE => 'enigmatic.crm.contact.form.field.phones.type.mobile.label',
ContactPhone::FAX => 'enigmatic.crm.contact.form.field.phones.type.fax.label',
ContactPhone::OTHER => 'enigmatic.crm.contact.form.field.phones.type.other.label',
),
'required' => true,
'multiple' => false,
'expanded' => false,
'label' => null,
))
->add('phone', 'text', array (
'label' => null,
'required' => false,
'attr' => array(
'pattern' => '^([+]{1}[0-9]{1})?[0-9]{10}$',
'placeholder' => 'enigmatic.crm.contact.form.field.phones.phone.label',
)
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Enigmatic\CRMBundle\Entity\ContactPhone'
));
}
/**
* @return string
*/
public function getName()
{
return 'enigmatic_crm_contact_phone';
}
}
| chadyred/crm | src/Enigmatic/CRMBundle/Form/ContactPhoneType.php | PHP | mit | 1,987 |
namespace EarTrumpet.Interop
{
internal enum AppBarEdge : uint
{
Left = 0,
Top = 1,
Right = 2,
Bottom = 3
}
}
| File-New-Project/EarTrumpet | EarTrumpet/Interop/AppBarEdge.cs | C# | mit | 157 |
require'rails_helper'
feature 'Admin edits site setting' do
let!(:admin) { create :admin_user }
before :each do
SiteSettings.instance.destroy
end
background do
login_as admin, scope: :user
end
scenario 'checks settings' do
visit root_path
click_link 'Admin Panel'
click_link 'Site Settings'
expect(page).to have_content 'Day starts'
expect(page).to have_content 'Day ends'
expect(page).to have_content 'Site title'
expect(page).to have_content 'Schedule time zone'
expect(page).to have_content 'Block reservation cancellation'
expect(page).to have_content 'Email'
end
scenario 'edits site title' do
visit root_path
click_link 'Admin Panel'
click_link 'Site Settings'
fill_in 'Site title', with: 'My Awesome Site'
click_button 'Save'
visit root_path
within 'nav' do
expect(page).to have_content 'My Awesome Site'
end
end
context 'with a schedule item' do
before :all do
Timecop.freeze(Time.now.utc.beginning_of_day)
end
after :all do
Timecop.return
end
let!(:schedule_item) { create :schedule_item, start: Time.now.utc.beginning_of_day + 12.hours }
scenario 'edits schedule time zone' do
visit root_path
click_link 'Admin Panel'
click_link 'Site Settings'
select '0', from: 'Day starts'
select '23', from: 'Day ends'
select 'UTC', from: 'Schedule time zone'
click_button 'Save'
visit root_path
within '.schedule' do
expect(page).to have_content '12:00'
end
click_link 'Admin Panel'
click_link 'Site Settings'
select 'Hawaii', from: 'Schedule time zone'
click_button 'Save'
visit root_path
within '.schedule' do
expect(page).to have_content '02:00'
end
end
scenario 'edits day start so that it\'s later than day end' do
visit root_path
click_link 'Admin Panel'
click_link 'Site Settings'
select '0', from: 'Day starts'
select '23', from: 'Day ends'
select 'UTC', from: 'Schedule time zone'
click_button 'Save'
visit root_path
within '.schedule' do
expect(page).to have_content '12:00'
end
click_link 'Admin Panel'
click_link 'Site Settings'
select '23', from: 'Day starts'
select '15', from: 'Day ends'
click_button 'Save'
visit root_path
within '.schedule' do
expect(page).not_to have_content '12:00'
end
end
end
end | angelikatyborska/fitness-class-schedule | spec/features/admin/site_settings/admin_edits_site_settings_spec.rb | Ruby | mit | 2,527 |
########
"""
This code is open source under the MIT license.
Its purpose is to help create special motion graphics
with effector controls inspired by Cinema 4D.
Example usage:
https://www.youtube.com/watch?v=BYXmV7fObOc
Notes to self:
Create a simialr, lower poly contorl handle and
perhaps auto enable x-ray/bounding.
Long term, might become an entire panel with tools
of all types of effectors, with secitons like
convinience tools (different split faces/loose buttons)
next to the actual different effector types
e.g. transform effector (as it is)
time effector (..?) etc. Research it more.
another scripting ref:
http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Cookbook/Code_snippets/Interface#A_popup_dialog
plans:
- Make checkboxes for fields to have effector affect (loc, rot, scale)
- Name the constraints consistent to effector name, e.g. effector.L.001 for easy removal
- add falloff types (and update-able in driver setting)
- custome driver equation field ('advanced' tweaking, changes drivers for all in that effector group)
- Empty vertex objects for location which AREN'T transformed, so that there is no limit to
how much the location can do (now limited to be between object and base bone)
- create list panel that shows effectors added, and with each selected can do things:
- all more effector objects
- select current objects (and rig)
- change falloff/equation
- remove selected from effector
- remove effector (drivers & rig)
- apply effector in position (removes rig)
Source code available on github:
https://github.com/TheDuckCow/Blender_Effectors
"""
########
bl_info = {
"name": "Blender Effectors",
"author": "Patrick W. Crawford",
"version": (1, 0, 3),
"blender": (2, 71, 0),
"location": "3D window toolshelf",
"category": "Object",
"description": "Effector special motion graphics",
"wiki_url": "https://github.com/TheDuckCow/Blender_Effectors"
}
import bpy
## just in case
from bpy.props import *
from bpy_extras.io_utils import ExportHelper
from bpy.types import Operator
from os.path import dirname, join
""" needed? """
"""
class SceneButtonsPanel():
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "scene"
@classmethod
def poll(cls, context):
rd = context.scene.render
return context.scene and (rd.engine in cls.COMPAT_ENGINES)
"""
""" original """
def createEffectorRig(bones,loc=None):
[bone_base,bone_control] = bones
if (loc==None):
loc = bpy.context.scene.cursor_location
bpy.ops.object.armature_add(location=loc)
rig = bpy.context.active_object
rig.name = "effector"
bpy.types.Object.one = bpy.props.FloatProperty(name="does this setting do anything at all?", description="one hundred million", default=1.000, min=0.000, max=1.000)
rig.one = 0.6
#bpy.ops.wm.properties_add(data_path="object")
"""
bpy.ops.object.mode_set(mode='EDIT')
control = rig.data.edit_bones.new('control')
#bpy.ops.armature.bone_primitive_add() #control
# eventually add property as additional factor
rig.data.bones[0].name = 'base'
rig.data.bones[0].show_wire = True
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
# SCENE REFRESH OR SOMETHING???
rig.data.bones[1].name = 'control'
control = obj.pose.bones[bones['base']]
#rig.data.bones[1].parent = rig.data.[bones['base']] #need other path to bone data
bpy.ops.object.mode_set(mode='OBJECT')
rig.pose.bones[0].custom_shape = bone_base
rig.pose.bones[1].custom_shape = bone_control
# turn of inherent rotation for control??
# property setup
#bpy.ops.wm.properties_edit(data_path='object', property='Effector Scale',
# value='1.0', min=0, max=100, description='Falloff scale of effector')
#scene property='Effector.001'
"""
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.armature.select_all(action='SELECT')
bpy.ops.armature.delete()
arm = rig.data
bones = {}
bone = arm.edit_bones.new('base')
bone.head[:] = 0.0000, 0.0000, 0.0000
bone.tail[:] = 0.0000, 0.0000, 1.0000
bone.roll = 0.0000
bone.use_connect = False
bone.show_wire = True
bones['base'] = bone.name
bone = arm.edit_bones.new('control')
bone.head[:] = 0.0000, 0.0000, 0.0000
bone.tail[:] = 0.0000, 1.0000, 0.0000
bone.roll = 0.0000
bone.use_connect = False
bone.parent = arm.edit_bones[bones['base']]
bones['control'] = bone.name
bpy.ops.object.mode_set(mode='OBJECT')
pbone = rig.pose.bones[bones['base']]
#pbone.rigify_type = ''
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
pbone.bone.layers = [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]
pbone = rig.pose.bones[bones['control']]
#pbone.rigify_type = ''
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
#pbone.bone.layers = [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True]
bpy.ops.object.mode_set(mode='EDIT')
for bone in arm.edit_bones:
bone.select = False
bone.select_head = False
bone.select_tail = False
for b in bones:
bone = arm.edit_bones[bones[b]]
bone.select = True
bone.select_head = True
bone.select_tail = True
arm.edit_bones.active = bone
arm.layers = [(x in [0]) for x in range(32)]
bpy.ops.object.mode_set(mode='OBJECT')
rig.pose.bones[0].custom_shape = bone_base
rig.pose.bones[1].custom_shape = bone_control
return rig
def createBoneShapes():
if (bpy.data.objects.get("effectorBone1") is None) or (bpy.data.objects.get("effectorBone2") is None):
bpy.ops.mesh.primitive_uv_sphere_add(segments=8, ring_count=8, enter_editmode=True)
bpy.ops.mesh.delete(type='ONLY_FACE')
bpy.ops.object.editmode_toggle()
effectorBone1 = bpy.context.active_object
effectorBone1.name = "effectorBone1"
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1, enter_editmode=False, size=0.5)
effectorBone2 = bpy.context.active_object
effectorBone2.name = "effectorBone2"
#move to last layer and hide
[False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True]
effectorBone1.hide = True
effectorBone2.hide = True
effectorBone1.hide_render = True
effectorBone2.hide_render = True
return [bpy.data.objects["effectorBone1"],bpy.data.objects["effectorBone2"]]
def addEffectorObj(objList, rig):
# store previous selections/active etc
prevActive = bpy.context.scene.objects.active
#default expression, change later with different falloff etc
default_expression = "1/(.000001+objDist)*scale"
#empty list versus obj list?
emptyList = []
# explicit state set
bpy.ops.object.mode_set(mode='OBJECT')
# iterate over all objects passed in
for obj in objList:
if obj.type=="EMPTY": continue
##############################################
# Add the empty intermediate object/parent
bpy.ops.object.empty_add(type='PLAIN_AXES', view_align=False, location=obj.location)
empty = bpy.context.active_object
empty.name = "effr.empty"
obj.select = True
preParent = obj.parent
bpy.ops.object.parent_set(type='OBJECT', keep_transform=True)
bpy.context.object.empty_draw_size = 0.1
if (preParent):
bpy.ops.object.select_all(action='DESELECT')
# need to keep transform!
preParent.select = True
empty.select = True
bpy.context.scene.objects.active = preParent
bpy.ops.object.parent_set(type='OBJECT', keep_transform=True)
#empty.parent = preParent
bpy.context.scene.objects.active = obj
preConts = len(obj.constraints) # starting number of constraints
###############################################
# LOCATION
bpy.ops.object.constraint_add(type='COPY_LOCATION')
obj.constraints[preConts].use_offset = True
obj.constraints[preConts].target_space = 'LOCAL'
obj.constraints[preConts].owner_space = 'LOCAL'
obj.constraints[preConts].target = rig
obj.constraints[preConts].subtarget = "control"
driverLoc = obj.constraints[preConts].driver_add("influence").driver
driverLoc.type = 'SCRIPTED'
# var for objDist two targets, 1st is "base" second is "distanceRef"
varL_dist = driverLoc.variables.new()
varL_dist.type = 'LOC_DIFF'
varL_dist.name = "objDist"
varL_dist.targets[0].id = rig
varL_dist.targets[0].bone_target = 'base'
varL_dist.targets[1].id = empty
varL_scale = driverLoc.variables.new()
varL_scale.type = 'TRANSFORMS'
varL_scale.name = 'scale'
varL_scale.targets[0].id = rig
varL_scale.targets[0].transform_type = 'SCALE_Z'
varL_scale.targets[0].bone_target = 'base'
driverLoc.expression = default_expression
###############################################
# ROTATION
bpy.ops.object.constraint_add(type='COPY_ROTATION')
preConts+=1
obj.constraints[preConts].target_space = 'LOCAL'
obj.constraints[preConts].owner_space = 'LOCAL'
obj.constraints[preConts].target = rig
obj.constraints[preConts].subtarget = "control"
driverRot = obj.constraints[preConts].driver_add("influence").driver
driverRot.type = 'SCRIPTED'
# var for objDist two targets, 1st is "base" second is "distanceRef"
varR_dist = driverRot.variables.new()
varR_dist.type = 'LOC_DIFF'
varR_dist.name = "objDist"
varR_dist.targets[0].id = rig
varR_dist.targets[0].bone_target = 'base'
varR_dist.targets[1].id = obj
varR_scale = driverRot.variables.new()
varR_scale.type = 'TRANSFORMS'
varR_scale.name = 'scale'
varR_scale.targets[0].id = rig
varR_scale.targets[0].transform_type = 'SCALE_Z'
varR_scale.targets[0].bone_target = 'base'
driverRot.expression = default_expression
###############################################
# SCALE
bpy.ops.object.constraint_add(type='COPY_SCALE')
preConts+=1
obj.constraints[preConts].target_space = 'LOCAL'
obj.constraints[preConts].owner_space = 'LOCAL'
obj.constraints[preConts].target = rig
obj.constraints[preConts].subtarget = "control"
driverScale = obj.constraints[preConts].driver_add("influence").driver
driverScale.type = 'SCRIPTED'
# var for objDist two targets, 1st is "base" second is "distanceRef"
varS_dist = driverScale.variables.new()
varS_dist.type = 'LOC_DIFF'
varS_dist.name = "objDist"
varS_dist.targets[0].id = rig
varS_dist.targets[0].bone_target = 'base'
varS_dist.targets[1].id = obj
varS_scale = driverScale.variables.new()
varS_scale.type = 'TRANSFORMS'
varS_scale.name = 'scale'
varS_scale.targets[0].id = rig
varS_scale.targets[0].transform_type = 'SCALE_Z'
varS_scale.targets[0].bone_target = 'base'
driverScale.expression = default_expression
########################################################################################
# Above for precursor functions
# Below for the class functions
########################################################################################
class addEffector(bpy.types.Operator):
"""Create the effector object and setup"""
bl_idname = "object.add_effector"
bl_label = "Add Effector"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
objList = bpy.context.selected_objects
[effectorBone1,effectorBone2] = createBoneShapes()
rig = createEffectorRig([effectorBone1,effectorBone2])
addEffectorObj(objList, rig)
bpy.context.scene.objects.active = rig
return {'FINISHED'}
class updateEffector(bpy.types.Operator):
bl_idname = "object.update_effector"
bl_label = "Update Effector"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
print("Update Effector: NOT CREATED YET!")
# use the popup window??
return {'FINISHED'}
class selectEmpties(bpy.types.Operator):
bl_idname = "object.select_empties"
bl_label = "Select Effector Empties"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
print("Selecting effector empties: NOT COMPLETELY CORRECT YET!")
# just selects all empties, lol.
bpy.ops.object.select_by_type(type='EMPTY')
return {'FINISHED'}
class separateFaces(bpy.types.Operator):
"""Separate all faces into new meshes"""
bl_idname = "object.separate_faces"
bl_label = "Separate Faces to Objects"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
# make sure it's currently in object mode for sanity
bpy.ops.object.mode_set(mode='OBJECT')
for obj in bpy.context.selected_objects:
bpy.context.scene.objects.active = obj
if obj.type != "MESH": continue
#set scale to 1
try:
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
except:
print("couodn't transform")
print("working?")
#mark all edges sharp
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.mark_sharp()
bpy.ops.object.mode_set(mode='OBJECT')
#apply modifier to split faces
bpy.ops.object.modifier_add(type='EDGE_SPLIT')
obj.modifiers[-1].split_angle = 0
bpy.ops.object.modifier_apply(apply_as='DATA', modifier=obj.modifiers[-1].name)
#clear sharp
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.mark_sharp(clear=True)
bpy.ops.object.mode_set(mode='OBJECT')
#separate to meshes
bpy.ops.mesh.separate(type="LOOSE")
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')
return {'FINISHED'}
# SceneButtonsPanel
# ^^ above for attempt to make in scenes panel
class effectorPanel(bpy.types.Panel):
"""Effector Tools"""
bl_label = "Effector Tools"
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOLS'
bl_category = "Tools"
"""
bl_label = "Effector Tools"
bl_space_type = 'VIEW_3D'#"PROPERTIES" #or 'VIEW_3D' ?
bl_region_type = "WINDOW"
bl_context = "scene"
"""
def draw(self, context):
view = context.space_data
scene = context.scene
layout = self.layout
split = layout.split()
col = split.column(align=True)
col.operator("object.separate_faces", text="Separate Faces")
split = layout.split() # uncomment to make vertical
#col = split.column(align=True) # uncomment to make horizontal
col.operator("object.add_effector", text="Add Effector")
split = layout.split()
col.operator("wm.mouse_position", text="Update Effector alt")
col.operator("object.select_empties", text="Select Empties")
split = layout.split()
col = split.column(align=True)
#col = layout.column()
layout.label("Disable Recommended:")
col.prop(view, "show_relationship_lines")
# shameless copy from vertex group pa
# funcitons to implement:
# add new (change from current, where it creates just the armature
# and later need to assign objects to it
# need to figure out data structure for it! I think properties
# for each of the objects, either unique per group or over+1 unique per group
# Assign
# Remove
# Select
# Deselect
# select Effector Control
"""
ob = context.object
group = ob.vertex_groups.active
rows = 1
if group:
rows = 3
row = layout.row()
row.template_list("MESH_UL_vgroups", "", ob, "vertex_groups", ob.vertex_groups, "active_index", rows=rows)
col = row.column(align=True)
col.operator("object.vertex_group_add", icon='ZOOMIN', text="")
col.operator("object.vertex_group_remove", icon='ZOOMOUT', text="").all = False
if ob.vertex_groups and (ob.mode == 'OBJECT'):
row = layout.row()
sub = row.row(align=True)
sub.operator("object.vertex_group_assign", text="Assign")
sub.operator("object.vertex_group_remove_from", text="Remove")
row = layout.row()
sub = row.row(align=True)
sub.operator("object.vertex_group_select", text="Select")
sub.operator("object.vertex_group_deselect", text="Deselect")
"""
########################################################################################
# Above for the class functions
# Below for extra classes/registration stuff
########################################################################################
#### WIP popup
class WIPpopup(bpy.types.Operator):
bl_idname = "error.message"
bl_label = "WIP popup"
type = StringProperty()
message = StringProperty()
def execute(self, context):
self.report({'INFO'}, self.message)
print(self.message)
return {'FINISHED'}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_popup(self, width=350, height=40)
return self.execute(context)
def draw(self, context):
self.layout.label("This addon is a work in progress, feature not yet implemented")
row = self.layout.split(0.80)
row.label("")
row.operator("error.ok")
# shows in header when run
class notificationWIP(bpy.types.Operator):
bl_idname = "wm.mouse_position"
bl_label = "Mouse location"
def execute(self, context):
# rather then printing, use the report function,
# this way the message appears in the header,
self.report({'INFO'}, "Not Implemented")
return {'FINISHED'}
def invoke(self, context, event):
return self.execute(context)
# WIP OK button general purpose
class OkOperator(bpy.types.Operator):
bl_idname = "error.ok"
bl_label = "OK"
def execute(self, context):
#eventually another one for url lib
return {'FINISHED'}
# This allows you to right click on a button and link to the manual
# auto-generated code, not fully changed
def add_object_manual_map():
url_manual_prefix = "https://github.com/TheDuckCow"
url_manual_mapping = (
("bpy.ops.mesh.add_object", "Modeling/Objects"),
)
return url_manual_prefix, url_manual_mapping
def register():
bpy.utils.register_class(addEffector)
bpy.utils.register_class(updateEffector)
bpy.utils.register_class(effectorPanel)
bpy.utils.register_class(separateFaces)
bpy.utils.register_class(selectEmpties)
bpy.utils.register_class(WIPpopup)
bpy.utils.register_class(notificationWIP)
bpy.utils.register_class(OkOperator)
#bpy.utils.register_manual_map(add_object_manual_map)
def unregister():
bpy.utils.unregister_class(addEffector)
bpy.utils.unregister_class(updateEffector)
bpy.utils.unregister_class(effectorPanel)
bpy.utils.unregister_class(separateFaces)
bpy.utils.unregister_class(selectEmpties)
bpy.utils.unregister_class(WIPpopup)
bpy.utils.unregister_class(notificationWIP)
bpy.utils.unregister_class(OkOperator)
#bpy.utils.unregister_manual_map(add_object_manual_map)
if __name__ == "__main__":
register()
| kmeirlaen/Blender_Effectors | effector.py | Python | mit | 18,791 |
var indexSectionsWithContent =
{
0: "acdefhilmnoprtw",
1: "w",
2: "aehilmoprw",
3: "w",
4: "acdefhlnrt",
5: "w",
6: "w",
7: "w"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "files",
3: "functions",
4: "variables",
5: "typedefs",
6: "enums",
7: "defines"
};
var indexSectionLabels =
{
0: "All",
1: "Data Structures",
2: "Files",
3: "Functions",
4: "Variables",
5: "Typedefs",
6: "Enumerations",
7: "Macros"
};
| niho/libwave | doc/private/html/search/searchdata.js | JavaScript | mit | 471 |
<?php
namespace Nwidart\Modules\Commands;
use Illuminate\Console\Command;
use Nwidart\Modules\Module;
use Symfony\Component\Console\Input\InputArgument;
class DisableCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'module:disable';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Disable the specified module.';
/**
* Execute the console command.
*/
public function handle() : int
{
/**
* check if user entred an argument
*/
if ($this->argument('module') === null) {
$this->disableAll();
}
/** @var Module $module */
$module = $this->laravel['modules']->findOrFail($this->argument('module'));
if ($module->isEnabled()) {
$module->disable();
$this->info("Module [{$module}] disabled successful.");
} else {
$this->comment("Module [{$module}] has already disabled.");
}
return 0;
}
/**
* disableAll
*
* @return void
*/
public function disableAll()
{
/** @var Modules $modules */
$modules = $this->laravel['modules']->all();
foreach ($modules as $module) {
if ($module->isEnabled()) {
$module->disable();
$this->info("Module [{$module}] disabled successful.");
} else {
$this->comment("Module [{$module}] has already disabled.");
}
}
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['module', InputArgument::OPTIONAL, 'Module name.'],
];
}
}
| nWidart/laravel-modules | src/Commands/DisableCommand.php | PHP | mit | 1,832 |
#! /usr/bin/env python
import flickr_api, pprint, os, sys,argparse,json,csv
flickr_api.set_keys(api_key = '52182e4e29c243689f8a8f45ee2939ae', api_secret = 'a6238b15052797dc')
def DownloadSource(SourceList, PhotosetTitle):
for url in SourceList:
os.system("wget --append-output=download.log --no-verbose --no-clobber -P '%s' -i %s" % (PhotosetTitle,'downloadstack'))
#print url
pass
def GetSource(PhotoList,SizeToDownload):
SourceList = []
f = open('downloadstack', 'wb')
for PhotoId in PhotoList:
r = flickr_api.method_call.call_api(
method = "flickr.photos.getSizes",
photo_id = PhotoId
)
for Size in r['sizes']['size']:
if Size['label'] == SizeToDownload:
SourceList.append(Size['source'])
f.write('%s \n' % Size['source'])
f.close()
return SourceList
def GetInfo(PhotoList,userid):
for PhotoId in PhotoList:
g = open('/home/chandrasg/Desktop/%s/%s_Info.json'%(userid,PhotoId),'wb')
g=convert(g)
h = open('/home/chandrasg/Desktop/%s/%s_Exif.json'%(userid,PhotoId),'wb')
h=convert(h)
#print g
q= flickr_api.method_call.call_api(
method = "flickr.photos.getInfo",
photo_id = PhotoId,
format='xml'
)
q=convert(q)
g.write(str(q))
g.close()
r=flickr_api.method_call.call_api(
method = "flickr.photos.getExif",
photo_id = PhotoId,
format='xml'
)
r=convert(r)
h.write(str(r))
h.close()
def GetFavorites(userid):
PhotoList=[]
r = flickr_api.method_call.call_api(
method = "flickr.favorites.getPublicList",
user_id = userid,
per_page=200
)
for r in r['photos']['photo']:
PhotoList.append(r['id'])
return PhotoList
def convert(input):
if isinstance(input, dict):
return {convert(key): convert(value) for key, value in input.iteritems()}
elif isinstance(input, list):
return [convert(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
def GetUserid(userid):
userid= "http://www.flickr.com/photos/"+userid+"/"
r = flickr_api.method_call.call_api(
method = "flickr.urls.lookupUser",
url=userid
)
return r['user']['id']
def GetUserfriends(userid):
h = open('/home/chandrasg/Desktop/%s_friends.json'%userid,'wb')
h=convert(h)
q= flickr_api.method_call.call_api(
method = "flickr.contacts.getPublicList",
user_id = userid,
format='xml'
)
q=convert(q)
g.write(str(q))
g.close()
with open('users.txt','rb') as infile:
reader=csv.reader(infile)
for user in reader:
userid=user[0]
if userid[0].isdigit():
print userid
SizeToDownload = 'Large'
PhotoList = GetFavorites(userid)
print "Found %s Photos..." % (len(PhotoList))
SourceList = GetSource(PhotoList,SizeToDownload)
print "Downloading %s Photos..." % (len(SourceList))
DownloadSource(SourceList,userid)
GetInfo(PhotoList,userid)
GetUserfriends(userid)
os.remove('./downloadstack')
else:
print userid
userid=GetUserid(userid)
userid=convert(userid)
print userid
SizeToDownload = 'Large'
PhotoList = GetFavorites(userid)
print "Found %s Photos..." % (len(PhotoList))
SourceList = GetSource(PhotoList,SizeToDownload)
print "Downloading %s Photos..." % (len(SourceList))
DownloadSource(SourceList,userid)
GetInfo(PhotoList,userid)
GetUserfriends(userid)
os.remove('./downloadstack')
| sharathchandra92/flickrapi_downloadfavorites | flickrdownload.py | Python | mit | 3,886 |
/**
* Homes Configuration
*/
.config(function ($routeProvider) {
$routeProvider.when('/homes', {
controller: 'homesRoute',
templateUrl: 'views/homes.html',
reloadOnSearch: false
});
}); | TheDarkCode/AngularAzureSearch | src/AngularAzureSearch/liamcaReference/js/app/homesCtrl/config/homesConfig.js | JavaScript | mit | 222 |
/**
* This deadlock is missed if the transitive closure of the
* `X is held by this thread while locking Y' relation is not computed when
* building the lock graph because the B lock causes the (A, B)(B, C)(C, A)
* cycle to have two edges (A, B)(B, C) within the same thread (t0). If the
* transitive closure is computed, the cycle we find is (A, C)(C, A) instead,
* which is valid. Thus, the transitive closure allows us to "jump" over the
* B lock because there is a DIRECT edge from A to C.
*/
#include <d2mock.hpp>
int main(int argc, char const* argv[]) {
d2mock::mutex A, B, C;
d2mock::thread t0([&] {
A.lock();
B.lock();
C.lock();
C.unlock();
B.unlock();
A.unlock();
});
d2mock::thread t1([&] {
C.lock();
A.lock();
A.unlock();
C.unlock();
});
auto test_main = [&] {
t0.start();
t1.start();
t1.join();
t0.join();
};
return d2mock::check_scenario(test_main, argc, argv, {
{
{t0, A, B, C},
{t1, C, A}
}
});
}
| ldionne/d2 | test/scenarios/miss_unless_transitive_closure.cpp | C++ | mit | 1,188 |
class Parent < ActiveRecord::Base
wikify
has_many :children
end | Arcath/Wikify | spec/models/parent.rb | Ruby | mit | 70 |
namespace IrbisUI.Pft
{
partial class PftDebuggerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// PftDebuggerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(584, 326);
this.Name = "PftDebuggerForm";
this.Text = "PftDebuggerForm";
this.ResumeLayout(false);
}
#endregion
}
} | amironov73/ManagedIrbis | Source/Classic/Libs/IrbisUI/Source/Pft/PftDebuggerForm.Designer.cs | C# | mit | 1,403 |
import {Glyphicon, Table} from 'react-bootstrap';
let defaultActions = ['Download', 'Bookmark'];
const actions = {
link : defaultActions,
image: defaultActions,
text : [...defaultActions, 'Edit'],
web : [...defaultActions, 'Preview', 'Edit']
};
export default class ActionView extends React.Component {
makeBookmark(activeId) {
this.getActiveModel(activeId).toggleBookmark();
}
makeAction(action, activeId) {
switch (action){
case 'Bookmark':
this.makeBookmark(activeId);
break;
}
}
getActiveModel(activeId) {
return this.props.collection.get(activeId);
}
fileActions(activeId){
let fileType = this.getActiveModel(activeId).toJSON().format || 'link';
return _.map(actions[fileType], (action, index)=> {
return (
<tr key={index}>
<td onClick={this.makeAction.bind(this, action, activeId)}>
{ action === 'Download' ? <Glyphicon glyph="download-alt"/> :
action === 'Bookmark' ? <Glyphicon glyph="bookmark"/> :
action === 'Preview' ? <Glyphicon glyph="eye-open"/> :
action === 'Edit' ? <Glyphicon glyph="pencil"/> : null
}
<strong> {action} </strong>
</td>
</tr>
)
});
}
showActiveFile(activeId){
return (
<tr>
<td>File selected:
<strong>{this.getActiveModel(activeId).toJSON().name}</strong>
</td>
</tr>
);
}
render() {
let selectFile = (
<tr>
<td>Select file at the left side by clicking on it</td>
</tr>
);
let activeId = this.props.activeId;
return (
<Table responsive hover bordered className="action-view">
<thead>
<tr>
<th><strong>Action</strong></th>
</tr>
</thead>
<tbody>
{ !activeId ? selectFile : this.fileActions.bind(this, activeId)()}
{ !activeId ? null : this.showActiveFile.bind(this, activeId)()}
</tbody>
</Table>
);
}
} | andrey-ponamarev/file-manager | app/components/ActionView.js | JavaScript | mit | 1,844 |
<?php
include_once 'session.inc.php';
include_once 'check_login.php';
include_once 'connect.inc.php';
if(!empty($_GET['category']) && (!empty($_GET['usn']) || !empty($_GET['email']) ) && !empty($_GET['passkey']))
{
$category=mysql_real_escape_string($_GET['category']);
$usn=mysql_real_escape_string($_GET['usn']);
$passkey=mysql_real_escape_string($_GET['passkey']);
$email=mysql_real_escape_string($_GET['email']);
if($category=="student")
{
$query1=mysql_query("SELECT activated FROM users WHERE usn='$usn' AND confirmation='$passkey'") or die('Cannot execute query1');
$row1=mysql_fetch_assoc($query1);
if($row1['activated']==1)
$_SESSION['msg1']="<div style=\"color:red\"><b>Your account has already been activated.</b></div><br><br>";
else if(mysql_num_rows($query1)==1)
{
$query2=mysql_query("UPDATE users SET activated=1 WHERE usn='$usn' AND confirmation='$passkey'") or die('Cannot execute query2');
$_SESSION['msg1']="<div style=\"color:green\"><b>Your account has been activated successfully.</b></div><br><br>";
}
else
$_SESSION['msg1']="<div style=\"color:red\"><b>Invalid operations.</b></div><br><br>";
}
else if($category=="teacher")
{
$query3=mysql_query("SELECT activated FROM staff WHERE email='$usn' AND confirmation='$passkey'") or die('Cannot execute query3');
$row3=mysql_fetch_assoc($query3);
if($row3['activated']==1)
$_SESSION['msg1']="<div style=\"color:red\"><b>Your account has already been activated.</b></div><br><br>";
else if(mysql_num_rows($query3)==1)
{
$query4=mysql_query("UPDATE users SET activated=1 WHERE email='$usn' AND confirmation='$passkey'") or die('Cannot execute query4');
$_SESSION['msg1']="<div style=\"color:green\"><b>Your account has been activated successfully.</b></div><br><br>";
}
else
$_SESSION['msg1']="<div style=\"color:red\"><b>Invalid operations.</b></div><br><br>";
}else if($category=="HOD")
{
$query3=mysql_query("SELECT activated FROM hod WHERE email='$email' AND confirmation='$passkey'") or die('Cannot execute query3');
$row3=mysql_fetch_assoc($query3);
if($row3['activated']==1)
$_SESSION['msg1']="<div style=\"color:red\"><b>Your account has already been activated.</b></div><br><br>";
else if(mysql_num_rows($query3)==1)
{
$query4=mysql_query("UPDATE hod SET activated=1 WHERE email='$email' AND confirmation='$passkey'") or die('Cannot execute query4');
$_SESSION['msg1']="<div style=\"color:green\"><b>Your account has been activated successfully.</b></div><br><br>";
}
else
$_SESSION['msg1']="<div style=\"color:red\"><b>Invalid operations.</b></div><br><br>";
}
}
header("location:index.php");
?> | ajhalthor/signup-login-form | confirm.php | PHP | mit | 2,717 |
import sigopt.cli.commands.cluster
import sigopt.cli.commands.config
import sigopt.cli.commands.experiment
import sigopt.cli.commands.init
import sigopt.cli.commands.local
import sigopt.cli.commands.version
import sigopt.cli.commands.training_run
from .base import sigopt_cli
| sigopt/sigopt-python | sigopt/cli/commands/__init__.py | Python | mit | 277 |
IonicNotification.setup do |config|
# ==> Configuration for the Ionic.io Application ID
# The Application ID can be found on the dashboard of
# https://apps.ionic.io/apps
config.ionic_application_id = ENV["IONIC_APPLICATION_ID"]
# ==> Configuration for the Ionic API Key
# The API Key for your application can be found
# within the Settings of your application on
# https://apps.ionic.io/apps
config.ionic_api_key = ENV["IONIC_API_KEY"]
config.ionic_application_api_token = ENV["IONIC_APPLICATION_API_TOKEN"]
# Your Ionic app name will be used for the notification
# title if none is provided. If you leave this undefined
# IonicNotification will use your Rails app name
config.ionic_app_name = Rails.application.class.parent_name
# If you want, you can customize IonicNotification logging level
# It defaults to :debug
# config.log_level = :debug
#
# You can change the amount of stored sent notifications
# config.notification_store_limit = 3
#
# By default, notifications with no message provided will be skipped,
# you don't want your clients to receive a notification with no message,
# right? Well, sometimes it can be useful to speed up development
# and test. You could like to be able to do something like:
# User.first.notify
# and see what happens, without bothering writing a fake message.
# You can enable this if you want:
# config.process_empty_messages = true
# Or in a more safe way:
# config.process_empty_messages = !Rails.env.production?
#
# Anyway, you can set up a default message to be used when you don't
# provide one:
# config.default_message = "This was intended to be a beautiful notification. Unfortunately, you're not qualified to read it."
# If production is set to true, notifications will be sent
# to all devices which have your app running with production
# certificates (generally coming from store). Otherwise,
# if set to false, to all devices which have your app running
# with developer certificates.
config.ionic_app_in_production = true
# NEEDS DOCUMENTATION
config.production_profile_tag = ENV["IONIC_APP_PRODUCTION_PROFILE"]
config.development_profile_tag = ENV["IONIC_APP_DEVELOPMENT_PROFILE"]
# If you want a more flexible solution, you can
# uncomment this, so that notifications will be sent
# to "production devices" only while Rails app is running
# in production environment
# config.ionic_app_in_production = Rails.env.production?
# ==> Configuration for the location of the API
# Refer to the Ionic documentation for the correct location
# Current documentation can be found here:
# http://docs.ionic.io/docs/push-sending-push and
# defaults to https://push.ionic.io
# config.ionic_api_url = ENV["IONIC_API_URL"]
end
| rentziass/ionic_notification | lib/generators/ionic_notification/install/templates/ionic_notification.rb | Ruby | mit | 2,789 |
<style type="text/css">
.cart-coupon-code-show{display:none;}
a.tooltip{ width: 23px;
height: 23px;
background: #9c9c9c;
display: block;
color: #fff;
position: absolute;
top: 10px;
right: 7px;
border-radius: 20px;
text-align: center;
line-height: 23px;
font-family: trade-gotich-medium, Helvetica, Arial, sans-serif;
font-weight: bold;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
var bagCount = $('.bag-count').find('a').length ? $('.bag-count a').html() : $('.bag-count').html();
$('#cartpage').addClass('cartpage')
$('#cartpage').addClass('my-bag-selected');
if(bagCount>0){
$('#cartpage').find('.header-mini-cart').removeClass('empty-red-bag').removeClass('empty-black-bag').addClass('filled-white-bag');
}else{
$('#cartpage').find('.header-mini-cart').removeClass('empty-red-bag').removeClass('empty-black-bag').addClass('empty-white-bag');
}
$('.mini-cart-holder').find('.bag-count').css('color','#fff');
$('.mini-cart-holder').find('.bag-count a').css('color','#fff');
});
</script>
<div id="main" role="main" class="primary-focus clearfix">
<div class="cart-header">
<h2>My Bag</h2>
</div>
<div class="breadcrumb-container cart-breadcrumb-container">
<ol class="breadcrumb cart-breadcrumb">
<li>
<h4>
<a href="<?=base_url();?>" title="Home" >Home</a>
</h4>
<span class="divider">/</span>
</li>
<li>
<h4>
<a href="<?=base_url('cart');?>" title="Your Shopping Bag" class="breadcrumb-last" >Your Shopping Bag</a>
</h4>
</li>
</ol>
</div>
<div class="cart-wrapper container-fluid cnc-redesign " data-purchase-limit="{'lineItem' :5.0, 'totalItem': 50.0}">
<?php if(isset($cart_data) && isset($cart_data['cart_detail']) && !empty($cart_data['cart_detail'])) { ?>
<div id="primary" class="primary-content pageName col-md-9" data-pagename="Cart">
<form action="<?=base_url('cart'); ?>" method="post" name="dwfrm_cart" class="cart-items-form" novalidate="novalidate">
<fieldset>
<button class="visually-hidden hide" type="submit" value="dwfrm_cart_updateCart" name="dwfrm_cart_updateCart"></button>
<div id="js-continue-shoping" class="continue-shopping primary-button">
Back to Shopping
</div>
<div id="js-checkout-button" class="checkout-button primary-button checkout-button-duplicate" style="display:none;">
Proceed with checkout
</div>
<div class="cart-footer visually-hidden">
<div class="cart-order-totals">
<button type="submit" value="dwfrm_cart_updateCart" name="dwfrm_cart_updateCart" id="update-cart">
Update Cart </button>
</div>
</div>
<div class="tabling-data col-md-12">
<div class="thead-data row mobile-hide">
<div class="col-md-6 section-header first-child">
Shopping Bag<span> -You have
<?php if(!empty($cart_data)) {
echo count($cart_data['cart_detail']);
} else {
echo '0';
} ?> products in your bag</span>
</div>
<h3 class="col-md-2 section-header qty">Quantity</h3>
<h3 class="col-md-2 section-header price">Price</h3>
<h3 class="col-md-2 section-header last-child">Total Price</h3>
</div>
<hr class="mobile-hide">
<?php if(!empty($cart_data)) { ?>
<?php foreach ($cart_data['cart_detail'] as $row) { ?>
<div class="tbody-data row " id="cart_box_<?=$row['cart_id']; ?>">
<div class="primary-product-detail global.product col-sm-12 col-md-6">
<div class="item-image col-sm-4 col-md-5">
<a href="<?=$row['link']; ?>" title="<?=$row['name']; ?>">
<img itemprop="image" class="primary-image" src="<?=$row['image']; ?>" >
</a>
</div>
<div class="item-details col-sm-8 col-md-7">
<div class="product-list-item">
<div class="name">
<a href="<?=$row['link']; ?>" title="<?=$row['name']; ?>">Diesel <?=$row['name']; ?></a>
</div>
<div class="product-group">
<?=$row['category'];?>
</div>
<?php if($row['color_name'] != '') { ?>
<div class="attribute">
<span class="label">Colour:</span>
<span class="value"><?=$row['color_name'];?></span>
</div>
<?php } ?>
<?php if($row['size'] != '') { ?>
<div class="attribute">
<span class="label">Size:</span>
<span class="value"><?=$row['size'];?></span>
</div>
<?php } ?>
<?php if($row['length'] != '') { ?>
<div class="attribute">
<span class="label">Length:</span>
<span class="value"><?=$row['length'];?></span>
</div>
<?php } ?>
</div>
<div class="diesel-sr-eligible-cart" name="sr_cartProductDiv"></div>
</div>
<div class="item-link">
<ul class="item-user-actions row ">
<li class="remove-bag-item col-sm-4 col-md-4 col-lg-3">
<input type="hidden" name="qty-<?=$row['barcode'].'-'.$row['cart_id']; ?>" id="qty-<?=$row['barcode'].'-'.$row['cart_id']; ?>" value="<?=$row['qty']; ?>">
<button data-pname="<?=$row['name']; ?>" class="remove-product button-text" title="Remove product from cart" type="submit" value="REMOVE" name="remove-item" id="remove-<?=$row['barcode'].'-'.$row['cart_id']; ?>"><span>REMOVE</span></button>
<script type="text/javascript">
$("#remove-<?php echo $row['barcode'].'-'.$row['cart_id']; ?>").click(function(){
$("#qty-<?php echo $row['barcode'].'-'.$row['cart_id']; ?>").val('0');
});
</script>
</li>
<li class="col-sm-4 col-lg-2 col-md-4 sprite-icon">
<a href="<?=$row['edit_link']; ?>" title="<?=$row['name']; ?>" style="text-decoration:underline;">Edit </a>
</li>
<li class=" wish-list-txt col-sm-4 col-md-4 col-lg-7 ">
<?php if($user_type == "Member") { ?>
<a data-pname="<?=$row['name']; ?>" class="add-to-wishlist" href="javascript:void(0);" name="dwfrm_cart_shipments_i0_items_i0_addToWishList" title="Move to Wishlist" onclick="move_to_wishlist('<?=$row['barcode']?>','<?=$row['cart_id']; ?>');" >
Add to Wishlist </a>
<?php } else { ?>
<a data-pname="<?=$row['name']; ?>" class="add-to-wishlist" title="Add to Wishlist" href="<?php echo base_url();?>wishlist/wishlist_login?source=productdetail">Add to Wishlist</a>
<?php } ?>
</li>
<li class="in-wishlist-wrapper" style="display: none;">
<div class="in-wishlist"></div>
</li>
</ul>
</div>
</div>
<div class="secondary-product-detail col-md-6 equal-width-five-sec">
<div class="product-details-template row" data-hbs-template="productiondetails">
<div class="item-quantity col-sm-6 col-md-4 equal-width-two">
<input type="hidden" id="barcode_qty" name="barcode_qty" value="<?=$row['barcode']; ?>">
<input type="hidden" id="cart_id_qty" name="cart_id_qty" value="<?=$row['cart_id']; ?>">
<h3 class="section-header">Quantity</h3>
<span class="decrease-quantity icons disabled " data-product-name="<?=$row['name']; ?>"></span>
<input type="text" name="dwfrm_cart_shipments_i0_items_i0_quantity" size="2" maxlength="2" value="<?= isset($row['qty']) ? $row['qty'] : 1; ?>" class="input-text" disabled="disabled">
<span class="increase-quantity icons " data-product-name="<?=$row['name']; ?>"></span>
</div>
<?php
$actual_discount = $row['discount_price'] / $row['qty'];
$price_sale = (!empty($row['price_sale']) && $row['price_sale'] != $row['unit_price'] && $row['price_sale'] != 0)? $row['price_sale'] : $row['unit_price'];
?>
<div class="item-price col-sm-6 col-md-4 equal-width-four">
<h3 class="section-header">Price</h3>
<p class="price-sales">$<?php
if($price_sale != $row['unit_price'] && !empty($price_sale) && $price_sale != 0){
echo "<span style='padding-right:3px; text-decoration: line-through; color:red;'><span style='color:grey'>".number_format($row['unit_price'], 2)."</span></span>".number_format($price_sale, 2);
}elseif($row['original_price'] != $row['unit_price'] && !empty($row['original_price']) && $row['original_price'] != 0){
echo "<span style='padding-right:3px; text-decoration: line-through; color:red;'><span style='color:grey'>".number_format($row['original_price'], 2)."</span></span>".number_format($row['unit_price'], 2);
}else{
echo number_format($row['unit_price'], 2);
}
?>
<br class="mobile-only"/>
<? if(!empty($row['discount_percent']) || $row['discount_percent'] != '0'):?> <span class="discount_percent" style="background: #e6e6e6;padding: 1px 4px;font-size: 10px;"><?php echo $row['discount_percent'];?>% OFF </span><? endif;?>
</p>
</div>
<div class="item-total col-sm-12 col-md-4 equal-width-four-sec">
<h3 class="section-header">Total Price</h3>
<p class="price-total">
<?php
if($row['discount_price'] < ($price_sale * $row['qty'])){
$total = $row['discount_price'];
} else {
$total = $row['qty'] * $price_sale;
}?>
$<?=number_format($total,2); ?>
</p>
</div>
<!-- Ecommerce tracking code -->
<?php if(ENVIRONMENT == 'production'){?>
<script type="text/javascript">
ga('ec:addProduct', {
'id': '<?php echo $row['sku'] ?>' ,
'name': '<?php echo $row['name'];?>',
'category': '<?php echo check_product_brand($row['category'],$row['gender']);?>',
'brand': '<?php echo $row['style'];?>',
'variant': '<?php echo $row['color'];?>',
'price': '<?php echo $total;?>',
'quantity': '<?php echo $row['qty'];?>'
});
ga('dieselitaly.ec:addProduct', {
'id': '<?php echo $row['sku'] ?>' ,
'name': '<?php echo $row['name'];?>',
'category': '<?php echo check_product_brand($row['category'],$row['gender']);?>',
'brand': '<?php echo $row['style'];?>',
'variant': '<?php echo $row['color'];?>',
'price': '<?php echo $total;?>',
'quantity': '<?php echo $row['qty'];?>'
});
ga('syg.ec:addProduct', {
'id': '<?php echo $row['sku'] ?>' ,
'name': '<?php echo $row['name'];?>',
'category': '<?php echo check_product_brand($row['category'],$row['gender']);?>',
'brand': '<?php echo $row['style'];?>',
'variant': '<?php echo $row['color'];?>',
'price': '<?php echo $total;?>',
'quantity': '<?php echo $row['qty'];?>'
});
</script>
<?}else{?>
<script type="text/javascript">
ga('ec:addProduct', {
'id': '<?php echo $row['sku'] ?>' ,
'name': '<?php echo $row['name'];?>',
'category': '<?php echo check_product_brand($row['category'],$row['gender']);?>',
'brand': '<?php echo $row['style'];?>',
'variant': '<?php echo $row['color'];?>',
'price': '<?php echo $total;?>',
'quantity': '<?php echo $row['qty'];?>'
});
</script>
<?php } ?>
<!-- Ecommerce tracking code-->
</div>
<ul class="product-availability-list"></ul>
</div>
</div>
<div class="item-seperator"></div>
<?php } ?>
<?php } ?>
<!--<textarea rows="50" cols="100"><? print_r($cart_data['cart_api']);?></textarea>-->
</div>
<!-- Ecommerce tracking code -->
<?php if(!empty($cart_data)): ?>
<?php if(ENVIRONMENT == 'production'){?>
<script type="text/javascript">
ga('ec:setAction','checkout', {
'step': 1, // A value of 1 indicates this action is first checkout step.
'option': 'Checkout' // Used to specify additional info about a checkout stage, e.g. payment method.
});
ga('dieselitaly.ec:setAction','checkout', {
'step': 1, // A value of 1 indicates this action is first checkout step.
'option': 'Checkout' // Used to specify additional info about a checkout stage, e.g. payment method.
});
ga('syg.ec:setAction','checkout', {
'step': 1, // A value of 1 indicates this action is first checkout step.
'option': 'Checkout' // Used to specify additional info about a checkout stage, e.g. payment method.
});
ga('send', 'pageview'); // Pageview for payment.html
ga('dieselitaly.send', 'pageview');
ga('syg.send', 'pageview');
</script>
<? }else{?>
<script type="text/javascript">
ga('ec:setAction','checkout', {
'step': 1, // A value of 1 indicates this action is first checkout step.
'option': 'Checkout' // Used to specify additional info about a checkout stage, e.g. payment method.
});
ga('send', 'pageview'); // Pageview for payment.html
</script>
<? }?>
<!--End of Ecommerce tracking code -->
<?php endif; ?>
</fieldset>
</form>
</div>
<div id="secondary" class="nav cart col-md-3" data-bonuseligibleorder="false">
<div class="cart-secondary">
<div class="order-totals-table">
<div style="display:none;">
<div class="content-asset">
<!-- dwMarker="content" dwContentID="bc8OsiaaiM5pEaaadqYUJ3Rq88" -->
<div id="cart-shipping-helptext">
The shipping cost will be a flat fee that is guaranteed based on the service level selected during checkout.
</div>
<div id="cart-tax-helptext">
Sales Tax is applied to your order in accordance with individual State and local regulations. Exact charges will be calculated automatically after your order is shipped, depending on the Zip Code of the shipping address.
</div>
</div>
<!-- End content-asset -->
</div>
<div class="order-subtotal">
<span class="label">
Order Subtotal </span>
<span class="value">$<?=isset($cart_data) ? number_format($cart_data['cart_total'],2) : '0.00'; ?></span>
</div>
<div class="order-shipping">
<span class="label">
<!-- Display Shipping Method -->
Shipping</span>
<span class="value">Free</span>
</div>
<div class="cart-secondary cart-coupon-code">
<label for="dwfrm_cart_couponCode" class="promotional-code-new">
Have a promotional code?</label>
<div class="cart-coupon" style="display:none;">
<input type="text" class="coupon-code" name="dwfrm_cart_couponCode" id="dwfrm_cart_couponCode" placeholder="Enter Coupon Code" onkeyup="checkVisibility()" >
<span class="error coupon-error"></span>
<div class="confirm-coupon"></div>
<div id="email_container" style="position:relative;display:none;">
<? if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){ ?>
<input type="text" class="coupon-code coupon-email" name="dwfrm_customer_email" id="dwfrm_customer_email" placeholder="Enter Your Email id"">
<? }else{
$user_email = $this->session->userdata('s_email');?>
<input type="text" class="coupon-code coupon-email" name="dwfrm_customer_email" id="dwfrm_customer_email" value="<?php echo $user_email;?>" readonly>
<? }?>
<span class="error email-error"></span>
<a class="tooltip">?
<div class="tooltip-content"><strong>Promotional Code</strong>
<p style="margin:10px 0">The promotion discount will only be applied to items that are not discounted already.</p>
<p>We require your email address to check if you are a member of the DIESEL TRIBE. If you're not, just click on login/register.</p>
</div>
</a>
</div>
<button type="submit" value="dwfrm_cart_addCoupon" name="dwfrm_cart_addCoupon" id="add-coupon" onclick="checkCodeStatus()">
Apply </button>
</div>
</div>
<div class="cart-secondary cart-coupon-code-show">
<div id="cartCouponRemove">
<span class="value" style="width: 53%;text-align: right;"></span>
<!--<form action="<?php echo site_url('cart/removecoupon'); ?>" method="post" name="dwfrm_cart_d0qpakcnxejy" id="ajaxremovecoupon" novalidate="novalidate">-->
<fieldset>
<label for="dwfrm_cart_couponCode">
Coupon code</label>
<?php if(!empty($coupon_code)){
$promo_code = $coupon_code['promo_code'];?>
<span class="value" style="width: 53%;text-align: right;"><? echo $coupon_code['promo_string'];?>
<a href="<?=base_url()?>cart/removecoupon/<?=$promo_code; ?>" class="remove_coupon" style="display: block;float: right;margin-left: 7px;">
<img src="<?=base_url()?>images/close-icon.png" width="24" height="24" id="remove_code_btn">
</a>
</span>
<?} ?>
<input type="hidden" name="cart_mast_id" value="<?=(!empty($coupon_code))? $coupon_code['cart_mast_id'] :''?>">
<input type="hidden" class="coupon-code" name="dwfrm_cart_couponCode" id="dwfrm_cart_couponCode" value="<?=(!empty($coupon_code))? $coupon_code['promo_code']:''?>">
<div class="confirm-coupon"></div>
</fieldset>
<!--</form>-->
</div>
</div>
<script type="text/javascript">
function checkVisibility() {
var pass1 = document.getElementById('dwfrm_cart_couponCode');
var pass2 = document.getElementById('dwfrm_customer_email');
if (pass1.value=='DLSIGNUP') {
$("#email_container").fadeIn();
//pass2.style.visibility = 'visible';
} else {
$("#email_container").fadeOut();
// pass2.style.visibility = 'hidden';
}
}
function checkCodeStatus(){
var promo_code = $(".cart-secondary .cart-coupon-code .coupon-code").val();
var email_id = $(".cart-secondary .cart-coupon-code .coupon-email").val();
var error=0;
if(promo_code == ''){
$('input[name="dwfrm_cart_couponCode"]').next('span').text('Please Enter the Promotion Code');
error=1;
}else {
if(promo_code == 'DLSIGNUP'){
if(email_id == ''){
$('input[name="dwfrm_customer_email"]').next('span').text('Please Enter a Email Id');
console.log('Email in if');
error=1;
}
}
}
if(error>0){
return false;
}else{
$.ajax(
{
url : "<?php echo base_url('cart/couponvalidate/'); ?>",
type : "POST",
data : {promo_code: promo_code,email_id:email_id} ,
cache : false,
dataType:'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success:function(data, textStatus, jqXHR)
{
//console.log('hi in success');return false;
if(data.result == 'success'){
console.log('hi in success success');
//$(".cart-secondary .cart-coupon-code-show").val(promo_code);
$('input[name=dwfrm_cart_couponCode]').val(promo_code);
$('.cart-secondary .cart-coupon-code-show span').html(promo_code);
//$(".remove_coupon").fadeIn();
$(".cart-coupon-code").fadeOut();
$(".cart-coupon-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
}else{
if(data.msg_type == 'promo_code'){
$(".coupon-error").html(data.msg);
}else{
$(".email-error").html(data.msg);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
//if fails
console.log(errorThrown);
}
});
}
}
//$(document).ready(function() {
$('.cart-coupon-code-show').hide();
var coupon_code = $("#cartCouponRemove #dwfrm_cart_couponCode").val();
if(coupon_code != ''){
$(".cart-coupon-code").fadeOut();
$(".cart-coupon-code-show").fadeIn();
}
// });
$(document).ready(function(){
$(".promotional-code-new").click(function(){
$(".cart-coupon").slideToggle();
});
});
</script>
<hr>
<div class="order-total">
<span class="label">Total(<span style="text-transform: lowercase;font-size:17px;">inc</span> GST)</span>
<span class="value">$<?=isset($cart_data) ? number_format($cart_data['cart_total'],2) : '0.00'; ?></span>
</div>
</div>
<div class="cart-action-checkout">
<?php if($user_type == "Member") { ?>
<form action="<?=base_url();?>order/checkout" method="post" name="dwfrm_cart_d0eqfxckhikc" novalidate="novalidate">
<fieldset>
<button class="btn-oswald red continue-checkout-button" type="submit" value="Proceed with checkout" name="dwfrm_cart_checkoutCart">
Proceed with checkout </button>
</fieldset>
</form>
<?php } else { ?>
<form class="mobile-only" action="<?=base_url();?>cart/checkout_signin" method="post" name="dwfrm_cart_d0eqfxckhikc" id="checkout-form" novalidate="novalidate">
<fieldset>
<button class="btn-oswald red continue-checkout-button" type="submit" value="Proceed with checkout" name="dwfrm_cart_checkoutCart" id="js-continue-checkout">
Proceed with checkout </button>
</fieldset>
</form>
<form class="no-mobile" action="<?=base_url();?>cart/proceed_checkout" method="post" name="dwfrm_cart_d0eqfxckhikc" id="checkout-form" novalidate="novalidate">
<fieldset>
<button class="btn-oswald red continue-checkout-button" type="submit" value="Proceed with checkout" name="dwfrm_cart_checkoutCart" id="js-continue-checkout">
Proceed with checkout </button>
</fieldset>
</form>
<?php } ?>
<form class="cart-action-continue-shopping" action="<?=base_url();?>" method="post" name="dwfrm_cart_d0ihllxcbhbi" id="continue-shopping" novalidate="novalidate">
<fieldset>
<button class="button-text" type="submit" value="Back to Shopping" name="dwfrm_cart_continueShopping" id="cart-continue-shoping">
Back to Shopping </button>
</fieldset>
</form>
</div>
</div>
<div class="appendPromo-message" style="display:none;"></div>
<div class="cart-secondary last-child hide"></div>
</div>
<?php } else { ?>
<div id="primary" class="primary-content pageName col-md-9" data-pagename="Cart">
<div class="cart-empty">
<h2 class="empty-bag-title">FEED ME I'M HUNGRY</h2>
<hr>
<div class="empty-header">
Your Shopping Bag is empty
</div>
<div class="cont-shopping">
<a href="<?=base_url();?>" class="continue button primary-button">
Back To Shopping </a>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<script type="text/javascript">
function move_to_wishlist(barcode,cart_id){
var url = '<?=base_url("Cart/move_product_to_wishlist");?>';
$.ajax({
type: "POST",
url: url,
async: false,
data: {barcode:barcode , cart_id:cart_id},
dataType: 'json',
success: function(result) {
/*console.log("hi"+result.res);
return false;*/
if(result){
if(result.res == 'success'){
$('#cart_box_'+cart_id).find('.in-wishlist').html('This item has been added to your Wish List.');
$('#cart_box_'+cart_id).find('.in-wishlist-wrapper').show();
$('.rgt-content .wishlist-header-count').find('span.favourite_count_red').html(result.count);
} else if(result.res == 'product_exist'){
$('#cart_box_'+cart_id).find('.in-wishlist').html('This item already in your Wish List.');
$('#cart_box_'+cart_id).find('.in-wishlist-wrapper').show();
} else {
$('#cart_box_'+cart_id).find('.in-wishlist-wrapper').hide();
}
}
},
error: function() {}
});
return false;
}
</script> | sygcom/diesel_2016 | application/views/cart_view_20161202.php | PHP | mit | 28,392 |
(function () {
'use strict';
describe('Inventories Controller Tests', function () {
// Initialize global variables
var InventoriesController,
$scope,
$httpBackend,
$state,
Authentication,
InventoriesService,
mockInventory;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _InventoriesService_) {
// Set a new global scope
$scope = $rootScope.$new();
// Point global variables to injected services
$httpBackend = _$httpBackend_;
$state = _$state_;
Authentication = _Authentication_;
InventoriesService = _InventoriesService_;
// create mock Inventory
mockInventory = new InventoriesService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Inventory Name'
});
// Mock logged in user
Authentication.user = {
roles: ['user']
};
// Initialize the Inventories controller.
InventoriesController = $controller('InventoriesController as vm', {
$scope: $scope,
inventoryResolve: {}
});
//Spy on state go
spyOn($state, 'go');
}));
describe('vm.save() as create', function () {
var sampleInventoryPostData;
beforeEach(function () {
// Create a sample Inventory object
sampleInventoryPostData = new InventoriesService({
name: 'Inventory Name'
});
$scope.vm.inventory = sampleInventoryPostData;
});
it('should send a POST request with the form input values and then locate to new object URL', inject(function (InventoriesService) {
// Set POST response
$httpBackend.expectPOST('api/inventories', sampleInventoryPostData).respond(mockInventory);
// Run controller functionality
$scope.vm.save(true);
$httpBackend.flush();
// Test URL redirection after the Inventory was created
expect($state.go).toHaveBeenCalledWith('inventories.view', {
inventoryId: mockInventory._id
});
}));
it('should set $scope.vm.error if error', function () {
var errorMessage = 'this is an error message';
$httpBackend.expectPOST('api/inventories', sampleInventoryPostData).respond(400, {
message: errorMessage
});
$scope.vm.save(true);
$httpBackend.flush();
expect($scope.vm.error).toBe(errorMessage);
});
});
describe('vm.save() as update', function () {
beforeEach(function () {
// Mock Inventory in $scope
$scope.vm.inventory = mockInventory;
});
it('should update a valid Inventory', inject(function (InventoriesService) {
// Set PUT response
$httpBackend.expectPUT(/api\/inventories\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
$scope.vm.save(true);
$httpBackend.flush();
// Test URL location to new object
expect($state.go).toHaveBeenCalledWith('inventories.view', {
inventoryId: mockInventory._id
});
}));
it('should set $scope.vm.error if error', inject(function (InventoriesService) {
var errorMessage = 'error';
$httpBackend.expectPUT(/api\/inventories\/([0-9a-fA-F]{24})$/).respond(400, {
message: errorMessage
});
$scope.vm.save(true);
$httpBackend.flush();
expect($scope.vm.error).toBe(errorMessage);
}));
});
describe('vm.remove()', function () {
beforeEach(function () {
//Setup Inventories
$scope.vm.inventory = mockInventory;
});
it('should delete the Inventory and redirect to Inventories', function () {
//Return true on confirm message
spyOn(window, 'confirm').and.returnValue(true);
$httpBackend.expectDELETE(/api\/inventories\/([0-9a-fA-F]{24})$/).respond(204);
$scope.vm.remove();
$httpBackend.flush();
expect($state.go).toHaveBeenCalledWith('inventories.list');
});
it('should should not delete the Inventory and not redirect', function () {
//Return false on confirm message
spyOn(window, 'confirm').and.returnValue(false);
$scope.vm.remove();
expect($state.go).not.toHaveBeenCalled();
});
});
});
})();
| ebonertz/mean-blog | modules/inventories/tests/client/inventories.client.controller.tests.js | JavaScript | mit | 5,483 |
import json
from sqlalchemy import create_engine, inspect, Table, Column
import pandas as pd
from ilxutils.args_reader import read_args
from ilxutils.scicrunch_client import scicrunch
import sys
import time
from ilxutils.interlex_sql import interlex_sql
import re
from collections import defaultdict
import requests as r
import subprocess as sb
from pathlib import Path as p
with open('/home/troy/elastic_migration/auth.ini', 'r') as uk:
vars = uk.read().split('\n')
username = vars[0].split('=')[-1].strip()
password = vars[1].split('=')[-1].strip()
args = read_args(
api_key=p.home() / 'keys/production_api_scicrunch_key.txt',
db_url=p.home() / 'keys/production_engine_scicrunch_key.txt',
production=True)
#args = read_args(api_key='../production_api_scicrunch_key.txt', db_url='../production_engine_scicrunch_key.txt', production=True)
sql = interlex_sql(db_url=args.db_url)
sci = scicrunch(
api_key=args.api_key, base_path=args.base_path, db_url=args.db_url)
def plink(ilxid):
return "http://interlex.scicrunch.io/scicrunch/term/%s" % ilxid
def blink(ilxid):
return "https://5f86098ac2b28a982cebf64e82db4ea2.us-west-2.aws.found.io:9243/interlex/term/%s" % ilxid
#8583532179
from random import choice
from string import ascii_uppercase
def get_random_words(lenghth=15, count=1):
return [
'troy_test_' + ''.join(choice(ascii_uppercase) for i in range(12))
for _ in range(count)
]
def create_ilx_format_from_words(words):
superclasses = [{
'id': '146',
}]
return [{
'term': w,
'type': 'term',
"definition": "test123",
"superclasses": superclasses
} for w in words]
words = get_random_words()
test_terms = create_ilx_format_from_words(words)
#print(test_terms)
#print(test_terms)
"""
ilx_data = sci.addTerms(test_terms)#, _print=True)
ilx_to_label = sql.get_ilx_to_label()
for d in ilx_data:
if not ilx_to_label[d['ilx']] == d['label']:
sys.exit(blink(d['ilx']))
terms_data = []
for d in ilx_data:
terms_data.append({'id':d['id'], 'definition':'update_test'})
update_data = sci.updateTerms(terms_data)#, _print=True)
for d in update_data:
if d['definition'] != 'update_test':
sys.exit(blink[d['ilx']])
"""
sci.updateTerms([{'id': 15065, 'definition': 'troy_test_may_17_2018'}])
def ela_search(ilx):
return r.get(blink(ilx), auth=(username, password))
ilx_data = [{'ilx': 'ilx_0115063'}]
results = [
ela_search(d['ilx']).json()
if not ela_search(d['ilx']).raise_for_status() else sys.exit(d)
for d in ilx_data
]
#print(results)
#json.dump(results, open('../elastic_testing.json', 'w'), indent=4)
#python3 elastic_test.py 8.60s user 1.07s system 3% cpu 4:55.25 total for new elastic
#annotation_format = {'tid':'', 'annotation_tid':'', 'value':''}
#annotation_format['tid']=49552
#annotation_format['annotation_tid']=15077
#annotation_format['value']='testing value2'
#sci.addAnnotations([annotation_format])
| tgbugs/pyontutils | ilxutils/tests/elastic_test.py | Python | mit | 2,991 |
version https://git-lfs.github.com/spec/v1
oid sha256:ff952c4ac029ba9d378d24581d9a56937e7dc731986397dc47c3c42c56fd0729
size 132398
| yogeshsaroya/new-cdnjs | ajax/libs/soundmanager2/2.97a.20120318/script/soundmanager2.js | JavaScript | mit | 131 |
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe PayloadProcessor do
describe "process!" do
context "with a payload containing 3 commits" do
before(:each) do
@project = Project.make
@content = {"commits"=>
[
{"author_email" => "developer_one@example.com",
"author_name" => "Developer One",
"committed_at" => "Wed May 20 09:09:06 -0500 2009",
"short_message" => "Last commit",
"authored_at" => "Wed May 20 09:09:06 -0500 2009",
"identifier" => "f3badd5624dfbc35176f0471261731e1b92ce957",
"message" => "Last commit\n- 2nd line of commit message",
"committer_email" => "developer_one@example.com",
"committer_name" => "Developer One",
"line_additions" => "15",
"line_deletions" => "25",
"line_total" => "34",
"affected_file_count" => "2"
},
{"author_email" => "developer_one@example.com",
"author_name" => "Developer One",
"committed_at" => "Wed May 13 22:40:46 -0500 2009",
"short_message" => "Second commit",
"authored_at" => "Wed May 13 22:40:46 -0500 2009",
"identifier" => "2debe9d1b2591d1face99fd49246fc952df38666",
"message" => "Second commit",
"committer_email" => "developer_one@example.com",
"committer_name" => "Developer One",
"line_additions" => "5",
"line_deletions" => "15",
"line_total" => "43",
"affected_file_count" => "3"
},
{"author_email" => "developer_one@example.com",
"author_name" => "Developer One",
"committed_at" => "Wed May 13 22:26:13 -0500 2009",
"short_message" => "Initial commit",
"authored_at" => "Wed May 13 22:26:13 -0500 2009",
"identifier" => "9aedb043a88b1e2e8c165a3791b9da4961d1dfa3",
"message" => "Initial commit",
"committer_email" => "developer_one@example.com",
"committer_name" => "Developer One",
"line_additions" => "25",
"line_deletions" => "5",
"line_total" => "33",
"affected_file_count" => "7"
}
]
}
end
context "when all commits are processed successfully" do
it "creates a new commit for each entry in the payload" do
lambda {
# Kicks off PayloadProcessor.process! in after_create hook
Payload.make(:project => @project, :content => @content)
}.should change(Commit, :count).by(3)
end
it "assigns the commits created to the same project the payload was associated with" do
lambda {
# Kicks off PayloadProcessor.process! in after_create hook
Payload.make(:project => @project, :content => @content)
}.should change(@project.commits, :count).by(3)
end
it "marks the 'outcome' as 'Successful'"
end
context "when all commits are not processed successfully" do
it "marks the 'outcome' as 'Unsuccessful'"
end
end
end
end
| tomkersten/codefumes-site | spec/models/payload_processor_spec.rb | Ruby | mit | 3,979 |
using ClosedXML.Excel;
using System;
namespace ClosedXML_Examples.Misc
{
public class RightToLeft : IXLExample
{
public void Create(String filePath)
{
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("RightToLeftSheet");
ws.Cell("A1").Value = "A1";
ws.Cell("B1").Value = "B1";
ws.Cell("C1").Value = "C1";
ws.RightToLeft = true;
wb.SaveAs(filePath);
}
}
}
| vbjay/ClosedXML | ClosedXML_Examples/Misc/RightToLeft.cs | C# | mit | 486 |
/*
* Copyright (c) 2009 Roy Wellington IV
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "json.h"
json::Array::Array(const json::Array &a) : Value(TYPE_ARRAY)
{
try
{
for(std::vector<Value *>::const_iterator i = a.m_values.begin();
i != a.m_values.end();
++i)
{
Value *v = NULL;
try
{
v = (*i)->clone();
m_values.push_back(v);
}
catch(...)
{
delete v;
throw;
}
}
}
catch(...)
{
for(std::vector<Value *>::const_iterator i = m_values.begin();
i != m_values.end();
++i)
{
delete *i;
}
throw;
}
}
json::Array::~Array()
{
for(std::vector<Value *>::iterator i = m_values.begin();
i != m_values.end();
++i)
{
delete *i;
}
}
void json::Array::swap(json::Array &a)
{
m_values.swap(a.m_values);
}
json::Array &json::Array::operator = (const json::Array &a)
{
if(this == &a)
return *this;
json::Array temp(a);
swap(temp);
return *this;
}
void json::Array::pushBack(const json::Value *v)
{
Value *c = NULL;
try
{
c = v->clone();
m_values.push_back(c);
}
catch(...)
{
delete c;
throw;
}
}
| thanatos/libjson | src/array.cpp | C++ | mit | 2,141 |
import { JKFPlayer } from "json-kifu-format";
import { observer } from "mobx-react";
import * as React from "react";
import Piece from "./Piece";
import KifuStore from "./stores/KifuStore";
export interface IProps {
kifuStore: KifuStore;
}
@observer
export default class Board extends React.Component<IProps, any> {
public render() {
const { reversed, player } = this.props.kifuStore;
const board = player.getState().board;
const lastMove = player.getMove();
const nineY = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const nineX = nineY.slice().reverse();
const ths = nineX.map((logicalX) => {
const x = reversed ? 10 - logicalX : logicalX;
return <th key={x}>{x}</th>;
});
const trs = nineY.map((logicalY) => {
const y = reversed ? 10 - logicalY : logicalY;
const pieces = nineX.map((logicalX) => {
const x = reversed ? 10 - logicalX : logicalX;
return (
<Piece
key={x}
data={board[x - 1][y - 1]}
x={x}
y={y}
lastMove={lastMove}
kifuStore={this.props.kifuStore}
/>
);
});
return (
<tr key={y}>
{pieces}
<th>{JKFPlayer.numToKan(y)}</th>
</tr>
);
});
return (
<table className="kifuforjs-board">
<tbody>
<tr>{ths}</tr>
{trs}
</tbody>
</table>
);
}
}
| na2hiro/Kifu-for-JS | src/Board.tsx | TypeScript | mit | 1,723 |
import java.util.*;
public class WeightedGraph<T> implements WeightedGraphInterface<T>
{
public static final int NULL_EDGE = 0;
private static final int DEFCAP = 50; // default capacity
private int numVertices;
private int maxVertices;
private T[] vertices;
private int[][] edges;
private boolean[] marks; // marks[i] is mark for vertices[i]
public WeightedGraph()
// Instantiates a graph with capacity DEFCAP vertices.
{
numVertices = 0;
maxVertices = DEFCAP;
vertices = (T[]) new Object[DEFCAP];
marks = new boolean[DEFCAP];
edges = new int[DEFCAP][DEFCAP];
}
public WeightedGraph(int maxV)
// Instantiates a graph with capacity maxV.
{
numVertices = 0;
maxVertices = maxV;
vertices = (T[]) new Object[maxV];
marks = new boolean[maxV];
edges = new int[maxV][maxV];
}
public boolean isEmpty()
{
if(numVertices == 0)
return true;
return false;
}
public boolean isFull()
{
if(numVertices == maxVertices)
return true;
return false;
}
public void addVertex(T vertex)
// Preconditions: This graph is not full.
// Vertex is not already in this graph.
// Vertex is not null.
//
// Adds vertex to this graph.
{
vertices[numVertices] = vertex;
for (int index = 0; index < numVertices; index++)
{
edges[numVertices][index] = NULL_EDGE;
edges[index][numVertices] = NULL_EDGE;
}
numVertices++;
}
private int indexIs(T vertex)
// Returns the index of vertex in vertices.
{
int index = 0;
while (!vertex.equals(vertices[index]))
index++;
return index;
}
public void addEdge(T fromVertex, T toVertex, int weight)
// Adds an edge with the specified weight from fromVertex to toVertex.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
edges[row][column] = weight;
}
public int weightIs(T fromVertex, T toVertex)
// If edge from fromVertex to toVertex exists, returns the weight of edge;
// otherwise, returns a special "null-edge" value.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
return edges[row][column];
}
public Queue<T> getToVertices(T vertex)
// Returns a queue of the vertices that are adjacent from vertex.
{
Queue<T> adjVertices = new LinkedList<>();
int fromIndex;
int toIndex;
fromIndex = indexIs(vertex);
for (toIndex = 0; toIndex < numVertices; toIndex++)
if (edges[fromIndex][toIndex] != NULL_EDGE)
adjVertices.add(vertices[toIndex]);
return adjVertices;
}
public void markVertex(T vertex)
// Sets mark for vertex to true.
{
int index;
index = indexIs(vertex);
marks[index] = true;
}
public boolean isMarked(T vertex) {
int index;
index = indexIs(vertex);
return (marks[index]);
}
public void clearMarks() {
for (int i = 0; i < this.numVertices; i++) {
marks[i] = false;
}
}
public static boolean isPath(WeightedGraph<String> graph, String startVertex, String endVertex) {
Deque<String> stack = new ArrayDeque<String>();
Queue<String> vertexQueue = new LinkedList<String>();
boolean found = false;
String vertex;
String item;
graph.clearMarks();
stack.push(startVertex);
do {
vertex = stack.peek();
stack.pop();
if (vertex == endVertex)
found = true;
else {
if (!graph.isMarked(vertex)) {
graph.markVertex(vertex);
vertexQueue = graph.getToVertices(vertex);
while (!vertexQueue.isEmpty()) {
item = vertexQueue.poll();
if (!graph.isMarked(item))
stack.push(item);
}
}
}
} while (!stack.isEmpty() && !found);
return found;
}
public static void shortestPaths(WeightedGraph<String> graph, String startVertex){
Flight flight;
Flight saveFlight; // for saving on priority queue
int minDistance;
int newDistance;
PriorityQueue<Flight> pq = new PriorityQueue<Flight>(20); // Assume at most 20 vertices
String vertex;
Queue<String> vertexQueue = new LinkedList<>();
graph.clearMarks();
saveFlight = new Flight(startVertex, startVertex, 0);
pq.add(saveFlight);
System.out.println("Last Vertex Destination Distance");
System.out.println("------------------------------------");
do {
flight = pq.remove();
if (!graph.isMarked(flight.getToVertex())) {
graph.markVertex(flight.getToVertex());
System.out.println(flight);
flight.setFromVertex(flight.getToVertex());
minDistance = flight.getDistance();
vertexQueue = graph.getToVertices(flight.getFromVertex());
while (!vertexQueue.isEmpty()) {
vertex = vertexQueue.poll();
if (!graph.isMarked(vertex)) {
newDistance = minDistance
+ graph.weightIs(flight.getFromVertex(), vertex);
saveFlight = new Flight(flight.getFromVertex(), vertex, newDistance);
pq.add(saveFlight);
}
}
}
} while (!pq.isEmpty());
}
}
| Josecc/CSC202 | 5-assignment/Graph/WeightedGraph.java | Java | mit | 5,724 |
// Copyright (c) 2014-2019 Daniel Kraft
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <names/main.h>
#include <chainparams.h>
#include <coins.h>
#include <consensus/validation.h>
#include <dbwrapper.h>
#include <hash.h>
#include <names/encoding.h>
#include <script/interpreter.h>
#include <script/names.h>
#include <txmempool.h>
#include <uint256.h>
#include <undo.h>
#include <util/system.h>
#include <util/strencodings.h>
#include <validation.h>
#include <string>
#include <vector>
namespace
{
/**
* Check whether a name at nPrevHeight is expired at nHeight. Also
* heights of MEMPOOL_HEIGHT are supported. For nHeight == MEMPOOL_HEIGHT,
* we check at the current best tip's height.
* @param nPrevHeight The name's output.
* @param nHeight The height at which it should be updated.
* @return True iff the name is expired.
*/
bool
isExpired (unsigned nPrevHeight, unsigned nHeight)
{
assert (nHeight != MEMPOOL_HEIGHT);
if (nPrevHeight == MEMPOOL_HEIGHT)
return false;
const Consensus::Params& params = Params ().GetConsensus ();
return nPrevHeight + params.rules->NameExpirationDepth (nHeight) <= nHeight;
}
} // anonymous namespace
/* ************************************************************************** */
/* CNameData. */
bool
CNameData::isExpired () const
{
return isExpired (::ChainActive ().Height ());
}
bool
CNameData::isExpired (unsigned h) const
{
return ::isExpired (nHeight, h);
}
/* ************************************************************************** */
/* CNameTxUndo. */
void
CNameTxUndo::fromOldState (const valtype& nm, const CCoinsView& view)
{
name = nm;
isNew = !view.GetName (name, oldData);
}
void
CNameTxUndo::apply (CCoinsViewCache& view) const
{
if (isNew)
view.DeleteName (name);
else
view.SetName (name, oldData, true);
}
/* ************************************************************************** */
bool
CheckNameTransaction (const CTransaction& tx, unsigned nHeight,
const CCoinsView& view,
TxValidationState& state, unsigned flags)
{
const bool fMempool = (flags & SCRIPT_VERIFY_NAMES_MEMPOOL);
/* Ignore historic bugs. */
CChainParams::BugType type;
if (Params ().IsHistoricBug (tx.GetHash (), nHeight, type))
return true;
/* As a first step, try to locate inputs and outputs of the transaction
that are name scripts. At most one input and output should be
a name operation. */
int nameIn = -1;
CNameScript nameOpIn;
Coin coinIn;
for (unsigned i = 0; i < tx.vin.size (); ++i)
{
const COutPoint& prevout = tx.vin[i].prevout;
Coin coin;
if (!view.GetCoin (prevout, coin))
return state.Invalid (TxValidationResult::TX_MISSING_INPUTS,
"bad-txns-inputs-missingorspent",
"Failed to fetch name input coin");
const CNameScript op(coin.out.scriptPubKey);
if (op.isNameOp ())
{
if (nameIn != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-multiple-name-inputs",
"Multiple name inputs");
nameIn = i;
nameOpIn = op;
coinIn = coin;
}
}
int nameOut = -1;
CNameScript nameOpOut;
for (unsigned i = 0; i < tx.vout.size (); ++i)
{
const CNameScript op(tx.vout[i].scriptPubKey);
if (op.isNameOp ())
{
if (nameOut != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-multiple-name-outputs",
"Multiple name outputs");
nameOut = i;
nameOpOut = op;
}
}
/* Check that no name inputs/outputs are present for a non-Namecoin tx.
If that's the case, all is fine. For a Namecoin tx instead, there
should be at least an output (for NAME_NEW, no inputs are expected). */
if (!tx.IsNamecoin ())
{
if (nameIn != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nonname-with-name-input",
"Non-name transaction has name input");
if (nameOut != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nonname-with-name-output",
"Non-name transaction has name output");
return true;
}
assert (tx.IsNamecoin ());
if (nameOut == -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-name-without-name-output",
"Name transaction has no name output");
/* Reject "greedy names". */
const Consensus::Params& params = Params ().GetConsensus ();
if (tx.vout[nameOut].nValue < params.rules->MinNameCoinAmount(nHeight))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-name-greedy",
"Greedy name operation");
/* Handle NAME_NEW now, since this is easy and different from the other
operations. */
if (nameOpOut.getNameOp () == OP_NAME_NEW)
{
if (nameIn != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-namenew-with-name-input",
"NAME_NEW with previous name input");
if (nameOpOut.getOpHash ().size () != 20)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-namenew-wrong-size",
"NAME_NEW's hash has the wrong size");
return true;
}
/* Now that we have ruled out NAME_NEW, check that we have a previous
name input that is being updated. */
assert (nameOpOut.isAnyUpdate ());
if (nameIn == -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-without-name-input",
"Name update has no previous name input");
const valtype& name = nameOpOut.getOpName ();
if (name.size () > MAX_NAME_LENGTH)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-name-invalid",
"Invalid name");
if (nameOpOut.getOpValue ().size () > MAX_VALUE_LENGTH)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-value-invalid",
"Invalid value");
/* Process NAME_UPDATE next. */
if (nameOpOut.getNameOp () == OP_NAME_UPDATE)
{
if (!nameOpIn.isAnyUpdate ())
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-invalid-prev",
"Name input for NAME_UPDATE is not an update");
if (name != nameOpIn.getOpName ())
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-name-mismatch",
"NAME_UPDATE name mismatch to name input");
/* If the name input is pending, then no further checks with respect
to the name input in the name database are done. Otherwise, we verify
that the name input matches the name database; this is redundant
as UTXO handling takes care of it anyway, but we do it for
an extra safety layer. */
const unsigned inHeight = coinIn.nHeight;
if (inHeight == MEMPOOL_HEIGHT)
return true;
CNameData oldName;
if (!view.GetName (name, oldName))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-nonexistant",
"NAME_UPDATE name does not exist");
if (oldName.isExpired (nHeight))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-expired",
"NAME_UPDATE on an expired name");
assert (inHeight == oldName.getHeight ());
assert (tx.vin[nameIn].prevout == oldName.getUpdateOutpoint ());
return true;
}
/* Finally, NAME_FIRSTUPDATE. */
assert (nameOpOut.getNameOp () == OP_NAME_FIRSTUPDATE);
if (nameOpIn.getNameOp () != OP_NAME_NEW)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-firstupdate-nonnew-input",
"NAME_FIRSTUPDATE input is not a NAME_NEW");
/* Maturity of NAME_NEW is checked only if we're not adding
to the mempool. */
if (!fMempool)
{
assert (static_cast<unsigned> (coinIn.nHeight) != MEMPOOL_HEIGHT);
if (coinIn.nHeight + MIN_FIRSTUPDATE_DEPTH > nHeight)
return state.Invalid (TxValidationResult::TX_PREMATURE_SPEND,
"tx-firstupdate-immature",
"NAME_FIRSTUPDATE on immature NAME_NEW");
}
if (nameOpOut.getOpRand ().size () > 20)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-firstupdate-invalid-rand",
"NAME_FIRSTUPDATE rand value is too large");
{
valtype toHash(nameOpOut.getOpRand ());
toHash.insert (toHash.end (), name.begin (), name.end ());
const uint160 hash = Hash160 (toHash);
if (hash != uint160 (nameOpIn.getOpHash ()))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-firstupdate-hash-mismatch",
"NAME_FIRSTUPDATE mismatch in hash / rand value");
}
CNameData oldName;
if (view.GetName (name, oldName) && !oldName.isExpired (nHeight))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-firstupdate-existing-name",
"NAME_FIRSTUPDATE on existing name");
/* We don't have to specifically check that miners don't create blocks with
conflicting NAME_FIRSTUPDATE's, since the mining's CCoinsViewCache
takes care of this with the check above already. */
return true;
}
void
ApplyNameTransaction (const CTransaction& tx, unsigned nHeight,
CCoinsViewCache& view, CBlockUndo& undo)
{
assert (nHeight != MEMPOOL_HEIGHT);
/* Handle historic bugs that should *not* be applied. Names that are
outputs should be marked as unspendable in this case. Otherwise,
we get an inconsistency between the UTXO set and the name database. */
CChainParams::BugType type;
const uint256 txHash = tx.GetHash ();
if (Params ().IsHistoricBug (txHash, nHeight, type)
&& type != CChainParams::BUG_FULLY_APPLY)
{
if (type == CChainParams::BUG_FULLY_IGNORE)
for (unsigned i = 0; i < tx.vout.size (); ++i)
{
const CNameScript op(tx.vout[i].scriptPubKey);
if (op.isNameOp () && op.isAnyUpdate ())
view.SpendCoin (COutPoint (txHash, i));
}
return;
}
/* This check must be done *after* the historic bug fixing above! Some
of the names that must be handled above are actually produced by
transactions *not* marked as Namecoin tx. */
if (!tx.IsNamecoin ())
return;
/* Changes are encoded in the outputs. We don't have to do any checks,
so simply apply all these. */
for (unsigned i = 0; i < tx.vout.size (); ++i)
{
const CNameScript op(tx.vout[i].scriptPubKey);
if (op.isNameOp () && op.isAnyUpdate ())
{
const valtype& name = op.getOpName ();
LogPrint (BCLog::NAMES, "Updating name at height %d: %s\n",
nHeight, EncodeNameForMessage (name));
CNameTxUndo opUndo;
opUndo.fromOldState (name, view);
undo.vnameundo.push_back (opUndo);
CNameData data;
data.fromScript (nHeight, COutPoint (tx.GetHash (), i), op);
view.SetName (name, data, false);
}
}
}
bool
ExpireNames (unsigned nHeight, CCoinsViewCache& view, CBlockUndo& undo,
std::set<valtype>& names)
{
names.clear ();
/* The genesis block contains no name expirations. */
if (nHeight == 0)
return true;
/* Otherwise, find out at which update heights names have expired
since the last block. If the expiration depth changes, this could
be multiple heights at once. */
const Consensus::Params& params = Params ().GetConsensus ();
const unsigned expDepthOld = params.rules->NameExpirationDepth (nHeight - 1);
const unsigned expDepthNow = params.rules->NameExpirationDepth (nHeight);
if (expDepthNow > nHeight)
return true;
/* Both are inclusive! The last expireTo was nHeight - 1 - expDepthOld,
now we start at this value + 1. */
const unsigned expireFrom = nHeight - expDepthOld;
const unsigned expireTo = nHeight - expDepthNow;
/* It is possible that expireFrom = expireTo + 1, in case that the
expiration period is raised together with the block height. In this
case, no names expire in the current step. This case means that
the absolute expiration height "n - expirationDepth(n)" is
flat -- which is fine. */
assert (expireFrom <= expireTo + 1);
/* Find all names that expire at those depths. Note that GetNamesForHeight
clears the output set, to we union all sets here. */
for (unsigned h = expireFrom; h <= expireTo; ++h)
{
std::set<valtype> newNames;
view.GetNamesForHeight (h, newNames);
names.insert (newNames.begin (), newNames.end ());
}
/* Expire all those names. */
for (std::set<valtype>::const_iterator i = names.begin ();
i != names.end (); ++i)
{
const std::string nameStr = EncodeNameForMessage (*i);
CNameData data;
if (!view.GetName (*i, data))
return error ("%s : name %s not found in the database",
__func__, nameStr);
if (!data.isExpired (nHeight))
return error ("%s : name %s is not actually expired",
__func__, nameStr);
/* Special rule: When d/postmortem expires (the name used by
libcoin in the name-stealing demonstration), it's coin
is already spent. Ignore. */
if (nHeight == 175868
&& EncodeName (*i, NameEncoding::ASCII) == "d/postmortem")
continue;
const COutPoint& out = data.getUpdateOutpoint ();
Coin coin;
if (!view.GetCoin(out, coin))
return error ("%s : name coin for %s is not available",
__func__, nameStr);
const CNameScript nameOp(coin.out.scriptPubKey);
if (!nameOp.isNameOp () || !nameOp.isAnyUpdate ()
|| nameOp.getOpName () != *i)
return error ("%s : name coin to be expired is wrong script", __func__);
if (!view.SpendCoin (out, &coin))
return error ("%s : spending name coin failed", __func__);
undo.vexpired.push_back (coin);
}
return true;
}
bool
UnexpireNames (unsigned nHeight, CBlockUndo& undo, CCoinsViewCache& view,
std::set<valtype>& names)
{
names.clear ();
/* The genesis block contains no name expirations. */
if (nHeight == 0)
return true;
std::vector<Coin>::reverse_iterator i;
for (i = undo.vexpired.rbegin (); i != undo.vexpired.rend (); ++i)
{
const CNameScript nameOp(i->out.scriptPubKey);
if (!nameOp.isNameOp () || !nameOp.isAnyUpdate ())
return error ("%s : wrong script to be unexpired", __func__);
const valtype& name = nameOp.getOpName ();
if (names.count (name) > 0)
return error ("%s : name %s unexpired twice",
__func__, EncodeNameForMessage (name));
names.insert (name);
CNameData data;
if (!view.GetName (nameOp.getOpName (), data))
return error ("%s : no data for name '%s' to be unexpired",
__func__, EncodeNameForMessage (name));
if (!data.isExpired (nHeight) || data.isExpired (nHeight - 1))
return error ("%s : name '%s' to be unexpired is not expired in the DB"
" or it was already expired before the current height",
__func__, EncodeNameForMessage (name));
if (ApplyTxInUndo (std::move(*i), view,
data.getUpdateOutpoint ()) != DISCONNECT_OK)
return error ("%s : failed to undo name coin spending", __func__);
}
return true;
}
void
CheckNameDB (bool disconnect)
{
const int option
= gArgs.GetArg ("-checknamedb", Params ().DefaultCheckNameDB ());
if (option == -1)
return;
assert (option >= 0);
if (option != 0)
{
if (disconnect || ::ChainActive ().Height () % option != 0)
return;
}
auto& coinsTip = ::ChainstateActive ().CoinsTip ();
coinsTip.Flush ();
const bool ok = coinsTip.ValidateNameDB ();
/* The DB is inconsistent (mismatch between UTXO set and names DB) between
(roughly) blocks 139,000 and 180,000. This is caused by libcoin's
"name stealing" bug. For instance, d/postmortem is removed from
the UTXO set shortly after registration (when it is used to steal
names), but it remains in the name DB until it expires. */
if (!ok)
{
const unsigned nHeight = ::ChainActive ().Height ();
LogPrintf ("ERROR: %s : name database is inconsistent\n", __func__);
if (nHeight >= 139000 && nHeight <= 180000)
LogPrintf ("This is expected due to 'name stealing'.\n");
else
assert (false);
}
}
| namecoin/namecore | src/names/main.cpp | C++ | mit | 17,522 |
/**
*/
package geometry.impl;
import geometry.GeometryPackage;
import geometry.Point;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Point</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link geometry.impl.PointImpl#getXLocation <em>XLocation</em>}</li>
* <li>{@link geometry.impl.PointImpl#getYLocation <em>YLocation</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class PointImpl extends GObjectImpl implements Point {
/**
* The default value of the '{@link #getXLocation() <em>XLocation</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getXLocation()
* @generated
* @ordered
*/
protected static final int XLOCATION_EDEFAULT = 0;
/**
* The cached value of the '{@link #getXLocation() <em>XLocation</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getXLocation()
* @generated
* @ordered
*/
protected int xLocation = XLOCATION_EDEFAULT;
/**
* The default value of the '{@link #getYLocation() <em>YLocation</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getYLocation()
* @generated
* @ordered
*/
protected static final int YLOCATION_EDEFAULT = 0;
/**
* The cached value of the '{@link #getYLocation() <em>YLocation</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getYLocation()
* @generated
* @ordered
*/
protected int yLocation = YLOCATION_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PointImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return GeometryPackage.Literals.POINT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getXLocation() {
return xLocation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setXLocation(int newXLocation) {
int oldXLocation = xLocation;
xLocation = newXLocation;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GeometryPackage.POINT__XLOCATION, oldXLocation, xLocation));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getYLocation() {
return yLocation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setYLocation(int newYLocation) {
int oldYLocation = yLocation;
yLocation = newYLocation;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GeometryPackage.POINT__YLOCATION, oldYLocation, yLocation));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case GeometryPackage.POINT__XLOCATION:
return getXLocation();
case GeometryPackage.POINT__YLOCATION:
return getYLocation();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case GeometryPackage.POINT__XLOCATION:
setXLocation((Integer)newValue);
return;
case GeometryPackage.POINT__YLOCATION:
setYLocation((Integer)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case GeometryPackage.POINT__XLOCATION:
setXLocation(XLOCATION_EDEFAULT);
return;
case GeometryPackage.POINT__YLOCATION:
setYLocation(YLOCATION_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case GeometryPackage.POINT__XLOCATION:
return xLocation != XLOCATION_EDEFAULT;
case GeometryPackage.POINT__YLOCATION:
return yLocation != YLOCATION_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (xLocation: ");
result.append(xLocation);
result.append(", yLocation: ");
result.append(yLocation);
result.append(')');
return result.toString();
}
} //PointImpl
| albertfdp/petrinet | src/dk.dtu.se2.geometry/src/geometry/impl/PointImpl.java | Java | mit | 5,044 |
'use strict';
angular.module('eklabs.angularStarterPack.offer')
.directive('removeOffer',function($log, $location, Offers){
return {
templateUrl : 'eklabs.angularStarterPack/modules/offers/views/MyRemoveOfferView.html',
scope : {
offer : '=?',
callback : '=?',
listOffer : '='
},link : function(scope, attr, $http) {
// Initialisation du constructeur
var offersCreation = new Offers();
// Supprimer une offre de stage
scope.deleteOffer = function(idOfferToDelete) {
offersCreation.deleteOffer(idOfferToDelete).then(idOfferToDelete);
alert("L\'annonce a bien été supprimer. Vous allez être redirigé sur la page d'accueil. ");
};
}
}
})
| julienbnr/InternMe | src/modules/offers/directives/my-offer/MyRemoveOfferDirective.js | JavaScript | mit | 883 |