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 |
|---|---|---|---|---|---|
Pony.options = {
via: :smtp,
from: 'HUD Notifier <no-reply@hud-notifier.herokuapp.com>',
via_options: {
address: 'smtp.sendgrid.net',
port: '587',
domain: 'heroku.com',
user_name: ENV['SENDGRID_USERNAME'],
password: ENV['SENDGRID_PASSWORD'],
authentication: :plain,
enable_starttls_auto: true
}
}
| ancorcruz/hud_notifier | lib/hud_notifier/mailer_config.rb | Ruby | mit | 333 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2020, Hamdi Douss
*
* 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.aljebra.scalar.mock;
import com.aljebra.field.Field;
import com.aljebra.scalar.Scalar;
import java.util.Optional;
/**
* Scalar decorator with spying capabilities on the value method calls.
* It holds the last {@link Field} passed when calling value method as an optional. The optional
* is empty if the method was never called.
* @param <T> scalar types
* @since 0.3
*/
public final class SpyScalar<T> implements Scalar<T> {
/**
* An optional holding the last field passed as parameter when calling value method.
* The optional is empty if the method was never called.
*/
private Optional<Field<T>> fld;
/**
* Decorated scalar.
*/
private final Scalar<T> org;
/**
* Ctor.
* @param origin The scalar to decorate.
*/
public SpyScalar(final Scalar<T> origin) {
this.org = origin;
this.fld = Optional.empty();
}
@Override
public T value(final Field<T> field) {
this.fld = Optional.of(field);
return this.org.value(field);
}
/**
* Accessor for the last field passed when calling value method.
* @return Optional containing the field passed when last called value method.
* If the optional is empty, that means the method was never called.
*/
public Optional<Field<T>> field() {
return this.fld;
}
}
| HDouss/jeometry | aljebra/src/test/java/com/aljebra/scalar/mock/SpyScalar.java | Java | mit | 2,523 |
package jeliot.mcode;
/**
* Currently this class is not used in Jeliot 3.
*
* @author Niko Myller
*/
public class Command {
// DOC: document!
/**
*
*/
private int expressionReference = 0;
/**
*
*/
private int type = 0;
/**
*
*/
protected Command() { }
/**
* @param t
* @param er
*/
public Command(int t, int er) {
this.type = t;
this.expressionReference = er;
}
/**
* @param er
*/
public void setExpressionReference(int er) {
this.expressionReference = er;
}
/**
* @param t
*/
public void setType(int t) {
this.type = t;
}
/**
* @return
*/
public int getExpressionReference() {
return this.expressionReference;
}
/**
* @return
*/
public int getType() {
return this.type;
}
} | moegyver/mJeliot | Jeliot/src/jeliot/mcode/Command.java | Java | mit | 899 |
/*
* Copyright 2007 ZXing authors
*
* 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.
*/
package com.google.zxing.common.reedsolomon;
/**
* <p>Implements Reed-Solomon decoding, as the name implies.</p>
* <p/>
* <p>The algorithm will not be explained here, but the following references were helpful
* in creating this implementation:</p>
* <p/>
* <ul>
* <li>Bruce Maggs.
* <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
* "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
* <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
* "Chapter 5. Generalized Reed-Solomon Codes"</a>
* (see discussion of Euclidean algorithm)</li>
* </ul>
* <p/>
* <p>Much credit is due to William Rucklidge since portions of this code are an indirect
* port of his C++ Reed-Solomon implementation.</p>
*
* @author Sean Owen
* @author William Rucklidge
* @author sanfordsquires
*/
public final class ReedSolomonDecoder {
private final GenericGF field;
public ReedSolomonDecoder(GenericGF field) {
this.field = field;
}
/**
* <p>Decodes given set of received codewords, which include both data and error-correction
* codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
* in the input.</p>
*
* @param received data and error-correction codewords
* @param twoS number of error-correction codewords available
* @throws ReedSolomonException if decoding fails for any reason
*/
public void decode(int[] received, int twoS) throws ReedSolomonException {
GenericGFPoly poly = new GenericGFPoly(field, received);
int[] syndromeCoefficients = new int[twoS];
boolean noError = true;
for (int i = 0; i < twoS; i++) {
int eval = poly.evaluateAt(field.exp(i + field.getGeneratorBase()));
syndromeCoefficients[syndromeCoefficients.length - 1 - i] = eval;
if (eval != 0) {
noError = false;
}
}
if (noError) {
return;
}
GenericGFPoly syndrome = new GenericGFPoly(field, syndromeCoefficients);
GenericGFPoly[] sigmaOmega =
runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
GenericGFPoly sigma = sigmaOmega[0];
GenericGFPoly omega = sigmaOmega[1];
int[] errorLocations = findErrorLocations(sigma);
int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations);
for (int i = 0; i < errorLocations.length; i++) {
int position = received.length - 1 - field.log(errorLocations[i]);
if (position < 0) {
throw new ReedSolomonException("Bad error location");
}
received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);
}
}
public GenericGFPoly[] runEuclideanAlgorithm(GenericGFPoly a, GenericGFPoly b, int R)
throws ReedSolomonException {
// Assume a's degree is >= b's
if (a.getDegree() < b.getDegree()) {
GenericGFPoly temp = a;
a = b;
b = temp;
}
GenericGFPoly rLast = a;
GenericGFPoly r = b;
GenericGFPoly tLast = field.getZero();
GenericGFPoly t = field.getOne();
// Run Euclidean algorithm until r's degree is less than R/2
while (r.getDegree() >= R / 2) {
GenericGFPoly rLastLast = rLast;
GenericGFPoly tLastLast = tLast;
rLast = r;
tLast = t;
// Divide rLastLast by rLast, with quotient in q and remainder in r
if (rLast.isZero()) {
// Oops, Euclidean algorithm already terminated?
throw new ReedSolomonException("r_{i-1} was zero");
}
r = rLastLast;
GenericGFPoly q = field.getZero();
int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
int dltInverse = field.inverse(denominatorLeadingTerm);
while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
int degreeDiff = r.getDegree() - rLast.getDegree();
int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
}
t = q.multiply(tLast).addOrSubtract(tLastLast);
if (r.getDegree() >= rLast.getDegree()) {
throw new IllegalStateException("Division algorithm failed to reduce polynomial?");
}
}
int sigmaTildeAtZero = t.getCoefficient(0);
if (sigmaTildeAtZero == 0) {
throw new ReedSolomonException("sigmaTilde(0) was zero");
}
int inverse = field.inverse(sigmaTildeAtZero);
GenericGFPoly sigma = t.multiply(inverse);
GenericGFPoly omega = r.multiply(inverse);
return new GenericGFPoly[]{sigma, omega};
}
private int[] findErrorLocations(GenericGFPoly errorLocator) throws ReedSolomonException {
// This is a direct application of Chien's search
int numErrors = errorLocator.getDegree();
if (numErrors == 1) { // shortcut
return new int[]{errorLocator.getCoefficient(1)};
}
int[] result = new int[numErrors];
int e = 0;
for (int i = 1; i < field.getSize() && e < numErrors; i++) {
if (errorLocator.evaluateAt(i) == 0) {
result[e] = field.inverse(i);
e++;
}
}
if (e != numErrors) {
throw new ReedSolomonException("Error locator degree does not match number of roots");
}
return result;
}
private int[] findErrorMagnitudes(GenericGFPoly errorEvaluator, int[] errorLocations) {
// This is directly applying Forney's Formula
int s = errorLocations.length;
int[] result = new int[s];
for (int i = 0; i < s; i++) {
int xiInverse = field.inverse(errorLocations[i]);
int denominator = 1;
for (int j = 0; j < s; j++) {
if (i != j) {
//denominator = field.multiply(denominator,
// GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
// Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
// Below is a funny-looking workaround from Steven Parkes
int term = field.multiply(errorLocations[j], xiInverse);
int termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1;
denominator = field.multiply(denominator, termPlus1);
}
}
result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
field.inverse(denominator));
if (field.getGeneratorBase() != 0) {
result[i] = field.multiply(result[i], xiInverse);
}
}
return result;
}
}
| yakovenkodenis/Discounty | src/main/java/com/google/zxing/common/reedsolomon/ReedSolomonDecoder.java | Java | mit | 7,749 |
<?php
$passEnc = '$2y$06$wRkrmRT6gm8g0CqcKnrWYOrLke6waZva11sqfv4RkjuCXCjG0qI56';
$user = 'admin';
?>
| jplsek/Basic-CMS-Project | cms/key.php | PHP | mit | 103 |
package us.corenetwork.tradecraft;
import net.minecraft.server.v1_10_R1.Item;
import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.MerchantRecipe;
import net.minecraft.server.v1_10_R1.NBTTagCompound;
/**
* Created by Matej on 5.3.2014.
*/
public class CustomRecipe extends MerchantRecipe
{
private int tradeID = 0; //trade id per villager
private boolean locked = false;
private int tier = 0;
private int tradesLeft = 0;
private int tradesPerformed = 0;
private boolean isNew = false;
private boolean needsSaving = false;
public CustomRecipe(ItemStack itemStack, ItemStack itemStack2, ItemStack itemStack3) {
super(itemStack, itemStack2, itemStack3);
}
public CustomRecipe(ItemStack itemStack, ItemStack itemStack2) {
super(itemStack, itemStack2);
}
public CustomRecipe(ItemStack itemStack, Item item) {
super(itemStack, item);
}
/**
* Returns if trade is locked (cannot be traded)
*/
@Override
public boolean h() {
return locked || tradesLeft <= 0;
}
public void lockManually()
{
locked = true;
}
public void removeManualLock()
{
locked = false;
}
public int getTier() {
return tier;
}
public void setTier(int tier) {
this.tier = tier;
}
public int getTradesLeft() {
return tradesLeft;
}
public void setTradesLeft(int tradesLeft) {
this.tradesLeft = tradesLeft;
}
public int getTradesPerformed()
{
return tradesPerformed;
}
public void setTradesPerformed(int tradesPerformed)
{
this.tradesPerformed = tradesPerformed;
}
public CustomRecipe(NBTTagCompound nbtTagCompound) {
super(nbtTagCompound);
}
public int getTradeID()
{
return tradeID;
}
public void setTradeID(int id)
{
tradeID = id;
}
public void useTrade()
{
setTradesLeft(this.getTradesLeft() - 1);
setTradesPerformed(this.getTradesPerformed() + 1);
needsSaving = true;
}
public void restock()
{
setTradesLeft(Villagers.getDefaultNumberOfTrades());
needsSaving = true;
}
public void setShouldSave(boolean b)
{
needsSaving = false;
}
public boolean shouldSave()
{
return needsSaving;
}
public boolean getIsNew()
{
return isNew;
}
public void setIsNew(boolean value)
{
isNew = value;
}
}
| Kongolan/TradeCraft | src/us/corenetwork/tradecraft/CustomRecipe.java | Java | mit | 2,230 |
package com.tom.util;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraftforge.fluids.FluidStack;
import com.tom.api.research.Research;
import com.tom.recipes.handler.AdvancedCraftingHandler.CraftingLevel;
public class RecipeData {
public RecipeData(FluidStack f1, FluidStack f2, FluidStack f3, FluidStack f4, int energy, int inputAmount) {
this.f1 = f1;
this.f2 = f2;
this.f3 = f3;
this.f4 = f4;
this.energy = energy;
this.inputAmount = inputAmount;
this.processTime = 1;
}
public RecipeData(Block block2, Block output) {
this.output = output;
this.block2 = block2;
this.processTime = 1;
}
public RecipeData(Block block2, Block output, Item invItem1) {
this.output = output;
this.block2 = block2;
this.invItem1 = invItem1;
this.hasInv = true;
this.processTime = 1;
}
public RecipeData(FluidStack f, int energy, int amount) {
this.f1 = f;
this.energy = energy;
this.inputAmount = amount;
this.processTime = 1;
}
public RecipeData(FluidStack f, int energy, int amount, int processTime) {
this.f1 = f;
this.energy = energy;
this.inputAmount = amount;
this.processTime = processTime;
}
public RecipeData(ItemStack i, int energy, int amount, int processTime) {
this.itemstack1 = i;
this.energy = energy;
this.inputAmount = amount;
this.processTime = processTime;
}
public RecipeData(ItemStack is, int time, ItemStack[] isIn, List<Research> researchList, boolean shaped, ItemStack isExtra, CraftingLevel level) {
this.processTime = time;
this.requiredResearches = researchList;
this.itemstack1 = isIn[0];
this.itemstack2 = isIn[1];
this.itemstack3 = isIn[2];
this.itemstack4 = isIn[3];
this.itemstack5 = isIn[4];
this.itemstack6 = isIn[5];
this.itemstack7 = isIn[6];
this.itemstack8 = isIn[7];
this.itemstack9 = isIn[8];
this.itemstack0 = is;
this.itemstack10 = isExtra;
this.shaped = shaped;
this.level = level;
}
public RecipeData(ItemStack itemstack0, ItemStack itemstack1) {
this.itemstack0 = itemstack0;
this.itemstack1 = itemstack1;
}
public RecipeData(int energy, ItemStack itemstack0, ItemStack itemstack1) {
this.energy = energy;
this.itemstack0 = itemstack0;
this.itemstack1 = itemstack1;
}
public RecipeData(ItemStack itemstack0, ItemStack itemstack1, ItemStack itemstack2) {
this.itemstack0 = itemstack0;
this.itemstack1 = itemstack1;
this.itemstack2 = itemstack2;
}
public RecipeData(ItemStack itemstack0, ItemStack itemstack1, ItemStack itemstack2, boolean mode) {
this.itemstack0 = itemstack0;
this.itemstack1 = itemstack1;
this.itemstack2 = itemstack2;
this.hasInv = mode;
}
public RecipeData(IRecipe recipe, int time, List<Research> researchList, ItemStack extra, CraftingLevel level, int extraD, String rid) {
this.processTime = time;
this.requiredResearches = researchList;
this.recipe = recipe;
this.itemstack10 = extra;
this.level = level;
this.energy = extraD;
this.id = rid;
}
public RecipeData(FluidStack f1, FluidStack f2, int energy, int inputAmount) {
this.f1 = f1;
this.f2 = f2;
this.energy = energy;
this.inputAmount = inputAmount;
this.processTime = 1;
}
public FluidStack f1;
public FluidStack f2;
public FluidStack f3;
public FluidStack f4;
public int energy;
public int inputAmount;
public Block block2;
public Block output;
public Item invItem1;
public Item invItem2;
public Item invItem3;
public Item invItem4;
public Item invReturn1;
public Item invReturn2;
public boolean hasInv;
public int processTime;
public ItemStack itemstack0;
public ItemStack itemstack1;
public ItemStack itemstack2;
public ItemStack itemstack3;
public ItemStack itemstack4;
public ItemStack itemstack5;
public ItemStack itemstack6;
public ItemStack itemstack7;
public ItemStack itemstack8;
public ItemStack itemstack9;
public ItemStack itemstack10;
public List<Research> requiredResearches;
public boolean shaped;
public CraftingLevel level;
public IRecipe recipe;
public String id;
public RecipeData setId(String id) {
this.id = id;
return this;
}
}
| tom5454/Toms-Mod | src/main/java/com/tom/util/RecipeData.java | Java | mit | 4,212 |
//This file makes it easier to import everything from the common folder
export * from './Button';
export * from './Card';
export * from './CardSection';
export * from './Header';
export * from './Input';
export * from './Spinner';
export * from './Confirm';
| srserx/react-native-ui-common | index.js | JavaScript | mit | 259 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename : video.py
# Author : Kim K
# Created : Fri, 29 Jan 2016
# Last Modified : Sun, 31 Jan 2016
from sys import exit as Die
try:
import sys
import cv2
from colordetection import ColorDetector
except ImportError as err:
Die(err)
class Webcam:
def __init__(self):
self.cam = cv2.VideoCapture(0)
self.stickers = self.get_sticker_coordinates('main')
self.current_stickers = self.get_sticker_coordinates('current')
self.preview_stickers = self.get_sticker_coordinates('preview')
def get_sticker_coordinates(self, name):
"""
Every array has 2 values: x and y.
Grouped per 3 since on the cam will be
3 rows of 3 stickers.
:param name: the requested color type
:returns: list
"""
stickers = {
'main': [
[200, 120], [300, 120], [400, 120],
[200, 220], [300, 220], [400, 220],
[200, 320], [300, 320], [400, 320]
],
'current': [
[20, 20], [54, 20], [88, 20],
[20, 54], [54, 54], [88, 54],
[20, 88], [54, 88], [88, 88]
],
'preview': [
[20, 130], [54, 130], [88, 130],
[20, 164], [54, 164], [88, 164],
[20, 198], [54, 198], [88, 198]
]
}
return stickers[name]
def draw_main_stickers(self, frame):
"""Draws the 9 stickers in the frame."""
for x,y in self.stickers:
cv2.rectangle(frame, (x,y), (x+30, y+30), (255,255,255), 2)
def draw_current_stickers(self, frame, state):
"""Draws the 9 current stickers in the frame."""
for index,(x,y) in enumerate(self.current_stickers):
cv2.rectangle(frame, (x,y), (x+32, y+32), ColorDetector.name_to_rgb(state[index]), -1)
def draw_preview_stickers(self, frame, state):
"""Draws the 9 preview stickers in the frame."""
for index,(x,y) in enumerate(self.preview_stickers):
cv2.rectangle(frame, (x,y), (x+32, y+32), ColorDetector.name_to_rgb(state[index]), -1)
def color_to_notation(self, color):
"""
Return the notation from a specific color.
We want a user to have green in front, white on top,
which is the usual.
:param color: the requested color
"""
notation = {
'green' : 'F',
'white' : 'U',
'blue' : 'B',
'red' : 'R',
'orange' : 'L',
'yellow' : 'D'
}
return notation[color]
def scan(self):
"""
Open up the webcam and scans the 9 regions in the center
and show a preview in the left upper corner.
After hitting the space bar to confirm, the block below the
current stickers shows the current state that you have.
This is show every user can see what the computer toke as input.
:returns: dictionary
"""
sides = {}
preview = ['white','white','white',
'white','white','white',
'white','white','white']
state = [0,0,0,
0,0,0,
0,0,0]
while True:
_, frame = self.cam.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
key = cv2.waitKey(10) & 0xff
# init certain stickers.
self.draw_main_stickers(frame)
self.draw_preview_stickers(frame, preview)
for index,(x,y) in enumerate(self.stickers):
roi = hsv[y:y+32, x:x+32]
avg_hsv = ColorDetector.average_hsv(roi)
color_name = ColorDetector.get_color_name(avg_hsv)
state[index] = color_name
# update when space bar is pressed.
if key == 32:
preview = list(state)
self.draw_preview_stickers(frame, state)
face = self.color_to_notation(state[4])
notation = [self.color_to_notation(color) for color in state]
sides[face] = notation
# show the new stickers
self.draw_current_stickers(frame, state)
# append amount of scanned sides
text = 'scanned sides: {}/6'.format(len(sides))
cv2.putText(frame, text, (20, 460), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)
# quit on escape.
if key == 27:
break
# show result
cv2.imshow("default", frame)
self.cam.release()
cv2.destroyAllWindows()
return sides if len(sides) == 6 else False
webcam = Webcam()
| muts/qbr | src/video.py | Python | mit | 4,872 |
import React from 'react';
import Example from './Example';
import Icon from '../../src/Icon';
import Button from '../../src/Button';
import IconButton from '../../src/IconButton';
import FABButton from '../../src/FABButton';
export default ( props ) => (
<section { ...props }>
<h3>Buttons</h3>
<Example>
<FABButton colored>
<Icon name="add" />
</FABButton>
<FABButton colored ripple>
<Icon name="add" />
</FABButton>
</Example>
<Example>
<FABButton>
<Icon name="add" />
</FABButton>
<FABButton ripple>
<Icon name="add" />
</FABButton>
<FABButton disabled>
<Icon name="add" />
</FABButton>
</Example>
<Example>
<Button raised>Button</Button>
<Button raised ripple>Button</Button>
<Button raised disabled>Button</Button>
</Example>
<Example>
<Button raised colored>Button</Button>
<Button raised accent>Button</Button>
<Button raised accent ripple>Button</Button>
</Example>
<Example>
<Button>Button</Button>
<Button ripple>Button</Button>
<Button disabled>Button</Button>
</Example>
<Example>
<Button primary colored>Button</Button>
<Button accent>Button</Button>
</Example>
<Example>
<IconButton name="mood" />
<IconButton colored name="mood" />
</Example>
<Example>
<FABButton mini>
<Icon name="add" />
</FABButton>
<FABButton colored mini>
<Icon name="add" />
</FABButton>
</Example>
</section>
);
| joshq00/react-mdl | demo/sections/Buttons.js | JavaScript | mit | 1,885 |
using System.Collections;
namespace System.ComponentModel.DataAnnotations
{
public class EnsureMinimumElementsAttribute : ValidationAttribute
{
private readonly int _minElements;
public EnsureMinimumElementsAttribute(int minElements)
{
_minElements = minElements;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return (((IList)value).Count >= _minElements) ? ValidationResult.Success : new ValidationResult(base.ErrorMessage);
}
}
}
| orbital7/orbital7.extensions | src/Orbital7.Extensions.Attributes/EnsureMinimumElementsAttribute.cs | C# | mit | 583 |
//
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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.
//
/*
* File manipulation helper functions.
*/
#include "misc/debug.h"
#include "misc/io.h"
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
/** Creates a new sub-directory in the process' working directory.
*
* @param name Name of the folder to create.
*
* @return true if the operation succeeded, false otherwise.
**/
bool Anvil::IO::create_directory(std::string name)
{
#ifdef _WIN32
wchar_t buffer[32767]; /* as per MSDN documentation */
std::wstring buffer_string;
std::wstring full_path_wide;
std::wstring name_wide = std::wstring(name.begin(), name.end() );
std::string prefix = std::string ("\x5C\x5C?\x5C");
std::wstring prefix_wide = std::wstring(prefix.begin(), prefix.end() );
/* CreateDirectory*() require us to pass the full path to the directory
* we want to create. Form a string that contains this data. */
memset(buffer,
0,
sizeof(buffer) );
GetCurrentDirectoryW(sizeof(buffer),
buffer);
buffer_string = std::wstring(buffer);
full_path_wide = prefix_wide + buffer + std::wstring(L"\\") + name_wide;
return (CreateDirectoryW(full_path_wide.c_str(),
nullptr /* lpSecurityAttributes */) != 0);
#else
std::string absolute_path;
{
const int max_size = 1000;
char buffer[max_size];
/* mkdir() require us to pass the full path to the directory
* we want to create. Form a string that contains this data. */
memset(buffer, 0, max_size);
if (nullptr == getcwd(buffer, max_size))
{
anvil_assert(false);
}
absolute_path = std::string(buffer);
if (*absolute_path.rbegin() != '/')
absolute_path.append("/");
absolute_path += name;
}
struct stat st;
bool status = true;
if (stat(absolute_path.c_str(), &st) != 0)
{
if(mkdir(absolute_path.c_str(), 0777) != 0)
{
status = false;
}
}
else if (!S_ISDIR(st.st_mode))
{
status = false;
}
if (status == false)
{
anvil_assert(false);
}
return status;
#endif
}
/** Deletes a file in the working directory.
*
* @param filename Name of the file to remove.
**/
void Anvil::IO::delete_file(std::string filename)
{
remove(filename.c_str());
}
/* Please see header for specification */
bool Anvil::IO::enumerate_files_in_directory(const std::string& path,
std::vector<std::string>* out_result_ptr)
{
bool result = false;
#ifdef _WIN32
{
HANDLE file_finder(INVALID_HANDLE_VALUE);
WIN32_FIND_DATAW find_data;
const std::string path_expanded (path + "//*");
const std::wstring path_expanded_wide(path_expanded.begin(), path_expanded.end() );
if ( (file_finder = ::FindFirstFileW(path_expanded_wide.c_str(),
&find_data)) == INVALID_HANDLE_VALUE)
{
goto end;
}
do
{
if (find_data.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
{
std::wstring file_name_wide(find_data.cFileName);
std::string file_name (file_name_wide.begin(), file_name_wide.end() );
out_result_ptr->push_back(file_name);
}
}
while (::FindNextFileW(file_finder,
&find_data) );
if (file_finder != INVALID_HANDLE_VALUE)
{
::FindClose(file_finder);
result = true;
}
}
#else
{
struct dirent* dir_ptr = nullptr;
DIR* file_finder = nullptr;
file_finder = opendir(path.c_str() );
if (file_finder != nullptr)
{
while ( (dir_ptr = readdir(file_finder) ) != nullptr)
{
out_result_ptr->push_back(dir_ptr->d_name);
}
closedir(file_finder);
result = true;
}
}
#endif
#ifdef _WIN32
end:
#endif
return result;
}
/* Please see header for specification */
bool Anvil::IO::is_directory(const std::string& path)
{
bool result = false;
struct stat stat_data = {0};
if ((stat(path.c_str(),
&stat_data) == 0) &&
(stat_data.st_mode & S_IFMT) == S_IFDIR)
{
result = true;
}
return result;
}
/** Reads contents of a file with user-specified name and returns it to the caller.
*
* @param filename Name of the file to use for the operation.
* @param is_text_file true if the file should be treated as a text file; false
* if it should be considered a binary file.
* @param out_result_ptr Deref will be set to an array, holding the read file contents.
* The array must be deleted with a delete[] operator when no
* longer needed. Must not be nullptr.
* @param out_opt_size_ptr Deref will be set to the number of bytes allocated for @param out_result_ptr.
* May be nullptr.
**/
void Anvil::IO::read_file(std::string filename,
bool is_text_file,
char** out_result_ptr,
size_t* out_opt_size_ptr)
{
FILE* file_handle = nullptr;
size_t file_size = 0;
char* result = nullptr;
file_handle = fopen(filename.c_str(),
(is_text_file) ? "rt" : "rb");
anvil_assert(file_handle != 0);
fseek(file_handle,
0,
SEEK_END);
file_size = static_cast<size_t>(ftell(file_handle) );
anvil_assert(file_size != -1 &&
file_size != 0);
fseek(file_handle,
0,
SEEK_SET);
result = new char[file_size + 1];
anvil_assert(result != nullptr);
memset(result,
0,
file_size + 1);
size_t n_bytes_read = fread(result,
1,
file_size,
file_handle);
fclose(file_handle);
result[n_bytes_read] = 0;
/* Set the output variables */
*out_result_ptr = result;
if (out_opt_size_ptr != nullptr)
{
*out_opt_size_ptr = file_size;
}
}
/** Please see header for specification */
void Anvil::IO::write_binary_file(std::string filename,
const void* data,
unsigned int data_size,
bool should_append)
{
FILE* file_handle = nullptr;
file_handle = fopen(filename.c_str(),
(should_append) ? "ab" : "wb");
anvil_assert(file_handle != 0);
if (fwrite(data,
data_size,
1, /* count */
file_handle) != 1)
{
anvil_assert(false);
}
fclose(file_handle);
}
/** Please see header for specification */
void Anvil::IO::write_text_file(std::string filename,
std::string contents,
bool should_append)
{
FILE* file_handle = nullptr;
file_handle = fopen(filename.c_str(),
(should_append) ? "a" : "wt");
anvil_assert(file_handle != 0);
if (fwrite(contents.c_str(),
strlen(contents.c_str() ),
1, /* count */
file_handle) != 1)
{
anvil_assert(false);
}
fclose(file_handle);
}
| baxtea/Anvil | src/misc/io.cpp | C++ | mit | 8,936 |
var async = require('async');
function _hasher() {
return "_";
}
function accessor(idx) {
return (this.memo._ || [])[idx];
};
module.exports = function mymoize(fn) {
var memoized = async.memoize(fn, _hasher);
memoized.getErr = accessor.bind(memoized, 0);
memoized.getRes = accessor.bind(memoized, 1);
return memoized;
}
| adrienjoly/npm-mymoize | index.js | JavaScript | mit | 335 |
module Sinkhole
module Commands
class Help < Command
def do_process
Responses::HelpMessage.new(":(... y u no smtp?")
end
end
end
end | andrewstucki/sinkhole | lib/sinkhole/commands/help.rb | Ruby | mit | 164 |
using System;
namespace _03.Mankind
{
public abstract class Human
{
private string firstName;
private string lastName;
protected Human(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public string FirstName
{
get { return this.firstName; }
set
{
var firstLetter = char.Parse(value.Substring(0, 1));
if (!char.IsUpper(firstLetter))
{
throw new ArgumentException("Expected upper case letter! Argument: firstName");
}
if (value.Length < 4)
{
throw new ArgumentException("Expected length at least 4 symbols! Argument: firstName");
}
this.firstName = value;
}
}
public string LastName
{
get { return this.lastName; }
set
{
var firstLetter = char.Parse(value.Substring(0, 1));
if (!char.IsUpper(firstLetter))
{
throw new ArgumentException("Expected upper case letter! Argument: lastName");
}
if (value.Length < 3)
{
throw new ArgumentException("Expected length at least 3 symbols! Argument: lastName");
}
this.lastName = value;
}
}
}
}
| George221b/SoftUni-Tasks | C#OOP-Basics/03.Inheritance-Exercise/03.Mankind/Human.cs | C# | mit | 1,540 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("Slack.ServiceLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Slack.ServiceLibrary")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("ea97ed70-cfb4-4bb0-8619-0061c5d33b11")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| nikeyes/SlackClient | Slack.ServiceLibrary/Properties/AssemblyInfo.cs | C# | mit | 1,558 |
var Promise = require('ia-promise');
var XHRPromise = require('./XHRPromise');
var CommandPromise = require('./CommandPromise');
var ProfilePromise = require('./ProfilePromise');
var ViewPromise = require('./ViewPromise');
var FutureViewPromise = require('./FutureViewPromise');
var RoomPromise = require('./RoomPromise');
function RoomsPromise(app, name) {
// Calling parent constructor
ViewPromise.call(this, app, name);
// Registering UI elements
this.tbody = document.querySelector('tbody'),
this.trTpl = this.tbody.firstChild;
this.tbody.removeChild(this.trTpl);
}
RoomsPromise.prototype = Object.create(ViewPromise.prototype);
RoomsPromise.prototype.reset = function () {
while(this.tbody.firstChild) {
this.tbody.removeChild(this.tbody.firstChild);
}
};
RoomsPromise.prototype.hide = function () {
this.reset();
this.tbody.appendChild(this.trTpl);
};
RoomsPromise.prototype.loop = function (timeout) {
var _this = this;
// roooms update
function getRoomsUpdatePromise() {
return new XHRPromise('GET', '/rooms.json', true).then(function(xhr){
_this.reset();
var rooms = JSON.parse(xhr.responseText);
rooms.forEach(function(room) {
var tr = _this.trTpl.cloneNode(true);
tr.firstChild.firstChild.setAttribute('href',
_this.trTpl.firstChild.firstChild.getAttribute('href') + room.id);
if(room.state)
tr.firstChild.firstChild.setAttribute('disabled','disabled');
tr.firstChild.firstChild.firstChild.textContent = room.name;
tr.childNodes[1].firstChild.textContent = room.players + '/6';
tr.childNodes[2].firstChild.textContent = room.mode;
_this.tbody.appendChild(tr);
});
});
}
return Promise.all(
_this.app.user && _this.app.user.name ?
Promise.sure() :
new ProfilePromise(_this.app, 'Profile', true),
getRoomsUpdatePromise()
).then(function() {
_this.display();
return Promise.any(
// Handling channel join
new CommandPromise(_this.app.cmdMgr, 'join', _this.name).then(function(data) {
return new RoomPromise(_this.app, 'Room', data.params.room);
}),
// Handling channel list refresh
new CommandPromise(_this.app.cmdMgr, 'refresh', _this.name),
// Handling the back button
new CommandPromise(_this.app.cmdMgr, 'back', _this.name).then(function() {
_this.end=true;
}),
// Handling menu
new CommandPromise(_this.app.cmdMgr, 'menu', _this.name).then(function(data) {
// Loading the selected view
return _this.app.loadView(data.params.view);
})
)
});
};
module.exports = RoomsPromise;
| nfroidure/Liar | src/RoomsPromise.js | JavaScript | mit | 2,568 |
/**
* ionNavBar
*
* ionNavBar and _ionNavBar are created to overcome Meteor's templating limitations. By utilizing Template.dynamic
* in blaze, we can force ionNavBar to destroy _ionNavBar, enabling css transitions and none of that javascript
* animation.
*/
let _ionNavBar_Destroyed = new ReactiveVar(false);
Template.ionNavBar.onCreated(function() {
this.data = this.data || {};
if (Platform.isAndroid()) {
this.transition = 'android';
} else {
this.transition = 'ios';
}
this.ionNavBarTemplate = new ReactiveVar('_ionNavBar');
$(window).on('statechange', e => this.ionNavBarTemplate.set(''));
this.autorun(() => {
if (_ionNavBar_Destroyed.get()) { this.ionNavBarTemplate.set('_ionNavBar'); }
});
});
Template.ionNavBar.onRendered(function() {
let container = this.$('.nav-bar-container');
container.attr('nav-bar-direction', 'forward');
let navBarContainer = this.find('.nav-bar-container');
navBarContainer._uihooks = {
// Override onDestroyed so that's children won't remove themselves immediately.
removeElement: function(node) {
// Worst case scenario. Remove if exceeded maximum transition duration.
Meteor.setTimeout(() => {
node.remove();
}, METEORIC.maximum_transition_duration);
}
};
});
Template.ionNavBar.helpers({
ionNavBarTemplate: function() {
return Template.instance().ionNavBarTemplate.get();
},
transition: function () {
return Template.instance().transition;
}
});
Template._ionNavBar.onCreated(function () {
this.entering = false;
this.leaving = false;
this.activate_view_timeout_id = null;
this.deactivate_view_timeout_id = null;
_ionNavBar_Destroyed.set(false);
});
Template._ionNavBar.onRendered(function () {
// Reset nav-bar-direction.
let navBarBlock = this.find('.nav-bar-block');
navBarBlock._uihooks = {
// Override onDestroyed so that's children won't remove themselves immediately.
removeElement: function(node) {
// Worst case scenario. Remove if exceeded maximum transition duration.
Meteor.setTimeout(() => {
node.remove();
}, METEORIC.maximum_transition_duration);
}
};
let $navBarBlock = this.$('.nav-bar-block').first();
let activate_view = () => {
this.entering = false;
let activate_timer_active = !!this.activate_view_timeout_id;
if (activate_timer_active) {
Meteor.clearTimeout(this.activate_view_timeout_id);
this.activate_view_timeout_id = null;
}
$navBarBlock.attr('nav-bar', 'active');
$('[data-navbar-container]').attr('nav-bar-direction', 'forward');
};
$navBarBlock.attr('nav-bar', 'stage');
let $headerBar = this.$('.nav-bar-block *');
Meteor.setTimeout(() => {
this.entering = true;
$navBarBlock.attr('nav-bar', 'entering');
$headerBar.one(METEORIC.UTILITY.transitionend_events.join(' '), activate_view);
}, 0);
// Worst case scenario, transitionend did not occur. Just place view in.
this.activate_view_timeout_id = Meteor.setTimeout(activate_view, METEORIC.maximum_transition_duration);
});
Template._ionNavBar.onDestroyed(function () {
_ionNavBar_Destroyed.set(true);
let $navBarBlock = this.$('.nav-bar-block');
let deactivate_view = () => {
this.leaving = false;
// If the user have trigger fingers, in which he/she can click back buttons
// really fast, activate view timer might still be going. Kill it.
let activate_timer_active = !!this.activate_view_timeout_id;
if (activate_timer_active) {
Meteor.clearTimeout(this.activate_view_timeout_id);
this.activate_view_timeout_id = null;
}
let deactivate_timer_active = !!this.deactivate_view_timeout_id;
if (deactivate_timer_active) {
Meteor.clearTimeout(this.deactivate_view_timeout_id);
this.deactivate_view_timeout_id = null;
}
this.deactivate_view_timeout_id = null;
$navBarBlock.remove();
};
let $headerBar = this.$('.nav-bar-block *');
Meteor.setTimeout(() => {
this.leaving = true;
$navBarBlock.attr('nav-bar', 'leaving');
$headerBar.one(METEORIC.UTILITY.transitionend_events.join(' '), deactivate_view);
}, 0);
// Worst case scenario, transitionend did not occur. Just remove the view.
this.deactivate_view_timeout_id = Meteor.setTimeout(deactivate_view, METEORIC.maximum_transition_duration);
});
| JoeyAndres/meteor-ionic | components/ionNavBar/ionNavBar.js | JavaScript | mit | 4,669 |
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("mko.Testdata")]
[assembly: AssemblyDescription("Testdatengeneratoren")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("mk-prg-net")]
[assembly: AssemblyProduct("mko.Testdata")]
[assembly: AssemblyCopyright("Copyright Martin Korneffel © 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("ea115078-b90f-446e-881f-8a2ddc578d7c")]
// 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")]
| mk-prg-net/mk-prg-net.lib | mko.Testdata/Properties/AssemblyInfo.cs | C# | mit | 1,447 |
using System;
using System.Collections.Generic;
using System.Reflection;
using WSDL.Models;
using WSDL.Models.Schema;
namespace WSDL.TypeManagement
{
/// <summary>
/// This provides a stateful context for managing the types required to define
/// a web service. It includes all the types, both static and instance related
/// </summary>
public interface ITypeContext : IDisposable
{
/// <summary>
/// It transforms the parameter types and return types into complex types for both
/// input and output
/// </summary>
/// <param name="methodInfo">The method to transform</param>
/// <param name="contractNamespace">The namespace of the contract to which this method belongs to</param>
/// <returns>Method description with input and output types</returns>
MethodDescription GetDescriptionForMethod(MethodInfo methodInfo, string contractNamespace);
/// <summary>
/// Returns the schemas for the types built during the last execution
/// </summary>
/// <returns>The schemas containing all the types built</returns>
IEnumerable<Schema> GetSchemas();
}
}
| carlos-vicente/Nancy.Soap | src/WSDL/TypeManagement/ITypeContext.cs | C# | mit | 1,193 |
/*
* jobshopConstants.java
*
* Created on February 3, 2001, 12:48 PM
*/
package hugs.apps.jobshop;
import java.lang.*;
import java.util.*;
/**
* This class holds all the constants used in the jobshop project
*
* @author Guy T. Schafer
* @version 1.0
*/
public class jobshopConstants
{
// Window titles:
public final static String TITLE = "Jobshop Optimizer";
public final static String TITLE2 = " v1.0 by Guy T. Schafer";
public final static String STBTITLE = "Algorithm Server Process ";
public final static String HISTTITLE= "Solution History";
public final static String GRPTITLE = "Group Solutions";
public final static String NAMTITLE = "Group Identifier";
// Top level menus:
public final static String FILE = "File";
public final static String VIEW = "View";
public final static String HIST = "History";
public final static String SERVER = "Servers";
public final static String MOBIL = "Mobilities";
public final static String HELP = "Help";
// Tools and Menu Items:
public final static String OPEN = "Open";
public final static String SAVE = "Save";
public final static String SAVEAS = "Save As";
public final static String EXIT = "Exit";
// public final static String TOOLBAR = "Toolbar";
public final static String ATTRIB = "Attributes";
// public final static String PRIOR = "Mobility";
public final static String SHOW = "Show ";
public final static String JOBCOL = "Job Colors";
public final static String JOBID = "Job IDs";
public final static String CHANGE = "Changes";
public final static String CRIT = "Critical Path";
// The first L here is actually an I so the L in Low
// is underlined for the menu shortcut:
public final static String LOW = "Set seIected to Low Mobility";
public final static String MED = "Set selected to Medium Mobility";
public final static String HIGH = "Set selected to High Mobility";
public final static String LOWALL = "Set all to Low Mobility";
public final static String MEDALL = "Set all to Medium Mobility";
public final static String HIGHALL = "Set all to High Mobility";
public final static String DOUBLE = " (double-click to set all)";
public final static String SCALE = "Scale";
public final static String FIT = "Fit on page";
public final static String ZOOMINH = "Stretch Horizontally";
public final static String ZOOMOUTH = "Shrink Horizontally";
public final static String ZOOMINV = "Stretch Vertically";
public final static String ZOOMOUTV = "Shrink Vertically";
public final static String GO = "Go";
public final static String STOP = "Stop";
public final static String LOOK = "Display solution / Add solution to history";
public final static String REL = "Kill this server process";
public final static String SPAN = "Spansize - improving any of these machines is an improvement";
public final static String PLY = "Minimum ply - no fewer than this many swaps";
public final static String UNDO = "Earlier Solution";
public final static String REDO = "Later Solution";
public final static String PROC = "Request server process";
public final static String CONTENTS = "Contents";
public final static String ABOUT = "About";
public final static String CHOOSE = "Choose search algorithm";
public final static String SHARE = "Share this solution with group";
// Labels for controls:
public final static String SPANLBL = "Span ";
public final static String PLYLBL = "min ply ";
public final static String SOLHIST = " History ";
public final static String GRPHIST = " Shared solutions ";
public final static String GRPID = " Group ";
public final static String GRPNAME = " Name ";
public final static String GETNAME = "Enter your name";
// Some labels are in menus (with dots) and tooltips (without dots):
public final static String DOTS = "...";
// Accelerators:
public final static char FACC = 'f';
public final static char VACC = 'v';
public final static char SACC = 's';
public final static char HACC = 'h';
public final static char OACC = 'o';
public final static char AACC = 'a';
public final static char XACC = 'x';
public final static char IACC = 'i';
public final static char GACC = 'g';
public final static char TACC = 't';
public final static char UACC = 'u';
public final static char CACC = 'c';
public final static char PACC = 'p';
public final static char RACC = 'r';
public final static char MACC = 'm';
public final static char LACC = 'l';
public final static char WACC = 'w';
public final static char DACC = 'd';
public final static char EACC = 'e';
public final static char JACC = 'j';
// Status bar has solution history:
public final static String NOHIST = "No solutions";
// Status bar messages:
public final static String GOSTATUS = "Start server process...";
public final static String STOPSTATUS = "Stop server process";
public final static String ENOPROC = "Server cannot supply more power";
public final static String FILEOPEN = "File opened";
public final static String ALERT = "Better solution found";
public final static String GRPSTATUS= "New schedule from group";
public final static String ALGSTATUS= "New schedule from server";
public final static String SHOWING = "Showing ";
public final static String HIDING = "Hiding ";
// Group info:
// The max number of members in each group
// (Also the max number of groups before the numbers
// wrap - hopefully, by the time the 10,000th group
// is created, group 0 is gone. But if it isn't
// unpredictable--but bad--behavior will result.)
public final static int MAXMEMBERS = 10000;
// Algorithm names (and count):
public final static int ALGOCNT = 3;
public final static String[] ALGO = { "Local Greedy",
"Local Deep",
"Tabu Search"
};
// File Dialog strings:
public final static String FILTER = "Jobshop files (*.jsp)";
public final static String EXT = ".jobshop";
// Group Name Input Dialog:
public final static String CANCEL = "Cancel";
// About Dialog strings:
public final static String COPYRIGHT= " (c) 2001 Mitsubishi Electric Research Lab";
public final static String OK = "OK";
// Client status messages:
public final static String CONNORB = " Connecting to ORB...";
public final static String OKORB = " Connected to ORB.";
public final static String ENOORB = " ERROR: Failed to acquire ORB. Check tnameserv is running.";
public final static String CONNALGO = " Finding Algorithm Server...";
public final static String OKALGO = " Found Algorithm Server.";
public final static String ENOALGO = " ERROR: Failed to find Algorithm Server. Cannot continue.";
public final static String CONNGROUP= " Finding Group Server...";
public final static String OKGROUP = " Found Group Server.";
public final static String MONITOR = " Group Monitor Mode ON.";
public final static String ENOGROUP = " ERROR: Failed to find Group Server. Cannot be Monitor.";
public final static String WNOGROUP = " WARNING: Failed to find Group Server. Working alone...";
public final static String ENOPACK = "Invalid move. Cannot pack schedule.";
// Output file comments:
public final static String DEFCOM1 = "// MachineCount JobCount:";
public final static String DEFCOM2 = "// Each line is a job, data format: {machine# jobDuration}";
public final static String HISTCOM1 = "// History of solutions:";
public final static String HISTCOM2 = "// Each line is a job, data format: {machine# jobDuration startTime}";
public final static String SLBLCOM = "// Maxspan = "; // Schedule label comment
// Critical path (it is either critcal because of job
// or machine or both so make the flags OR-able):
public final static int NOTCR = 0;
public final static int CRJOB = 1;
public final static int CRMACH = 2;
// Mobilites:
public final static int LOWMOB = 4;
public final static int MEDMOB = 2;
public final static int HIGHMOB = 1;
// Flags for menu to tell client to move in history:
public final static int NEXT = -2;
public final static int PREV = -4;
}
| guwek/HuGS | hugs/apps/jobshop/jobshopConstants.java | Java | mit | 9,091 |
/* eslint no-unused-expressions: "off" */
import { expect } from 'chai';
import { Session } from '../utils';
import * as ModelUtils from '../../../src/utils/model-utils';
const session = new Session();
const Vehicle = session.model('Vehicle', {});
const Car = session.model('Car', {}, {
'extends': Vehicle
});
const Sedan = session.model('Sedan', {
'numDoors': {
'type': Number
}
}, {
'extends': Car
});
describe('Model Utilities tests', () => {
describe('getModel()', () => {
it('Fails when no argument given', () => {
const result = ModelUtils.getModel();
expect(result).to.be.null;
});
it('Fails when given non-model', () => {
const result = ModelUtils.getModel({});
expect(result).to.be.null;
});
it('Returns model class given', () => {
const result = ModelUtils.getModel(Car);
expect(result).to.equal(Car);
});
it('Returns model class for instance', () => {
const car = new Car();
const result = ModelUtils.getModel(car);
expect(result).to.not.equal(car);
expect(result).to.equal(Car);
});
});
describe('getName()', () => {
it('Returns name for model class', () => {
const result = ModelUtils.getName(Car);
expect(result).to.equal('Car');
});
it('Returns name for model instance', () => {
const result = ModelUtils.getName(new Car());
expect(result).to.equal('Car');
});
});
describe('getParent()', () => {
it('Returns parent for model class', () => {
const result = ModelUtils.getParent(Sedan);
expect(result).to.equal(Car);
});
it('Returns parent for model instance', () => {
const result = ModelUtils.getParent(new Sedan());
expect(result).to.equal(Car);
});
it('Returns null if given model is root', () => {
const result = ModelUtils.getParent(Vehicle);
expect(result).to.be.null;
});
it('Returns null if argument missing', () => {
const result = ModelUtils.getParent();
expect(result).to.be.null;
});
});
describe('getAncestors()', () => {
it('Returns ancestors for model class', () => {
const result = ModelUtils.getAncestors(Sedan, session);
expect(result).to.deep.equal([Car, Vehicle]);
});
it('Returns ancestors for model instance', () => {
const result = ModelUtils.getAncestors(new Sedan(), session);
expect(result).to.deep.equal([Car, Vehicle]);
});
});
describe('getField()', () => {
it('Returns field for model class', () => {
const result = ModelUtils.getField(Sedan, 'numDoors');
expect(result).to.deep.equal({
'column': 'numDoors',
'name': 'numDoors',
'type': Number,
'owningModel': Sedan
});
});
it('Returns field for model instance', () => {
const result = ModelUtils.getField(new Sedan(), 'numDoors');
expect(result).to.deep.equal({
'column': 'numDoors',
'name': 'numDoors',
'type': Number,
'owningModel': Sedan
});
});
});
describe('getFields()', () => {
it('Returns fields for model class', () => {
const result = ModelUtils.getFields(Sedan);
expect(result).to.deep.equal({
'numDoors': {
'column': 'numDoors',
'name': 'numDoors',
'owningModel': Sedan,
'type': Number
}
});
});
it('Returns fields for model instance', () => {
const result = ModelUtils.getFields(new Sedan());
expect(result).to.deep.equal({
'numDoors': {
'column': 'numDoors',
'name': 'numDoors',
'owningModel': Sedan,
'type': Number
}
});
});
});
describe('getAllFields()', () => {
it('Returns fields for model class', () => {
const result = ModelUtils.getAllFields(Sedan, session);
expect(result).to.deep.equal({
'numDoors': {
'column': 'numDoors',
'name': 'numDoors',
'owningModel': Sedan,
'type': Number
}
});
});
it('Returns fields for model instance', () => {
const result = ModelUtils.getAllFields(new Sedan(), session);
expect(result).to.deep.equal({
'numDoors': {
'column': 'numDoors',
'name': 'numDoors',
'owningModel': Sedan,
'type': Number
}
});
});
});
describe('getChangedFields', () => {
it('Returns array of field names for model instance', () => {
const sedan = new Sedan({
'numDoors': 4,
'numWheels': 4,
'numWindows': 6
});
const result = ModelUtils.getChangedFields(sedan, session);
expect(result).to.deep.equal(['numDoors']);
});
});
}); | one-orm/core | test/unit/utils/model-utils-test.js | JavaScript | mit | 5,551 |
#!/usr/bin/python
"""
Author: Mohamed K. Eid (mohamedkeid@gmail.com)
Description: stylizes an image using a generative model trained on a particular style
Args:
--input: path to the input image you'd like to apply a style to
--style: name of style (found in 'lib/generators') to apply to the input
--out: path to where the stylized image will be created
--styles: lists trained models available
"""
import argparse
import os
import time
import tensorflow as tf
import generator
import helpers
# Loss term weights
CONTENT_WEIGHT = 1.
STYLE_WEIGHT = 3.
TV_WEIGHT = .1
# Default image paths
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
TRAINED_MODELS_PATH = DIR_PATH + '/../lib/generators/'
INPUT_PATH, STYLE = None, None
OUT_PATH = DIR_PATH + '/../output/out_%.0f.jpg' % time.time()
if not os.path.isdir(DIR_PATH + '/../output'):
os.makedirs(DIR_PATH + '/../output')
# Parse arguments and assign them to their respective global variables
def parse_args():
global INPUT_PATH, STYLE, OUT_PATH
# Create flags
parser = argparse.ArgumentParser()
parser.add_argument('--input', help="path to the input image you'd like to apply a style to")
parser.add_argument('--style', help="name of style (found in 'lib/generators') to apply to the input")
parser.add_argument('--out', default=OUT_PATH, help="path to where the stylized image will be created")
parser.add_argument('--styles', action="store_true", help="list available styles")
args = parser.parse_args()
# Assign image paths from the arg parsing
if args.input and args.style:
INPUT_PATH = os.path.abspath(args.input)
STYLE = args.style
OUT_PATH = args.out
else:
if args.styles:
list_styles()
exit(0)
else:
parser.print_usage()
exit(1)
# Lists trained models
def list_styles():
print("Available styles:")
files = os.listdir(TRAINED_MODELS_PATH)
for file in files:
if os.path.isdir(TRAINED_MODELS_PATH + file):
print(file)
parse_args()
with tf.Session() as sess:
# Check if there is a model trained on the given style
if not os.path.isdir(TRAINED_MODELS_PATH + STYLE):
print("No trained model with the style '%s' was found." % STYLE)
list_styles()
exit(1)
# Load and initialize the image to be stlylized
input_img, _ = helpers.load_img(INPUT_PATH)
input_img = tf.convert_to_tensor(input_img, dtype=tf.float32)
input_img = tf.expand_dims(input_img, axis=0)
# Initialize new generative net
with tf.variable_scope('generator'):
gen = generator.Generator()
gen.build(tf.convert_to_tensor(input_img))
sess.run(tf.global_variables_initializer())
# Restore previously trained model
ckpt_dir = TRAINED_MODELS_PATH + STYLE
saved_path = ckpt_dir + "/{}".format(STYLE)
saver = tf.train.Saver()
saver.restore(sess, saved_path)
# Generate stylized image
img = sess.run(gen.output)
# Save the generated image and close the tf session
helpers.render(img, path_out=OUT_PATH)
sess.close()
| mohamedkeid/Feed-Forward-Style-Transfer | src/test.py | Python | mit | 3,177 |
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express',reqCsrf:req.csrfToken()});
});
router.post('/regist',function(req,res){
res.send('OK')
});
router.post('/registXhr',function(req,res){
if(req.xhr){
res.send('xhr Access');
}else{
res.send('not xhr Access');
}
});
module.exports = router
| CM-Kajiwara/csurfSample | routes/index.js | JavaScript | mit | 439 |
using Diabhelp.Core.Api;
using Diabhelp.Core.Api.ResponseModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Diabhelp.Core
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class InscriptionScreen : Page
{
public InscriptionScreen()
{
this.InitializeComponent();
}
private void inscription_confirm_button_Click(object sender, RoutedEventArgs e)
{
if (inscriptionPanel.Children.OfType<TextBox>().Any(t => string.IsNullOrWhiteSpace(t.Text)) ||
inscriptionPanel.Children.OfType<PasswordBox>().Any(t => string.IsNullOrWhiteSpace(t.Password)) ||
!role_panel.Children.OfType<RadioButton>().Any(b => b.IsChecked == true))
{
error_lbl.Text = "Veuillez remplir tout les champs";
}
else if (!password_input.Password.Equals(password_confirm_input.Password))
error_lbl.Text = "Les mots de passe doivent correspondre";
else if (login_input.Text.Length < 6)
error_lbl.Text = "Le login doit faire au moins 6 caractères";
else if (password_input.Password.Length < 6)
error_lbl.Text = "Le mot de passe doit faire au moins 6 caractères";
else
{
string role = "";
if (patient_radio_btn.IsChecked == true)
role = "ROLE_PATIENT";
else if (medecin_radio_btn.IsChecked == true)
role = "ROLE_DOCTOR";
else
role = "ROLE_PROCHE";
new ApiClient().doInscription(login_input.Text, email_input.Text, password_input.Password, role, firstname_input.Text, lastname_input.Text, inscription_button_callback);
}
}
public async void inscription_button_callback(InscriptionResponseBody response)
{
if (response.success)
{
error_lbl.Text = "";
await new ApiClient().doLoginPost(login_input.Text, password_input.Password, connect_after_inscription_button_callback);
}
else
{
String errortext = "Erreur lors de l'inscription : ";
if (response.errors.Count >= 1)
errortext += response.errors[0];
else
errortext += "Erreur Inconnue";
error_lbl.Text = errortext;
}
}
public void connect_after_inscription_button_callback(LoginResponseBody response)
{
if (response.success)
{
this.Frame.Navigate(typeof(MainScreen), response);
}
else
{
this.Frame.Navigate(typeof(LoginScreen));
}
}
}
} | DiabHelp/DiabHelp-App-WP | Diabhelp/Core/InscriptionScreen.xaml.cs | C# | mit | 3,398 |
var React = require('react');
var AWSMixin = require('../mixins/aws.mixin');
var AWSActions = require('../actions/AWSActions');
var EC2Item = React.createClass({
render: function() {
return (
<a href="#" onClick={this._onSSHClick} className="col one-fourth ec2-instance">{this.props.instance.Name}</a>
);
},
_onSSHClick: function() {
AWSActions.sshInto(this.props.instance);
}
});
var EC2Section = React.createClass({
mixins:[AWSMixin],
render: function() {
instances = this.state['ec2-instances'];
var ec2items = [];
instances.forEach(function(i) {
ec2items.push(<EC2Item instance={i} />);
});
return (
<div>
<h4 class="section-title" id="grid">EC2 Instances</h4>
<div className="container" id="ec2-instances">{ec2items}</div>
</div>
);
}
});
module.exports = EC2Section;
| sunils34/visualize-aws | www/js/components/EC2.react.js | JavaScript | mit | 865 |
describe('jQuery Plugin', function () {
it('jQuery.fn.plugin should exist', function () {
expect(jQuery.fn.plugin).toBeDefined();
});
}); | angryobject/jquery-plugin-starter | app/jquery.plugin.spec.js | JavaScript | mit | 149 |
using HtmlAgilityPack;
using MagicNewCardsBot.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MagicNewCardsBot
{
public class MTGPicsTasker : Tasker
{
#region Definitions
protected new string _websiteUrl = "https://www.mtgpics.com/";
#endregion
protected string ValidateAndFixUrl(string url)
{
if (!url.Contains(_websiteUrl))
{
url = _websiteUrl + url;
}
return url;
}
#region Overrided Methods
async override protected IAsyncEnumerable<Card> GetAvaliableCardsInWebSiteAsync()
{
List<Set> setsToCrawl = await Database.GetAllCrawlableSetsAsync();
foreach (Set set in setsToCrawl)
{
//loads the website
HtmlDocument doc = new();
//crawl the webpage to get this information
using (Stream stream = await Utils.GetStreamFromUrlAsync(set.URL))
{
doc.Load(stream);
}
//all the cards are a a href so we get all of that
HtmlNodeCollection nodesCards = doc.DocumentNode.SelectNodes("//td[@valign='middle']");
if (nodesCards != null)
{
int crawlsFromThisSite = 0;
foreach (HtmlNode node in nodesCards)
{
var nodeImageCard = node.SelectSingleNode(".//img");
//also the cards have a special class called 'card', so we use it to get the right ones
if (nodeImageCard != null &&
nodeImageCard.Attributes.Contains("src") &&
nodeImageCard.Attributes["src"].Value.ToString().EndsWith(".jpg"))
{
string cardUrl = nodeImageCard.ParentNode.Attributes["href"].Value.ToString();
cardUrl = ValidateAndFixUrl(cardUrl);
string imageUrl = nodeImageCard.Attributes["src"].Value.ToString();
imageUrl = ValidateAndFixUrl(imageUrl);
var card = new Card
{
FullUrlWebSite = cardUrl,
ImageUrl = imageUrl
};
yield return card;
crawlsFromThisSite++;
}
//only get the lastest
if (crawlsFromThisSite == Database.MAX_CARDS)
break;
}
}
}
}
private static void ProcessFieldByType(IList<HtmlNode> nodes, Card mainCard, CardFields field)
{
for (int i = 0; i < nodes.Count; i++)
{
try
{
var node = nodes[i];
Card card;
if (i == 0)
card = mainCard;
else
card = mainCard.ExtraSides[i - 1];
switch (field)
{
case CardFields.Name:
card.Name = node.InnerText.Trim();
break;
case CardFields.ManaCost:
string totalCost = String.Empty;
foreach (var childNode in node.ChildNodes)
{
string imgUrl = childNode.Attributes["src"].Value;
if (imgUrl.EndsWith(".png"))
{
int lastIndex = imgUrl.LastIndexOf('/');
string cost = imgUrl[(lastIndex + 1)..];
cost = cost.Replace(".png", String.Empty);
totalCost += cost.Trim().ToUpper();
}
}
if (!String.IsNullOrEmpty(totalCost))
{
card.ManaCost = totalCost;
}
break;
case CardFields.Type:
string type = node.InnerText;
type = type.Replace("\u0097", "-");
type = System.Net.WebUtility.HtmlDecode(type);
type = type.Trim();
if (!String.IsNullOrEmpty(type))
card.Type = type;
break;
case CardFields.Text:
StringBuilder sb = new();
foreach (var childNode in node.ChildNodes)
{
if (childNode.Attributes != null)
{
if (childNode.Attributes["alt"] != null)
{
string symbol = childNode.Attributes["alt"].Value;
symbol = symbol.Replace("%", "");
sb.Append(symbol.ToUpper());
continue;
}
else if (childNode.Attributes["onclick"] != null && childNode.Attributes["onclick"].Value.Contains("LoadGlo"))
{
continue;
}
}
string text = childNode.InnerText.Replace("\u0095", "");
text = text.Replace("\u0097", "-");
text = text.Replace("\n\t\t\t", String.Empty);
text = text.Replace(" ", " ");
text = WebUtility.HtmlDecode(text);
sb.Append(text);
}
string sbString = sb.ToString();
if (!String.IsNullOrEmpty(sbString))
card.Text = sbString;
break;
case CardFields.PT:
foreach (var childNodes in node.ChildNodes)
{
var text = childNodes.InnerText.Trim();
text = text.Replace("\n", String.Empty);
if (text.Contains("/"))
{
String[] arrPt = text.Split('/');
if (arrPt.Length == 2)
{
card.Power = arrPt[0];
card.Toughness = arrPt[1];
break;
}
}
else if (text.Contains("Loyalty:") || text.Contains("Loyalty :"))
{
string numbersOnly = Regex.Replace(text, "[^0-9]", "");
card.Loyalty = Convert.ToInt32(numbersOnly);
}
}
break;
case CardFields.Rarity:
string rarityValue = node.Attributes?["src"].Value;
Rarity? rarity = null;
rarityValue = rarityValue.Replace("graph/rarity/", string.Empty).Trim();
switch (rarityValue)
{
case "carte30.png":
rarity = Rarity.Common;
break;
case "carte20.png":
rarity = Rarity.Uncommon;
break;
case "carte10.png":
rarity = Rarity.Rare;
break;
case "carte4.png":
rarity = Rarity.Mythic;
break;
}
if(rarity.HasValue)
{
card.Rarity = rarity;
}
break;
default:
break;
}
}
catch { }
}
}
private string GetImageUrlFromHtmlDoc(HtmlDocument html)
{
try
{
var nodeParent = html.DocumentNode.SelectSingleNode(".//div[@id='CardScan']");
var nodeImage = nodeParent.SelectSingleNode(".//img");
string urlNewImage = nodeImage.Attributes["src"].Value.ToString();
urlNewImage = ValidateAndFixUrl(urlNewImage);
return urlNewImage;
}
catch
{ }
return null;
}
private static void GetDetails(Card card, HtmlDocument html)
{
//NAME
var nodes = html.DocumentNode.SelectNodes(".//div[@class='Card20']");
if (nodes != null)
ProcessFieldByType(nodes, card, CardFields.Name);
//MANA COST
nodes = html.DocumentNode.SelectNodes(".//div[@style='height:25px;float:right;']");
if (nodes != null)
ProcessFieldByType(nodes, card, CardFields.ManaCost);
//TEXT
nodes = html.DocumentNode.SelectNodes(".//div[@id='EngShort']");
if (nodes != null)
ProcessFieldByType(nodes, card, CardFields.Text);
var g16nodes = html.DocumentNode.SelectNodes(".//div[@class='CardG16']");
//TYPE
var nodesType = g16nodes.Where(x => x.Attributes["style"] != null &&
x.Attributes["style"].Value.Trim().Equals("padding:5px 0px 5px 0px;")
).ToList();
if (nodesType != null)
ProcessFieldByType(nodesType, card, CardFields.Type);
//POWER AND TOUGHNESS AND LOYALTY
var nodesPT = g16nodes.Where(x => x.Attributes["align"] != null &&
!String.IsNullOrEmpty(x.InnerText.Trim()) &&
x.Attributes["align"].Value.Trim().Equals("right")).ToList();
if (nodesPT != null)
ProcessFieldByType(nodesPT, card, CardFields.PT);
var nodesRarity = html.DocumentNode.SelectNodes("//img[contains(@src,'graph/rarity/')]");
if (nodesRarity != null)
ProcessFieldByType(nodesRarity,card, CardFields.Rarity);
}
private void GetExtraSides(Card card, HtmlDocument html)
{
//SEE IF IT HAS EXTRA IMAGES
try
{
var nodeParent = html.DocumentNode.SelectSingleNode(".//div[@id='CardScanBack']");
if (nodeParent != null)
{
var nodeImage = nodeParent.SelectSingleNode(".//img");
string urlNewImage = nodeImage?.Attributes["src"].Value.ToString();
urlNewImage = ValidateAndFixUrl(urlNewImage);
if (!string.IsNullOrEmpty(urlNewImage))
{
card.AddExtraSide(new Card() { ImageUrl = urlNewImage });
}
}
}
catch
{ }
}
async override protected Task GetAdditionalInfoAsync(Card card)
{
//we do all of this in empty try catches because it is not mandatory information
try
{
HtmlDocument html = await GetHtmlDocumentFromUrlAsync(card.FullUrlWebSite);
//IMAGE
card.ImageUrl = GetImageUrlFromHtmlDoc(html);
GetExtraSides(card, html);
GetDetails(card, html);
//SEE IF IT HAS ALTERNATIVE ARTS/STYLE CARDS
try
{
for (int i = 1; i < 10; i++)
{
var resultNodes = html.DocumentNode.SelectNodes($"//text()[. = '{i}']");
if (resultNodes != null)
{
foreach (HtmlNode node in resultNodes)
{
var nodeParent = node.ParentNode;
if (nodeParent != null && nodeParent.Attributes.Count > 0 && nodeParent.Attributes["href"] != null)
{
var hrefAlternative = nodeParent.Attributes["href"].Value;
hrefAlternative = ValidateAndFixUrl(hrefAlternative);
var alternativeHtmlDoc = await GetHtmlDocumentFromUrlAsync(hrefAlternative);
var alernativeImage = GetImageUrlFromHtmlDoc(alternativeHtmlDoc);
if (!String.IsNullOrEmpty(alernativeImage))
{
Card alternativeCard = new() { FullUrlWebSite = hrefAlternative, ImageUrl = alernativeImage };
GetExtraSides(alternativeCard, alternativeHtmlDoc);
GetDetails(alternativeCard, alternativeHtmlDoc);
//small workarround to not cascade extra sides
card.AddExtraSide(alternativeCard);
for (int j = 0; j < alternativeCard.ExtraSides.Count; j++)
{
Card extraSideAlternative = alternativeCard.ExtraSides[j];
card.AddExtraSide(extraSideAlternative);
alternativeCard.ExtraSides.RemoveAt(j);
}
}
}
}
}
}
}
catch
{ }
}
catch
{ }
}
#endregion
}
} | vinimk/MagicNewCardsBotForTelegram | TaskersAndControllers/MTGPicsTasker.cs | C# | mit | 15,297 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Pickin.Models
{
public class PickinUser : IComparable
{
[Key]
public int PickinUserId { get; set; }
[Required]
public virtual ApplicationUser RealUser { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// ICollection, IEnumerable, IQueryable
public List<Tune> Tunes { get; set; }
public List<PickinUser> AllPickinUsers { get; set; }
public int CompareTo(object obj)
{
// sort user based on email because email is string AND...
// .NET knows how to compare strings already. ha!
// first need to explicitly cast from boject type to PickinUser type
PickinUser other_user = obj as PickinUser;
int answer = this.RealUser.Email.CompareTo(other_user.RealUser.Email);
return answer;
}
}
}
| jbrooks036/Pickin | Pickin/Models/PickinUser.cs | C# | mit | 1,050 |
/* --------------------------------------------------------------------------
*
* File MainScene.cpp
* Description
* Ported By Young-Hwan Mun
* Contact xmsoft77@gmail.com
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft.
* Copyright (c) 2012 喆 肖 (12/08/10). All rights reserved.
*
* --------------------------------------------------------------------------
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* -------------------------------------------------------------------------- */
#include "Precompiled.h"
#include "MainScene.h"
#include "Controllers/InputLayer.h"
enum
{
eTagLife = 1000 ,
eTagLevel ,
};
CCScene* MainScene::scene ( KDint nLevel, KDint nStatus, KDint nLife )
{
CCScene* pScene = CCScene::create ( );
MainScene* pLayer = new MainScene ( );
if ( pScene && pLayer && pLayer->initWithMapInformation ( nLevel, nStatus, nLife ) )
{
pLayer->autorelease ( );
pScene->addChild ( pLayer );
}
else
{
CC_SAFE_DELETE ( pScene );
CC_SAFE_DELETE ( pLayer );
}
return pScene;
}
MainScene::MainScene ( KDvoid )
{
m_pIconArray = KD_NULL;
}
MainScene::~MainScene ( KDvoid )
{
CC_SAFE_RELEASE ( m_pIconArray );
}
KDbool MainScene::initWithMapInformation ( KDint nLevel, KDint nStatus, KDint nLife )
{
if ( !CCLayer::initWithVisibleViewport ( ) )
{
return KD_FALSE;
}
const CCSize& tLyrSize = this->getContentSize ( );
SimpleAudioEngine::sharedEngine ( )->playEffect ( "Sounds/02 start.wav" );
CCLayerColor* pBackColor = CCLayerColor::create ( ccc4 ( 192, 192, 192, 255 ), tLyrSize );
this->addChild ( pBackColor );
CCSpriteFrameCache::sharedSpriteFrameCache ( )->addSpriteFramesWithFile ( "Images/images.plist" );
m_pIconArray = CCArray::create ( );
m_pIconArray->retain ( );
this->iconTank ( );
CCSprite* pLife = CCSprite::createWithSpriteFrameName ( "IP.png" );
pLife->setPosition ( ccp ( 30, tLyrSize.cy - 50 ) );
this->addChild ( pLife );
CCSprite* pLifeIcon = CCSprite::createWithSpriteFrameName ( "p1.png" );
pLifeIcon->setPosition ( ccp ( 20, tLyrSize.cy - 70 ) );
pLifeIcon->setScale ( 0.5f );
this->addChild ( pLifeIcon );
this->showLife ( nLife );
CCSprite* pFlag = CCSprite::createWithSpriteFrameName ( "flag.png" );
pFlag->setPosition ( ccp ( tLyrSize.cx - 50 , tLyrSize.cy - 200 ) );
this->addChild ( pFlag );
this->showLevel ( nLevel );
MapLayer* pMapLayer = MapLayer::create ( nLevel, nStatus, nLife );
pMapLayer->setDelegate ( this );
this->addChild ( pMapLayer );
InputLayer* pInputLayer = InputLayer::create ( );
pInputLayer->setMapLayer ( pMapLayer );
this->addChild ( pInputLayer );
return KD_TRUE;
}
//
// PrivateMethods
//
KDvoid MainScene::iconTank ( KDvoid )
{
const CCSize& tLyrSize = this->getContentSize ( );
CCSpriteFrame* pIconFrame = CCSpriteFrameCache::sharedSpriteFrameCache ( )->spriteFrameByName ( "enemy.png" );
KDint nWidth = 55;
KDint nHeight = 15;
for ( KDint i = 0; i < 10; i++ )
{
nHeight += 15;
CCSprite* pIconA = CCSprite::createWithSpriteFrame ( pIconFrame );
pIconA->setPosition ( ccp ( tLyrSize.cx - nWidth, tLyrSize.cy - nHeight ) );
this->addChild ( pIconA );
m_pIconArray->addObject ( pIconA );
CCSprite* pIconB = CCSprite::createWithSpriteFrame ( pIconFrame );
pIconB->setPosition ( ccp ( tLyrSize.cx - nWidth + 18, tLyrSize.cy - nHeight ) );
this->addChild ( pIconB );
m_pIconArray->addObject ( pIconB );
}
}
KDvoid MainScene::showLife ( KDint nLife )
{
const CCSize& tLyrSize = this->getContentSize ( );
this->removeChildByTag ( eTagLife );
CCLabelTTF* pLabel = CCLabelTTF::create ( ccszf ( "%d", nLife ), "Font/CourierBold.ttf", 20 );
pLabel->setColor ( ccc3 ( 0, 0, 0 ) );
pLabel->setPosition ( ccp ( 45, tLyrSize.cy - 70 ) );
this->addChild ( pLabel, 0, eTagLife );
}
KDvoid MainScene::showLevel ( KDint nLevel )
{
const CCSize& tLyrSize = this->getContentSize ( );
this->removeChildByTag ( eTagLevel );
CCLabelTTF* pLabel = CCLabelTTF::create ( ccszf ( "%d", nLevel ), "Font/CourierBold.ttf", 20 );
pLabel->setColor ( ccc3 ( 0, 0, 0 ) );
pLabel->setPosition ( ccp ( tLyrSize.cx - 40, tLyrSize.cy - 230 ) );
this->addChild ( pLabel, 0, eTagLevel );
}
//
// MapLayerDelegate methods
//
KDvoid MainScene::gameOver ( KDvoid )
{
}
KDvoid MainScene::bornEnmey ( KDvoid )
{
if ( m_pIconArray->count ( ) > 0 )
{
CCSprite* pIcon = (CCSprite*) m_pIconArray->lastObject ( );
pIcon->removeFromParent ( );
m_pIconArray->removeLastObject ( );
}
}
KDvoid MainScene::changeTankLife ( KDint nLife )
{
this->showLife ( nLife );
}
| mcodegeeks/OpenKODE-Framework | 04_Sample/BattleCity/Source/Views/MainScene.cpp | C++ | mit | 5,528 |
<?php
/**
* Класс User - предназначен для работы с учетными записями пользователей системы.
* Доступен из любой точки программы.
* Реализован в виде синглтона, что исключает его дублирование.
*
* @author Авдеев Марк <mark-avdeev@mail.ru>
* @package moguta.cms
* @subpackage Libraries
*/
class User {
static private $_instance = null;
private $auth = array();
static $accessStatus = array(0 => 'Разрешен', 1 => 'Заблокирован');
static $groupName = array(1 => 'Администратор', 2 => 'Пользователь', 3 => 'Менеджер', 4 => 'Модератор');
private function __construct() {
// Если пользователь был авторизован, то присваиваем сохраненные данные.
if (isset($_SESSION['user'])) {
if ($_SESSION['userAuthDomain'] == $_SERVER['SERVER_NAME']) {
$this->auth = $_SESSION['user'];
}
}
}
private function __clone() {
}
private function __wakeup() {
}
/**
* Возвращет единственный экземпляр данного класса.
* @return object - объект класса URL.
*/
static public function getInstance() {
if (is_null(self::$_instance)) {
self::$_instance = new self;
}
return self::$_instance;
}
/**
* Инициализирует объект данного класса User.
* @return void
*/
public static function init() {
self::getInstance();
}
/**
* Возвращает авторизированнго пользователя.
* @return void
*/
public static function getThis() {
return self::$_instance->auth;
}
/**
* Добавляет новую учетную запись пользователя в базу сайта.
* @param $userInfo - массив значений для вставки в БД [Поле => Значение].
* @return bool
*/
public static function add($userInfo) {
$result = false;
// Если пользователя с таким емайлом еще нет.
if (!self::getUserInfoByEmail($userInfo['email'])) {
$userInfo['pass'] = crypt($userInfo['pass']);
foreach ($array as $k => $v) {
if($k!=='pass'){
$array[$k] = htmlspecialchars_decode($v);
$array[$k] = htmlspecialchars($v);
}
}
if (DB::buildQuery('INSERT INTO `'.PREFIX.'user` SET ', $userInfo)) {
$id = DB::insertId();
$result = $id;
}
} else {
$result = false;
}
$args = func_get_args();
return MG::createHook(__CLASS__."_".__FUNCTION__, $result, $args);
}
/**
* Удаляет учетную запись пользователя из базы.
* @param $id id пользовате, чью запись следует удалить.
* @return void
*/
public static function delete($id) {
$res = DB::query('SELECT `role` FROM `'.PREFIX.'user` WHERE id = '.DB::quote($id));
$role = DB::fetchArray($res);
// Нельзя удалить первого пользователя, поскольку он является админом
if ($role['role'] == 1 ) {
$res = DB::query('SELECT `id` FROM `'.PREFIX.'user` WHERE `role` = 1');
if (DB::numRows($res) == 1 || $_SESSION['user']->id == $id) {
return false;
}
}
DB::query('DELETE FROM `'.PREFIX.'user` WHERE id = '.DB::quote($id));
return true;
}
/**
* Обновляет пользователя учетную запись пользователя.
* @param $id - id пользователя.
* @param $data - массив значений для вставки в БД [Поле => Значение].
* @param $authRewrite - false = перезапишет данные в сессии детущего пользователя, на полученные у $data.
* @return void
*/
public static function update($id, $data, $authRewrite = false) {
$userInfo = USER::getUserById($id);
foreach ($data as $k => $v) {
if($k!=='pass'){
$v = htmlspecialchars_decode($v);
$data[$k] = htmlspecialchars($v);
}
}
//только если пытаемся разжаловать админа, проверяем,
// не является ли он последним админом
// Без админов никак незя!
if ($userInfo->role == '1' && $data['role'] != '1') {
$countAdmin = DB::query('
SELECT count(id) as "count"
FROM `'.PREFIX.'user`
WHERE role = 1
');
if ($row = DB::fetchAssoc($countAdmin)) {
if ($row['count'] == 1) {// остался один админ
$data['role'] = 1; // не даем разжаловать админа, уж лучше плохой чем никакого :-)
}
}
}
DB::query('
UPDATE `'.PREFIX.'user`
SET '.DB::buildPartQuery($data).'
WHERE id = '.DB::quote($id));
if (!$authRewrite) {
foreach ($data as $k => $v) {
self::$_instance->auth->$k = $v;
}
$_SESSION['user'] = self::$_instance->auth;
}
return true;
}
/**
* Разлогинивает авторизованного пользователя.
* @param $id - id пользователя.
* @return void
*/
public static function logout() {
self::getInstance()->auth = null;
unset($_SESSION['user']);
unset($_SESSION['cart']);
unset($_SESSION['loginAttempt']);
unset($_SESSION['blockTimeStart']);
//Удаляем данные о корзине.
SetCookie('cart', '', time());
MG::redirect('/enter');
}
/**
* Аутентифицирует данные, с помощью криптографического алгоритма
* @param $email - емайл.
* @param $pass - пароль.
* @return bool
*/
public static function auth($email, $pass, $cap) {
// проверка заблокирована ли авторизация,
if (isset($_SESSION['blockTimeStart'])) {
$period = time() - $_SESSION['blockTimeStart'];
if ($period < 15 * 60) {
return false;
} else {
unset($_SESSION['loginAttempt']);
unset($_SESSION['blockTimeStart']);
}
}
$result = DB::query('
SELECT *
FROM `'.PREFIX.'user`
WHERE email = "%s"
', $email, $pass);
// если был введен код капчи,
if ($cap && (($cap == '') || (strtolower($cap) != strtolower($_SESSION['capcha'])))) {
$_SESSION['loginAttempt'] += 1;
return false;
}
if ($row = DB::fetchObject($result)) {
if ($row->pass == crypt($pass, $row->pass)) {
self::$_instance->auth = $row;
$_SESSION['userAuthDomain'] = $_SERVER['SERVER_NAME'];
$_SESSION['user'] = self::$_instance->auth;
$_SESSION['loginAttempt']='';
return true;
}
}
// если в настройках блокировка отменена, то количество попыток не суммируется.
$lockAuth = MG::getOption('lockAuthorization') == 'false' ? false : true;
if ($lockAuth) {
if (!isset($_SESSION['loginAttempt'])) {
$_SESSION['loginAttempt'] = 0;
}
$_SESSION['loginAttempt'] += 1;
}
return false;
}
/**
* Получает все данные пользователя из БД по ID.
* @param $id - пользователя.
* @return void
*/
public static function getUserById($id) {
$result = false;
$res = DB::query('
SELECT *
FROM `'.PREFIX.'user`
WHERE id = "%s"
', $id);
if ($row = DB::fetchObject($res)) {
$result = $row;
}
$args = func_get_args();
return MG::createHook(__CLASS__."_".__FUNCTION__, $result, $args);
}
/**
* Получает все данные пользователя из БД по email.
* @param $email - пользователя.
* @return void
*/
public static function getUserInfoByEmail($email) {
$result = false;
$res = DB::query('
SELECT *
FROM `'.PREFIX.'user`
WHERE email = "%s"
', $email);
if ($row = DB::fetchObject($res)) {
$result = $row;
}
$args = func_get_args();
return MG::createHook(__CLASS__."_".__FUNCTION__, $result, $args);
}
/**
* Проверяет, авторизован ли текущий пользователь.
* @return void
*/
public static function isAuth() {
if (self::getThis()) {
return true;
}
return false;
}
/**
* Получает список пользователей.
* @param $id - пользователя.
* @return void
*/
public static function getListUser() {
$result = false;
$res = DB::query('
SELECT *
FROM `'.PREFIX.'user`
', $id);
while ($row = DB::fetchObject($res)) {
$result[] = $row;
}
$args = func_get_args();
return MG::createHook(__CLASS__."_".__FUNCTION__, $result, $args);
}
/**
* Проверяет права пользователя на выполнение ajax запроса.
* @param string $roleMask - строка с перечисленными ролями, которые имеют доступ,
* если параметр не передается, то доступ открыт для всех.
* 1 - администратор,
* 2 - пользователь,
* 3 - менеджер,
* 4 - модератор
* @return bool or exit;
*/
public static function AccessOnly($roleMask="1,2,3,4",$exit=null) {
$thisRole = empty(self::getThis()->role)?'2':self::getThis()->role;
if(strpos($roleMask,(string)$thisRole)!==false){
return true;
}
// мод для аяксовых запросов.
if($exit){
exit();
}
return false;
}
/**
* Возвращает дату последней регистрации пользователя
* @return array
*/
public function getMaxDate() {
$res = DB::query('
SELECT MAX(date_add) as res
FROM `'.PREFIX.'user`');
if ($row = DB::fetchObject($res)) {
$result = $row->res;
}
return $result;
}
/**
* Возвращает дату первой регистрации пользователя.
* @return array
*/
public function getMinDate() {
$res = DB::query('
SELECT MIN(date_add) as res
FROM `'.PREFIX.'user`'
);
if ($row = DB::fetchObject($res)) {
$result = $row->res;
}
return $result;
}
/**
* Получает все email пользователя из БД
*
*/
public static function searchEmail($email) {
$result = false;
$res = DB::query('
SELECT `email`
FROM `'.PREFIX.'user`
WHERE email LIKE '.$email.'%');
if ($row = DB::fetchObject($res)) {
$result = $row;
}
return $result;
}
} | hlogeon/autoryad | mg-core/lib/user.php | PHP | mit | 11,648 |
/**
* @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 |
<!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 |
// 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 |
<?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 |