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 |
|---|---|---|---|---|---|
<?php
namespace AmsterdamPHP\JobBundle\Form;
use AmsterdamPHP\JobBundle\Form\ChoiceList\ContractType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class JobType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('languageOfAd', 'choice', array(
'label' => 'Language',
'choices' => array('en' => 'English', 'nl' => 'Dutch')
))
->add('description', 'ckeditor', array(
'config' => array(
'toolbar' => array(
array(
'name' => 'basicstyles',
'items' => array('Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat')
),
array(
'name' => 'paragraph',
'items' => array('NumberedList', 'BulletedList', '-','Outdent','Indent')
),
array(
'name' => 'links',
'items' => array('Link', 'Unlink')
)
),
)
))
->add('contractType', 'choice', array(
'label' => 'Type of contract',
'choice_list' => new ContractType()
))
->add('location')
->add('salary', 'text', array(
'required' => false
))
->add('url', 'url', array(
'required' => false
))
->add('expires', 'date', array( 'data' => new \DateTime("+1 month")))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AmsterdamPHP\JobBundle\Entity\Job'
));
}
public function getName()
{
return 'amsterdamphp_jobbundle_jobtype';
}
}
| AmsterdamPHP/job-board | src/AmsterdamPHP/JobBundle/Form/JobType.php | PHP | mit | 2,149 |
namespace OmniXaml.Typing
{
using System;
using System.Collections.Generic;
using System.Reflection;
using Glass.Core;
public class MetadataProvider
{
private readonly IDictionary<string, AutoKeyDictionary<Type, object>> lookupDictionaries = new Dictionary<string, AutoKeyDictionary<Type, object>>();
public void Register(Type type, Metadata medataData)
{
foreach (var propertyInfo in medataData.GetType().GetRuntimeProperties())
{
var dic = GetDictionary(propertyInfo.Name);
var value = propertyInfo.GetValue(medataData);
if (value != null)
{
dic.Add(type, value);
}
}
}
private AutoKeyDictionary<Type, object> GetDictionary(string name)
{
AutoKeyDictionary<Type, object> dic;
var hadValue = lookupDictionaries.TryGetValue(name, out dic);
if (hadValue)
{
return dic;
}
var autoKeyDictionary = new AutoKeyDictionary<Type, object>(t => t.GetTypeInfo().BaseType, t => t != null);
lookupDictionaries.Add(name, autoKeyDictionary);
return autoKeyDictionary;
}
public Metadata Get(Type type)
{
var metadata = new Metadata();
foreach (var prop in MedataProperties)
{
AutoKeyDictionary<Type, object> dic;
var hadDictionary = lookupDictionaries.TryGetValue(prop.Name, out dic);
if (hadDictionary)
{
object value;
var hadValue = dic.TryGetValue(type, out value);
if (hadValue)
{
prop.SetValue(metadata, value);
}
else
{
prop.SetValue(metadata, null);
}
}
else
{
prop.SetValue(metadata, null);
}
}
return metadata;
}
private static IEnumerable<PropertyInfo> MedataProperties => typeof(Metadata).GetRuntimeProperties();
}
} | Perspex/OmniXAML | Source/OmniXaml/Typing/MetadataProvider.cs | C# | mit | 2,302 |
/****************************************************************************
** Copyright (c) quickfixengine.org All rights reserved.
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact ask@quickfixengine.org if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/
#include "stdafx.h"
#include "Log.h"
namespace FIX
{
Mutex ScreenLog::s_mutex;
Log* ScreenLogFactory::create()
{
bool incoming, outgoing, event;
init( m_settings.get(), incoming, outgoing, event );
return new ScreenLog( incoming, outgoing, event );
}
Log* ScreenLogFactory::create( const SessionID& sessionID )
{
Dictionary settings;
if( m_settings.has(sessionID) )
settings = m_settings.get( sessionID );
bool incoming, outgoing, event;
init( settings, incoming, outgoing, event );
return new ScreenLog( sessionID, incoming, outgoing, event );
}
void ScreenLogFactory::init( const Dictionary& settings, bool& incoming, bool& outgoing, bool& event )
{
if( m_useSettings )
{
incoming = true;
outgoing = true;
event = true;
if( settings.has(SCREEN_LOG_SHOW_INCOMING) )
incoming = settings.getBool(SCREEN_LOG_SHOW_INCOMING);
if( settings.has(SCREEN_LOG_SHOW_OUTGOING) )
outgoing = settings.getBool(SCREEN_LOG_SHOW_OUTGOING);
if( settings.has(SCREEN_LOG_SHOW_EVENTS) )
event = settings.getBool(SCREEN_LOG_SHOW_EVENTS);
}
else
{
incoming = m_incoming;
outgoing = m_outgoing;
event = m_event;
}
}
void ScreenLogFactory::destroy( Log* pLog )
{
delete pLog;
}
} //namespace FIX
| SoftFx/FDK | FDK/QuickFix/Log.cpp | C++ | mit | 2,071 |
// --------------------------------------------
// Copyright KAPSARC. Open source MIT License.
// --------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2015 King Abdullah Petroleum Studies and Research Center
//
// 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.
// --------------------------------------------
//
// Demonstrate a very basic, but highly parameterizable, model of committee selection
//
// --------------------------------------------
#include <cstdio>
#include <string>
#include <vector>
#include "kutils.h"
#include "kmatrix.h"
#include "prng.h"
#include "kmodel.h"
#include "smp.h"
#include "comsel.h"
#include "democomsel.h"
using namespace std;
using KBase::VUI;
using KBase::PRNG;
using KBase::KMatrix;
using KBase::Actor;
using KBase::Model;
using KBase::Position;
using KBase::State;
using KBase::VotingRule;
namespace DemoComSel {
using std::function;
using std::get;
using std::string;
using KBase::ReportingLevel;
using KBase::MtchPstn;
using ComSelLib::CSModel;
using ComSelLib::CSActor;
using ComSelLib::CSState;
using ComSelLib::intToVB;
using ComSelLib::vbToInt;
// -------------------------------------------------
// like printVUI, but with range-checking and boolean output
string printCS(const VUI& v) {
unsigned int n = v.size();
string cs("[CS ");
for (unsigned int i = 0; i < n; i++) {
switch (v[i]) {
case 0:
cs += "-";
break;
case 1:
cs += "+";
break;
default:
LOG(INFO) << "printCS:: unrecognized case";
exit(-1);
break;
}
}
cs += "]";
return cs;
}
void demoActorUtils(const uint64_t s, PRNG* rng) {
LOG(INFO) << KBase::getFormattedString("Using PRNG seed: %020llu", s);
rng->setSeed(s);
return;
}
void demoCSC(unsigned int numA, unsigned int nDim,
bool cpP, bool siP, const uint64_t s) {
// need a template for ...
// position type (each is a committee)
// utility to an actor of a position (committee)
// getting actor's scalar capability
LOG(INFO) << KBase::getFormattedString("Using PRNG seed: %020llu", s);
auto trng = new PRNG();
trng->setSeed(s);
if (0 == numA) { numA = 2 + (trng->uniform() % 4); } // i.e. [2,6] inclusive
if (0 == nDim) { nDim = 1 + (trng->uniform() % 7); } // i.e. [1,7] inclusive
LOG(INFO) << "Num parties:" << numA;
LOG(INFO) << "Num dimensions:" << nDim;
unsigned int numItm = numA;
unsigned int numCat = 2; // out or in, respectively
unsigned int numPos = exp2(numA); // i.e. numCat ^^ numItm
vector<VUI> positions = {};
for (unsigned int i = 0; i < numPos; i++) {
const VUI vbi = intToVB(i, numA);
const unsigned int j = vbToInt(vbi);
assert(j == i);
const VUI vbj = intToVB(j, numA);
assert(vbj == vbi);
positions.push_back(vbi);
}
assert(numPos == positions.size());
LOG(INFO) << "Num positions:" << numPos;
auto ndfn = [](string ns, unsigned int i) {
auto ali = KBase::newChars(10 + ((unsigned int)(ns.length())));
std::sprintf(ali, "%s%i", ns.c_str(), i);
auto s = string(ali);
delete ali;
ali = nullptr;
return s;
};
// create a model to hold some random actors
auto csm = new CSModel(nDim, "csm0", s);
LOG(INFO) << "Configuring actors: randomizing";
for (unsigned int i = 0; i < numA; i++) {
auto ai = new CSActor(ndfn("csa-", i), ndfn("csaDesc-", i), csm);
ai->randomize(csm->rng, nDim);
csm->addActor(ai);
}
assert(csm->numAct == numA);
csm->numItm = numA;
assert(csm->numCat == 2);
if ((9 == numA) && (2 == nDim)) {
for (unsigned int i = 0; i < 3; i++) {
auto ci = KMatrix::uniform(csm->rng, nDim, 1, 0.1, 0.9);
for (unsigned int j = 0; j < 3; j++) {
auto ej = KMatrix::uniform(csm->rng, nDim, 1, -0.05, +0.05);
const KMatrix pij = clip(ci + ej, 0.0, 1.0);
unsigned int n = (3 * i) + j;
auto an = ((CSActor *)(csm->actrs[n]));
an->vPos = VctrPstn(pij);
}
}
}
LOG(INFO) << "Scalar positions of actors (fixed) ...";
for (auto a : csm->actrs) {
auto csa = ((CSActor*)a);
LOG(INFO) << csa->name << "v-position:";
trans(csa->vPos).mPrintf(" %5.2f");
LOG(INFO) << a->name << "v-salience:";
trans(csa->vSal).mPrintf(" %5.2f");
}
LOG(INFO) << "Getting scalar strength of actors ...";
KMatrix aCap = KMatrix(1, csm->numAct);
for (unsigned int i = 0; i < csm->numAct; i++) {
auto ai = ((const CSActor *)(csm->actrs[i]));
aCap(0, i) = ai->sCap;
}
aCap = (100.0 / sum(aCap)) * aCap;
LOG(INFO) << "Scalar strengths:";
for (unsigned int i = 0; i < csm->numAct; i++) {
auto ai = ((CSActor *)(csm->actrs[i]));
ai->sCap = aCap(0, i);
LOG(INFO) << KBase::getFormattedString("%3i %6.2f", i, ai->sCap);
}
LOG(INFO) << "Computing utilities of positions ... ";
for (unsigned int i = 0; i < numA; i++) {
// (0,0) causes computation of entire table
double uii = csm->getActorCSPstnUtil(i, i);
}
// At this point, we have almost a generic enumerated model,
// so much of the code below should be easily adaptable to EModel.
// rows are actors, columns are all possible position
KMatrix uij = KMatrix(numA, numPos);
LOG(INFO) << "Complete (normalized) utility matrix of all possible positions (rows)"
<<" versus actors (columns)";
string utilMtx;
for (unsigned int pj = 0; pj < numPos; pj++) {
utilMtx += std::to_string(pj) + " ";
auto pstn = positions[pj];
utilMtx += printCS(pstn) + " ";
for (unsigned int ai = 0; ai < numA; ai++) {
const double uap = csm->getActorCSPstnUtil(ai, pj);
uij(ai, pj) = uap;
utilMtx += KBase::getFormattedString("%6.4f, ", uap);
}
}
LOG(INFO) << utilMtx;
LOG(INFO) << "Computing best position for each actor";
vector<VUI> bestAP = {}; // list of each actor's best position (followed by CP)
for (unsigned int ai = 0; ai < numA; ai++) {
unsigned int bestJ = 0;
double bestV = 0;
for (unsigned int pj = 0; pj < numPos; pj++) {
if (bestV < uij(ai, pj)) {
bestJ = pj;
bestV = uij(ai, pj);
}
}
LOG(INFO) << "Best for" << ai << "is" << bestJ << " " << printCS(positions[bestJ]);
bestAP.push_back(positions[bestJ]);
}
trans(aCap).mPrintf("%5.2f ");
// which happens to indicate the PCW *if* proportional voting,
// when we actually use PropBin
LOG(INFO) << "Computing zeta ... ";
KMatrix zeta = aCap * uij;
assert((1 == zeta.numR()) && (numPos == zeta.numC()));
LOG(INFO) << "Sorting positions from most to least net support ...";
auto betterPR = [](tuple<unsigned int, double, VUI> pr1,
tuple<unsigned int, double, VUI> pr2) {
double v1 = get<1>(pr1);
double v2 = get<1>(pr2);
bool better = (v1 > v2);
return better;
};
auto pairs = vector<tuple<unsigned int, double, VUI>>();
for (unsigned int i = 0; i < numPos; i++) {
auto pri = tuple<unsigned int, double, VUI>(i, zeta(0, i), positions[i]);
pairs.push_back(pri);
}
sort(pairs.begin(), pairs.end(), betterPR);
const unsigned int maxDisplayed = 256;
unsigned int numPr = (pairs.size() < maxDisplayed) ? pairs.size() : maxDisplayed;
LOG(INFO) << "Displaying highest " << numPr;
for (unsigned int i = 0; i < numPr; i++) {
auto pri = pairs[i];
unsigned int ni = get<0>(pri);
double zi = get<1>(pri);
VUI pi = get<2>(pri);
LOG(INFO) << KBase::getFormattedString(" %3u: %4u %7.2f ", i, ni, zi)
<< printCS(pi);
}
VUI bestCS = get<2>(pairs[0]);
bestAP.push_back(bestCS); // last one is the CP
auto css0 = new CSState(csm);
csm->addState(css0);
assert(numA == css0->pstns.size()); // pre-allocated by constructor, all nullptr's
// Either start them all at the CP or have each choose an initial position which
// maximizes their direct utility, regardless of expected utility.
for (unsigned int i = 0; i < numA; i++) {
auto pi = new MtchPstn();
pi->numCat = numCat;
pi->numItm = numItm;
if (cpP) {
pi->match = bestCS;
}
if (siP) {
pi->match = bestAP[i];
}
css0->pstns[i] = pi;
assert(numA == css0->pstns.size()); // must be invariant
}
css0->step = [css0]() {
return css0->stepSUSN();
};
unsigned int maxIter = 1000;
csm->stop = [maxIter, csm](unsigned int iter, const KBase::State * s) {
bool doneP = iter > maxIter;
if (doneP) {
LOG(INFO) << "Max iteration limit of" << maxIter << "exceeded";
}
auto s2 = ((const CSState *)(csm->history[iter]));
for (unsigned int i = 0; i < iter; i++) {
auto s1 = ((const CSState *)(csm->history[i]));
if (CSModel::equivStates(s1, s2)) {
doneP = true;
LOG(INFO) << "State number" << iter << "matched state number" << i;
}
}
return doneP;
};
css0->setUENdx();
csm->run();
return;
}
} // end of namespace
int main(int ac, char **av) {
using std::string;
using KBase::dSeed;
el::Configurations confFromFile("./comsel-logger.conf");
el::Loggers::reconfigureAllLoggers(confFromFile);
auto sTime = KBase::displayProgramStart(DemoComSel::appName, DemoComSel::appVersion);
uint64_t seed = dSeed; // arbitrary
bool run = true;
bool cpP = false;
bool siP = true;
auto showHelp = []() {
printf("\n");
printf("Usage: specify one or more of these options\n");
printf("--cp start each actor from the central position \n");
printf("--si start each actor from their most self-interested position \n");
printf(" If neither cp nor si are specified, it will use si \n");
printf(" If both cp and si are specified, it will use the second specified \n");
printf("--help print this message \n");
printf("--seed <n> set a 64bit seed \n");
printf(" 0 means truly random \n");
printf(" default: %020llu \n", dSeed);
};
// tmp args
// seed = 0;
if (ac > 1) {
for (int i = 1; i < ac; i++) {
if (strcmp(av[i], "--seed") == 0) {
i++;
seed = std::stoull(av[i]);
}
else if (strcmp(av[i], "--cp") == 0) {
siP = false;
cpP = true;
}
else if (strcmp(av[i], "--si") == 0) {
cpP = false;
siP = true;
}
else if (strcmp(av[i], "--help") == 0) {
run = false;
}
else {
run = false;
printf("Unrecognized argument %s\n", av[i]);
}
}
}
if (!run) {
showHelp();
return 0;
}
if (0 == seed) {
PRNG * rng = new PRNG();
seed = rng->setSeed(0); // 0 == get a random number
delete rng;
rng = nullptr;
}
LOG(INFO) << KBase::getFormattedString("Using PRNG seed: %020llu", seed);
LOG(INFO) << KBase::getFormattedString("Same seed in hex: 0x%016llX", seed);
LOG(INFO) << "Creating objects from SMPLib ... ";
auto sm = new SMPLib::SMPModel("", seed); // , "SMPScen-010101"
auto sa = new SMPLib::SMPActor("Bob", "generic spatial actor");
delete sm;
sm = nullptr;
delete sa;
sa = nullptr;
LOG(INFO) << "Done creating objects from SMPLib.";
// note that we reset the seed every time, so that in case something
// goes wrong, we need not scroll back too far to find the
// seed required to reproduce the bug.
DemoComSel::demoCSC(9, // actors trying to get onto committee
2, // issues to be addressed by the committee
cpP, siP,
seed);
KBase::displayProgramEnd(sTime);
return 0;
}
// --------------------------------------------
// Copyright KAPSARC. Open source MIT License.
// --------------------------------------------
| ambah/KTAB | examples/comsel/src/democomsel.cpp | C++ | mit | 13,110 |
/*
* This file is part of Flow Engine, licensed under the MIT License (MIT).
*
* Copyright (c) 2013 Spout LLC <http://www.spout.org/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.flowpowered.engine.network.handler;
import com.flowpowered.api.Server;
import com.flowpowered.engine.network.FlowSession;
import com.flowpowered.networking.Message;
import com.flowpowered.networking.MessageHandler;
public class FlowMessageHandler<T extends Message> implements MessageHandler<FlowSession, T> {
@Override
public void handle(FlowSession session, T message) {
if (session.getEngine().get(Server.class) != null) {
handle0(session, message, true);
} else {
handle0(session, message, false);
}
}
public void handle0(FlowSession session, T message, boolean server) {
if (session.getPlayer() == null) {
switch (requiresPlayer()) {
case ERROR:
throw new UnsupportedOperationException("Handler " + getClass() + " requires a player, but it was null!");
case IGNORE:
System.out.println("Ignoring handler b/c no player");
return;
}
}
if (server) {
handleServer(session, message);
} else {
handleClient(session, message);
}
}
public void handleServer(FlowSession session, T message) {
throw new UnsupportedOperationException("This handler cannot handle on the server!");
}
public void handleClient(FlowSession session, T message) {
throw new UnsupportedOperationException("This handler cannot handle on the client!");
}
public PlayerRequirement requiresPlayer() {
return PlayerRequirement.NO;
}
public enum PlayerRequirement {
NO,
IGNORE,
ERROR
}
}
| flow/engine | src/main/java/com/flowpowered/engine/network/handler/FlowMessageHandler.java | Java | mit | 2,915 |
package com.joao.pedro.nardari.locationstrategysampleproject;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scheduleTask(View v) {
// Set time to alert user
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 7);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
// Create Intent
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
// Register
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
pendingIntent
);
Toast.makeText(this, "Task Scheduled!",Toast.LENGTH_LONG).show();
}
}
| joaopedronardari/LocationStrategySampleProject | app/src/main/java/com/joao/pedro/nardari/locationstrategysampleproject/MainActivity.java | Java | mit | 1,526 |
namespace InControl
{
using System;
using System.IO;
using UnityEngine;
public class MouseBindingSource : BindingSource
{
public Mouse Control { get; protected set; }
public static float ScaleX = 0.05f;
public static float ScaleY = 0.05f;
public static float ScaleZ = 0.05f;
internal MouseBindingSource()
{
}
public MouseBindingSource( Mouse mouseControl )
{
Control = mouseControl;
}
// Unity doesn't allow mouse buttons above certain numbers on
// some platforms. For example, the limit on Windows 7 appears
// to be 6.
internal static bool SafeGetMouseButton( int button )
{
try
{
return Input.GetMouseButton( button );
}
catch (ArgumentException)
{
}
return false;
}
// This is necessary to maintain backward compatibility. :(
readonly static int[] buttonTable = new[] {
-1, 0, 1, 2, -1, -1, -1, -1, -1, -1, 3, 4, 5, 6, 7, 8
};
internal static bool ButtonIsPressed( Mouse control )
{
var button = buttonTable[(int) control];
if (button >= 0)
{
return SafeGetMouseButton( button );
}
return false;
}
public override float GetValue( InputDevice inputDevice )
{
var button = buttonTable[(int) Control];
if (button >= 0)
{
return SafeGetMouseButton( button ) ? 1.0f : 0.0f;
}
switch (Control)
{
case Mouse.NegativeX:
return -Mathf.Min( Input.GetAxisRaw( "mouse x" ) * ScaleX, 0.0f );
case Mouse.PositiveX:
return Mathf.Max( 0.0f, Input.GetAxisRaw( "mouse x" ) * ScaleX );
case Mouse.NegativeY:
return -Mathf.Min( Input.GetAxisRaw( "mouse y" ) * ScaleY, 0.0f );
case Mouse.PositiveY:
return Mathf.Max( 0.0f, Input.GetAxisRaw( "mouse y" ) * ScaleY );
case Mouse.NegativeScrollWheel:
return -Mathf.Min( Input.GetAxisRaw( "mouse z" ) * ScaleZ, 0.0f );
case Mouse.PositiveScrollWheel:
return Mathf.Max( 0.0f, Input.GetAxisRaw( "mouse z" ) * ScaleZ );
}
return 0.0f;
}
public override bool GetState( InputDevice inputDevice )
{
return Utility.IsNotZero( GetValue( inputDevice ) );
}
public override string Name
{
get
{
return Control.ToString();
}
}
public override string DeviceName
{
get
{
return "Mouse";
}
}
public override bool Equals( BindingSource other )
{
if (other == null)
{
return false;
}
var bindingSource = other as MouseBindingSource;
if (bindingSource != null)
{
return Control == bindingSource.Control;
}
return false;
}
public override bool Equals( object other )
{
if (other == null)
{
return false;
}
var bindingSource = other as MouseBindingSource;
if (bindingSource != null)
{
return Control == bindingSource.Control;
}
return false;
}
public override int GetHashCode()
{
return Control.GetHashCode();
}
public override BindingSourceType BindingSourceType
{
get
{
return BindingSourceType.MouseBindingSource;
}
}
internal override void Save( BinaryWriter writer )
{
writer.Write( (int) Control );
}
internal override void Load( BinaryReader reader )
{
Control = (Mouse) reader.ReadInt32();
}
}
}
| Hekaton/SolarWind | Assets/InControl/Source/Binding/MouseBindingSource.cs | C# | mit | 3,202 |
package com.github.kennedyoliveira.asteriskjava.khomp.manager.event;
import org.asteriskjava.manager.event.ManagerEvent;
/**
* Reports the detection of a {@code Collect Call}.
*
* @author kennedy
*/
public class CollectCallEvent extends ManagerEvent {
private String channel;
public CollectCallEvent(Object source) {
super(source);
}
/**
* @return The channel name in the format {@code Khomp/BxCy} where {@code x} is the Device ID and {@code y} is the Channel Number.
*/
public String getChannel() {
return channel;
}
/**
* Internal use.
*
* @param channel The channel name in the format {@code Khomp/BxCy} where {@code x} is the Device ID and {@code y} is the Channel Number.
*/
public void setChannel(String channel) {
this.channel = channel;
}
}
| kennedyoliveira/asterisk-java-khomp | src/main/java/com/github/kennedyoliveira/asteriskjava/khomp/manager/event/CollectCallEvent.java | Java | mit | 807 |
using AppCampus.Domain.Interfaces.Repositories;
using System;
using System.ComponentModel.DataAnnotations;
namespace AppCampus.PortalApi.Validation.ValidationAttributes
{
public sealed class UniqueCompanyIdAttribute : ValidationAttribute
{
public ICompanyRepository CompanyRepository { get; set; }
public UniqueCompanyIdAttribute()
: base("Company Id does not exist.")
{
CompanyRepository = (ICompanyRepository)Startup.HttpConfiguration.DependencyResolver.GetService(typeof(ICompanyRepository));
}
public override bool IsValid(object value)
{
return CompanyRepository.Find(Guid.Parse(value.ToString())) == null;
}
}
} | hendrikdelarey/appcampus | AppCampus.PortalApi/Validation/ValidationAttributes/UniqueCompanyIdAttribute.cs | C# | mit | 727 |
'use strict';
(function(module) {
const repos = {};
repos.all = [];
repos.requestRepos = function(callback) {
$.get('/github/user/repos')
.then(data => repos.all = data, err => console.error(err))
.then(callback(repos));
};
repos.with = attr => repos.all.filter(repo => repo[attr]);
module.repos = repos;
})(window);
| Jamesbillard12/jamesPortfolio | public/js/repo.js | JavaScript | mit | 347 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameScene : MonoBehaviour {
void Start () {
GameController gameController = GameController.Instance;
ItemSpawnManager itemSpawnManager = ItemSpawnManager.Instance;
RespawnManager respawnManager = RespawnManager.Instance;
gameController.BeginGame();
}
void Update () {
}
}
| sasvdw/LD37 | Unity/LD37/Assets/Scripts/Scenes/GameScene.cs | C# | mit | 411 |
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthenticationService, AlertService } from '../services';
import { DttType } from '../models';
import 'rxjs/add/operator/map'
@Injectable()
export class DttTypeService {
constructor(private http: Http, private authService: AuthenticationService) { }
private apiEndpointUrl: string = '/api/dttTypes';
create(dttType: DttType) {
// add authorization header with jwt token
let headers = new Headers({ 'Authorization': this.authService.token });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.apiEndpointUrl, dttType, options)
.map((response: Response) => {
// login successful if there's a jwt token in the response
let dttType = response.json();
if (dttType) {
return dttType;
}
});
}
update(dttType: DttType) {
// add authorization header with jwt token
let headers = new Headers({ 'Authorization': this.authService.token });
let options = new RequestOptions({ headers: headers });
return this.http.put(this.apiEndpointUrl + '/' + dttType._id, dttType, options)
.map((response: Response) => {
// update successful - return dttType
let dttType = response.json();
if (dttType) {
return dttType;
}
});
}
list(query:string) {
// add authorization header with jwt token
let headers = new Headers({ 'Authorization': this.authService.token });
let options = new RequestOptions({ headers: headers });
query = query && query.length > 0 ? '?' + query : '';
return this.http.get(this.apiEndpointUrl + query, options)
.map((response: Response) => {
// login successful if there's a jwt token in the response
let dttTypes = response.json() as Array<DttType>;
return dttTypes;
});
}
get(id: string) {
// add authorization header with jwt token
let headers = new Headers({ 'Authorization': this.authService.token });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.apiEndpointUrl + '/' + id, options)
.map((response: Response) => {
// login successful if there's a jwt token in the response
let dttType = response.json() as DttType;
return dttType;
});
}
delete(id: string) {
// add authorization header with jwt token
let headers = new Headers({ 'Authorization': this.authService.token });
let options = new RequestOptions({ headers: headers });
return this.http.delete(this.apiEndpointUrl + '/' + id, options)
.map((response: Response) => {
let dttType = response.json() as DttType;
return dttType;
});
}
}
| manuelnelson/patient-pal | src/client/services/dtt-type.service.ts | TypeScript | mit | 3,176 |
<?php
namespace Tangent\Bundle\BookTrackerBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('TangentBookTrackerBundle:Default:index.html.twig', array('name' => $name));
}
}
| gump/book-tracker | src/Tangent/Bundle/BookTrackerBundle/Controller/DefaultController.php | PHP | mit | 332 |
package com.grapapp.grapapp.adapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.grapapp.grapapp.R;
import com.grapapp.grapapp.activity.TupianBaseActivity;
import com.grapapp.grapapp.models.TupianTitleModel;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by ian on 16/4/16.
*/
public class TupianTitleAdapter extends RecyclerView.Adapter<TupianTitleAdapter.NormalTextViewHolder> {
private final LayoutInflater mLayoutInflater;
private final Context mContext;
private final List<TupianTitleModel> list;
public TupianTitleAdapter(Context context, List<TupianTitleModel> list1) {
mContext = context;
this.list = list1;
mLayoutInflater = LayoutInflater.from(context);
}
@Override
public NormalTextViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new NormalTextViewHolder(mLayoutInflater.inflate(R.layout.adapter_tupiantitle_line, parent, false));
}
@Override
public void onBindViewHolder(NormalTextViewHolder holder, int position) {
holder.mTextView.setText(list.get(position).getTitle());
holder.mTextView.setTag(list.get(position).getPath().toString());
}
@Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
public class NormalTextViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.text_view)
TextView mTextView;
NormalTextViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
@OnClick(R.id.text_view) void titleClick(View view) {
// TODO call server...
Log.d("NormalTextViewHolder", "onClick--> position = " + getPosition());
String path = view.getTag().toString();
Bundle b = new Bundle();
b.putString("path",path);
Intent i=new Intent();
i.setClass(mContext, TupianBaseActivity.class);
i.putExtras(b);
mContext.startActivity(i);
}
}
} | Hz-Ryze/GrapApp | app/src/main/java/com/grapapp/grapapp/adapter/TupianTitleAdapter.java | Java | mit | 2,351 |
require_relative 'gluey/base/version'
require_relative 'gluey/base/exceptions'
# environments
require_relative 'gluey/base/environment'
require_relative 'gluey/workshop/workshop'
require_relative 'gluey/warehouse/warehouse'
# addons
require_relative 'gluey/base/rack_mountable'
| doooby/gluey | lib/gluey.rb | Ruby | mit | 281 |
<?php
namespace Somnambulist\Tenancy\Tests\Stubs\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('em', function ($app) {
return new class {
function getClassMetadata()
{
return [];
}
};
});
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
| dave-redfern/laravel-doctrine-tenancy | tests/Stubs/Providers/AppServiceProvider.php | PHP | mit | 644 |
<?php
namespace SiteBundle\Repository;
/**
* TagRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class UserGroupRepository extends \Doctrine\ORM\EntityRepository
{
}
| firestorm23/gyrolab-ste | src/SiteBundle/Repository/UserGroupRepository.php | PHP | mit | 236 |
<table >
<?php
$rq = "SELECT acquisto,utente,colloquio FROM acquisti_aperti join utenti using(utente)";
$trs = $db -> query($rq) -> fetchAll(PDO::FETCH_ASSOC);
?>
<?php
foreach ($trs as $k => $q) {
echo "<td style=\"width:1em\" >
<form name=input action=\"cassa.php\" method=POST>
<input type = hidden name= acquisto value={$q['acquisto']}>
<button type=submit value=\"" ;
echo "{$q['colloquio']}/{$q['utente']}";
echo "\">";
echo "{$q['colloquio']} / {$q['utente']}";
echo "</button> </form></td>" ;
}
if ($_SESSION['acquisto'] == "") {
$_SESSION['acquisto'] = $trs[0]['acquisto'];
$_SESSION['utenteacquisto'] =$trs[0]['utente'];
}
?>
</table>
| paolino/emporio | selezioneacquisto.php | PHP | mit | 702 |
package com.swallow.core.dom;
import org.w3c.dom.Element;
/**
* Swallow 2017-03-10 15:33
*/
public interface ElementUtil {
static String getAttributeValue(Element element, String name, String defaultValue) {
String value = element.getAttribute(name);
if (!(value == null || "".equals(value))) {
return value;
}
return defaultValue;
}
static Integer getAttributeValue(Element element, String name, Integer defaultValue) {
String value = element.getAttribute(name);
if (!(value == null || "".equals(value))) {
return Integer.parseInt(value);
}
return defaultValue;
}
}
| zhuzaixiaoshulin/swallow | src/main/java/com/swallow/core/dom/ElementUtil.java | Java | mit | 676 |
using System.Collections.Generic;
namespace Magnesium.OpenGL.Internals
{
public class GLNextPipelineLayout : IGLPipelineLayout
{
public GLUniformBinding[] Bindings { get; private set; }
public int NoOfBindingPoints { get; private set; }
public IDictionary<int, GLBindingPointOffsetInfo> Ranges { get; private set; }
public uint NoOfStorageBuffers { get; private set; }
public uint NoOfExpectedDynamicOffsets { get; private set; }
public GLDynamicOffsetInfo[] OffsetDestinations { get; private set; }
public GLNextPipelineLayout(MgPipelineLayoutCreateInfo pCreateInfo)
{
if (pCreateInfo.SetLayouts.Length == 1)
{
var layout = (IGLDescriptorSetLayout)pCreateInfo.SetLayouts[0];
Bindings = layout.Uniforms;
}
else
{
Bindings = new GLUniformBinding[0];
}
NoOfBindingPoints = 0;
NoOfStorageBuffers = 0;
NoOfExpectedDynamicOffsets = 0;
Ranges = new SortedDictionary<int, GLBindingPointOffsetInfo>();
OffsetDestinations = ExtractBindingsInformation();
SetupOffsetRangesByBindings();
}
private GLDynamicOffsetInfo[] ExtractBindingsInformation()
{
var signPosts = new List<GLDynamicOffsetInfo>();
// build flat slots array for uniforms
foreach (var desc in Bindings)
{
if (desc.DescriptorType == MgDescriptorType.UNIFORM_BUFFER
|| desc.DescriptorType == MgDescriptorType.UNIFORM_BUFFER_DYNAMIC)
{
NoOfBindingPoints += (int) desc.DescriptorCount;
Ranges.Add((int) desc.Binding,
new GLBindingPointOffsetInfo
{
Binding = desc.Binding,
First = 0,
Last = (int) desc.DescriptorCount - 1
});
if (desc.DescriptorType == MgDescriptorType.UNIFORM_BUFFER_DYNAMIC)
{
signPosts.Add(new GLDynamicOffsetInfo
{
Target = GLBufferRangeTarget.UNIFORM_BUFFER,
DstIndex = NoOfExpectedDynamicOffsets,
});
NoOfExpectedDynamicOffsets += desc.DescriptorCount;
}
}
else if (desc.DescriptorType == MgDescriptorType.STORAGE_BUFFER
|| desc.DescriptorType == MgDescriptorType.STORAGE_BUFFER_DYNAMIC)
{
NoOfStorageBuffers += desc.DescriptorCount;
if (desc.DescriptorType == MgDescriptorType.STORAGE_BUFFER_DYNAMIC)
{
signPosts.Add(new GLDynamicOffsetInfo
{
Target = GLBufferRangeTarget.STORAGE_BUFFER,
DstIndex = desc.Binding,
});
NoOfExpectedDynamicOffsets += desc.DescriptorCount;
}
}
}
return signPosts.ToArray();
}
void SetupOffsetRangesByBindings()
{
var startingOffset = 0;
foreach (var g in Ranges.Values)
{
g.First += startingOffset;
g.Last += startingOffset;
startingOffset = g.Last + 1;
}
}
public bool Equals(IGLPipelineLayout other)
{
if (other == null)
return false;
if (ReferenceEquals(this, other))
return true;
if (NoOfBindingPoints != other.NoOfBindingPoints)
return false;
if (NoOfExpectedDynamicOffsets != other.NoOfExpectedDynamicOffsets)
return false;
if (NoOfStorageBuffers != other.NoOfStorageBuffers)
return false;
if (Bindings != null && other.Bindings == null)
return false;
if (Bindings == null && other.Bindings != null)
return false;
if (OffsetDestinations != null && other.OffsetDestinations == null)
return false;
if (OffsetDestinations == null && other.OffsetDestinations != null)
return false;
if (Ranges != null && other.Ranges == null)
return false;
if (Ranges == null && other.Ranges != null)
return false;
if (Bindings.Length != other.Bindings.Length)
return false;
{
var count = Bindings.Length;
for (var i = 0; i < count; i += 1)
{
var left = Bindings[i];
var right = other.Bindings[i];
if (!left.Equals(right))
return false;
}
}
if (OffsetDestinations.Length != other.OffsetDestinations.Length)
return false;
{
var count = OffsetDestinations.Length;
for (var i = 0; i < count; i += 1)
{
var left = OffsetDestinations[i];
var right = other.OffsetDestinations[i];
if (!left.Equals(right))
return false;
}
}
if (Ranges.Count != other.Ranges.Count)
return false;
return Ranges.Equals(other.Ranges);
}
#region IMgPipelineLayout implementation
private bool mIsDisposed = false;
public void DestroyPipelineLayout(IMgDevice device, IMgAllocationCallbacks allocator)
{
if (mIsDisposed)
return;
mIsDisposed = true;
}
#endregion
}
}
| tgsstdio/Mg | Magnesium.OpenGL/DescriptorSets/GLNextPipelineLayout.cs | C# | mit | 4,510 |
/**
*
*/
package net.caiban.auth.dashboard.dao.bs.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import net.caiban.auth.dashboard.dao.BaseDao;
import net.caiban.auth.dashboard.dao.bs.BsDao;
import net.caiban.auth.dashboard.domain.bs.Bs;
import net.caiban.auth.dashboard.domain.staff.Dept;
import net.caiban.auth.dashboard.domain.staff.Staff;
import net.caiban.auth.dashboard.dto.PageDto;
import net.caiban.auth.dashboard.dto.staff.StaffDto;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
/**
* @author root
*
*/
@Component("bsDao")
public class BsDaoImpl extends BaseDao implements BsDao {
final static String SQL_PREFIX="bs";
@Resource
private MessageSource messageSource;
@Override
public Integer countBsOfDept(Integer deptId, String projectCode) {
// Assert.notNull(deptId, messageSource.getMessage("assert.notnull", new String[] { "deptId" }, null));
Map<String, Object> root = new HashMap<String, Object>();
root.put("deptId", deptId);
root.put("code", projectCode);
return (Integer) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "countBsOfDept"), root);
}
@Override
public Integer countBsOfStaff(Integer staffId, String projectCode) {
// Assert.notNull(staffId, messageSource.getMessage("assert.notnull", new String[] { "staffId" }, null));
Map<String,Object> root =new HashMap<String,Object>();
root.put("staffId", staffId);
root.put("code", projectCode);
return (Integer)getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "countBsOfStaff"),root);
}
@SuppressWarnings("unchecked")
@Override
public List<Bs> queryBsOfDept(Integer deptId, String types) {
// Assert.notNull(deptId, messageSource.getMessage("assert.notnull", new String[] { "deptId" }, null));
Map<String,Object> root=new HashMap<String,Object>();
root.put("deptId", deptId);
root.put("types",types);
return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX,"queryBsOfDept"),root);
}
@SuppressWarnings("unchecked")
@Override
public List<Bs> queryBsOfStaff(Integer staffId, String types) {
// Assert.notNull(staffId, messageSource.getMessage("assert.notnull", new String[] { "staffId" }, null));
Map<String,Object> root=new HashMap<String,Object>();
root.put("staffId", staffId);
root.put("types", types);
return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX,"queryBsOfStaff"),root);
}
@Override
public String queryRightCodeOfBs(String projectCode) {
// Assert.notNull(projectCode, messageSource.getMessage("assert.notnull", new String[] { "projectCode" }, null));
return (String)getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX,"queryRightCodeOfBs"),projectCode);
}
@Override
public String queryPasswordOfBs(String pcode) {
return (String) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "queryPasswordOfBs"), pcode);
}
@Override
public Integer insertBs(Bs bs) {
return (Integer) getSqlMapClientTemplate().insert(buildId(SQL_PREFIX, "insertBs"), bs);
}
@Override
public Integer deleteBs(Integer id) {
return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBs"), id);
}
@Override
public Integer updateBs(Bs bs) {
return getSqlMapClientTemplate().update(buildId(SQL_PREFIX, "updateBs"),bs);
}
@SuppressWarnings("unchecked")
@Override
public List<Bs> queryBs(Bs bs, PageDto<Bs> page) {
Map<String, Object> root=new HashMap<String,Object>();
root.put("bs", bs);
root.put("page", page);
return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX,"queryBs"),root);
}
@Override
public Integer queryBsCount(Bs bs) {
Map<String,Object> root=new HashMap<String,Object>();
root.put("bs", bs);
return (Integer) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "queryBsCount"),root);
}
@Override
public Bs queryOneBs(Integer id) {
return (Bs) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "queryOneBs"), id);
}
@SuppressWarnings("unchecked")
@Override
public List<Staff> queryStaffByBs(Integer id, String types) {
Map<String,Object> root=new HashMap<String,Object>();
root.put("id", id);
root.put("types", types);
return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryStaffByBs"), root);
}
@SuppressWarnings("unchecked")
@Override
public List<Dept> queryDeptByBs(Integer id, String types) {
Map<String,Object> root=new HashMap<String,Object>();
root.put("id", id);
root.put("types", types);
return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryDeptByBs"),root);
}
@SuppressWarnings("unchecked")
@Override
public List<Integer> queryDeptIdByBsId(Integer bsId) {
return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryDeptIdByBsId"), bsId);
}
@SuppressWarnings("unchecked")
@Override
public List<StaffDto> queryBsStaff(Integer bsId) {
return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryBsStaff"), bsId);
}
@Override
public Integer insertBsStaff(Integer bsId, Integer staffId) {
Map<String, Object> root=new HashMap<String, Object>();
root.put("bsId", bsId);
root.put("staffId", staffId);
return (Integer) getSqlMapClientTemplate().insert(buildId(SQL_PREFIX, "insertBsStaff"),root);
}
@Override
public Integer deleteBsStaff(Integer bsId, Integer staffId) {
Map<String, Object> root=new HashMap<String, Object>();
root.put("bsId", bsId);
root.put("staffId", staffId);
return (Integer) getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBsStaff"),root);
}
@Override
public Integer deleteBsDept(Integer bsId, Integer deptId) {
Map<String, Object> root=new HashMap<String, Object>();
root.put("bsId", bsId);
root.put("deptId", deptId);
return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBsDept"), root);
}
@Override
public Integer insertBsDept(Integer bsId, Integer deptId) {
Map<String, Object> root=new HashMap<String, Object>();
root.put("bsId", bsId);
root.put("deptId", deptId);
return (Integer) getSqlMapClientTemplate().insert(buildId(SQL_PREFIX, "insertBsDept"), root);
}
@Override
public Integer deleteBsDept(Integer bsId) {
return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBsDeptByBsId"), bsId);
}
@Override
public Integer deleteBsStaff(Integer bsId) {
return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBsStaffByBsId"), bsId);
}
@Override
public String queryUrl(String key) {
return (String) getSqlMapClientTemplate().queryForObject(SQL_PREFIX, "queryUrl");
}
/***************************/
/*
public Integer countPageBs(Bs bs) {
Assert.notNull(bs, "bs is not null");
return (Integer) getSqlMapClientTemplate().queryForObject(
"bs.countPageBs", bs);
}
@SuppressWarnings("unchecked")
public List<Bs> queryMyBsByStaffId(Integer staffId, String types) {
Assert.notNull(staffId, "staffId is not null");
Map<String, Object> root = new HashMap<String, Object>();
root.put("staffId", staffId);
root.put("types", types);
return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryMyBsByStaffId"),
root);
}
@SuppressWarnings("unchecked")
public List<Bs> queryMyBsByDeptId(Integer deptId, String types) {
Assert.notNull(deptId, "deptId is not null");
Map<String, Object> root = new HashMap<String, Object>();
root.put("deptId", deptId);
root.put("types", types);
return getSqlMapClientTemplate().queryForList("bs.queryMyBsByDeptId",
root);
}
public Integer insertBs(Bs bs) {
Assert.notNull(bs, "bs is not null");
return (Integer) getSqlMapClientTemplate().insert("bs.insertBs", bs);
}
public Integer updateBs(Bs bs) {
Assert.notNull(bs, "bs is not null");
return getSqlMapClientTemplate().update("bs.updateBs", bs);
}
@SuppressWarnings("unchecked")
public List<BsDto> pageBsByBsDo(Bs bs, PageDto page) {
Assert.notNull(bs, "bs is not null");
Assert.notNull(page, "page is not null");
Map<String, Object> map = new HashMap<String, Object>();
map.put("bs", bs);
map.put("page", page);
return getSqlMapClientTemplate().queryForList("bs.pageBsByBsDo", map);
}
*/
}
| yysoft/yy-auth | auth-dashboard/src/main/java/net/caiban/auth/dashboard/dao/bs/impl/BsDaoImpl.java | Java | mit | 8,217 |
package demo.rest;
import demo.domain.RunningInfo;
import demo.service.RunningInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class RunningInfoRestController {
private RunningInfoService runningInfoService;
@Autowired
public RunningInfoRestController(RunningInfoService runningInfoService){
this.runningInfoService = runningInfoService;
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void upload(@RequestBody List<RunningInfo> runningInfos){
this.runningInfoService.saveRunningInfos(runningInfos);
}
@RequestMapping(value = "/delete/all", method = RequestMethod.POST)
public void purge() {
this.runningInfoService.deleteAll();
}
@RequestMapping(value = "/search/pagingByWarning", method = RequestMethod.GET)
Page<RunningInfo> findAllByOrderByHealthWarningLevelDescHeartRateDesc(@RequestParam(name = "page") int page){
return this.runningInfoService.findAllByOrderByHealthWarningLevelDescHeartRateDesc(new PageRequest(page,2));
}
@RequestMapping(value = "/delete/{runningId}", method = RequestMethod.POST)
public void deleteByRunningId(@PathVariable String runningId) {
this.runningInfoService.deleteByRunningId(runningId);
}
}
| zjxjasper/running-info-service | src/main/java/demo/rest/RunningInfoRestController.java | Java | mit | 1,573 |
import {Injectable, EventEmitter, Inject, ElementRef, Renderer, Renderer2} from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { MetaModel } from './meta.model';
export class MetaService {
public url: EventEmitter<string> = new EventEmitter<string>();
public _url: string;
public _safeurl: string;
private _r: Renderer;
private _document: any;
private headElement: any;//HTMLElement;
private ogTitle: HTMLElement;
private ogType: HTMLElement;
private ogUrl: HTMLElement;
private ogImage: HTMLElement;
private ogDescription: HTMLElement;
private description: HTMLElement;
private canonical: HTMLElement;
private router: Router;
constructor(renderer: Renderer, router: Router) {
this._r = renderer;
this._document = document;
this.headElement = this._document.head;
this.router = router;
this.ogTitle = this.getOrCreateMetaElement('og:title', 'property');
this.ogImage = this.getOrCreateMetaElement('og:image', 'property');
this.ogDescription = this.getOrCreateMetaElement('og:description', 'property');
this.ogUrl = this.getOrCreateMetaElement('og:url', 'property');
this.description = this.getOrCreateMetaElement('description', 'name');
this.canonical = this.getOrCreateCanonical();
}
public set(model: MetaModel) {
this.setTitle(model.title, "Lego Dimensions Builder");
this.setAttr(this.description, model.description);
this.setAttr(this.ogTitle, model.title);
this.setAttr(this.ogDescription, model.description);
if (model.image) {
this.setAttr(this.ogImage, 'http://dimensions-builder.com' + model.image);
} else {
this.setAttr(this.ogImage, 'http://dimensions-builder.com/assets/images/lego-dimensions.jpg');
}
if (model.canonical !== undefined) {
this._url = 'http://dimensions-builder.com' + model.canonical;
} else {
this._url = 'http://dimensions-builder.com' + this.router.url;
}
this._safeurl = this._url.replace(':', '%3A');
this.setAttr(this.ogUrl, this._url);
this.setAttr(this.canonical, this._url, 'href');
this.url.emit(this._url);
}
public setTitle(siteTitle = '', pageTitle ='', separator = ' - '){
let title = siteTitle;
if (!title) {
title = pageTitle + separator + 'All about abilities, characters, levels and more';
}
else {
if (pageTitle != '') {
title += separator + pageTitle;
}
}
this._document.title = title;
}
private getOrCreateMetaElement(name: string,attr: string): HTMLElement {
let el: HTMLElement;
var prop = ((attr != null)? attr : 'name');
el = this._r.createElement(this.headElement, 'meta');
this._r.setElementAttribute(el, prop, name);
return el;
}
private getOrCreateCanonical(): HTMLElement {
let el: HTMLElement;
el = this._r.createElement(this.headElement, 'link');
this._r.setElementAttribute(el, 'rel', 'canonical');
return el;
}
private setAttr(el: HTMLElement, value: string, property: string = 'content') {
this._r.setElementAttribute(el, property, value);
}
}
| schmist/dimensions-builder | src/app/meta/meta.service.ts | TypeScript | mit | 3,420 |
const create = require('./create')
const geom2 = require('../geometry/geom2')
const fromPoints = points => {
const geometry = geom2.fromPoints(points)
const newShape = create()
newShape.geometry = geometry
return newShape
}
module.exports = fromPoints
| jscad/csg.js | src/core/shape2/fromPoints.js | JavaScript | mit | 262 |
package com.plexobject.rx.util;
import java.util.Spliterator;
import java.util.function.Consumer;
public class ArraySpliterator<T> implements Spliterator<T> {
private final Object[] array;
private int origin; // current index, advanced on split or traversal
private final int fence; // one past the greatest index
public ArraySpliterator(Object[] array, int origin, int fence) {
this.array = array;
this.origin = origin;
this.fence = fence;
}
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super T> action) {
for (; origin < fence; origin++)
action.accept((T) array[origin]);
}
@SuppressWarnings("unchecked")
public boolean tryAdvance(Consumer<? super T> action) {
if (origin < fence) {
action.accept((T) array[origin]);
origin++;
return true;
} else
// cannot advance
return false;
}
public Spliterator<T> trySplit() {
int lo = origin; // divide range in half
int mid = ((lo + fence) >>> 1) & ~1; // force midpoint to be even
if (lo < mid) { // split out left half
origin = mid; // reset this Spliterator's origin
return new ArraySpliterator<>(array, lo, mid);
} else
// too small to split
return null;
}
public long estimateSize() {
return (long) (fence - origin);
}
public int characteristics() {
return ORDERED | SIZED | IMMUTABLE | SUBSIZED;
}
}
| bhatti/RxJava8 | src/test/java/com/plexobject/rx/util/ArraySpliterator.java | Java | mit | 1,567 |
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCScene.h"
#include "CCPointExtension.h"
#include "CCDirector.h"
namespace cocos2d {
CCScene::CCScene()
{
m_bIsRelativeAnchorPoint = false;
m_tAnchorPoint = ccp(0.5f, 0.5f);
m_eSceneType = ccNormalScene;
}
CCScene::~CCScene()
{
}
bool CCScene::init()
{
bool bRet = false;
do
{
CCDirector * pDirector;
CC_BREAK_IF( ! (pDirector = CCDirector::sharedDirector()) );
this->setContentSize(pDirector->getWinSize());
// success
bRet = true;
} while (0);
return bRet;
}
CCScene *CCScene::node()
{
CCScene *pRet = new CCScene();
if (pRet && pRet->init())
{
pRet->autorelease();
return pRet;
}
else
{
CC_SAFE_DELETE(pRet)
return NULL;
}
}
}//namespace cocos2d
| DmitriyKirakosyan/testNinjaX | libs/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp | C++ | mit | 2,012 |
<?php
namespace Fallen\FallenBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('email', 'email', array('attr'=>array('class'=>'form-control')));
$builder->add('sujet', 'text', array('attr'=>array('class'=>'form-control')));
$builder->add('message', 'textarea', array('attr'=>array('class'=>'form-control')));
$builder->add('captcha', 'genemu_recaptcha',array('mapped'=>false));
}
public function getName()
{
return 'contact';
}
}
| laureenw/Projet-Symfony2 | src/Fallen/FallenBundle/Form/ContactType.php | PHP | mit | 681 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// source: https://forum.unity3d.com/threads/a-free-simple-smooth-mouselook.73117/#post-3101292
// added: lockCursor
namespace UnityLibrary
{
public class SmoothMouseLookAveraged : MonoBehaviour
{
[Header("Info")]
private List<float> _rotArrayX = new List<float>(); // TODO: could use fixed array, or queue
private List<float> _rotArrayY = new List<float>();
private float rotAverageX;
private float rotAverageY;
private float mouseDeltaX;
private float mouseDeltaY;
[Header("Settings")]
public float _sensitivityX = 1.5f;
public float _sensitivityY = 1.5f;
[Tooltip("The more steps, the smoother it will be.")]
public int _averageFromThisManySteps = 3;
public bool lockCursor = false;
[Header("References")]
[Tooltip("Object to be rotated when mouse moves left/right.")]
public Transform _playerRootT;
[Tooltip("Object to be rotated when mouse moves up/down.")]
public Transform _cameraT;
//============================================
// FUNCTIONS (UNITY)
//============================================
void Start()
{
Cursor.visible = !lockCursor;
}
void Update()
{
HandleCursorLock();
MouseLookAveraged();
}
//============================================
// FUNCTIONS (CUSTOM)
//============================================
void HandleCursorLock()
{
// pressing esc toggles between hide/show and lock/unlock cursor
if (Input.GetKeyDown(KeyCode.Escape))
{
lockCursor = !lockCursor;
}
// Ensure the cursor is always locked when set
Cursor.lockState = lockCursor ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !lockCursor;
}
void MouseLookAveraged()
{
rotAverageX = 0f;
rotAverageY = 0f;
mouseDeltaX = 0f;
mouseDeltaY = 0f;
mouseDeltaX += Input.GetAxis("Mouse X") * _sensitivityX;
mouseDeltaY += Input.GetAxis("Mouse Y") * _sensitivityY;
// Add current rot to list, at end
_rotArrayX.Add(mouseDeltaX);
_rotArrayY.Add(mouseDeltaY);
// Reached max number of steps? Remove oldest from list
if (_rotArrayX.Count >= _averageFromThisManySteps)
_rotArrayX.RemoveAt(0);
if (_rotArrayY.Count >= _averageFromThisManySteps)
_rotArrayY.RemoveAt(0);
// Add all of these rotations together
for (int i_counterX = 0; i_counterX < _rotArrayX.Count; i_counterX++)
rotAverageX += _rotArrayX[i_counterX];
for (int i_counterY = 0; i_counterY < _rotArrayY.Count; i_counterY++)
rotAverageY += _rotArrayY[i_counterY];
// Get average
rotAverageX /= _rotArrayX.Count;
rotAverageY /= _rotArrayY.Count;
// Apply
_playerRootT.Rotate(0f, rotAverageX, 0f, Space.World);
_cameraT.Rotate(-rotAverageY, 0f, 0f, Space.Self);
}
}
}
| UnityCommunity/UnityLibrary | Assets/Scripts/Camera/SmoothMouseLookAveraged.cs | C# | mit | 3,365 |
<?php declare(strict_types=1);
namespace WyriHaximus\Travis\Resource\Sync;
use ApiClients\Foundation\Hydrator\CommandBus\Command\BuildAsyncFromSyncCommand;
use Rx\React\Promise;
use WyriHaximus\Travis\Resource\Repository as BaseRepository;
use WyriHaximus\Travis\Resource\RepositoryInterface;
use WyriHaximus\Travis\Resource\RepositoryKeyInterface;
use WyriHaximus\Travis\Resource\SettingsInterface;
use function React\Promise\resolve;
class Repository extends BaseRepository
{
/**
* @return array
*/
public function builds(): array
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return Promise::fromObservable($repository->builds()->toArray());
})
);
}
/**
* @param int $id
* @return Build
*/
public function build(int $id): Build
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) use ($id) {
return $repository->build($id);
})
);
}
/**
* @return array
*/
public function commits(): array
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return Promise::fromObservable($repository->commits()->toArray());
})
);
}
/**
* @return SettingsInterface
*/
public function settings(): SettingsInterface
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return $repository->settings();
})
);
}
/**
* @return bool
*/
public function isActive(): bool
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return $repository->isActive();
})->otherwise(function (bool $state) {
return resolve($state);
})
);
}
/**
* @return Repository
*/
public function enable(): Repository
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return $repository->enable();
})
);
}
/**
* @return Repository
*/
public function disable(): Repository
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return $repository->disable();
})
);
}
/**
* @return array
*/
public function branches(): array
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return Promise::fromObservable($repository->branches()->toArray());
})
);
}
/**
* @return array
*/
public function vars(): array
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return Promise::fromObservable($repository->vars()->toArray());
})
);
}
/**
* @return array
*/
public function caches(): array
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return Promise::fromObservable($repository->caches()->toArray());
})
);
}
/**
* @return RepositoryKeyInterface
*/
public function key(): RepositoryKeyInterface
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return $repository->key();
})
);
}
/**
* @return Repository
*/
public function refresh() : Repository
{
return $this->wait(
$this->handleCommand(
new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
)->then(function (RepositoryInterface $repository) {
return $repository->refresh();
})
);
}
}
| WyriHaximus/php-travis-client | src/Resource/Sync/Repository.php | PHP | mit | 5,196 |
////////////////////////////////////////////////////////////////////////////////
//
// keytreeutil.h
//
// Copyright (c) 2013-2014 Tim Lee
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "keytreeutil.h"
#include <sstream>
namespace KeyTreeUtil {
uchar_vector extKeyBase58OrHexToBytes(const std::string& extKey) {
uchar_vector extendedKey;
if (isBase58CheckValid(extKey))
extendedKey = fromBase58ExtKey(extKey);
else if (StringUtils::isHex(extKey))
extendedKey = uchar_vector(extKey);
else
throw std::runtime_error("Invalid extended key. Extended key must be in base58 or hex form.");
return extendedKey;
}
uchar_vector fromBase58ExtKey(const std::string& extKey) {
static unsigned int dummy = 0;
uchar_vector fillKey;
fromBase58Check(extKey, fillKey, dummy);
static const std::string VERSION_BYTE("04");
return uchar_vector(VERSION_BYTE+fillKey.getHex()); //append VERSION_BYTE to begining
}
TreeChains parseChainString(const std::string& chainStr, bool isPrivate) {
TreeChains treeChains;
const std::string s = StringUtils::split(chainStr)[0]; //trim trailing whitespaces
std::deque<std::string> splitChain = StringUtils::split(s, '/');
if (splitChain[0] != "m")
throw std::runtime_error("Invalid Chain string.");
//account for root node
treeChains.push_back(IsPrivateNPathRange(true , Range(NODE_IDX_M, NODE_IDX_M)));
if (splitChain.back() == "") splitChain.pop_back(); // happens if chainStr has '/' at end
splitChain.pop_front();
for (std::string& node : splitChain) {
if (node.back() == '\'') {
if (! isPrivate) throw std::runtime_error("Invalid chain "+ chainStr+ ", not private extended key.");
node = node.substr(0,node.length()-1);
if (node.front() == '(' && node.back() == ')') {
IsPrivateNPathRange range = parseRange(node, true);
treeChains.push_back(range);
} else {
uint32_t num = toPrime(std::stoi(node));
if (num == NODE_IDX_M)
throw std::invalid_argument("Invalid arguments. Invalid Range: " + std::to_string(num));
treeChains.push_back(IsPrivateNPathRange(true , Range(num, num)));
}
} else {
if (node.front() == '(' && node.back() == ')') {
IsPrivateNPathRange range = parseRange(node, false);
treeChains.push_back(range);
} else {
uint32_t num = std::stoi(node);
if (num == NODE_IDX_M)
throw std::invalid_argument("Invalid arguments. Invalid Range: " + std::to_string(num));
treeChains.push_back(IsPrivateNPathRange(false , Range(num, num)));
}
}
}
return treeChains;
}
IsPrivateNPathRange parseRange(const std::string node, bool isPrivate) {
//node must be like (123-9345)
const std::string minMaxString = node.substr(1,node.length()-2);
const std::deque<std::string> minMaxPair = StringUtils::split(minMaxString, '-');
if (minMaxPair.size() != 2)
throw std::invalid_argument("Invalid arguments.");
uint32_t min = std::stoi(minMaxPair[0]);
uint32_t max = std::stoi(minMaxPair[1]);
if (min == NODE_IDX_M)
throw std::invalid_argument("Invalid arguments. Invalid Range: " + std::to_string(min));
if (max == NODE_IDX_M)
throw std::invalid_argument("Invalid arguments. Invalid Range: " + std::to_string(max));
if (isPrivate) {
return IsPrivateNPathRange(true, Range(min, max));
} else {
return IsPrivateNPathRange(false, Range(min, max));
}
}
std::string iToString(uint32_t i) {
std::stringstream ss;
ss << (0x7fffffff & i);
if (isPrime(i)) { ss << "'"; }
return ss.str();
}
}
| stequald/KeyTree-qt | keytree-qt/keytreeutil.cpp | C++ | mit | 5,198 |
'use strict';
var users = require('../../app/controllers/users.server.controller'),
streams = require('../../app/controllers/streams.server.controller');
module.exports = function(app){
app.route('/api/streams')
.get(streams.list)
.post(users.requiresLogin, streams.create);
app.route('/api/streams/:streamId')
.get(streams.read)
.put(users.requiresLogin, streams.hasAuthorization, streams.update)
.delete(users.requiresLogin, streams.hasAuthorization, streams.delete);
app.param('streamId', streams.streamByID);
}; | plonsker/onetwo | app/routes/streams.server.routes.js | JavaScript | mit | 599 |
import Reflux from 'reflux';
//TODO: recheck the flow of these actions 'cause it doesn't seem to be OK
export default Reflux.createActions([
'eventPartsReady',
'eventPartsUpdate'
]);
| fk1blow/repeak | src/client/actions/event-part-actions.js | JavaScript | mit | 188 |
<?php
namespace ProductBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class SausHotType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('available')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'ProductBundle\Entity\SausHot'
));
}
/**
* @return string
*/
public function getName()
{
return 'productbundle_saushot';
}
}
| Kelevari/webshop-opdracht | src/ProductBundle/Form/SausHotType.php | PHP | mit | 884 |
// ReSharper disable All
using System;
using System.Configuration;
using System.Diagnostics;
using System.Net.Http;
using System.Runtime.Caching;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Hosting;
using System.Web.Http.Routing;
using Xunit;
namespace Frapid.Config.Api.Tests
{
public class AppRouteTests
{
[Theory]
[InlineData("/api/{apiVersionNumber}/config/app/delete/{appName}", "DELETE", typeof(AppController), "Delete")]
[InlineData("/api/config/app/delete/{appName}", "DELETE", typeof(AppController), "Delete")]
[InlineData("/api/{apiVersionNumber}/config/app/edit/{appName}", "PUT", typeof(AppController), "Edit")]
[InlineData("/api/config/app/edit/{appName}", "PUT", typeof(AppController), "Edit")]
[InlineData("/api/{apiVersionNumber}/config/app/count-where", "POST", typeof(AppController), "CountWhere")]
[InlineData("/api/config/app/count-where", "POST", typeof(AppController), "CountWhere")]
[InlineData("/api/{apiVersionNumber}/config/app/get-where/{pageNumber}", "POST", typeof(AppController), "GetWhere")]
[InlineData("/api/config/app/get-where/{pageNumber}", "POST", typeof(AppController), "GetWhere")]
[InlineData("/api/{apiVersionNumber}/config/app/add-or-edit", "POST", typeof(AppController), "AddOrEdit")]
[InlineData("/api/config/app/add-or-edit", "POST", typeof(AppController), "AddOrEdit")]
[InlineData("/api/{apiVersionNumber}/config/app/add/{app}", "POST", typeof(AppController), "Add")]
[InlineData("/api/config/app/add/{app}", "POST", typeof(AppController), "Add")]
[InlineData("/api/{apiVersionNumber}/config/app/bulk-import", "POST", typeof(AppController), "BulkImport")]
[InlineData("/api/config/app/bulk-import", "POST", typeof(AppController), "BulkImport")]
[InlineData("/api/{apiVersionNumber}/config/app/meta", "GET", typeof(AppController), "GetEntityView")]
[InlineData("/api/config/app/meta", "GET", typeof(AppController), "GetEntityView")]
[InlineData("/api/{apiVersionNumber}/config/app/count", "GET", typeof(AppController), "Count")]
[InlineData("/api/config/app/count", "GET", typeof(AppController), "Count")]
[InlineData("/api/{apiVersionNumber}/config/app/all", "GET", typeof(AppController), "GetAll")]
[InlineData("/api/config/app/all", "GET", typeof(AppController), "GetAll")]
[InlineData("/api/{apiVersionNumber}/config/app/export", "GET", typeof(AppController), "Export")]
[InlineData("/api/config/app/export", "GET", typeof(AppController), "Export")]
[InlineData("/api/{apiVersionNumber}/config/app/1", "GET", typeof(AppController), "Get")]
[InlineData("/api/config/app/1", "GET", typeof(AppController), "Get")]
[InlineData("/api/{apiVersionNumber}/config/app/get?appNames=1", "GET", typeof(AppController), "Get")]
[InlineData("/api/config/app/get?appNames=1", "GET", typeof(AppController), "Get")]
[InlineData("/api/{apiVersionNumber}/config/app", "GET", typeof(AppController), "GetPaginatedResult")]
[InlineData("/api/config/app", "GET", typeof(AppController), "GetPaginatedResult")]
[InlineData("/api/{apiVersionNumber}/config/app/page/1", "GET", typeof(AppController), "GetPaginatedResult")]
[InlineData("/api/config/app/page/1", "GET", typeof(AppController), "GetPaginatedResult")]
[InlineData("/api/{apiVersionNumber}/config/app/count-filtered/{filterName}", "GET", typeof(AppController), "CountFiltered")]
[InlineData("/api/config/app/count-filtered/{filterName}", "GET", typeof(AppController), "CountFiltered")]
[InlineData("/api/{apiVersionNumber}/config/app/get-filtered/{pageNumber}/{filterName}", "GET", typeof(AppController), "GetFiltered")]
[InlineData("/api/config/app/get-filtered/{pageNumber}/{filterName}", "GET", typeof(AppController), "GetFiltered")]
[InlineData("/api/config/app/first", "GET", typeof(AppController), "GetFirst")]
[InlineData("/api/config/app/previous/1", "GET", typeof(AppController), "GetPrevious")]
[InlineData("/api/config/app/next/1", "GET", typeof(AppController), "GetNext")]
[InlineData("/api/config/app/last", "GET", typeof(AppController), "GetLast")]
[InlineData("/api/{apiVersionNumber}/config/app/custom-fields", "GET", typeof(AppController), "GetCustomFields")]
[InlineData("/api/config/app/custom-fields", "GET", typeof(AppController), "GetCustomFields")]
[InlineData("/api/{apiVersionNumber}/config/app/custom-fields/{resourceId}", "GET", typeof(AppController), "GetCustomFields")]
[InlineData("/api/config/app/custom-fields/{resourceId}", "GET", typeof(AppController), "GetCustomFields")]
[InlineData("/api/{apiVersionNumber}/config/app/meta", "HEAD", typeof(AppController), "GetEntityView")]
[InlineData("/api/config/app/meta", "HEAD", typeof(AppController), "GetEntityView")]
[InlineData("/api/{apiVersionNumber}/config/app/count", "HEAD", typeof(AppController), "Count")]
[InlineData("/api/config/app/count", "HEAD", typeof(AppController), "Count")]
[InlineData("/api/{apiVersionNumber}/config/app/all", "HEAD", typeof(AppController), "GetAll")]
[InlineData("/api/config/app/all", "HEAD", typeof(AppController), "GetAll")]
[InlineData("/api/{apiVersionNumber}/config/app/export", "HEAD", typeof(AppController), "Export")]
[InlineData("/api/config/app/export", "HEAD", typeof(AppController), "Export")]
[InlineData("/api/{apiVersionNumber}/config/app/1", "HEAD", typeof(AppController), "Get")]
[InlineData("/api/config/app/1", "HEAD", typeof(AppController), "Get")]
[InlineData("/api/{apiVersionNumber}/config/app/get?appNames=1", "HEAD", typeof(AppController), "Get")]
[InlineData("/api/config/app/get?appNames=1", "HEAD", typeof(AppController), "Get")]
[InlineData("/api/{apiVersionNumber}/config/app", "HEAD", typeof(AppController), "GetPaginatedResult")]
[InlineData("/api/config/app", "HEAD", typeof(AppController), "GetPaginatedResult")]
[InlineData("/api/{apiVersionNumber}/config/app/page/1", "HEAD", typeof(AppController), "GetPaginatedResult")]
[InlineData("/api/config/app/page/1", "HEAD", typeof(AppController), "GetPaginatedResult")]
[InlineData("/api/{apiVersionNumber}/config/app/count-filtered/{filterName}", "HEAD", typeof(AppController), "CountFiltered")]
[InlineData("/api/config/app/count-filtered/{filterName}", "HEAD", typeof(AppController), "CountFiltered")]
[InlineData("/api/{apiVersionNumber}/config/app/get-filtered/{pageNumber}/{filterName}", "HEAD", typeof(AppController), "GetFiltered")]
[InlineData("/api/config/app/get-filtered/{pageNumber}/{filterName}", "HEAD", typeof(AppController), "GetFiltered")]
[InlineData("/api/config/app/first", "HEAD", typeof(AppController), "GetFirst")]
[InlineData("/api/config/app/previous/1", "HEAD", typeof(AppController), "GetPrevious")]
[InlineData("/api/config/app/next/1", "HEAD", typeof(AppController), "GetNext")]
[InlineData("/api/config/app/last", "HEAD", typeof(AppController), "GetLast")]
[InlineData("/api/{apiVersionNumber}/config/app/custom-fields", "HEAD", typeof(AppController), "GetCustomFields")]
[InlineData("/api/config/app/custom-fields", "HEAD", typeof(AppController), "GetCustomFields")]
[InlineData("/api/{apiVersionNumber}/config/app/custom-fields/{resourceId}", "HEAD", typeof(AppController), "GetCustomFields")]
[InlineData("/api/config/app/custom-fields/{resourceId}", "HEAD", typeof(AppController), "GetCustomFields")]
[Conditional("Debug")]
public void TestRoute(string url, string verb, Type type, string actionName)
{
//Arrange
url = url.Replace("{apiVersionNumber}", this.ApiVersionNumber);
url = Host + url;
//Act
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url);
IHttpControllerSelector controller = this.GetControllerSelector();
IHttpActionSelector action = this.GetActionSelector();
IHttpRouteData route = this.Config.Routes.GetRouteData(request);
request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;
request.Properties[HttpPropertyKeys.HttpConfigurationKey] = this.Config;
HttpControllerDescriptor controllerDescriptor = controller.SelectController(request);
HttpControllerContext context = new HttpControllerContext(this.Config, route, request)
{
ControllerDescriptor = controllerDescriptor
};
var actionDescriptor = action.SelectAction(context);
//Assert
Assert.NotNull(controllerDescriptor);
Assert.NotNull(actionDescriptor);
Assert.Equal(type, controllerDescriptor.ControllerType);
Assert.Equal(actionName, actionDescriptor.ActionName);
}
#region Fixture
private readonly HttpConfiguration Config;
private readonly string Host;
private readonly string ApiVersionNumber;
public AppRouteTests()
{
this.Host = ConfigurationManager.AppSettings["HostPrefix"];
this.ApiVersionNumber = ConfigurationManager.AppSettings["ApiVersionNumber"];
this.Config = GetConfig();
}
private HttpConfiguration GetConfig()
{
if (MemoryCache.Default["Config"] == null)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("VersionedApi", "api/" + this.ApiVersionNumber + "/{schema}/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute("DefaultApi", "api/{schema}/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.EnsureInitialized();
MemoryCache.Default["Config"] = config;
return config;
}
return MemoryCache.Default["Config"] as HttpConfiguration;
}
private IHttpControllerSelector GetControllerSelector()
{
if (MemoryCache.Default["ControllerSelector"] == null)
{
IHttpControllerSelector selector = this.Config.Services.GetHttpControllerSelector();
return selector;
}
return MemoryCache.Default["ControllerSelector"] as IHttpControllerSelector;
}
private IHttpActionSelector GetActionSelector()
{
if (MemoryCache.Default["ActionSelector"] == null)
{
IHttpActionSelector selector = this.Config.Services.GetActionSelector();
return selector;
}
return MemoryCache.Default["ActionSelector"] as IHttpActionSelector;
}
#endregion
}
} | nubiancc/frapid | src/Frapid.Web/Areas/Frapid.Config/WebApi/Tests/AppRouteTests.cs | C# | mit | 11,134 |
/**
* @license Angular v5.2.2
* (c) 2010-2018 Google, Inc. https://angular.io/
* License: MIT
*/
import { EventEmitter, Injectable } from '@angular/core';
import { __extends } from 'tslib';
import { LocationStrategy } from '@angular/common';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A spy for {\@link Location} that allows tests to fire simulated location events.
*
* \@experimental
*/
var SpyLocation = /** @class */ (function () {
function SpyLocation() {
this.urlChanges = [];
this._history = [new LocationState('', '')];
this._historyIndex = 0;
/**
* \@internal
*/
this._subject = new EventEmitter();
/**
* \@internal
*/
this._baseHref = '';
/**
* \@internal
*/
this._platformStrategy = /** @type {?} */ ((null));
}
/**
* @param {?} url
* @return {?}
*/
SpyLocation.prototype.setInitialPath = /**
* @param {?} url
* @return {?}
*/
function (url) { this._history[this._historyIndex].path = url; };
/**
* @param {?} url
* @return {?}
*/
SpyLocation.prototype.setBaseHref = /**
* @param {?} url
* @return {?}
*/
function (url) { this._baseHref = url; };
/**
* @return {?}
*/
SpyLocation.prototype.path = /**
* @return {?}
*/
function () { return this._history[this._historyIndex].path; };
/**
* @param {?} path
* @param {?=} query
* @return {?}
*/
SpyLocation.prototype.isCurrentPathEqualTo = /**
* @param {?} path
* @param {?=} query
* @return {?}
*/
function (path, query) {
if (query === void 0) { query = ''; }
var /** @type {?} */ givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path;
var /** @type {?} */ currPath = this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path();
return currPath == givenPath + (query.length > 0 ? ('?' + query) : '');
};
/**
* @param {?} pathname
* @return {?}
*/
SpyLocation.prototype.simulateUrlPop = /**
* @param {?} pathname
* @return {?}
*/
function (pathname) {
this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'popstate' });
};
/**
* @param {?} pathname
* @return {?}
*/
SpyLocation.prototype.simulateHashChange = /**
* @param {?} pathname
* @return {?}
*/
function (pathname) {
// Because we don't prevent the native event, the browser will independently update the path
this.setInitialPath(pathname);
this.urlChanges.push('hash: ' + pathname);
this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'hashchange' });
};
/**
* @param {?} url
* @return {?}
*/
SpyLocation.prototype.prepareExternalUrl = /**
* @param {?} url
* @return {?}
*/
function (url) {
if (url.length > 0 && !url.startsWith('/')) {
url = '/' + url;
}
return this._baseHref + url;
};
/**
* @param {?} path
* @param {?=} query
* @return {?}
*/
SpyLocation.prototype.go = /**
* @param {?} path
* @param {?=} query
* @return {?}
*/
function (path, query) {
if (query === void 0) { query = ''; }
path = this.prepareExternalUrl(path);
if (this._historyIndex > 0) {
this._history.splice(this._historyIndex + 1);
}
this._history.push(new LocationState(path, query));
this._historyIndex = this._history.length - 1;
var /** @type {?} */ locationState = this._history[this._historyIndex - 1];
if (locationState.path == path && locationState.query == query) {
return;
}
var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push(url);
this._subject.emit({ 'url': url, 'pop': false });
};
/**
* @param {?} path
* @param {?=} query
* @return {?}
*/
SpyLocation.prototype.replaceState = /**
* @param {?} path
* @param {?=} query
* @return {?}
*/
function (path, query) {
if (query === void 0) { query = ''; }
path = this.prepareExternalUrl(path);
var /** @type {?} */ history = this._history[this._historyIndex];
if (history.path == path && history.query == query) {
return;
}
history.path = path;
history.query = query;
var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push('replace: ' + url);
};
/**
* @return {?}
*/
SpyLocation.prototype.forward = /**
* @return {?}
*/
function () {
if (this._historyIndex < (this._history.length - 1)) {
this._historyIndex++;
this._subject.emit({ 'url': this.path(), 'pop': true });
}
};
/**
* @return {?}
*/
SpyLocation.prototype.back = /**
* @return {?}
*/
function () {
if (this._historyIndex > 0) {
this._historyIndex--;
this._subject.emit({ 'url': this.path(), 'pop': true });
}
};
/**
* @param {?} onNext
* @param {?=} onThrow
* @param {?=} onReturn
* @return {?}
*/
SpyLocation.prototype.subscribe = /**
* @param {?} onNext
* @param {?=} onThrow
* @param {?=} onReturn
* @return {?}
*/
function (onNext, onThrow, onReturn) {
return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });
};
/**
* @param {?} url
* @return {?}
*/
SpyLocation.prototype.normalize = /**
* @param {?} url
* @return {?}
*/
function (url) { return /** @type {?} */ ((null)); };
SpyLocation.decorators = [
{ type: Injectable },
];
/** @nocollapse */
SpyLocation.ctorParameters = function () { return []; };
return SpyLocation;
}());
var LocationState = /** @class */ (function () {
function LocationState(path, query) {
this.path = path;
this.query = query;
}
return LocationState;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A mock implementation of {\@link LocationStrategy} that allows tests to fire simulated
* location events.
*
* \@stable
*/
var MockLocationStrategy = /** @class */ (function (_super) {
__extends(MockLocationStrategy, _super);
function MockLocationStrategy() {
var _this = _super.call(this) || this;
_this.internalBaseHref = '/';
_this.internalPath = '/';
_this.internalTitle = '';
_this.urlChanges = [];
/**
* \@internal
*/
_this._subject = new EventEmitter();
return _this;
}
/**
* @param {?} url
* @return {?}
*/
MockLocationStrategy.prototype.simulatePopState = /**
* @param {?} url
* @return {?}
*/
function (url) {
this.internalPath = url;
this._subject.emit(new _MockPopStateEvent(this.path()));
};
/**
* @param {?=} includeHash
* @return {?}
*/
MockLocationStrategy.prototype.path = /**
* @param {?=} includeHash
* @return {?}
*/
function (includeHash) {
if (includeHash === void 0) { includeHash = false; }
return this.internalPath;
};
/**
* @param {?} internal
* @return {?}
*/
MockLocationStrategy.prototype.prepareExternalUrl = /**
* @param {?} internal
* @return {?}
*/
function (internal) {
if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) {
return this.internalBaseHref + internal.substring(1);
}
return this.internalBaseHref + internal;
};
/**
* @param {?} ctx
* @param {?} title
* @param {?} path
* @param {?} query
* @return {?}
*/
MockLocationStrategy.prototype.pushState = /**
* @param {?} ctx
* @param {?} title
* @param {?} path
* @param {?} query
* @return {?}
*/
function (ctx, title, path, query) {
this.internalTitle = title;
var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : '');
this.internalPath = url;
var /** @type {?} */ externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push(externalUrl);
};
/**
* @param {?} ctx
* @param {?} title
* @param {?} path
* @param {?} query
* @return {?}
*/
MockLocationStrategy.prototype.replaceState = /**
* @param {?} ctx
* @param {?} title
* @param {?} path
* @param {?} query
* @return {?}
*/
function (ctx, title, path, query) {
this.internalTitle = title;
var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : '');
this.internalPath = url;
var /** @type {?} */ externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push('replace: ' + externalUrl);
};
/**
* @param {?} fn
* @return {?}
*/
MockLocationStrategy.prototype.onPopState = /**
* @param {?} fn
* @return {?}
*/
function (fn) { this._subject.subscribe({ next: fn }); };
/**
* @return {?}
*/
MockLocationStrategy.prototype.getBaseHref = /**
* @return {?}
*/
function () { return this.internalBaseHref; };
/**
* @return {?}
*/
MockLocationStrategy.prototype.back = /**
* @return {?}
*/
function () {
if (this.urlChanges.length > 0) {
this.urlChanges.pop();
var /** @type {?} */ nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : '';
this.simulatePopState(nextUrl);
}
};
/**
* @return {?}
*/
MockLocationStrategy.prototype.forward = /**
* @return {?}
*/
function () { throw 'not implemented'; };
MockLocationStrategy.decorators = [
{ type: Injectable },
];
/** @nocollapse */
MockLocationStrategy.ctorParameters = function () { return []; };
return MockLocationStrategy;
}(LocationStrategy));
var _MockPopStateEvent = /** @class */ (function () {
function _MockPopStateEvent(newUrl) {
this.newUrl = newUrl;
this.pop = true;
this.type = 'popstate';
}
return _MockPopStateEvent;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Generated bundle index. Do not edit.
*/
export { SpyLocation, MockLocationStrategy };
//# sourceMappingURL=testing.js.map
| RJ15/FixIt | badminton/node_modules/@angular/common/esm5/testing.js | JavaScript | mit | 11,979 |
package de.helwich.junit;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation used to configure jasmine test runner.
*
* @author Hendrik Helwich
*/
@Target(TYPE)
@Retention(RUNTIME)
public @interface JasmineTest {
String srcDir() default "/src/main/js";
String testDir() default "/src/test/js";
String fileSuffix() default ".js";
String[] src() default {};
String[] test();
boolean browser() default false;
boolean classPathJsResources() default false;
}
| dddpaul/junit-jasmine-runner | src/main/java/de/helwich/junit/JasmineTest.java | Java | mit | 651 |
import javafx.application.Application;
// Scene
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
// Stage
import javafx.stage.Stage;
public class ChessApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("ChessViewer-2.1.fxml"));
stage.setTitle("Chess Viewer 2.1");
stage.setScene(new Scene(root, 1200, 720));
stage.show();
}
}
| tlee753/chess-visualizer | src/ChessApp.java | Java | mit | 574 |
function router(handle, pathname, res, postdata) {
console.log('into the router request for->'+pathname);
// var newpathname = pathname;
// var newpostdata = postdata;
// console.log(pathname.lastIndexOf('.'));
var extendNM = pathname.substr(pathname.lastIndexOf('.')+1);
// console.log(extendNM);
// var cssFileRegex = new RegExp('^/css/.*css?$');
// if (cssFileRegex.test(pathname)) {
// newpathname = 'css';
// newpostdata = pathname;
// }
if (typeof handle[extendNM] === 'function') {
handle[extendNM](res, postdata, pathname);
} else {
console.log('no request handle found for->'+pathname);
res.writeHead(404, {'Content-Type':'text/plain'});
res.write('404 not found!');
res.end();
}
}
exports.router = router; | noprettyboy/my_portal_page | serverjs/router.js | JavaScript | mit | 744 |
require 'fog/core/model'
module Fog
module Brightbox
class Compute
class LoadBalancer < Fog::Model
identity :id
attribute :url
attribute :name
attribute :status
attribute :resource_type
attribute :nodes
attribute :policy
attribute :healthcheck
attribute :listeners
attribute :account
def ready?
status == 'active'
end
def save
requires :nodes, :listeners, :healthcheck
options = {
:nodes => nodes,
:listeners => listeners,
:healthcheck => healthcheck,
:policy => policy,
:name => name
}.delete_if {|k,v| v.nil? || v == "" }
data = connection.create_load_balancer(options)
merge_attributes(data)
true
end
def destroy
requires :identity
connection.destroy_load_balancer(identity)
true
end
end
end
end
end
| jbenjore/JPs-love-project | annotate-models/ruby/1.9.1/gems/fog-0.8.1/lib/fog/compute/models/brightbox/load_balancer.rb | Ruby | mit | 1,025 |
package com.eway.payment.sdk.android.entities;
import com.eway.payment.sdk.android.beans.CodeDetail;
import java.util.ArrayList;
public class CodeLookupResponse {
private String Language;
private ArrayList<CodeDetail> CodeDetails;
private String Errors;
public CodeLookupResponse(String errors, String language, ArrayList<CodeDetail> codeDetails) {
Language = language;
CodeDetails = codeDetails;
Errors = errors;
}
public CodeLookupResponse() {
}
public String getLanguage() {
return Language;
}
public void setLanguage(String language) {
Language = language;
}
public ArrayList<CodeDetail> getCodeDetails() {
return CodeDetails;
}
public void setCodeDetails(ArrayList<CodeDetail> codeDetails) {
CodeDetails = codeDetails;
}
public String getErrors() {
return Errors;
}
public void setErrors(String errors) {
Errors = errors;
}
}
| eWAYPayment/eway-rapid-android | sdk/src/main/java/com/eway/payment/sdk/android/entities/CodeLookupResponse.java | Java | mit | 991 |
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("_16.LongSequence")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("_16.LongSequence")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("68d8028d-7e4d-4919-b932-9f5cf2760d26")]
// 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")]
| dobri19/OldRepos | Telerik/01-Programming-with-C#/01-C#-Fundamentals-2016-October/01-Intro-Programming/16.LongSequence/Properties/AssemblyInfo.cs | C# | mit | 1,426 |
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("WorldBankBBS.WCF.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WorldBankBBS.WCF.Data")]
[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("25f3699d-4ec4-45b2-8b08-ec78e1d9bca3")]
// 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.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| sharpninja/WorldBankBBS | WorldBankBBS.WCF.Data/Properties/AssemblyInfo.cs | C# | mit | 1,418 |
"use strict"
class Compress extends R.Compressor{
/**
*
*
*/
run(R,compressor){
this.compressBackbone(true);
}
}
module.exports=Compress; | williamamed/Raptor.js | @raptorjs-development/raptor-panel/Compressor/Compress.js | JavaScript | mit | 154 |
# requires all of the integrators at the end of the file
class Metriculator
@@integrations = {}
@parsed, @db_stored, @finished = false, false, false
# integration points are:
@@names = [:on_db_store, :on_finish, :on_metric_parse]
@@names.each {|name| @@integrations[name] = [] }
class << self
## Takes procs to run them at the specified integration time.
def integration(name, &block)
if @@names.include? name
@@integrations[name] << block
end
end
# Calls stored procs at the database storage moment in msruninfo.rb
def on_db_store(msrun)
return if on_db_store?
@@integrations[:on_db_store].each {|block| block.call msrun }
@db_stored = true
end
# Calls stored procs after everything is done in bin/metriculator (after messaging system)
def on_finish(msrun)
return if on_finish?
@@integrations[:on_finish].each {|block| block.call msrun }
@finished = true
end
# calls stored procs after the parsing is done in metrics.rb, hands back the metric object
def on_metric_parse(metric)
return if on_metric_parse?
@@integrations[:on_metric_parse].each { |block| block.call metric }
@on_parsed = true
end
def on_metric_parse?
@parsed
end
def on_finish?
@finished
end
def on_db_store?
@db_stored
end
end # class << self
end
Dir.glob(File.join(File.dirname(__FILE__), "integrators", "*.rb")).each do |integrator_file|
require_relative integrator_file
end
| princelab/metriculator | lib/integrators.rb | Ruby | mit | 1,530 |
var parserx = require('parse-regexp')
var EventEmitter = require('events').EventEmitter
var MuxDemux = require('mux-demux')
var remember = require('remember')
var idle = require('idle')
var timestamp = require('monotonic-timestamp')
var from = require('from')
var sync = require('./state-sync')
module.exports = Rumours
//THIS IS STRICTLY FOR DEBUGGING
var ids = 'ABCDEFHIJKLMNOP'
function createId () {
var id = ids[0]
ids = ids.substring(1)
return id
}
function Rumours (schema) {
var emitter = new EventEmitter()
//DEBUG
emitter.id = createId()
var rules = []
var live = {}
var locals = {}
/* schema must be of form :
{ '/regexp/g': function (key) {
//must return a scuttlebutt instance
//regexes must match from the first character.
//[else madness would ensue]
}
}
*/
for (var p in schema) {
rules.push({rx: parserx(p) || p, fn: schema[p]})
}
function match (key) {
for (var i in rules) {
var r = rules[i]
var m = key.match(r.rx)
if(m && m.index === 0)
return r.fn
}
}
//OPEN is a much better verb than TRANSCIEVE
emitter.open =
emitter.transceive =
emitter.trx = function (key, local, cb) {
if(!cb && 'function' === typeof local)
cb = local, local = true
local = (local !== false) //default to true
if(local) locals[key] = true
if(live[key]) return live[key]
//if we havn't emitted ready, emit it now,
//can deal with the rest of the updates later...
if(!emitter.ready) {
emitter.ready = true
emitter.emit('ready')
}
var fn = match(key)
if(!fn) throw new Error('no schema for:'+key)
var doc = fn(key) //create instance.
doc.key = key
live[key] = doc //remeber what is open.
emitter.emit('open', doc, local) //attach to any open streams.
emitter.emit('trx', doc, local)
doc.once('dispose', function () {
delete locals[doc.key]
delete live[doc.key]
})
if(cb) doc.once('sync', cb)
return doc
}
//CLOSE(doc)
emitter.close =
emitter.untransceive =
emitter.untrx = function (doc) {
doc.dispose()
emitter.emit('untrx', doc)
emitter.emit('close', doc)
return this
}
/*
so the logic here:
if open a doc,
RTR over stream;
if idle
close stream
if change
reopen stream
*/
function activations (listen) {
emitter.on('open', onActive)
for(var key in live) {
(onActive)(live[key])
}
function onActive (doc, local) {
local = (local !== false)
var up = true
function onUpdate (u) {
if(up) return
up = true
listen(doc, true)
}
function onIdle () {
up = false
listen(doc, false)
}
//call onIdle when _update hasn't occured within ms...
idle(doc, '_update', 1e3, onIdle)
doc.once('dispose', function () {
if(up) {
up = false
listen(doc, false)
}
doc.removeListener('_update', onIdle)
doc.removeListener('_update', onUpdate)
})
doc.on('_update', onUpdate)
listen(doc, true)
}
}
var state = {}
var syncState = sync(emitter, state)
//a better name for this?
function onReadyOrNow (cb) {
process.nextTick(function () {
if(emitter.ready) return cb()
emitter.once('ready', cb)
})
}
emitter.createStream = function (mode) {
var streams = {}
var mx = MuxDemux(function (stream) {
if(/^__state/.test(stream.meta.key)) {
return stateStream(stream)
}
if(_stream = streams[stream.meta.key]) {
if(_stream.meta.ts > stream.meta.ts)
return _stream.end()
else
stream.end(), stream = _stream
}
streams[stream.meta.key] = stream
//this will trigger connectIf
emitter.open(stream.meta.key, false)
})
function connectIf(doc) {
var stream = streams[doc.key]
if(!stream) {
streams[doc.key] = stream =
mx.createStream({key: doc.key, ts: timestamp()})
}
stream.pipe(doc.createStream({wrapper:'raw', tail: true})).pipe(stream)
stream.once('close', function () {
delete streams[doc.key]
})
}
//replicate all live documents.
process.nextTick(function () {
activations(function (doc, up) {
if(up) {
process.nextTick(function () {
connectIf(doc)
})
} else {
if(streams[doc.key])
streams[doc.key].end()
if(!locals[doc.key])
doc.dispose()
}
})
})
function stateStream (stream) {
stream.on('data', function (ary) {
var key = ary.shift()
var hash = ary.shift()
if(state[key] !== hash && !live[key]) {
//(_, false) means close this again after it stops changing...
emitter.open(key, false)
}
})
}
//wait untill is ready, if not yet ready...
onReadyOrNow(function () {
from(
Object.keys(state).map(function (k) {
return [k, state[k]]
})
)
.pipe(mx.createStream({key: '__state'}))
/*.on('data', function (data) {
var key = data.shift()
var hash = data.shift()
//just have to open the document,
//and it will be replicated to the remote.
if(state[key] !== hash)
emitter.open(key)
})*/
})
return mx
}
//inject kv object used to persist everything.
emitter.persist = function (kv) {
var sync = remember(kv)
function onActive (doc) {
sync(doc)
}
//check if any docs are already active.
//start persisting them.
for (var k in live) {
onActive(live[k])
}
emitter.on('trx', onActive)
//load the state - this is the hash of the documents!
syncState(kv)
return emitter
}
return emitter
}
| dominictarr/rumours_ | index.js | JavaScript | mit | 6,007 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlackHole.Entity
{
public class UserInfo
{
}
public class BasicUserInfo
{
/// <summary>唯一识别码
///
/// </summary>
public string UserGUID { get; set; }
/// <summary>
///
/// </summary>
public string CardNo { get; set; }
public string NewName { get; set; }
public string OleName { get; set; }
public int Age { get; set; }
public int Sex { get; set; }
public DateTime BirthDate { get; set; }
public string Img { get; set; }
}
}
| 1024home/BlackHole | BlackHole/BlackHole.Entity/UserInfo.cs | C# | mit | 711 |
'use strict';
var xpath = require('xpath');
var dom = require('xmldom').DOMParser;
module.exports = function (grunt) {
var xml = grunt.file.read(__dirname + '/../pom.xml');
var doc = new dom().parseFromString(xml);
var select = xpath.useNamespaces({"xmlns": "http://maven.apache.org/POM/4.0.0"});
var version = select("/xmlns:project/xmlns:version/text()", doc).toString().split( /-/ )[0];
var repository = select("/xmlns:project/xmlns:url/text()", doc).toString();
require('load-grunt-tasks')(grunt);
grunt.initConfig({
changelog: {
options: {
version: version,
repository: repository,
dest: '../CHANGELOG.md'
}
},
});
grunt.registerTask('default', ['changelog']);
};
| bheiskell/HungerRain | changelog/Gruntfile.js | JavaScript | mit | 800 |
/*
The MIT License (MIT)
Copyright (c) 2013-2015 winlin
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.
*/
#ifndef SRS_RTMP_PROTOCOL_IO_HPP
#define SRS_RTMP_PROTOCOL_IO_HPP
/*
#include <srs_rtmp_io.hpp>
*/
#include <srs_core.hpp>
// for srs-librtmp, @see https://github.com/winlinvip/simple-rtmp-server/issues/213
#ifndef _WIN32
#include <sys/uio.h>
#endif
/**
* the system io reader/writer architecture:
+---------------+ +--------------------+ +---------------+
| IBufferReader | | IStatistic | | IBufferWriter |
+---------------+ +--------------------+ +---------------+
| + read() | | + get_recv_bytes() | | + write() |
+------+--------+ | + get_recv_bytes() | | + writev() |
/ \ +---+--------------+-+ +-------+-------+
| / \ / \ / \
| | | |
+------+------------------+-+ +-----+----------------+--+
| IProtocolReader | | IProtocolWriter |
+---------------------------+ +-------------------------+
| + readfully() | | + set_send_timeout() |
| + set_recv_timeout() | +-------+-----------------+
+------------+--------------+ / \
/ \ |
| |
+--+-----------------------------+-+
| IProtocolReaderWriter |
+----------------------------------+
| + is_never_timeout() |
+----------------------------------+
*/
/**
* the reader for the buffer to read from whatever channel.
*/
class ISrsBufferReader
{
public:
ISrsBufferReader();
virtual ~ISrsBufferReader();
// for protocol/amf0/msg-codec
public:
virtual int read(void* buf, size_t size, ssize_t* nread) = 0;
};
/**
* the writer for the buffer to write to whatever channel.
*/
class ISrsBufferWriter
{
public:
ISrsBufferWriter();
virtual ~ISrsBufferWriter();
// for protocol
public:
/**
* write bytes over writer.
* @nwrite the actual written bytes. NULL to ignore.
*/
virtual int write(void* buf, size_t size, ssize_t* nwrite) = 0;
/**
* write iov over writer.
* @nwrite the actual written bytes. NULL to ignore.
*/
virtual int writev(const iovec *iov, int iov_size, ssize_t* nwrite) = 0;
};
/**
* get the statistic of channel.
*/
class ISrsProtocolStatistic
{
public:
ISrsProtocolStatistic();
virtual ~ISrsProtocolStatistic();
// for protocol
public:
/**
* get the total recv bytes over underlay fd.
*/
virtual int64_t get_recv_bytes() = 0;
/**
* get the total send bytes over underlay fd.
*/
virtual int64_t get_send_bytes() = 0;
};
/**
* the reader for the protocol to read from whatever channel.
*/
class ISrsProtocolReader : public virtual ISrsBufferReader, public virtual ISrsProtocolStatistic
{
public:
ISrsProtocolReader();
virtual ~ISrsProtocolReader();
// for protocol
public:
/**
* set the recv timeout in us, recv will error when timeout.
* @remark, if not set, use ST_UTIME_NO_TIMEOUT, never timeout.
*/
virtual void set_recv_timeout(int64_t timeout_us) = 0;
/**
* get the recv timeout in us.
*/
virtual int64_t get_recv_timeout() = 0;
// for handshake.
public:
/**
* read specified size bytes of data
* @param nread, the actually read size, NULL to ignore.
*/
virtual int read_fully(void* buf, size_t size, ssize_t* nread) = 0;
};
/**
* the writer for the protocol to write to whatever channel.
*/
class ISrsProtocolWriter : public virtual ISrsBufferWriter, public virtual ISrsProtocolStatistic
{
public:
ISrsProtocolWriter();
virtual ~ISrsProtocolWriter();
// for protocol
public:
/**
* set the send timeout in us, send will error when timeout.
* @remark, if not set, use ST_UTIME_NO_TIMEOUT, never timeout.
*/
virtual void set_send_timeout(int64_t timeout_us) = 0;
/**
* get the send timeout in us.
*/
virtual int64_t get_send_timeout() = 0;
};
/**
* the reader and writer.
*/
class ISrsProtocolReaderWriter : public virtual ISrsProtocolReader, public virtual ISrsProtocolWriter
{
public:
ISrsProtocolReaderWriter();
virtual ~ISrsProtocolReaderWriter();
// for protocol
public:
/**
* whether the specified timeout_us is never timeout.
*/
virtual bool is_never_timeout(int64_t timeout_us) = 0;
};
#endif
| Akagi201/srs-librtmp | src/protocol/srs_rtmp_io.hpp | C++ | mit | 5,514 |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace WizBot.Common.Pokemon
{
public class SearchPokemon
{
public class GenderRatioClass
{
public float M { get; set; }
public float F { get; set; }
}
public class BaseStatsClass
{
public int HP { get; set; }
public int ATK { get; set; }
public int DEF { get; set; }
public int SPA { get; set; }
public int SPD { get; set; }
public int SPE { get; set; }
public override string ToString() => $@"💚**HP:** {HP,-4} ⚔**ATK:** {ATK,-4} 🛡**DEF:** {DEF,-4}
✨**SPA:** {SPA,-4} 🎇**SPD:** {SPD,-4} 💨**SPE:** {SPE,-4}";
}
[JsonProperty("num")]
public int Id { get; set; }
public string Species { get; set; }
public string[] Types { get; set; }
public GenderRatioClass GenderRatio { get; set; }
public BaseStatsClass BaseStats { get; set; }
public Dictionary<string, string> Abilities { get; set; }
public float HeightM { get; set; }
public float WeightKg { get; set; }
public string Color { get; set; }
public string[] Evos { get; set; }
public string[] EggGroups { get; set; }
}
}
| Wizkiller96/WizBot | src/WizBot/Common/Pokemon/SearchPokemon.cs | C# | mit | 1,319 |
package com.tomogle.iemclient.requests;
/**
* Represents a type of request in the IEM API.
* According to the IEM API docs, it represents the 'name of the API file in question'.
*
* We ignore the Java uppercase enum naming convention for ease of use.
*/
public enum RequestType {
subscribers,
authentication,
lists,
stats
}
| tom-ogle/InterspireEmailMarketerClient | src/main/java/com/tomogle/iemclient/requests/RequestType.java | Java | mit | 338 |
import Class from '../mixin/class';
import Media from '../mixin/media';
import {$, addClass, after, Animation, assign, attr, css, fastdom, hasClass, isNumeric, isString, isVisible, noop, offset, offsetPosition, query, remove, removeClass, replaceClass, scrollTop, toFloat, toggleClass, toPx, trigger, within} from 'uikit-util';
export default {
mixins: [Class, Media],
props: {
top: null,
bottom: Boolean,
offset: String,
animation: String,
clsActive: String,
clsInactive: String,
clsFixed: String,
clsBelow: String,
selTarget: String,
widthElement: Boolean,
showOnUp: Boolean,
targetOffset: Number
},
data: {
top: 0,
bottom: false,
offset: 0,
animation: '',
clsActive: 'uk-active',
clsInactive: '',
clsFixed: 'uk-sticky-fixed',
clsBelow: 'uk-sticky-below',
selTarget: '',
widthElement: false,
showOnUp: false,
targetOffset: false
},
computed: {
offset({offset}) {
return toPx(offset);
},
selTarget({selTarget}, $el) {
return selTarget && $(selTarget, $el) || $el;
},
widthElement({widthElement}, $el) {
return query(widthElement, $el) || this.placeholder;
},
isActive: {
get() {
return hasClass(this.selTarget, this.clsActive);
},
set(value) {
if (value && !this.isActive) {
replaceClass(this.selTarget, this.clsInactive, this.clsActive);
trigger(this.$el, 'active');
} else if (!value && !hasClass(this.selTarget, this.clsInactive)) {
replaceClass(this.selTarget, this.clsActive, this.clsInactive);
trigger(this.$el, 'inactive');
}
}
}
},
connected() {
this.placeholder = $('+ .uk-sticky-placeholder', this.$el) || $('<div class="uk-sticky-placeholder"></div>');
this.isFixed = false;
this.isActive = false;
},
disconnected() {
if (this.isFixed) {
this.hide();
removeClass(this.selTarget, this.clsInactive);
}
remove(this.placeholder);
this.placeholder = null;
this.widthElement = null;
},
events: [
{
name: 'load hashchange popstate',
el: window,
handler() {
if (!(this.targetOffset !== false && location.hash && window.pageYOffset > 0)) {
return;
}
const target = $(location.hash);
if (target) {
fastdom.read(() => {
const {top} = offset(target);
const elTop = offset(this.$el).top;
const elHeight = this.$el.offsetHeight;
if (this.isFixed && elTop + elHeight >= top && elTop <= top + target.offsetHeight) {
scrollTop(window, top - elHeight - (isNumeric(this.targetOffset) ? this.targetOffset : 0) - this.offset);
}
});
}
}
}
],
update: [
{
read({height}, type) {
if (this.isActive && type !== 'update') {
this.hide();
height = this.$el.offsetHeight;
this.show();
}
height = !this.isActive ? this.$el.offsetHeight : height;
this.topOffset = offset(this.isFixed ? this.placeholder : this.$el).top;
this.bottomOffset = this.topOffset + height;
const bottom = parseProp('bottom', this);
this.top = Math.max(toFloat(parseProp('top', this)), this.topOffset) - this.offset;
this.bottom = bottom && bottom - height;
this.inactive = !this.matchMedia;
return {
lastScroll: false,
height,
margins: css(this.$el, ['marginTop', 'marginBottom', 'marginLeft', 'marginRight'])
};
},
write({height, margins}) {
const {placeholder} = this;
css(placeholder, assign({height}, margins));
if (!within(placeholder, document)) {
after(this.$el, placeholder);
attr(placeholder, 'hidden', '');
}
// ensure active/inactive classes are applied
this.isActive = this.isActive;
},
events: ['resize']
},
{
read({scroll = 0}) {
this.width = (isVisible(this.widthElement) ? this.widthElement : this.$el).offsetWidth;
this.scroll = window.pageYOffset;
return {
dir: scroll <= this.scroll ? 'down' : 'up',
scroll: this.scroll,
visible: isVisible(this.$el),
top: offsetPosition(this.placeholder)[0]
};
},
write(data, type) {
const {initTimestamp = 0, dir, lastDir, lastScroll, scroll, top, visible} = data;
const now = performance.now();
data.lastScroll = scroll;
if (scroll < 0 || scroll === lastScroll || !visible || this.disabled || this.showOnUp && type !== 'scroll') {
return;
}
if (now - initTimestamp > 300 || dir !== lastDir) {
data.initScroll = scroll;
data.initTimestamp = now;
}
data.lastDir = dir;
if (this.showOnUp && Math.abs(data.initScroll - scroll) <= 30 && Math.abs(lastScroll - scroll) <= 10) {
return;
}
if (this.inactive
|| scroll < this.top
|| this.showOnUp && (scroll <= this.top || dir === 'down' || dir === 'up' && !this.isFixed && scroll <= this.bottomOffset)
) {
if (!this.isFixed) {
if (Animation.inProgress(this.$el) && top > scroll) {
Animation.cancel(this.$el);
this.hide();
}
return;
}
this.isFixed = false;
if (this.animation && scroll > this.topOffset) {
Animation.cancel(this.$el);
Animation.out(this.$el, this.animation).then(() => this.hide(), noop);
} else {
this.hide();
}
} else if (this.isFixed) {
this.update();
} else if (this.animation) {
Animation.cancel(this.$el);
this.show();
Animation.in(this.$el, this.animation).catch(noop);
} else {
this.show();
}
},
events: ['resize', 'scroll']
}
],
methods: {
show() {
this.isFixed = true;
this.update();
attr(this.placeholder, 'hidden', null);
},
hide() {
this.isActive = false;
removeClass(this.$el, this.clsFixed, this.clsBelow);
css(this.$el, {position: '', top: '', width: ''});
attr(this.placeholder, 'hidden', '');
},
update() {
const active = this.top !== 0 || this.scroll > this.top;
let top = Math.max(0, this.offset);
if (this.bottom && this.scroll > this.bottom - this.offset) {
top = this.bottom - this.scroll;
}
css(this.$el, {
position: 'fixed',
top: `${top}px`,
width: this.width
});
this.isActive = active;
toggleClass(this.$el, this.clsBelow, this.scroll > this.bottomOffset);
addClass(this.$el, this.clsFixed);
}
}
};
function parseProp(prop, {$props, $el, [`${prop}Offset`]: propOffset}) {
const value = $props[prop];
if (!value) {
return;
}
if (isNumeric(value) && isString(value) && value.match(/^-?\d/)) {
return propOffset + toPx(value);
} else {
return offset(value === true ? $el.parentNode : query(value, $el)).bottom;
}
}
| RadialDevGroup/rails-uikit-sass | vendor/assets/js/core/sticky.js | JavaScript | mit | 8,774 |
// app/models/article.js
var Mongoose = require('mongoose');
// define article schema
var articleSchema = Mongoose.Schema({
url: {
type: String,
required: true
},
tags: [String],
userId: {
type: String,
required: true
},
meta: {
title: String,
author: String,
readTime: String,
summary: String,
domain: String,
createdAt: {
type: Date,
default: Date.now
},
starred: {
type: Boolean,
default: false
},
archived: {
type: Boolean,
default: false
}
},
content: {
html: String,
text: String
}
});
module.exports = Mongoose.model('Article', articleSchema);
| isaacev/Ink | app/models/article.js | JavaScript | mit | 615 |
#include "ReadAlignChunk.h"
#include "Parameters.h"
#include "OutSJ.h"
#include <limits.h>
#include "ErrorWarning.h"
int compareUint(const void* i1, const void* i2) {//compare uint arrays
uint s1=*( (uint*)i1 );
uint s2=*( (uint*)i2 );
if (s1>s2) {
return 1;
} else if (s1<s2) {
return -1;
} else {
return 0;
};
};
void outputSJ(ReadAlignChunk** RAchunk, Parameters& P) {//collapses junctions from all therads/chunks; outputs junctions to file
Junction oneSJ(RAchunk[0]->RA->genOut);
char** sjChunks = new char* [P.runThreadN+1];
#define OUTSJ_limitScale 5
OutSJ allSJ (P.limitOutSJcollapsed*OUTSJ_limitScale,P,RAchunk[0]->RA->genOut);
if (P.outFilterBySJoutStage!=1) {//chunkOutSJ
for (int ic=0;ic<P.runThreadN;ic++) {//populate sjChunks with links to data
sjChunks[ic]=RAchunk[ic]->chunkOutSJ->data;
memset(sjChunks[ic]+RAchunk[ic]->chunkOutSJ->N*oneSJ.dataSize,255,oneSJ.dataSize);//mark the junction after last with big number
};
} else {//chunkOutSJ1
for (int ic=0;ic<P.runThreadN;ic++) {//populate sjChunks with links to data
sjChunks[ic]=RAchunk[ic]->chunkOutSJ1->data;
memset(sjChunks[ic]+RAchunk[ic]->chunkOutSJ1->N*oneSJ.dataSize,255,oneSJ.dataSize);//mark the junction after last with big number
};
};
while (true) {
int icOut=-1;//chunk from which the junction is output
for (int ic=0;ic<P.runThreadN;ic++) {//scan through all chunks, find the "smallest" junction
if ( *(uint*)(sjChunks[ic])<ULONG_MAX && (icOut==-1 ||compareSJ((void*) sjChunks[ic], (void*) sjChunks[icOut])<0 ) ) {
icOut=ic;
};
};
if (icOut<0) break; //no more junctions to output
for (int ic=0;ic<P.runThreadN;ic++) {//scan through all chunks, find the junctions equal to icOut-junction
if (ic!=icOut && compareSJ((void*) sjChunks[ic], (void*) sjChunks[icOut])==0) {
oneSJ.collapseOneSJ(sjChunks[icOut],sjChunks[ic],P);//collapse ic-junction into icOut
sjChunks[ic] += oneSJ.dataSize;//shift ic-chunk by one junction
};
};
//write out the junction
oneSJ.junctionPointer(sjChunks[icOut],0);//point to the icOut junction
//filter the junction
bool sjFilter;
sjFilter=*oneSJ.annot>0 \
|| ( ( *oneSJ.countUnique>=(uint) P.outSJfilterCountUniqueMin[(*oneSJ.motif+1)/2] \
|| (*oneSJ.countMultiple+*oneSJ.countUnique)>=(uint) P.outSJfilterCountTotalMin[(*oneSJ.motif+1)/2] )\
&& *oneSJ.overhangLeft >= (uint) P.outSJfilterOverhangMin[(*oneSJ.motif+1)/2] \
&& *oneSJ.overhangRight >= (uint) P.outSJfilterOverhangMin[(*oneSJ.motif+1)/2] \
&& ( (*oneSJ.countMultiple+*oneSJ.countUnique)>P.outSJfilterIntronMaxVsReadN.size() || *oneSJ.gap<=(uint) P.outSJfilterIntronMaxVsReadN[*oneSJ.countMultiple+*oneSJ.countUnique-1]) );
if (sjFilter) {//record the junction in all SJ
memcpy(allSJ.data+allSJ.N*oneSJ.dataSize,sjChunks[icOut],oneSJ.dataSize);
allSJ.N++;
if (allSJ.N == P.limitOutSJcollapsed*OUTSJ_limitScale ) {
ostringstream errOut;
errOut <<"EXITING because of fatal error: buffer size for SJ output is too small\n";
errOut <<"Solution: increase input parameter --limitOutSJcollapsed\n";
exitWithError(errOut.str(),std::cerr, P.inOut->logMain, EXIT_CODE_INPUT_FILES, P);
};
};
sjChunks[icOut] += oneSJ.dataSize;//shift icOut-chunk by one junction
};
bool* sjFilter=new bool[allSJ.N];
if (P.outFilterBySJoutStage!=2) {
//filter non-canonical junctions that are close to canonical
uint* sjA = new uint [allSJ.N*3];
for (uint ii=0;ii<allSJ.N;ii++) {//scan through all junctions, filter by the donor ditance to a nearest donor, fill acceptor array
oneSJ.junctionPointer(allSJ.data,ii);
sjFilter[ii]=false;
uint x1=0, x2=-1;
if (ii>0) x1=*( (uint*)(allSJ.data+(ii-1)*oneSJ.dataSize) ); //previous junction donor
if (ii+1<allSJ.N) x2=*( (uint*)(allSJ.data+(ii+1)*oneSJ.dataSize) ); //next junction donor
uint minDist=min(*oneSJ.start-x1, x2-*oneSJ.start);
sjFilter[ii]= minDist >= (uint) P.outSJfilterDistToOtherSJmin[(*oneSJ.motif+1)/2];
sjA[ii*3]=*oneSJ.start+(uint)*oneSJ.gap;//acceptor
sjA[ii*3+1]=ii;
if (*oneSJ.annot==0) {
sjA[ii*3+2]=*oneSJ.motif;
} else {
sjA[ii*3+2]=SJ_MOTIF_SIZE+1;
};
};
qsort((void*) sjA, allSJ.N, sizeof(uint)*3, compareUint);
for (uint ii=0;ii<allSJ.N;ii++) {//
if (sjA[ii*3+2]==SJ_MOTIF_SIZE+1) {//no filtering for annotated junctions
sjFilter[sjA[ii*3+1]]=true;
} else {
uint x1=0, x2=-1;
if (ii>0) x1=sjA[ii*3-3]; //previous junction donor
if (ii+1<allSJ.N) x2=sjA[ii*3+3]; //next junction donor
uint minDist=min(sjA[ii*3]-x1, x2-sjA[ii*3]);
sjFilter[sjA[ii*3+1]] = sjFilter[sjA[ii*3+1]] && ( minDist >= (uint) P.outSJfilterDistToOtherSJmin[(sjA[ii*3+2]+1)/2] );
};
};
};
//output junctions
P.sjAll[0].reserve(allSJ.N);
P.sjAll[1].reserve(allSJ.N);
if (P.outFilterBySJoutStage!=1) {//output file
ofstream outSJfileStream((P.outFileNamePrefix+"SJ.out.tab").c_str());
ofstream outSJtmpStream((P.outFileTmp+"SJ.start_gap.tsv").c_str());
for (uint ii=0;ii<allSJ.N;ii++) {//write to file
if ( P.outFilterBySJoutStage==2 || sjFilter[ii] ) {
oneSJ.junctionPointer(allSJ.data,ii);
oneSJ.outputStream(outSJfileStream);//write to file
outSJtmpStream << *oneSJ.start <<'\t'<< *oneSJ.gap <<'\n';
P.sjAll[0].push_back(*oneSJ.start);
P.sjAll[1].push_back(*oneSJ.gap);
};
};
outSJfileStream.close();
} else {//make sjNovel array in P
P.sjNovelN=0;
for (uint ii=0;ii<allSJ.N;ii++) {//count novel junctions
if (sjFilter[ii]) {//only those passing filter
oneSJ.junctionPointer(allSJ.data,ii);
if (*oneSJ.annot==0) P.sjNovelN++;
};
};
P.sjNovelStart = new uint [P.sjNovelN];
P.sjNovelEnd = new uint [P.sjNovelN];
P.inOut->logMain <<"Detected " <<P.sjNovelN<<" novel junctions that passed filtering, will proceed to filter reads that contained unannotated junctions"<<endl;
uint isj=0;
for (uint ii=0;ii<allSJ.N;ii++) {//write to file
if (sjFilter[ii]) {
oneSJ.junctionPointer(allSJ.data,ii);
if (*oneSJ.annot==0) {//unnnotated only
P.sjNovelStart[isj]=*oneSJ.start;
P.sjNovelEnd[isj]=*oneSJ.start+(uint)(*oneSJ.gap)-1;
isj++;
};
};
};
};
};
| alexdobin/STAR | source/outputSJ.cpp | C++ | mit | 7,239 |
package sc_zap
import (
"crypto/sha256"
"encoding/base32"
"errors"
"github.com/watermint/toolbox/essentials/log/esl"
"github.com/watermint/toolbox/infra/app"
"github.com/watermint/toolbox/infra/control/app_control"
"github.com/watermint/toolbox/infra/control/app_resource"
"github.com/watermint/toolbox/infra/security/sc_obfuscate"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
func Unzap(ctl app_control.Control) (b []byte, err error) {
tas, err := app_resource.Bundle().Keys().Bytes("toolbox.appkeys.secret")
if err != nil {
return nil, err
}
return sc_obfuscate.Deobfuscate(ctl.Log(), []byte(app.BuildInfo.Zap), tas)
}
var (
keyEnvNames = []string{
"HOME",
"HOSTNAME",
"CI_BUILD_REF",
"CI_JOB_ID",
"CIRCLE_BUILD_NUM",
"CIRCLE_NODE_INDEX",
}
)
var (
ErrorObfuscateFailure = errors.New("obfuscation failure")
ErrorCantFileWrite = errors.New("cant write file")
)
func NewZap(extraSeed string) string {
seeds := make([]byte, 0)
seeds = strconv.AppendInt(seeds, time.Now().Unix(), 16)
seeds = append(seeds, app.BuildId...)
seeds = append(seeds, extraSeed...)
for _, k := range keyEnvNames {
if v, ok := os.LookupEnv(k); ok {
seeds = append(seeds, k...)
seeds = append(seeds, v...)
}
}
hash := make([]byte, 32)
sha2 := sha256.Sum256(seeds)
copy(hash[:], sha2[:])
b32 := base32.StdEncoding.WithPadding('_').EncodeToString(hash)
return strings.ReplaceAll(b32, "_", "")
}
func Zap(zap string, prjRoot string, data []byte) error {
secretPath := filepath.Join(prjRoot, "resources/keys/toolbox.appkeys.secret")
l := esl.Default()
b, err := sc_obfuscate.Obfuscate(l, []byte(zap), data)
if err != nil {
return ErrorObfuscateFailure
}
if err := ioutil.WriteFile(secretPath, b, 0600); err != nil {
return ErrorCantFileWrite
}
return nil
}
| watermint/toolbox | infra/security/sc_zap/zap.go | GO | mit | 1,823 |
using System;
using Xamarin.Forms;
namespace people
{
public partial class NewItemPage : ContentPage
{
public Item Item { get; set; }
public NewItemPage()
{
InitializeComponent();
Item = new Item
{
Text = "Item name",
Description = "This is an item description."
};
BindingContext = this;
}
async void Save_Clicked(object sender, EventArgs e)
{
MessagingCenter.Send(this, "AddItem", Item);
await Navigation.PopToRootAsync();
}
}
}
| pjsamuel3/xPlatformDotNet | mac_app/people/Views/NewItemPage.xaml.cs | C# | mit | 624 |
using Abstraction;
using System;
namespace CohesionAndCoupling
{
public static class PointUtils
{
public static double CalcDistance2D(Point3D first, Point3D second)
{
double distanceX = (second.X - first.X) * (second.X - first.X);
double distanceY = (second.Y - first.Y) * (second.Y - first.Y);
double distance = Math.Sqrt(distanceX + distanceY);
return distance;
}
public static double CalcDistance3D(Point3D first, Point3D second)
{
double distance = first.DistanceTo(second);
return distance;
}
}
}
| dobri19/OldRepos | Telerik/01-Programming-with-C#/03-HighQualityCode01-2016-August/08-HighClasses/Cohesion-and-Coupling/PointUtils.cs | C# | mit | 642 |
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', 'ArticlesController@index');
//Route::get('contact', 'WelcomeController@contact');
//
//Route::get('home', 'HomeController@index');
Route::resource('articles', 'ArticlesController');
Route::get('tags/{tags}', 'TagsController@show');
Route::controllers(['auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',]);
| bionikspoon/playing-with-laravel-5---getting-up-to-speed | app/Http/routes.php | PHP | mit | 768 |
module Fontello
module Rails
class Engine < ::Rails::Engine
end
end
end
| blackxored/fontello-rails | lib/fontello-rails/engine.rb | Ruby | mit | 84 |
const webModel = require('../webModel');
const webModelFunctions = require('../webModelFunctions');
const robotModel = require('../robotModel');
const getCmdVelIdleTime = require('../getCmdVelIdleTime');
const WayPoints = require('../WayPoints.js');
const wayPointEditor = new WayPoints();
function pickRandomWaypoint() {
if (webModel.debugging && webModel.logBehaviorMessages) {
const message = ' - Checking: Random Waypoint Picker';
console.log(message);
webModelFunctions.scrollingStatusUpdate(message);
}
if (
webModel.ROSisRunning &&
webModel.wayPoints.length > 1 && // If we only have 1, it hardly works.
webModel.mapName !== '' &&
!webModel.pluggedIn &&
!webModel.wayPointNavigator.goToWaypoint &&
!robotModel.goToWaypointProcess.started &&
getCmdVelIdleTime() > 2 // TODO: Set this time in a config or something.
// TODO: Also make it 5 once we are done debugging.
) {
if (webModel.debugging && webModel.logBehaviorMessages) {
console.log(` - Picking a random waypoint!`);
}
if (robotModel.randomWaypointList.length === 0) {
robotModel.randomWaypointList = [...webModel.wayPoints];
}
// Remove most recent waypoint from list in case this was a list reload.
if (robotModel.randomWaypointList.length > 1) {
const lastWaypointEntry = robotModel.randomWaypointList.indexOf(
webModel.wayPointNavigator.wayPointName,
);
if (lastWaypointEntry > -1) {
robotModel.randomWaypointList.splice(lastWaypointEntry, 1);
}
}
// Pick a random entry from the list.
const randomEntryIndex = Math.floor(
Math.random() * robotModel.randomWaypointList.length,
);
// Set this as the new waypoint, just like user would via web site,
// and remove it from our list.
if (webModel.debugging && webModel.logBehaviorMessages) {
console.log(` - ${robotModel.randomWaypointList[randomEntryIndex]}`);
}
wayPointEditor.goToWaypoint(
robotModel.randomWaypointList[randomEntryIndex],
);
robotModel.randomWaypointList.splice(randomEntryIndex, 1);
// Preempt remaining functions, as we have an action to take now.
return false;
}
// This behavior is idle, allow behave loop to continue to next entry.
return true;
}
module.exports = pickRandomWaypoint;
| chrisl8/ArloBot | node/behaviors/pickRandomWaypoint.js | JavaScript | mit | 2,341 |
/**
* Created by zhibo on 15-8-20.
*/
/*
* 上传图片插件改写
* @author:
* @data: 2013年2月17日
* @version: 1.0
* @rely: jQuery
*/
$(function(){
/*
* 参数说明
* baseUrl: 【字符串】表情路径的基地址
*/
var lee_pic = {
uploadTotal : 0,
uploadLimit : 8, //最多传多少张
uploadify:function(){
//文件上传测试
$('#file').uploadify({
swf : 'http://ln.localhost.com/static/uploadify/uploadify.swf',
uploader : '',
width : 120,
height : 30,
fileTypeDesc : '图片类型',
buttonCursor:'pointer',
buttonText:'上传图片',
fileTypeExts : '*.jpeg; *.jpg; *.png; *.gif',
fileSizeLimit : '1MB',
overrideEvents : ['onSelectError','onSelect','onDialogClose'],
//错误替代
onSelectError : function (file, errorCode, errorMsg) {
switch (errorCode) {
case -110 :
$('#error').dialog('open').html('超过1024KB...');
setTimeout(function () {
$('#error').dialog('close').html('...');
}, 1000);
break;
}
},
//开始上传前
onUploadStart : function () {
if (lee_pic.uploadTotal == 8) {
$('#file').uploadify('stop');
$('#file').uploadify('cancel');
$('#error').dialog('open').html('限制为8张...');
setTimeout(function () {
$('#error').dialog('close').html('...');
}, 1000);
} else {
$('.weibo_pic_list').append('<div class="weibo_pic_content"><span class="remove"></span><span class="text">删除</span><img src="' + ThinkPHP['IMG'] + '/loading_100.png" class="weibo_pic_img"></div>');
}
},
//上传成功后的函数
onUploadSuccess : function (file, data, response) {
// alert(data); //打印出返回的数据
$('.weibo_pic_list').append('<input type="hidden" name="images" value='+ data +'> ')
var imageUrl= $.parseJSON(data);
/*
data是返回的回调信息alert
file上传的图片信息 用console.log(file);测试
response上传成功与否 alert
alert(response);
alert(data);
$('.weibo_pic_list').append('<div class="weibo_pic_content"><span class="remove"></span><span class="text">删除</span><img src="' + ThinkPHP['IMG'] + '/loading_100.png" class="weibo_pic_img"></div>'); //把上传的图片返回的缩略图结果写入html页面中
*/
lee_pic.thumb(imageUrl['thumb']); //执行缩略图显示问题
lee_pic.hover();
lee_pic.remove();
//共 0 张,还能上传 8 张(按住ctrl可选择多张
lee_pic.uploadTotal++;
lee_pic.uploadLimit--;
$('.weibo_pic_total').text(lee_pic.uploadTotal);
$('.weibo_pic_limit').text(lee_pic.uploadLimit);
}
});
},
hover:function(){
//上传图片鼠标经过显示删除按扭
var content=$('.weibo_pic_content');
var len=content.length;
$(content[len - 1]).hover(function(){
$(this).find('.remove').show();
$(this).find('.text').show();
},function(){
$(this).find('.remove').hide();
$(this).find('.text').hide();
});
},
remove:function(){
//删除上传的图片操作
var remove=$('.weibo_pic_content .text');
var removelen=remove.length;
$(remove[removelen-1]).on('click',function(){
$(this).parent('.weibo_pic_content').next('input[name="images"]').remove();
$(this).parents('.weibo_pic_content').remove();
//共 0 张,还能上传 8 张(按住ctrl可选择多张
lee_pic.uploadTotal--;
lee_pic.uploadLimit++;
$('.weibo_pic_total').text(lee_pic.uploadTotal);
$('.weibo_pic_limit').text(lee_pic.uploadLimit);
});
},
thumb : function (src) {
/*调节缩略图显示问题-即不以中心点为起点显示*/
var img = $('.weibo_pic_img');
var len = img.length;
//alert(src);
$(img[len - 1]).attr('src', ThinkPHP['LOCALNAME']+src).hide();
setTimeout(function () {
if ($(img[len - 1]).width() > 100) {
$(img[len - 1]).css('left', -($(img[len - 1]).width() - 100) / 2);
}
if ($(img[len - 1]).height() > 100) {
$(img[len - 1]).css('top', -($(img[len - 1]).height() - 100) / 2);
}
//记图片淡入淡出
$(img[len - 1]).attr('src', ThinkPHP['LOCALNAME']+src).fadeIn();
}, 50);
},
init:function(){
/*绑定上传图片弹出按钮响应,初始化。*/
//绑定uploadify函数
lee_pic.uploadify();
/*绑定关闭按钮*/
$('#pic_box a.close').on('click',function(){
$('#pic_box').hide();
$('.pic_arrow_top').hide();
});
/*绑定document点击事件,对target不在上传图片弹出框上时执行引藏事件
//由于鼠标离开窗口就会关闭,影响使用,所以取消
$(document).on('click',function(e){
var target = $(e.target);
if( target.closest("#pic_btn").length == 1 || target.closest(".weibo_pic_content .text").length == 1)
return;
if( target.closest("#pic_box").length == 0 ){
$('#pic_box').hide();
$('.pic_arrow_top').hide();
}
});
*/
}
};
lee_pic.init(); //调用初始化函数。
window.uploadCount = {
clear : function () {
lee_pic.uploadTotal = 0;
lee_pic.uploadLimit = 8;
}
};
}); | zl0314/ruida | static/js/lee_pic.js | JavaScript | mit | 6,916 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cart extends CI_Controller {
private $data;
public function __construct()
{
parent::__construct();
$this->load->library('cart');
$this->load->model("cart_model");
$this->load->model("product_model");
}
public function index(){
if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){
$user_type = 'Guest';
$user_id = $this->session->userdata('__ci_last_regenerate');
}else{
$user_type = 'Member';
$user_id = $this->session->userdata('s_uid');
}
$cart_arr = array();
if(isset($_POST['remove-item'])){
$this->cart_model->remove_cart_product($_POST);
}
if(isset($_GET['quantity'])){
$this->cart_model->update_cart_qty($_GET);
exit;
}
$cart = $this->cart_model->get_cart_items($user_id);
if(!empty($cart)){
$cart_arr = $cart;
//For Promo Code
$get_promo_code = $this->cart_model->get_promo_code($user_id);
if(!empty($get_promo_code)){
array_push($cart_arr,$get_promo_code);
$this->data['coupon_code'] = $get_promo_code;
}
//Get cart data and cart total
$data = $this->get_showcart_details($cart_arr,$user_id,$user_type);
} else {
//Used when cart_detail is empty for user_id and cart_mast have data for that user_id then remove cart_mast detail
$this->cart_model->delete_cart_mast($user_id);
$data = '';
}
/*echo "<pre>";
print_r($data);
exit;*/
$this->data['cart_data'] = $data;
$view_file_name = 'cart_view';
$this->data['view_file_name'] = $view_file_name;
$this->data['user_id'] = $user_id;
$this->data['user_type'] = $user_type;
$this->template->load_cart_view($view_file_name , $this->data);
}//End of index
public function proceed_checkout(){
/*$this->form_validation->set_message('dwfrm_login_username_d0jbuwnvxveb','Please enter valid email;');
$view_file_name = 'proceed_checkout';
$data = '';
$data['view_file_name'] = $view_file_name;
$this->load->view($view_file_name , $data);*/
$this->load->view('proceed_checkout');
}
public function checkout_signin(){
$view_file_name = 'checkout_signin';
$data['view_file_name'] = $view_file_name;
$this->template->load_info_view($view_file_name , $data);
}
public function get_showcart_details($cart,$user_id,$user_type){
if(!empty($cart)){
$data = $this->cart_api($cart,$user_id);
if(!empty($data)){
$cart_total = $data['cart_total'];
$total_discount = $data['total_discount'];
$freight_charges = $data['freight_charges'];//Freight charges get from xml response
$cart_mast_arr = array(
'cart_total' => $cart_total,
'freight_charges' => $freight_charges,
//'total_discount' => $total_discount,
'original_cart_total' => $data['original_cart_total']
);
//Insert or update cart_mast
$insert_total = $this->cart_model->insert_cart_total($user_id,$cart_mast_arr);
$cart_details = $data['cart_detail'];
if(!empty($cart_details)){
foreach ($cart_details as $item){
if (!empty($item['Price']) && $item['Price'] != 0) {
if(!empty($item['Discounts'])){
$discounts = (array)$item['Discounts'];
$discount = (array)$discounts['Discount'];
$discounts_xml = "
<Discounts>
<Discount>
<Id>".$discount['Id']."</Id>
<ParentId>".$discount['ParentId']."</ParentId>
<DiscountType>".$discount['DiscountType']."</DiscountType>
<DiscountTypeId>".$discount['DiscountTypeId']."</DiscountTypeId>
<PromoId>".$discount['PromoId']."</PromoId>
<LoyaltyId />
<Sequence>".$discount['Sequence']."</Sequence>
<Description>".$discount['Description']."</Description>
<Percentage>".$discount['Percentage']."</Percentage>
<Value>".$discount['Value']."</Value>
<TaxPercent>".$discount['TaxPercent']."</TaxPercent>
</Discount>
</Discounts>
";
$discount_percentage = $discount['Percentage'];
}else{
$discounts_xml = '';
$discount_percentage ='';
}
$update_data = array(
'user_id' => $user_id,
'user_type' => $user_type,
'cart_id' => $item['cart_id'],
'product_id' => $item['ProductId'],
'sku' => $item['SkuId'],
'barcode' => $item['barcode'],
'style' => $item['style'],
'color' => $item['color'],
'size' => $item['SizeCode'],
'length' => $item['length'],
'qty' => $item['Quantity'],
'discount_xml' => $discounts_xml,
'discount_percentage' => $discount_percentage,
'discount_price'=> $item['Value'],
'price_sale' => $item['price_sale'],
'unit_price' => $item['Price'],
'original_price'=> $item['original_price'],
'category'=> $item['category'],
'gender'=> $item['gender'],
'operation' => 'update'
);
//Update value from xml into cart_detail
$returnVal = $this->cart_model->insert_into_cart_details($update_data);
}// end of (!empty($item['Price']) && $item['Price'] != 0
}// end of foreach $cart_details
}// end of (!empty($cart_details)
$return_data['cart_xml'] = $data['cart_xml'];
$return_data['cart_api'] = $data['cart_api'];
$return_data['cart_detail'] = $this->cart_model->get_cart_items($user_id);
$return_data['cart_total'] = $cart_total;
} else {
//When API call not get connected directaly call from table
$return_data['cart_detail'] = $this->cart_model->get_cart_items($user_id);
$cart_total = $this->cart_model->get_cart_total($user_id);
if (!empty($cart_total)) {
$return_data['cart_total'] = $cart_total;
} else {
$return_data['cart_total'] = 0;
}
}
} else {
$return_data = '';
}
return $return_data;
} //End of get showcart details
public function cart_api($cart,$user_id){
$data='';
if(!empty($cart)){
$cart_xml="<Cart>
<PersonId>115414</PersonId>
<Contacts>
</Contacts>
<CartDetails>\n\t";
foreach ($cart as $item) {
$sku = $item['sku'];
$qty = $item['qty'];
$cart_xml.=" <CartDetail>
<SkuId>$sku</SkuId>
<Quantity>$qty</Quantity>
</CartDetail>\n\t";
}
$cart_xml.="</CartDetails>
</Cart>";
// $data['cart_xml']=$cart_xml;
/*echo "<pre>";
print_r($cart_xml);
exit;*/
$URL = APP21_URL."/Carts/1234?countryCode=".COUNTRY_CODE;
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml,Accept: version_2.0'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$cart_xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
if ( curl_errno($ch) ) {
$result = 'cURL ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
$curl_errno = curl_errno($ch);
$returnVal = false;
$syncproduct_data = array(
'curl_error_no' => $curl_errno,
'url' => $URL,
'curl_result' => $result,
'error_text' => 'Cart Error'
);
//add alert here
} else {
$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
switch($returnCode){
case 200:
$xml = simplexml_load_string($output);
/*echo "<pre>";
print_r($xml);
exit();*/
$cartdetail_arr=array();
foreach ($xml->CartDetails->CartDetail as $curr_detail) {
$temp = (array) $curr_detail;
$sku = $curr_detail->SkuId;
if(!empty($curr_detail->Price)){
$result = $this->cart_model->get_cart_details($sku,$user_id);
$temp['cart_id']= $result->cart_id;
$temp['original_price']= $result->original_price;
$temp['style']= $result->style;//Style
$temp['price_sale']= $result->price_sale;
$temp['barcode']= $result->barcode;
$temp['color'] = $result->color;
$temp['length'] = $result->length;
$temp['category'] = $result->category;
$temp['gender'] = $result->gender;
}
$cartdetail_arr[] = $temp;
}
$freight_charges = $xml->SelectedFreightOption->Value;//Freight chareges
$total_due = (array)$xml->TotalDue;
$cart_total = $total_due[0];//Cart total
$total_disc = (array)$xml->TotalDiscount;
$total_discount = $total_disc[0];//Cart total
$data['cart_api'] = $xml;
$data['cart_detail']= $cartdetail_arr;
$data['cart_total'] = $cart_total - $freight_charges;
$data['original_cart_total'] = $cart_total;
$data['total_discount'] = $total_discount;
$data['freight_charges'] = $freight_charges;
break;
default:
$result = 'HTTP ERROR -> ' . $returnCode ."<br>".$data;
$return_value = false;
$syncproduct_data = array(
'curl_error_no' => $returnCode,
'url' => $URL,
'curl_result' => $result,
'error_text' => 'Cart Error'
);
//add alert here
break;
}
}
curl_close($ch);
return $data;
}
}//End of cart api
public function add($type = '') {
//retrieve all the post data.
/*echo "<pre>";
print_r($_POST);*/
//exit();
$color = $this->input->post('color');
$style = $this->input->post('style');
$prod_qty = $this->input->post('qty');
$barcode = $this->input->post('barcode');
$size = $this->input->post('size');
$length = $this->input->post('length');
$cart_id = $this->input->post('cart_id');
$seo_category = $this->input->post('seo_category');
$cat_result = $this->product_model->get_product_category($style);
switch($cat_result){
case "t-shirts-and-tops":
$category_result = 't-shirt';
break;
case "pants":
$category_result = 'pant';
break;
case "sweat-shirts":
$category_result = 'sweat shirt';
break;
case "wallets-and-small-goods":
$category_result = 'wallet';
break;
default:
$category_result = $cat_result;
}
if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){
$user_type = 'Guest';
$user_id = $this->session->userdata('__ci_last_regenerate');
}else{
$user_type = 'Member';
$user_id = $this->session->userdata('s_uid');
}
// check if the products exists in database
$prod = $this->cart_model->check_product($barcode);
/*echo "<pre>";
print_r($prod);
exit();*/
if(!empty($prod)){
$data = array(
'user_id' => $user_id,
'user_type' => $user_type,
'product_id' => $prod['product_mast_id'],
'category' => $seo_category, //$prod['productGroup'],
'gender' => $prod['gender'],
'sku' => $prod['sku_idx'], //sku
'barcode' => $barcode, //barcode
'style' => $style, //barcode
'color' => $color,
'size' => $size,
'length' => $length,
'qty' => $prod_qty,
'discount_xml' => '',
'discount_percentage' =>'',
'discount_price' => $prod['price'],
'price_sale' => (!empty($prod['price_sale']))? $prod['price_sale']:0,
'unit_price' => $prod['price'],
'original_price' => $prod['price'],
'created_dt' => date('Y-m-d H:i:s')
);
if($type == 'ajax'){
$data['operation'] = 'insert';
} elseif ($cart_id == null) {
$data['operation'] = 'insert';
} else {
echo $data['operation'] = 'update';
$data['cart_id'] = $cart_id;
}
$this->cart_model->insert_into_cart_details($data);
$flag = TRUE;
/*if($data['operation'] == 'update'):
redirect(base_url()."cart");
endif;*/
} else {
$flag = FALSE;
}
echo $flag;
}// end of add method
public function ajax_cart(){
if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){
$user_id = $this->session->userdata('__ci_last_regenerate');
}else{
$user_id = $this->session->userdata('s_uid');
}
$carts = $this->cart_model->get_cart_items($user_id);
echo json_encode($carts);
} // end of ajax cart method
public function remove_item(){
$this->cart_model->delete_cart_item($_GET);
}//end of remove_item
public function show_product($cat="",$prod_name="",$style="",$color="",$barcode="",$cart_id="",$quantity=""){
/*echo "$cat<br/>";
echo "$prod_name<br/>";
echo "$style<br/>";
echo "$color<br/>";
echo "$barcode<br/>";
exit();*/
$data = '';
$this->data['title']="";
$this->data['category'] = $cat;
if($barcode != ""){
$this->data['prod_barcode_details'] = $this->product_model->get_prod_barcode_details($barcode);
}
if($style != '' && $color != '') {
$this->data['prod_arr'] = $this->product_model->get_showproduct_detail($style,$color);
$this->data['size'] = $this->product_model->get_size($style,$color);
$this->data['length'] = $this->product_model->get_length($style,$color);
$this->data['color'] = $this->product_model->get_color_new($style);
$count = sizeof($this->data['color']);
$this->data['count_color'] = $count;
$this->data['prod_image_arr'] = $this->product_model->get_prod_images($style,$color);
$this->data['count_image'] = sizeof($this->data['prod_image_arr']);
}
$this->data['cat'] = $cat;
$this->data['prod_name'] = $prod_name;
$this->data['cart_id'] = $cart_id;
$this->data['product_color'] = $color;
$this->data['quantity'] = $quantity;
/*echo "<pre>";
print_r($this->data);
exit();*/
$this->data['view_file_name'] = 'quickview_product';
$this->load->view('quickview_product',$this->data);
}
public function checkout_view(){
$data['view_file_name'] = 'checkout_view';
//$data['curr_page_shoppingcart']= 'selected';
$this->template->load_info_view('cart/checkout_view',$data);
}
public function couponvalidate(){
//echo "Hi";exit;
$promotion = array();
$coupon_code = $_POST['promo_code'];
$email_id = $_POST['email_id'];
//echo "CC :".$coupon_code." email : ".$email_id;exit;
if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){
$user_type = 'Guest';
$user_id = $this->session->userdata('__ci_last_regenerate');
}else{
$user_type = 'Member';
$user_id = $this->session->userdata('s_uid');
}
if(isset($coupon_code) && $coupon_code != ''){
$result = $this->cart_model->check_coupon_code($coupon_code);
if($result){
if($result == 'exp'){
$promotion ['result'] = 'fail';
$promotion['msg'] = 'Promotion code expired';
$promotion['redirect'] = 0;
} else {
$check_email = $this->cart_model->check_coupon_emailuser($coupon_code,$email_id);
if($check_email){
if($check_email == 'used'){
$promotion ['result'] = 'fail';
$promotion['msg'] = 'Whoops, you have used this promotion code already';
$promotion['redirect'] = 0;
} else {
$promotion ['result'] = 'success';
$promotion['msg'] = 'Valid Code';
$promotion['url'] = base_url('cart');
$promotion['redirect'] = 1;
$cart_mast = array(
'user_id' => $user_id,
'promo_code' => $result->promo_code,
'promo_string' => $result->promo_string,
'sku' => $result->skuidx,
);
$this->cart_model->insert_cart_mast($cart_mast);
}
}else{
$promotion ['result'] = 'fail';
$promotion['msg'] = 'Please enter the email address you have used to register with, if you have not yet - register here';
$promotion['redirect'] = 0;
}
}
} else{
$promotion ['result'] = 'fail';
$promotion['msg'] = 'Discount Code is not valid';
$promotion['redirect'] = 0;
}
} else {
$promotion ['result'] = 'fail';
$promotion['msg'] = 'Please enter Discount Code';
$promotion['redirect'] = 0;
}
echo json_encode($promotion);
//echo $promotion;
}//end of couponvalidate
public function removecoupon($promo_code) {
if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){
$user_type = 'Guest';
$user_id = $this->session->userdata('__ci_last_regenerate');
}else{
$user_type = 'Member';
$user_id = $this->session->userdata('s_uid');
}
if (isset($promo_code)) {
$promotion = $this->cart_model->deleteCoupon($user_id,$promo_code);
}
redirect('cart');
}//end of removecoupon
} // end of class
| sygcom/diesel_2016 | application/controllers/Cart_2016_09_28.php | PHP | mit | 17,322 |
module Fintech
class Stat
attr_accessor :date, :previous, :rate, :installment, :payments, :fees_assessed
def initialize(attrs = {})
attrs.each { |k, v| send("#{k}=", v) if respond_to?("#{k}=") }
end
def scheduled_payment_cents
@scheduled_payment_cents ||= if payments.any?
[payments.map(&:amount_cents).reduce(:+), remaining_balance].min.truncate
else
0
end
end
def payment_cents
@payment_cents ||= scheduled_payment_cents - apply_to_future_credits_applied
end
def payment_dollars
@payment_dollars ||= payment_cents / 100.0
end
def remaining_balance
@remaining_balance ||= beginning_principal + beginning_interest +
beginning_fees + fees_assessed
end
# apply to future
def beginning_apply_to_future_credits
@beginning_apply_to_future_credits ||= previous.ending_apply_to_future_credits
end
def apply_to_future_credits_earned
@apply_to_future_credits_earned ||= payments.inject(0) do |memo, payment|
memo += (payment.apply_to_future ? payment.amount_cents : 0)
end
end
def apply_to_future_credits_applied
@apply_to_future_credits_applied ||= if installment
[scheduled_payment_cents, beginning_apply_to_future_credits].min
else
0
end
end
def ending_apply_to_future_credits
@ending_apply_to_future_credits ||= beginning_apply_to_future_credits +
apply_to_future_credits_earned -
apply_to_future_credits_applied
end
# principal
def beginning_principal
@beginning_principal ||= previous.ending_principal
end
def ending_principal
@ending_principal ||= beginning_principal - principal
end
def principal
@principal ||= payment_cents - fees_paid - interest_paid
end
def principal_due
@principal_due ||= installment ? installment.principal : 0
end
def total_principal_due
@total_principal_due ||= previous.total_principal_due + principal_due
end
def total_principal_paid
@total_principal_paid ||= previous.total_principal_paid + principal
end
def principal_receivable
@principal_receivable ||= total_principal_due - total_principal_paid
end
# interest
def beginning_interest
@beginning_interest ||= previous.ending_interest
end
def interest_paid
@interest_paid ||= [payment_cents - fees_paid, beginning_interest].min
end
def interest_accrued
@interest_accrued ||= [ending_principal, 0].max * rate.daily
end
def ending_interest
@ending_interest ||= beginning_interest + interest_accrued - interest_paid
end
def total_interest_income
@total_interest_income ||= previous.total_interest_income + interest_accrued
end
def total_interest_due
@total_interest_due ||= if installment
previous.total_interest_income
else
previous.total_interest_due
end
end
def total_interest_paid
@total_interest_paid ||= previous.total_interest_paid + interest_paid
end
def interest_receivable
@interest_receivable ||= total_interest_due - total_interest_paid
end
# fees
def beginning_fees
@beginning_fees ||= previous.ending_fees
end
def fees_paid
@fees_paid ||= [[beginning_fees + fees_assessed, payment_cents].min, 0].max
end
def ending_fees
@ending_fees ||= beginning_fees + fees_assessed - fees_paid
end
def accounts_receivable
@accounts_receivable ||= principal_receivable + interest_receivable
end
def inspect
"<Fintech::Stat date: #{date}, ending_principal: #{ending_principal.truncate}>"
end
end
end
| dvanderbeek/fintech | lib/fintech/stat.rb | Ruby | mit | 3,844 |
<?php
namespace Numa\DOAApiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('NumaDOAApiBundle:Default:index.html.twig', array('name' => $name));
}
}
| genjerator13/doa | src/Numa/DOAApiBundle/Controller/DefaultController.php | PHP | mit | 303 |
import pytest
from aiohttp_json_api.common import JSONAPI_CONTENT_TYPE
class TestDocumentStructure:
"""Document Structure"""
@pytest.mark.parametrize(
'resource_type',
('authors', 'books', 'chapters', 'photos', 'stores')
)
async def test_response_by_json_schema(self, fantasy_client,
jsonapi_validator, resource_type):
response = await fantasy_client.get(f'/api/{resource_type}')
json = await response.json(content_type=JSONAPI_CONTENT_TYPE)
assert jsonapi_validator.is_valid(json)
| vovanbo/aiohttp_json_api | tests/integration/test_document_structure.py | Python | mit | 587 |
from collections import defaultdict
from collections import namedtuple
from itertools import izip
from enum import Enum
from tilequeue.process import Source
def namedtuple_with_defaults(name, props, defaults):
t = namedtuple(name, props)
t.__new__.__defaults__ = defaults
return t
class LayerInfo(namedtuple_with_defaults(
'LayerInfo', 'min_zoom_fn props_fn shape_types', (None,))):
def allows_shape_type(self, shape):
if self.shape_types is None:
return True
typ = shape_type_lookup(shape)
return typ in self.shape_types
class ShapeType(Enum):
point = 1
line = 2
polygon = 3
# aliases, don't use these directly!
multipoint = 1
linestring = 2
multilinestring = 2
multipolygon = 3
@classmethod
def parse_set(cls, inputs):
outputs = set()
for value in inputs:
t = cls[value.lower()]
outputs.add(t)
return outputs or None
# determine the shape type from the raw WKB bytes. this means we don't have to
# parse the WKB, which can be an expensive operation for large polygons.
def wkb_shape_type(wkb):
reverse = ord(wkb[0]) == 1
type_bytes = map(ord, wkb[1:5])
if reverse:
type_bytes.reverse()
typ = type_bytes[3]
if typ == 1 or typ == 4:
return ShapeType.point
elif typ == 2 or typ == 5:
return ShapeType.line
elif typ == 3 or typ == 6:
return ShapeType.polygon
else:
assert False, 'WKB shape type %d not understood.' % (typ,)
def deassoc(x):
"""
Turns an array consisting of alternating key-value pairs into a
dictionary.
Osm2pgsql stores the tags for ways and relations in the planet_osm_ways and
planet_osm_rels tables in this format. Hstore would make more sense now,
but this encoding pre-dates the common availability of hstore.
Example:
>>> from raw_tiles.index.util import deassoc
>>> deassoc(['a', 1, 'b', 'B', 'c', 3.14])
{'a': 1, 'c': 3.14, 'b': 'B'}
"""
pairs = [iter(x)] * 2
return dict(izip(*pairs))
# fixtures extend metadata to include ways and relations for the feature.
# this is unnecessary for SQL, as the ways and relations tables are
# "ambiently available" and do not need to be passed in arguments.
class Metadata(object):
def __init__(self, source, ways, relations):
assert source is None or isinstance(source, Source)
self.source = source and source.name
self.ways = ways
self.relations = relations
class Table(namedtuple('Table', 'source rows')):
def __init__(self, source, rows):
super(Table, self).__init__(source, rows)
assert isinstance(source, Source)
def shape_type_lookup(shape):
typ = shape.geom_type
if typ.startswith('Multi'):
typ = typ[len('Multi'):]
return typ.lower()
# list of road types which are likely to have buses on them. used to cut
# down the number of queries the SQL used to do for relations. although this
# isn't necessary for fixtures, we replicate the logic to keep the behaviour
# the same.
BUS_ROADS = set([
'motorway', 'motorway_link', 'trunk', 'trunk_link', 'primary',
'primary_link', 'secondary', 'secondary_link', 'tertiary',
'tertiary_link', 'residential', 'unclassified', 'road', 'living_street',
])
class Relation(object):
def __init__(self, obj):
self.id = obj['id']
self.tags = deassoc(obj['tags'])
way_off = obj['way_off']
rel_off = obj['rel_off']
self.node_ids = obj['parts'][0:way_off]
self.way_ids = obj['parts'][way_off:rel_off]
self.rel_ids = obj['parts'][rel_off:]
def mz_is_interesting_transit_relation(tags):
public_transport = tags.get('public_transport')
typ = tags.get('type')
return public_transport in ('stop_area', 'stop_area_group') or \
typ in ('stop_area', 'stop_area_group', 'site')
# starting with the IDs in seed_relations, recurse up the transit relations
# of which they are members. returns the set of all the relation IDs seen
# and the "root" relation ID, which was the "furthest" relation from any
# leaf relation.
def mz_recurse_up_transit_relations(seed_relations, osm):
root_relation_ids = set()
root_relation_level = 0
all_relations = set()
for rel_id in seed_relations:
front = set([rel_id])
seen = set([rel_id])
level = 0
if root_relation_level == 0:
root_relation_ids.add(rel_id)
while front:
new_rels = set()
for r in front:
new_rels |= osm.transit_relations(r)
new_rels -= seen
level += 1
if new_rels and level > root_relation_level:
root_relation_ids = new_rels
root_relation_level = level
elif new_rels and level == root_relation_level:
root_relation_ids |= new_rels
front = new_rels
seen |= front
all_relations |= seen
root_relation_id = min(root_relation_ids) if root_relation_ids else None
return all_relations, root_relation_id
# extract a name for a transit route relation. this can expand comma
# separated lists and prefers to use the ref rather than the name.
def mz_transit_route_name(tags):
# prefer ref as it's less likely to contain the destination name
name = tags.get('ref')
if not name:
name = tags.get('name')
if name:
name = name.strip()
return name
def is_station_or_stop(fid, shape, props):
'Returns true if the given (point) feature is a station or stop.'
return (
props.get('railway') in ('station', 'stop', 'tram_stop') or
props.get('public_transport') in ('stop', 'stop_position', 'tram_stop')
)
def is_station_or_line(fid, shape, props):
"""
Returns true if the given (line or polygon from way) feature is a station
or transit line.
"""
railway = props.get('railway')
return railway in ('subway', 'light_rail', 'tram', 'rail')
Transit = namedtuple(
'Transit', 'score root_relation_id '
'trains subways light_rails trams railways')
def mz_calculate_transit_routes_and_score(osm, node_id, way_id, rel_id):
candidate_relations = set()
if node_id:
candidate_relations.update(osm.relations_using_node(node_id))
if way_id:
candidate_relations.update(osm.relations_using_way(way_id))
if rel_id:
candidate_relations.add(rel_id)
seed_relations = set()
for rel_id in candidate_relations:
rel = osm.relation(rel_id)
if rel and mz_is_interesting_transit_relation(rel.tags):
seed_relations.add(rel_id)
del candidate_relations
# this complex query does two recursive sweeps of the relations
# table starting from a seed set of relations which are or contain
# the original station.
#
# the first sweep goes "upwards" from relations to "parent" relations. if
# a relation R1 is a member of relation R2, then R2 will be included in
# this sweep as long as it has "interesting" tags, as defined by the
# function mz_is_interesting_transit_relation.
#
# the second sweep goes "downwards" from relations to "child" relations.
# if a relation R1 has a member R2 which is also a relation, then R2 will
# be included in this sweep as long as it also has "interesting" tags.
all_relations, root_relation_id = mz_recurse_up_transit_relations(
seed_relations, osm)
del seed_relations
# collect all the interesting nodes - this includes the station node (if
# any) and any nodes which are members of found relations which have
# public transport tags indicating that they're stations or stops.
stations_and_stops = set()
for rel_id in all_relations:
rel = osm.relation(rel_id)
if not rel:
continue
for node_id in rel.node_ids:
node = osm.node(node_id)
if node and is_station_or_stop(*node):
stations_and_stops.add(node_id)
if node_id:
stations_and_stops.add(node_id)
# collect any physical railway which includes any of the above
# nodes.
stations_and_lines = set()
for node_id in stations_and_stops:
for way_id in osm.ways_using_node(node_id):
way = osm.way(way_id)
if way and is_station_or_line(*way):
stations_and_lines.add(way_id)
if way_id:
stations_and_lines.add(way_id)
# collect all IDs together in one array to intersect with the parts arrays
# of route relations which may include them.
all_routes = set()
for lookup, ids in ((osm.relations_using_node, stations_and_stops),
(osm.relations_using_way, stations_and_lines),
(osm.relations_using_rel, all_relations)):
for i in ids:
for rel_id in lookup(i):
rel = osm.relation(rel_id)
if rel and \
rel.tags.get('type') == 'route' and \
rel.tags.get('route') in ('subway', 'light_rail', 'tram',
'train', 'railway'):
all_routes.add(rel_id)
routes_lookup = defaultdict(set)
for rel_id in all_routes:
rel = osm.relation(rel_id)
if not rel:
continue
route = rel.tags.get('route')
if route:
route_name = mz_transit_route_name(rel.tags)
routes_lookup[route].add(route_name)
trains = list(sorted(routes_lookup['train']))
subways = list(sorted(routes_lookup['subway']))
light_rails = list(sorted(routes_lookup['light_rail']))
trams = list(sorted(routes_lookup['tram']))
railways = list(sorted(routes_lookup['railway']))
del routes_lookup
# if a station is an interchange between mainline rail and subway or
# light rail, then give it a "bonus" boost of importance.
bonus = 2 if trains and (subways or light_rails) else 1
score = (100 * min(9, bonus * len(trains)) +
10 * min(9, bonus * (len(subways) + len(light_rails))) +
min(9, len(trams) + len(railways)))
return Transit(score=score, root_relation_id=root_relation_id,
trains=trains, subways=subways, light_rails=light_rails,
railways=railways, trams=trams)
_TAG_NAME_ALTERNATES = (
'name',
'int_name',
'loc_name',
'nat_name',
'official_name',
'old_name',
'reg_name',
'short_name',
'name_left',
'name_right',
'name:short',
)
_ALT_NAME_PREFIX_CANDIDATES = (
'name:left:', 'name:right:', 'name:', 'alt_name:', 'old_name:'
)
# given a dictionary of key-value properties, returns a list of all the keys
# which represent names. this is used to assign all the names to a single
# layer. this makes sure that when we generate multiple features from a single
# database record, only one feature gets named and labelled.
def name_keys(props):
name_keys = []
for k in props.keys():
is_name_key = k in _TAG_NAME_ALTERNATES
if not is_name_key:
for prefix in _ALT_NAME_PREFIX_CANDIDATES:
if k.startswith(prefix):
is_name_key = True
break
if is_name_key:
name_keys.append(k)
return name_keys
_US_ROUTE_MODIFIERS = set([
'Business',
'Spur',
'Truck',
'Alternate',
'Bypass',
'Connector',
'Historic',
'Toll',
'Scenic',
])
# properties for a feature (fid, shape, props) in layer `layer_name` at zoom
# level `zoom`. also takes an `osm` parameter, which is an object which can
# be used to look up nodes, ways and relations and the relationships between
# them.
def layer_properties(fid, shape, props, layer_name, zoom, osm):
layer_props = props.copy()
# drop the 'source' tag, if it exists. we override it anyway, and it just
# gets confusing having multiple source tags. in the future, we may
# replace the whole thing with a separate 'meta' for source.
layer_props.pop('source', None)
# need to make sure that the name is only applied to one of
# the pois, landuse or buildings layers - in that order of
# priority.
if layer_name in ('pois', 'landuse', 'buildings'):
for key in name_keys(layer_props):
layer_props.pop(key, None)
# urgh, hack!
if layer_name == 'water' and shape.geom_type == 'Point':
layer_props['label_placement'] = True
if shape.geom_type in ('Polygon', 'MultiPolygon'):
layer_props['area'] = shape.area
if layer_name == 'roads' and \
shape.geom_type in ('LineString', 'MultiLineString') and \
fid >= 0:
mz_networks = []
mz_cycling_networks = set()
mz_is_bus_route = False
for rel_id in osm.relations_using_way(fid):
rel = osm.relation(rel_id)
if not rel:
continue
typ, route, network, ref, modifier = [rel.tags.get(k) for k in (
'type', 'route', 'network', 'ref', 'modifier')]
# the `modifier` tag gives extra information about the route, but
# we want that information to be part of the `network` property.
if network and modifier:
modifier = modifier.capitalize()
us_network = network.startswith('US:')
us_route_modifier = modifier in _US_ROUTE_MODIFIERS
# don't want to add the suffix if it's already there.
suffix = ':' + modifier
needs_suffix = suffix not in network
if us_network and us_route_modifier and needs_suffix:
network += suffix
if route and (network or ref):
mz_networks.extend([route, network, ref])
if typ == 'route' and \
route in ('hiking', 'foot', 'bicycle') and \
network in ('icn', 'ncn', 'rcn', 'lcn'):
mz_cycling_networks.add(network)
if typ == 'route' and route in ('bus', 'trolleybus'):
mz_is_bus_route = True
mz_cycling_network = None
for cn in ('icn', 'ncn', 'rcn', 'lcn'):
if layer_props.get(cn) == 'yes' or \
('%s_ref' % cn) in layer_props or \
cn in mz_cycling_networks:
mz_cycling_network = cn
break
if mz_is_bus_route and \
zoom >= 12 and \
layer_props.get('highway') in BUS_ROADS:
layer_props['is_bus_route'] = True
layer_props['mz_networks'] = mz_networks
if mz_cycling_network:
layer_props['mz_cycling_network'] = mz_cycling_network
is_poi = layer_name == 'pois'
is_railway_station = props.get('railway') == 'station'
is_point_or_poly = shape.geom_type in (
'Point', 'MultiPoint', 'Polygon', 'MultiPolygon')
if is_poi and is_railway_station and \
is_point_or_poly:
node_id = None
way_id = None
rel_id = None
if shape.geom_type in ('Point', 'MultiPoint'):
node_id = fid
elif fid >= 0:
way_id = fid
else:
rel_id = -fid
transit = mz_calculate_transit_routes_and_score(
osm, node_id, way_id, rel_id)
layer_props['mz_transit_score'] = transit.score
layer_props['mz_transit_root_relation_id'] = (
transit.root_relation_id)
layer_props['train_routes'] = transit.trains
layer_props['subway_routes'] = transit.subways
layer_props['light_rail_routes'] = transit.light_rails
layer_props['tram_routes'] = transit.trams
return layer_props
| tilezen/tilequeue | tilequeue/query/common.py | Python | mit | 15,803 |
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
module AliasMethodChainSpec # namespacing
describe "alias method chain" do
module ModifiedAliasMethodChain
# From Tammo Freese's patch:
# https://rails.lighthouseapp.com/projects/8994/tickets/285-alias_method_chain-limits-extensibility
def alias_method_chain(target, feature)
punctuation = nil
with_method, without_method = "#{target}_with_#{feature}#{punctuation}", "#{target}_without_#{feature}#{punctuation}"
method_defined_here = (instance_methods(false) + private_instance_methods(false)).include?(RUBY_VERSION < '1.9' ? target.to_s : target)
unless method_defined_here
module_eval <<-EOS
def #{target}(*args, &block)
super
end
EOS
end
alias_method without_method, target
# alias_method target, with_method
target_method_exists = (instance_methods + private_instance_methods).include?(RUBY_VERSION < '1.9' ? with_method : with_method.to_sym)
raise NameError unless target_method_exists
module_eval <<-EOS
def #{target}(*args, &block)
self.__send__(:'#{with_method}', *args, &block)
end
EOS
end
end
module BasicAliasMethodChain
def alias_method_chain(target, feature)
punctuation = nil
with_method, without_method = "#{target}_with_#{feature}#{punctuation}", "#{target}_without_#{feature}#{punctuation}"
alias_method without_method, target
alias_method target, with_method
end
end
module Bar
def bar
'bar'
end
end
module Baz
def baz
'baz'
end
end
module BazWithLess
def self.included(base)
base.alias_method_chain :baz, :less
end
def baz_with_less
baz_without_less + ' less'
end
end
class Foo
extend ModifiedAliasMethodChain
include Bar
def foo_with_more
foo_without_more + ' more'
end
def foo
'foo'
end
alias_method_chain :foo, :more
def bar_with_less
bar_without_less + ' less'
end
alias_method_chain :bar, :less
include Baz
include BazWithLess
end
class FooBasic
extend BasicAliasMethodChain
include Bar
def foo_with_more
foo_without_more + ' more'
end
def foo
'foo'
end
alias_method_chain :foo, :more
def bar_with_less
bar_without_less + ' less'
end
alias_method_chain :bar, :less
include Baz
include BazWithLess
end
it "test modified alias method chain" do
f = Foo.new
f.foo.should == 'foo more'
f.foo_without_more.should == 'foo'
f.foo_with_more.should == 'foo more'
f.bar.should == 'bar less'
f.bar_without_less.should == 'bar'
f.bar_with_less.should == 'bar less'
f.baz.should == 'baz less'
f.baz_without_less.should == 'baz'
f.baz_with_less.should == 'baz less'
Bar.class_eval do
def bar
'new bar'
end
end
f.bar.should == 'new bar less'
f.bar_without_less.should == 'new bar'
f.bar_with_less.should == 'new bar less'
Foo.class_eval do
def baz_with_less
'lesser'
end
end
f.baz_without_less.should == 'baz'
f.baz_with_less.should == 'lesser'
f.baz.should == 'lesser'
end
it "test basic alias method chain" do
f = FooBasic.new
f.foo.should == 'foo more'
f.foo_without_more.should == 'foo'
f.foo_with_more.should == 'foo more'
f.bar.should == 'bar less'
f.bar_without_less.should == 'bar'
f.bar_with_less.should == 'bar less'
Bar.class_eval do
def bar
'new bar'
end
end
# no change
f.bar.should == 'bar less'
f.bar_without_less.should == 'bar'
f.bar_with_less.should == 'bar less'
Foo.class_eval do
def baz_with_less
raise
end
end
# no error
f.baz_without_less.should == 'baz'
f.baz_with_less.should == 'baz less'
f.baz.should == 'baz less'
end
end
end
| jpartlow/graph_mediator | spec/investigation/alias_method_chain_spec.rb | Ruby | mit | 4,078 |
'use strict';
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1750, 'easeInOutSine');
event.preventDefault();
});
});
| mskalandunas/parcel | app/js/lib/smooth_scroll.js | JavaScript | mit | 270 |
// @flow
import React, { Component } from 'react'
import Carousel, { Modal, ModalGateway } from '../../../../src/components'
import { videos } from './data'
import { Poster, Posters } from './Poster'
import View from './View'
import { Code, Heading } from '../../components'
type Props = {}
type State = { currentModal: number | null }
export default class AlternativeMedia extends Component<Props, State> {
state = { currentModal: null }
toggleModal = (index: number | null = null) => {
this.setState({ currentModal: index })
}
render() {
const { currentModal } = this.state
return (
<div>
<Heading source="/CustomComponents/AlternativeMedia/index.js">Alternative Media</Heading>
<p>
In this example the data passed to <Code>views</Code> contains source and poster information. The <Code><View /></Code> component has been
replaced to render an HTML5 video tag and custom controls.
</p>
<p>
Videos courtesy of{' '}
<a href="https://peach.blender.org/" target="_blank">
"Big Buck Bunny"
</a>{' '}
and{' '}
<a href="https://durian.blender.org/" target="_blank">
"Sintel"
</a>
</p>
<Posters>
{videos.map((vid, idx) => (
<Poster key={idx} data={vid} onClick={() => this.toggleModal(idx)} />
))}
</Posters>
<ModalGateway>
{Number.isInteger(currentModal) ? (
<Modal allowFullscreen={false} closeOnBackdropClick={false} onClose={this.toggleModal}>
<Carousel currentIndex={currentModal} components={{ Footer: null, View }} views={videos} />
</Modal>
) : null}
</ModalGateway>
</div>
)
}
}
| jossmac/react-images | docs/pages/CustomComponents/AlternativeMedia/index.js | JavaScript | mit | 1,796 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.maizegenetics.util;
import net.maizegenetics.dna.snp.GenotypeTable;
/**
*
* @author qs24
*/
public class VCFUtil {
// variables for calculating OS and PL for VCF, might not be in the correct class
private static double error;
private static double v1;
private static double v2;
private static double v3;
private static int[][][] myGenoScoreMap;
public static final int VCF_DEFAULT_MAX_NUM_ALLELES = 3;
static {
error = 0.001; //TODO this seems low, is this the standard
v1 = Math.log10(1.0 - error * 3.0 /4.0);
v2 = Math.log10(error/4);
v3 = Math.log10(0.5 - (error/4.0));
myGenoScoreMap = new int[128][128][];
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 128; j++) {
myGenoScoreMap[i][j]= calcScore(i, j);
}
}
}
private VCFUtil ()
{
}
public static int[] getScore(int i, int j) {
if(i>127 || j>127) return calcScore(i,j);
return myGenoScoreMap[i][j];
}
// Calculate QS and PL for VCF might not be in the correct class
private static int[] calcScore (int a, int b)
{
int[] results= new int[4];
int n = a + b;
int m = a;
if (b > m) {
m = b;
}
double fact = 0;
if (n > m) {
for (int i = n; i > m; i--) {
fact += Math.log10(i);
}
for (int i = 1; i <= (n - m); i++){
fact -= Math.log10(i);
}
}
double aad = Math.pow(10, fact + (double)a * v1 + (double)b * v2);
double abd = Math.pow(10, fact + (double)n * v3);
double bbd = Math.pow(10, fact + (double)b * v1 + (double)a * v2);
double md = aad;
if (md < abd) {
md = abd;
}
if (md < bbd) {
md = bbd;
}
int gq = 0;
if ((aad + abd + bbd) > 0) {
gq = (int)(md / (aad + abd + bbd) * 100);
}
int aa =(int) (-10 * (fact + (double)a * v1 + (double)b * v2));
int ab =(int) (-10 * (fact + (double)n * v3));
int bb =(int) (-10 * (fact + (double)b * v1 + (double)a * v2));
m = aa;
if (m > ab) {
m = ab;
}
if (m>bb) {
m = bb;
}
aa -= m;
ab -= m;
bb -= m;
results[0] = aa > 255 ? 255 : aa;
results[1] = ab > 255 ? 255 : ab;
results[2] = bb > 255 ? 255 : bb;
results[3] = gq;
return results;
}
public static byte resolveVCFGeno(byte[] alleles, int[][] allelesInTaxa, int tx) {
int[] alleleDepth = new int[allelesInTaxa.length];
for (int i=0; i<allelesInTaxa.length; i++)
{
alleleDepth[i] = allelesInTaxa[i][tx];
}
return resolveVCFGeno(alleles, alleleDepth);
}
public static byte resolveVCFGeno(byte[] alleles, int[] alleleDepth) {
int depth = 0;
for (int i = 0; i < alleleDepth.length; i++) {
depth += alleleDepth[i];
}
if (depth == 0) {
return (byte)((GenotypeTable.UNKNOWN_ALLELE << 4) | GenotypeTable.UNKNOWN_ALLELE);
}
int max = 0;
byte maxAllele = GenotypeTable.UNKNOWN_ALLELE;
int nextMax = 0;
byte nextMaxAllele = GenotypeTable.UNKNOWN_ALLELE;
for (int i = 0; i < alleles.length; i++) {
if (alleleDepth[i] > max) {
nextMax = max;
nextMaxAllele = maxAllele;
max = alleleDepth[i];
maxAllele = alleles[i];
} else if (alleleDepth[i] > nextMax) {
nextMax = alleleDepth[i];
nextMaxAllele = alleles[i];
}
}
if (alleles.length == 1) {
return (byte)((alleles[0] << 4) | alleles[0]);
} else {
max = (max > 127) ? 127 : max;
nextMax = (nextMax > 127) ? 127 : nextMax;
int[] scores = getScore(max, nextMax);
if ((scores[1] <= scores[0]) && (scores[1] <= scores[2])) {
return (byte)((maxAllele << 4) | nextMaxAllele);
} else if ((scores[0] <= scores[1]) && (scores[0] <= scores[2])) {
return (byte)((maxAllele << 4) | maxAllele);
} else {
return (byte)((nextMaxAllele << 4) | nextMaxAllele);
}
}
}
}
| yzhnasa/TASSEL-iRods | src/net/maizegenetics/util/VCFUtil.java | Java | mit | 4,777 |
define(['react', 'lodash', './searchView.rt'], function
(React, _, template) {
'use strict';
var exactMatchFieldNames = ['type', 'topic'];
var partialMatchFieldNames = ['title'];
return React.createClass({
displayName: 'searchView',
propTypes: {
configData: React.PropTypes.object.isRequired,
bricksData: React.PropTypes.array.isRequired
},
getInitialState: function(){
return {
type: '',
title: '',
topic: ''
};
},
getSearchResults: function(){
var bricks = this.props.bricksData;
var exactMatchFields = _.pick(this.state, function(value, key){
return _.includes(exactMatchFieldNames, key) && value;
});
var partialMatchFields = _.pick(this.state, partialMatchFieldNames);
var results = _.filter(bricks, function(brick){
var result = true;
_.forEach(exactMatchFields, function(value, key){
if (brick[key] !== value){
result = false;
}
});
_.forEach(partialMatchFields, function(value, key){
if (!_.includes(brick[key], value)){
result = false;
}
});
return result;
});
return results;
},
linkState: function (propName) {
return {
value: this.state[propName],
requestChange: function (value) {
var newState = _.clone(this.state);
newState[propName] = value;
if (this.state[propName] !== value){
this.setState(newState);
}
}.bind(this)
};
},
getResultWrapperClasses: function(result){
return {
'result-wrapper': true,
'selected': result.selected
};
},
render: template
});
});
| rommguy/merkaz-hadraha | src/main/webapp/client/views/searchView.js | JavaScript | mit | 2,152 |
package redis
import (
"encoding/json"
"net"
"github.com/boz/ephemerald/lifecycle"
"github.com/boz/ephemerald/params"
rredis "github.com/garyburd/redigo/redis"
)
func init() {
lifecycle.MakeActionPlugin("redis.exec", actionRedisExecParse)
lifecycle.MakeActionPlugin("redis.ping", actionRedisExecParse)
}
type actionRedisExec struct {
lifecycle.ActionConfig
Command string
}
func actionRedisExecParse(buf []byte) (lifecycle.Action, error) {
action := &actionRedisExec{
ActionConfig: lifecycle.DefaultActionConfig(),
Command: "PING",
}
return action, parseRedisExec(action, buf)
}
func parseRedisExec(action *actionRedisExec, buf []byte) error {
err := json.Unmarshal(buf, action)
if err != nil {
return err
}
return err
}
func (a *actionRedisExec) Do(e lifecycle.Env, p params.Params) error {
address := net.JoinHostPort(p.Hostname, p.Port)
e.Log().WithField("address", address).Debug("dialing")
conn, err := rredis.Dial("tcp", address,
rredis.DialConnectTimeout(a.Timeout),
rredis.DialReadTimeout(a.Timeout),
rredis.DialWriteTimeout(a.Timeout))
if err != nil {
e.Log().WithError(err).Debug("ERROR: dialing")
return err
}
defer conn.Close()
e.Log().WithField("command", a.Command).Debug("executing")
_, err = conn.Do(a.Command)
if err != nil {
e.Log().WithError(err).Debug("ERROR: executing")
}
return err
}
| boz/ephemerald | builtin/redis/exec.go | GO | mit | 1,370 |
import requests
from pprint import pprint
r = requests.get("http://pokeapi.co/api/v2/pokedex/1")
#pprint(r.json()["pokemon_entries"])
regpath = "regular/"
shinypath = "shiny/"
import os
for pkmn in r.json()["pokemon_entries"]:
id = str(pkmn["entry_number"])
name = pkmn["pokemon_species"]["name"]
for file in os.listdir(regpath):
if file.split(".")[0] == name:
os.rename(os.path.join(regpath, file), os.path.join(regpath, file.replace(name, id)))
os.rename(os.path.join(shinypath, file), os.path.join(shinypath, file.replace(name, id)))
break
| MarkSpencerTan/pokemaster_bot | img/pokemon/image_rename.py | Python | mit | 559 |
export * from './InvalidValueInput'
| sanity-io/sanity | packages/@sanity/form-builder/src/inputs/InvalidValueInput/index.ts | TypeScript | mit | 36 |
package net.kahowell.xsd.fuzzer.generator;
import java.lang.annotation.Annotation;
import java.text.MessageFormat;
import javax.xml.namespace.QName;
import net.kahowell.xsd.fuzzer.XsdTypeValueGenerator;
import net.kahowell.xsd.fuzzer.config.DefaultGeneratorsModule;
/**
* Provides functions for selecting an {@link XsdTypeValueGenerator} using
* Guice.
*
* Copyright (c) 2012 Kevin Howell. See LICENSE file for copying permission.
*
* @author Kevin Howell
*/
public class XsdType {
private static GeneratesType typeFromParts(final String namespace, final String localname) {
return new GeneratesType() {
public Class<? extends Annotation> annotationType() {
return GeneratesType.class;
}
public String namespace() {
return namespace;
}
public String localname() {
return localname;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((localname() == null) ? 0 : localname().hashCode());
result = prime * result
+ ((namespace() == null) ? 0 : namespace().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof GeneratesType))
return false;
GeneratesType type = (GeneratesType) obj;
return type.namespace().equals(namespace()) && type.localname().equals(localname());
}
public String toString() {
return MessageFormat.format("T={1}@{0}", namespace(), localname());
}
};
}
/**
* Constructs a {@link GeneratesType} instance from a {@link QName}.
*
* @param name the qualified name
* @return a {@link GeneratesType} instance for the given qualified name
*/
public static GeneratesType named(QName name) {
return typeFromParts(name.getNamespaceURI(), name.getLocalPart());
}
/**
* Constructs a {@link GeneratesType} instance from an annotation instance.
* This is used to assist Guice in binding the generators. (It returns an
* instance that can be compared against another instance).
*
* @param annotation instance of the annotation
* @return a {@link GeneratesType} instance for the given qualified name.
* @see DefaultGeneratorsModule#configure(com.google.inject.Binder)
*/
public static GeneratesType fromAnnotation(GeneratesType annotation) {
return typeFromParts(annotation.namespace(), annotation.localname());
}
}
| kahowell/java-xmlfuzzer | src/main/java/net/kahowell/xsd/fuzzer/generator/XsdType.java | Java | mit | 2,469 |
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
let zipcode = params.zipcode || '97212';
let zipcode2 = params.zipcode2 || '98074';
return Ember.RSVP.hash({
first_location: $.getJSON(`https://api.wunderground.com/api/13fcb02d16148708/conditions/forecast/q/${zipcode}.json`).then(function(data) {
data.forecast.days = data.forecast.simpleforecast.forecastday.slice(1,4);
return data;
}),
second_location: $.getJSON(`https://api.wunderground.com/api/13fcb02d16148708/conditions/forecast/q/${zipcode2}.json`).then(function(data) {
data.forecast.days = data.forecast.simpleforecast.forecastday.slice(1,4);
return data;
})
});
},
afterModel: function(model) {
model.temperature_difference = Math.abs(parseFloat(model.second_location.current_observation.temp_f - model.first_location.current_observation.temp_f).toFixed(2));
},
actions: {
updateZip(model) {
this.transitionTo('index', model.first_location.current_observation.display_location.zip, model.second_location.current_observation.display_location.zip);
}
}
});
| gpxl/simple-weather-ember | app/routes/index.js | JavaScript | mit | 1,151 |
import { RpcRequest } from '../RpcRequest'
import { RpcResponse } from '../RpcResponse'
/**
* JSON-RPC request for the `help` command.
*/
export interface HelpRequest extends RpcRequest {
readonly method: 'help'
readonly params?: [string]
}
/**
* JSON-RPC response for the `help` command.
*/
export interface HelpResponse extends RpcResponse {
readonly result: HelpResult | null
}
/**
* Result of the `help` command.
*/
export type HelpResult = string
export function Help(command?: string): HelpRequest {
return command === undefined ? { method: 'help' } : { method: 'help', params: [command] }
}
| Tilkal/multichain-api | src/Commands/Help.ts | TypeScript | mit | 616 |
namespace DvachBrowser3.TextRender
{
/// <summary>
/// Элемент программы с атрибутом.
/// </summary>
public interface IAttributeRenderProgramElement : IRenderProgramElement
{
/// <summary>
/// Атрибут.
/// </summary>
ITextRenderAttribute Attribute { get; }
}
} | Opiumtm/DvachBrowser3 | DvachBrowser3.TextRender/RenderProgram/IAttributeRenderProgramElement.cs | C# | mit | 353 |
#include <string>
#include <iostream>
#include "Flight.h"
#include "Plane.h"
using namespace std;
int main()
{
Flight test(3233, 43, "JFK", "FLF", "Boeing 747", 614, "NA");
cout << test.getFlightInfo() << endl;
} | johnnynybble/CIS17A-SI-CODE | Session-11-6-17/main.cpp | C++ | mit | 218 |
/**
* Copyright 2000-2010 Geometria Contributors
* http://geocentral.net/geometria
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License
* http://www.gnu.org/licenses
*/
package net.geocentral.geometria.model.answer.condition;
import javax.vecmath.Point3d;
import net.geocentral.geometria.model.GDocument;
import net.geocentral.geometria.model.GProblem;
import org.w3c.dom.Element;
public interface GCondition {
public String getDescription();
public void make(Element node, GProblem document) throws Exception;
public void validate(String valueString, GDocument document)
throws Exception;
public void serialize(StringBuffer buf);
public String getStringValue();
public boolean verify(Point3d[] coords, GDocument document);
}
| stelian56/geometria | archive/3.0/src/net/geocentral/geometria/model/answer/condition/GCondition.java | Java | mit | 855 |
(function () {
'use strict';
angular
.module('starter-app')
.run(['$window', function ($window) {
$window.proj4 = require('proj4');
}]);
})(); | OrdnanceSurvey/web-elements-starter | src/app/app.constants.js | JavaScript | mit | 187 |
<?php
$lang['dashboardHeading'] = 'Dashboard';
$lang['bestSafetyHeading'] = 'Best Safety';
$lang['auditsHeading'] = 'Audits';
$lang['auditsfail'] = 'Failed';
$lang['auditspassed'] = 'Passed';
$lang['auditsissues'] = 'Issues';
$lang['auditsasset'] = 'Asset';
$lang['auditsdriver'] = 'DRIVER';
$lang['auditsshipper'] = 'SHIPPER';
$lang['auditscon'] = 'CONS.';
$lang['auditscust'] = 'CUST';
$lang['capacityanalysis'] = 'CAPACITY ANALYSIS';
$lang['drivermsg'] = 'driver messages - last 7 days';
$lang['drivermsginemncy'] = 'In Emergency';
$lang['drivermsgonhighprior'] = 'High Priority';
$lang['drivermsgopened'] = 'Opened';
$lang['drivermsgunopened'] = 'Un Opened';
$lang['trucklocation'] = 'Trucks Location';
$lang['newsfeed'] = 'NEWS FEED';
$lang['topcustomer'] = 'TOP 5 CUSTOMERS';
$lang['topcustomercamas'] = 'Camas Transport';
$lang['topcustomerrpm'] = 'RPM Freight';
$lang['topcustomervclogist'] = 'VC Logistics';
$lang['topcustomermaston'] = 'Matson Logistics';
$lang['topcustomerbennett'] = 'Bennett';
$lang['loadonroad'] = 'Loads On the Road';
$lang['loadonroadorigin'] = 'ORIGIN';
$lang['loadonroaddseti'] = 'DESTINATION';
$lang['loadonroadpayment'] = 'PAYMENT';
$lang['loadonroadmiles'] = 'MILES';
$lang['loadonroadrpm'] = 'RPM';
$lang['noloadonroad'] = 'No Load on the road';
$lang['wheatherinfo'] = 'Weather Info';
$lang['nowheatherinfo'] = 'weather not found!';
$lang['wheatherinfocurrently'] = 'Currently';
$lang['wheatherinfoscale'] = '°F';
$lang['wheatherfeellike'] = 'Feels Like';
$lang['wheatherinfo1'] = 'Weather information';
$lang['wheatherwind'] = 'Wind';
$lang['wheathersunrise'] = 'Sunrise';
$lang['wheatherhumidity'] = 'Humidity';
$lang['wheathersunset'] = 'Sunset';
$lang['wheathernight'] = 'Night';
$lang['loadstatus'] = 'Load Status';
$lang['loadstatusassigned'] = 'Assigned';
$lang['loadstatusbooked'] = 'Booked';
$lang['loadstatusinprogress'] = 'In Progress';
$lang['loadstatusnoloads'] = 'No Load';
$lang['loadstatusdelivered'] = 'Delivered';
$lang['loadstatusinvoice'] = 'Invoices';
$lang['loadstatusinvoicwaitppr'] = 'Waiting Paperwork';
$lang['loadstatusinvoicpaynoreciv'] = 'Payments Not Recieved';
$lang['loadstatusinvoicpayoncoll'] = 'Payment On Collection';
$lang['allDrivers'] = 'All Drivers';
$lang['allGroups'] = 'All Groups';
$lang['showingWeatherFor'] = 'Showing weather info for ';
$lang['selectDriver'] = 'Select Driver';
$lang['invoiced'] = 'Invoiced';
$lang['charges'] = 'Charges';
$lang['miles'] = 'Miles';
$lang['deadmiles'] = 'Dead Miles';
$lang['profit'] = 'Profit';
$lang['profit_percent'] = 'Profit %';
$lang['dispatcher'] = 'Dispatcher';
$lang['driver'] = 'Driver';
$lang['loadno'] = 'Load #';
$lang['pickupdate'] = 'Pickup Date';
$lang['deliverdate'] = 'Delivery Date';
$lang['todayinsights'] = 'TODAY INSIGHTS';
$lang['pickup'] = 'PICKUP';
$lang['inprogress'] = 'INPROGRESS';
$lang['delivery'] = 'DELIVERY';
$lang['idle'] = 'IDLE';
$lang['driver'] = 'DRIVER';
$lang['truck'] = 'TRUCK';
$lang['origin'] = 'ORIGIN';
$lang['st'] = 'ST';
$lang['destination'] = 'DESTINATION';
$lang['payment'] = 'PAYMENT';
$lang['rpm'] = 'RPM';
$lang['company'] = 'COMPANY';
$lang['leaderboard'] = 'LEADER BOARD';
$lang['message'] = 'Message';
$lang['weatherreport'] = 'Weather Report';
$lang['day'] = 'Day';
$lang['temperature'] = 'Temperature';
$lang['wind'] = 'Wind';
$lang['humidity'] = 'Humidity';
$lang['mintemperature'] = 'Min. Temperature';
$lang['maxtemperature'] = 'Max. Temperature';
$lang['feelslike'] = 'Feels Like';
$lang['driverwithouttr'] = 'active drivers without truck';
$lang['trucksnotrep'] = 'Trucks are not reporting current location';
$lang['truckwithoutdriver'] = 'Trucks without driver';
$lang['incompleteLoads'] = 'Incomplete Loads';
| sureshClerisy/trackingnew | application/language/english/dashboard_lang.php | PHP | mit | 3,725 |
"use strict";
define([
'lodash',
'jquery',
'jquery-ui/ui/autocomplete',
'deckslots/cardstore'
], function(_, $, autocomplete, CardStore) {
var CardSelector = function (conf) {
this.domNode = conf.domNode;
this.onSelectCallback = conf.onSelect;
this.cardSource = [];
var that = this;
this.loadCards(function () {
that.domNode.autocomplete({
source: that.cardSource,
focus: function(event, ui) {
that.domNode.val(ui.item.label);
return false;
},
select: function(event, ui) {
that.onSelectCallback(event, ui);
that.domNode.val('');
return false;
}
});
})
};
CardSelector.prototype.loadCards = function (callback) {
var that = this;
_.forEach(CardStore.cards, function(card) {
that.cardSource.push({
label : card.name,
value : card.id,
card: card
});
});
callback();
};
return CardSelector;
}); | hodavidhara/deckslots | static/js/deckslots/cardselector.js | JavaScript | mit | 1,188 |
for(_="taz'+qadd@=a.Z0,Wre!SCALE6void(~trans%[1]+'$=\"qc`.map(_',^0 K!turnJ){JIentRdelzQ/)&&(QPelmSvgO),100W5K75,^'fill: # 1075function+)/g,(,K5W0zngramZpagepolygon[0]ate(a){mousevar 25 25,25Zzrget touchpointsc!SVG( W 5W5000c.match(/'],['.!place(/szrtetAttribute('active%l aI'<svg viewBox=\"KKK800\">qa_(cI'< `+'\" style`$\"/>'}).join('')+'</svg>'}=null,Q,,=rot='^m=window.m=cZtype,dX,eY,g=1;J''=.zgName&&r|w/)?(,~=[d,e])):~&&(vP=[d-,e-[1]],='(qQ+^qQ$)'p|ndP?(='^.s^.g')([\\d.]hI+h+Q[g?g=0:g=1]})Q==0):console.log('click')a.p!vRDefault(.s%form^+'qrot||(=0)))},6=2.5,=[['WK1f3fW 1074D9,7FDBFF,5K39CCCC5253D997052ECC400 75,01FF70']]_J a=a(\\dcI c*6}a}); @(a,c,d){e=documR.c!ElemR(a);J e.innerHTML=c,d.p!pend(ee}O=@('div^ b);'down move upendmove'\\w+/g,O.@EvRListener(a,m)});";G=/[-O-RI-K^-`$%~6!WZ@qz]/.exec(_);)with(_.split(G))_=join(shift());eval(_)
| ripter/js1k | 2017/dragdrop/914_code_babili_rp.js | JavaScript | mit | 986 |
#!/usr/bin/env ruby
require 'optparse'
require 'bio-logger'
require 'systemu'
SCRIPT_NAME = File.basename(__FILE__); LOG_NAME = SCRIPT_NAME.gsub('.rb','')
# Parse command line options into the options hash
options = {
:logger => 'stderr',
:log_level => 'info',
}
o = OptionParser.new do |opts|
opts.banner = "
Usage: #{SCRIPT_NAME} -b <contigs_against_assembly.blast_outfmt6.csv>
Takes a set of contigs, and an assembly. Works out if there are any contigs where there is a blast hit spanning of the contigs using two of the assembly's contig ends.\n\n"
opts.on("--query FASTA_FILE", "new contigs fasta file [Required]") do |arg|
options[:query_file] = arg
end
opts.on("--blastdb FASTA_FILE_FORMATTED", "basename of makeblastdb output [Required]") do |arg|
options[:blastdb] = arg
end
# logger options
opts.separator "\nVerbosity:\n\n"
opts.on("-q", "--quiet", "Run quietly, set logging to ERROR level [default INFO]") {options[:log_level] = 'error'}
opts.on("--logger filename",String,"Log to file [default #{options[:logger]}]") { |name| options[:logger] = name}
opts.on("--trace options",String,"Set log level [default INFO]. e.g. '--trace debug' to set logging level to DEBUG"){|s| options[:log_level] = s}
end; o.parse!
if ARGV.length != 0 or options[:query_file].nil? or options[:blastdb].nil?
$stderr.puts o
exit 1
end
# Setup logging
Bio::Log::CLI.logger(options[:logger]); Bio::Log::CLI.trace(options[:log_level]); log = Bio::Log::LoggerPlus.new(LOG_NAME); Bio::Log::CLI.configure(LOG_NAME)
# Read in the blast file
blast_results = []
class BlastResult
attr_accessor :qseqid, :sseqid, :pident, :length, :mismatch, :gapopen, :qstart, :qend, :sstart, :subject_end, :evalue, :bitscore, :query_length, :subject_length
attr_accessor :cutoff_inwards
def initialize
@cutoff_inwards = 500
end
def hits_end_of_subject?
@subject_end >= @subject_length-@cutoff_inwards and @length >= 100
end
def hits_start_of_subject?
@sstart <= @cutoff_inwards and @length >= 100
end
def hits_end_of_query?
@qend >= @query_length-@cutoff_inwards and @length >= 100
end
def hits_start_of_query?
@qstart <= @cutoff_inwards and @length >= 100
end
end
status, blast_output, stderr = systemu "blastn -query #{options[:query_file].inspect} -db #{options[:blastdb].inspect} -outfmt '6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore qlen slen' -evalue 1e-5"
raise stderr unless stderr==""
raise "bad status running blast" unless status.exitstatus == 0
log.debug "Finished running blast, presumably successfully"
blast_output.each_line do |line|
res = BlastResult.new
row = line.chomp.split "\t"
[:qseqid, :sseqid, :pident, :length, :mismatch, :gapopen, :qstart,
:qend, :sstart, :subject_end, :evalue, :bitscore,
:query_length, :subject_length].each_with_index do |attr, i|
res.send "#{attr}=".to_sym, row[i]
end
[:length, :mismatch, :gapopen, :qstart,
:qend, :sstart, :subject_end,:query_length, :subject_length].each do |attr|
res.send "#{attr}=".to_sym, res.send(attr).to_i
end
[:pident, :evalue, :bitscore].each do |attr|
res.send "#{attr}=".to_sym, res.send(attr).to_f
end
blast_results.push res
end
log.info "Parsed #{blast_results.length} blast results e.g. #{blast_results[0].inspect}"
query_to_blast_results = {}
hit_to_blast_results = {}
blast_results.each do |result|
query_to_blast_results[result.qseqid] ||= []
query_to_blast_results[result.qseqid].push result
hit_to_blast_results[result.sseqid] ||= []
hit_to_blast_results[result.sseqid].push result
end
# For each query sequence, does it map to the ends of both contigs
header = %w(query subject1 subject2 qstart1? qend1? sstart1? send1? qstart2? qend2? sstart2? send2?).join("\t")
query_to_blast_results.each do |query_id, hits|
query_length = hits[0].query_length
keepers = []
hits.each do |hit|
# perfect if it hits the start or the end (but not both) of both the query and the subject, unless it is circular
if hit.hits_start_of_query? ^ hit.hits_end_of_query? and
hit.hits_start_of_subject? ^ hit.hits_end_of_subject?
keepers.push hit
elsif hit.hits_start_of_query? or hit.hits_end_of_query? or
hit.hits_start_of_subject? or hit.hits_end_of_subject?
log.info "There's a half-correct hit for #{query_id}: qstart? #{hit.hits_start_of_query?} qend #{hit.hits_end_of_query?} "+
"sstart #{hit.hits_start_of_subject?} send #{hit.hits_end_of_subject?}, to subject sequence #{hit.sseqid}"
end
end
if keepers.empty?
log.debug "no latchings found for #{query_id}"
elsif keepers.length == 1
log.info "Query #{query_id} only latches on to a single end, maybe manually inspect"
elsif keepers.length == 2
log.debug "Query #{query_id} has 2 keepers!"
q = keepers.collect{|hit| hit.hits_start_of_query?}.join
s = keepers.collect{|hit| hit.hits_start_of_subject?}.join
if (q == 'truefalse' or q == 'falsetrue') and
(s == 'truefalse' or s == 'falsetrue')
outs = (0..1).collect{|i|
[
keepers[i].hits_start_of_query?,
keepers[i].hits_end_of_query?,
keepers[i].hits_start_of_subject?,
keepers[i].hits_end_of_subject?,
]
}.flatten
unless header.nil?
puts header
header = nil
end
puts [query_id, keepers[0].sseqid, keepers[1].sseqid, outs].flatten.join("\t")
else
log.info "Query #{query_id} has 2 keepers, but they are fighting it seems"
end
else
log.info "More than 2 keepers found for #{query_id}, manual inspection likely required"
end
end
| timbalam/finishm | bin/contigs_against_assembly.rb | Ruby | mit | 5,675 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
public class HighScores
{
private static HighScores _instance;
public static HighScores Instance
{
get
{
if (_instance==null)
{
_instance = new HighScores();
}
return _instance;
}
set { _instance = value; }
}
private List<PlayerScore> _scores;
public List<PlayerScore> Scores
{
get { return _scores; }
private set { _scores = value; }
}
private HighScores()
{
load();
}
public void SubmitScore(string name, int score)
{
Scores.Add(new PlayerScore(name, score));
Scores = Scores.OrderBy(s => s.Score).Reverse<PlayerScore>().ToList<PlayerScore>();
Scores.RemoveAt(10);
save();
}
public void Clear()
{
for (int i = 0; i < 10; i++)
{
PlayerPrefs.SetString(i.ToString(), "Foo Bar");
PlayerPrefs.SetInt(i.ToString(), 0);
}
load();
}
void save()
{
for (int i = 0; i < 10; i++)
{
PlayerPrefs.SetString(i.ToString()+"name", Scores[i].Name);
PlayerPrefs.SetInt(i.ToString(), Scores[i].Score);
}
}
void load()
{
Scores = new List<PlayerScore>(10);
for (int i = 0; i < 10; i++)
{
Scores.Add(new PlayerScore(PlayerPrefs.GetString(i.ToString()+"name", "Foo Bar"), PlayerPrefs.GetInt(i.ToString(), 0)));
}
Scores = Scores.OrderBy(s => s.Score).Reverse<PlayerScore>().ToList<PlayerScore>();
}
}
public class PlayerScore
{
public string Name { get; set; }
public int Score { get; set; }
public PlayerScore(string name, int score)
{
Name = name;
Score = score;
}
}
| richardkopelow/Wedges | Assets/HighScores.cs | C# | mit | 1,896 |
"""
Script that trains Sklearn singletask models on GDB7 dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from sklearn.kernel_ridge import KernelRidge
tasks, datasets, transformers = dc.molnet.load_qm7(
featurizer='CoulombMatrix', split='stratified', move_mean=False)
train, valid, test = datasets
regression_metric = dc.metrics.Metric(
dc.metrics.mean_absolute_error, mode="regression")
def model_builder(model_dir):
sklearn_model = KernelRidge(kernel="rbf", alpha=5e-4, gamma=0.008)
return dc.models.SklearnModel(sklearn_model, model_dir)
model = dc.models.SingletaskToMultitask(tasks, model_builder)
# Fit trained model
model.fit(train)
model.save()
train_evaluator = dc.utils.evaluate.Evaluator(model, train, transformers)
train_scores = train_evaluator.compute_model_performance([regression_metric])
print("Train scores [kcal/mol]")
print(train_scores)
test_evaluator = dc.utils.evaluate.Evaluator(model, test, transformers)
test_scores = test_evaluator.compute_model_performance([regression_metric])
print("Validation scores [kcal/mol]")
print(test_scores)
| ktaneishi/deepchem | examples/qm7/qm7_sklearn.py | Python | mit | 1,271 |
package com.bitdecay.game.ui.pointBurst;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.AlphaAction;
import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.bitdecay.game.MyGame;
public class PointBurstEffect extends Group {
final float DURATION = 2;
public PointBurstEffect(Image mainIcon, Image secondaryIcon, String text) {
addActor(mainIcon);
if (secondaryIcon != null) {
secondaryIcon.setPosition(secondaryIcon.getWidth() * -0.55f, mainIcon.getY());
addActor(secondaryIcon);
}
Label textLabel = new Label(text, new Label.LabelStyle(MyGame.FONT, Color.WHITE));
textLabel.setFontScale(2);
textLabel.moveBy(mainIcon.getWidth() * mainIcon.getScaleX(), mainIcon.getHeight() * mainIcon.getScaleY() / 2 - textLabel.getHeight() * 0.55f);
addActor(textLabel);
float screenHeight = Gdx.graphics.getHeight();
setPosition(Gdx.graphics.getWidth() / 2, screenHeight / 2);
MoveToAction moveTo = Actions.moveTo(getX(), screenHeight);
moveTo.setDuration(DURATION);
addAction(moveTo);
AlphaAction alphaAction = Actions.alpha(0, DURATION);
addAction(alphaAction);
// TODO Play sound here?
}
@Override
public void act(float delta) {
super.act(delta);
if (!hasActions()) {
addAction(Actions.removeActor());
}
}
}
| bitDecayGames/LudumDare38 | src/main/java/com/bitdecay/game/ui/pointBurst/PointBurstEffect.java | Java | mit | 1,697 |
import { GluegunCommand } from 'gluegun'
import { SolidarityOutputMode, SolidarityRequirementChunk, SolidarityRunContext } from '../types'
import Listr from 'listr'
module.exports = {
alias: 'f',
description: 'Applies all specified fixes for rules',
run: async (context: SolidarityRunContext) => {
// Node Modules Quirk
require('../extensions/functions/quirksNodeModules')
const { toPairs } = require('ramda')
const { print, solidarity } = context
const { checkRequirement, getSolidaritySettings, setOutputMode } = solidarity
// get settings or error
let solidaritySettings
try {
solidaritySettings = await getSolidaritySettings(context)
} catch (e) {
print.error(e.message || 'No Solidarity Settings Found')
print.info(
`Make sure you are in the correct folder or run ${print.colors.success(
'solidarity onboard'
)} to create a .solidarity file for this project.`
)
process.exit(3)
}
// Merge flags and configs
context.outputMode = setOutputMode(context.parameters, solidaritySettings)
// Adjust output depending on mode
let listrSettings: Object = { concurrent: true, collapse: false, exitOnError: false }
switch (context.outputMode) {
case SolidarityOutputMode.SILENT:
listrSettings = { ...listrSettings, renderer: 'silent' }
break
case SolidarityOutputMode.MODERATE:
// have input clear itself
listrSettings = { ...listrSettings, clearOutput: true }
}
// build Listr of checks
const checks = new Listr(
await toPairs(solidaritySettings.requirements).map((requirement: SolidarityRequirementChunk) => ({
title: requirement[0],
task: async () => checkRequirement(requirement, context, true),
})),
listrSettings
)
// run the array of promises in Listr
await checks
.run()
.then(results => {
const silentOutput = context.outputMode === SolidarityOutputMode.SILENT
// Add empty line between final result if printing rule results
if (!silentOutput) print.success('')
if (!silentOutput) print.success(print.checkmark + ' Solidarity checks valid')
})
.catch(_err => {
const silentOutput = context.outputMode === SolidarityOutputMode.SILENT
// Used to have message in the err, but that goes away with `exitOnError: false` so here's a generic one
if (!silentOutput) print.error('Solidarity checks failed')
process.exit(2)
})
},
} as GluegunCommand
| infinitered/solidarity | src/commands/fix.ts | TypeScript | mit | 2,567 |
// Parser.cc for FbTk
// Copyright (c) 2004 - 2006 Fluxbox Team (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "Parser.hh"
namespace FbTk {
const Parser::Item Parser::s_empty_item("", "");
};
| ystk/debian-fluxbox | src/FbTk/Parser.cc | C++ | mit | 1,265 |
import * as vscode from 'vscode';
import Server from './Server';
import Logger from '../utils/Logger';
const L = Logger.getLogger('StatusBarItem');
class StatusBarItem {
server: Server = null;
item: vscode.StatusBarItem;
constructor() {
L.trace('constructor');
this.item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right);
this.item.color = new vscode.ThemeColor('statusBar.foreground');
this.item.text = '$(rss)';
}
setServer(server: Server) {
L.trace('setServer');
if (this.server) {
L.debug('setServer', 'remove all listeners');
this.server.removeAllListeners();
}
this.server = server;
this.handleEvents(server);
}
handleEvents(server: Server) {
L.trace('handleEvents');
server.on('restarting', this.onRestarting.bind(this));
server.on('starting', this.onStarting.bind(this));
server.on('ready', this.onReady.bind(this));
server.on('error', this.onError.bind(this));
server.on('stopped', this.onStopped.bind(this))
}
onRestarting() {
L.trace('onRestarting');
this.item.tooltip = 'Remote: Restarting server...';
this.item.color = new vscode.ThemeColor('statusBar.foreground');
this.item.show();
}
onStarting() {
L.trace('onStarting');
this.item.tooltip = 'Remote: Starting server...';
this.item.color = new vscode.ThemeColor('statusBar.foreground');
this.item.show();
}
onReady() {
L.trace('onReady');
this.item.tooltip = 'Remote: Server ready.';
this.item.color = new vscode.ThemeColor('statusBar.foreground');
this.item.show();
}
onError(e) {
L.trace('onError');
if (e.code == 'EADDRINUSE') {
L.debug('onError', 'EADDRINUSE');
this.item.tooltip = 'Remote error: Port already in use.';
} else {
this.item.tooltip = 'Remote error: Failed to start server.';
}
this.item.color = new vscode.ThemeColor('errorForeground');
this.item.show();
}
onStopped() {
L.trace('onStopped');
this.item.tooltip = 'Remote: Server stopped.';
this.item.color = new vscode.ThemeColor('statusBar.foreground');
this.item.hide();
}
}
export default StatusBarItem;
| rafaelmaiolla/remote-vscode | src/lib/StatusBarItem.ts | TypeScript | mit | 2,197 |
package main
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/rpc"
"net/url"
"os"
"os/exec"
"os/signal"
"reflect"
"regexp"
"strconv"
"syscall"
"time"
"github.com/aws/aws-lambda-go/lambda/messages"
)
var apiBase = "http://127.0.0.1:9001/2018-06-01"
func main() {
rand.Seed(time.Now().UTC().UnixNano())
debugMode := flag.Bool("debug", false, "enables delve debugging")
delvePath := flag.String("delvePath", "/tmp/lambci_debug_files/dlv", "path to delve")
delvePort := flag.String("delvePort", "5985", "port to start delve server on")
delveAPI := flag.String("delveAPI", "1", "delve api version")
flag.Parse()
positionalArgs := flag.Args()
var handler string
if len(positionalArgs) > 0 {
handler = positionalArgs[0]
} else {
handler = getEnv("AWS_LAMBDA_FUNCTION_HANDLER", getEnv("_HANDLER", "handler"))
}
var eventBody string
if len(positionalArgs) > 1 {
eventBody = positionalArgs[1]
} else {
eventBody = os.Getenv("AWS_LAMBDA_EVENT_BODY")
if eventBody == "" {
if os.Getenv("DOCKER_LAMBDA_USE_STDIN") != "" {
stdin, _ := ioutil.ReadAll(os.Stdin)
eventBody = string(stdin)
} else {
eventBody = "{}"
}
}
}
stayOpen := os.Getenv("DOCKER_LAMBDA_STAY_OPEN") != ""
mockContext := &mockLambdaContext{
RequestID: fakeGUID(),
EventBody: eventBody,
FnName: getEnv("AWS_LAMBDA_FUNCTION_NAME", "test"),
Version: getEnv("AWS_LAMBDA_FUNCTION_VERSION", "$LATEST"),
MemSize: getEnv("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", "1536"),
Timeout: getEnv("AWS_LAMBDA_FUNCTION_TIMEOUT", "300"),
Region: getEnv("AWS_REGION", getEnv("AWS_DEFAULT_REGION", "us-east-1")),
AccountID: getEnv("AWS_ACCOUNT_ID", strconv.FormatInt(int64(rand.Int31()), 10)),
Start: time.Now(),
}
mockContext.ParseTimeout()
awsAccessKey := getEnv("AWS_ACCESS_KEY", os.Getenv("AWS_ACCESS_KEY_ID"))
awsSecretKey := getEnv("AWS_SECRET_KEY", os.Getenv("AWS_SECRET_ACCESS_KEY"))
awsSessionToken := getEnv("AWS_SESSION_TOKEN", os.Getenv("AWS_SECURITY_TOKEN"))
port := getEnv("_LAMBDA_SERVER_PORT", "54321")
os.Setenv("AWS_LAMBDA_FUNCTION_NAME", mockContext.FnName)
os.Setenv("AWS_LAMBDA_FUNCTION_VERSION", mockContext.Version)
os.Setenv("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", mockContext.MemSize)
os.Setenv("AWS_LAMBDA_LOG_GROUP_NAME", "/aws/lambda/"+mockContext.FnName)
os.Setenv("AWS_LAMBDA_LOG_STREAM_NAME", logStreamName(mockContext.Version))
os.Setenv("AWS_REGION", mockContext.Region)
os.Setenv("AWS_DEFAULT_REGION", mockContext.Region)
os.Setenv("_HANDLER", handler)
var err error
var errored bool
var mockServerCmd = exec.Command("/var/runtime/mockserver")
mockServerCmd.Env = append(os.Environ(),
"DOCKER_LAMBDA_NO_BOOTSTRAP=1",
"DOCKER_LAMBDA_USE_STDIN=1",
)
mockServerCmd.Stdout = os.Stdout
mockServerCmd.Stderr = os.Stderr
stdin, _ := mockServerCmd.StdinPipe()
if err = mockServerCmd.Start(); err != nil {
log.Fatalf("Error starting mock server: %s", err.Error())
return
}
stdin.Write([]byte(eventBody))
stdin.Close()
defer mockServerCmd.Wait()
pingTimeout := time.Now().Add(1 * time.Second)
for {
resp, err := http.Get(apiBase + "/ping")
if err != nil {
if time.Now().After(pingTimeout) {
log.Fatal("Mock server did not start in time")
return
}
time.Sleep(5 * time.Millisecond)
continue
}
if resp.StatusCode != 200 {
log.Fatal("Non 200 status code from local server")
return
}
resp.Body.Close()
break
}
var cmd *exec.Cmd
if *debugMode == true {
delveArgs := []string{
"--listen=:" + *delvePort,
"--headless=true",
"--api-version=" + *delveAPI,
"--log",
"exec",
"/var/task/" + handler,
}
cmd = exec.Command(*delvePath, delveArgs...)
} else {
cmd = exec.Command("/var/task/" + handler)
}
cmd.Env = append(os.Environ(),
"_LAMBDA_SERVER_PORT="+port,
"AWS_ACCESS_KEY="+awsAccessKey,
"AWS_ACCESS_KEY_ID="+awsAccessKey,
"AWS_SECRET_KEY="+awsSecretKey,
"AWS_SECRET_ACCESS_KEY="+awsSecretKey,
)
if len(awsSessionToken) > 0 {
cmd.Env = append(cmd.Env,
"AWS_SESSION_TOKEN="+awsSessionToken,
"AWS_SECURITY_TOKEN="+awsSessionToken,
)
}
var logsBuf bytes.Buffer
if stayOpen {
cmd.Stdout = io.MultiWriter(os.Stdout, &logsBuf)
cmd.Stderr = io.MultiWriter(os.Stderr, &logsBuf)
} else {
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
}
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err = cmd.Start(); err != nil {
defer abortInit(mockContext, err)
return
}
defer syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
var conn net.Conn
for {
conn, err = net.Dial("tcp", ":"+port)
if mockContext.HasExpired() {
defer abortInit(mockContext, mockContext.TimeoutErr())
return
}
if err == nil {
break
}
if oerr, ok := err.(*net.OpError); ok {
// Connection refused, try again
if oerr.Op == "dial" && oerr.Net == "tcp" {
time.Sleep(5 * time.Millisecond)
continue
}
}
defer abortInit(mockContext, err)
return
}
client := rpc.NewClient(conn)
for {
err = client.Call("Function.Ping", messages.PingRequest{}, &messages.PingResponse{})
if mockContext.HasExpired() {
defer abortInit(mockContext, mockContext.TimeoutErr())
return
}
if err == nil {
break
}
time.Sleep(5 * time.Millisecond)
}
sighupReceiver := make(chan os.Signal, 1)
signal.Notify(sighupReceiver, syscall.SIGHUP)
go func() {
<-sighupReceiver
fmt.Fprintln(os.Stderr, ("SIGHUP received, exiting runtime..."))
os.Exit(2)
}()
var initEndSent bool
var invoked bool
var receivedInvokeAt time.Time
for {
if !invoked {
receivedInvokeAt = time.Now()
invoked = true
} else {
logsBuf.Reset()
}
resp, err := http.Get(apiBase + "/runtime/invocation/next")
if err != nil {
if uerr, ok := err.(*url.Error); ok {
if uerr.Unwrap().Error() == "EOF" {
if stayOpen {
os.Exit(2)
} else if errored {
os.Exit(1)
} else {
os.Exit(0)
}
return
}
}
log.Fatal(err)
return
}
if resp.StatusCode != 200 {
log.Fatal("Non 200 status code from local server")
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
return
}
resp.Body.Close()
deadlineMs, _ := strconv.ParseInt(resp.Header.Get("Lambda-Runtime-Deadline-Ms"), 10, 64)
deadline := time.Unix(0, deadlineMs*int64(time.Millisecond))
var invokeRequest = &messages.InvokeRequest{
Payload: body,
RequestId: resp.Header.Get("Lambda-Runtime-Aws-Request-Id"),
XAmznTraceId: resp.Header.Get("Lambda-Runtime-Trace-Id"),
InvokedFunctionArn: resp.Header.Get("Lambda-Runtime-Invoked-Function-Arn"),
Deadline: messages.InvokeRequest_Timestamp{
Seconds: deadline.Unix(),
Nanos: int64(deadline.Nanosecond()),
},
ClientContext: []byte(resp.Header.Get("Lambda-Runtime-Client-Context")),
}
cognitoIdentityHeader := []byte(resp.Header.Get("Lambda-Runtime-Cognito-Identity"))
if len(cognitoIdentityHeader) > 0 {
var identityObj *cognitoIdentity
err := json.Unmarshal(cognitoIdentityHeader, &identityObj)
if err != nil {
log.Fatal(err)
return
}
invokeRequest.CognitoIdentityId = identityObj.IdentityID
invokeRequest.CognitoIdentityPoolId = identityObj.IdentityPoolID
}
logTail := resp.Header.Get("Docker-Lambda-Log-Type") == "Tail"
var initEnd time.Time
if !initEndSent {
initEnd = time.Now()
}
errored = false
var reply *messages.InvokeResponse
err = client.Call("Function.Invoke", invokeRequest, &reply)
suffix := "/response"
payload := reply.Payload
if err != nil || reply.Error != nil {
errored = true
suffix = "/error"
var lambdaErr lambdaError
if err != nil {
lambdaErr = toLambdaError(mockContext, err)
} else if reply.Error != nil {
lambdaErr = convertInvokeResponseError(reply.Error)
}
payload, _ = json.Marshal(lambdaErr)
}
req, err := http.NewRequest("POST", apiBase+"/runtime/invocation/"+invokeRequest.RequestId+suffix, bytes.NewBuffer(payload))
if err != nil {
log.Fatal(err)
return
}
if logTail {
// This is very annoying but seems to be necessary to ensure we get all the stdout/stderr from the process
time.Sleep(1 * time.Millisecond)
logs := logsBuf.Bytes()
if len(logs) > 0 {
if len(logs) > 4096 {
logs = logs[len(logs)-4096:]
}
req.Header.Add("Docker-Lambda-Log-Result", base64.StdEncoding.EncodeToString(logs))
}
}
if !initEndSent {
req.Header.Add("Docker-Lambda-Invoke-Wait", strconv.FormatInt(receivedInvokeAt.UnixNano()/int64(time.Millisecond), 10))
req.Header.Add("Docker-Lambda-Init-End", strconv.FormatInt(initEnd.UnixNano()/int64(time.Millisecond), 10))
initEndSent = true
}
resp, err = http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
return
}
if resp.StatusCode != 202 {
log.Printf("Non 202 status code from local server: %d\n", resp.StatusCode)
body, _ = ioutil.ReadAll(resp.Body)
log.Println(string(body))
log.Println("When trying to send payload:")
log.Println(string(payload))
if resp.StatusCode >= 300 {
os.Exit(1)
return
}
}
resp.Body.Close()
}
}
func abortInit(mockContext *mockLambdaContext, err error) {
lambdaErr := toLambdaError(mockContext, err)
jsonBytes, _ := json.Marshal(lambdaErr)
resp, err := http.Post(apiBase+"/runtime/init/error", "application/json", bytes.NewBuffer(jsonBytes))
if err != nil {
log.Fatal(err)
return
}
resp.Body.Close()
}
func toLambdaError(mockContext *mockLambdaContext, exitErr error) lambdaError {
err := &exitError{err: exitErr, context: mockContext}
responseErr := lambdaError{
Message: err.Error(),
Type: getErrorType(err),
}
if responseErr.Type == "errorString" {
responseErr.Type = ""
if responseErr.Message == "unexpected EOF" {
responseErr.Message = "RequestId: " + mockContext.RequestID + " Process exited before completing request"
}
} else if responseErr.Type == "ExitError" {
responseErr.Type = "Runtime.ExitError" // XXX: Hack to add 'Runtime.' to error type
}
return responseErr
}
func convertInvokeResponseError(err *messages.InvokeResponse_Error) lambdaError {
var stackTrace []string
for _, v := range err.StackTrace {
stackTrace = append(stackTrace, fmt.Sprintf("%s:%d %s", v.Path, v.Line, v.Label))
}
return lambdaError{
Message: err.Message,
Type: err.Type,
StackTrace: stackTrace,
}
}
func getEnv(key, fallback string) string {
value := os.Getenv(key)
if value != "" {
return value
}
return fallback
}
func fakeGUID() string {
randBuf := make([]byte, 16)
rand.Read(randBuf)
hexBuf := make([]byte, hex.EncodedLen(len(randBuf))+4)
hex.Encode(hexBuf[0:8], randBuf[0:4])
hexBuf[8] = '-'
hex.Encode(hexBuf[9:13], randBuf[4:6])
hexBuf[13] = '-'
hex.Encode(hexBuf[14:18], randBuf[6:8])
hexBuf[18] = '-'
hex.Encode(hexBuf[19:23], randBuf[8:10])
hexBuf[23] = '-'
hex.Encode(hexBuf[24:], randBuf[10:])
hexBuf[14] = '1' // Make it look like a v1 guid
return string(hexBuf)
}
func logStreamName(version string) string {
randBuf := make([]byte, 16)
rand.Read(randBuf)
hexBuf := make([]byte, hex.EncodedLen(len(randBuf)))
hex.Encode(hexBuf, randBuf)
return time.Now().Format("2006/01/02") + "/[" + version + "]" + string(hexBuf)
}
func arn(region string, accountID string, fnName string) string {
nonDigit := regexp.MustCompile(`[^\d]`)
return "arn:aws:lambda:" + region + ":" + nonDigit.ReplaceAllString(accountID, "") + ":function:" + fnName
}
func getErrorType(err interface{}) string {
errorType := reflect.TypeOf(err)
if errorType.Kind() == reflect.Ptr {
return errorType.Elem().Name()
}
return errorType.Name()
}
type lambdaError struct {
Message string `json:"errorMessage"`
Type string `json:"errorType,omitempty"`
StackTrace []string `json:"stackTrace,omitempty"`
}
type exitError struct {
err error
context *mockLambdaContext
}
func (e *exitError) Error() string {
return fmt.Sprintf("RequestId: %s Error: %s", e.context.RequestID, e.err.Error())
}
type mockLambdaContext struct {
RequestID string
EventBody string
FnName string
Version string
MemSize string
Timeout string
Region string
AccountID string
Start time.Time
TimeoutDuration time.Duration
}
func (mc *mockLambdaContext) ParseTimeout() {
timeoutDuration, err := time.ParseDuration(mc.Timeout + "s")
if err != nil {
panic(err)
}
mc.TimeoutDuration = timeoutDuration
}
func (mc *mockLambdaContext) Deadline() time.Time {
return mc.Start.Add(mc.TimeoutDuration)
}
func (mc *mockLambdaContext) HasExpired() bool {
return time.Now().After(mc.Deadline())
}
func (mc *mockLambdaContext) Request() *messages.InvokeRequest {
return &messages.InvokeRequest{
Payload: []byte(mc.EventBody),
RequestId: mc.RequestID,
XAmznTraceId: getEnv("_X_AMZN_TRACE_ID", ""),
InvokedFunctionArn: getEnv("AWS_LAMBDA_FUNCTION_INVOKED_ARN", arn(mc.Region, mc.AccountID, mc.FnName)),
Deadline: messages.InvokeRequest_Timestamp{
Seconds: mc.Deadline().Unix(),
Nanos: int64(mc.Deadline().Nanosecond()),
},
}
}
func (mc *mockLambdaContext) TimeoutErr() error {
return fmt.Errorf("%s %s Task timed out after %s.00 seconds", time.Now().Format("2006-01-02T15:04:05.999Z"),
mc.RequestID, mc.Timeout)
}
type cognitoIdentity struct {
IdentityID string `json:"identity_id,omitempty"`
IdentityPoolID string `json:"identity_pool_id,omitempty"`
}
| lambci/docker-lambda | go1.x/run/aws-lambda-mock.go | GO | mit | 13,597 |
/*
* The Plaid API
*
* The Plaid REST API. Please see https://plaid.com/docs/api for more details.
*
* API version: 2020-09-14_1.78.0
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package plaid
import (
"encoding/json"
)
// Deductions An object with the deduction information found on a paystub.
type Deductions struct {
Subtotals *[]Total `json:"subtotals,omitempty"`
Breakdown []DeductionsBreakdown `json:"breakdown"`
Totals *[]Total `json:"totals,omitempty"`
Total DeductionsTotal `json:"total"`
AdditionalProperties map[string]interface{}
}
type _Deductions Deductions
// NewDeductions instantiates a new Deductions object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewDeductions(breakdown []DeductionsBreakdown, total DeductionsTotal) *Deductions {
this := Deductions{}
this.Breakdown = breakdown
this.Total = total
return &this
}
// NewDeductionsWithDefaults instantiates a new Deductions object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewDeductionsWithDefaults() *Deductions {
this := Deductions{}
return &this
}
// GetSubtotals returns the Subtotals field value if set, zero value otherwise.
func (o *Deductions) GetSubtotals() []Total {
if o == nil || o.Subtotals == nil {
var ret []Total
return ret
}
return *o.Subtotals
}
// GetSubtotalsOk returns a tuple with the Subtotals field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *Deductions) GetSubtotalsOk() (*[]Total, bool) {
if o == nil || o.Subtotals == nil {
return nil, false
}
return o.Subtotals, true
}
// HasSubtotals returns a boolean if a field has been set.
func (o *Deductions) HasSubtotals() bool {
if o != nil && o.Subtotals != nil {
return true
}
return false
}
// SetSubtotals gets a reference to the given []Total and assigns it to the Subtotals field.
func (o *Deductions) SetSubtotals(v []Total) {
o.Subtotals = &v
}
// GetBreakdown returns the Breakdown field value
func (o *Deductions) GetBreakdown() []DeductionsBreakdown {
if o == nil {
var ret []DeductionsBreakdown
return ret
}
return o.Breakdown
}
// GetBreakdownOk returns a tuple with the Breakdown field value
// and a boolean to check if the value has been set.
func (o *Deductions) GetBreakdownOk() (*[]DeductionsBreakdown, bool) {
if o == nil {
return nil, false
}
return &o.Breakdown, true
}
// SetBreakdown sets field value
func (o *Deductions) SetBreakdown(v []DeductionsBreakdown) {
o.Breakdown = v
}
// GetTotals returns the Totals field value if set, zero value otherwise.
func (o *Deductions) GetTotals() []Total {
if o == nil || o.Totals == nil {
var ret []Total
return ret
}
return *o.Totals
}
// GetTotalsOk returns a tuple with the Totals field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *Deductions) GetTotalsOk() (*[]Total, bool) {
if o == nil || o.Totals == nil {
return nil, false
}
return o.Totals, true
}
// HasTotals returns a boolean if a field has been set.
func (o *Deductions) HasTotals() bool {
if o != nil && o.Totals != nil {
return true
}
return false
}
// SetTotals gets a reference to the given []Total and assigns it to the Totals field.
func (o *Deductions) SetTotals(v []Total) {
o.Totals = &v
}
// GetTotal returns the Total field value
func (o *Deductions) GetTotal() DeductionsTotal {
if o == nil {
var ret DeductionsTotal
return ret
}
return o.Total
}
// GetTotalOk returns a tuple with the Total field value
// and a boolean to check if the value has been set.
func (o *Deductions) GetTotalOk() (*DeductionsTotal, bool) {
if o == nil {
return nil, false
}
return &o.Total, true
}
// SetTotal sets field value
func (o *Deductions) SetTotal(v DeductionsTotal) {
o.Total = v
}
func (o Deductions) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.Subtotals != nil {
toSerialize["subtotals"] = o.Subtotals
}
if true {
toSerialize["breakdown"] = o.Breakdown
}
if o.Totals != nil {
toSerialize["totals"] = o.Totals
}
if true {
toSerialize["total"] = o.Total
}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
return json.Marshal(toSerialize)
}
func (o *Deductions) UnmarshalJSON(bytes []byte) (err error) {
varDeductions := _Deductions{}
if err = json.Unmarshal(bytes, &varDeductions); err == nil {
*o = Deductions(varDeductions)
}
additionalProperties := make(map[string]interface{})
if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
delete(additionalProperties, "subtotals")
delete(additionalProperties, "breakdown")
delete(additionalProperties, "totals")
delete(additionalProperties, "total")
o.AdditionalProperties = additionalProperties
}
return err
}
type NullableDeductions struct {
value *Deductions
isSet bool
}
func (v NullableDeductions) Get() *Deductions {
return v.value
}
func (v *NullableDeductions) Set(val *Deductions) {
v.value = val
v.isSet = true
}
func (v NullableDeductions) IsSet() bool {
return v.isSet
}
func (v *NullableDeductions) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableDeductions(val *Deductions) *NullableDeductions {
return &NullableDeductions{value: val, isSet: true}
}
func (v NullableDeductions) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableDeductions) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
| plaid/plaid-go | plaid/model_deductions.go | GO | mit | 5,789 |
/**
* Code derived from Leaflet.heat by Vladimir Agafonkin (2-clause BSD License)
* https://github.com/Leaflet/Leaflet.heat/blob/gh-pages/src/HeatLayer.js
*/
L.CanvasLayer = (L.Layer ? L.Layer : L.Class).extend({
redraw: function () {
if (this._heat && !this._frame && !this._map._animating) {
this._frame = L.Util.requestAnimFrame(this._redraw, this);
}
this._redraw();
return this;
},
_redraw: function () {
throw 'implement in subclass';
this._frame = null;
},
onAdd: function (map) {
this._map = map;
if (!this._canvas) {
this._initCanvas();
}
map._panes.overlayPane.appendChild(this._canvas);
map.on('moveend', this._reset, this);
if (map.options.zoomAnimation && L.Browser.any3d) {
map.on('zoomanim', this._animateZoom, this);
}
this._reset();
},
onRemove: function (map) {
map.getPanes().overlayPane.removeChild(this._canvas);
map.off('moveend', this._reset, this);
if (map.options.zoomAnimation) {
map.off('zoomanim', this._animateZoom, this);
}
},
addTo: function (map) {
map.addLayer(this);
return this;
},
_initCanvas: function () {
var canvas = this._canvas = L.DomUtil.create('canvas', 'leaflet-bil-layer leaflet-layer');
var size = this._map.getSize();
canvas.width = size.x;
canvas.height = size.y;
// TODO subclass
L.DomUtil.setOpacity(canvas, this.options.opacity);
var animated = this._map.options.zoomAnimation && L.Browser.any3d;
L.DomUtil.addClass(canvas, 'leaflet-zoom-' + (animated ? 'animated' : 'hide'));
},
_reset: function () {
var topLeft = this._map.containerPointToLayerPoint([0, 0]);
L.DomUtil.setPosition(this._canvas, topLeft);
var size = this._map.getSize();
if (this._canvas.width !== size.x) {
this._canvas.width = size.x;
}
if (this._canvas.height !== size.y) {
this._canvas.height = size.y;
}
this._redraw();
},
_animateZoom: function (e) {
var scale = this._map.getZoomScale(e.zoom),
offset = this._map._getCenterOffset(e.center)._multiplyBy(-scale).subtract(this._map._getMapPanePos());
if (L.DomUtil.setTransform) {
L.DomUtil.setTransform(this._canvas, offset, scale);
} else {
this._canvas.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ')';
}
}
}); | nrenner/leaflet-raw-dem | js/CanvasLayer.js | JavaScript | mit | 2,656 |
import Ember from 'ember';
export default Ember.Route.extend({
model() {
const eventRecord = this.store.createRecord('event');
const openingTier = this.store.createRecord('opening-tier');
eventRecord.set('openingTier', openingTier);
return eventRecord;
},
actions: {
didTransition() {
this.set('title', 'Create new Event');
return true;
}
}
});
| NullVoxPopuli/aeonvera-ui | app/pods/events/new/route.js | JavaScript | mit | 392 |
# Copyright (c) 2010-2014 Bo Lin
# Copyright (c) 2010-2014 Yanhong Annie Liu
# Copyright (c) 2010-2014 Stony Brook University
# Copyright (c) 2010-2014 The Research Foundation of SUNY
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import sys
import pickle
import random
import select
import socket
import logging
class EndPoint:
"""Represents a target for sending of messages.
This is the base class for all types of communication channels in
DistAlgo. It uniquely identifies a "node" in the distributed system. In
most scenarios, a process will only be associated with one EndPoint
instance. The 'self' keyword in DistAlgo is ultimately translated into an
instance of this class.
"""
def __init__(self, name=None, proctype=None):
if name is None:
self._name = socket.gethostname()
else:
self._name = name
self._proc = None
self._proctype = proctype
self._log = logging.getLogger("runtime.EndPoint")
self._address = None
def send(self, data, src, timestamp = 0):
pass
def recv(self, block, timeout = None):
pass
def setname(self, name):
self._name = name
def getlogname(self):
if self._address is not None:
return "%s_%s" % (self._address[0], str(self._address[1]))
else:
return self._name
def close(self):
pass
###################################################
# Make the EndPoint behave like a Process object:
def is_alive(self):
if self._proc is not None:
return self._proc.is_alive()
else:
self._log.warn("is_alive can only be called from parent process.")
return self
def join(self):
if self._proc is not None:
return self._proc.join()
else:
self._log.warn("join can only be called from parent process.")
return self
def terminate(self):
if self._proc is not None:
return self._proc.terminate()
else:
self._log.warn("terminate can only be called from parent process.")
return self
###################################################
def __getstate__(self):
return ("EndPoint", self._address, self._name, self._proctype)
def __setstate__(self, value):
proto, self._address, self._name, self._proctype = value
self._log = logging.getLogger("runtime.EndPoint")
def __str__(self):
if self._address is not None:
return str(self._address)
else:
return self._name
def __repr__(self):
if self._proctype is not None:
return "<" + self._proctype.__name__ + str(self) + ">"
else:
return "<process " + str(self) + ">"
def __hash__(self):
return hash(self._address)
def __eq__(self, obj):
if not hasattr(obj, "_address"):
return False
return self._address == obj._address
def __lt__(self, obj):
return self._address < obj._address
def __le__(self, obj):
return self._address <= obj._address
def __gt__(self, obj):
return self._address > obj._address
def __ge__(self, obj):
return self._address >= obj._address
def __ne__(self, obj):
if not hasattr(obj, "_address"):
return True
return self._address != obj._address
# TCP Implementation:
INTEGER_BYTES = 8
MAX_TCP_CONN = 200
MIN_TCP_PORT = 10000
MAX_TCP_PORT = 40000
MAX_TCP_BUFSIZE = 200000 # Maximum pickled message size
MAX_RETRY = 5
class TcpEndPoint(EndPoint):
"""Endpoint based on TCP.
"""
senders = None
receivers = None
def __init__(self, name=None, proctype=None, port=None):
super().__init__(name, proctype)
TcpEndPoint.receivers = dict()
TcpEndPoint.senders = LRU(MAX_TCP_CONN)
self._conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if port is None:
while True:
self._address = (self._name,
random.randint(MIN_TCP_PORT, MAX_TCP_PORT))
try:
self._conn.bind(self._address)
break
except socket.error:
pass
else:
self._address = (self._name, port)
self._conn.bind(self._address)
self._conn.listen(10)
TcpEndPoint.receivers[self._conn] = self._address
self._log = logging.getLogger("runtime.TcpEndPoint(%s)" %
super().getlogname())
self._log.debug("TcpEndPoint %s initialization complete",
str(self._address))
def send(self, data, src, timestamp = 0):
retry = 1
while True:
conn = TcpEndPoint.senders.get(self)
if conn is None:
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
conn.connect(self._address)
TcpEndPoint.senders[self] = conn
except socket.error:
self._log.debug("Can not connect to %s. Peer is down.",
str(self._address))
return False
bytedata = pickle.dumps((src, timestamp, data))
l = len(bytedata)
header = int(l).to_bytes(INTEGER_BYTES, sys.byteorder)
mesg = header + bytedata
if len(mesg) > MAX_TCP_BUFSIZE:
self._log.warn("Packet size exceeded maximum buffer size! "
"Outgoing packet dropped.")
self._log.debug("Dropped packet: %s",
str((src, timestamp, data)))
break
else:
try:
if self._send_1(mesg, conn):
break
except socket.error as e:
pass
self._log.debug("Error sending packet, retrying.")
retry += 1
if retry > MAX_RETRY:
self._log.debug("Max retry count reached, reconnecting.")
conn.close()
del TcpEndPoint.senders[self]
retry = 1
self._log.debug("Sent packet %r to %r." % (data, self))
return True
def _send_1(self, data, conn):
msglen = len(data)
totalsent = 0
while totalsent < msglen:
sent = conn.send(data[totalsent:])
if sent == 0:
return False
totalsent += sent
return True
def recvmesgs(self):
try:
while True:
r, _, _ = select.select(TcpEndPoint.receivers.keys(), [], [])
if self._conn in r:
# We have pending new connections, handle the first in
# line. If there are any more they will have to wait until
# the next iteration
conn, addr = self._conn.accept()
TcpEndPoint.receivers[conn] = addr
r.remove(self._conn)
for c in r:
try:
bytedata = self._receive_1(INTEGER_BYTES, c)
datalen = int.from_bytes(bytedata, sys.byteorder)
bytedata = self._receive_1(datalen, c)
src, tstamp, data = pickle.loads(bytedata)
bytedata = None
if not isinstance(src, TcpEndPoint):
raise TypeError()
else:
yield (src, tstamp, data)
except pickle.UnpicklingError as e:
self._log.warn("UnpicklingError, packet from %s dropped",
TcpEndPoint.receivers[c])
except socket.error as e:
self._log.debug("Remote connection %s terminated.",
str(c))
del TcpEndPoint.receivers[c]
except select.error as e:
self._log.debug("select.error occured, terminating receive loop.")
def _receive_1(self, totallen, conn):
msg = bytes()
while len(msg) < totallen:
chunk = conn.recv(totallen-len(msg))
if len(chunk) == 0:
raise socket.error("EOF received")
msg += chunk
return msg
def close(self):
pass
def __getstate__(self):
return ("TCP", self._address, self._name, self._proctype)
def __setstate__(self, value):
proto, self._address, self._name, self._proctype = value
self._conn = None
self._log = logging.getLogger("runtime.TcpEndPoint(%s)" % self._name)
class Node(object):
__slots__ = ['prev', 'next', 'me']
def __init__(self, prev, me):
self.prev = prev
self.me = me
self.next = None
def __str__(self):
return str(self.me)
def __repr__(self):
return self.me.__repr__()
class LRU:
"""
Implementation of a length-limited O(1) LRU queue.
Built for and used by PyPE:
http://pype.sourceforge.net
Copyright 2003 Josiah Carlson.
"""
def __init__(self, count, pairs=[]):
self.count = max(count, 1)
self.d = {}
self.first = None
self.last = None
for key, value in pairs:
self[key] = value
def __contains__(self, obj):
return obj in self.d
def __getitem__(self, obj):
a = self.d[obj].me
self[a[0]] = a[1]
return a[1]
def __setitem__(self, obj, val):
if obj in self.d:
del self[obj]
nobj = Node(self.last, (obj, val))
if self.first is None:
self.first = nobj
if self.last:
self.last.next = nobj
self.last = nobj
self.d[obj] = nobj
if len(self.d) > self.count:
if self.first == self.last:
self.first = None
self.last = None
return
a = self.first
a.next.prev = None
self.first = a.next
a.next = None
del self.d[a.me[0]]
del a
def __delitem__(self, obj):
nobj = self.d[obj]
if nobj.prev:
nobj.prev.next = nobj.next
else:
self.first = nobj.next
if nobj.next:
nobj.next.prev = nobj.prev
else:
self.last = nobj.prev
del self.d[obj]
def __iter__(self):
cur = self.first
while cur != None:
cur2 = cur.next
yield cur.me[1]
cur = cur2
def __str__(self):
return str(self.d)
def __repr__(self):
return self.d.__repr__()
def iteritems(self):
cur = self.first
while cur != None:
cur2 = cur.next
yield cur.me
cur = cur2
def iterkeys(self):
return iter(self.d)
def itervalues(self):
for i,j in self.iteritems():
yield j
def keys(self):
return self.d.keys()
def get(self, k, d=None):
v = self.d.get(k)
if v is None: return None
a = v.me
self[a[0]] = a[1]
return a[1]
# UDP Implementation:
MIN_UDP_PORT = 10000
MAX_UDP_PORT = 40000
MAX_UDP_BUFSIZE = 20000
class UdpEndPoint(EndPoint):
sender = None
def __init__(self, name=None, proctype=None, port=None):
super().__init__(name, proctype)
UdpEndPoint.sender = None
self._conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if port is None:
while True:
self._address = (self._name,
random.randint(MIN_UDP_PORT, MAX_UDP_PORT))
try:
self._conn.bind(self._address)
break
except socket.error:
pass
else:
self._address = (self._name, port)
self._conn.bind(self._address)
self._log = logging.getLogger("runtime.UdpEndPoint(%s)" %
super().getlogname())
self._log.debug("UdpEndPoint %s initialization complete",
str(self._address))
def send(self, data, src, timestamp = 0):
if UdpEndPoint.sender is None:
UdpEndPoint.sender = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
bytedata = pickle.dumps((src, timestamp, data))
if len(bytedata) > MAX_UDP_BUFSIZE:
self._log.warn("Data size exceeded maximum buffer size!" +
" Outgoing packet dropped.")
self._log.debug("Dropped packet: %s", str((src, timestamp, data)))
elif (UdpEndPoint.sender.sendto(bytedata, self._address) !=
len(bytedata)):
raise socket.error()
def recvmesgs(self):
flags = 0
try:
while True:
bytedata = self._conn.recv(MAX_UDP_BUFSIZE, flags)
src, tstamp, data = pickle.loads(bytedata)
if not isinstance(src, UdpEndPoint):
raise TypeError()
else:
yield (src, tstamp, data)
except socket.error as e:
self._log.debug("socket.error occured, terminating receive loop.")
def __getstate__(self):
return ("UDP", self._address, self._name, self._proctype)
def __setstate__(self, value):
proto, self._address, self._name, self._proctype = value
self._conn = None
self._log = logging.getLogger("runtime.UdpEndPoint")
| mayli/DistAlgo | da/endpoint.py | Python | mit | 14,912 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_03_01
module Models
#
# Bgp Communities sent over ExpressRoute with each route corresponding to a
# prefix in this VNET.
#
class VirtualNetworkBgpCommunities
include MsRestAzure
# @return [String] The BGP community associated with the virtual network.
attr_accessor :virtual_network_community
# @return [String] The BGP community associated with the region of the
# virtual network.
attr_accessor :regional_community
#
# Mapper for VirtualNetworkBgpCommunities class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'VirtualNetworkBgpCommunities',
type: {
name: 'Composite',
class_name: 'VirtualNetworkBgpCommunities',
model_properties: {
virtual_network_community: {
client_side_validation: true,
required: true,
serialized_name: 'virtualNetworkCommunity',
type: {
name: 'String'
}
},
regional_community: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'regionalCommunity',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2020-03-01/generated/azure_mgmt_network/models/virtual_network_bgp_communities.rb | Ruby | mit | 1,751 |
$(document).ready( function () {
var Counter = Backbone.Model.extend({
defaults : {"value" : 0},
inc : function () {
var val = this.get("value");
this.set("value", val+1);
}
});
var CounterView = Backbone.View.extend({
render: function () {
var val = this.model.get("value");
var btn = '<button>Increment</button>';
this.$el.html('<p>'+val+'</p>' + btn);
},
initialize: function () {
this.model.on("change", this.render, this);
},
events : {
'click button' : 'increment'
},
increment : function () {
this.model.inc();
}
});
var counterModel = new Counter();
var counterView1 = new CounterView({model : counterModel});
var counterView2 = new CounterView({model : counterModel});
counterView1.render();
counterView2.render();
$("#counterdiv").append(counterView1.$el);
$("#counterdiv").append(counterView2.$el);
});
| clarissalittler/backbone-tutorials | counterMulti.js | JavaScript | mit | 1,026 |
public class UnsatNullPointerException02 {
public int x;
public static void main(String args[]) {
UnsatNullPointerException02 a = null;
a.x = 42;
}
}
| jayhorn/jayhorn | jayhorn/src/test/resources/horn-encoding/null/UnsatNullPointerException02.java | Java | mit | 178 |
<?php
require_once('../../Classes/ClassParent.php');
class Users extends ClassParent{
var $empid = NULL;
var $password = NULL;
var $lastname = NULL;
var $firstname = NULL;
var $visibility = false;
var $archived = false;
var $usertype = NULL;
public function __construct(
$empid,
$password,
$lastname,
$firstname,
$visibility,
$archived,
$usertype
){
$fields = get_defined_vars();
if(empty($fields)){
return(FALSE);
}
//sanitize
foreach($fields as $k=>$v){
$this->$k = pg_escape_string(trim(strip_tags($v)));
}
return(true);
}
public function auth(){
$code = $this->code;
$sql = <<<EOT
select
empid,
firstname,
lastname
from users
where empid = '$this->empid'
and password = md5('$this->password')
and archived = false
;
EOT;
return ClassParent::get($sql);
}
public function fetchAll(){
$sql = <<<EOT
select
empid,
firstname,
lastname,
visibility,
archived,
usertype
from users
where empid != '1'
and visibility = $this->visibility
and archived = false
order by visibility
;
EOT;
return ClassParent::get($sql);
}
public function fetch(){
$sql = <<<EOT
select
empid,
firstname,
lastname,
visibility,
archived,
usertype
from users
where empid = '$this->empid'
;
EOT;
return ClassParent::get($sql);
}
public function create(){
$sql = <<<EOT
insert into users
(empid, lastname, firstname, usertype)
values
('$this->empid','$this->lastname','$this->firstname','$this->usertype')
;
EOT;
return ClassParent::insert($sql);
}
public function delete(){
$sql = <<<EOT
update users
set archived = true
where empid = '$this->empid'
;
EOT;
return ClassParent::update($sql);
}
public function status(){
$sql = <<<EOT
update users
set visibility = '$this->visibility'
where empid = '$this->empid'
;
EOT;
return ClassParent::update($sql);
}
}
?> | rpascual0812/calltracker | Classes/Users.php | PHP | mit | 3,176 |
# encoding: utf-8
module NiceBootstrap3Form::Wrappers
def _offset_wrapper(&block)
if horizontal
content_tag(:div, class: _input_offset_classes, &block)
else
block.call
end
end
def _input_group_wrapper(attribute, &block)
if @inside_group
block.call
else
content_tag(:div, class: _form_group_classes(attribute), &block)
end
end
def _input_wrapper(attribute, options, &block)
if horizontal && !@inside_group
klasses = options[:label].false? ? _input_offset_classes : @input_width_class
content_tag(:div, class: klasses, &block)
else
capture(&block)
end
end
end
| jh125486/nice_bootstrap3_form | lib/nice_bootstrap3_form/wrappers.rb | Ruby | mit | 650 |