repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
lihanli/eternal-scroll | test/test.js | 384 | (function() {
var times = 0
, $el = $('#load-more').click(function() {
var $this = $(this);
$this.hide();
setTimeout(function() {
$this.show();
}, 250);
$('.spacers').append('<div class="spacer"></div>');
times++;
$('#output').text(times);
});
window.scroller = new EternalScroll({
loadMoreButton: $el,
});
})(); | mit |
SpongePowered/SpongeForge | src/main/java/org/spongepowered/mod/plugin/SpongeModPluginManager.java | 3110 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.mod.plugin;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.inject.Singleton;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.plugin.PluginManager;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@NonnullByDefault
@Singleton
public class SpongeModPluginManager implements PluginManager {
@Override
public Optional<PluginContainer> getPlugin(String id) {
checkNotNull(id, "id");
ModContainer container = Loader.instance().getIndexedModList().get(id);
if (container == null) {
for (ModContainer mod : Loader.instance().getModList()) {
if (mod.getModId().equalsIgnoreCase(id)) {
container = mod;
break;
}
}
}
return Optional.ofNullable((PluginContainer) container);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Collection<PluginContainer> getPlugins() {
return ImmutableList.copyOf((List) Loader.instance().getActiveModList());
}
@Override
public Optional<PluginContainer> fromInstance(Object instance) {
checkNotNull(instance, "instance");
if (instance instanceof PluginContainer) {
return Optional.of((PluginContainer) instance);
}
return Optional.ofNullable((PluginContainer) Loader.instance().getReversedModObjectList().get(instance));
}
@Override
public boolean isLoaded(String id) {
checkNotNull(id, "id");
return Loader.isModLoaded(id);
}
}
| mit |
petyodelta/ASP-NET-MVC | Orders/OrdersSystem/Models/OrdersSystem.Models/Order.cs | 854 | namespace OrdersSystem.Models
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Common;
public abstract class Order
{
public int Id { get; set; }
[Required]
[MinLength(ValidationConstants.DescriptionMinLength, ErrorMessage = ValidationConstants.DescriptionErrorMessage)]
[MaxLength(ValidationConstants.DescriptionMaxLength, ErrorMessage = ValidationConstants.DescriptionErrorMessage)]
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public OrderStatus Status { get; set; }
public string AuthorId { get; set; }
[ForeignKey("AuthorId")]
public virtual User Author { get; set; }
}
}
| mit |
bwthomas/stachio | lib/stachio/version.rb | 39 | module Stachio
VERSION = "0.2.1"
end
| mit |
TheKevJames/dead-simple-ops | dsops/monitor_repos.py | 4257 | #!/usr/bin/env python
"""DeadSimpleMonitorRepos
Usage:
monitor-repos <org> [--port=PORT] [--conf=CONF]
Options:
--port=PORT Host the monitor on a specific port. [default: 5000]
--conf=CONF Specified config file.
--version Show version.
-h --help Show this screen.
"""
from flask import Flask, render_template, request
from flask_sockets import Sockets
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
import json
import logging
import os
from python_util import docopt
import requests
import sys
from .common.config import get, parse
from .common.logging import warn
GITHUB_TOKEN = os.environ['GITHUB_TOKEN']
config = {
'base-branch': None,
'branches': None,
'org': None,
'repos': None,
}
webapp = Flask(__name__)
sockets = Sockets(webapp)
logger = logging.getLogger(__name__)
logging.getLogger('geventwebsocket').setLevel(logging.WARNING)
logging.getLogger('requests').setLevel(logging.WARNING)
@sockets.route('/githubWS')
def github_ws(ws):
while True:
req = ws.receive()
try:
request_ws = json.loads(req)
except TypeError:
# TODO: avoid this with `if req` ?
return
payload = github(request_ws=request_ws)
ws.send(payload)
@webapp.route('/github')
def github(request_ws=None):
headers = {'Authorization': 'token %s' % GITHUB_TOKEN}
r = request_ws or request.args
for required in ('repo', 'route'):
if required not in r:
warn(logger, 'Bad request: %s is a required parameter.' % required)
return '?'
url = 'https://api.github.com/repos/%s/%s/%s' % (config['org'], r['repo'],
r['route'])
if 'route_after' in r:
url += r['route_after']
if 'state' in r:
url += '?state=' + r['state']
response = requests.get(url, headers=headers).content
data = json.loads(response)
if 'count' in r:
# Github API considers pulls to also be issues
if r['route'] == 'issues':
data = filter(lambda x: 'pull_request' not in x, data)
count = len(data)
if count == 30:
return '30+'
return str(count)
if 'lag' in r:
if 'message' in data:
# Not tracked
return '?'
if data['status'] == 'identical':
return '='
elif data['status'] == 'behind':
return '-%s' % str(data['behind_by'])
elif data['status'] == 'ahead':
return '+%s' % str(data['ahead_by'])
elif data['status'] == 'diverged':
return '-%s +%s' % (str(data['behind_by']), str(data['ahead_by']))
else:
warn(logger,
'Error: could not parse API response (%s)' % data['status'])
return '?'
return data
@webapp.route('/')
def dash():
branches_deployable = filter(lambda x: x != config['base-branch'],
config['branches'])
return render_template('monitor_repos.html',
base_branch=config['base-branch'],
branches=config['branches'],
branches_deployable=branches_deployable,
org=config['org'], repos=config['repos'],
thresholds={'issues': 50, 'pulls': 5})
def main(args=None):
if not args:
args = docopt(__doc__, argv=sys.argv[1:], transforms={'--port': int},
version='DeadSimpleMonitorRepos v0.0.3')
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - '
'%(message)s')
app = args.get('<org>')
conf = args.get('--conf')
configfile = get(logger, filename=conf)
parse(logger, configfile, config, app=app, task='monitor-repos',
required=['base-branch', 'branches', 'repos'])
config['org'] = app # hacky way of accessing this elsewhere
server = WSGIServer(('0.0.0.0', args.get('--port')), webapp,
handler_class=WebSocketHandler)
server.serve_forever()
if __name__ == '__main__':
main()
| mit |
davidwparker/programmingtil-webgl | 0024-random-color-pixels/libs/uiUtils.js | 472 | (function(global){
var uiUtils = {
VERSION : '0.0.1',
pixelInputToGLCoord: function(event, canvas) {
var x = event.clientX, y = event.clientY,
midX = canvas.width/2, midY = canvas.height/2,
rect = event.target.getBoundingClientRect();
x = ((x - rect.left) - midX) / midX;
y = (midY - (y - rect.top)) / midY;
return {x:x,y:y};
},
};
// Expose uiUtils globally
global.uiUtils = uiUtils;
}(window || this));
| mit |
piotrlewalski/birdstorm | game/utils/patch.py | 809 | import rest_framework.fields
from sockjs.tornado.basehandler import BaseHandler
#TODO add a comment
from sockjs.tornado.transports.websocket import WebSocketTransport
def strip_multiple_choice_msg(_):
return ''
rest_framework.fields.strip_multiple_choice_msg = strip_multiple_choice_msg
#mitigates following exception raised when any error will occur during processing SockJS message
# > AttributeError: 'WebSocketTransport' object has no attribute 'abort_connection'
def abort_connection(*args, **kwargs):
pass
WebSocketTransport.abort_connection = abort_connection
#TODO send pull request to sockjs-tornado
def finish(self, *args, **kwargs):
"""Tornado `finish` handler"""
self._log_disconnect()
super(BaseHandler, self).finish(*args, **kwargs)
BaseHandler.finish = finish
| mit |
rafaeljuzo/makeuptown | site/controllers/admin/AdminTabsController.php | 9491 | <?php
/*
* 2007-2013 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2013 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class AdminTabsControllerCore extends AdminController
{
protected $position_identifier = 'id_tab';
public function __construct()
{
$this->context = Context::getContext();
$this->multishop_context = Shop::CONTEXT_ALL;
$this->table = 'tab';
$this->className = 'Tab';
$this->lang = true;
$this->fieldImageSettings = array(
'name' => 'icon',
'dir' => 't'
);
$this->imageType = 'gif';
$this->fields_list = array(
'id_tab' => array(
'title' => $this->l('ID'),
'width' => 25
),
'name' => array(
'title' => $this->l('Name'),
'width' => 200
),
'logo' => array(
'title' => $this->l('Icon'),
'image' => 't',
'image_id' => 'class_name',
'orderby' => false,
'search' => false
),
'module' => array(
'title' => $this->l('Module')
),
'active' => array(
'title' => $this->l('Enabled'),
'width' => 70,
'align' => 'center',
'active' => 'status',
'type' => 'bool',
'orderby' => false
),
'position' => array(
'title' => $this->l('Position'),
'width' => 40,
'filter_key' => 'a!position',
'position' => 'position'
)
);
parent::__construct();
}
/**
* AdminController::renderForm() override
* @see AdminController::renderForm()
*/
public function renderForm()
{
$tabs = Tab::getTabs($this->context->language->id, 0);
// If editing, we clean itself
if (Tools::isSubmit('id_tab'))
foreach ($tabs as $key => $tab)
if ($tab['id_tab'] == Tools::getValue('id_tab'))
unset($tabs[$key]);
// added category "Home" in var $tabs
$tab_zero = array(
'id_tab' => 0,
'name' => $this->l('Home')
);
array_unshift($tabs, $tab_zero);
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Menus'),
'image' => '../img/admin/tab.gif'
),
'input' => array(
array(
'type' => 'hidden',
'name' => 'position',
'required' => false
),
array(
'type' => 'text',
'label' => $this->l('Name:'),
'name' => 'name',
'lang' => true,
'size' => 33,
'required' => true,
'hint' => $this->l('Invalid characters:').' <>;=#{}'
),
array(
'type' => 'text',
'label' => $this->l('Class:'),
'name' => 'class_name',
'required' => true
),
array(
'type' => 'text',
'label' => $this->l('Module:'),
'name' => 'module'
),
array(
'type' => 'file',
'label' => $this->l('Icon:'),
'name' => 'icon',
'desc' => $this->l('Upload a logo from your computer (.gif, .jpg, .jpeg or .png).')
),
array(
'type' => 'radio',
'label' => $this->l('Status:'),
'name' => 'active',
'required' => false,
'class' => 't',
'is_bool' => true,
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('Disabled')
)
),
'desc' => $this->l('Show or hide menu.')
),
array(
'type' => 'select',
'label' => $this->l('Parent:'),
'name' => 'id_parent',
'options' => array(
'query' => $tabs,
'id' => 'id_tab',
'name' => 'name'
)
)
),
'submit' => array(
'title' => $this->l(' Save '),
'class' => 'button'
)
);
return parent::renderForm();
}
/**
* AdminController::renderList() override
* @see AdminController::renderList()
*/
public function renderList()
{
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->addRowAction('details');
$this->_where = 'AND a.`id_parent` = 0';
$this->_orderBy = 'position';
return parent::renderList();
}
/**
* method call when ajax request is made with the details row action
* @see AdminController::postProcess()
*/
public function ajaxProcessDetails()
{
if (($id = Tools::getValue('id')))
{
// override attributes
$this->display = 'list';
$this->lang = false;
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->_select = 'b.*';
$this->_join = 'LEFT JOIN `'._DB_PREFIX_.'tab_lang` b ON (b.`id_tab` = a.`id_tab` AND b.`id_lang` = '.$this->context->language->id.')';
$this->_where = 'AND a.`id_parent` = '.(int)$id;
$this->_orderBy = 'position';
// get list and force no limit clause in the request
$this->getList($this->context->language->id);
// Render list
$helper = new HelperList();
$helper->actions = $this->actions;
$helper->list_skip_actions = $this->list_skip_actions;
$helper->no_link = true;
$helper->shopLinkType = '';
$helper->identifier = $this->identifier;
$helper->imageType = $this->imageType;
$helper->toolbar_scroll = false;
$helper->show_toolbar = false;
$helper->orderBy = 'position';
$helper->orderWay = 'ASC';
$helper->currentIndex = self::$currentIndex;
$helper->token = $this->token;
$helper->table = $this->table;
$helper->position_identifier = $this->position_identifier;
// Force render - no filter, form, js, sorting ...
$helper->simple_header = true;
$content = $helper->generateList($this->_list, $this->fields_list);
echo Tools::jsonEncode(array('use_parent_structure' => false, 'data' => $content));
}
die;
}
public function postProcess()
{
/* PrestaShop demo mode */
if (_PS_MODE_DEMO_)
{
$this->errors[] = Tools::displayError('This functionality has been disabled.');
return;
}
/* PrestaShop demo mode*/
if (($id_tab = (int)Tools::getValue('id_tab')) && ($direction = Tools::getValue('move')) && Validate::isLoadedObject($tab = new Tab($id_tab)))
{
if ($tab->move($direction))
Tools::redirectAdmin(self::$currentIndex.'&token='.$this->token);
}
elseif (Tools::getValue('position') && !Tools::isSubmit('submitAdd'.$this->table))
{
if ($this->tabAccess['edit'] !== '1')
$this->errors[] = Tools::displayError('You do not have permission to edit this.');
elseif (!Validate::isLoadedObject($object = new Tab((int)Tools::getValue($this->identifier))))
$this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').
' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
if (!$object->updatePosition((int)Tools::getValue('way'), (int)Tools::getValue('position')))
$this->errors[] = Tools::displayError('Failed to update the position.');
else
Tools::redirectAdmin(self::$currentIndex.'&conf=5&token='.Tools::getAdminTokenLite('AdminTabs'));
}
elseif (Tools::isSubmit('submitAddtab') && Tools::getValue('id_tab') === Tools::getValue('id_parent'))
$this->errors[] = Tools::displayError('You can\'t put this menu inside itself. ');
else
{
// Temporary add the position depend of the selection of the parent category
if (!Tools::isSubmit('id_tab')) // @todo Review
$_POST['position'] = Tab::getNbTabs(Tools::getValue('id_parent'));
}
if (!count($this->errors))
parent::postProcess();
}
protected function afterImageUpload()
{
if (!($obj = $this->loadObject(true)))
return;
@rename(_PS_IMG_DIR_.'t/'.$obj->id.'.gif', _PS_IMG_DIR_.'t/'.$obj->class_name.'.gif');
}
public function ajaxProcessUpdatePositions()
{
$way = (int)(Tools::getValue('way'));
$id_tab = (int)(Tools::getValue('id'));
$positions = Tools::getValue('tab');
// when changing positions in a tab sub-list, the first array value is empty and needs to be removed
if (!$positions[0])
{
unset($positions[0]);
// reset indexation from 0
$positions = array_merge($positions);
}
foreach ($positions as $position => $value)
{
$pos = explode('_', $value);
if (isset($pos[2]) && (int)$pos[2] === $id_tab)
{
if ($tab = new Tab((int)$pos[2]))
if (isset($position) && $tab->updatePosition($way, $position))
echo 'ok position '.(int)$position.' for tab '.(int)$pos[1].'\r\n';
else
echo '{"hasError" : true, "errors" : "Can not update tab '.(int)$id_tab.' to position '.(int)$position.' "}';
else
echo '{"hasError" : true, "errors" : "This tab ('.(int)$id_tab.') can t be loaded"}';
break;
}
}
}
}
| mit |
siddharthsudheer/lumX-fontAwesome | build/js/templates/file-input_template.js | 334 | angular.module("lumx.file-input").run(['$templateCache', function(a) { a.put('file-input.html', '<div class="input-file">\n' +
' <span class="input-file__label" ng-bind-html="label | unsafe"></span>\n' +
' <span class="input-file__filename"></span>\n' +
' <input type="file">\n' +
'</div>\n' +
'');
}]); | mit |
oleiade/Dormeur | dormeur/response/middlewares.py | 974 | # -*- coding: utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
from functools import wraps
def with_headers(headers):
"""Middleware updating response header with provided datas.
Parameters
----------
list(tuples) : headers
A list of key/value headers wrapped in tuples.
Example :
[('Allow', 'GET, POST'),
('Content-Type', 'application/json') ...]
Returns
-------
Response : response
Original functional call returned response, updated
with the provided headers.
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
response = f(*args, **kwargs)
for header in headers:
if not header[0] in response.headers:
response.headers.add(header[0], header[1])
else:
response.headers.set(header[0], header[1])
return response
return decorated_function
return decorator
| mit |
jeremywohl/moviebot | tests/mock_slack.rb | 255 | #
# Slack mock
#
class SlackMock
attr :history
def initialize
@history = []
end
def pop
@history.pop
end
def say(s)
Thread.new { COMMANDS.handle_msg(s) }.join
end
def notify(s, opts={})
@history << s
end
end
| mit |
lijeffreytli/GeoBeacon | src/com/geobeacondev/geobeacon/ShareMyLocation.java | 21548 | package com.geobeacondev.geobeacon;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class ShareMyLocation extends ActionBarActivity {
private static final int DIALOG_ABOUT_ID = 1;
private static final int DIALOG_HELP_ID = 2;
static final int DIALOG_GETTING_STARTED_ID = 3;
private static final String DELIVERED_ACTION = "SMS_DELIVERED";
private static final String SENT_ACTION = "SMS_SENT";
private Button btnSendSMS;
private String mMessage;
private ArrayList<Contact> mSelectedContacts;
private String mAddress;
private String mMapURL;
private double mLatitude;
private double mLongitude;
private String mStrOptionalMessage = "";
private EditText mOptionalMessage;
private boolean mValidMessage = true;
private SharedPreferences mPrefs;
private TextView tvCharCount;
// Sound
private SoundPool mSounds;
private boolean mSoundOn;
private int mSendSoundID;
/* Debugging Purposes */
private static final String TAG = "GEOBEACON_SHAREMYLOCATION";
static final int PICK_CONTACT_REQUEST = 219;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_share_my_location);
Log.d(TAG, "in onCreate");
if (savedInstanceState != null) {
Log.d(TAG, "in onCreate, savedInstanceState isn't null");
Log.d(TAG, "char sequence we stored for mOptionalMessage is " +
savedInstanceState.getCharSequence("mOptionalMessage").toString());
mMessage = savedInstanceState.getString("mMessage");
Log.d(TAG, "mMessage is " + mMessage);
mSelectedContacts = savedInstanceState.getParcelableArrayList("mSelectedContacts");
Log.d(TAG, "mSelectedContacts is " + mSelectedContacts);
mAddress = savedInstanceState.getString("mAddress");
Log.d(TAG, "mAddress is " + mAddress);
mLongitude = savedInstanceState.getDouble("mLongitude");
Log.d(TAG, "mLongitude is " + mLongitude);
mLatitude = savedInstanceState.getDouble("mLatitude");
Log.d(TAG, "mLatitude is " + mLatitude);
TextView tv = (TextView) findViewById(R.id.tvOptionalMessage);
tv.setText(savedInstanceState.getCharSequence("mOptionalMessage"));
} else {
if (mSelectedContacts == null)
mSelectedContacts = new ArrayList<Contact>();
}
mPrefs = getSharedPreferences("ttt_prefs", MODE_PRIVATE);
/* Get the location information from MainActivity */
Intent intent = getIntent();
mAddress = intent.getStringExtra(MainActivity.ADDRESS);
String latStr = intent.getStringExtra(MainActivity.LAT);
String longStr = intent.getStringExtra(MainActivity.LONG);
//get the selected contacts from "Select Contacts button"
Bundle data = getIntent().getExtras();
mSelectedContacts = data.getParcelableArrayList("SELECTED_CONTACTS");
registerReceiver(sentReceiver, new IntentFilter(SENT_ACTION));
registerReceiver(deliverReceiver, new IntentFilter(DELIVERED_ACTION));
if (longStr != null) {
mLongitude = Double.parseDouble(longStr);
}
if (latStr != null) {
mLatitude = Double.parseDouble(latStr);
}
/* Debugging Purposes */
if (mAddress != null){
Log.d(TAG, mAddress + " : " + mLongitude + " : " + mLatitude);
} else
Log.d(TAG, "address is null");
/* Display the current street address to the screen */
mMessage = mAddress;
TextView currentAddress = (TextView)findViewById(R.id.editCompleteMessage);
currentAddress.setMovementMethod(new ScrollingMovementMethod());
currentAddress.setTextColor(getResources().getColor(R.color.katiewhite));
currentAddress.setText(mMessage);
/* Add the googlemaps link for the sent message */
mMapURL = "https://www.google.com/maps?z=18&t=m&q=loc:" + mLatitude + "+" + mLongitude;
/* Obtain the view of the 'Send Button' */
btnSendSMS = (Button) findViewById(R.id.buttonSend);
/* Once the user hits the "Send" button */
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
playSound(mSendSoundID);
/* Error handling for null contact */
if (mSelectedContacts == null || mSelectedContacts.size() == 0){
/* AlertDialog box for user confirmation */
AlertDialog.Builder builder = new AlertDialog.Builder(ShareMyLocation.this);
builder.setMessage("Please select a contact");
builder.setCancelable(true);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog noContactAlert = builder.create();
noContactAlert.show();
} else {
/* Error handling */
if (mValidMessage == false){
Toast.makeText(getBaseContext(),
"Message exceeds character limit.",
Toast.LENGTH_SHORT).show();
} else {
/* Obtain the optional message if any */
// mOptionalMessage = (EditText)findViewById(R.id.editMessage);
if (mOptionalMessage == null || mOptionalMessage.getText().toString().isEmpty()){
Log.d(TAG, "No Optional Message");
} else {
mStrOptionalMessage = mOptionalMessage.getText().toString();
Log.d(TAG, "Optional Message" + mStrOptionalMessage);
}
/* AlertDialog box for user confirmation */
AlertDialog.Builder builder = new AlertDialog.Builder(ShareMyLocation.this);
String contactNames = "";
for (Contact contact : mSelectedContacts){
contactNames += contact.getName() + ", ";
}
// remove the trailing comma for the last one
if (contactNames.length() > 2)
contactNames = contactNames.substring(0, contactNames.length() - 2);
builder.setMessage("Send to " + contactNames + "?");
builder.setCancelable(true);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (mSelectedContacts != null){
for (Contact contact: mSelectedContacts) {
sendToContact(contact);
}
} else {
Toast.makeText(getBaseContext(),
"Please select a contact.",
Toast.LENGTH_SHORT).show();
}
}
private void sendToContact(Contact contact) {
String phoneNo = contact.getPhoneNo();
String message = "My location: " + mMessage + " ";
String mapURL = "Map coordinates: " + mMapURL + " ";
if (phoneNo != null && phoneNo.length() > 0) {
/* Send the optional message */
sendSMS(phoneNo, mStrOptionalMessage);
/* Send the user's location */
if (message.length() > 160) {
int i = 0;
while (i < message.length()) {
int endIdx = Math.min(message.length(), i + 160);
sendSMS(phoneNo, message.substring(i, endIdx));
i += 160;
}
sendSMS(phoneNo, mapURL);
}
else if (message.length() + mapURL.length() < 160) {
message = message + "\n" + mapURL;
sendSMS(phoneNo, message);
} else {
sendSMS(phoneNo, message);
sendSMS(phoneNo, mapURL);
}
finish(); //After sending the message, return back to MainActivity
}
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
});
displaySelectedContacts();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "in onDestroy");
unregisterReceiver(deliverReceiver);
unregisterReceiver(sentReceiver);
}
public void getContactList(View view){
playSound(mSendSoundID);
ProgressDialog progress = new ProgressDialog(this, R.style.ProgressDialogTheme);
String message = "Loading Contact List...";
SpannableString ss1= new SpannableString(message);
ss1.setSpan(new RelativeSizeSpan(1.3f), 0, ss1.length(), 0);
ss1.setSpan(new ForegroundColorSpan(Color.BLACK), 0, ss1.length(), 0);
progress.setMessage(ss1);
// progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// progress.setMessage(message);
progress.setTitle("Please wait");
new LaunchContactsTask(progress).execute();
}
/* This method sends a text message to a specific phone number */
private void sendSMS(String phoneNumber, String message){
if (message == null || message.isEmpty()){
return;
}
if (phoneNumber == null || phoneNumber.isEmpty()){
return;
}
SmsManager sms = SmsManager.getDefault();
/* delivery confirmation code adapted from Mike's SMS
* automatic responder, ResponserService.java
*/
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT_ACTION), PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED_ACTION), PendingIntent.FLAG_UPDATE_CURRENT);
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
public void getAdditionalMessage(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this, R.style.ProgressDialogTheme);
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(parms);
layout.setGravity(Gravity.CLIP_VERTICAL);
layout.setPadding(2, 2, 2, 2);
TextView tv = new TextView(this);
tv.setText("Additional Message");
tv.setPadding(10, 10, 10, 10);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(20);
TextView currentMessage = (TextView) findViewById(R.id.tvOptionalMessage);
mOptionalMessage = new EditText(this);
mOptionalMessage.setText(currentMessage.getText());
mOptionalMessage.setSelection(mOptionalMessage.getText().length());
mOptionalMessage.setTextColor(Color.parseColor("#000000"));
tvCharCount = new TextView(this);
tvCharCount.setText(mOptionalMessage.getText().toString().length() + "/160");
mOptionalMessage.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
//checkSMSLength(mOptionalMessage); // pass your EditText Obj here.
int valid_len = 0;
tvCharCount.setTextColor(Color.parseColor("#000000"));
try {
if (mOptionalMessage.getText().toString().length() <= 0) {
mOptionalMessage.setError(null);
valid_len = 0;
tvCharCount.setText("0/160");
tvCharCount.setTextColor(Color.parseColor("000000"));
} else if (mOptionalMessage.getText().toString().length() > 160){
mValidMessage = false;
mOptionalMessage.setError("Error: Character limit exceeded");
valid_len = 0;
tvCharCount.setText("Error");
tvCharCount.setTextColor(Color.parseColor("#D00000"));
} else {
mValidMessage = true;
mOptionalMessage.setError(null);
valid_len = mOptionalMessage.getText().toString().length();
tvCharCount.setText(String.valueOf(valid_len) + "/" + 160);
tvCharCount.setTextColor(Color.parseColor("000000"));
}
} catch (Exception e) {
Log.e("error", "" + e);
}
}
});
LinearLayout.LayoutParams tv1Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
tv1Params.bottomMargin = 5;
layout.addView(mOptionalMessage, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(tvCharCount,tv1Params);
alertDialogBuilder.setView(layout);
alertDialogBuilder.setTitle("Title");
alertDialogBuilder.setCustomTitle(tv);
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
TextView mtvOptionalMessage = (TextView) findViewById(R.id.tvOptionalMessage);
mtvOptionalMessage.setText(mOptionalMessage.getText().toString());
mtvOptionalMessage.setTextColor(Color.parseColor("#EBE6C5"));
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alertDialogBuilder.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.share_my_location, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()){
case R.id.action_settings:
startActivityForResult(new Intent(this, Preferences.class),0);
return true;
case R.id.menu_about:
showDialog(DIALOG_ABOUT_ID);
return true;
case R.id.menu_help:
showDialog(DIALOG_HELP_ID);
return true;
case R.id.menu_getting_started:
showDialog(DIALOG_GETTING_STARTED_ID);
return true;
}
return false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("mMessage", mMessage);
outState.putParcelableArrayList("mSelectedContacts", mSelectedContacts);
TextView tv = (TextView) findViewById(R.id.tvOptionalMessage);
outState.putCharSequence("mOptionalMessage", tv.getText());
outState.putString("mAddress", mAddress);
outState.putDouble("mLongitude", mLongitude);
outState.putDouble("mLatitude", mLatitude);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mMessage = savedInstanceState.getString("mMessage");
mSelectedContacts = savedInstanceState.getParcelableArrayList("mSelectedContacts");
mAddress = savedInstanceState.getString("mAddress");
mLongitude = savedInstanceState.getDouble("mLongitude");
mLatitude = savedInstanceState.getDouble("mLatitude");
TextView tv = (TextView) findViewById(R.id.tvOptionalMessage);
tv.setText(savedInstanceState.getCharSequence("mOptionalMessage"));
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch(id) {
case DIALOG_ABOUT_ID:
dialog = createAboutDialog(builder);
break;
case DIALOG_HELP_ID:
dialog = createHelpDialog(builder);
break;
case DIALOG_GETTING_STARTED_ID:
dialog = createGettingStartedDialog(builder);
break;
}
return dialog;
}
private Dialog createHelpDialog(Builder builder) {
Context context = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.help_dialog, null);
builder.setView(layout);
builder.setPositiveButton("OK", null);
return builder.create();
}
private Dialog createAboutDialog(Builder builder) {
Context context = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.about_dialog, null);
builder.setView(layout);
builder.setPositiveButton("OK", null);
return builder.create();
}
private Dialog createGettingStartedDialog(Builder builder) {
Context context = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.getting_started_dialog, null);
builder.setView(layout);
builder.setPositiveButton("OK", null);
return builder.create();
}
/* Method obtains phone number from the contact Uri. */
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT_REQUEST) :
if (resultCode == Activity.RESULT_OK) {
mSelectedContacts = data.getParcelableArrayListExtra("SELECTED_CONTACTS");
displaySelectedContacts();
}
break;
case RESULT_CANCELED:
// Apply potentially new settings
mSoundOn = mPrefs.getBoolean("sound", true);
break;
}
}
private String getContactNames() {
String contactNames = "";
for (Contact contact: mSelectedContacts) {
contactNames += contact.contactName + ", ";
}
// remove the trailing comma for the last one
if (contactNames.length() >= 2)
contactNames = contactNames.substring(0, contactNames.length() - 2);
return contactNames;
}
private void displaySelectedContacts(){
TextView text = (TextView) findViewById(R.id.selectedContacts);
text.setTextColor(getResources().getColor(R.color.katiewhite));
text.setMovementMethod(new ScrollingMovementMethod());
if (mSelectedContacts != null){
String output = getContactNames();
if (output != null && !output.isEmpty()){
text.setText(output);
}
else
text.setText("No contacts selected");
}
}
private void createSoundPool() {
mSounds = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
// 2 = maximum sounds to play at the same time,
// AudioManager.STREAM_MUSIC is the stream type typically used for games
// 0 is the "the sample-rate converter quality. Currently has no effect. Use 0 for the default."
mSendSoundID = mSounds.load(this, R.raw.click, 1);
}
private void playSound(int soundID) {
if (mSoundOn && mSounds != null)
mSounds.play(soundID, 1, 1, 1, 0, 1);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "in on Resume");
mSoundOn = mPrefs.getBoolean("sound", true);
createSoundPool();
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "in onPause");
if(mSounds != null) {
mSounds.release();
mSounds = null;
}
}
private BroadcastReceiver sentReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context c, Intent in) {
Log.d(TAG, "in onReceive method of sentReceiver");
Log.d(TAG, "result code: " + getResultCode());
Log.d(TAG, "result code equals Activity.RESULT_OK " + (getResultCode() == Activity.RESULT_OK));
Log.d(TAG, "Context: " + c);
Log.d(TAG, "Intent: " + in);
if(getResultCode() == Activity.RESULT_OK && in.getAction().equals(SENT_ACTION)) {
Log.d(TAG, "Activity result ok");
smsSent();
}
else {
Log.d(TAG, "Activity result NOT ok");
smsFailed();
}
}
};
public void smsSent(){
Toast.makeText(this, "SMS sent", Toast.LENGTH_SHORT).show();
}
public void smsFailed(){
Toast.makeText(this, "SMS failed to send", Toast.LENGTH_SHORT).show();
}
private BroadcastReceiver deliverReceiver = new BroadcastReceiver() {
// this is never getting called
@Override public void onReceive(Context c, Intent in) {
//SMS delivered actions
Log.d(TAG, "in onReceive method of deliverReceiver");
smsDelivered();
}
};
public void smsDelivered(){
Log.d(TAG, "in smsDelivered method");
Toast.makeText(this, "SMS delivered", Toast.LENGTH_LONG).show();
}
// http://stackoverflow.com/questions/5202158/how-to-display-progress-dialog-before-starting-an-activity-in-android
public class LaunchContactsTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress;
public LaunchContactsTask(ProgressDialog progress) {
this.progress = progress;
}
public void onPreExecute() {
progress.show();
}
public Void doInBackground(Void... unused) {
Intent intent = new Intent(ShareMyLocation.this, ContactList.class);
intent.putExtra("SELECTED_CONTACTS", mSelectedContacts);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
return null;
}
public void onPostExecute(Void unused) {
progress.dismiss();
}
}
}
| mit |
mtchavez/circleci | spec/support/checkout_keys.rb | 219 | # frozen_string_literal: true
def test_checkout_key_fingerprint
'3e:35:e0:96:f7:c8:23:9c:b8:2f:50:9e:d0:16:f7:05'
end
def test_delete_checkout_key_fingerprint
'29:15:12:e8:f7:f4:17:7a:8f:cc:db:de:43:53:f4:73'
end
| mit |
MihailDobrev/SoftUni | C# Fundamentals/C# OOP Advanced/BashSoft/BashSoftProgram/IO/Commands/DisplayCommand.cs | 2903 | namespace BashSoftProgram
{
using BashSoftProgram.Attributes;
using BashSoftProgram.Contracts;
using BashSoftProgram.Exceptions;
using BashSoftProgram.IO.Commands;
using System;
using System.Collections.Generic;
[Alias("display")]
public class DisplayCommand : Command, IExecutable
{
[Inject]
private IDatabase repository;
public DisplayCommand(string input, string[] data)
: base(input, data)
{
}
public override void Execute()
{
if (this.Data.Length != 3)
{
throw new InvalidCommandException(this.Input);
}
string entityToDisplay = this.Data[1];
string sortType = this.Data[2];
if (entityToDisplay.Equals("students", System.StringComparison.OrdinalIgnoreCase))
{
IComparer<IStudent> studentComparer = this.CreateStudentComparator(sortType);
ISimpleOrderedBag<IStudent> list = this.repository.GetAllStudentsSorted(studentComparer);
OutputWriter.WriteMessageOnNewLine(list.JoinWith(Environment.NewLine));
}
else if (entityToDisplay.Equals("courses", System.StringComparison.OrdinalIgnoreCase))
{
IComparer<ICourse> courseComparer = this.CreateCourseComparator(sortType);
ISimpleOrderedBag<ICourse> list = this.repository.GetAllCoursesSorted(courseComparer);
OutputWriter.WriteMessageOnNewLine(list.JoinWith(Environment.NewLine));
}
else
{
throw new InvalidCommandException(this.Input);
}
}
private IComparer<ICourse> CreateCourseComparator(string sortType)
{
if (sortType.Equals("ascending", StringComparison.OrdinalIgnoreCase))
{
return Comparer<ICourse>.Create((courseOne, courseTwo) => courseOne.CompareTo(courseTwo));
}
if (sortType.Equals("descending", StringComparison.OrdinalIgnoreCase))
{
return Comparer<ICourse>.Create((courseOne, courseTwo) => courseTwo.CompareTo(courseOne));
}
throw new InvalidCommandException(this.Input);
}
private IComparer<IStudent> CreateStudentComparator(string sortType)
{
if (sortType.Equals("ascending", StringComparison.OrdinalIgnoreCase))
{
return Comparer<IStudent>.Create((studentOne, studentTwo) => studentOne.CompareTo(studentTwo));
}
if (sortType.Equals("descending",StringComparison.OrdinalIgnoreCase))
{
return Comparer<IStudent>.Create((studentOne, studentTwo) => studentTwo.CompareTo(studentOne));
}
throw new InvalidCommandException(this.Input);
}
}
} | mit |
feedbin/feedbin | app/presenters/subscription_presenter.rb | 1664 | class SubscriptionPresenter < BasePresenter
presents :subscription
def graph_volume
@template.number_with_delimiter(total_posts)
end
def total_posts
counts.last(30).sum
end
def graph_date_start
days.ago.to_formatted_s(:day_month).upcase
end
def graph_date_mid
total_days = (Time.now - days.ago).to_i
(days.ago + total_days / 2).to_formatted_s(:day_month).upcase
end
def graph_date_end
Time.now.to_formatted_s(:day_month).upcase
end
def graph_bars
max = counts.max
counts.each_with_index.map do |count, index|
percent = count == 0 ? 0 : ((count.to_f / max.to_f) * 100).round
date = (days.ago + index.days)
ordinal = date.day.ordinalize
display_date = "#{date.strftime("%B")} #{ordinal}"
OpenStruct.new(percent: percent, count: count, day: display_date)
end
end
def graph_quarter(quarter)
count = counts.max.to_f / 4.to_f
if count == 0 || (quarter != 4 && counts.max < 4)
nil
else
(count * quarter).round
end
end
def bar_class(data)
data.count == 0 ? "zero" : ""
end
def bar_count(data)
type = subscription.feed.twitter_feed? ? "tweet" : "article"
@template.pluralize(data.count, type)
end
def muted_status
if subscription.muted
"muted"
end
end
def mute_class
if subscription.muted
"status-muted"
end
end
def sparkline
Sparkline.new(width: 80, height: 15, stroke: 2, percentages: subscription.entries_count)
end
private
def counts
@counts ||= FeedStat.get_entry_counts([subscription.feed.id], days.ago).values.first
end
def days
89.days
end
end
| mit |
davinnovation/TikiTaka | encog-examples/src/main/java/org/encog/examples/neural/cpn/RocketCPN.java | 9437 | /*
* Encog(tm) Java Examples v3.3
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-examples
*
* Copyright 2008-2014 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.examples.neural.cpn;
import org.encog.Encog;
import org.encog.ml.data.MLData;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.data.basic.BasicMLData;
import org.encog.ml.data.basic.BasicMLDataSet;
import org.encog.ml.train.MLTrain;
import org.encog.neural.cpn.CPN;
import org.encog.neural.cpn.training.TrainInstar;
import org.encog.neural.cpn.training.TrainOutstar;
/**
*
* Use a counterpropagation network to determine the angle a rocket is pointed.
*
* This is based on a an example by Karsten Kutza,
* written in C on 1996-01-24.
* http://www.neural-networks-at-your-fingertips.com
*
*/
public class RocketCPN {
public static final int WIDTH = 11;
public static final int HEIGHT = 11;
public static final String[][] PATTERN1 = { {
" ",
" ",
" O ",
" O ",
" OOO ",
" OOO ",
" OOO ",
" OOOOO ",
" OOOOO ",
" ",
" " },
{ " ",
" ",
" O ",
" O ",
" OOO ",
" OOO ",
" OOO ",
" OOOOO ",
"OOOOO ",
" ",
" " },
{ " ",
" ",
" ",
" OO ",
" OOOOO ",
" OOOOOOO ",
" OOOOO ",
" OO ",
" ",
" ",
" " },
{ " ",
" ",
"OOOOO ",
" OOOOO ",
" OOO ",
" OOO ",
" OOO ",
" O ",
" O ",
" ",
" " },
{ " ",
" ",
" OOOOO ",
" OOOOO ",
" OOO ",
" OOO ",
" OOO ",
" O ",
" O ",
" ",
" " },
{ " ",
" ",
" OOOOO",
" OOOOO ",
" OOO ",
" OOO ",
" OOO ",
" O ",
" O ",
" ",
" " },
{ " ",
" ",
" ",
" OO ",
" OOOOO ",
" OOOOOOO ",
" OOOOO ",
" OO ",
" ",
" ",
" " },
{ " ",
" ",
" O ",
" O ",
" OOO ",
" OOO ",
" OOO ",
" OOOOO ",
" OOOOO",
" ",
" " } };
String[][] PATTERN2 = { {
" ",
" ",
" O ",
" O ",
" O ",
" OOO ",
" OOO ",
" OOO ",
" OOOOO ",
" ",
" " },
{ " ",
" ",
" O ",
" O ",
" O O ",
" O O ",
" O O ",
" O O ",
" O O ",
" ",
" " },
{ " ",
" ",
" ",
" O ",
" OOO ",
" OOO ",
" OOO ",
" OOOOO ",
" ",
" ",
" " },
{ " ",
" ",
" ",
" ",
" O ",
" O ",
" O ",
" OOO ",
" ",
" ",
" " },
{ " ",
" O ",
" O ",
" O ",
" OOO ",
" OO ",
" OOO O",
" OOOO ",
" OOOOO ",
" ",
" O " },
{ " ",
" ",
" O ",
" O ",
" OOO ",
" OOO ",
" OOO ",
" OOOOO ",
" OOOOO ",
" ",
" " },
{ " ",
" ",
" O ",
" O ",
" OOO ",
" OOO ",
" OOO ",
" OOOOO ",
" OOOOO ",
" ",
" " },
{ " ",
" ",
" O ",
" O ",
" OOO ",
" OOO ",
" OOO ",
" OOOOO ",
"OOOOO ",
" ",
" " } };
public static final double HI = 1;
public static final double LO = 0;
private double[][] input1;
private double[][] input2;
private double[][] ideal1;
private int inputNeurons;
private int instarNeurons;
private int outstarNeurons;
public void prepareInput()
{
int n,i,j;
this.inputNeurons = WIDTH * HEIGHT;
this.instarNeurons = PATTERN1.length;
this.outstarNeurons = 2;
this.input1 = new double[PATTERN1.length][this.inputNeurons];
this.input2 = new double[PATTERN2.length][this.inputNeurons];
this.ideal1 = new double[PATTERN1.length][this.outstarNeurons];
for (n=0; n<PATTERN1.length; n++) {
for (i=0; i<HEIGHT; i++) {
for (j=0; j<WIDTH; j++) {
input1[n][i*WIDTH+j] = (PATTERN1[n][i].charAt(j) == 'O') ? HI : LO;
input2[n][i*WIDTH+j] = (PATTERN2[n][i].charAt(j) == 'O') ? HI : LO;
}
}
}
normalizeInput();
for (n=0; n<PATTERN1.length; n++) {
this.ideal1[n][0] = Math.sin(n * 0.25 * Math.PI);
this.ideal1[n][1] = Math.cos(n * 0.25 * Math.PI);
}
}
public double sqr(double x)
{
return x*x;
}
void normalizeInput()
{
int n,i;
double length1, length2;
for (n=0; n<PATTERN1.length; n++) {
length1 = 0;
length2 = 0;
for (i=0; i<this.inputNeurons; i++) {
length1 += sqr(this.input1[n][i]);
length2 += sqr(this.input2[n][i]);
}
length1 = Math.sqrt(length1);
length2 = Math.sqrt(length2);
for (i=0; i<this.inputNeurons; i++) {
input1[n][i] /= length1;
input2[n][i] /= length2;
}
}
}
public CPN createNetwork()
{
CPN result = new CPN(this.inputNeurons, this.instarNeurons, this.outstarNeurons,1);
return result;
}
public void trainInstar(CPN network,MLDataSet training)
{
int epoch = 1;
MLTrain train = new TrainInstar(network,training,0.1,true);
do {
train.iteration();
System.out
.println("Training instar, Epoch #" + epoch + ", Error: " + train.getError() );
epoch++;
} while(train.getError()>0.01);
}
public void trainOutstar(CPN network,MLDataSet training)
{
int epoch = 1;
MLTrain train = new TrainOutstar(network,training,0.1);
do {
train.iteration();
System.out
.println("Training outstar, Epoch #" + epoch + ", error=" + train.getError() );
epoch++;
} while(train.getError()>0.01);
}
public MLDataSet generateTraining(double[][] input,double[][] ideal)
{
MLDataSet result = new BasicMLDataSet(input,ideal);
return result;
}
public double determineAngle(MLData angle)
{
double result;
result = ( Math.atan2(angle.getData(0), angle.getData(1)) / Math.PI) * 180;
if (result < 0)
result += 360;
return result;
}
public void test(CPN network,String[][] pattern,double[][] input)
{
for(int i=0;i<pattern.length;i++)
{
MLData inputData = new BasicMLData(input[i]);
MLData outputData = network.compute(inputData);
double angle = determineAngle(outputData);
// display image
for(int j=0;j<HEIGHT;j++)
{
if( j==HEIGHT-1 )
System.out.println("["+pattern[i][j]+"] -> " + ((int)angle) + " deg");
else
System.out.println("["+pattern[i][j]+"]");
}
System.out.println();
}
}
public void run()
{
prepareInput();
normalizeInput();
CPN network = createNetwork();
MLDataSet training = generateTraining(this.input1,this.ideal1);
trainInstar(network,training);
trainOutstar(network,training);
test(network,PATTERN1,this.input1);
}
public static void main(String[] args)
{
RocketCPN cpn = new RocketCPN();
cpn.run();
Encog.getInstance().shutdown();
}
}
| mit |
tuupola/base85 | src/Base85/PhpEncoder.php | 3016 | <?php
declare(strict_types = 1);
/*
Copyright (c) 2017-2021 Mika Tuupola
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.
*/
/**
* @see https://github.com/tuupola/base85
* @license https://opensource.org/licenses/mit-license.php
*/
namespace Tuupola\Base85;
class PhpEncoder extends BaseEncoder
{
/**
* Encode given data to a base85 string
*/
public function encode(string $data): string
{
$padding = 0;
if ($modulus = strlen($data) % 4) {
$padding = 4 - $modulus;
}
$data .= str_repeat("\0", $padding);
$converted = [$this->options["prefix"]];
foreach ((array)unpack("N*", $data) as $uint32) {
/* Four spaces exception. */
if ($this->options["compress.spaces"]) {
if (0x20202020 === $uint32) {
$converted[] = "y";
continue;
}
}
/* All zero data exception. */
if ($this->options["compress.zeroes"]) {
if (0x00000000 === $uint32) {
$converted[] = "z";
continue;
}
}
$digits = "";
$quotient = $uint32;
foreach ([52200625, 614125, 7225, 85, 1] as $pow) {
$reminder = $quotient % $pow;
$quotient = (integer) ($quotient / $pow);
$digits .= $this->options["characters"][$quotient];
$quotient = $reminder;
}
$converted[] = $digits;
}
$last = count($converted) - 1;
/* The z exception does not apply to the last block. */
if ("z" === $converted[$last]) {
$converted[$last] = "!!!!!";
}
/* Remove any padding from the returned result. */
if ($padding) {
$converted[$last] = substr($converted[$last], 0, 5 - $padding);
}
$converted[] = $this->options["suffix"];
return implode($converted);
}
}
| mit |
jonbo372/sipstack | sipstack-core/src/main/java/io/sipstack/transaction/event/impl/SipTransactionEventImpl.java | 596 | package io.sipstack.transaction.event.impl;
import io.pkts.packet.sip.SipMessage;
import io.sipstack.transaction.Transaction;
import io.sipstack.transaction.event.SipTransactionEvent;
/**
* @author jonas@jonasborjesson.com
*/
public class SipTransactionEventImpl extends TransactionEventImpl implements SipTransactionEvent {
private final SipMessage msg;
public SipTransactionEventImpl(final Transaction transaction, final SipMessage msg) {
super(transaction);
this.msg = msg;
}
@Override
public final SipMessage message() {
return msg;
}
}
| mit |
esjay/nonbots-bot | webpack.config.js | 137 | module.exports = {
entry: './site/index.js',
output: {
path: './dist',
filename: 'site.bundle.js'
}
};
| mit |
mattherman/MbDotNet | MbDotNet/Models/Predicates/MatchesPredicate.cs | 604 | using Newtonsoft.Json;
using MbDotNet.Models.Predicates.Fields;
namespace MbDotNet.Models.Predicates
{
public class MatchesPredicate<T> : PredicateBase where T : PredicateFields
{
[JsonProperty("matches")]
public T Fields { get; private set; }
public MatchesPredicate(T fields, bool isCaseSensitive = false, string exceptExpression = null,
XPathSelector xpath = null, JsonPathSelector jsonpath = null)
: base(isCaseSensitive, exceptExpression, xpath, jsonpath)
{
Fields = fields;
}
}
}
| mit |
mike-robertson/doctor_finder | client/app/app.js | 633 | 'use strict';
angular.module('mrWebdesignApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'btford.socket-io',
'ui.router',
'ui.bootstrap',
'google-maps'.ns()
])
.config(['GoogleMapApiProvider'.ns(), function (GoogleMapApi) {
GoogleMapApi.configure({
key: 'AIzaSyAaZm95uSnPabqgVJx9cpl2UbSKyBCa9Ok',
v: '3.17',
libraries: 'weather,geometry,visualization'
});
}])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
$urlRouterProvider
.otherwise('/');
$locationProvider.html5Mode(true);
})
.run(function () {
}); | mit |
nikofil/go-dpi | modules/classifiers/rdp.go | 1135 | package classifiers
import (
"encoding/binary"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/mushorg/go-dpi/types"
"strings"
)
// RDPClassifier struct
type RDPClassifier struct{}
// HeuristicClassify for RDPClassifier
func (classifier RDPClassifier) HeuristicClassify(flow *types.Flow) bool {
return checkFirstPayload(flow.GetPackets(), layers.LayerTypeTCP,
func(payload []byte, packetsRest []gopacket.Packet) bool {
if len(payload) < 20 {
return false
}
tpktLen := int(binary.BigEndian.Uint16(payload[2:4]))
// check TPKT header
isValidTpkt := payload[0] == 3 && payload[1] == 0 && tpktLen == len(payload)
// check COTP header
isValidCotp := int(payload[4]) == len(payload[5:]) && payload[5] == 0xE0
// check RDP payload
rdpPayloadStr := string(payload[11:])
isValidRdp := strings.Contains(rdpPayloadStr, "mstshash=") ||
strings.Contains(rdpPayloadStr, "msts=")
return isValidTpkt && isValidCotp && isValidRdp
})
}
// GetProtocol returns the corresponding protocol
func (classifier RDPClassifier) GetProtocol() types.Protocol {
return types.RDP
}
| mit |
CSClassroom/CSClassroom | Services/test/CSClassroom/CSClassroom.Service.UnitTests/Assignments/QuestionResolvers/QuestionResolverUnitTestBase.cs | 1624 | using System;
using System.Collections.Generic;
using System.Text;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using CSC.CSClassroom.Model.Assignments;
using CSC.CSClassroom.Model.Classrooms;
using CSC.CSClassroom.Model.Users;
using CSC.CSClassroom.Service.UnitTests.Utilities;
namespace CSC.CSClassroom.Service.UnitTests.Assignments.QuestionResolvers
{
/// <summary>
/// The base class for classes that unit test different types
/// of question resolvers.
/// </summary>
public class QuestionResolverUnitTestBase
{
/// <summary>
/// Creates a new UserQuestionData object.
/// </summary>
protected UserQuestionData CreateUserQuestionData(
bool attemptsRemaining,
int templateQuestionId = 1,
string cachedQuestionData = null,
int? seed = null,
Question question = null,
Classroom classroom = null,
User user = null)
{
return new UserQuestionData()
{
AssignmentQuestion = new AssignmentQuestion()
{
Assignment = new Assignment()
{
MaxAttempts = attemptsRemaining
? (int?)null
: 1,
Classroom = classroom
},
QuestionId = templateQuestionId,
Question = question
},
NumAttempts = 1,
CachedQuestionData = cachedQuestionData,
Seed = seed,
User = user
};
}
/// <summary>
/// Creates a new UserQuestionSubmission object.
/// </summary>
protected UserQuestionSubmission CreateUserQuestionSubmission(
string cachedQuestionData = null,
int? seed = null)
{
return new UserQuestionSubmission()
{
CachedQuestionData = cachedQuestionData,
Seed = seed
};
}
}
}
| mit |
thomasvanhorde/self-engine | inc/class/external/zend/Gdata/YouTube/Extension/Token.php | 2269 | <?php
/**
* zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category zend
* @package zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Token.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see zend_Gdata_Extension
*/
require_once ENGINE_URL.FOLDER_CLASS_EXT.'zend/Gdata/Extension.php';
/**
* Represents the yt:token element used by the YouTube data API
*
* @category zend
* @package zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class zend_Gdata_YouTube_Extension_Token extends zend_Gdata_App_Extension
{
protected $_rootNamespace = 'yt';
protected $_rootElement = 'token';
/**
* Constructs a new zend_Gdata_YouTube_Extension_Token object.
*/
public function __construct($text = null)
{
$this->registerAllNamespaces(zend_Gdata_YouTube::$namespaces);
parent::__construct();
$this->_text = $text;
}
/**
* Retrieves a DOMElement which corresponds to this element and all
* child properties. This is used to build an entry back into a DOM
* and eventually XML text for sending to the server upon updates, or
* for application storage/persistence.
*
* @param DOMDocument $doc The DOMDocument used to construct DOMElements
* @return DOMElement The DOMElement representing this element and all
* child properties.
*/
public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
{
$element = parent::getDOM($doc, $majorVersion, $minorVersion);
return $element;
}
}
| mit |
vue-bulma/vue-bulma | packages/vue-bulma-examples/src/code/components/navbar.js | 5253 | let code = {}
code.basic = `\
<vb-navbar>
<vb-navbar-item slot="brand">
<a>
<img src="https://bulma.io/images/bulma-logo.png" width="112" height="28" alt="Bulma">
</a>
</vb-navbar-item>
<vb-navbar-item>
<vb-icon name="fa fa-home" iconSize="lg"></vb-icon>
</vb-navbar-item>
<vb-navbar-item>Documentation</vb-navbar-item>
<vb-navbar-dropdown>
<template slot="title">More</template>
<vb-navbar-item>About</vb-navbar-item>
<vb-navbar-item>Jobs</vb-navbar-item>
<hr class="navbar-divider">
<vb-navbar-item>Contact</vb-navbar-item>
</vb-navbar-dropdown>
<vb-navbar-item slot="right" static>
<vb-buttons-list>
<vb-button color="primary">Sign up</vb-button>
<vb-button color="light">Log in</vb-button>
</vb-buttons-list>
</vb-navbar-item>
</vb-navbar>
`
code.transparentNavbar = `\
<vb-navbar transparent>
<vb-navbar-item slot="brand">
<a>
<img src="https://bulma.io/images/bulma-logo.png" width="112" height="28" alt="Bulma">
</a>
</vb-navbar-item>
<vb-navbar-item>
<vb-icon name="fa fa-home" iconSize="lg"></vb-icon>
</vb-navbar-item>
<vb-navbar-item>Documentation</vb-navbar-item>
<vb-navbar-dropdown>
<template slot="title">More</template>
<vb-navbar-item>About</vb-navbar-item>
<vb-navbar-item>Jobs</vb-navbar-item>
<hr class="navbar-divider">
<vb-navbar-item>Contact</vb-navbar-item>
</vb-navbar-dropdown>
<template slot="right">
<vb-navbar-item>
<vb-buttons-list>
<vb-button color="primary">Sign up</vb-button>
<vb-button color="light">Log in</vb-button>
</vb-buttons-list>
</vb-navbar-item>
</template>
</vb-navbar>
`
code.fixedNavbar = `\
<template>
<div>
<vb-button-addons>
<vb-button @click="togglePosition('top')">Show Fixed Top</vb-button>
<vb-button @click="togglePosition('bottom')">Show Fixed Bottom</vb-button>
<vb-button @click="togglePosition()">Hide</vb-button>
</vb-button-addons>
<vb-navbar v-if="position" :position="position">
<vb-navbar-item slot="brand">
<a>
<img src="https://bulma.io/images/bulma-logo.png" width="112" height="28" alt="Bulma">
</a>
</vb-navbar-item>
<vb-navbar-item>
<vb-icon name="fa fa-home" iconSize="lg"></vb-icon>
</vb-navbar-item>
<vb-navbar-item>Documentation</vb-navbar-item>
<vb-navbar-dropdown>
<template slot="title">More</template>
<vb-navbar-item>About</vb-navbar-item>
<vb-navbar-item>Jobs</vb-navbar-item>
</vb-navbar-dropdown>
<template slot="right">
<vb-navbar-item static>
<vb-buttons-list>
<vb-button color="primary">Sign up</vb-button>
<vb-button color="light">Log in</vb-button>
</vb-buttons-list>
</vb-navbar-item>
</template>
</vb-navbar>
</div>
</template>
<script>
export default {
data() {
return {
position: null
}
},
methods: {
togglePosition(value) {
this.position = value
}
}
}
</script>
`
code.rightDropdown = `\
<vb-navbar>
<vb-navbar-dropdown>
<template slot="title">Left</template>
<vb-navbar-item>About</vb-navbar-item>
<vb-navbar-item>Jobs</vb-navbar-item>
</vb-navbar-dropdown>
<vb-navbar-dropdown dropup>
<template slot="title">Up</template>
<vb-navbar-item>About</vb-navbar-item>
<vb-navbar-item>Jobs</vb-navbar-item>
</vb-navbar-dropdown>
<vb-navbar-dropdown arrow-less>
<template slot="title">Dropdown without arrow</template>
<vb-navbar-item>About</vb-navbar-item>
<vb-navbar-item>Jobs</vb-navbar-item>
</vb-navbar-dropdown>
<template slot="right">
<vb-navbar-dropdown>
<template slot="title">Right</template>
<vb-navbar-item>About</vb-navbar-item>
<vb-navbar-item>Jobs</vb-navbar-item>
</vb-navbar-dropdown>
</template>
</vb-navbar>
`
code.colors = `\
<template>
<div>
<vb-buttons-list slot="control">
<vb-button v-for="color in colors" :key="color" :color="color" @click="handleCheckColor(color)">{{color}}</vb-button>
</vb-buttons-list>
<vb-navbar :color="color">
<vb-navbar-item slot="brand">
<a>
<img :src="colorPicture" width="112" height="28" alt="Bulma">
</a>
</vb-navbar-item>
<vb-navbar-item>Home</vb-navbar-item>
<vb-navbar-dropdown title="More">
<vb-navbar-item>About</vb-navbar-item>
</vb-navbar-dropdown>
<vb-navbar-item slot="right" static>
<vb-button color="primary">Sign up</vb-button>
</vb-navbar-item>
</vb-navbar>
</div>
</template>
<script>
const COLORS = [
'primary',
'info',
'success',
'warning',
'danger',
'white',
'light',
'dark',
'black',
'link'
]
export default {
data() {
return {
colors,
color: 'primary'
}
},
computed: {
picture() {
const picName = ['warning', 'light', 'white'].includes(this.color)
? 'bulma-logo.png'
: 'bulma-logo-white.png'
return \`https://bulma.io/images/\${picName}\`
}
},
methods: {
handleCheckColor(color) {
this.color = color
}
}
}
</script>
`
export default code
| mit |
LeoPlatform/PHP | src/lib/Stream.php | 1172 | <?php
namespace LEO;
class Stream {
private $id;
private $opts;
private $config;
public function __construct($id=null, $opts=[]) {
$this->id = $id;
$this->opts = array_merge([
"enableLogging"=>false,
"version"=>"latest",
"server"=>gethostname(),
"uploader"=>"firehose"
],$opts);
$this->config = array_merge([
"region"=>"us-west-2",
"firehose"=>null,
"kinesis"=>null,
"s3"=>null
], $opts['config']);
}
public function createBufferedWriteStream($opts=[], $checkpointer) {
if(!$this->id) {
throw new \Exception("You must specify a bot id");
}
switch($this->opts['uploader']) {
case "firehose":
$uploader = new Firehose($this->id, $this->config);
break;
case "kinesis":
$uploader = new Kinesis($this->id, $this->config);
break;
case "mass":
$uploader = new Mass($this->id, $this->config);
break;
case "ugradeable":
$uploader = new Upgradeable($this->id, $this->config);
break;
}
return new Combiner($this->id, $opts, $uploader,$checkpointer);
}
public function checkpoint() {
}
public function createTransformStream($queue, $toQueue, $opts, $transformFunc) {
}
} | mit |
ozburo/babushka | example/models.py | 943 | # -*- coding: utf-8 -*-
"""
example.models.py
"""
from google.appengine.ext.ndb import model
from babushka.model import BabushkaModel
# --------------------------------------------------------------------
# Blog Model
# --------------------------------------------------------------------
class Blog(BabushkaModel):
name = model.StringProperty(required=True)
@property
def latest_posts(self):
return Post.query().filter(Post.blog==self.key).order(-Post.updated)
# --------------------------------------------------------------------
# Post Model
# --------------------------------------------------------------------
class Post(BabushkaModel):
blog = model.KeyProperty(kind='Blog', required=False)
title = model.StringProperty(required=True)
body = model.TextProperty(required=True)
_cache_break = 'blog'
#: alternative syntax style
class Babushka:
cache_break = 'blog'
| mit |
corker/estuite | Estuite.StreamStore/AggregateId.cs | 322 | using System;
namespace Estuite.StreamStore
{
public class AggregateId
{
public AggregateId(string value)
{
if (string.IsNullOrWhiteSpace(value)) throw new ArgumentOutOfRangeException(nameof(value));
Value = value;
}
public string Value { get; }
}
} | mit |
ajlopez/SharpMongo | Src/SharpMongo.Language/Commands/ExitCommand.cs | 332 | namespace SharpMongo.Language.Commands
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class ExitCommand : ICommand
{
public object Execute(Context context)
{
throw new NotImplementedException();
}
}
}
| mit |
kanonirov/lanb-client | src/main/java/ru/lanbilling/webservice/wsdl/DelPacketResponse.java | 1709 |
package ru.lanbilling.webservice.wsdl;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ret" type="{http://www.w3.org/2001/XMLSchema}long"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ret"
})
@XmlRootElement(name = "delPacketResponse")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class DelPacketResponse {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected long ret;
/**
* Gets the value of the ret property.
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public long getRet() {
return ret;
}
/**
* Sets the value of the ret property.
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setRet(long value) {
this.ret = value;
}
}
| mit |
aulas-lab/ads-and | SQLiteLab/app/src/main/java/br/unopar/sqlitelab/MainActivity.java | 3315 | package br.unopar.sqlitelab;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
EditText edxID, edxNome;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edxID = (EditText)findViewById(R.id.edxID);
edxNome = (EditText)findViewById(R.id.edxNome);
SQLiteOpenHelper ajudador = new SQLiteOpenHelper(this, "banco.db", null, 1) {
@Override
public void onCreate(SQLiteDatabase db) {
String script =
"CREATE TABLE Cliente (" +
" ID INTEGER PRIMARY KEY, " +
" Nome TEXT NOT NULL, " +
" DtCadastro INTEGER NOT NULL)";
db.execSQL(script);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
};
db = ajudador.getWritableDatabase();
}
public void inserirClick(View v) {
String nome = edxNome.getText().toString();
ContentValues valores = new ContentValues();
valores.put("Nome", nome);
valores.put("DtCadastro", new Date().getTime());
long pk = db.insert("Cliente", null, valores);
edxID.setText(String.valueOf(pk));
}
public void atualizarClick(View v) {
String id = edxID.getText().toString();
String nome = edxNome.getText().toString();
ContentValues valores = new ContentValues();
valores.put("Nome", nome);
String[] whereArgs = new String[] { id };
db.update("Cliente", valores, "ID = ?", whereArgs);
}
public void excluirClick(View v) {
String id = edxID.getText().toString();
String[] whereArgs = new String[] { id };
db.delete("Cliente", "ID = ?", whereArgs);
}
public void recuperarClick(View v) {
String sql = "SELECT Nome FROM Cliente WHERE ID = ?";
String id = edxID.getText().toString();
String[] whereArgs = new String[] { id };
Cursor c = db.rawQuery(sql, whereArgs);
if(c.moveToNext()) {
String nome = c.getString(0);
edxNome.setText(nome);
edxID.setError(null);
} else {
edxID.setError("Cliente não localizado.");
}
}
public void recuperarTodosClientesClick(View v) {
String sql = "SELECT ID, Nome FROM Cliente";
Cursor c = db.rawQuery(sql, null);
StringBuilder nomes = new StringBuilder();
while(c.moveToNext()) {
nomes.append(c.getLong(0) + " - " + c.getString(1) + " \n");
}
new AlertDialog.Builder(this)
.setTitle("Clientes")
.setMessage(nomes)
.setPositiveButton("OK", null)
.create()
.show();
}
}
| mit |
nickjanssen/react-native-swipe-a-lot | example/root.js | 4666 | import React, { PropTypes } from 'react'
import { View, Text, Image } from 'react-native'
import SwipeALot from '../src/index'
const styles = {
wrapper: {
flex: 1,
},
image: {
flex: 1,
// tintColor: 'blue',
// resizeMode: 'cover',
// justifyContent: 'center',
alignItems: 'center',
width: null,
height: null
},
titleBase: {
// bottom: 100,
fontSize: 30,
color: 'white',
backgroundColor: 'transparent',
textShadowColor: 'black',
textShadowOffset: {width:1, height: 1}
}
}
export default class Root extends React.Component {
render() {
return (
<View style={{flex:1}}>
<SwipeALot autoplay={{
enabled: true,
disableOnSwipe: true,
}}
onSetActivePage={(index) => { /* console.log('active', index); */ }}
>
<View style={styles.wrapper}>
<Image
style={styles.image}
source={require('./images/1.jpg')}
>
<Text style={[styles.titleBase, {
top: 30
}]}>Simple Swiping Component.</Text>
</Image>
</View>
<View style={styles.wrapper}>
<Image
style={styles.image}
source={require('./images/2.jpg')}
>
<Text style={[styles.titleBase, {color: 'gold', textShadowColor: 'black', top: 120}]}>Support for iOS{'\n'}and Android.</Text>
</Image>
</View>
<View style={styles.wrapper}>
<Image
style={styles.image}
source={require('./images/3.jpg')}
>
<View style={{
position: 'absolute',
left: 10,
right: 10,
bottom: 0,
top: 30,
alignItems: 'center',
}}>
<Text style={[styles.titleBase, {color: 'rgb(255, 165, 29)', textShadowColor: 'red'}]}>Works with any View!</Text>
</View>
<View style={{
position: 'absolute',
left: 10,
right: 10,
bottom: 40,
top: 0,
justifyContent: 'flex-end',
alignItems: 'center',
}}>
<Text style={[styles.titleBase, {fontSize: 20}]}>Whether your view is positioned absolutely or takes only a portion of the screen.</Text>
</View>
</Image>
</View>
<View style={styles.wrapper}>
<Image
style={styles.image}
source={require('./images/4.jpg')}
>
<View style={{
position: 'absolute',
left: 10,
right: 10,
bottom: 0,
top: 50,
alignItems: 'center',
}}>
<Text style={[styles.titleBase, {color: 'cyan', textShadowColor: 'red'}]}>Any device orientation</Text>
</View>
<View style={{
position: 'absolute',
left: 10,
right: 10,
bottom: 80,
top: 0,
justifyContent: 'flex-end',
alignItems: 'center',
}}>
<Text style={[styles.titleBase, {fontSize: 20}]}>Adjusts itself to landscape/portrait mode when you rotate your phone.</Text>
</View>
</Image>
</View>
<View style={styles.wrapper}>
<Image
style={styles.image}
source={require('./images/5.jpg')}
>
<View style={{
position: 'absolute',
left: 10,
right: 10,
bottom: 0,
top: 50,
alignItems: 'center',
}}>
<Text style={[styles.titleBase, {color: 'pink', textShadowColor: 'red'}]}>Includes autoplay!</Text>
</View>
<View style={{
position: 'absolute',
left: 10,
right: 10,
bottom: 80,
top: 0,
justifyContent: 'flex-end',
alignItems: 'center',
}}>
<Text style={[styles.titleBase, {fontSize: 20}]}>Automatically goes to the next slide after a set amount of seconds.</Text>
</View>
</Image>
</View>
</SwipeALot>
</View>
)
}
}
| mit |
GaryCas/Vermello | src/VM/CoreBundle/Tests/Controller/DefaultControllerTest.php | 396 | <?php
namespace VM\CoreBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/hello/Fabien');
$this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
}
}
| mit |
yannickcr/pw2014-isomorphic | tasks/start.js | 171 | 'use strict';
module.exports = function(grunt) {
grunt.registerTask('start', 'Start the server and watch for file change', ['browserify:dist', 'concurrent:start']);
};
| mit |
wavebeem/battenberg | app/src/js/paginator.js | 714 | function Paginator(pageSize, currentPage, data) {
function pageCount() {
return Math.ceil(data.length / pageSize);
}
function isOnFirstPage() {
return currentPage === 1;
}
function isOnLastPage() {
return currentPage === pageCount();
}
function goToPrevPage() {
currentPage = Math.max(currentPage - 1, 0);
}
function goToNextPage() {
currentPage = Math.min(currentPage + 1, pageCount());
}
function currentPageData() {
const i = currentPage - 1;
return data.slice(i * pageSize, (i + 1) * pageSize);
}
return {
pageCount,
isOnFirstPage,
isOnLastPage,
goToPrevPage,
goToNextPage,
currentPageData
};
}
module.exports = Paginator;
| mit |
strillo/JEFF | JEFF.Portal/Startup.cs | 478 | using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(JEFF.Portal.Startup))]
namespace JEFF.Portal
{
/// <summary>
/// Startup
/// </summary>
public partial class Startup
{
/// <summary>
/// Configures the specified application.
/// </summary>
/// <param name="app">The application.</param>
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| mit |
MomentumCMS/momentum_cms | spec/models/momentum_cms/entry_spec.rb | 83 | require_relative '../../rails_helper'
describe MomentumCms::Entry, 'Model' do
end
| mit |
coreation/Cachet | app/views/dashboard/incidents/add.blade.php | 5762 | @extends('layout.dashboard')
@section('content')
<div class="header">
<div class="sidebar-toggler visible-xs">
<i class="icon ion-navicon"></i>
</div>
<span class="uppercase">
<i class="icon icon ion-android-alert"></i> {{ trans('dashboard.incidents.incidents') }}
</span>
> <small>{{ trans('dashboard.incidents.add.title') }}</small>
</div>
<div class="content-wrapper">
<div class="row">
<div class="col-md-12">
@include('partials.dashboard.errors')
{{ Form::open(['name' => 'IncidentForm', 'class' => 'form-vertical', 'role' => 'form']) }}
<fieldset>
@if($incidentTemplates->count() > 0)
<div class="form-group">
<label for="incident-template">{{ trans('forms.incidents.templates.template') }}</label>
<select class="form-control" name="template">
<option selected></option>
@foreach($incidentTemplates as $tpl)
<option value="{{ $tpl->slug }}">{{ $tpl->name }}</option>
@endforeach
</select>
</div>
@endif
<div class="form-group">
<label for="incident-name">{{ trans('forms.incidents.name') }}</label>
<input type="text" class="form-control" name="incident[name]" id="incident-name" required value="{{ Input::old('incident.name') }}">
</div>
<div class="form-group">
<label for="incident-name">{{ trans('forms.incidents.status') }}</label><br>
<label class="radio-inline">
<input type="radio" name="incident[status]" value="1">
<i class="icon ion-flag"></i>
{{ trans('cachet.incidents.status')[1] }}
</label>
<label class="radio-inline">
<input type="radio" name="incident[status]" value="2">
<i class="icon ion-alert-circled"></i>
{{ trans('cachet.incidents.status')[2] }}
</label>
<label class="radio-inline">
<input type="radio" name="incident[status]" value="3">
<i class="icon ion-eye"></i>
{{ trans('cachet.incidents.status')[3] }}
</label>
<label class="radio-inline">
<input type="radio" name="incident[status]" value="4">
<i class="icon ion-checkmark"></i>
{{ trans('cachet.incidents.status')[4] }}
</label>
</div>
@if($components->count() > 0)
<div class="form-group">
<label>{{ trans('forms.incidents.component') }}</label>
<select name='incident[component_id]' class='form-control'>
<option value='0' selected></option>
@foreach($components as $component)
<option value='{{ $component->id }}'>{{ $component->name }}</option>
@endforeach
</select>
<span class='help-block'>{{ trans('forms.optional') }}</span>
</div>
@endif
<div class="form-group hidden" id='component-status'>
<div class="well">
<div class="radio-items">
@foreach(trans('cachet.components.status') as $statusID => $status)
<div class="radio-inline">
<label>
<input type="radio" name="incident[component_status]" value="{{ $statusID }}" >
{{ $status }}
</label>
</div>
@endforeach
</div>
</div>
</div>
<div class="form-group">
<label>{{ trans('forms.incidents.message') }}</label>
<div class='markdown-control'>
<textarea name="incident[message]" class="form-control" rows="5" required>{{ Input::old('incident.message') }}</textarea>
</div>
</div>
</fieldset>
<input type="hidden" name="incident[user_id]" value="{{ Auth::user()->id }}">
<div class='form-group'>
<div class='btn-group'>
<button type="submit" class="btn btn-success">{{ trans('forms.add') }}</button>
<a class="btn btn-default" href="{{ route('dashboard.incidents') }}">{{ trans('forms.cancel') }}</a>
</div>
</div>
{{ Form::close() }}
</div>
</div>
</div>
@stop
| mit |
dynamicform/dynamicform-react-client | src/components/elements/TimePicker.js | 3553 | /**
* Created by KangYe on 2017/4/24.
*/
import React from 'react';
import {connect} from 'react-redux';
import moment from 'moment';
import {TimePicker, Form} from 'antd';
import _ from 'lodash';
import {initFormData,initDynamicFormData ,updateFormData,updateDynamicFormData} from '../../actions/formAction';
import {IsNullorUndefined, FormItemLayout, MapStateToProps,getIsCascadeElement} from '../../utility/common';
import {timePickerProType} from '../../utility/propTypes';
import Base from './Base';
const FormItem = Form.Item;
export class QTimePicker extends Base {
constructor(props) {
super(props);
this.state = {
...props.definition
};
this.handleOnChange = this.handleOnChange.bind(this);
}
componentWillMount() {
this.state = this.props.definition || this.state;
if(this.getValue(this.props.formData)){
this.state.defaultvalue =moment(this.getValue(this.props.formData), IsNullorUndefined(this.state.format) ? 'kk:mm:ss' : this.state.format);
}else{
if(this.props.definition.defaultvalue){
this.state.defaultvalue =moment(this.props.definition.defaultvalue, IsNullorUndefined(this.state.format) ? 'kk:mm:ss' : this.state.format);
}else{
this.state.defaultvalue =null;
}
}
if (this.props.isNewForm) {
const value = this.getValue(this.props.formData);
if(this.props.isDynamic) {
const dataPosition = this.props.dataPosition;
this.props.dispatch(initDynamicFormData(this.objectPath, value, dataPosition));
} else {
this.props.dispatch(initFormData(this.objectPath, value));
}
}
if(this.props.isDynamic) {
const dataPosition = this.props.dataPosition;
this.props.dispatch(initDynamicFormData(this.objectPath, null, dataPosition));
}
}
shouldComponentUpdate(nextProps, nextState) {
const currentValue = this.getValue(this.props.formData);
const nextValue = this.getValue(nextProps.formData);
let isCascadElement=getIsCascadeElement(nextProps.formData,this.props.formData,this.state.conditionMap);
//only render when value is changed or form is submitting
return currentValue !== nextValue || nextProps.isSubmitting ||isCascadElement ;
}
handleOnChange(date, dateString) {
const value = dateString;
this.props.dispatch(updateFormData(this.objectPath, value));
}
render() {
const {getFieldDecorator} = this.props.form;
const key = this.DynamicKey;
return (
<FormItem {...FormItemLayout()} style={{display:this.isHidden}} label={this.state.label}>
{getFieldDecorator(key, {
rules: this.Rules,
initialValue: this.state.defaultvalue === '' ? null : this.state.defaultvalue
})(<TimePicker
placeholder={this.state.placeholder}
disabled={this.isDisabled}
use12Hours={this.state.use12hours}
format={IsNullorUndefined(this.state.format) ? 'HH:mm:ss' : this.state.format}
onChange={(date, dateString) => this.handleOnChange(date, dateString)}
/>
)}
</FormItem>
);
}
}
QTimePicker.propTypes = timePickerProType;
export default connect(MapStateToProps)(QTimePicker); | mit |
kakakaya/tweetsave-python | setup.py | 835 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author: kakakaya, Date: Sat Feb 4 18:59:06 2017
from setuptools import setup, find_packages
setup(
name="tweetsave",
version="1.1.0",
description='A Python3 library for https://tweetsave.com',
author='kakakaya',
author_email="kakakaya@gmail.com",
url="https://github.com/kakakaya/tweetsave-python",
license="MIT",
packages=find_packages(),
test_suite="nose.collector",
entry_points={
'console_scripts': 'tweetsave = tweetsave.cli:cli'
},
install_requires=[
'requests',
'click'
],
classifiers=[
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3 :: Only",
]
)
| mit |
adaltas/node-nikita | packages/core/lib/actions/fs/base/stat.js | 5501 | // Generated by CoffeeScript 2.6.1
// # `nikita.fs.base.stat`
// Retrieve file information.
// ## File information
// The `mode` parameter indicates the file type. For conveniency, the
// `@nikitajs/core/lib/utils/stats` module provide functions to check each
// possible file types.
// ## Example
// Check if target is a file:
// ```js
// utils = require('@nikitajs/core/lib/utils')
// const {stats} = await nikita
// .file.touch("/tmp/a_file")
// .fs.base.stat("/tmp/a_file")
// assert(utils.stats.isFile(stats.mode) === true)
// ```
// Check if target is a directory:
// ```js
// utils = require('@nikitajs/core/lib/utils')
// const {stats} = await nikita
// .fs.base.mkdir("/tmp/a_file")
// .fs.base.stat("/tmp/a_file")
// assert(utils.stats.isDirectory(stats.mode) === true)
// ```
// ## Note
// The `stat` command return an empty stdout in some circounstances like uploading
// a large file with `file.download`, thus the activation of `retry` and `sleep`
// confguration properties.
// ## Schema definitions
// The parameters include a subset as the one of the Node.js native
// [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object.
// TODO: we shall be able to reference this as a `$ref` once schema does apply to
// returned values.
var definitions, definitions_output, errors, escapeshellarg, handler, utils;
definitions_output = {
type: 'object',
properties: {
'stats': {
type: 'object',
properties: {
'mode': {
$ref: 'module://@nikitajs/core/lib/actions/fs/base/chmod#/definitions/config/properties/mode'
},
'uid': {
type: 'integer',
description: `The numeric user identifier of the user that owns the file
(POSIX).`
},
'gid': {
type: 'integer',
description: `The numeric group identifier of the group that owns the file
(POSIX).`
},
'size': {
type: 'integer',
description: `The size of the file in bytes.`
},
'atime': {
type: 'integer',
description: `The timestamp indicating the last time this file was accessed
expressed in milliseconds since the POSIX Epoch.`
},
'mtime': {
type: 'integer',
description: `The timestamp indicating the last time this file was modified
expressed in milliseconds since the POSIX Epoch.`
}
}
}
}
};
definitions = {
config: {
type: 'object',
properties: {
'dereference': {
type: 'boolean',
description: `Follow links, similar to \`lstat\`, default is "true", just like in the
native Node.js \`fs.stat\` function, use \`nikita.fs.lstat\` to retrive
link information.`
},
'target': {
oneOf: [
{
type: 'string'
},
{
instanceof: 'Buffer'
}
],
description: `Location of the file to analyse`
}
},
required: ['target']
}
};
// ## Handler
handler = async function({config}) {
var atime, dereference, err, gid, mtime, rawmodehex, size, stdout, uid;
// Normalize configuration
if (config.dereference == null) {
config.dereference = true;
}
dereference = config.dereference ? '-L' : '';
try {
({stdout} = (await this.execute({
command: `[ ! -e ${config.target} ] && exit 3
if [ -d /private ]; then
stat ${dereference} -f '%Xp|%u|%g|%z|%a|%m' ${escapeshellarg(config.target)} # MacOS
else
stat ${dereference} -c '%f|%u|%g|%s|%X|%Y' ${escapeshellarg(config.target)} # Linux
fi`,
trim: true
})));
[rawmodehex, uid, gid, size, atime, mtime] = stdout.split('|');
return {
stats: {
mode: parseInt(rawmodehex, 16), // dont know why `rawmodehex` was prefixed by `"0xa1ed"`
uid: parseInt(uid, 10),
gid: parseInt(gid, 10),
size: parseInt(size, 10),
atime: parseInt(atime, 10),
mtime: parseInt(mtime, 10)
}
};
} catch (error) {
err = error;
if (err.exit_code === 3) {
err = errors.NIKITA_FS_STAT_TARGET_ENOENT({
config: config,
err: err
});
}
throw err;
}
};
// ## Exports
module.exports = {
handler: handler,
metadata: {
argument_to_config: 'target',
log: false,
raw_output: true,
definitions: definitions
},
definitions_output: definitions_output
};
// ## Errors
errors = {
NIKITA_FS_STAT_TARGET_ENOENT: function({config, err}) {
return utils.error('NIKITA_FS_STAT_TARGET_ENOENT', ['failed to stat the target, no file exists for target,', `got ${JSON.stringify(config.target)}`], {
exit_code: err.exit_code,
errno: -2,
syscall: 'rmdir',
path: config.target
});
}
};
// ## Dependencies
utils = require('../../../utils');
({escapeshellarg} = utils.string);
// ## Stat implementation
// On Linux, the format argument is '-c'. The following codes are used:
// - `%f` The raw mode in hexadecimal.
// - `%u` The user ID of owner.
// - `%g` The group ID of owner.
// - `%s` The block size of file.
// - `%X` The time of last access, seconds since Epoch.
// - `%y` The time of last modification, human-readable.
// On MacOS, the format argument is '-f'. The following codes are used:
// - `%Xp` File type and permissions in hexadecimal.
// - `%u` The user ID of owner.
// - `%g` The group ID of owner.
// - `%z` The size of file in bytes.
// - `%a` The time file was last accessed.
// - `%m` The time file was last modified.
| mit |
gfmio/Whitespace | src/js/whitespace.dist.js | 376 | //
// Whitespace JS browser component library
//
var whitespace = require('./whitespace.lib').whitespace;
if (typeof window != "undefined") {
// Export as global browser variable
window.whitespace = whitespace;
$().ready(function(){
// $("input[type=color]").spectrum({});
$('input[type="range"]').rangeslider({});
$("form").validate({});
});
}
| mit |
stl-florida/casestudy-riskmap | node_modules/aurelia-dependency-injection/dist/native-modules/aurelia-dependency-injection.js | 21199 | var _dec, _class, _dec2, _class3, _dec3, _class5, _dec4, _class7, _dec5, _class9, _dec6, _class11, _dec7, _class13, _classInvokers;
import { protocol, metadata } from 'aurelia-metadata';
import { AggregateError } from 'aurelia-pal';
export var resolver = protocol.create('aurelia:resolver', function (target) {
if (!(typeof target.get === 'function')) {
return 'Resolvers must implement: get(container: Container, key: any): any';
}
return true;
});
export var Lazy = (_dec = resolver(), _dec(_class = function () {
function Lazy(key) {
this._key = key;
}
Lazy.prototype.get = function get(container) {
var _this = this;
return function () {
return container.get(_this._key);
};
};
Lazy.of = function of(key) {
return new Lazy(key);
};
return Lazy;
}()) || _class);
export var All = (_dec2 = resolver(), _dec2(_class3 = function () {
function All(key) {
this._key = key;
}
All.prototype.get = function get(container) {
return container.getAll(this._key);
};
All.of = function of(key) {
return new All(key);
};
return All;
}()) || _class3);
export var Optional = (_dec3 = resolver(), _dec3(_class5 = function () {
function Optional(key) {
var checkParent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
this._key = key;
this._checkParent = checkParent;
}
Optional.prototype.get = function get(container) {
if (container.hasResolver(this._key, this._checkParent)) {
return container.get(this._key);
}
return null;
};
Optional.of = function of(key) {
var checkParent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
return new Optional(key, checkParent);
};
return Optional;
}()) || _class5);
export var Parent = (_dec4 = resolver(), _dec4(_class7 = function () {
function Parent(key) {
this._key = key;
}
Parent.prototype.get = function get(container) {
return container.parent ? container.parent.get(this._key) : null;
};
Parent.of = function of(key) {
return new Parent(key);
};
return Parent;
}()) || _class7);
export var StrategyResolver = (_dec5 = resolver(), _dec5(_class9 = function () {
function StrategyResolver(strategy, state) {
this.strategy = strategy;
this.state = state;
}
StrategyResolver.prototype.get = function get(container, key) {
switch (this.strategy) {
case 0:
return this.state;
case 1:
var singleton = container.invoke(this.state);
this.state = singleton;
this.strategy = 0;
return singleton;
case 2:
return container.invoke(this.state);
case 3:
return this.state(container, key, this);
case 4:
return this.state[0].get(container, key);
case 5:
return container.get(this.state);
default:
throw new Error('Invalid strategy: ' + this.strategy);
}
};
return StrategyResolver;
}()) || _class9);
export var Factory = (_dec6 = resolver(), _dec6(_class11 = function () {
function Factory(key) {
this._key = key;
}
Factory.prototype.get = function get(container) {
var _this2 = this;
return function () {
for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
rest[_key] = arguments[_key];
}
return container.invoke(_this2._key, rest);
};
};
Factory.of = function of(key) {
return new Factory(key);
};
return Factory;
}()) || _class11);
export var NewInstance = (_dec7 = resolver(), _dec7(_class13 = function () {
function NewInstance(key) {
this.key = key;
this.asKey = key;
for (var _len2 = arguments.length, dynamicDependencies = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
dynamicDependencies[_key2 - 1] = arguments[_key2];
}
this.dynamicDependencies = dynamicDependencies;
}
NewInstance.prototype.get = function get(container) {
var dynamicDependencies = this.dynamicDependencies.length > 0 ? this.dynamicDependencies.map(function (dependency) {
return dependency['protocol:aurelia:resolver'] ? dependency.get(container) : container.get(dependency);
}) : undefined;
var instance = container.invoke(this.key, dynamicDependencies);
container.registerInstance(this.asKey, instance);
return instance;
};
NewInstance.prototype.as = function as(key) {
this.asKey = key;
return this;
};
NewInstance.of = function of(key) {
for (var _len3 = arguments.length, dynamicDependencies = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
dynamicDependencies[_key3 - 1] = arguments[_key3];
}
return new (Function.prototype.bind.apply(NewInstance, [null].concat([key], dynamicDependencies)))();
};
return NewInstance;
}()) || _class13);
export function getDecoratorDependencies(target, name) {
var dependencies = target.inject;
if (typeof dependencies === 'function') {
throw new Error('Decorator ' + name + ' cannot be used with "inject()". Please use an array instead.');
}
if (!dependencies) {
dependencies = metadata.getOwn(metadata.paramTypes, target).slice();
target.inject = dependencies;
}
return dependencies;
}
export function lazy(keyValue) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'lazy');
params[index] = Lazy.of(keyValue);
};
}
export function all(keyValue) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'all');
params[index] = All.of(keyValue);
};
}
export function optional() {
var checkParentOrTarget = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
var deco = function deco(checkParent) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'optional');
params[index] = Optional.of(params[index], checkParent);
};
};
if (typeof checkParentOrTarget === 'boolean') {
return deco(checkParentOrTarget);
}
return deco(true);
}
export function parent(target, key, index) {
var params = getDecoratorDependencies(target, 'parent');
params[index] = Parent.of(params[index]);
}
export function factory(keyValue, asValue) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'factory');
var factory = Factory.of(keyValue);
params[index] = asValue ? factory.as(asValue) : factory;
};
}
export function newInstance(asKeyOrTarget) {
for (var _len4 = arguments.length, dynamicDependencies = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
dynamicDependencies[_key4 - 1] = arguments[_key4];
}
var deco = function deco(asKey) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'newInstance');
params[index] = NewInstance.of.apply(NewInstance, [params[index]].concat(dynamicDependencies));
if (!!asKey) {
params[index].as(asKey);
}
};
};
if (arguments.length >= 1) {
return deco(asKeyOrTarget);
}
return deco();
}
export function invoker(value) {
return function (target) {
metadata.define(metadata.invoker, value, target);
};
}
export function invokeAsFactory(potentialTarget) {
var deco = function deco(target) {
metadata.define(metadata.invoker, FactoryInvoker.instance, target);
};
return potentialTarget ? deco(potentialTarget) : deco;
}
export var FactoryInvoker = function () {
function FactoryInvoker() {
}
FactoryInvoker.prototype.invoke = function invoke(container, fn, dependencies) {
var i = dependencies.length;
var args = new Array(i);
while (i--) {
args[i] = container.get(dependencies[i]);
}
return fn.apply(undefined, args);
};
FactoryInvoker.prototype.invokeWithDynamicDependencies = function invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) {
var i = staticDependencies.length;
var args = new Array(i);
while (i--) {
args[i] = container.get(staticDependencies[i]);
}
if (dynamicDependencies !== undefined) {
args = args.concat(dynamicDependencies);
}
return fn.apply(undefined, args);
};
return FactoryInvoker;
}();
FactoryInvoker.instance = new FactoryInvoker();
export function registration(value) {
return function (target) {
metadata.define(metadata.registration, value, target);
};
}
export function transient(key) {
return registration(new TransientRegistration(key));
}
export function singleton(keyOrRegisterInChild) {
var registerInChild = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
return registration(new SingletonRegistration(keyOrRegisterInChild, registerInChild));
}
export var TransientRegistration = function () {
function TransientRegistration(key) {
this._key = key;
}
TransientRegistration.prototype.registerResolver = function registerResolver(container, key, fn) {
var existingResolver = container.getResolver(this._key || key);
return existingResolver === undefined ? container.registerTransient(this._key || key, fn) : existingResolver;
};
return TransientRegistration;
}();
export var SingletonRegistration = function () {
function SingletonRegistration(keyOrRegisterInChild) {
var registerInChild = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (typeof keyOrRegisterInChild === 'boolean') {
this._registerInChild = keyOrRegisterInChild;
} else {
this._key = keyOrRegisterInChild;
this._registerInChild = registerInChild;
}
}
SingletonRegistration.prototype.registerResolver = function registerResolver(container, key, fn) {
var targetContainer = this._registerInChild ? container : container.root;
var existingResolver = targetContainer.getResolver(this._key || key);
return existingResolver === undefined ? targetContainer.registerSingleton(this._key || key, fn) : existingResolver;
};
return SingletonRegistration;
}();
function validateKey(key) {
if (key === null || key === undefined) {
throw new Error('key/value cannot be null or undefined. Are you trying to inject/register something that doesn\'t exist with DI?');
}
}
export var _emptyParameters = Object.freeze([]);
metadata.registration = 'aurelia:registration';
metadata.invoker = 'aurelia:invoker';
var resolverDecorates = resolver.decorates;
export var InvocationHandler = function () {
function InvocationHandler(fn, invoker, dependencies) {
this.fn = fn;
this.invoker = invoker;
this.dependencies = dependencies;
}
InvocationHandler.prototype.invoke = function invoke(container, dynamicDependencies) {
return dynamicDependencies !== undefined ? this.invoker.invokeWithDynamicDependencies(container, this.fn, this.dependencies, dynamicDependencies) : this.invoker.invoke(container, this.fn, this.dependencies);
};
return InvocationHandler;
}();
function invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) {
var i = staticDependencies.length;
var args = new Array(i);
while (i--) {
args[i] = container.get(staticDependencies[i]);
}
if (dynamicDependencies !== undefined) {
args = args.concat(dynamicDependencies);
}
return Reflect.construct(fn, args);
}
var classInvokers = (_classInvokers = {}, _classInvokers[0] = {
invoke: function invoke(container, Type) {
return new Type();
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[1] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[2] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]), container.get(deps[1]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[3] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[4] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[5] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3]), container.get(deps[4]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers.fallback = {
invoke: invokeWithDynamicDependencies,
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers);
function getDependencies(f) {
if (!f.hasOwnProperty('inject')) {
return [];
}
if (typeof f.inject === 'function') {
return f.inject();
}
return f.inject;
}
export var Container = function () {
function Container(configuration) {
if (configuration === undefined) {
configuration = {};
}
this._configuration = configuration;
this._onHandlerCreated = configuration.onHandlerCreated;
this._handlers = configuration.handlers || (configuration.handlers = new Map());
this._resolvers = new Map();
this.root = this;
this.parent = null;
}
Container.prototype.makeGlobal = function makeGlobal() {
Container.instance = this;
return this;
};
Container.prototype.setHandlerCreatedCallback = function setHandlerCreatedCallback(onHandlerCreated) {
this._onHandlerCreated = onHandlerCreated;
this._configuration.onHandlerCreated = onHandlerCreated;
};
Container.prototype.registerInstance = function registerInstance(key, instance) {
return this.registerResolver(key, new StrategyResolver(0, instance === undefined ? key : instance));
};
Container.prototype.registerSingleton = function registerSingleton(key, fn) {
return this.registerResolver(key, new StrategyResolver(1, fn === undefined ? key : fn));
};
Container.prototype.registerTransient = function registerTransient(key, fn) {
return this.registerResolver(key, new StrategyResolver(2, fn === undefined ? key : fn));
};
Container.prototype.registerHandler = function registerHandler(key, handler) {
return this.registerResolver(key, new StrategyResolver(3, handler));
};
Container.prototype.registerAlias = function registerAlias(originalKey, aliasKey) {
return this.registerResolver(aliasKey, new StrategyResolver(5, originalKey));
};
Container.prototype.registerResolver = function registerResolver(key, resolver) {
validateKey(key);
var allResolvers = this._resolvers;
var result = allResolvers.get(key);
if (result === undefined) {
allResolvers.set(key, resolver);
} else if (result.strategy === 4) {
result.state.push(resolver);
} else {
allResolvers.set(key, new StrategyResolver(4, [result, resolver]));
}
return resolver;
};
Container.prototype.autoRegister = function autoRegister(key, fn) {
fn = fn === undefined ? key : fn;
if (typeof fn === 'function') {
var _registration = metadata.get(metadata.registration, fn);
if (_registration === undefined) {
return this.registerResolver(key, new StrategyResolver(1, fn));
}
return _registration.registerResolver(this, key, fn);
}
return this.registerResolver(key, new StrategyResolver(0, fn));
};
Container.prototype.autoRegisterAll = function autoRegisterAll(fns) {
var i = fns.length;
while (i--) {
this.autoRegister(fns[i]);
}
};
Container.prototype.unregister = function unregister(key) {
this._resolvers.delete(key);
};
Container.prototype.hasResolver = function hasResolver(key) {
var checkParent = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
validateKey(key);
return this._resolvers.has(key) || checkParent && this.parent !== null && this.parent.hasResolver(key, checkParent);
};
Container.prototype.getResolver = function getResolver(key) {
return this._resolvers.get(key);
};
Container.prototype.get = function get(key) {
validateKey(key);
if (key === Container) {
return this;
}
if (resolverDecorates(key)) {
return key.get(this, key);
}
var resolver = this._resolvers.get(key);
if (resolver === undefined) {
if (this.parent === null) {
return this.autoRegister(key).get(this, key);
}
var _registration2 = metadata.get(metadata.registration, key);
if (_registration2 === undefined) {
return this.parent._get(key);
}
return _registration2.registerResolver(this, key, key).get(this, key);
}
return resolver.get(this, key);
};
Container.prototype._get = function _get(key) {
var resolver = this._resolvers.get(key);
if (resolver === undefined) {
if (this.parent === null) {
return this.autoRegister(key).get(this, key);
}
return this.parent._get(key);
}
return resolver.get(this, key);
};
Container.prototype.getAll = function getAll(key) {
validateKey(key);
var resolver = this._resolvers.get(key);
if (resolver === undefined) {
if (this.parent === null) {
return _emptyParameters;
}
return this.parent.getAll(key);
}
if (resolver.strategy === 4) {
var state = resolver.state;
var i = state.length;
var results = new Array(i);
while (i--) {
results[i] = state[i].get(this, key);
}
return results;
}
return [resolver.get(this, key)];
};
Container.prototype.createChild = function createChild() {
var child = new Container(this._configuration);
child.root = this.root;
child.parent = this;
return child;
};
Container.prototype.invoke = function invoke(fn, dynamicDependencies) {
try {
var _handler = this._handlers.get(fn);
if (_handler === undefined) {
_handler = this._createInvocationHandler(fn);
this._handlers.set(fn, _handler);
}
return _handler.invoke(this, dynamicDependencies);
} catch (e) {
throw new AggregateError('Error invoking ' + fn.name + '. Check the inner error for details.', e, true);
}
};
Container.prototype._createInvocationHandler = function _createInvocationHandler(fn) {
var dependencies = void 0;
if (fn.inject === undefined) {
dependencies = metadata.getOwn(metadata.paramTypes, fn) || _emptyParameters;
} else {
dependencies = [];
var ctor = fn;
while (typeof ctor === 'function') {
var _dependencies;
(_dependencies = dependencies).push.apply(_dependencies, getDependencies(ctor));
ctor = Object.getPrototypeOf(ctor);
}
}
var invoker = metadata.getOwn(metadata.invoker, fn) || classInvokers[dependencies.length] || classInvokers.fallback;
var handler = new InvocationHandler(fn, invoker, dependencies);
return this._onHandlerCreated !== undefined ? this._onHandlerCreated(handler) : handler;
};
return Container;
}();
export function autoinject(potentialTarget) {
var deco = function deco(target) {
var previousInject = target.inject ? target.inject.slice() : null;
var autoInject = metadata.getOwn(metadata.paramTypes, target) || _emptyParameters;
if (!previousInject) {
target.inject = autoInject;
} else {
for (var i = 0; i < autoInject.length; i++) {
if (previousInject[i] && previousInject[i] !== autoInject[i]) {
var prevIndex = previousInject.indexOf(autoInject[i]);
if (prevIndex > -1) {
previousInject.splice(prevIndex, 1);
}
previousInject.splice(prevIndex > -1 && prevIndex < i ? i - 1 : i, 0, autoInject[i]);
} else if (!previousInject[i]) {
previousInject[i] = autoInject[i];
}
}
target.inject = previousInject;
}
};
return potentialTarget ? deco(potentialTarget) : deco;
}
export function inject() {
for (var _len5 = arguments.length, rest = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
rest[_key5] = arguments[_key5];
}
return function (target, key, descriptor) {
if (typeof descriptor === 'number' && rest.length === 1) {
var params = target.inject;
if (typeof params === 'function') {
throw new Error('Decorator inject cannot be used with "inject()". Please use an array instead.');
}
if (!params) {
params = metadata.getOwn(metadata.paramTypes, target).slice();
target.inject = params;
}
params[descriptor] = rest[0];
return;
}
if (descriptor) {
var _fn = descriptor.value;
_fn.inject = rest;
} else {
target.inject = rest;
}
};
} | mit |
cryptoquick/evweb | Version2/ShipMovement.js | 1727 | // Define global variables
var MoveX = 0;
var MoveY = 0;
var SpeedX = 0;
var SpeedY = 0;
var otherShipX;
// curX = document.getElementById('PlanetLayer').style.top;
// curX = curX.substring(0, curX.length - 2);
// curY = document.getElementById('PlanetLayer').style.left;
// curY = curY.substring(0, curY.length - 2);
// curY = parseInt(curY);
var curX = 0;
var curY = 0;
var Friction = .997;
// Move objects to simulate movement of the ship.
function ShipMove() {
MyShip.checkShow();
if (MyShip.checkShow() == 1) {
ShipAngle = MyShip.getShipDirection() * 15;
MoveX = MyShip.getShipAccel() * Math.sin((ShipAngle*Math.PI)/180) * -1;
MoveY = MyShip.getShipAccel() * Math.cos((ShipAngle*Math.PI)/180);
SpeedX *= Friction;
SpeedY *= Friction;
curX += SpeedX;
curY += SpeedY;
MyX = (curX * -1) + ShipX;
MyY = (curY * -1) + ShipY;
var objPlanet = document.getElementById('PlanetLayer');
objPlanet.style.top = curY;
objPlanet.style.left = curX;
var objShips = document.getElementById('ShipLayer');
objShips.style.top = curY;
objShips.style.left = curX;
}
var objInfo = document.getElementById('Info');
objInfo.innerHTML = "MyY = " + MyY + " OtherShipX = " + otherShipX
for (var i=0, o; o=ShipsInSystem[i]; i++) {
intLeft = GetShipValue(o, 14);
intTop = GetShipValue(o, 15);
otherShipX = intTop
document.getElementById('Ship' + o).style.top = intTop;
document.getElementById('Ship' + o).style.left = intLeft;
}
window.setTimeout('ShipMove();', 50);
}
function setMyLocation() {
MyShip.setLocation(MyX,MyY);
window.setTimeout('setMyLocation();', 500);
}
| mit |
kaelzhang/switch | plugins/cleaner.js | 2952 | 'use strict';
/**
* temporarily remove unnecessary items away from the container
*/
var _ = require('underscore');
var METHODS_OVERRIDDEN = {
_cleanItems: function() {
var self = this,
activeIndex = self.activeIndex,
rightIndexOfStage = activeIndex + self.get('stage') - 1,
testDistance = Cleaner.TEST_DISTANCE * self.get('move'),
/**
Abbr:
t: testDistance,
a: activeIndex, b: rightIndexOfStage
l: leftTestIndex, L: cleanLeft, r: rightTestIndex, R: cleanRight,
rl: removeLeft, rr: removeRight
Suppose:
plugin: 'endless'
length: 100
////////////////////////////////////////////////////////////////////////////////////////
| t | stage | t |
_________
a b
| rl | | rr |
_______________________________________________
L l r R
|
calculate -9 0 4
this._limit 91 0 4 // so before we calculate removeLeft, never use this._limit,
// preventing logic error during calculating circlewize index
////////////////////////////////////////////////////////////////////////////////////////
*/
rightTestIndex = rightIndexOfStage + testDistance,
leftTestIndex = activeIndex - testDistance,
removeLeft = leftTestIndex - self.cleanLeft,
removeRight = self.cleanRight - rightTestIndex;
if (removeLeft > 0) {
self._removeItems(self.cleanLeft - 1, removeLeft);
self.cleanLeft = leftTestIndex;
}
if (removeRight > 0) {
self._removeItems(rightTestIndex, removeRight);
self.cleanRight = rightTestIndex;
}
},
/**
* @param {number} start
* @param {number} amount always positive
* @param {boolean} toAdd
*/
_removeItems: function(start, amount, toAdd) {
var self = this,
item, index;
while (amount) {
// use
index = self._limit(start + amount);
item = self._getItem(index);
if (item) {
toAdd ? self._plantItem(index) : item.dispose();
}
--amount;
}
}
};
var Cleaner = {
name: 'cleaner',
TEST_DISTANCE: 1,
ATTRS: {
// times of move
// - auto manage removing infomation
// potentialMove: 1
},
init: function(self) {
var EVENTS = self.get('EVENTS');
self.on(EVENTS.AFTER_INIT, function() {
var self = this,
activeIndex = self.activeIndex;
_.extend(self, METHODS_OVERRIDDEN);
self.cleanLeft = activeIndex;
self.cleanRight = activeIndex + self.get('stage') - 1;
});
// self.on(EVENTS.COMPLETE_SWITCH, self._cleanItems);
self.on(EVENTS.COMPLETE_SWITCH, function() {
self._cleanItems();
});
}
};
module.exports = Cleaner; | mit |
DJTobias/JetsonTX1 | gst_cam_test.py | 1173 | # copied from https://gist.github.com/jampekka/ec4a3f3a3748fd2a281d/
import numpy as np
import cv2
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst
def gst_to_opencv(gst_buffer):
return np.ndarray((480,640,3), buffer=gst_buffer.extract_dup(0, gst_buffer.get_size()), dtype=np.uint8)
Gst.init(None)
pipe = Gst.parse_launch("""v4l2src device=/dev/video1 ! video/x-raw, width=640, height=480,format=(string)BGR ! appsink sync=false max-buffers=2 drop=true name=sink emit-signals=true""")
pipe2 = Gst.parse_launch("""v4l2src device=/dev/video2 ! video/x-raw, width=640, height=480,format=(string)BGR ! appsink sync=false max-buffers=2 drop=true name=sink emit-signals=true""")
sink = pipe.get_by_name('sink')
sink2 = pipe2.get_by_name('sink')
pipe.set_state(Gst.State.PLAYING)
pipe2.set_state(Gst.State.PLAYING)
while True:
sample = sink.emit('pull-sample')
sample2 = sink2.emit('pull-sample')
img = gst_to_opencv(sample.get_buffer())
img2 = gst_to_opencv(sample2.get_buffer())
cv2.imshow('frame',img)
cv2.imshow('frame2',img2)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
| mit |
Felorati/Thesis | code/Tests/Multiverse/multiverse-core/src/test/java/org/multiverse/commitbarriers/CountDownCommitBarrier_joinCommitUninterruptiblyWithTransactionTest.java | 7108 | package org.multiverse.commitbarriers;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.multiverse.TestThread;
import org.multiverse.api.Txn;
import org.multiverse.api.TxnStatus;
import org.multiverse.api.callables.TxnVoidCallable;
import org.multiverse.api.exceptions.DeadTxnException;
import org.multiverse.api.references.TxnInteger;
import org.multiverse.stms.gamma.GammaStm;
import org.multiverse.stms.gamma.transactionalobjects.GammaTxnInteger;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.multiverse.TestUtils.*;
import static org.multiverse.api.TxnThreadLocal.clearThreadLocalTxn;
public class CountDownCommitBarrier_joinCommitUninterruptiblyWithTransactionTest {
private CountDownCommitBarrier barrier;
private GammaStm stm;
@Before
public void setUp() {
stm = new GammaStm();
clearThreadLocalTxn();
clearCurrentThreadInterruptedStatus();
}
@After
public void tearDown() {
clearCurrentThreadInterruptedStatus();
}
@Test
public void whenTransactionNull_thenFailWithNullPointerException() {
barrier = new CountDownCommitBarrier(1);
try {
barrier.joinCommitUninterruptibly(null);
fail();
} catch (NullPointerException expected) {
}
assertTrue(barrier.isClosed());
assertEquals(0, barrier.getNumberWaiting());
}
@Test
public void whenTransactionFailsToPrepare() {
barrier = new CountDownCommitBarrier(1);
Txn tx = mock(Txn.class);
when(tx.getStatus()).thenReturn(TxnStatus.Active);
doThrow(new RuntimeException()).when(tx).prepare();
try {
barrier.joinCommitUninterruptibly(tx);
fail("Expecting Runtime Exception thrown on Txn preparation");
} catch (RuntimeException ex) {
}
assertTrue(barrier.isClosed());
assertEquals(0, barrier.getNumberWaiting());
}
@Test
public void whenTransactionAborted_thenDeadTxnException() {
barrier = new CountDownCommitBarrier(1);
Txn tx = stm.newDefaultTxn();
tx.abort();
try {
barrier.joinCommitUninterruptibly(tx);
fail("Should have thrown DeadTxnException");
} catch (DeadTxnException expected) {
}
assertIsAborted(tx);
assertTrue(barrier.isClosed());
assertEquals(0, barrier.getNumberWaiting());
}
@Test
public void whenTransactionCommitted_thenDeadTxnException() {
barrier = new CountDownCommitBarrier(1);
Txn tx = stm.newDefaultTxn();
tx.commit();
try {
barrier.joinCommitUninterruptibly(tx);
fail("Should have thrown DeadTxnException");
} catch (DeadTxnException expected) {
}
assertIsCommitted(tx);
assertTrue(barrier.isClosed());
assertEquals(0, barrier.getNumberWaiting());
}
@Test
@Ignore
public void whenStartingInterrupted() throws InterruptedException {
}
@Test
public void whenInterruptedWhileWaiting_thenNoInterruption() throws InterruptedException {
barrier = new CountDownCommitBarrier(2);
final TxnInteger ref = stm.getDefaultRefFactory().newTxnInteger(10);
TestThread t = new TestThread() {
@Override
public void doRun() throws Exception {
stm.getDefaultTxnExecutor().execute(new TxnVoidCallable() {
@Override
public void call(Txn tx) throws Exception {
ref.incrementAndGet(tx, 1);
barrier.joinCommitUninterruptibly(tx);
}
});
}
};
t.setPrintStackTrace(false);
t.start();
sleepMs(500);
t.interrupt();
sleepMs(500);
assertAlive(t);
assertTrue(barrier.isClosed());
//todo
//assertTrue(t.isInterrupted());
}
@Test
public void whenCommittedWhileWaiting() throws InterruptedException {
barrier = new CountDownCommitBarrier(2);
final GammaTxnInteger ref = stm.getDefaultRefFactory().newTxnInteger(0);
TestThread t = new TestThread() {
@Override
public void doRun() throws Exception {
stm.getDefaultTxnExecutor().execute(new TxnVoidCallable() {
@Override
public void call(Txn tx) throws Exception {
ref.incrementAndGet(tx, 1);
barrier.joinCommitUninterruptibly(tx);
}
});
}
};
t.setPrintStackTrace(false);
t.start();
sleepMs(500);
barrier.countDown();
sleepMs(500);
t.join();
assertNothingThrown(t);
assertTrue(barrier.isCommitted());
assertEquals(1, ref.atomicGet());
assertEquals(0, barrier.getNumberWaiting());
}
@Test
public void whenAbortedWhileWaiting_() throws InterruptedException {
barrier = new CountDownCommitBarrier(2);
final GammaTxnInteger ref = stm.getDefaultRefFactory().newTxnInteger(0);
TestThread t = new TestThread() {
@Override
public void doRun() throws Exception {
stm.getDefaultTxnExecutor().execute(new TxnVoidCallable() {
@Override
public void call(Txn tx) throws Exception {
ref.getAndIncrement(tx, 1);
barrier.joinCommitUninterruptibly(tx);
}
});
}
};
t.setPrintStackTrace(false);
t.start();
sleepMs(500);
barrier.abort();
sleepMs(500);
t.join();
t.assertFailedWithException(IllegalStateException.class);
assertTrue(barrier.isAborted());
assertEquals(0, ref.atomicGet());
assertEquals(0, barrier.getNumberWaiting());
}
@Test
public void whenAborted_thenCommitBarrierOpenException() {
barrier = new CountDownCommitBarrier(1);
barrier.abort();
Txn tx = stm.newDefaultTxn();
try {
barrier.joinCommitUninterruptibly(tx);
fail("Expecting CommitBarrierOpenException");
} catch (CommitBarrierOpenException expected) {
}
assertTrue(barrier.isAborted());
assertEquals(0, barrier.getNumberWaiting());
assertIsAborted(tx);
}
@Test
public void whenCommitted_thenCommitBarrierOpenException() {
barrier = new CountDownCommitBarrier(0);
Txn tx = stm.newDefaultTxn();
try {
barrier.joinCommitUninterruptibly(tx);
fail("Expecting CommitBarrierOpenException");
} catch (CommitBarrierOpenException expected) {
}
assertTrue(barrier.isCommitted());
assertEquals(0, barrier.getNumberWaiting());
assertIsAborted(tx);
}
}
| mit |
Sugarfooot/VeggyBot | Assets/Scripts/InGame/Bonus/WaterPill.js | 219 | #pragma strict
function Start () {
}
function Update () {
}
function OnTriggerEnter (collider : Collider){
if (collider.CompareTag("Player")){
UIManager.Instance().FillWaterTank();
Destroy(gameObject);
}
} | mit |
6iplus/music_wall | startup.js | 2009 | var MongoClient = require('mongodb').MongoClient,
settings = require('./config.js'),
Guid = require('Guid');
var fullMongoUrl = settings.mongoConfig.serverUrl + settings.mongoConfig.database;
function runSetup() {
return MongoClient.connect(fullMongoUrl)
.then(function(db) {
return db.createCollection("party");
}).then(function(partyCollection) {
return partyCollection.count().then(function(theCount) {
// the result of find() is a cursor to MongoDB, and we can call toArray() on it
if (theCount > 0) return partyCollection.find().toArray();
return partyCollection.insertOne({_id: Guid.create().toString(), partyId: "RunxiD", partyName: "Runxi1st", createdBy: "Runxi_Ding", playList: [], config: {}}).then(function(newDoc) {
return newDoc;
}).then(function() {
return partyCollection.insertOne({_id: Guid.create().toString(), partyId: "TianchiTim", partyName: "Tianchi1st", createdBy: "Tianchi_Liu", playList: [], config: {}});
}).then(function() {
return partyCollection.insertOne({_id: Guid.create().toString(), partyId: "ZhiDream", partyName: "Meng1st", createdBy: "Meng_Zhi", playList: [], config: {}});
}).then(function() {
return partyCollection.insertOne({_id: Guid.create().toString(), partyId: "XibeiziM", partyName: "Xibeizi1st", createdBy: "Xibeizi_Ma", playList: [], config: {}});
}).then(function() {
return partyCollection.insertOne({_id: Guid.create().toString(), partyId: "XinyuZ", partyName: "Xinyu1st", createdBy: "Xinyu_Zhang", playList: [], config: {}});
}).then(function() {
return partyCollection.find().toArray();
});
});
});
}
// By exporting a function, we can run
var exports = module.exports = runSetup; | mit |
dreamineering/start.ionic | tasks/karma.js | 357 | 'use strict';
// path config
var cfg = require('../gulp_config');
// gulp and general utils
var gulp = require('gulp');
// karma
var karma = require('gulp-karma');
module.exports = gulp.task('karma', ['lint'], function () {
return gulp.src(cfg.test.js)
.pipe(karma({
configFile: 'test/karma/karma.conf.js',
action: 'run'
}));
});
| mit |
jaykang920/x2boost | include/x2boost/event_sink.hpp | 733 | // Copyright (c) 2014-2017 Jae-jun Kang
// See the file LICENSE for details.
#ifndef X2BOOST_EVENT_SINK_HPP_
#define X2BOOST_EVENT_SINK_HPP_
#ifndef X2BOOST_PRE_HPP_
#include "x2boost/pre.hpp"
#endif
#include <boost/weak_ptr.hpp>
namespace x2boost
{
class X2BOOST_API event_sink
{
public:
virtual ~event_sink()
{
cleanup();
}
flow_ptr flow() const { return f.lock(); }
void set_flow(flow_ptr value) { f = value; }
protected:
void cleanup()
{
if (flow_ptr p = f.lock())
{
// ...
}
}
private:
boost::weak_ptr<x2boost::flow> f;
};
}
#endif // X2BOOST_EVENT_SINK_HPP_
| mit |
hshoff/vx | packages/visx-demo/src/pages/network.tsx | 485 | import React from 'react';
import Show from '../components/Show';
import Network from '../sandboxes/visx-network/Example';
import NetworkSource from '!!raw-loader!../sandboxes/visx-network/Example';
import packageJson from '../sandboxes/visx-network/package.json';
const NetworkPage = () => (
<Show
component={Network}
title="Network"
codeSandboxDirectoryName="visx-network"
packageJson={packageJson}
>
{NetworkSource}
</Show>
);
export default NetworkPage;
| mit |
franklingu/leetcode-solutions | questions/groups-of-special-equivalent-strings/Solution.py | 1851 | """
You are given an array A of strings.
Two strings S and T are special-equivalent if after any number of moves, S == T.
A move consists of choosing two indices i and j with i % 2 == j % 2, and swapping S[i] with S[j].
Now, a group of special-equivalent strings from A is a non-empty subset S of A such that any string not in S is not special-equivalent with any string in S.
Return the number of groups of special-equivalent strings from A.
Example 1:
Input: ["a","b","c","a","c","c"]
Output: 3
Explanation: 3 groups ["a","a"], ["b"], ["c","c","c"]
Example 2:
Input: ["aa","bb","ab","ba"]
Output: 4
Explanation: 4 groups ["aa"], ["bb"], ["ab"], ["ba"]
Example 3:
Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
Explanation: 3 groups ["abc","cba"], ["acb","bca"], ["bac","cab"]
Example 4:
Input: ["abcd","cdab","adcb","cbad"]
Output: 1
Explanation: 1 group ["abcd","cdab","adcb","cbad"]
Note:
1 <= A.length <= 1000
1 <= A[i].length <= 20
All A[i] have the same length.
All A[i] consist of only lowercase letters.
"""
class Solution(object):
def numSpecialEquivGroups(self, A):
"""
:type A: List[str]
:rtype: int
"""
done = [0] * len(A)
track = []
for s in A:
t = [{}, {}]
for i, c in enumerate(s):
d = t[i % 2]
if c not in d:
d[c] = 1
else:
d[c] += 1
track.append(t)
g = 0
for i, t in enumerate(track):
if done[i] != 0:
continue
for j, t2 in enumerate(track):
if j <= i:
continue
if t2 == t:
done[j] = 1
done[i] = 1
# print(done)
g += 1
return g
| mit |
neogeek/reader.py | fetch_remote_file.py | 972 | import os
import datetime
import requests
def fetch_remote_file(url, cache = '', expire = 0):
if cache and expire:
expire = (datetime.datetime.now() - datetime.timedelta(minutes=expire)).strftime('%s')
if not os.path.isfile(cache) or int(os.path.getmtime(cache)) < int(expire):
try:
content = requests.get(url, verify=False).text.encode('utf-8')
file_put_contents(cache, content)
except Exception, e:
print e
else:
content = file_get_contents(cache)
else:
content = requests.get(url, verify=False).text.encode('utf-8')
return content
def file_get_contents(file):
if os.path.isfile(file):
file = open(file, 'r')
content = file.read()
file.close()
return content
def file_put_contents(file, content):
file = open(file, 'w')
file.write(content)
file.close()
return content
| mit |
wolfogre/AndroidProgramming | ActivityTaskFragment/ActivityLifeCycleSample/src/main/java/com/example/me/activitylifecyclesample/SecondActivity.java | 1884 | package com.example.me.activitylifecyclesample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class SecondActivity extends AppCompatActivity {
/** Called when the activity is first created. */
private Button b2;
private static final String TAG="second";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Log.i(TAG, "onCreate------------------------------>");
b2 = (Button) findViewById(R.id.Button02);
// 响应按键事件
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 显示方式声明Intent,直接启动SecondActivity
Intent intent = new Intent(SecondActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart------------------------------>");
}
protected void onRestart() {
super.onRestart();
Log.i(TAG, "onRestart------------------------------>");
}
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume------------------------------>");
}
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause------------------------------>");
}
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop------------------------------>");
}
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy------------------------------>");
}
}
| mit |
gviau/sketch-3d | sketch3d-main/src/render/Renderer.cpp | 10268 | #include "render/Renderer.h"
#include "math/Constants.h"
#include "math/Sphere.h"
#include "render/OpenGL/RenderSystemOpenGL.h"
#include "system/Platform.h"
// Windows is the only OS where it makes sense to have DirectX
#if PLATFORM == PLATFORM_WIN32
#include "render/Direct3D9/RenderSystemDirect3D9.h"
#endif
#include "render/RenderStateCache.h"
#include "render/Texture2D.h"
#include "render/TextureManager.h"
#include "system/Logger.h"
#include "system/Window.h"
#include <math.h>
#include <FreeImage.h>
namespace Sketch3D {
Renderer Renderer::instance_;
Renderer::Renderer() : renderSystem_(nullptr), useFrustumCulling_(true), nearFrustumPlane_(0.0f), farFrustumPlane_(0.0f),
oldViewportX_(0), oldViewportY_(0), oldViewportWidth_(0), oldViewportHeight_(0)
{
}
Renderer::~Renderer() {
delete renderSystem_;
}
Renderer* Renderer::GetInstance() {
return &instance_;
}
bool Renderer::Initialize(RenderSystem_t renderSystem,
Window& window, const RenderParameters_t& renderParameters)
{
renderParamters_ = renderParameters;
switch (renderSystem) {
case RENDER_SYSTEM_OPENGL:
renderSystem_ = new RenderSystemOpenGL(window);
break;
#if PLATFORM == PLATFORM_WIN32
case RENDER_SYSTEM_DIRECT3D9:
renderSystem_ = new RenderSystemDirect3D9(window);
break;
#endif
default:
Logger::GetInstance()->Error("Unknown render system");
break;
}
if (!renderSystem_->Initialize(renderParamters_)) {
Logger::GetInstance()->Error("Couldn't initialize render system properly");
return false;
}
SetDefaultRenderingValues();
return true;
}
void Renderer::SetClearColor(float red, float green, float blue, float alpha) const {
renderSystem_->SetClearColor(red, green, blue, alpha);
}
void Renderer::Clear(int buffer) const {
renderSystem_->GetRenderStateCache()->ApplyClearStateChanges();
renderSystem_->Clear(buffer);
}
void Renderer::StartRender() {
renderSystem_->StartRender();
}
void Renderer::EndRender() {
renderSystem_->EndRender();
}
void Renderer::Render() {
// Commit the state changes
RenderStateCache* renderStateCache = renderSystem_->GetRenderStateCache();
renderStateCache->ApplyRenderStateChanges();
// Draw the static batches first
sceneTree_.RenderStaticBatches();
// Populate the render queue with nodes from the scene tree
FrustumPlanes_t frustumPlanes;
if (useFrustumCulling_) {
frustumPlanes = ExtractViewFrustumPlanes();
}
sceneTree_.Render(frustumPlanes, useFrustumCulling_, opaqueRenderQueue_, transparentRenderQueue_);
// Draw the render queue contents
opaqueRenderQueue_.Render();
if (!transparentRenderQueue_.IsEmpty()) {
renderStateCache->SetBlendingEquation(BLENDING_EQUATION_ADD);
renderStateCache->EnableBlending(true);
renderStateCache->ApplyRenderStateChanges();
transparentRenderQueue_.Render();
renderStateCache->EnableBlending(false);
}
}
void Renderer::PresentFrame() {
renderSystem_->PresentFrame();
}
void Renderer::OrthoProjection(float left, float right,
float bottom, float top,
float nearPlane, float farPlane)
{
projection_ = renderSystem_->OrthoProjection(left, right, bottom, top, nearPlane, farPlane);
viewProjection_ = projection_ * view_;
nearFrustumPlane_ = nearPlane;
farFrustumPlane_ = farPlane;
}
void Renderer::PerspectiveProjection(float left, float right,
float bottom, float top,
float nearPlane, float farPlane)
{
projection_ = renderSystem_->PerspectiveProjection(left, right, bottom, top, nearPlane, farPlane);
viewProjection_ = projection_ * view_;
nearFrustumPlane_ = nearPlane;
farFrustumPlane_ = farPlane;
}
void Renderer::PerspectiveProjection(float fov, float aspect, float nearPlane,
float farPlane)
{
float h = tan(fov * DEG_2_RAD_OVER_2) * nearPlane;
float w = h * aspect;
PerspectiveProjection(-w, w, -h, h, nearPlane, farPlane);
}
void Renderer::CameraLookAt(const Vector3& position, const Vector3& point,
const Vector3& up)
{
Vector3 direction = point - position;
direction.Normalize();
Vector3 right = direction.Cross(up);
right.Normalize();
Vector3 u = right.Cross(direction);
u.Normalize();
SetViewMatrix(right, u, direction, position);
}
void Renderer::SetViewMatrix(const Vector3& right, const Vector3& up, const Vector3& look, const Vector3& position) {
view_[0][0] = right.x;
view_[0][1] = right.y;
view_[0][2] = right.z;
view_[1][0] = up.x;
view_[1][1] = up.y;
view_[1][2] = up.z;
view_[2][0] = -look.x;
view_[2][1] = -look.y;
view_[2][2] = -look.z;
view_[0][3] = -position.Dot(right);
view_[1][3] = -position.Dot(up);
view_[2][3] = position.Dot(look);
viewProjection_ = projection_ * view_;
}
void Renderer::SetRenderFillMode(RenderMode_t mode) const {
renderSystem_->SetRenderFillMode(mode);
}
void Renderer::SetViewport(size_t x, size_t y, size_t width, size_t height) {
if (x != oldViewportX_ || y != oldViewportY_ || width != oldViewportWidth_ || height != oldViewportHeight_) {
renderSystem_->SetViewport(x, y, width, height);
oldViewportX_ = x;
oldViewportY_ = y;
oldViewportWidth_ = width;
oldViewportHeight_ = height;
}
}
void Renderer::EnableDepthTest(bool val) const {
renderSystem_->EnableDepthTest(val);
}
void Renderer::EnableDepthWrite(bool val) const {
renderSystem_->EnableDepthWrite(val);
}
void Renderer::EnableColorWrite(bool val) const {
renderSystem_->EnableColorWrite(val);
}
void Renderer::SetDepthComparisonFunc(DepthFunc_t comparison) const {
renderSystem_->SetDepthComparisonFunc(comparison);
}
void Renderer::SetCullingMethod(CullingMethod_t cullingMethod) {
cullingMethod_ = cullingMethod;
renderSystem_->SetCullingMethod(cullingMethod);
}
Shader* Renderer::CreateShader() const {
return renderSystem_->CreateShader();
}
Texture2D* Renderer::CreateTexture2D() const {
return renderSystem_->CreateTexture2D();
}
Texture2D* Renderer::CreateTexture2DFromFile(const string& filename, bool generateMipmaps) const {
// Check cache first
if (TextureManager::GetInstance()->CheckIfTextureLoaded(filename)) {
return TextureManager::GetInstance()->LoadTextureFromCache(filename);
}
Texture2D* texture = renderSystem_->CreateTexture2D();
texture->SetGenerateMipmaps(generateMipmaps);
if (!texture->Load(filename)) {
Logger::GetInstance()->Error("Couldn't create texture from file " + filename);
delete texture;
return nullptr;
}
return texture;
}
Texture3D* Renderer::CreateTexture3D() const {
return renderSystem_->CreateTexture3D();
}
RenderTexture* Renderer::CreateRenderTexture(unsigned int width, unsigned int height, TextureFormat_t format) const {
return renderSystem_->CreateRenderTexture(width, height, format);
}
void Renderer::BindScreenBuffer() const {
renderSystem_->BindScreenBuffer();
}
void Renderer::EnableBlending(bool val) const {
renderSystem_->EnableBlending(val);
}
void Renderer::SetBlendingEquation(BlendingEquation_t equation) const {
renderSystem_->SetBlendingEquation(equation);
}
void Renderer::SetBlendingFactor(BlendingFactor_t srcFactor, BlendingFactor_t dstFactor) const {
renderSystem_->SetBlendingFactor(srcFactor, dstFactor);
}
Vector3 Renderer::ScreenToWorldPoint(const Vector2& point) const {
return renderSystem_->ScreenToWorldPoint(viewProjection_.Inverse(), point);
}
size_t Renderer::BindTexture(const Texture* texture) {
return renderSystem_->BindTexture(texture);
}
void Renderer::BindShader(const Shader* shader) {
renderSystem_->BindShader(shader);
}
FrustumPlanes_t Renderer::ExtractViewFrustumPlanes() const {
return renderSystem_->ExtractViewFrustumPlanes(viewProjection_);
}
void Renderer::EnableFrustumCulling(bool val) {
useFrustumCulling_ = val;
}
void Renderer::DrawTextBuffer(BufferObject* bufferObject, Texture2D* fontAtlas, const Vector3& textColor) {
RenderStateCache* renderStateCache = renderSystem_->GetRenderStateCache();
renderStateCache->EnableDepthTest(false);
renderStateCache->ApplyRenderStateChanges();
renderSystem_->DrawTextBuffer(bufferObject, fontAtlas, textColor);
renderStateCache->EnableDepthTest(true);
}
const Matrix4x4& Renderer::GetProjectionMatrix() const {
return projection_;
}
const Matrix4x4& Renderer::GetViewMatrix() const {
return view_;
}
const Matrix4x4& Renderer::GetViewProjectionMatrix() const {
return viewProjection_;
}
float Renderer::GetNearFrustumPlane() const {
return nearFrustumPlane_;
}
float Renderer::GetFarFrustumPlane() const {
return farFrustumPlane_;
}
const SceneTree& Renderer::GetSceneTree() const {
return sceneTree_;
}
SceneTree& Renderer::GetSceneTree() {
return sceneTree_;
}
BufferObjectManager* Renderer::GetBufferObjectManager() const {
return renderSystem_->GetBufferObjectManager();
}
RenderStateCache* Renderer::GetRenderStateCache() const {
return renderSystem_->GetRenderStateCache();
}
size_t Renderer::GetScreenWidth() const {
return renderSystem_->GetWidth();
}
size_t Renderer::GetScreenHeight() const {
return renderSystem_->GetHeight();
}
CullingMethod_t Renderer::GetCullingMethod() const {
return cullingMethod_;
}
void Renderer::SetDefaultRenderingValues() {
// Some initial values
PerspectiveProjection(45.0f, (float)renderParamters_.width / (float)renderParamters_.height, 1.0f, 1000.0f);
CameraLookAt(Vector3::ZERO, Vector3::LOOK);
SetCullingMethod(CULLING_METHOD_BACK_FACE);
}
bool FrustumPlanes_t::IsSphereOutside(const Sphere& sphere) const {
return sphere.IntersectsPlane(nearPlane) == RELATIVE_PLANE_POSITION_OUTSIDE ||
sphere.IntersectsPlane(farPlane) == RELATIVE_PLANE_POSITION_OUTSIDE ||
sphere.IntersectsPlane(leftPlane) == RELATIVE_PLANE_POSITION_OUTSIDE ||
sphere.IntersectsPlane(rightPlane) == RELATIVE_PLANE_POSITION_OUTSIDE ||
sphere.IntersectsPlane(bottomPlane) == RELATIVE_PLANE_POSITION_OUTSIDE ||
sphere.IntersectsPlane(topPlane) == RELATIVE_PLANE_POSITION_OUTSIDE;
}
}
| mit |
will14smith/Toxon.Fonts | src/Toxon.Fonts.Application/Properties/AssemblyInfo.cs | 835 | 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Toxon.Fonts.Application")]
[assembly: AssemblyTrademark("")]
// 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("f9c86bd1-1ca9-4822-afad-29643b9f8d2e")]
| mit |
jupiny/MIDASChallenge2017 | midas_web_solution/midas_web_solution/settings/partials/static.py | 359 | # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
import os
from .base import BASE_DIR, PROJECT_ROOT_DIR
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
# Media files
MEDIA_ROOT = os.path.join(
PROJECT_ROOT_DIR,
"dist",
"media",
)
MEDIA_URL = '/media/'
| mit |
kolocoda/Debt-Manager | app/src/main/java/com/chikeandroid/debtmanager/util/NetworkUtil.java | 916 | package com.chikeandroid.debtmanager.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public final class NetworkUtil {
private NetworkUtil() {
}
/**
* Returns true if the Throwable is an instance of RetrofitError with an
* http status code equals to the given one.
*/
/* public static boolean isHttpStatusCode(Throwable throwable, int statusCode) {
return throwable instanceof HttpException
&& ((HttpException) throwable).code() == statusCode;
}*/
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
} | mit |
markkimsal/php-raft | src/raft/msghandler.php | 4846 | <?php
/**
* Raft consensus algorithm
*
* Copyright 2015 Mark Kimsal
*
* 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.
*/
class Raft_Msghandler {
public function onMsgReply($msg, $node) {
$type = $msg->pop();
if ($type == 'VOTE') {
$node->votes++;
if ($node->votes >= floor(count($node->getPeers())/2) +1) {
Raft_Logger::log( sprintf('[%s] is leader', $node->name), 'D');
$node->transitionToLeader();
$node->resetHb();
$node->pingPeers();
}
}
if ($type == 'AppendEntriesReply') {
$from = $msg->pop();
$term = (int)$msg->pop();
$success = (int)$msg->pop();
$matchIndex = $msg->pop();
//TODO this isn't the right comparison
if ($matchIndex < $node->log->getCommitIndex()) {
$p = $node->findPeer($from);
if (!$p) {
Raft_Logger::log( sprintf('[%s] cannot find peer %s', $node->name, $from), 'E');
return;
}
Raft_Logger::log( sprintf('[%s] leader committing log', $node->name), 'D');
$node->log->commitIndex($matchIndex);
$node->log->debugLog();
$p->matchIndex = (int)$matchIndex;
$p->nextIndex = (int)$matchIndex+1;
}
}
}
public function onMsg($msg, $node) {
$from = $msg->pop();
//$null = $msg->pop();
$type = $msg->pop();
if ($type == 'REQUEST') {
Raft_Logger::log( sprintf('[%s] got request', $node->name), 'D');
$node->appendEntry($msg->pop(), $from);
return;
}
if ($type == 'AppendEntries') {
$term = (int)$msg->pop();
if ($term <= $node->currentTerm) {
//TODO: update peer log, respond
$node->resetHb();
$node->votes = 0;
if (!$node->isLeader()) {
$leaderId = $msg->pop();
$prevIdx = (int)$msg->pop();
$prevTerm = $msg->pop();
$entry = $msg->pop();
$commitIdx = -1;
if ($msg->parts()) {
$commitIdx = (int)$msg->pop();
}
if ($node->log->getTermForIndex($prevIdx) != $prevTerm) {
$node->log->debugLog();
Raft_Logger::log( sprintf('[%s] reject entry based on term diff \'%s\' \'%s\'', $node->name, $node->log->getTermForIndex($prevIdx), $prevTerm), 'D');
return;
}
if (!empty($entry)) {
Raft_Logger::log( sprintf('[%s] peer updating log', $node->name), 'D');
Raft_Logger::log( sprintf('[%s] appending entry', print_r($entry, 1)), 'D');
$node->appendEntry($entry, $from);
}
$node->conn->sendAppendReply($from, $term, $node->log->getCommitIndex());
if ($commitIdx > -1) {
$node->log->commitIndex($commitIdx);
$node->log->debugLog();
}
}
} else {
Raft_Logger::log( sprintf('[%s] reject entry based on term %d', $node->name, $node->currentTerm), 'D');
}
}
/*
if ($type == 'HEARTBEAT') {
$node->resetHb();
$node->votes = 0;
Raft_Logger::log( sprintf('[%s] got hb', $node->name), 'D');
}
*/
if ($type == 'ELECT') {
$term = (int)$msg->pop();
if ($term <= $node->currentTerm) {
Raft_Logger::log( sprintf('[%s] rejecting old term election %s <= %s from %s', $node->name, $term, $node->currentTerm, $from), 'D');
}
if ($term > $node->currentTerm) {
Raft_Logger::log( sprintf('[%s] got election from %s', $node->name, $from), 'D');
Raft_Logger::log( sprintf('[%s] casting vote for %s @t%s', $node->name, $from, $term), 'D');
$node->conn->sendVote($from, $term, 0);
$node->currentTerm = $term;
/*
$p = $node->findPeer($from);
if (!$p) {
Raft_Logger::log( sprintf('[%s] cannot find peer %s', $node->name, $from), 'E');
return;
}
Raft_Logger::log( sprintf('[%s] casting vote for %s @t%s', $node->name, $from, $term), 'D');
$p->conn->sendVote($from, $term, 0);
$node->currentTerm = $term;
$node->state = 'follower';
$node->setLeaderNode($from);
$node->resetHb();
$node->votes++;
*/
}
}
}
}
| mit |
roydejong/midway-editor | src/midway-toolbar-button.js | 497 | /**
* A reusable instance of a toolbar button.
* @constructor
*/
var MidwayToolbarButton = function (id, label) {
this.id = id;
this.label = "Button";
this.icon = this.id;
this.style = '';
if (label) {
this.label = label;
}
this.apply = function (midway, selection) {
// To be implemented by user
return false;
};
this.queryState = function (midway, selection) {
// To be implemented by user
return false;
};
}; | mit |
lixar/giant | giant/plugins/client/objc_ios/objc_ios/objc_ios/examples.py | 5539 | #!/usr/bin/env python
import random
from collections import defaultdict
from giant.giant_base.giant_base import GiantError
def raise_(ex):
raise ex
swagger_to_objc_enum_example_map = {
'string': defaultdict(lambda: lambda enum: '@"' + random.choice(enum) + '"',
{
'guid': lambda enum: '@"' + random.choice(enum) + '"',
'date': lambda enum: '@"' + random.choice(enum) + '"',
'date-time': lambda enum: '@"' + random.choice(enum) + '"',
'byte': lambda enum: raise_(GiantError('Shiver me timbers, I can\'t parse a enum byte type. Implement it yerself!')),
'binary': lambda enum: raise_(GiantError('Shiver me timbers, I can\'t parse a enum binary type. Implement it yerself!')),
'password': lambda enum: '@"' + random.choice(enum) + '"',
}
),
'integer': defaultdict(lambda: lambda enum: '@(' + str(random.choice(enum)) + ')',
{
'int32': lambda enum: '@(' + str(random.choice(enum)) + ')',
'int64': lambda enum: '@(' + str(random.choice(enum)) + ')'
}
),
'number': defaultdict(lambda: lambda enum: '@(' + str(random.choice(enum)) + ')',
{
'float': lambda enum: '@(' + str(random.choice(enum)) + ')',
'double': lambda enum: '@(' + str(random.choice(enum)) + ')',
}
),
'boolean': defaultdict(lambda: lambda enum: '@(' + str(random.choice(enum)) + ')')
}
def example_integer(schema):
minimum = schema.get('minimum', 1)
maximum = schema.get('maximum', minimum + 100)
multiple = schema.get('multipleOf', 1)
return random.choice(range(minimum, maximum, multiple))
def example_float(schema):
minimum = schema.get('minimum', 0.0)
maximum = schema.get('maximum', 100.0)
multiple = schema.get('multipleOf', 0.01)
return str(round(random.uniform(minimum, maximum) / multiple) * multiple)
swagger_to_objc_example_map = {
'string': defaultdict(lambda: lambda schema: '@"ExampleString"',
{
'guid': lambda schema: '@"ExampleString"',
'date': lambda schema: '[NSDate date]',
'date-time': lambda schema: '[NSDate date]',
'byte': lambda schema: '@"ExampleString"',
'binary': lambda schema: '@"ExampleString"',
'password': lambda schema: '@"thepasswordispassword"'
}
),
'integer': defaultdict(lambda: lambda schema: "@" + str(example_integer(schema)),
{
'int32': lambda schema: "@" + str(example_integer(schema)),
'int64': lambda schema: "@" + str(example_integer(schema))
}
),
'number': defaultdict(lambda: lambda schema: str(example_float(schema)),
{
'float': lambda schema: "@" + str(example_float(schema)),
'double': lambda schema: "@" + str(example_float(schema))
}
),
'boolean': defaultdict(lambda: lambda schema: random.choice(('YES', 'NO'))),
'array': defaultdict(lambda: lambda schema: '@[]')
}
swagger_to_objc_example_string_map = {
'string': defaultdict(lambda: lambda schema: '@"ExampleString"',
{
'guid': lambda schema: '@"ExampleString"',
'date': lambda schema: '[NSDate date].iso8601;',
'date-time': lambda schema: '[NSDate date].iso8601;',
'byte': lambda schema: '@"ExampleString"',
'binary': lambda schema: '@"ExampleString"',
'password': lambda schema: '"thepasswordispassword"'
}
),
'integer': defaultdict(lambda: lambda schema: "@(" + str(example_integer(schema)) + ').stringValue',
{
'int32': lambda schema: "@(" + str(example_integer(schema)) + ').stringValue',
'int64': lambda schema: "@(" + str(example_integer(schema)) + ').stringValue'
}
),
'number': defaultdict(lambda: lambda schema: str(example_float(schema)) + '.stringValue',
{
'float': lambda schema: "@(" + str(example_float(schema)) + ').stringValue',
'double': lambda schema: "@(" + str(example_float(schema)) + ').stringValue'
}
),
'boolean': defaultdict(lambda: lambda schema: '@(' + random.choice(('YES', 'NO')) + ').stringValue'),
'array': defaultdict(lambda: lambda schema: '@"[]"')
}
swagger_to_objc_string_map = {
'string': defaultdict(lambda: lambda schema, variable_name: variable_name,
{
'guid': lambda schema, variable_name: variable_name,
'date': lambda schema, variable_name: variable_name + '.iso8601;',
'date-time': lambda schema, variable_name: variable_name + '.iso8601;',
'byte': lambda schema, variable_name: variable_name,
'binary': lambda schema, variable_name: variable_name,
'password': lambda schema, variable_name: variable_name
}
),
'integer': defaultdict(lambda: lambda schema, variable_name: variable_name + '.stringValue',
{
'int32': lambda schema, variable_name: variable_name + '.stringValue',
'int64': lambda schema, variable_name: variable_name + '.stringValue'
}
),
'number': defaultdict(lambda: lambda schema, variable_name: variable_name + '.stringValue',
{
'float': lambda schema, variable_name: variable_name + '.stringValue',
'double': lambda schema, variable_name: variable_name + '.stringValue'
}
),
'boolean': defaultdict(lambda: lambda schema, variable_name: variable_name +'.stringValue')
} | mit |
kidshenlong/warpspeed | Project Files/Assets/Scripts/Editor/StateRemoveComponentInspector.cs | 587 | using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(StateRemoveComponentScript))]
public class StateRemoveComponentInspector : Editor
{
private StateRemoveComponentScript remover;
public void OnEnable()
{
remover = (StateRemoveComponentScript)target;
}
public override void OnInspectorGUI()
{
remover.gameStateMask = (GameState)EditorGUILayout.EnumMaskField("Remove State", remover.gameStateMask);
remover.removeComponent = (Component)EditorGUILayout.ObjectField(remover.removeComponent, typeof(Component), true, null);
}
}
| mit |
yaseenagag/pizza-restaurant | src/server/routes/preference.js | 1765 | const dbPreference = require('../../models/preference.js');
const router = require('express').Router();
const renderError = require('../utils.js');
router.post('/', (request, response, next) => {
dbPreference.createPreference(request.body)
.then(function(preference) {
if (preference) return response.redirect(`/preferences/${preference[0].id}`);
next();
})
.catch( error => renderError(error, response));
});
router.get('/', (request, response, next) => {
dbPreference.getPreferences()
.then(function(preference) {
if (preference) return response.json(preference);
next();
})
.catch( error => renderError(error, response));
});
router.get('/:preferenceid', (request, response, next) => {
const preferenceID = request.params.preferenceid;
if (!preferenceID || !/^\d+$/.test(preferenceID)) return next();
dbPreference.getPreference(preferenceID)
.then(function(preference) {
if (preference) return response.json(preference);
next();
})
.catch( error => renderError(error, response));
});
router.patch('/:preferenceid', (request, response, next) => {
const preferenceID = request.params.preferenceid;
dbPreference.updatePreference(request.body, preferenceID)
.then(function(preference) {
if (preference) return response.redirect(`/preferences/${preferenceID}`);
next();
})
.catch( error => renderError(error, response));
});
router.delete('/:preferenceid', (request, response, next) => {
const preferenceID = request.params.preferenceid;
dbPreference.deletePreference(preferenceID)
.then(function(preference) {
if (preference) return response.redirect(`/preferences/${preferenceID}`);
next();
})
.catch( error => renderError(error, response));
});
module.exports = router;
| mit |
gulian/fuzzy-octo-hipster | routes/article.js | 3211 | exports.retreive = function(req, res){
var request = req.params.id ? { _id : req.params.id } : null ;
req.mongoose.models.article.find(request).sort({created: -1}).populate('user', 'email').populate('comments').exec(function(error, articles){
req.mongoose.models.user.populate(articles, {
path: 'comments.user',
select: 'email'
}, function(error, articles){
res.json(200, articles);
});
});
};
exports.create = function(req, res){
req.body.user = req.session._id;
if(!req.body.user)
return res.send(403);
if(!req.body.tags)
req.body.tags = [];
else if(typeof req.body.tags === "string"){
var tmp = [];
for (var i = 0; i < req.body.tags.split(',').length; i++) {
tmp.push({
name: req.body.tags.split(',')[i]
});
}
req.body.tags = tmp;
}
new req.mongoose.models.article(req.body).save(function (error, article) {
if (error)
res.send(500);
else{
req.mongoose.models.user.populate(article, {
path: 'user',
select: 'email'
}, function(error, article){
if (error)
return res.send(500);
else
res.json(200, article);
});
}
});
};
exports.update = function(req, res){
req.mongoose.models.article.findOne({ _id: req.params.id}, function (error, article) {
if(error)
return res.send(500);
if(article && article.user != req.session._id && article.user !== undefined)
return res.send(403);
article.title = req.body.title;
article.content = req.body.content;
article.tags = req.body.tags;
article.created = Date.now();
article.save(function(error, article){
if(error){
console.log(error);
return res.send(500);
}
return res.json(200, article);
});
});
};
exports.updateClick = function(req, res){
req.mongoose.models.article.findOne({ _id: req.params.id}, function (error, article) {
if(error)
return res.send(500);
req.mongoose.models.user.findOne({ _id: req.session._id}, function (error, user) {
if(error)
return res.send(500);
if(article.click.indexOf(user.email) === -1 )
article.click.push(user.email);
article.save(function(error, article){
if(error){
console.log(error);
return res.send(500);
}
return res.json(200, article);
});
});
});
};
exports.delete = function(req,res){
req.mongoose.models.article.findOne({ _id:req.params.id }, function(error, article){
if(article && article.user != req.session._id && article.user !== undefined)
return res.send(403);
article.remove(function(error){
if(error)
res.send(500);
else
res.send(200);
});
});
};
| mit |
gschrader/ratpack-react-boilerplate | react/src/Login.js | 2436 | import React, { useState } from 'react';
import {Alert, Button, FormControl, FormGroup, Modal} from 'react-bootstrap';
import {Redirect} from 'react-router-dom';
import {AuthConsumer} from './AuthContext'
function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
return (<AuthConsumer>
{({isAuth, message, login}) => (
<div>
{isAuth ? (
<Redirect to="/"/>
) : (
<Modal show={true}>
<Modal.Header>
<Modal.Title>Welcome</Modal.Title>
</Modal.Header>
<Modal.Body>
{message
? <Alert variant='warning'>
{message}
</Alert>
: React.Fragment}
<form>
<FormGroup>
<FormControl id="username" type="text" label="Username"
placeholder="Username"
onChange={event => {
setUsername(event.target.value);
}}
value={username}
/>
<FormControl id="password" label="Password" type="password"
placeholder="password"
onChange={event => {
setPassword(event.target.value);
}}
value={password}
/>
</FormGroup>
</form>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={() => {login(username, password)}}>Sign in</Button>
</Modal.Footer>
</Modal>
)}
</div>
)}
</AuthConsumer>);
}
export default Login;
| mit |
charliesome/opal | spec/language/ensure_spec.rb | 2633 | module EnsureSpec
class Container
attr_reader :executed
def initialize
@executed = []
end
def raise_in_method_with_ensure
@executed << :method
raise "An Exception"
ensure
@executed << :ensure
end
def raise_and_rescue_in_method_with_ensure
@executed << :method
raise "An Exception"
rescue => e
@executed << :rescue
ensure
@executed << :ensure
end
def implicit_return_in_method_with_ensure
:method
ensure
:ensure
end
def explicit_return_in_method_with_ensure
return :method
ensure
return :ensure
end
end
end
describe "An ensure block inside a begin block" do
before :each do
ScratchPad.record []
end
it "is executed when an exception is raised in it's corresponding begin block" do
begin
lambda {
begin
ScratchPad << :begin
raise "An exception occured!"
ensure
ScratchPad << :ensure
end
}.should raise_error(RuntimeError)
ScratchPad.recorded.should == [:begin, :ensure]
end
end
it "is executed when an exception is raised and rescued in it's corresponding begin block" do
begin
begin
ScratchPad << :begin
raise "An exception occured!"
rescue => e
ScratchPad << :rescue
ensure
ScratchPad << :ensure
end
ScratchPad.recorded.should == [:begin, :rescue, :ensure]
end
end
it "is executed when nothing is raised or thrown in it's corresponding begin block" do
begin
ScratchPad << :begin
rescue
ScratchPad << :rescue
ensure
ScratchPad << :ensure
end
ScratchPad.recorded.should == [:begin, :ensure]
end
it "has no return value" do
begin
:begin
ensure
:ensure
end.should == :begin
end
end
describe "An ensure block inside a method" do
before(:each) do
@obj = EnsureSpec::Container.new
end
it "is executed when an exception is raised in the method" do
lambda { @obj.raise_in_method_with_ensure }.should raise_error(RuntimeError)
@obj.executed.should == [:method, :ensure]
end
it "is executed when an exception is raised and rescued in the method" do
@obj.raise_and_rescue_in_method_with_ensure
@obj.executed.should == [:method, :rescue, :ensure]
end
it "has no impact on the method's implicit return value" do
@obj.implicit_return_in_method_with_ensure.should == :method
end
it "has an impact on the method's explicit return value" do
@obj.explicit_return_in_method_with_ensure.should == :ensure
end
end | mit |
wkevina/feature-requests-app | features/tests/test_models.py | 2927 | import django.db
from django.test import TestCase
from ..models import Client, ProductArea, FeatureRequest
class ModelSanityTests(TestCase):
def test_client(self):
name = 'ClientA'
# Check that the universe is roughly logical
client_A = Client(name=name)
client_A.save()
assert client_A.name == name
# This should exist, right?
loaded_client = Client.objects.get(name=name)
# Cool, it does. But is it what we think it is?
assert loaded_client
assert loaded_client.id == client_A.id
assert loaded_client.name == client_A.name
# I guess it is.
def test_product_area(self):
name = 'Sales'
area = ProductArea(name=name)
area.save()
assert area.name == name
loaded_area = ProductArea.objects.get(name=name)
assert loaded_area
assert loaded_area.id == area.id
assert loaded_area.name == area.name
class FeatureRequestTests(TestCase):
def test_creation(self):
"""Test basic creation API"""
title = 'Test feature title'
description = 'Test feature description.'
feature = FeatureRequest(
title=title,
description=description,
client=Client.objects.create(name='test_client'),
client_priority=1,
target_date='2016-1-1',
product_area=ProductArea.objects.create(name='test_area')
)
feature.save()
# Verify all data goes in and comes out the right way
assert feature.title == title
assert feature.description == description
self.assertIsInstance(feature.client, Client)
assert feature.client.name == 'test_client'
assert feature.client_priority == 1
assert feature.target_date == '2016-1-1'
self.assertIsInstance(feature.product_area, ProductArea)
assert feature.product_area.name == 'test_area'
def test_unique_priority(self):
"""For each Client, there should be no more than one FeatureRequest with
a given client_priority"""
client = Client.objects.create(name='test_client')
area = ProductArea.objects.create(name='test_area')
priority = 1
# Make an FR for client, priority=1
feature = FeatureRequest(
title='',
description='',
client=client,
client_priority=priority,
target_date='2016-1-1',
product_area=area
)
feature.save()
# Make another FR for same client, same priority
impostor = FeatureRequest(
title='',
description='',
client=client,
client_priority=priority,
target_date='2016-1-1',
product_area=area
)
with self.assertRaises(django.db.IntegrityError):
impostor.save()
| mit |
lpdw/Stratajm | src/AdminBundle/Resources/public/js/bootstrap-table-export.js | 5128 | /**
* @author zhixin wen <wenzhixin2010@gmail.com>
* extensions: https://github.com/kayalshri/tableExport.jquery.plugin
*/
(function ($) {
'use strict';
var sprintf = $.fn.bootstrapTable.utils.sprintf;
var TYPE_NAME = {
json: 'JSON',
xml: 'XML',
png: 'PNG',
csv: 'CSV',
txt: 'TXT',
sql: 'SQL',
doc: 'Word',
excel: 'Excel',
powerpoint: 'MS-Powerpoint',
pdf: 'PDF'
};
$.extend($.fn.bootstrapTable.defaults, {
showExport: false,
exportDataType: 'all', // basic, all, selected
// 'json', 'xml', 'png', 'csv', 'txt', 'sql', 'doc', 'excel', 'powerpoint', 'pdf'
exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel'],
exportOptions: {}
});
$.extend($.fn.bootstrapTable.defaults.icons, {
export: 'glyphicon-export icon-share'
});
$.extend($.fn.bootstrapTable.locales, {
formatExport: function () {
return 'Export data';
}
});
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
var BootstrapTable = $.fn.bootstrapTable.Constructor,
_initToolbar = BootstrapTable.prototype.initToolbar;
BootstrapTable.prototype.initToolbar = function () {
this.showToolbar = this.options.showExport;
_initToolbar.apply(this, Array.prototype.slice.apply(arguments));
if (this.options.showExport) {
var that = this,
$btnGroup = this.$toolbar.find('>.btn-group'),
$export = $btnGroup.find('div.export');
if (!$export.length) {
$export = $([
'<div class="export btn-group">',
'<button class="btn' +
sprintf(' btn-%s', this.options.buttonsClass) +
sprintf(' btn-%s', this.options.iconSize) +
' dropdown-toggle" ' +
'title="' + this.options.formatExport() + '" ' +
'data-toggle="dropdown" type="button">',
sprintf('<i class="%s %s"></i> ', this.options.iconsPrefix, this.options.icons.export),
'<span class="caret"></span>',
'</button>',
'<ul class="dropdown-menu" role="menu">',
'</ul>',
'</div>'].join('')).appendTo($btnGroup);
var $menu = $export.find('.dropdown-menu'),
exportTypes = this.options.exportTypes;
if (typeof this.options.exportTypes === 'string') {
var types = this.options.exportTypes.slice(1, -1).replace(/ /g, '').split(',');
exportTypes = [];
$.each(types, function (i, value) {
exportTypes.push(value.slice(1, -1));
});
}
$.each(exportTypes, function (i, type) {
if (TYPE_NAME.hasOwnProperty(type)) {
$menu.append(['<li data-type="' + type + '">',
'<a href="javascript:void(0)">',
TYPE_NAME[type],
'</a>',
'</li>'].join(''));
}
});
$menu.find('li').click(function () {
var type = $(this).data('type'),
doExport = function () {
that.$el.tableExport($.extend({}, that.options.exportOptions, {
type: type,
escape: false
}));
};
if (that.options.exportDataType === 'all' && that.options.pagination) {
that.$el.one(that.options.sidePagination === 'server' ? 'post-body.bs.table' : 'page-change.bs.table', function () {
doExport();
that.togglePagination();
});
that.togglePagination();
} else if (that.options.exportDataType === 'selected') {
var data = that.getData(),
selectedData = that.getAllSelections();
// Quick fix #2220
if (that.options.sidePagination === 'server') {
data = {total: that.options.totalRows};
data[that.options.dataField] = that.getData();
selectedData = {total: that.options.totalRows};
selectedData[that.options.dataField] = that.getAllSelections();
}
that.load(selectedData);
doExport();
that.load(data);
} else {
doExport();
}
});
}
}
};
})(jQuery);
| mit |
ikikai/HelpIn | db/migrate/20160528145121_create_experts.rb | 281 | class CreateExperts < ActiveRecord::Migration
def change
create_table :experts do |t|
t.string :name
t.string :email, unique: true
t.text :bio
t.string :specialization
t.decimal :rating
t.timestamps
end
end
end
| mit |
f500/equatable | src/Exceptions/InRangeException.php | 519 | <?php
/**
* @license https://github.com/f500/equatable/blob/master/LICENSE MIT
*/
declare(strict_types=1);
namespace F500\Equatable\Exceptions;
use OutOfRangeException as BaseException;
/**
* @copyright Copyright (c) 2015 Future500 B.V.
* @author Jasper N. Brouwer <jasper@future500.nl>
*/
final class InRangeException extends BaseException
{
public static function alreadyContainsKey(string $key): self
{
return new self(sprintf('Collection already contains the key "%s"', $key));
}
}
| mit |
laura333/Q1-project | js/init.js | 1731 | 'use strict';
$(document).ready(function() {
console.log('Let\'s do this!');
$('.button-collapse').sideNav();
$('.parallax').parallax();
$('.modal').modal();
var answers = {};
$('.gender').on('click', function(event) {
event.preventDefault();
var $elmf = $(event.target);
var gender = $elmf.text();
answers.gender = gender;
var $xhr = $.getJSON('https://g-comicvine3.herokuapp.com/api/characters?api_key=19b875b3fb7d4abe44bbf49506248a975491895f&format=JSON&filter=gender:' + answers.gender);
// var $xhr = $('data.js');
$('.popup').toggle();
$('#modal5').modal('open');
$('#modal5').on('click', function() {
$('#modal6').modal('open');
});
$('#modal6').on('click', function() {
$('#modal7').modal('open');
});
$('#modal7').on('click', function() {
$('#result').modal('open');
});
$xhr.done(function(data) {
if ($xhr.status !== 200) {
return;
}
var randomNum = Math.floor((Math.random(data.results.length) * 100) + 1);
var char = data.results[randomNum];
console.log(char);
if (char.image.super_url) {
$("#result").append('Name: ' + char.name +
'<br><br><img class="char-img" src=' + char.image.super_url + '>' +
'<br>Origin: ' + char.origin.name +
'<br><p class="description">Description: ' + char.deck);
}
});
$xhr.fail(function(err) {
console.log(err);
$('.popup').toggle();
});
});
});
| mit |
noelheesen/Ensured | Ensured/Ensure.cs | 8825 | namespace Ensured
{
using System;
using System.Linq.Expressions;
/// <summary>
/// Exposes methods to validate values
/// </summary>
/// <remarks>
/// The only public class for the API.
/// </remarks>
public static class Ensure
{
/// <summary>
/// This method provides a context on which validation can be performed
/// </summary>
/// <remarks>
/// This method creates an expression from the given <paramref name="value"/> and calls <see cref="That{T}(Expression{Func{T}})"/> internally
/// </remarks>
/// <typeparam name="T">The <see cref="Type"/> of the <paramref name="value"/></typeparam>
/// <param name="value">The value to validate</param>
/// <returns>An <see cref="ArgumentContext{T}"/> that contains information about the <paramref name="value"/></returns>
public static ArgumentContext<T> That<T>(T value) {
return Ensure.That<T>(() => value);
}
/// <summary>
/// This method provides a context on which validation can be performed
/// </summary>
/// <typeparam name="T">The <see cref="Type"/> of the value that the <paramref name="expression"/> returns</typeparam>
/// <param name="expression">An <see cref="Expression"/> that returns a value to validate</param>
/// <returns>An <see cref="ArgumentContext{T}"/> that contains information about the <paramref name="value"/></returns>
public static ArgumentContext<T> That<T>(Expression<Func<T>> expression) {
return new ArgumentContext<T>(expression);
}
/// <summary>
/// Ensures the given <paramref name="value"/> is not <c>null</c> without creating an <see cref="ArgumentContext{T}"/>
/// </summary>
/// <remarks>
/// Calls <see cref="NotNull{T}(Expression{Func{T}}, string, string)"/> internally
/// An optional <paramref name="paramName"/> and <paramref name="message"/> can be provided
/// If not specified the <paramref name="paramName"/> will be extracted from the created expression and use the default message of the <see cref="ArgumentNullException"/>
/// </remarks>
/// <typeparam name="T">The <see cref="Type"/> of the <paramref name="value"/></typeparam>
/// <param name="value">The value to validate</param>
/// <param name="paramName">An optional custom parameter name for the <see cref="ArgumentNullException"/></param>
/// <param name="message">An optional custom message for the <see cref="ArgumentNullException"/></param>
/// <returns>The <paramref name="value"/> if it passes validation</returns>
/// <exception cref="ArgumentNullException">If <paramref name="value"/> is <c>null</c></exception>
public static T NotNull<T>(T value, string paramName = null, string message = null) {
return Ensure.NotNull(() => value, paramName, message);
}
/// <summary>
/// Ensures the value returned by the expression is not <c>null</c> without creating an <see cref="ArgumentContext{T}"/>
/// </summary>
/// <remarks>
/// An optional <paramref name="paramName"/> and <paramref name="message"/> can be provided
/// If not specified the <paramref name="paramName"/> will be extracted from the <paramref name="expression"/> and use the default message of the <see cref="ArgumentNullException"/>
/// </remarks>
/// <typeparam name="T">The <see cref="Type"/> of the value that the <paramref name="expression"/> returns</typeparam>
/// <param name="expression">An <see cref="Expression"/> that returns a value to validate</param>
/// <param name="paramName">An optional custom parameter name for the <see cref="ArgumentNullException"/></param>
/// <param name="message">An optional custom message for the <see cref="ArgumentNullException"/></param>
/// <returns>The value that the <paramref name="expression"/> returns if validation is passed</returns>
/// <exception cref="ArgumentNullException">If the value returned from the <paramref name="expression"/> is or compiled to <c>null</c> </exception>
public static T NotNull<T>(Expression<Func<T>> expression, string paramName = null, string message = null) {
if (Equals(expression, null))
throw new ArgumentNullException("expression");
var value = expression.Compile().Invoke();
var name = paramName ?? ((MemberExpression)expression.Body).Member.Name;
if (Equals(value, null)) {
if (Equals(message, null)) {
throw new ArgumentNullException(name);
} else {
throw new ArgumentNullException(name, message);
}
}
return value;
}
/// <summary>
/// Ensures the given <paramref name="condition"/> results to <c>true</c> when passing in the given <paramref name="value"/>
/// </summary>
/// <remarks>
/// An optional <paramref name="paramName"/> and <paramref name="message"/> can be provided
/// If not specified the <paramref name="paramName"/> will be extracted and use the default message of the <see cref="ArgumentException"/>
/// </remarks>
/// <typeparam name="T">The <see cref="Type"/> of the <paramref name="value"/></typeparam>
/// <param name="value">The value to validate</param>
/// <param name="condition">The condition to use when validating the value</param>
/// <param name="message">An optional custom message for the <see cref="ArgumentException"/></param>
/// <param name="paramName">An optional custom parameter name for the <see cref="ArgumentException"/></param>
/// <returns>The <paramref name="value"/> if it passes validation</returns>
/// <exception cref="ArgumentException">If the <paramref name="value"/> does not pass validation</exception>
/// <exception cref="ArgumentNullException">If the <paramref name="value"/> or <paramref name="condition"/> is <c>null</c></exception>
public static T Condition<T>(T value, Expression<Func<T, bool>> condition, string message = null, string paramName = null, bool allowNull = false) {
Ensure.NotNull(condition);
if (!allowNull)
Ensure.NotNull(value);
if (!condition.Compile()(value)) {
if (Equals(paramName, null)) {
throw new ArgumentException(message ?? $"{value} does not pass {condition}");
} else {
throw new ArgumentException(message ?? $"{value} does not pass {condition}", paramName);
}
}
return value;
}
/// <summary>
/// Ensures the given <paramref name="condition"/> results to <c>true</c> when passing in the value of the given <paramref name="expression"/>
/// </summary>
/// <remarks>
/// An optional <paramref name="paramName"/> and <paramref name="message"/> can be provided
/// If not specified the <paramref name="paramName"/> will be extracted and use the default message of the <see cref="ArgumentException"/>
/// </remarks>
/// <typeparam name="T">The <see cref="Type"/> of the value that the <paramref name="expression"/> returns</typeparam>
/// <param name="expression">An <see cref="Expression"/> that returns a value to validate</param>
/// <param name="condition">The condition to use when validating the value</param>
/// <param name="paramName">An optional custom message for the <see cref="ArgumentException"/></param>
/// <param name="message">An optional custom parameter name for the <see cref="ArgumentException"/></param>
/// <returns>The value that the <paramref name="expression"/> returns if validation is passed</returns>
/// <exception cref="ArgumentException">If the value returned from the <paramref name="expression"/> does not pass validation</exception>
/// <exception cref="ArgumentNullException">If the <paramref name="expression"/> or <paramref name="condition"/> is <c>null</c></exception>
public static T Condition<T>(Expression<Func<T>> expression, Expression<Func<T, bool>> condition, string message = null, string paramName = null, bool allowNull = false) {
if (Equals(expression, null))
throw new ArgumentNullException("expression");
var value = expression.Compile().Invoke();
var name = paramName ?? ((MemberExpression)expression.Body).Member.Name;
return Ensure.Condition(value, condition, message, name, allowNull);
}
}
}
| mit |
juanhm93/proyecto | application/models/excel_data_insert_model.php | 1902 | <?php
class Excel_data_insert_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function gerencia($g){
$this->db->insert('gerencia',$g);
}
public function categoria($categ){
$this->db->insert('categoria',$categ);
}
public function plan($planproyec){
$this->db->insert('plan',$planproyec);
}
public function reales($realesvar){
$this->db->insert('reales',$realesvar);
}
public function mv($mvvar){
$this->db->insert('mejorv',$mvvar);
}
public function anteproyecto($ante){
$this->db->insert('anteproyecto',$ante);
}
public function realesupdate($id,$reales){
$this->db->where('idproyecto',$id);
$this->db->update('reales',$reales);
}
public function proyectos($proyec){
$this->db->insert('proyecto',$proyec);
}
public function habilitador($hab){
if($this->db->insert('habilitadora',$hab)){
return true;
}
}
public function udphabilitador($id,$hab){
$this->db->where('idhab',$id);
$this->db->update('habilitadora',$hab);
}
public function inserthabilitadora($hab){
$this->db->insert('habelec',$hab);
}
public function mixtas($mix){
$this->db->insert('mixta',$mix);
}
public function direccion($dir){
$this->db->insert('direccion',$dir);
}
public function updatereal($id,$reales){
$this->db->where('idreal',$id);
$this->db->update('reales',$reales);
}
public function updateplan($id,$plan){
$this->db->where('idplan',$id);
$this->db->update('plan',$plan);
}
public function updatemv($id,$mejorv){
$this->db->where('idmv',$id);
$this->db->update('mejorv',$mejorv);
}
public function updateante($id,$ante){
$this->db->where('idante',$id);
$this->db->update('anteproyecto',$ante);
}
} | mit |
stolinski/st2017 | src/pages/projects.js | 2311 | import React from 'react';
import Layout from '../components/Layout';
import { Title, MainWrapper } from '../components/Headings';
import { ProjectsList } from '../components/ProjectsStyles';
const projects = [
{
title: 'Level Up Tutorials',
link: 'https://www.leveluptutorials.com/',
desc:
'2000+ Web Dev Tutorials on: <a target="_blank" href="https://www.youtube.com/channel/UCyU5wkjgQYGRB0hIHMwm2Sg">Youtube</a><br />Built With: Meteor, React, Stylus',
},
{
title: 'Syntax',
link: 'https://syntax.fm/',
desc: 'A popular web-dev podcast hosted by Wes Bos & Scott Tolinski',
},
{
title: 'Ford.com Global UX',
link: 'http://www.ford.com/',
desc:
'Design Prototypes and Interactive Digital Styleguide for the Ford.com Global Redesign:<br />Built With: Angular.js, Sass',
},
{
title: 'Q LTD',
link: 'http://qltd.com/',
desc:
'Built for: <a target="_blank" href="http://qltd.com">Q LTD</a><br />Built With: Node.js, Express, MongoDB, Sass/Compass/Susy',
},
{
title: 'ACM SIGGRAPH',
link: 'http://www.siggraph.org/',
desc:
'Built for: <a target="_blank" href="http://qltd.com">Q LTD</a><br />Built With: Drupal 7, Omega 3, Sass/Compass',
},
{
title: 'Concrete.org',
link: 'http://www.concrete.org/',
desc:
'Built for: <a target="_blank" href="http://qltd.com">Q LTD</a><br />Built Templates With: HTML5, CSS3, JavaScript',
},
];
export default class Projects extends React.Component {
render() {
return (
<Layout {...this.props}>
<MainWrapper color="#e74c3c">
<Title>Projects</Title>
<p>
I've worked on many types of projects both personal and professional. Here are some projects I've
developed/created.
</p>
<ProjectsList>
{projects.map(project => (
<li key={project.title}>
<h3 className="project-title">
<a target="_blank" rel="noopener noreferrer" href={project.link}>
{project.title}
</a>
</h3>
<p dangerouslySetInnerHTML={{ __html: project.desc }} />
</li>
))}
</ProjectsList>
</MainWrapper>
</Layout>
);
}
}
| mit |
paymentwall/paymentwall-ruby | features/step_definitions/charge.rb | 749 | When(/^test token is retrieved$/) do
pending # Write code here that turns the phrase above into concrete actions
end
Then(/^charge should be successful$/) do
pending # Write code here that turns the phrase above into concrete actions
end
Given(/^charge ID "([^"]*)"$/) do |arg1|
pending # Write code here that turns the phrase above into concrete actions
end
Then(/^charge should be refunded$/) do
pending # Write code here that turns the phrase above into concrete actions
end
Given(/^CVV code "([^"]*)"$/) do |arg1|
pending # Write code here that turns the phrase above into concrete actions
end
Then(/^I see this error message "([^"]*)"$/) do |arg1|
pending # Write code here that turns the phrase above into concrete actions
end | mit |
elmanortiz/adminbeard | src/ERP/AdminBundle/Entity/ClientePotencial.php | 8030 | <?php
namespace ERP\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ClientePotencial
*
* @ORM\Table(name="cliente_potencial", indexes={@ORM\Index(name="fk_cliente_potencial_contacto1_idx", columns={"contacto_id"})})
* @ORM\Entity
*/
class ClientePotencial
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nombre", type="string", length=60, nullable=false)
*/
private $nombre;
/**
* @var string
*
* @ORM\Column(name="telefono", type="string", length=25, nullable=false)
*/
private $telefono;
/**
* @var string
*
* @ORM\Column(name="nrc", type="string", length=25, nullable=true)
*/
private $nrc;
/**
* @var string
*
* @ORM\Column(name="nit", type="string", length=25, nullable=true)
*/
private $nit;
/**
* @var string
*
* @ORM\Column(name="correoelectronico", type="string", length=60, nullable=true)
*/
private $correoelectronico;
/**
* @var string
*
* @ORM\Column(name="movil", type="string", length=25, nullable=true)
*/
private $movil;
/**
* @var string
*
* @ORM\Column(name="pagina_web", type="string", length=80, nullable=true)
*/
private $paginaWeb;
/**
* @var string
*
* @ORM\Column(name="referido_por", type="string", length=60, nullable=true)
*/
private $referidoPor;
/**
* @var string
*
* @ORM\Column(name="descripcion", type="string", length=255, nullable=true)
*/
private $descripcion;
/**
* @var string
*
* @ORM\Column(name="direccion", type="string", length=100, nullable=true)
*/
private $direccion;
/**
* @var \Contacto
*
* @ORM\ManyToOne(targetEntity="Contacto")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="contacto_id", referencedColumnName="id")
* })
*/
private $contacto;
// /**
// * @var \EstadoClientePotencial
// *
// * @ORM\ManyToOne(targetEntity="EstadoClientePotencial")
// * @ORM\JoinColumns({
// * @ORM\JoinColumn(name="estado_cliente_potencial_id", referencedColumnName="id")
// * })
// */
// private $estadoClientePotencial;
//
/**
* @var integer
* @ORM\Column(name="estado", type="integer", nullable=false)
*/
private $estado;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
* @return ClientePotencial
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set telefono
*
* @param string $telefono
* @return ClientePotencial
*/
public function setTelefono($telefono)
{
$this->telefono = $telefono;
return $this;
}
/**
* Get telefono
*
* @return string
*/
public function getTelefono()
{
return $this->telefono;
}
/**
* Set nrc
*
* @param string $nrc
* @return ClientePotencial
*/
public function setNrc($nrc)
{
$this->nrc = $nrc;
return $this;
}
/**
* Get nrc
*
* @return string
*/
public function getNrc()
{
return $this->nrc;
}
/**
* Set nit
*
* @param string $nit
* @return ClientePotencial
*/
public function setNit($nit)
{
$this->nit = $nit;
return $this;
}
/**
* Get nit
*
* @return string
*/
public function getNit()
{
return $this->nit;
}
/**
* Set correoelectronico
*
* @param string $correoelectronico
* @return ClientePotencial
*/
public function setCorreoelectronico($correoelectronico)
{
$this->correoelectronico = $correoelectronico;
return $this;
}
/**
* Get correoelectronico
*
* @return string
*/
public function getCorreoelectronico()
{
return $this->correoelectronico;
}
/**
* Set movil
*
* @param string $movil
* @return ClientePotencial
*/
public function setMovil($movil)
{
$this->movil = $movil;
return $this;
}
/**
* Get movil
*
* @return string
*/
public function getMovil()
{
return $this->movil;
}
/**
* Set paginaWeb
*
* @param string $paginaWeb
* @return ClientePotencial
*/
public function setPaginaWeb($paginaWeb)
{
$this->paginaWeb = $paginaWeb;
return $this;
}
/**
* Get paginaWeb
*
* @return string
*/
public function getPaginaWeb()
{
return $this->paginaWeb;
}
/**
* Set referidoPor
*
* @param string $referidoPor
* @return ClientePotencial
*/
public function setReferidoPor($referidoPor)
{
$this->referidoPor = $referidoPor;
return $this;
}
/**
* Get referidoPor
*
* @return string
*/
public function getReferidoPor()
{
return $this->referidoPor;
}
/**
* Set descripcion
*
* @param string $descripcion
* @return ClientePotencial
*/
public function setDescripcion($descripcion)
{
$this->descripcion = $descripcion;
return $this;
}
/**
* Get descripcion
*
* @return string
*/
public function getDescripcion()
{
return $this->descripcion;
}
/**
* Set direccion
*
* @param string $direccion
* @return ClientePotencial
*/
public function setDireccion($direccion)
{
$this->direccion = $direccion;
return $this;
}
/**
* Get direccion
*
* @return string
*/
public function getDireccion()
{
return $this->direccion;
}
/**
* Set contacto
*
* @param \DG\AdminBundle\Entity\Contacto $contacto
* @return ClientePotencial
*/
public function setContacto(\DG\AdminBundle\Entity\Contacto $contacto = null)
{
$this->contacto = $contacto;
return $this;
}
/**
* Get contacto
*
* @return \DG\AdminBundle\Entity\Contacto
*/
public function getContacto()
{
return $this->contacto;
}
// /**
// * Set estadoClientePotencial
// *
// * @param \DG\AdminBundle\Entity\EstadoClientePotencial $estadoClientePotencial
// * @return ClientePotencial
// */
// public function setEstadoClientePotencial(\DG\AdminBundle\Entity\EstadoClientePotencial $estadoClientePotencial = null)
// {
// $this->estadoClientePotencial = $estadoClientePotencial;
//
// return $this;
// }
//
// /**
// * Get estadoClientePotencial
// *
// * @return \DG\AdminBundle\Entity\EstadoClientePotencial
// */
// public function getEstadoClientePotencial()
// {
// return $this->estadoClientePotencial;
// }
//
/**
* Set estado
*
* @param string $estado
* @return ClientePotencial
*/
public function setEstado($estado)
{
$this->estado = $estado;
return $this;
}
/**
* Get estado
*
* @return integer
*/
public function getEstado()
{
return $this->estado;
}
public function __toString() {
return $this->nombre;
}
}
| mit |
girub/accreditamenti | app/DoctrineMigrations/Version20120830105303.php | 1007 | <?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your need!
*/
class Version20120830105303 extends AbstractMigration
{
public function up(Schema $schema)
{
// this up() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql("CREATE TABLE Iscritti (id INT AUTO_INCREMENT NOT NULL, cognome VARCHAR(255) NOT NULL, nome VARCHAR(255) NOT NULL, codice_fiscale VARCHAR(255) NOT NULL, tipologia_iscritto VARCHAR(255) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB");
}
public function down(Schema $schema)
{
// this down() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql("DROP TABLE Iscritti");
}
}
| mit |
kraumor/symblog | src/Blogger/BlogBundle/Entity/Repository/BlogRepository.php | 1793 | <?php
namespace Blogger\BlogBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
/**
* BlogRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class BlogRepository extends EntityRepository
{
public function getLatestBlogs($limit = null)
{
$qb = $this->createQueryBuilder('b')
->select('b','c')
->leftJoin('b.comments', 'c')
->addOrderBy('b.created', 'DESC');
if (false === is_null($limit))
$qb->setMaxResults($limit);
return $qb->getQuery()
->getResult();
}
public function getTags()
{
$blogTags = $this->createQueryBuilder('b')
->select('b.tags')
->getQuery()
->getResult();
$tags = array();
foreach ($blogTags as $blogTag)
{
$tags = array_merge(explode(",", $blogTag['tags']), $tags);
}
foreach ($tags as &$tag)
{
$tag = trim($tag);
}
return $tags;
}
public function getTagWeights($tags)
{
$tagWeights = array();
if (empty($tags))
return $tagWeights;
foreach ($tags as $tag)
{
$tagWeights[$tag] = (isset($tagWeights[$tag])) ? $tagWeights[$tag] + 1 : 1;
}
// Shuffle the tags
uksort($tagWeights, function() {
return rand() > rand();
});
$max = max($tagWeights);
// Max of 5 weights
$multiplier = ($max > 5) ? 5 / $max : 1;
foreach ($tagWeights as &$tag)
{
$tag = ceil($tag * $multiplier);
}
return $tagWeights;
}
}
| mit |
codeandcats/delaunay-animation-editor | client/typescripts/app/actions/fileDialogs.ts | 1907 | import { ActionType, IAction, IProjectAttributes } from '../models';
export interface IShowNewProjectDialog extends IAction {
}
export interface ICancelNewProjectDialog extends IAction {
}
export interface IProjectFileNamesAction extends IAction {
fileNames: string[];
}
export interface IUpdateAllProjectFileNamesAction extends IProjectFileNamesAction {
}
export interface IShowOpenProjectDialogAction extends IProjectFileNamesAction {
}
export interface IShowSaveProjectDialogAction extends IProjectFileNamesAction {
}
export interface ICancelProjectFileDialog extends IAction {
}
export interface IUpdateSelectedFileNameAction extends IAction {
fileName: string;
}
export interface IUpdateNewProjectAttributes extends IAction {
attributes: IProjectAttributes;
}
export const updateAllProjectFileNames = (fileNames: string[]): IUpdateAllProjectFileNamesAction => ({ type: ActionType.UpdateAllProjectFileNames, fileNames });
export const showNewProjectDialog = (): IShowNewProjectDialog => ({ type: ActionType.ShowNewProjectDialog });
export const cancelNewProjectDialog = (): ICancelNewProjectDialog => ({ type: ActionType.CancelNewProjectDialog });
export const showOpenProjectDialog = (fileNames: string[]): IShowOpenProjectDialogAction => ({ type: ActionType.ShowOpenProjectDialog, fileNames });
export const showSaveProjectDialog = (fileNames: string[]): IShowSaveProjectDialogAction => ({ type: ActionType.ShowSaveProjectDialog, fileNames });
export const cancelProjectFileDialog = (): ICancelProjectFileDialog => ({ type: ActionType.CancelProjectFileDialog });
export const updateSelectedFileName = (fileName: string): IUpdateSelectedFileNameAction => ({ type: ActionType.UpdateSelectedFileName, fileName });
export const updateNewProjectAttributes = (attributes: IProjectAttributes): IUpdateNewProjectAttributes => ({ type: ActionType.UpdateNewProjectAttributes, attributes });
| mit |
Mohammad-Alavi/Samandoon | app/Containers/NGO/UI/API/Routes/FindNgoByPublicName.v1.private.php | 556 | <?php
/**
* @apiGroup NGO
* @apiName findNgoByPublicName
*
* @api {GET} /v1/ngo/get/{public_name} Find NGO by Public Name
* @apiDescription Search a NGO in local DB and return it's data if ngo is found
*
* @apiVersion 1.0.0
* @apiPermission none
*
* @apiUse NGOSuccessSingleResponse
*/
$router->get('ngo/get/{public_name}', [
'as' => 'api_ngo_find_ngo_by_public_name',
'uses' => 'Controller@findNgoByPublicName',
// 'middleware' => [
// 'auth:api',
// ],
]);
| mit |
bodrovis/ChgkRating | lib/chgk_rating/collections/tournaments/tournament_team_players.rb | 540 | module ChgkRating
module Collections
class TournamentTeamPlayers < Base
attr_reader :team, :tournament
def initialize(params = {})
@tournament = build_model params[:tournament], ChgkRating::Models::Tournament
@team = build_model params[:team]
super
end
private
def process(*_args)
super { |result| ChgkRating::Models::TournamentTeamPlayer.new result }
end
def api_path
"tournaments/#{@tournament.id}/recaps/#{@team.id}"
end
end
end
end | mit |
SMarone/NDInterp | NDimInterp.py | 62528 | import numpy as np
from scipy import spatial
from scipy.sparse import csc_matrix
import scipy.sparse.linalg as spsl
import scipy.interpolate as interp
from matplotlib import cm
import matplotlib.pyplot as plt
import time
import math
from mpl_toolkits.mplot3d import Axes3D
import copy as cp
from matplotlib.backends.backend_pdf import PdfPages
from contextlib import contextmanager
import sys, os
## Written by Stephen Marone
## Intern at the NASA GRC
## Project Start - June 8th, 2015
## Program Version 12
## This is an n-dimensional interpolation code. More information can be found
# at the end of the code along with the lines which run it.
# Local Methods ================================================================
'''
The Methods and functions in this section of the code are here in order to
have an easy reference to change the test problems in this code. This
entire section can be removed if these interpolation routines are being
integrated into another code.
'''
@contextmanager
def suppress_stdout():
## This function just suppresses outputs
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
def Solve(points, funct):
## Library of different problems to test interpolation
if (funct == 'Crate'):
## Egg Crate Function
x = points[:,0]
y = points[:,1]
z = -x * np.sin(np.sqrt(abs(x - y - 47))) - \
(y+47) * np.sin(np.sqrt(abs(x/2 + y + 47)))
elif (funct == 'PW'):
## Piecewise Function with 3 Planes - made up
x = points[:,0]
y = points[:,1]
dtype = type(points[0,0])
z = np.empty(len(x), dtype=dtype)
count = 0
for i in range(len(x)):
if (x[i] > 0):
if (y[i] > 0):
z[count] = x[i] + 8*y[i]
count +=1
else:
z[count] = 5*x[i] + y[i]
count +=1
else:
z[count] = 5*x[i] + 6*y[i]
count +=1
elif (funct == 'Plane'):
## Simple Plane Function, made up
x = points[:,0]
y = points[:,1]
z = 3*x+24*y
elif (funct == '5D2O'):
## Completely made up
v = points[:,0]
w = points[:,1]
x = points[:,2]
y = points[:,3]
z = 15*(v**2) - w - 4*x + 3*(y*y)
#z = 15*(v**2) - w - 4*x + np.sin(np.pi*(y*y))
elif (funct == '5D4O'):
## More bs stuff I made up
v = points[:,0]
w = points[:,1]
x = points[:,2]
y = points[:,3]
z = 9*(v**4) + w*w - 7*x + 2*(y*y)
#z = 9*(v**4) + w*w - np.sin(np.pi*x) + np.cos(np.pi*(y*y))
elif (funct == '2D3O'):
## 3rd Order Legendre Polynomial
x = points[:,0]/500. ## The 500s ensures it is the normal range
z = 0.5*(5*(x**3)-3*x)*500
elif (funct == '2D5O'):
## 5rd Order Legendre Polynomial
x = points[:,0]/500. ## The 500s ensures it is the normal range
z = (1/8.)*(63*(x**5) - 70*(x**3) + 15*x)*500
else:
print 'Function type not found.' #Srsly, read some instructions
print
return
return z
# Local Data Class =============================================================
'''
The Methods and functions in this section of the code are here in order to
easily setup and test data that might resemble good cases the interpolators
will run. This entire section is unnecesary when wrapping the interpolation
classes into another code.
'''
class N_Data(object):
## Main data type with N dimension. Only needed if you want to use the
# example functions, check for error, or plot.
def __init__(self, mini, maxi, numpts, funct='PW', dtype='rand', dims=3):
## For funct possibilities, refer to the Solve function above
## Dtype: cart for cartesian, LH for latin h-cube, rand for random
self.funct = funct
self.dtype = dtype
self.dims = dims
'''
print "Creating Independent Data"
print "-Function Type:", funct
print "-Data Distribution Type:", dtype
print "-Quantity of Points:", numpts
print "-Dimensions:", dims
for d in range(dims-1):
print "-Range of dimension %s: [%s,%s]" % ((d+1), mini[d], maxi[d])
print
'''
## Setup independent data for each function via distribution
if (dtype == 'rand'):
self.points = np.random.rand(numpts,dims-1) * \
(maxi-mini) + mini
if (dims == 2):
self.points = np.sort(self.points, axis=0)
'''
if (funct == 'PW'):
## This ensures points exist on discontinuities for piecewise
self.points[0,0] = mini/2
self.points[1,0] = mini
self.points[2,0] = 0
self.points[3,0] = maxi/2
self.points[4,0] = maxi
self.points[5:10,0] = 0
self.points[0:5,1] = 0
self.points[5,1] = mini/2
self.points[6,1] = mini
self.points[7,1] = maxi/2
self.points[8,1] = maxi
'''
elif (dtype == 'LH'):
points = np.zeros((numpts,dims-1), dtype="float")
for d in range(dims-1):
## Latin Hypercube it up
points[:,d] = np.linspace(mini[d],maxi[d],numpts)
np.random.shuffle(points[:,d])
self.points = points
elif (dtype == 'cart'):
if (dims == 3):
stp = (maxi-mini)/(np.sqrt(numpts)-1)
x = np.arange(mini[0],maxi[0],stp[0])
y = np.arange(mini[1],maxi[1],stp[1])
x, y = np.meshgrid(x, y)
self.points = np.transpose(np.array([x.flatten(), y.flatten()]))
elif (dims == 2):
stp = float(maxi[0]-mini[0])/float(numpts+1)
x = np.arange((mini[0]+stp),maxi[0],stp)
self.points = np.transpose(np.array([x.flatten()]))
else:
print 'Can not currently do cartesian in any dimension \
except for 2 and 3. Blame meshgrid.'
raise SystemExit
else:
print 'Distribution type not found.'
raise SystemExit
def AssignDep(self, values, gradient=[0]):
## Takes numpy array of values and stores inside the class variable
#print '**Assigning Dependent Data**'
#print
self.values = values[:,np.newaxis]
self.gradient=gradient
def CreateDep(self):
## This creates the dependant from the specified function type
#print '**Creating Dependent Data from Problem Library**'
#print
z = Solve(self.points,self.funct)
self.values = z[:,np.newaxis]
def PlotResults(self, title, pltfile='None'):
## Plots the value results of a 2 or 3 dimensional problem
## Ensure points and values have been created
try:
self.values
except NameError:
print 'Values have not been set.'
print
return
fig = plt.figure()
if (self.dims == 3):
x = self.points[:,0]
y = self.points[:,1]
ax = fig.gca(projection='3d')
surf = ax.tricontour(x.flatten(), y.flatten(),
self.values.real.flatten(),
500, rstride=1, cstride=1,
cmap=cm.coolwarm, linewidth=0,
antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
fig.suptitle('%s Results' % title,
fontsize=14, fontweight='bold')
ax.set_xlabel('X - Independent Variable')
ax.set_ylabel('Y - Independent Variable')
ax.set_zlabel('Z - Dependent Variable')
ax.set_zticklabels([])
## These adjustments are to improve view of the 3D problems when
# the maximum and minimum are set to 500 and -500 for each
# independent dimension respectively.
'''
if (self.funct == 'PW'):
ax.set_zlim([-5000,5000])
elif (self.funct == 'Crate'):
ax.set_zlim([-1000,1000])
elif (self.funct == 'Plane'):
ax.set_zlim([-300000,300000])
'''
elif (self.dims == 2):
x = self.points[:,0].flatten()
y = self.values[:,0].flatten()
plt.plot(x, y, 'ko-')
fig.suptitle('%s Results' % title,
fontsize=14, fontweight='bold')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.xlim(min(x), max(x))
else:
print 'Unable to plot this dimension of points.'
print
return
if (pltfile != 'None'):
pltfile.savefig()
def PlotPoints(self, title, pltfile='None'):
## Dim-1 plot of point locations for visualization
try:
## Ensure points have been created
self.points
except NameError:
print 'Points have not been set.'
print
return
if (self.dims == 3):
fig = plt.figure()
plt.scatter(self.points[:,0], self.points[:,1])
fig.suptitle('%s Point Locations' % title,
fontsize=14, fontweight='bold')
plt.xlabel('X Value')
plt.ylabel('Y Value')
elif (self.dims == 4):
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(self.points[:,0], self.points[:,1],
self.points[:,2], c=c, marker=m)
fig.suptitle('%s Point Locations' % title,
fontsize=14, fontweight='bold')
ax.set_ylabel('X Value')
ax.set_ylabel('Y Value')
ax.set_zlabel('Z Value')
elif (self.dims == 2):
zeros = np.zeros((len(self.points[:,0])), dtype='float')
fig = plt.figure()
plt.scatter(self.points[:,0], zeros)
fig.suptitle('%s Point Locations' % title,
fontsize=14, fontweight='bold')
plt.xlabel('X Value')
plt.ylabel('')
return
else:
print 'Unable to plot this dimension of points.'
print
return
if (pltfile != 'None'):
pltfile.savefig()
def FindError(self, title, pltfile='None', plot=True,
check=False, step=0.00000001):
## Find and plot error of the found values
try:
## Ensure points and values have been created
self.values
except NameError:
print 'Values have not been set.'
return
vals = self.values.flatten()
loc = 1+np.arange(len(vals), dtype='float')
zc = Solve(self.points,self.funct)
error = abs((zc-vals)/(zc+0.000000000001)) * 100
avg = np.average(error)
if check:
for i in range(len(error)):
if (error[i] > 100):
print '**High Percent Error found of', error[i], '**'
print '-Location:', xc[i], yc[i]
print '-Calculated Value:', zc[i]
print '-Found Value:', vals[i]
print '%s Error Information' % title
print '-Average Result Percent Error:', avg
print '-Max Result Percent Error:', np.max(error)
if plot:
fig = plt.figure()
plt.plot(loc, error, 'k')
fig.suptitle('%s Error Per Point' % title,
fontsize=14, fontweight='bold')
plt.xlabel('Point Identifier')
plt.ylabel('Percent Error')
plt.ylim((0,((avg+0.00000000001)*2)))
if (pltfile != 'None'):
pltfile.savefig()
self.error = error
self.actualvalues = zc
if (np.all(self.gradient) != 0):
## Use complex step to check nearby points with found gradient
g = np.empty((len(vals),self.dims-1), dtype='float')
points = np.zeros((len(vals),self.dims-1), dtype='complex')
points += self.points
for D in range(self.dims-1):
points[:,D] += (step*1j)
zs = Solve(points,self.funct)
g[:,D] = zs.imag/ step
points[:,D] = points[:,D].real
gerror = abs((g-self.gradient)/(g+0.00000000000000001)) * 100.
gerror = np.sum(gerror, axis=1)/2
gavg = np.average(gerror)
if check:
for i in range(len(error)):
if (gerror[i] > 100):
print '**High Percent Error found of', gerror[i], '**'
print '-Location:', points[i,:]
print '-Calculated Value:', g[i,:]
print '-Found Value:', self.gradient[i,:]
print '-Average Actual Gradient Percent Error:', gavg
print '-Max Actual Gradient Percent Error:', np.max(gerror)
if plot:
if (self.dims == 2):
col = 1
rows = 1
else:
col = 2
rows = int(self.dims/2)
gbfig, gbax = plt.subplots(col,rows)
gbfig.suptitle('%s Gradient wrt Independent' % title,
fontsize=14, fontweight='bold')
gbax = np.reshape(gbax,((self.dims-1)))
for D in range(self.dims-1):
ming = min(self.gradient[:,D])
ming -= 0.05*abs(ming)
maxg = max(self.gradient[:,D])
maxg += 0.05*abs(ming)
gbax[D].plot(points[:,D].real,g[:,D],'bo',
points[:,D].real,self.gradient[:,D],'rx')
gbax[D].set_xlabel('Independent %s Value' % (D+1))
gbax[D].set_ylabel('Gradient Value')
gbax[D].set_ylim([ming,maxg])
gbax[D].legend(['Complex Step in Function','Interpolation'],
loc=4, prop={'size':8})
if (pltfile != 'None'):
pltfile.savefig()
gfig = plt.figure()
plt.plot(loc, gerror, 'k')
gfig.suptitle('%s Actual Gradient Error Per Point' % title,
fontsize=14, fontweight='bold')
plt.xlabel('Point Identifier')
plt.ylabel('Percent Error')
plt.ylim((0,((gavg+0.0000000000001)*2)))
if (pltfile != 'None'):
pltfile.savefig()
self.gaerror = gerror
print
def CheckGrad(self, title, Interp, itype, pltfile='None', plot=True,
check=False, step=0.00000001, N=5, DistEff=3,
tension=0, bias=0, tight=False):
loc = 1+np.arange(len(self.values), dtype='float')
## Find and plot error of the found values
if (np.all(self.gradient) == 0):
## If the gradient is empty, just leave. Ain't got time for that.
print 'Gradient does not have a solution.'
print
return
PrdiPts = np.empty((len(self.points[:,0]),self.dims-1), dtype='complex')
PrdiPts.real = self.points
gradi = np.empty((len(self.values),self.dims-1), dtype='float')
vals = self.values.reshape((len(self.values)))
for D in range(self.dims-1):
PrdiPts[:,:].imag = 0.
PrdiPts[:,D] = self.points[:,D] + (step*1.0j)
with suppress_stdout():
## Redo interpolation with complex addition but suppress output
if (itype == 'LN'):
zi = Interp(PrdiPts)
elif (itype == 'WN'):
zi = Interp(PrdiPts, N, DistEff)
elif (itype == 'CN'):
zi = Interp(PrdiPts, N)
elif (itype == 'HN'):
zi = Interp(PrdiPts, N, tension, bias, tight)
elif (itype == 'CR'):
zi = Interp(PrdiPts)
gradi[:,D] = zi.imag/ step
## Compare the difference in complex addition with the gradient answer
gerror = abs((gradi-self.gradient)/(gradi+0.000000000000000001)) * 100.
gerror = np.sum(gerror, axis=1)/(self.dims-1)
gavg = np.average(gerror)
if check:
for i in range(len(error)):
if (gerror[i] > 100):
print '**High Percent Error found of', gerror[i], '**'
print '-Location:', PrdiPts[i,:]
print '-Calculated Value:', gradi[i,:]
print '-Found Value:', self.gradient[i,:]
print '%s Gradient Check' % title
print '-Average Gradient Percent Error:', gavg
print '-Max Gradient Percent Error:', np.max(gerror)
print
if plot:
if (self.dims == 2):
col = 1
rows = 1
else:
col = 2
rows = int(self.dims/2)
gbfig, gbax = plt.subplots(col,rows)
gbfig.suptitle('%s Gradient wrt Independent' % title,
fontsize=14, fontweight='bold')
gbax = np.reshape(gbax,((self.dims-1)))
for D in range(self.dims-1):
ming = min(self.gradient[:,D])
ming -= 0.05*abs(ming)
maxg = max(self.gradient[:,D])
maxg += 0.05*abs(ming)
gbax[D].plot(PrdiPts[:,D].real,gradi[:,D],'bo',
PrdiPts[:,D].real,self.gradient[:,D],'rx')
gbax[D].set_xlabel('Independent %s Value' % (D+1))
gbax[D].set_ylabel('Gradient Value')
gbax[D].set_ylim([ming,maxg])
gbax[D].legend(['Complex Step in Interp.','Interpolation'],
loc=4, prop={'size':8})
if (pltfile != 'None'):
pltfile.savefig()
gfig = plt.figure()
plt.plot(loc, gerror, 'k')
gfig.suptitle('%s Gradient Error Per Point' % title,
fontsize=14, fontweight='bold')
plt.xlabel('Point Identifier')
plt.ylabel('Percent Error')
plt.ylim((0,((gavg+0.0000000000001)*2)))
if (pltfile != 'None'):
pltfile.savefig()
self.gcerror = gerror
def PlotAll(self, title, Interp, itype, pltfile='None', erplot=True,
check=False, ptplot=False, step=0.00000001, neighs=5,
DistEff=3, tension=0, bias=0, tight=False):
## This routine runs through all checks and plotting options/
self.PlotResults(title,pltfile)
if ptplot:
self.PlotPoints(title,pltfile)
self.FindError(title,pltfile,erplot,check,step)
self.CheckGrad(title,Interp,itype,pltfile,erplot,check,step,
neighs,DistEff,tension,bias,tight)
# Interpolation Classes ========================================================
'''
The classes inside this section are the main parts of this code. Below are
the interpolation methods all individually defined and ready to use. Most
of the classes are children the the first class below, NNInterpBase. All of
the methods use a KD-Tree to sort the data; this improves the cost of each
query done with them. To query for dependent answers, call methods are set.
To query for gradients, self.gradient methods are set.
'''
class NNInterpBase(object):
## The shared aspects of all nearest neighbor interpolators
def __init__(self, TrnPts, TrnVals, NumLeaves=2):
## TrainPts and TrainVals are the known points and their
# respective values which will be interpolated against.
## Grab the mins and normals of each dimension
self.tpm = np.amin(TrnPts, axis=0)
self.tpr = (np.amax(TrnPts, axis=0) - self.tpm)
self.tvm = np.amin(TrnVals, axis=0)
self.tvr = (np.amax(TrnVals, axis=0) - self.tvm)
## This prevents against colinear data (range = 0)
self.tpr[self.tpr == 0] = 1
self.tvr[self.tvr == 0] = 1
## Normalize all points
self.tp = (TrnPts - self.tpm) / self.tpr
self.tv = (TrnVals - self.tvm) / self.tvr
## Set important variables
self.dims = len(TrnPts[0,:]) + 1
self.ntpts = len(TrnPts[:,0])
'''
print 'Interpolation Input Values'
print '-KDTree Leaves:', NumLeaves
print '-Number of Training Points:', self.ntpts
print
'''
## Make training data into a Tree
leavesz = math.ceil(self.ntpts/(NumLeaves+0.00000000000001))
KData = spatial.cKDTree(self.tp,leafsize=leavesz)
self.KData = KData
class LNInterp(NNInterpBase):
def main(self, PrdPts, nppts, dims, nloc):
## Extra Inputs for Finding the normal are found below
## Number of row vectors needed always dimensions - 1
r = np.arange(dims-1, dtype="int")
## Diagonal counters are found here to speed up finding each normal
da = np.zeros((dims, dims-1), dtype="int")
db = np.zeros((dims, dims-1), dtype="int")
for i in xrange(dims):
da[i] = (r+1+i) % dims
db[i] = (i-r-1) % dims
## Planar vectors need both dep and ind dimensions
trnd = np.concatenate((self.tp[nloc,:] ,
self.tv[nloc].reshape(nppts,dims,1)),
axis=2)
## Set the prddata to a temporary array so it has the same
# dimensions as the training data with the dependant as 0
prdtemp = np.concatenate((PrdPts, \
np.zeros((nppts,1),dtype='float')), 1)
nvect = np.empty((nppts,(dims-1),dims), dtype='float')
for n in range(dims-1): ## Go through each neighbor
## Creates array[neighbor, dimension] from NN results
nvect[:,n,:] = trnd[:,(n+1),:] - trnd[:,n,:]
## Nvec used below to finish a hodge star product
# (in 3D essentially a cross product).
normal = np.prod(nvect[:,r,da], axis=2) - \
np.prod(nvect[:,r,db], axis=2)
## Use the point of the closest neighbor to
# solve for pc - the constant of the n-dimensional plane.
pc = np.einsum('ij, ij->i',trnd[:,0,:],normal)
return normal, prdtemp, pc
def main2D(self, PrdPts, nppts, nloc):
## Need to find a tangent instead of a normal, y=mx+b
d = self.tp[nloc[:,1],0] - self.tp[nloc[:,0],0]
d[abs(d) < 0.0000000000000001] = 100000000000000000000
m = (self.tv[nloc[:,1],0] - self.tv[nloc[:,0],0]) / d
b = self.tv[nloc[:,0],0] - (m * self.tp[nloc[:,0],0])
return m, b
def __call__(self, PredPoints):
## This method uses linear interpolation by defining a plane with
# a set number of nearest neighbors to the predicted
PrdPts = (PredPoints - self.tpm) / self.tpr
nppts = len(PrdPts[:,0])
## Linear interp only uses as many neighbors as it has dimensions
dims = self.dims
## Find them neigbors. Linear only uses #neighs=#dims
## KData query takes (data, #ofneighbors) to determine closest
# training points to predicted data
ndist, nloc = self.KData.query(PrdPts.real ,self.dims)
'''
print 'Linear Plane Nearest Neighbors (LN) KDTree Results'
print '-Number of Predicted Points:', nppts
print '-Number of Neighbors per Predicted Point:', dims
print '-Nearest Neighbor Distance:', np.min(ndist)
print '-Farthest Neighbor Distance:', np.max(ndist)
print
'''
## Need to ensure there are enough dimensions to find the normal with
if (self.dims > 2):
normal, prdtemp, pc = self.main(PrdPts, nppts, self.dims, nloc)
## Set all prdz from values on plane
prdz = (np.einsum('ij, ij->i',prdtemp,normal)-pc)
## Check to see if there are any colinear points and replace them
n0 = np.where(normal[:,-1] == 0)
prdz[n0] = self.tv[nloc[n0,0]]
## Finish computation for the good normals
n = np.where(normal[:,-1] != 0)
prdz[n] = prdz[n]/-normal[n,-1]
else:
m, b = self.main2D(PrdPts, nppts, nloc)
prdz = (m * PrdPts[:,0]) + b
predz = (prdz * self.tvr) + self.tvm
return predz
def gradient(self, PredPoints):
## Extra method to find the gradient at each location of a set of
# supplied predicted points.
PrdPts = (PredPoints - self.tpm) / self.tpr
nppts = len(PrdPts[:,0])
gradient = np.zeros((nppts, self.dims-1), dtype="float")
## Linear interp only uses as many neighbors as it has dimensions
dims = self.dims
## Find them neigbors
ndist, nloc = self.KData.query(PrdPts.real ,self.dims)
## Need to ensure there are enough dimensions to find the normal with
if (self.dims > 2):
normal, prdtemp, pc = self.main(PrdPts, nppts, self.dims, nloc)
if (np.any(normal[:,-1]) == 0):
return gradient
gradient = -normal[:,:-1]/normal[:,-1:]
else:
gradient[:,0], b = self.main2D(PrdPts, nppts, nloc)
grad = gradient * (self.tvr/self.tpr)
return grad
class WNInterp(NNInterpBase):
## Weighted Neighbor Interpolation
def __call__(self, PredPoints, N=5, DistEff=3):
PrdPts = (PredPoints - self.tpm) / self.tpr
nppts = len(PrdPts[:,0])
## Find them neigbors
## KData query takes (data, #ofneighbors) to determine closest
# training points to predicted data
ndist, nloc = self.KData.query(PrdPts.real ,N)
'''
print 'Weighted Nearest Neighbors (WN) KDTree Results'
print '-Number of Predicted Points:', nppts
print '-Number of Neighbors per Predicted Point:', N
print '-Nearest Neighbor Distance:', np.min(ndist)
print '-Farthest Neighbor Distance:', np.max(ndist)
print
'''
## Setup problem
vals = 0.0
pdims = self.dims - 1
dimdiff = np.subtract(PrdPts.reshape(nppts,1,pdims), self.tp[nloc,:])
for D in range(pdims):
if (PrdPts[0,D].imag > 0):
## KD Tree ignores imaginary part, muse redo ndist if complex
ndist = np.sqrt(np.sum((dimdiff**2), axis=2))
vals += 0.0j
## Find the weighted neighbors per defined formula for distance effect
part = ndist**DistEff
sd = np.sum(1.0/part, axis=1)
vals += self.tv[nloc]
wt = np.sum(vals[:,:,0]/part, axis=1)
predz = ((wt/sd) * self.tvr) + self.tvm
return predz
def gradient(self, PredPoints, N=5, DistEff=3):
PrdPts = (PredPoints - self.tpm) / self.tpr
nppts = len(PrdPts[:,0])
## Find them neigbors
ndist, nloc = self.KData.query(PrdPts.real ,N)
## Setup problem
vals = 0.0
pdims = self.dims - 1
dimdiff = np.subtract(PrdPts.reshape(nppts,1,pdims), self.tp[nloc,:])
## Find the weighted neighbors per defined formula for distance effect
part = ndist**DistEff
sd = np.sum(1.0/part, axis=1)
vals += self.tv[nloc]
## Calculate necessaties for gradient
dsd = np.sum((dimdiff/(ndist**(DistEff+2)).reshape(nppts,N,1)),
axis=1).reshape(nppts,1,pdims)
## Reshape a couple things for matrix operations
sumdist = sd.reshape(nppts,1,1)
ndist = ndist.reshape(nppts,N,1)
## Solve for gradient
const = (DistEff/(sd*sd)).reshape(nppts,1)
gradient = (const*np.sum((vals/(ndist**DistEff)) * \
(dsd-(sumdist*dimdiff/(ndist*ndist))), axis=1))
grad = gradient * (self.tvr/self.tpr)
return grad
class CNInterp(NNInterpBase):
## Cosine Neighbor Interpolation
def main(self, PrdPts, nppts, D, N, neighvals):
orgneighs = np.empty((nppts,N,self.dims), dtype='float')
anppts = np.arange(nppts)
for t in range(nppts):
## I want this gone but can't figure out sorting
orgneighs[t,:,:] = neighvals[t,neighvals[t,:,D].argsort(),:]
## Make some temporary variables
tprd = PrdPts.reshape(nppts,1,(self.dims-1))
podiff = np.subtract(tprd[:,:,D], orgneighs[:,:,D])+0.00000000000001
## Gives the indices of the closest neighbors to each prdpt per dim.
cnd = np.argmin((np.abs(podiff)), axis=1)
## If the closest neighbor per dim is a smaller value, add 1.
cnd += np.ceil((podiff[anppts,cnd].real) / \
(np.abs(podiff[anppts,cnd].real*2)))
## Stay in the range!
cnd[cnd == 0] = 1
cnd[cnd == N] = N-1
## Mark upper and lower closest neighbors
zu = orgneighs[anppts,cnd,-1]
zl = orgneighs[anppts,(cnd-1),-1]
## Need to ensure no colinear data causes a divide by 0
ddiff = (orgneighs[anppts,cnd,D]-orgneighs[anppts,(cnd-1),D])
ddiff[ddiff < 0.00000000001] = podiff[:,(cnd-1)].real*2.
ddiff = 1./ddiff
diff = podiff[anppts,(cnd-1)] * ddiff
return zu, zl, diff, ddiff
def __call__(self, PredPoints, N=5):
PrdPts = (PredPoints - self.tpm) / self.tpr
nppts = len(PrdPts[:,0])
## Find them neigbors
## KData query takes (data, #ofneighbors) to determine closest
# training points to predicted data
ndist, nloc = self.KData.query(PrdPts.real ,N)
'''
print 'Cosine Nearest Neighbors (CN) KDTree Results'
print '-Number of Predicted Points:', nppts
print '-Number of Neighbors per Predicted Point:', N
print '-Nearest Neighbor Distance:', np.min(ndist)
print '-Farthest Neighbor Distance:', np.max(ndist)
print
'''
## This sorts the rows by the values in the column specified.
## The neighvals dim is [neigh#, dimension]
neighvals = np.concatenate((self.tp[nloc,:] ,
self.tv[nloc,:]),
axis=2)
tprdz = np.zeros((nppts), dtype='complex')
for D in range(self.dims-1):
zu, zl, diff, ddiff = self.main(PrdPts, nppts, D, N, neighvals)
## Take info from main function and insert into the cosine funct.
mu2 = (1-np.cos(np.pi*diff))/2
tprdz += zu * mu2 + zl * (1-mu2)
## Average found solutions and remove normalization
predz = ((tprdz/(D+1)) * self.tvr) + self.tvm
return predz
def gradient(self, PredPoints, N=5):
PrdPts = (PredPoints - self.tpm) / self.tpr
nppts = len(PrdPts[:,0])
gradient = np.zeros((nppts, self.dims-1), dtype="float")
## Find them neigbors
ndist, nloc = self.KData.query(PrdPts.real ,N)
## This sorts the rows by the values in the column specified.
## The neighvals dim is [neigh#, dimension]
neighvals = np.concatenate((self.tp[nloc,:] ,
self.tv[nloc,:]),
axis=2)
for D in range(self.dims-1):
zu, zl, diff, ddiff = self.main(PrdPts, nppts, D, N, neighvals)
## Take info from main function and solve for grad of cosine funct.
gradient[:,D] = (np.pi/2)*(zu-zl)*ddiff* \
np.sin(np.pi*diff.real)/(self.dims-1)
## Remove normalization
grad = gradient * (self.tvr/self.tpr)
return grad
class HNInterp(NNInterpBase):
## Hermite Neighbor Interpolation
def HermFunctRes(self, y, mu, tension, bias):
## Should have 4 neighbor values (y) and percent distance along line
# from y1 and y2 to get the wanted value (mu). Bias and tension
# are optional values. This one returns the dependent values.
mu2 = mu * mu
mu3 = mu2 * mu
m0 = (y[:,1]-y[:,0])*(1+bias)*(1-tension)/2
m0 += (y[:,2]-y[:,1])*(1-bias)*(1-tension)/2
m1 = (y[:,2]-y[:,1])*(1+bias)*(1-tension)/2
m1 += (y[:,3]-y[:,2])*(1-bias)*(1-tension)/2
a0 = 2*mu3 - 3*mu2 + 1
a1 = mu3 - 2*mu2 + mu
a2 = mu3 - mu2
a3 = -2*mu3 + 3*mu2
return (a0*y[:,1] + a1*m0 + a2*m1 + a3*y[:,2])
def HermFunctGrad(self, y, mu, dmu, tension, bias):
## Should have 4 neighbor values (y) and percent distance along line
# from y1 and y2 to get the wanted value (mu). Bias and tension
# are optional values. This one returns the gradient values.
mu2 = mu * mu
m0 = (y[:,1]-y[:,0])*(1+bias)*(1-tension)/2
m0 += (y[:,2]-y[:,1])*(1-bias)*(1-tension)/2
m1 = (y[:,2]-y[:,1])*(1+bias)*(1-tension)/2
m1 += (y[:,3]-y[:,2])*(1-bias)*(1-tension)/2
## Derivatives of the 'a's
b0 = 6*mu2 - 6*mu
b1 = 3*mu2 - 4*mu + 1
b2 = 3*mu2 - 2*mu
b3 = -6*mu2 + 6*mu
return ((dmu*(b0*y[:,1]+b1*m0+b2*m1+b3*y[:,2]))/(self.dims-1)).real
def main(self, PrdPts, nppts, D, N, u, l, neighvals):
orgneighs = np.empty((nppts,N,self.dims), dtype='float')
anppts = np.arange(nppts)
y = np.empty((nppts,4), dtype='float')
for t in range(nppts):
## I want this gone but can't figure out sorting
orgneighs[t,:,:] = neighvals[t,neighvals[t,:,D].argsort(),:]
## Make some temporary variables
tprd = PrdPts.reshape(nppts,1,(self.dims-1))
podiff = np.subtract(tprd[:,:,D], orgneighs[:,:,D])+0.000000000001
## Gives the indices of the closest neighbors to each prdpt per dim.
cnd = np.argmin((np.abs(podiff)), axis=1)
## If the closest neighbor per dim is a smaller value, add 1.
cnd += np.ceil(podiff[anppts,cnd].real / \
np.abs((podiff[anppts,cnd].real)*2))
## Stay in the range!
cnd[cnd <= 1] = 2
cnd[cnd >= (N-1)] = N-2
## Find location of value in min and max of neighvals to be used
ddiff = (orgneighs[anppts,(cnd+u),D]-orgneighs[anppts,(cnd-l),D])
## Avoid colinear causing /0
ddiff[ddiff < 0.000000001] = podiff[:,(cnd-l)].real*2.
ddiff = 1./ddiff
diff = podiff[anppts,(cnd-l)] * ddiff
for n in range(4):
## Only need 4 inputs. Would like to remove this sometime
y[:,n] = orgneighs[anppts,(cnd-2+n),-1]
return y, diff, ddiff
def __call__(self, PredPoints, N=5, tension=0, bias=0, tight=False):
## Traindata has n dimensions, prddata has n-1 dimensions because last
# dimension is the dependent one we are solving for.
## N neighbors will be found but only 4 will be used per dimension
PrdPts = (PredPoints - self.tpm) / self.tpr
nppts = len(PrdPts[:,0])
tprdz = np.zeros((nppts), dtype='complex')
u = 1
l = 2
if tight:
## Added this because tight works much better with smaller problems
# but very badly with larger problems
u -= 1
l -= 1
if (N < 5):
## Hermite requires at least 5 neighbors
N = 5
## Find them neigbors
## KData query takes (data, #ofneighbors) to determine closest
# training points to predicted data
ndist, nloc = self.KData.query(PrdPts.real ,N)
'''
print 'Hermite Nearest Neighbors (HN) KDTree Results'
print '-Number of Predicted Points:', nppts
print '-Number of Neighbors per Predicted Point:', N
print '-Nearest Neighbor Distance:', np.min(ndist)
print '-Farthest Neighbor Distance:', np.max(ndist)
print
'''
## This sorts the rows by the values in the column specified.
## The neighvals dim is [neigh#, dimension]
neighvals = np.concatenate((self.tp[nloc,:] ,
self.tv[nloc,:]),
axis=2)
for D in range(self.dims-1):
y, diff, ddiff = self.main(PrdPts, nppts, D, N, u, l, neighvals)
## Find necessary values and put into the Hermite function
tprdz += self.HermFunctRes(y,diff,tension,bias)
## Average found solutions and remove normalization
predz = ((tprdz/(D+1)) * self.tvr) + self.tvm
return predz
def gradient(self, PredPoints, N=5, tension=0, bias=0, tight=False):
## Traindata has n dimensions, prddata has n-1 dimensions because last
# dimension is the dependent one we are solving for.
## N neighbors will be found but only 4 will be used per dimension
PrdPts = (PredPoints - self.tpm) / self.tpr
nppts = len(PrdPts[:,0])
gradient = np.zeros((nppts, self.dims-1), dtype="float")
u = 1
l = 2
if tight:
## Added this because tight works much better with smaller problems
# but very badly with larger problems
u -= 1
l -= 1
if (N < 5):
## Hermite requires at least 5 neighbors
N = 5
## Find them neigbors
ndist, nloc = self.KData.query(PrdPts.real ,N)
## This sorts the rows by the values in the column specified.
## The neighvals dim is [neigh#, dimension]
neighvals = np.concatenate((self.tp[nloc,:] ,
self.tv[nloc,:]),
axis=2)
for D in range(self.dims-1):
y, diff, ddiff = self.main(PrdPts, nppts, D, N, u, l, neighvals)
## Find necessary variables and throw into the Hermite funct.
gradient[:,D] = self.HermFunctGrad(y,diff,ddiff,tension,bias)
## Remove normalization
grad = gradient * (self.tvr/self.tpr)
return grad
class CRInterp(object):
## Compactly Supported Radial Basis Function
def FindR(self, npp, T, loc):
R = np.zeros((npp, self.ntpts), dtype="complex")
## Choose type of CRBF R matrix
if (self.comp == -1):
## Comp #1 - a
Cf = (1.-T)**5
Cb = (8.+(40.*T)+(48.*T*T)+ \
(72.*T*T*T)+(5.*T*T*T*T))
elif (self.comp == -2):
## Comp #2
Cf = (1.-T)**6.
Cb = (6.+(36.*T)+(82.*T*T)+(72.*T*T*T)+ \
(30.*T*T*T*T)+(5.*T*T*T*T*T))
elif (self.comp == -3):
## Comp #3
Cf = T**0.
Cb = np.sqrt((T*T)+1.)
else:
## The above options did not specify a dimensional requirement
# in the paper found but the rest are said to only be guaranteed
# as positive definite iff the dimensional requirements are.
# Because of this, the user can select 0 through 4 to adjust to a
# level of order trying to be attained.
if (self.dims <= 2):
if (self.comp == 0):
# This starts the dk comps, here d=1, k=0
Cf = 1.-T
Cb = np.ones((len(T[:,0]),len(T[0,:])), dtype="complex")
elif (self.comp == 1):
Cf = (1.-T)*(1.-T)*(1.-T)/12.
Cb = 1.+(3.*T)
elif (self.comp == 2):
Cf = ((1.-T)**5)/840.
Cb = 3.+(15.*T)+(24.*T*T)
elif (self.comp == 3):
Cf = ((1.-T)**7)/151200.
Cb = 15.+(105.*T)+(285.*T*T)+(315.*T*T*T)
elif (self.comp == 4):
Cf = ((1.-T)**9)/51891840.
Cb = 105.+(945.*T)+(3555.*T*T)+(6795.*T*T*T)+\
(5760.*T*T*T*T)
elif (self.dims <= 4):
if (self.comp == 0):
Cf = (1.-T)
Cb = (1.-T)
elif (self.comp == 1):
Cf = ((1.-T)**4)/20.
Cb = 1.+(4.*T)
elif (self.comp == 2):
Cf = ((1.-T)**6)/1680.
Cb = 3.+(18.*T)+(35.*T*T)
elif (self.comp == 3):
Cf = ((1.-T)**8)/332640.
Cb = 15.+(120.*T)+(375.*T*T)+(480.*T*T*T)
elif (self.comp == 4):
Cf = ((1.-T)**10)/121080960.
Cb = (105.+(1050.*T)+(4410.*T*T)+(9450.*T*T*T)+\
(9009.*T*T*T*T))
elif (self.dims <= 6):
if (self.comp == 0):
Cf = (1.-T)*(1.-T)
Cb = (1.-T)
elif (self.comp == 1):
Cf = ((1.-T)**5)/30.
Cb = 1.+(5.*T)
elif (self.comp == 2):
Cf = ((1.-T)**7)/3024.
Cb = 3.+(21.*T)+(48.*T*T)
elif (self.comp == 3):
Cf = ((1.-T)**9)/665280.
Cb = 15.+(135.*T)+(477.*T*T)+(693.*T*T*T)
elif (self.comp == 4):
Cf = ((1.-T)**11)/259459200.
Cb = (105.+(1155.*T)+(5355.*T*T)+(12705.*T*T*T)+\
(13440.*T*T*T*T))
else:
## Although not listed, this is ideally for 8 dim or less
if (self.comp == 0):
Cf = (1.-T)*(1.-T)
Cb = (1.-T)*(1.-T)
elif (self.comp == 1):
Cf = ((1.-T)**6)/42.
Cb = 1.+(6.*T)
elif (self.comp == 2):
Cf = ((1.-T)**8)/5040.
Cb = 3.+(24.*T)+(63.*T*T)
elif (self.comp == 3):
Cf = ((1.-T)**10)/1235520.
Cb = 15.+(150.*T)+(591.*T*T)+(960.*T*T*T)
elif (self.comp == 4):
Cf = ((1.-T)**12)/518918400.
Cb = (105.+(1260.*T)+(6390.*T*T)+(16620.*T*T*T)+\
(19305.*T*T*T*T))
for i in xrange(npp):
R[i,loc[i,:-1]] = Cf[i,:] * Cb[i,:]
return R
def FinddR(self, PrdPts, ploc, pdist):
T = (pdist[:,:-1]/pdist[:,-1:])
## Solve for the gradient analytically
## The first quantity needed is dRp/dt
if (self.comp == -1):
frnt = (1.-T)**4
dRp = frnt*((-5.*(8. + (40.*T) + (48.*T*T) + \
(72.*T*T*T) + (5.*T*T*T*T))) + \
((1.-T) * (40. + (96.*T) + \
(216.*T*T) + (20.*T*T*T))))
elif (self.comp == -2):
frnt = (1.-T)**5
dRp = frnt*((-6. * (6. + (36.*T) + \
(82.*T*T) + (72.*T*T*T) + \
(30.*T*T*T*T) + (5.*T*T*T*T*T))) + \
((1.-T)) * (36. + (164.*T) + \
(216.*T*T) + (120.*T*T*T) + \
(25.*T*T*T*T)))
elif (self.comp == -3):
dRp = T/np.sqrt((T*T)*1.)
else:
## Start dim dependent comps, review first occurance for more info
if (self.dims <= 2):
if (self.comp == 0):
# This starts the dk comps(Wendland Functs), here d=1, k=0
dRp = -1.
elif (self.comp == 1):
dRp = -T*(1.-T)*(1.-T)
elif (self.comp == 2):
frnt = ((1.-T)**4)/-20.
dRp = frnt*(T+(4.*T*T))
elif (self.comp == 3):
frnt = ((1.-T)**6)/-1680.
dRp = frnt*((3.*T)+(18.*T*T)+(35.*T*T*T))
elif (self.comp == 4):
frnt = ((1.-T)**8)/-22176.
dRp = frnt*(T+(8.*T*T)+(25.*T*T*T)+(32.*T*T*T*T))
elif (self.dims <= 4):
if (self.comp == 0):
dRp = -2.*(1-T)
elif (self.comp == 1):
dRp = -T*(1.-T)*(1.-T)*(1.-T)
elif (self.comp == 2):
frnt = ((1.-T)**5)/-30.
dRp = frnt*(T+(5.*T*T))
elif (self.comp == 3):
frnt = ((1.-T)**7)/-1008.
dRp = frnt*(T+(7.*T*T)+(16.*T*T*T))
elif (self.comp == 4):
frnt = ((1.-T)**9)/-221760.
dRp = frnt*((5.*T)+(45.*T*T)+(159.*T*T*T)+(231.*T*T*T*T))
elif (self.dims <= 6):
if (self.comp == 0):
dRp = -3.*(1.-T)*(1.-T)
elif (self.comp == 1):
dRp = -T*((1.-T)**4)
elif (self.comp == 2):
frnt = ((1.-T)**6)/-42.
dRp = frnt*(T+(6.*T*T))
elif (self.comp == 3):
frnt = ((1.-T)**8)/-1680.
dRp = frnt*(T+(8.*T*T)+(21.*T*T*T))
elif (self.comp == 4):
frnt = ((1.-T)**10)/-411840.
dRp = frnt*((5.*T)+(50.*T*T)+(197.*T*T*T)+(320.*T*T*T*T))
else:
## Although not listed, this is ideally for 8 dim or less
if (self.comp == 0):
dRp = -4.*(1.-T)*(1.-T)*(1.-T)
elif (self.comp == 1):
dRp = -T*((1.-T)**5)
elif (self.comp == 2):
frnt = ((1.-T)**7)/-56.
dRp = frnt*(T+(7.*T*T))
elif (self.comp == 3):
frnt = ((1.-T)**9)/-7920.
dRp = frnt*((3.*T)+(27.*T*T)+(80.*T*T*T))
elif (self.comp == 4):
frnt = ((1.-T)**11)/-720720.
dRp = frnt*((5.*T)+(55.*T*T)+(239.*T*T*T)+(429.*T*T*T*T))
## Now need dt/dx
xpi = np.subtract(PrdPts, self.tp[ploc[:,:-1],:])
xpm = PrdPts - self.tp[ploc[:,-1:],:]
dtx = (xpi-(T*T*xpm))/ \
(pdist[:,-1:,:]*pdist[:,-1:,:]*T)
## The gradient then is the summation across neighs of w*df/dt*dt/dx
return np.sum((dRp * dtx * self.weights[ploc[:,:-1]]), axis=1)
def __init__(self, TrnPts, TrnVals, NumLeaves=2, N=5, comp=2):
## TrainPts and TrainVals are the known points and their
# respective values which will be interpolated against.
## Grab the min and range of each dimension
self.tpm = np.floor(np.amin(TrnPts, axis=0))
self.tpr = np.ceil(np.amax(TrnPts, axis=0) - self.tpm)
## This prevents against colinear data (range = 0)
self.tpr[self.tpr == 0] = 1
## Normalize all points
self.tp = (TrnPts - self.tpm) / self.tpr
self.tv = TrnVals
self.dims = len(TrnPts[0,:]) + 1
self.ntpts = len(TrnPts[:,0])
## Comp is an arbitrary value that pics a function to use
self.comp = comp
## The order of each comp can be found from the dims and its value
order = int(np.floor((self.dims-1)/2) + (3*comp) + 1)
if (comp < 0):
## The two comps that do not follow the function above
if (comp == -1):
order = 9
else:
order = 11
## Uses a KD Tree to set the distances, locations, and values
# of the closest neighbors to each point in the
'''
print 'Interpolation Input Values'
print '-Comp Equation Used:', comp
print '-Resulting order:', order
print '-KDTree Leaves:', NumLeaves
print '-Number of Training Points:', self.ntpts
print
'''
## Make into training data into a Tree
leavesz = math.ceil(self.ntpts/NumLeaves)
## Start by creating a KDTree around the training points
KData = spatial.cKDTree(self.tp,leafsize=leavesz)
## For weights, first find the training points radial neighbors
tdist, tloc = KData.query(self.tp, N, 0.0, 2)
Tt = tdist[:,:-1]/tdist[:,-1:]
## Next determine weight matrix
Rt = self.FindR(self.ntpts, Tt, tloc)
weights = (spsl.spsolve(csc_matrix(Rt), self.tv))[:,np.newaxis]
## KData query takes (data, #ofneighbors) to determine closest
# training points to predicted data
self.N = N
self.KData = KData
self.weights = weights
def __call__(self, PredPoints):
PrdPts = (PredPoints - self.tpm) / self.tpr
nppts = len(PrdPts[:,0])
## Setup prediction points and find their radial neighbors
pdist, ploc = self.KData.query(PrdPts.real, self.N)
## Check if complex step is being run
if (np.any(PrdPts[0,:].imag) > 0):
dimdiff = np.subtract(PrdPts.reshape(nppts,1,(self.dims-1)),
self.tp[ploc,:])
## KD Tree ignores imaginary part, muse redo ndist if complex
pdist = np.sqrt(np.sum((dimdiff*dimdiff), axis=2))
## Take farthest distance of each point
Tp = pdist[:,:-1]/pdist[:,-1:]
'''
print 'Compactly Supported Radial Basis Function (CR) KDTree Results'
print '-Number of Predicted Points:', nppts
print '-Number of Radial Neighbers per Predicted Point:', self.N
print '-Minimum Compact Support Domain Radius:', min(pdist[:,-1:])
print '-Maximum Compact Support Domain Radius:', max(pdist[:,-1:])
print
'''
Rp = self.FindR(nppts, Tp, ploc)
predz = np.dot(Rp, self.weights).reshape(nppts)
return predz
def gradient(self, PredPoints):
PrdPts = (PredPoints - self.tpm) / self.tpr
#PrdPts = PredPoints
nppts = len(PrdPts[:,0])
## Setup prediction points and find their radial neighbors
pdist, ploc = self.KData.query(PrdPts, self.N)
## Find Gradient
grad = self.FinddR(PrdPts[:,np.newaxis,:], ploc,
pdist[:,:,np.newaxis])/self.tpr
return grad
## Check and Run - Open Methods ================================================
'''
The functions in this section are unnecessary, but can be useful even if this
code is wrapped into another program. Some may not be able to be run without
a valid problem type.
'''
def CheckInputs(neighbors, trnpoints, NumLeaves, maximum, minimum,
problem, dimensions, DistanceEffect, tension, bias):
## The first checks the inputs for default 0s or trips that may
# cause errors so that it can fix them.
## Organize inputs
if (dimensions == 0):
if((problem == '2D3O') or (problem == '2D5O')):
dimensions = 2
elif((problem == 'Plane') or (problem == 'PW') or (problem == 'Crate')):
dimensions = 3
elif((problem == '5D2O') or (problem == '5D4O')):
dimensions = 5
else:
print 'Problem type %s does not exist.' % problem
raise SystemExit
if (neighbors == 0):
neighbors = max(int(trnpoints*dimensions/1500), min(10, trnpoints))
print 'Number of neighbors has been changed to %s' % neighbors
print
if (NumLeaves == 0):
NumLeaves = max(int(neighbors*5), 2)
print 'Number of KD-Tree leaves has been changed to %s' % NumLeaves
print
if (NumLeaves > (trnpoints/neighbors)):
## Can not have more leaves than training data points. Also
# need to ensure there will be enough neighbors in each leaf
NumLeaves = max((trnpoints // (neighbors*1.5), 2))
print 'Number of KD-Tree leaves has been changed to %s' % NumLeaves
print
if (NumLeaves > trnpoints):
print 'The problem has too few training points for'
print 'its number of dimensions.'
raise SystemExit
if (len(maximum) != (dimensions-1)):
print "Due to being incorrectly inputted, the program is now"
print "adjusting the maximum and minimum settings."
print
mini = minimum[0]
maxi = maximum[0]
minimum = np.zeros((dimensions-1), dtype="int")
maximum = np.zeros((dimensions-1), dtype="int")
for D in xrange(dimensions-1):
minimum[D] = mini
maximum[D] = maxi
if ((trnpoints*dimensions) < 100):
tight = True # Default algorithm had only true, change if bad
# results with neighs << trnpoints or a high dimension (>3)
else:
tight = False
return problem, dimensions, neighbors, DistanceEffect, tension, \
bias, tight, NumLeaves, maximum, minimum
def RunTestCode():
print
print '^---- N Dimensional Interpolation ----^'
print
## Check and shorten inputs for ease of typing:
# pr=problem, dim=dimensions, N=neighbors, DE=DistanceEffect,
# t=tension, b=bias, tt=tight, NL=NumLeaves, maxi=maximum, mini=minimum
pr, dim, N, DE, t, b, tt, NL, maxi, mini = \
CheckInputs(neighbors, trnpoints, NumLeaves, maximum, minimum,
problem, dimensions, DistanceEffect, tension, bias)
## Can override tt here
## Create the Independent Data
train = N_Data(mini, maxi, trnpoints, pr, trndist, dim)
actul = N_Data(mini, maxi, (trnpoints*AbyT), pr, trndist, dim)
predL = N_Data(mini, maxi, prdpoints, pr, prddist, dim)
predW = cp.deepcopy(predL)
predC = cp.deepcopy(predL)
predH = cp.deepcopy(predL)
predR = cp.deepcopy(predL)
#predRbf = cp.deepcopy(predL)
## Set Dependents for Training Data and Plot
train.CreateDep()
actul.CreateDep()
# Setup Interpolation Methods around Training Points
p0 = time.time()
trainLNInt = LNInterp(train.points, train.values, NL)
p1 = time.time()
trainWNInt = WNInterp(train.points, train.values, NL)
p2 = time.time()
trainCNInt = CNInterp(train.points, train.values, NL)
p3 = time.time()
trainHNInt = HNInterp(train.points, train.values, NL)
p4 = time.time()
trainCRInt = CRInterp(train.points, train.values, NL, N, comp)
p5 = time.time()
#rbfi = interp.Rbf(train.points[:,0], train.points[:,1], train.values[:,0], function='multiquadric')
#prbf = time.time()
print
print '^---- Running Interpolation Code ----^'
print
# Perform Interpolation on Predicted Points
t0 = time.time()
prdzL = trainLNInt(predL.points)
tp5 = time.time()
prdgL = trainLNInt.gradient(predL.points)
t1 = time.time()
prdzW = trainWNInt(predW.points, N, DE)
t1p5 = time.time()
prdgW = trainWNInt.gradient(predW.points, N, DE)
t2 = time.time()
prdzC = trainCNInt(predC.points, N)
t2p5 = time.time()
prdgC = trainCNInt.gradient(predC.points, N)
t3 = time.time()
prdzH = trainHNInt(predH.points, N, t, b, tt)
t3p5 = time.time()
prdgH = trainHNInt.gradient(predH.points, N, t, b, tt)
t4 = time.time()
prdzR = trainCRInt(predR.points)
t4p5 = time.time()
prdgR = trainCRInt.gradient(predR.points)
t5 = time.time()
#prdzrbf = rbfi(predRbf.points[:,0],predRbf.points[:,1])
#trbf = time.time()
## Assign all Dependents to Check Plots and Error
predL.AssignDep(prdzL, prdgL)
predW.AssignDep(prdzW, prdgW)
predC.AssignDep(prdzC, prdgC)
predH.AssignDep(prdzH, prdgH)
predR.AssignDep(prdzR, prdgR)
#predRbf.AssignDep(prdzrbf, [0])
if CheckResults:
## Plot All Results, Point Locations, and Error. Since this will
# probably vary greatly per analysis, this function was not commented
# a lot and was just written without much care for aesthetics or cost.
print
print '^---- Checking Results ----^'
print
if (dim == 3):
actul.PlotResults('Actual Data')
train.PlotResults('Training Data', pp)
predL.PlotAll('LN Predicted Data', trainLNInt, 'LN',
pltfile='None', erplot=erplot, check=False, ptplot = False,
step=step, neighs=N, DistEff=DE, tension=t, bias=b, tight=tt)
predW.PlotAll('WN Predicted Data', trainWNInt, 'WN',
pltfile='None', erplot=erplot, check=False, ptplot = False,
step=step, neighs=N, DistEff=DE, tension=t, bias=b, tight=tt)
predC.PlotAll('CN Predicted Data', trainCNInt, 'CN',
pltfile='None', erplot=erplot, check=False, ptplot = False,
step=step, neighs=N, DistEff=DE, tension=t, bias=b, tight=tt)
predH.PlotAll('HN Predicted Data', trainHNInt, 'HN',
pltfile='None', erplot=erplot, check=False, ptplot = False,
step=step, neighs=N, DistEff=DE, tension=t, bias=b, tight=tt)
predR.PlotAll('CR Predicted Data', trainCRInt, 'CR',
pltfile='None', erplot=erplot, check=False, ptplot = False,
step=step, neighs=N, DistEff=DE, tension=t, bias=b, tight=tt)
# predRbf.PlotResults('RBF Predicted Data', pltfile='None')
# predRbf.FindError('RBF Predicted Data', pltfile='None', plot=True,
# check=False, step=0.00000001)
elif (dim == 2):
fig = plt.figure()
ax = plt.subplot(111)
Ax = actul.points[:,0].flatten()
Ay = actul.values[:,0].flatten()
Tx = train.points[:,0].flatten()
Ty = train.values[:,0].flatten()
Lx = predL.points[:,0].flatten()
Ly = predL.values[:,0].flatten()
Wx = predW.points[:,0].flatten()
Wy = predW.values[:,0].flatten()
Cx = predC.points[:,0].flatten().real
Cy = predC.values[:,0].flatten().real
Hx = predH.points[:,0].flatten().real
Hy = predH.values[:,0].flatten().real
Rx = predR.points[:,0].flatten().real
Ry = predR.values[:,0].flatten().real
xmi = np.min(Ax)
xma = np.max(Ax)
ymi = np.min(Ay)
yma = np.max(Ay)
ax.plot(Tx, Ty, 'bo', label='Training')
ax.plot(Ax, Ay, 'k-', linewidth=2., label='Actual')
ax.plot(Lx, Ly, 'm--', linewidth=2., label='Linear')
#ax.plot(Wx, Wy, '--', linewidth=2., color=[0.,.38,1.], label='Weighted')
#ax.plot(Cx, Cy, 'g--', linewidth=2., label='Cosine')
#ax.plot(Hx, Hy, 'r--', linewidth=2., label='Hermite')
#ax.plot(Rx, Ry, '--', linewidth=2., color=[1.,.48,0.], label='CS-RBF')
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
ax.set_title('%s Predicted Data Results' % problem,
fontsize=16, fontweight='bold')
ax.set_xlabel('Independent Variable', fontsize=14)
ax.set_ylabel('Dependent Variable', fontsize=14)
plt.tick_params(labelsize=14)
plt.xlim(xmi, xma)
plt.ylim(ymi, yma)
if (allplot == True):
fig = plt.figure()
title = 'Linear'
Px = predL.points[:,0].flatten()
Py = predL.values[:,0].flatten()
plt.plot(Ax, Ay, 'k-', Px, Py, 'r-', Tx, Ty, 'bo')
fig.suptitle('%s Data Results' % title,
fontsize=14, fontweight='bold')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.xlim(xmi, xma)
plt.ylim(ymi, yma)
plt.legend(['Actual', 'Predicted', 'Training'], loc='upper left')
fig = plt.figure()
title = 'Weighted'
Px = predW.points[:,0].flatten()
Py = predW.values[:,0].flatten()
plt.plot(Ax, Ay, 'k-', Px, Py, 'r-', Tx, Ty, 'bo')
fig.suptitle('%s Data Results' % title,
fontsize=14, fontweight='bold')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.xlim(xmi, xma)
plt.ylim(ymi, yma)
plt.legend(['Actual', 'Predicted', 'Training'], loc='upper left')
fig = plt.figure()
title = 'Cosine'
Px = predC.points[:,0].flatten().real
Py = predC.values[:,0].flatten().real
plt.plot(Ax, Ay, 'k-', Px, Py, 'r-', Tx, Ty, 'bo')
fig.suptitle('%s Data Results' % title,
fontsize=14, fontweight='bold')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.xlim(xmi, xma)
plt.ylim(ymi, yma)
plt.legend(['Actual', 'Predicted', 'Training'], loc='upper left')
fig = plt.figure()
title = 'Hermite'
Px = predH.points[:,0].flatten().real
Py = predH.values[:,0].flatten().real
plt.plot(Ax, Ay, 'k-', Px, Py, 'r-', Tx, Ty, 'bo')
fig.suptitle('%s Data Results' % title,
fontsize=14, fontweight='bold')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.xlim(xmi, xma)
plt.ylim(ymi, yma)
plt.legend(['Actual', 'Predicted', 'Training'], loc='upper left')
fig = plt.figure()
title = 'CRBF'
Px = predR.points[:,0].flatten().real
Py = predR.values[:,0].flatten().real
plt.plot(Ax, Ay, 'k-', Px, Py, 'r-', Tx, Ty, 'bo')
fig.suptitle('%s Data Results' % title,
fontsize=14, fontweight='bold')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.xlim(xmi, xma)
plt.ylim(ymi, yma)
plt.legend(['Actual', 'Predicted', 'Training'], loc='upper left')
predL.FindError('LN Predicted Data', 'None', erplot, False)
predL.CheckGrad('LN Predicted Data',trainLNInt,'LN',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
predW.FindError('WN Predicted Data', 'None', erplot, False)
predW.CheckGrad('WN Predicted Data',trainWNInt,'WN',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
predC.FindError('CN Predicted Data', 'None', erplot, False)
predC.CheckGrad('CN Predicted Data',trainCNInt,'CN',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
predH.FindError('HN Predicted Data', 'None', erplot, False)
predH.CheckGrad('HN Predicted Data',trainHNInt,'HN',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
predR.FindError('CR Predicted Data', 'None', erplot, False)
predR.CheckGrad('CR Predicted Data',trainCRInt,'CR',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
else:
predL.FindError('LN Predicted Data', 'None', erplot, False)
predL.CheckGrad('LN Predicted Data',trainLNInt,'LN',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
predW.FindError('WN Predicted Data', 'None', erplot, False)
predW.CheckGrad('WN Predicted Data',trainWNInt,'WN',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
predC.FindError('CN Predicted Data', 'None', erplot, False)
predC.CheckGrad('CN Predicted Data',trainCNInt,'CN',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
predH.FindError('HN Predicted Data', 'None', erplot, False)
predH.CheckGrad('HN Predicted Data',trainHNInt,'HN',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
predR.FindError('CR Predicted Data', 'None', erplot, False)
predR.CheckGrad('CR Predicted Data',trainCRInt,'CR',
pltfile='None',plot=erplot,check=False,
step=step,N=N,DistEff=DE,tension=t,bias=b,tight=tt)
print '<< Run Times >>'
print
print '-LN Interpolator Setup:', (p1-p0)
print '-LN Interpolator Value Query:', (tp5-t0)
print '-LN Interpolator Gradient Query:', (t1-tp5)
print
print '-WN Interpolator Setup:', (p2-p1)
print '-WN Interpolator Value Query:', (t1p5-t1)
print '-WN Interpolator Gradient Query:', (t2-t1p5)
print
print '-CN Interpolator Setup:', (p3-p2)
print '-CN Interpolator Value Query:', (t2p5-t2)
print '-CN Interpolator Gradient Query:', (t3-t2p5)
print
print '-HN Interpolator Setup:', (p4-p3)
print '-HN Interpolator Value Query:', (t3p5-t3)
print '-HN Interpolator Gradient Query:', (t4-t3p5)
print
print '-CR Interpolator Setup:', (p5-p4)
print '-CR Interpolator Value Query:', (t4p5-t4)
print '-CR Interpolator Gradient Query:', (t5-t4p5)
print
'''
print '-RBF Interpolator Setup:', (prbf-p5)
print '-RBF Interpolator Value Query:', (trbf-t5)
print
with open("RBFTimes.txt", "a") as efile:
efile.write("Number of Training Points:"+str(len(train.points[:,0]))+"\n")
efile.write("CSRBF Setup:"+str(p5-p4)+"\n")
efile.write("CSRBF Query:"+str(t4p5-t4)+"\n")
efile.write("RBF Setup:"+str(prbf-p5)+"\n")
efile.write("RBF Query:"+str(trbf-t5)+"\n")
efile.write("\n")
with open("RunError.txt", "a") as efile:
efile.write(predL.funct+ "\n")
efile.write("Run"+ "\n")
efile.write( "LN"+ "\n")
efile.write(str(np.average(predL.error)) + "\n")
efile.write(str( np.max(predL.error)) + "\n")
efile.write(str(np.average(predL.gaerror))+ "\n")
efile.write(str( np.max(predL.gaerror))+ "\n")
efile.write(str(np.average(predL.gcerror))+ "\n")
efile.write(str( np.max(predL.gcerror))+ "\n")
efile.write( "WN"+ "\n")
efile.write(str(np.average(predW.error)) + "\n")
efile.write(str( np.max(predW.error)) + "\n")
efile.write(str(np.average(predW.gaerror))+ "\n")
efile.write(str( np.max(predW.gaerror))+ "\n")
efile.write(str(np.average(predW.gcerror))+ "\n")
efile.write(str( np.max(predW.gcerror))+ "\n")
efile.write( "CN"+ "\n")
efile.write(str(np.average(predC.error)) + "\n")
efile.write(str( np.max(predC.error)) + "\n")
efile.write(str(np.average(predC.gaerror))+ "\n")
efile.write(str( np.max(predC.gaerror))+ "\n")
efile.write(str(np.average(predC.gcerror))+ "\n")
efile.write(str( np.max(predC.gcerror))+ "\n")
efile.write( "HN"+ "\n")
efile.write(str(np.average(predH.error)) + "\n")
efile.write(str( np.max(predH.error)) + "\n")
efile.write(str(np.average(predH.gaerror))+ "\n")
efile.write(str( np.max(predH.gaerror))+ "\n")
efile.write(str(np.average(predH.gcerror))+ "\n")
efile.write(str( np.max(predH.gcerror))+ "\n")
efile.write( "RN"+ "\n")
efile.write(str(np.average(predR.error)) + "\n")
efile.write(str( np.max(predR.error)) + "\n")
efile.write(str(np.average(predR.gaerror))+ "\n")
efile.write(str( np.max(predR.gaerror))+ "\n")
efile.write(str(np.average(predR.gcerror))+ "\n")
efile.write(str( np.max(predR.gcerror))+ "\n")
efile.write("\n")
'''
#pp.close()
## More Information (As Promised) ==============================================
'''
\/\/ Nomenclature \/\/
LN-LinearNearest Neighbor, WN-Weighted Nearest Neighbor,
CN-Cosine Nearest Neighbor, HN-Hermite Nearest Neighbor
prd - Predicted Points: Points which you want the values at
trn - Training Points: Points with known values
Ind - Independent: Dimensions which should be known
Dep - Dependent: Dimensions which are a function of Ind
\/\/ Method Breakdown \/\/
# Local Methods ================================================================
df suppress_stdout():
df Solve(points, funct):
rtrn z
\/\/ Class Breakdown \/\/
# Local Data Class =============================================================
clss N_Data(object):
df __init__(self, mini, maxi, numpts, funct='PW', dtype='rand', dims=3):
df AssignDep(self, values, gradient=[0]):
df CreateDep(self):
df PlotResults(self, title, pltfile='None'):
df PlotPoints(self, title, pltfile='None'):
df FindError(self, title, pltfile='None', plot=True,
check=False, step=0.00000001):
df CheckGrad(self, title, Interp, itype, pltfile='None', plot=True,
check=False, step=0.00000001, N=5, DistEff=3,
tension=0, bias=0, tight=False):
df PlotAll(self, title, Interp, itype, pltfile='None', erplot=True,
check=False, ptplot = False, step=0.00000001, neighs=5,
DistEff=3, tension=0, bias=0, tight=False):
# Interpolation Classes ========================================================
clss NNInterpBase(object):
df __init__(self, TrnPts, TrnVals, NumLeaves=2):
clss LNInterp(NNInterpBase):
df main(self, PrdPts, nppts, dims, nloc):
rtrn normal, prdtemp, pc
df main2D(self, PrdPts, nppts, nloc):
rtrn m, b
df __call__(self, PredPoints):
rtrn predz
df gradient(self, PredPoints):
rtrn grad
clss WNInterp(NNInterpBase):
df __call__(self, PredPoints, N=5, DistEff=3):
rtrn predz
df gradient(self, PredPoints, N=5, DistEff=3):
rtrn grad
clss CNInterp(NNInterpBase):
df main(self, PrdPts, nppts, D, N, neighvals):
rtrn zu, zl, diff, ddiff
df __call__(self, PredPoints, N=5):
rtrn predz
df gradient(self, PredPoints, N=5):
rtrn grad
clss HNInterp(NNInterpBase):
df HermFunctRes(self, y, mu, tension, bias):
rtrn (a0*y[:,1] + a1*m0 + a2*m1 + a3*y[:,2])
df HermFunctGrad(self, y, mu, dmu, tension, bias):
rtrn ((dmu*(b0*y[:,1]+b1*m0+b2*m1+b3*y[:,2]))/(self.dims-1)).real
df main(self, PrdPts, nppts, D, N, u, l, neighvals):
rtrn y, diff, ddiff
df __call__(self, PredPoints, N=5, tension=0, bias=0, tight=False):
rtrn predz
df gradient(self, PredPoints, N=5, tension=0, bias=0, tight=False):
rtrn grad
clss CRInterp(object):
df FindR(self, npp, T, loc):
rtrn R
df FinddR(self, PrdPts, ploc, pdist):
rtrn np.sum((dRp * dtx * self.weights[ploc[:,:-1]]), axis=1)
df __init__(self, TrnPts, TrnVals, N=5, NumLeaves=2, comp=2):
df __call__(self, PredPoints):
rtrn predz
df gradient(self, PredPoints):
rtrn grad
## Check Inputs and Results - Open Methods =====================================
df CheckInputs(neighbors, trnpoints, NumLeaves, maximum, minimum,
problem, DistanceEffect, tension, bias, tight):
rtrn problem, dimensions, neighbors, DistanceEffect, tension, \
bias, tight, NumLeaves, maximum, minimum
df RunTestCode():
Note - some vowels removed to ensure vim friendliness.
'''
## Running Code ================================================================
## Problem Inputs
dimensions = 0 # If 0, the dimensions is chosen from the problem type
minimum = np.array([-500, -500]) # Minimum value for independent range
maximum = np.array([500, 500]) # Maximum value for independent range
trndist = 'rand' # Can be rand, LH, or cart (only for 2D and 3D)
prddist = 'rand' # Can be rand, LH, or cart (only for 2D and 3D)
problem = '2D5O' # Problem type, options seen in organize inputs loop below
trnpoints = 10 # Number of training pts, min of 5 because of Hermite lims
prdpoints = 3000 # Number of prediction points
neighbors = 100 # KD-Tree neighbors found, default 0, min 2
DistanceEffect = 2 # Effect of distance of neighbors in WN, default 2
tension = 0 # Hermite adjustable, loose is -ive, tight fit is +ive, default 0
bias = 0 # Attention to each closest neighbor in hermite, default 0
comp = -2 # Type of CRBF used in the CR interpolation, default 4
NumLeaves = 10 # Leaves of KD Tree, default 0
## Extra Inputs
CheckResults = True #All results will not be checked if this is false
step = 0.00000001 # Complex step step size
allplot = False #For 2D, plot separate graphs for each interp
erplot = False #Choose to plot error
AbyT = 1 # Multilpier for actual to training data points
ptplot = False #For plotting the predicted point locations
# Variable for saved file of multiple plots
#pp = PdfPages('ND_Interpolation_Plots.pdf')
pp = 'None'
RunTestCode()
plt.show()
#plt.savefig('Lin2.eps', format='eps', dpi=1000)
'''
Side note: PrdPts are predicted points technically, although it's not really
that simple. They are better named pride points. Everyone needs pride points,
but their value is unknown usually and can only be determined when related to
those around you. Usually taken from Corey Watt.
'''
| mit |
white-cats/white-cat | src/demos/components/CheckBox/CheckBoxSize.tsx | 382 | import * as React from 'react'
import {CheckBox} from '../../../index'
export interface ICheckBoxSizeProps {}
export default class CheckBoxSize extends React.Component<ICheckBoxSizeProps> {
render () {
return (
<div>
<CheckBox size='small'>小</CheckBox>
<CheckBox>中</CheckBox>
<CheckBox size='large'>大</CheckBox>
</div>
)
}
}
| mit |
transcranial/keras-js | src/layers/convolutional/Conv1D.js | 3986 | import Layer from '../../Layer'
import Tensor from '../../Tensor'
import Conv2D from './Conv2D'
import * as tensorUtils from '../../utils/tensorUtils'
import ops from 'ndarray-ops'
import squeeze from 'ndarray-squeeze'
import unsqueeze from 'ndarray-unsqueeze'
/**
* Conv1D layer class
*/
export default class Conv1D extends Layer {
/**
* Creates a Conv1D layer
*
* @param {Object} [attrs] - layer config attributes
* @param {number} [attrs.filters] - Number of convolution filters to use
* @param {number} [attrs.kernel_size] - Length of 1D convolution kernel
*/
constructor(attrs = {}) {
super(attrs)
this.layerClass = 'Conv1D'
const {
filters = 1,
kernel_size = 1,
strides = 1,
padding = 'valid',
dilation_rate = 1,
activation = 'linear',
use_bias = true
} = attrs
this.description = `${filters} filters of size ${kernel_size}, striding ${strides}`
this.description += padding === 'valid' ? `, no border padding` : ', pad to same borders'
this.description += dilation_rate > 1 ? `, dilation rate ${dilation_rate}` : ''
this.description += activation !== 'linear' ? `, ${activation} activation` : ''
if (padding !== 'valid' && padding !== 'same') {
this.throwError('Invalid padding.')
}
if (dilation_rate !== 1 && strides !== 1) {
// Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1
// https://keras.io/layers/convolutional/#conv1d
this.throwError('Incompatible combination of dilation_rate with strides.')
}
this.use_bias = use_bias
// Layer weights specification
this.params = this.use_bias ? ['kernel', 'bias'] : ['kernel']
// Bootstrap Conv2D layer:
// Conv1D is actually a shim on top of Conv2D, where
// all of the computational action is performed
// Note that we use `channels_first` dim ordering here.
const conv2dAttrs = {
filters,
kernel_size: [kernel_size, 1],
strides: [strides, 1],
padding,
data_format: 'channels_first',
dilation_rate,
activation,
use_bias
}
this._conv2dAttrs = conv2dAttrs
this._conv2d = new Conv2D(Object.assign(conv2dAttrs, { gpu: attrs.gpu }))
}
/**
* Method for setting layer weights
*
* Override `super` method since weights must be set in `this._conv2d`
*
* @param {Tensor[]} weightsArr - array of weights which are instances of Tensor
*/
setWeights(weightsArr) {
weightsArr[0].tensor = unsqueeze(weightsArr[0].tensor).transpose(2, 1, 0, 3)
this._conv2d.setWeights(weightsArr)
}
/**
* Layer computational logic
*
* @param {Tensor} x
* @returns {Tensor}
*/
call(x) {
if (this.gpu) {
this._callGPU(x)
} else {
this._callCPU(x)
}
return this.output
}
/**
* CPU call
*
* @param {Tensor} x
*/
_callCPU(x) {
const input = new Tensor(x.tensor.data, x.tensor.shape)
input.tensor = unsqueeze(input.tensor).transpose(0, 2, 1)
const conv2dOutput = this._conv2d.call(input)
this.outputShape = [0, 2].map(i => this._conv2d.outputShape[i])
this.output = new Tensor([], this.outputShape)
ops.assign(this.output.tensor, squeeze(conv2dOutput.tensor).transpose(1, 0, 2))
}
/**
* GPU call
*
* @param {Tensor} x
*/
_callGPU(x) {
if (!x.glTexture) {
x.createGLTexture({ type: '2d', format: 'float' })
}
const inputShape = x.tensor.shape
const input = new Tensor([], inputShape)
Object.assign(input, x)
input.glTextureShape = inputShape
input.is2DReshaped = true
input.originalShape = [inputShape[0], 1, inputShape[1]]
input.indicesForReshaped = tensorUtils.createIndicesFor2DReshaped(input.originalShape, false, -1)
this.output = this._conv2d.call(input)
// GPU -> CPU data transfer
if (this.outbound.length === 0) {
this.output.transferFromGLTexture()
}
}
}
| mit |
MarimerLLC/csla | Source/Csla.Blazor/EditContextCslaExtensions.cs | 3869 | using System;
using System.Collections.Generic;
using System.Text;
using Csla.Core;
using Csla.Rules;
using Microsoft.AspNetCore.Components.Forms;
namespace Csla.Blazor
{
/// <summary>
/// Implements extension methods for edit context.
/// </summary>
public static class EditContextCslaExtensions
{
/// <summary>
/// Adds validation support to the <see cref="EditContext"/> for objects implementing ICheckRules.
/// </summary>
/// <param name="editContext">The <see cref="EditContext"/>.</param>
public static EditContext AddCslaValidation(this EditContext editContext)
{
if (editContext == null)
{
throw new ArgumentNullException(nameof(editContext));
}
var messages = new ValidationMessageStore(editContext);
// Perform object-level validation on request
editContext.OnValidationRequested +=
(sender, eventArgs) => ValidateModel((EditContext)sender, messages);
// Perform per-field validation on each field edit
editContext.OnFieldChanged +=
(sender, eventArgs) => ValidateField(editContext, messages, eventArgs.FieldIdentifier);
return editContext;
}
/// <summary>
/// Method to perform validation on the model as a whole
/// Applies changes to the validation store provided as a parameter
/// </summary>
/// <param name="editContext">The EditContext provided by the form doing the editing</param>
/// <param name="messages">The validation message store to be updated during validation</param>
private static void ValidateModel(EditContext editContext, ValidationMessageStore messages)
{
if (editContext.Model is ICheckRules model)
{
// Transfer broken rules of severity Error to the ValidationMessageStore
messages.Clear();
foreach (var brokenRuleNode in BusinessRules.GetAllBrokenRules(model))
{
foreach (var brokenRule in brokenRuleNode.BrokenRules)
if (brokenRule.Severity == RuleSeverity.Error)
{
// Add a new message for each broken rule
messages.Add(new FieldIdentifier(brokenRuleNode.Object, brokenRule.Property), brokenRule.Description);
}
}
}
// Inform consumers that the state may have changed
editContext.NotifyValidationStateChanged();
}
/// <summary>
/// Method to perform validation on a single property of the model being edit
/// Applies changes to the validation store provided as a parameter
/// </summary>
/// <param name="editContext">The EditContext provided by the form doing the editing</param>
/// <param name="messages">The validation message store to be updated during validation</param>
/// <param name="fieldIdentifier">Identifier that indicates the field being validated</param>
private static void ValidateField(EditContext editContext, ValidationMessageStore messages, in FieldIdentifier fieldIdentifier)
{
if (fieldIdentifier.Model is ICheckRules model)
{
// Transfer any broken rules of severity Error for the required property to the store
messages.Clear(fieldIdentifier);
foreach (BrokenRule brokenRule in model.GetBrokenRules())
{
if (brokenRule.Severity == RuleSeverity.Error)
{
if (fieldIdentifier.FieldName.Equals(brokenRule.Property))
{
// Add a message for each broken rule on the property under validation
messages.Add(fieldIdentifier, brokenRule.Description);
}
}
}
}
// We have to notify even if there were no messages before and are still no messages now,
// because the "state" that changed might be the completion of some async validation task
editContext.NotifyValidationStateChanged();
}
}
}
| mit |
mattatz/unity-teddy | Assets/Teddy/Scripts/Drawer.cs | 3647 | using UnityEngine;
using System;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using mattatz.Utils;
using mattatz.Triangulation2DSystem;
namespace mattatz.TeddySystem.Example {
public enum OperationMode {
Default,
Draw,
Move
};
public class Drawer : MonoBehaviour {
[SerializeField, Range(0.2f, 1.5f)] float threshold = 1.0f;
[SerializeField] GameObject prefab;
[SerializeField] GameObject floor;
[SerializeField] Material lineMat;
[SerializeField] TextAsset json;
OperationMode mode;
Teddy teddy;
List<Vector2> points;
List<Puppet> puppets = new List<Puppet>();
Camera cam;
float screenZ = 0f;
Puppet selected;
Vector3 origin;
Vector3 startPoint;
void Start () {
cam = Camera.main;
screenZ = Mathf.Abs(cam.transform.position.z - transform.position.z);
points = new List<Vector2>();
points = JsonUtility.FromJson<JsonSerialization<Vector2>>(json.text).ToList();
Build();
}
void Update () {
var bottom = cam.ViewportToWorldPoint(new Vector3(0.5f, 0f, screenZ));
floor.transform.position = bottom;
var screen = Input.mousePosition;
screen.z = screenZ;
switch(mode) {
case OperationMode.Default:
if(Input.GetMouseButtonDown(0)) {
Clear();
var ray = cam.ScreenPointToRay(screen);
RaycastHit hit;
if(Physics.Raycast(ray.origin, ray.direction, out hit, float.MaxValue)) {
startPoint = cam.ScreenToWorldPoint(screen);;
selected = hit.collider.GetComponent<Puppet>();
selected.Select();
startPoint = hit.point;
origin = selected.transform.position;
mode = OperationMode.Move;
} else {
mode = OperationMode.Draw;
}
}
break;
case OperationMode.Draw:
if(Input.GetMouseButtonUp(0)) {
Build();
mode = OperationMode.Default;
} else {
var p = cam.ScreenToWorldPoint(screen);
var p2D = new Vector2(p.x, p.y);
if(points.Count <= 0 || Vector2.Distance(p2D, points.Last()) > threshold) {
points.Add(p2D);
}
}
break;
case OperationMode.Move:
if(Input.GetMouseButtonUp(0)) {
selected.Unselect();
selected = null;
mode = OperationMode.Default;
} else {
var currentPoint = cam.ScreenToWorldPoint(screen);
var offset = currentPoint - startPoint;
selected.transform.position = origin + offset;
}
break;
}
}
void Build () {
if(points.Count < 3) return;
points = Utils2D.Constrain(points, threshold);
if(points.Count < 3) return;
teddy = new Teddy(points);
var mesh = teddy.Build(MeshSmoothingMethod.HC, 2, 0.2f, 0.75f);
var go = Instantiate(prefab);
go.transform.parent = transform;
var puppet = go.GetComponent<Puppet>();
puppet.SetMesh(mesh);
puppets.Add(puppet);
}
void Clear () {
points.Clear();
}
public void Save () {
LocalStorage.SaveList<Vector2>(points, "points.json");
}
public void Reset () {
puppets.ForEach(puppet => {
puppet.Ignore();
Destroy(puppet.gameObject, 10f);
});
puppets.Clear();
}
void OnDrawGizmos () {
if(points != null) {
Gizmos.color = Color.white;
points.ForEach(p => {
Gizmos.DrawSphere(p, 0.02f);
});
}
}
void OnRenderObject () {
if(points != null) {
GL.PushMatrix();
GL.MultMatrix (transform.localToWorldMatrix);
lineMat.SetColor("_Color", Color.white);
lineMat.SetPass(0);
GL.Begin(GL.LINES);
for(int i = 0, n = points.Count - 1; i < n; i++) {
GL.Vertex(points[i]); GL.Vertex(points[i + 1]);
}
GL.End();
GL.PopMatrix();
}
}
}
}
| mit |
aggiedefenders/aggiedefenders.github.io | node_modules/chordsheetjs/lib/chord_sheet/song.js | 2746 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _line = require('./line');
var _line2 = _interopRequireDefault(_line);
var _tag = require('./tag');
var _tag2 = _interopRequireDefault(_tag);
var _utilities = require('../utilities');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var TITLE = 'title';
var SUBTITLE = 'subtitle';
var Song = function () {
function Song() {
var metaData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Song);
this.lines = [];
this.currentLine = null;
this.metaData = metaData;
}
_createClass(Song, [{
key: 'chords',
value: function chords(chr) {
this.currentLine.chords(chr);
}
}, {
key: 'lyrics',
value: function lyrics(chr) {
this.ensureLine();
this.currentLine.lyrics(chr);
}
}, {
key: 'addLine',
value: function addLine() {
this.currentLine = (0, _utilities.pushNew)(this.lines, _line2.default);
return this.currentLine;
}
}, {
key: 'addChordLyricsPair',
value: function addChordLyricsPair() {
this.ensureLine();
return this.currentLine.addChordLyricsPair();
}
}, {
key: 'dropLine',
value: function dropLine() {
this.lines.pop();
}
}, {
key: 'ensureLine',
value: function ensureLine() {
if (!this.currentLine) {
this.addLine();
}
}
}, {
key: 'addTag',
value: function addTag(name, value) {
var tag = new _tag2.default(name, value);
if (tag.isMetaTag()) {
this.metaData[tag.name] = tag.value;
}
this.ensureLine();
this.currentLine.addTag(tag);
return tag;
}
}, {
key: 'title',
get: function get() {
return this.metaData[TITLE] || "";
}
}, {
key: 'subtitle',
get: function get() {
return this.metaData[SUBTITLE] || "";
}
}]);
return Song;
}();
exports.default = Song; | mit |
virtualstaticvoid/human_faktor | app/models/demo_request.rb | 636 | class DemoRequest < ActiveRecord::Base
belongs_to :country
default_values :identifier => lambda { TokenHelper.friendly_token },
:country => lambda { Country.default },
:trackback => false
validates :identifier, :presence => true, :uniqueness => true
# contact details
validates :first_name, :presence => true, :length => { :maximum => 255 }
validates :last_name, :presence => true, :length => { :maximum => 255 }
validates :email, :confirmation => true, :email => true
validates :country, :existence => true
def full_name
"#{self.first_name} #{self.last_name}"
end
end
| mit |
bonnici/scrobble-along-scrobbler | scrapers/json/DigMusicScraper.js | 2009 | "use strict";
/// <reference path="../../definitions/typescript-node-definitions/winston.d.ts"/>
/// <reference path="../../definitions/DefinitelyTyped/underscore/underscore.d.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var scrap = require("./JsonScraper");
var _ = require("underscore");
var winston = require("winston");
var DigMusicScraper = (function (_super) {
__extends(DigMusicScraper, _super);
function DigMusicScraper(name, baseUrl) {
var _this = _super.call(this, name) || this;
_this.url = baseUrl || "http://digmusic.net.au/player-data.php";
return _this;
}
DigMusicScraper.prototype.getUrl = function (lastfmUsername) {
return this.url;
};
DigMusicScraper.prototype.extractNowPlayingSong = function (jsonData) {
var artistName = null;
var title = null;
_.each(jsonData, function (element) {
if (element && element.playing == 'now') {
artistName = element.artistName;
title = element.title;
}
});
if (!artistName || !title) {
winston.info("DigMusicScraper could not find song");
return { Artist: null, Track: null };
}
else {
winston.info("DigMusicScraper found song " + artistName + " - " + title);
return { Artist: artistName, Track: title };
}
};
return DigMusicScraper;
}(scrap.JsonScraper));
exports.DigMusicScraper = DigMusicScraper;
//# sourceMappingURL=DigMusicScraper.js.map | mit |
zachdimitrov/Homework | CSharp-OOP/CSharpOOPWorkshop/SocietiesCore/Contracts/IConsumable.cs | 264 | namespace SocietiesCore.Contracts
{
using Infrastructure.Enumerations.Common;
using System;
using System.Collections.Generic;
public interface IConsumable
{
BeverageType Type { get; set; }
decimal Price { get; set; }
}
} | mit |
shaggy8871/frame | src/Frame/Response/StdOut.php | 480 | <?php
namespace Frame\Response;
/*
* For CLI sapi only
*/
class StdOut extends Foundation implements ResponseInterface
{
/*
* Render must send through a string
*/
public function render($params = null)
{
$params = ($params != null ? $params : $this->viewParams);
if (!is_string($params)) {
throw new InvalidResponseException('StdOut response value must be a string');
}
fwrite(STDOUT, $params);
}
}
| mit |
derekgraham/portfolio | scripts/models/experience.js | 254 | (function(module) {
var experience = {};
experience.all = [];
experience.getData = function(callback) {
experience.all = experienceData;
callback();
};
module.experience = experience;
// module.followers = followers;
})(window);
| mit |
Semyonic/Study | Java/BinaryHeap.java | 2181 | import java.util.*;
public class BinaryHeap<T extends Comparable<T>> {
private T[] arr;
private int total;
private boolean max;
public BinaryHeap(int capacity, boolean isMax)
{
arr = (T[]) new Comparable[capacity];
total = 0;
max = isMax;
}
public BinaryHeap(boolean isMax) { this(1, isMax); }
public BinaryHeap() { this(false); }
private void resize(int capacity)
{
T[] tmp = (T[]) new Comparable[capacity];
System.arraycopy(arr, 0, tmp, 0, total + 1);
arr = tmp;
}
private void swap(int a, int b)
{
T tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
private boolean compare(int a, int b)
{
return arr[max ? b : a].compareTo(arr[max ? a : b]) > 0;
}
public void add(T ele)
{
if (total == arr.length - 1) resize(arr.length * 2);
arr[++total] = ele;
up(total);
}
public T peek()
{
if (total == 0) throw new NoSuchElementException();
return arr[1];
}
public T remove()
{
if (total == 0) throw new NoSuchElementException();
swap(1, total);
T ele = arr[total--];
down(1);
arr[total + 1] = null;
if ((total > 0) && (total == (arr.length - 1) / 4)) resize(arr.length / 2);
return ele;
}
private void up(int i)
{
while (i > 1 && compare(i / 2, i)) {
swap(i, i / 2);
i /= 2;
}
}
private void down(int i)
{
while (i * 2 <= total) {
int j = i * 2;
if (j < total && compare(j, j + 1)) j++;
if ( ! compare(i, j)) break;
swap(i, j);
i = j;
}
}
public String toString()
{
return Arrays.toString(arr);
}
public static void main(final String[] args)
{
BinaryHeap<Integer> heap = new BinaryHeap<>();
for (int i = 0; i < 10; i++)
heap.add(i);
System.out.println(heap);
for (int i = 0; i < 10; i++)
System.out.print(heap.remove() + " ");
System.out.println();
}
}
| mit |
Gary-Moore/DevOps-Portal | DevOps.Portal.Application/ActionResponse.cs | 322 | using System.Collections.Generic;
namespace DevOps.Portal.Application
{
public class ActionResponse
{
public bool Success { get; set; }
public IEnumerable<string> Errors { get; set; }
}
public class ActionResponse<T> : ActionResponse
{
public T Data { get; set; }
}
}
| mit |
winiceo/pm_pmker | app/controller/api/activity.js | 7383 | 'use strict';
const Parse = require('../../lib/parse');
const moment = require('moment');
const _ = require('lodash');
const Activity = Parse.Object.extend('activity');
// 活动管理
// cate 'dzp','zjd'
module.exports = app => {
class ActivityController extends app.Controller {
* list() {
const {ctx, service} = this;
const bpwall_id = ctx.params.id;
const params = ctx.request.query;
const ret = {
code: 200,
data: {}
};
const test = {
cate: 'dzp',
page: 1,
limit: 20,
importance: undefined,
title: undefined,
type: undefined,
sort: '+id'
};
const page = parseInt(params.page) || 1;
let limit = parseInt(params.limit) || 20;
const cate = parseInt(params.cate) || 'dzp';
const title = parseInt(params.title) || '';
if (limit > 100) {
limit = 100;
}
// const account = new Account();
//
// account.id = ctx.session.accountId;
// const relation = account.relation('activity');
// const userQuery = relation.query();
const query = new Parse.Query(Activity);
if (cate != '') {
query.equalTo('cate', cate);
}
query.equalTo('team', ctx.user.team);
query.notEqualTo('status', 'deleted');
query.limit(limit);
query.skip(limit * (page - 1));
query.descending('createdAt');// 先进先出,正序排列
// app.logge.info(limit)
yield query.count().then(function (count) {
ret.data.total = count + 1;
return query.find();
}).then(function (items) {
const temp = [];
_.forEach(items, function (n, i) {
const item = n.toJSON();
item.createdAt = ctx.helper.dateAt(n.createdAt, 'YYYY/MM/DD');
temp.push(item);
});
ret.data.items = temp;
}, function (error) {
});
ctx.body = ret;
}
* save() {
const {ctx, service} = this;
const body = ctx.request.body;
const ret = {
code: 200,
data: {}
};
const Activity = Parse.Object.extend('activity');
const Award = Parse.Object.extend('award');
const activity = new Activity();
if (body.objectId) {
activity.id = body.objectId;
yield app.redis.hdel('activitys', activity.id, function (e, b) {
console.log([e, b]);
});
} else {
activity.set('accountId', ctx.user.accountId);
activity.set('team', ctx.user.team);
activity.set('status', 'draft');
activity.set('pageviews', 0);
}
// yield activity.save().then(function(activity){
// var query = new Parse.Query(Award);
// query.equalTo("activity", activity);
//
// });
const relation = activity.relation('award');
// relation.remove(activity)
// yield activity.save();
const awards = [];
_.each(body.awardList, function (item) {
item.num = parseInt(item.num);
item.total = parseInt(item.total);
const award = new Award(item);
awards.push(award);
});
yield Parse.Object.saveAll(awards).then(function (result) {
result.map(r => {
relation.add(r);
});
delete (body.awardList);
console.log(body)
activity.set(body);
return activity.save();
}).then(function (activity) {
ret.data = activity;
}, function (e) {
ret.code = '10001';
ret.message = e;
});
ctx.body = ret;
}
* get() {
const {ctx, service} = this;
const activityId = ctx.params.id;
const ret = {
code: 200,
data: yield service.activity.get(activityId)
};
ctx.body = ret;
}
* destoryActivity() {
const {ctx, service} = this;
const pageid = ctx.params.id;
const query = new Parse.Query('activity');
query.equalTo('objectId', pageid);
const ret = {
code: 200,
};
yield query.first().then(function (page) {
if (page) {
if (page.get('team') == ctx.user.team) {
page.set('status', 'deleted');
return page.save();
} else {
ret.code = 10020;
ret.message = '没有权限操作';
}
}
ret.code = 10030;
ret.message = '活动不在存';
}, function (err) {
ret.code = 10040;
ret.message = '操作错误';
app.logger.error(err);
return null;
});
ctx.body = ret;
}
//改变状态
* changeStatus() {
const {ctx, service} = this;
const pageid = ctx.params.id;
const query = new Parse.Query('activity');
query.equalTo('objectId', pageid);
const body = ctx.request.body;
const ret = {
code: 200,
};
yield query.first().then(function (page) {
if (page) {
if (page.get('team') == ctx.user.team) {
page.set('status', body.status);
return page.save();
} else {
ret.code = 10020;
ret.message = '没有权限操作';
}
}
ret.code = 10030;
ret.message = '活动不在存';
}, function (err) {
ret.code = 10040;
ret.message = '操作错误';
app.logger.error(err);
return null;
});
ctx.body = ret;
}
* destroyAward() {
const {ctx, service} = this;
const awardid = ctx.params.id;
const ret = {
code: 200,
};
const Award = Parse.Object.extend('award');
const award = new Award();
award.id = awardid;
yield award.destroy({
success(myObject) {
// The object was deleted from the Parse Cloud.
},
error(myObject, error) {
ret.message = '奖品错误';
}
});
ctx.body = ret;
}
}
return ActivityController;
};
| mit |
beathan/django-ajax-filtered-fields | ajax_filtered_fields/forms/fields.py | 10078 | # -*- coding: utf-8 -*-
from django import forms
from django.forms.util import ValidationError
from django.utils.translation import ugettext as _
from ajax_filtered_fields.forms import FilteredSelectMultiple, FilteredSelect
from ajax_filtered_fields import utils
class AjaxManyToManyField(forms.ModelMultipleChoiceField):
"""
Base many to many form field that display filter choices using
JQuery ajax requests.
"""
def __init__(self, model, lookups, default_index=0, select_related=None,
widget=FilteredSelectMultiple, *args, **kwargs):
"""
model: the related model
lookups: a sequence of (label, lookup_dict) that tells how to
filter the objects
e.g. (
('active', {'is_active': True}),
('inactive', {'is_active': False}),
)
you may specify what you want in lookup_dict, give multiple
filter lookups for the same choice and also set a choice that
gets all unfiltered objects
e.g. (
('some stuff', {
'field1__startswith': 'a',
'field2': 'value'
}),
('all stuff', {}),
)
default_index: the index of the lookup sequence that will
be the default choice when the field is initially displayed.
set to None if you want the widget to start empty
select_related: if not None the resulting querydict is performed
using select_related(select_related), allowing foreign keys
to be retrieved (e.g. useful when the unicode representation
of the model objects contains references to foreign keys)
It is possible to pass all the other args and kwargs accepted by
the django field class.
"""
# get the default index and queryset
# queryset is empty if default index is None
if default_index is None:
queryset = model.objects.none()
else:
lookups_list = utils.getLookups(lookups)
lookup_dict = lookups_list[default_index][1]
# get the queryset
queryset = utils.getObjects(model, lookup_dict, select_related)
# call the parent constructor
super(AjaxManyToManyField, self
).__init__(queryset, widget=widget, *args, **kwargs)
# populate widget with some data
self.widget.lookups = self.lookups = lookups
self.widget.model = self.model = model
self.widget.select_related = select_related
def clean(self, value):
if self.required and not value:
raise ValidationError(self.error_messages['required'])
elif not self.required and not value:
return []
if not isinstance(value, (list, tuple)):
raise ValidationError(self.error_messages['list'])
final_values = []
# if there is only one lookup used to limit choices, then a real
# validation over that limited choices is performed
lookups_list = utils.getLookups(self.lookups)
limit_choices_to = {} if len(lookups_list) != 1 else lookups_list[0][1]
for val in value:
try:
obj = self.model.objects.get(pk=val, **limit_choices_to)
except self.model.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'] % val)
else:
final_values.append(obj)
return final_values
class AjaxForeignKeyField(forms.ModelChoiceField):
"""
Base foreign key form field that display filter choices using
JQuery ajax requests.
"""
def __init__(self, model, lookups, default_index=0, select_related=None,
widget=FilteredSelect, *args, **kwargs):
"""
See the AjaxManyToManyField docstring.
"""
# get the default index and queryset
# queryset is empty if default index is None
if default_index is None:
queryset = model.objects.none()
else:
lookups_list = utils.getLookups(lookups)
lookup_dict = lookups_list[default_index][1]
# get the queryset
queryset = utils.getObjects(model, lookup_dict, select_related)
# call the parent constructor
super(AjaxForeignKeyField, self
).__init__(queryset, widget=widget, *args, **kwargs)
# populate widget with some data
self.widget.lookups = self.lookups = lookups
self.widget.model = self.model = model
self.widget.select_related = select_related
def clean(self, value):
forms.Field.clean(self, value)
if value in forms.fields.EMPTY_VALUES:
return None
# if there is only one lookup used to limit choices, then a real
# validation over that limited choices is performed
lookups_list = utils.getLookups(self.lookups)
limit_choices_to = {} if len(lookups_list) != 1 else lookups_list[0][1]
try:
key = self.to_field_name or 'pk'
limit_choices_to[key] = value
value = self.model.objects.get(**limit_choices_to)
except self.model.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return value
def _byLetterFactory(parent):
"""
Factory function returning a ManyToMany or ForeignKey field with
filters based on initials of a field of the objects.
parent can be AjaxManyToManyField or AjaxForeignKeyField.
"""
class ByLetter(parent):
"""
Ajax filtered field that displays filters based on
initials of a field of the objects, as they are typed by the user.
"""
def __init__(self, model, field_name="name", *args, **kwargs):
"""
model: the related model
field_name: the name of the field looked up
for initial
It is possible to pass all the other args and kwargs accepted by
parent ajax filtered field.
"""
import string
lookup_key = "%s__istartswith" % field_name
lookups = [(i, {lookup_key: i}) for i in string.lowercase]
# other non-letter records
regex_lookup_key = "%s__iregex" % field_name
lookups.append((_('other'), {regex_lookup_key: "^[^a-z]"}))
super(ByLetter, self).__init__(model, lookups, *args, **kwargs)
return ByLetter
ManyToManyByLetter = _byLetterFactory(AjaxManyToManyField)
ForeignKeyByLetter = _byLetterFactory(AjaxForeignKeyField)
def _byStatusFactory(parent):
"""
Factory function returning a ManyToMany or ForeignKey field with
filters based on activation status of the object.
parent can be AjaxManyToManyField or AjaxForeignKeyField.
"""
class ByStatus(parent):
"""
Ajax filtered field that displays filters based on
activation status of the objects.
"""
def __init__(self, model, field_name="is_active", *args, **kwargs):
"""
model: the related model
field_name: the name of the field that
manages the activation of the object
It is possible to pass all the other args and kwargs accepted by
parent ajax filtered field.
"""
lookups = (
(_('active'), {field_name: True}),
(_('inactive'), {field_name: False}),
(_('all'), {}),
)
super(ByStatus, self).__init__(model, lookups, *args, **kwargs)
return ByStatus
ManyToManyByStatus = _byStatusFactory(AjaxManyToManyField)
ForeignKeyByStatus = _byStatusFactory(AjaxForeignKeyField)
def _byRelatedFieldFactory(parent):
"""
Factory function returning a ManyToMany or ForeignKey field with
filters based on a related field (foreign key or many to many) of the
object. parent can be AjaxManyToManyField or AjaxForeignKeyField.
"""
class ByRelatedField(parent):
"""
Ajax filtered field that displays filters based on a related field
(foreign key or many to many) of the object.
"""
def __init__(self, model, field_name, include_blank=False,
*args, **kwargs):
"""
model: the related model
field_name: the name of the field representing the relationship
between the model and the related model
include_blank: if not False is displayed a NULL choice for
objects without relation (field_name__isnull=True).
The label of the choice must be specified as string.
It is possible to pass all the other args and kwargs accepted by
parent ajax filtered field.
"""
field = model._meta.get_field(field_name)
attname = "%s__pk" % field_name
def lookups():
"""
Return the lookups dict. This is needed because the lookups
may change as consequence of database changes at runtime.
"""
choices = field.get_choices(include_blank=include_blank)
lookups_ = [(label, {attname: pk}) for pk, label in choices if pk]
# add the blank choice lookup
if include_blank:
attname_isnull = "%s__isnull" % field_name
lookups_.append((include_blank, {attname_isnull: True}))
# add the all objects lookup
lookups_.append((_('all'), {}))
return lookups_
super(ByRelatedField, self).__init__(model, lookups, *args, **kwargs)
return ByRelatedField
ManyToManyByRelatedField = _byRelatedFieldFactory(AjaxManyToManyField)
ForeignKeyByRelatedField = _byRelatedFieldFactory(AjaxForeignKeyField)
| mit |
DiegoPatrocinio/ArcMovies | ArcMovies/ArcMovies/Helpers/ObservableRangeCollection.cs | 3307 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
namespace ArcMovies.Helpers
{
/// <summary>
/// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ObservableRangeCollection<T> : ObservableCollection<T>
{
/// <summary>
/// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class.
/// </summary>
public ObservableRangeCollection()
: base()
{
}
/// <summary>
/// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class that contains elements copied from the specified collection.
/// </summary>
/// <param name="collection">collection: The collection from which the elements are copied.</param>
/// <exception cref="System.ArgumentNullException">The collection parameter cannot be null.</exception>
public ObservableRangeCollection(IEnumerable<T> collection)
: base(collection)
{
}
/// <summary>
/// Adds the elements of the specified collection to the end of the ObservableCollection(Of T).
/// </summary>
public void AddRange(IEnumerable<T> collection, NotifyCollectionChangedAction notificationMode = NotifyCollectionChangedAction.Add)
{
if (collection == null)
throw new ArgumentNullException("collection");
CheckReentrancy();
if (notificationMode == NotifyCollectionChangedAction.Reset)
{
foreach (var i in collection)
{
Items.Add(i);
}
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
return;
}
int startIndex = Count;
var changedItems = collection is List<T> ? (List<T>)collection : new List<T>(collection);
foreach (var i in changedItems)
{
Items.Add(i);
}
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, changedItems, startIndex));
}
/// <summary>
/// Removes the first occurence of each item in the specified collection from ObservableCollection(Of T).
/// </summary>
public void RemoveRange(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
foreach (var i in collection)
Items.Remove(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
/// <summary>
/// Clears the current collection and replaces it with the specified item.
/// </summary>
public void Replace(T item)
{
ReplaceRange(new T[] { item });
}
/// <summary>
/// Clears the current collection and replaces it with the specified collection.
/// </summary>
public void ReplaceRange(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
Items.Clear();
AddRange(collection, NotifyCollectionChangedAction.Reset);
}
}
} | mit |
lucasjo/todo | src/main/resources/public/bower_components/angular-material/modules/js/radioButton/radioButton.js | 10725 | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.1-master-342ee53
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.radioButton
* @description radioButton module!
*/
mdRadioGroupDirective['$inject'] = ["$mdUtil", "$mdConstant", "$mdTheming", "$timeout"];
mdRadioButtonDirective['$inject'] = ["$mdAria", "$mdUtil", "$mdTheming"];
angular.module('material.components.radioButton', [
'material.core'
])
.directive('mdRadioGroup', mdRadioGroupDirective)
.directive('mdRadioButton', mdRadioButtonDirective);
/**
* @ngdoc directive
* @module material.components.radioButton
* @name mdRadioGroup
*
* @restrict E
*
* @description
* The `<md-radio-group>` directive identifies a grouping
* container for the 1..n grouped radio buttons; specified using nested
* `<md-radio-button>` tags.
*
* As per the [material design spec](http://www.google.com/design/spec/style/color.html#color-ui-color-application)
* the radio button is in the accent color by default. The primary color palette may be used with
* the `md-primary` class.
*
* Note: `<md-radio-group>` and `<md-radio-button>` handle tabindex differently
* than the native `<input type='radio'>` controls. Whereas the native controls
* force the user to tab through all the radio buttons, `<md-radio-group>`
* is focusable, and by default the `<md-radio-button>`s are not.
*
* @param {string} ng-model Assignable angular expression to data-bind to.
* @param {boolean=} md-no-ink Use of attribute indicates flag to disable ink ripple effects.
*
* @usage
* <hljs lang="html">
* <md-radio-group ng-model="selected">
*
* <md-radio-button
* ng-repeat="d in colorOptions"
* ng-value="d.value" aria-label="{{ d.label }}">
*
* {{ d.label }}
*
* </md-radio-button>
*
* </md-radio-group>
* </hljs>
*
*/
function mdRadioGroupDirective($mdUtil, $mdConstant, $mdTheming, $timeout) {
RadioGroupController.prototype = createRadioGroupControllerProto();
return {
restrict: 'E',
controller: ['$element', RadioGroupController],
require: ['mdRadioGroup', '?ngModel'],
link: { pre: linkRadioGroup }
};
function linkRadioGroup(scope, element, attr, ctrls) {
element.addClass('_md'); // private md component indicator for styling
$mdTheming(element);
var rgCtrl = ctrls[0];
var ngModelCtrl = ctrls[1] || $mdUtil.fakeNgModel();
rgCtrl.init(ngModelCtrl);
scope.mouseActive = false;
element
.attr({
'role': 'radiogroup',
'tabIndex': element.attr('tabindex') || '0'
})
.on('keydown', keydownListener)
.on('mousedown', function(event) {
scope.mouseActive = true;
$timeout(function() {
scope.mouseActive = false;
}, 100);
})
.on('focus', function() {
if(scope.mouseActive === false) {
rgCtrl.$element.addClass('md-focused');
}
})
.on('blur', function() {
rgCtrl.$element.removeClass('md-focused');
});
/**
*
*/
function setFocus() {
if (!element.hasClass('md-focused')) { element.addClass('md-focused'); }
}
/**
*
*/
function keydownListener(ev) {
var keyCode = ev.which || ev.keyCode;
// Only listen to events that we originated ourselves
// so that we don't trigger on things like arrow keys in
// inputs.
if (keyCode != $mdConstant.KEY_CODE.ENTER &&
ev.currentTarget != ev.target) {
return;
}
switch (keyCode) {
case $mdConstant.KEY_CODE.LEFT_ARROW:
case $mdConstant.KEY_CODE.UP_ARROW:
ev.preventDefault();
rgCtrl.selectPrevious();
setFocus();
break;
case $mdConstant.KEY_CODE.RIGHT_ARROW:
case $mdConstant.KEY_CODE.DOWN_ARROW:
ev.preventDefault();
rgCtrl.selectNext();
setFocus();
break;
case $mdConstant.KEY_CODE.ENTER:
var form = angular.element($mdUtil.getClosest(element[0], 'form'));
if (form.length > 0) {
form.triggerHandler('submit');
}
break;
}
}
}
function RadioGroupController($element) {
this._radioButtonRenderFns = [];
this.$element = $element;
}
function createRadioGroupControllerProto() {
return {
init: function(ngModelCtrl) {
this._ngModelCtrl = ngModelCtrl;
this._ngModelCtrl.$render = angular.bind(this, this.render);
},
add: function(rbRender) {
this._radioButtonRenderFns.push(rbRender);
},
remove: function(rbRender) {
var index = this._radioButtonRenderFns.indexOf(rbRender);
if (index !== -1) {
this._radioButtonRenderFns.splice(index, 1);
}
},
render: function() {
this._radioButtonRenderFns.forEach(function(rbRender) {
rbRender();
});
},
setViewValue: function(value, eventType) {
this._ngModelCtrl.$setViewValue(value, eventType);
// update the other radio buttons as well
this.render();
},
getViewValue: function() {
return this._ngModelCtrl.$viewValue;
},
selectNext: function() {
return changeSelectedButton(this.$element, 1);
},
selectPrevious: function() {
return changeSelectedButton(this.$element, -1);
},
setActiveDescendant: function (radioId) {
this.$element.attr('aria-activedescendant', radioId);
},
isDisabled: function() {
return this.$element[0].hasAttribute('disabled');
}
};
}
/**
* Change the radio group's selected button by a given increment.
* If no button is selected, select the first button.
*/
function changeSelectedButton(parent, increment) {
// Coerce all child radio buttons into an array, then wrap then in an iterator
var buttons = $mdUtil.iterator(parent[0].querySelectorAll('md-radio-button'), true);
if (buttons.count()) {
var validate = function (button) {
// If disabled, then NOT valid
return !angular.element(button).attr("disabled");
};
var selected = parent[0].querySelector('md-radio-button.md-checked');
var target = buttons[increment < 0 ? 'previous' : 'next'](selected, validate) || buttons.first();
// Activate radioButton's click listener (triggerHandler won't create a real click event)
angular.element(target).triggerHandler('click');
}
}
}
/**
* @ngdoc directive
* @module material.components.radioButton
* @name mdRadioButton
*
* @restrict E
*
* @description
* The `<md-radio-button>`directive is the child directive required to be used within `<md-radio-group>` elements.
*
* While similar to the `<input type="radio" ng-model="" value="">` directive,
* the `<md-radio-button>` directive provides ink effects, ARIA support, and
* supports use within named radio groups.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {string} ngValue Angular expression which sets the value to which the expression should
* be set when selected.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} aria-label Adds label to radio button for accessibility.
* Defaults to radio button's text. If no text content is available, a warning will be logged.
*
* @usage
* <hljs lang="html">
*
* <md-radio-button value="1" aria-label="Label 1">
* Label 1
* </md-radio-button>
*
* <md-radio-button ng-model="color" ng-value="specialValue" aria-label="Green">
* Green
* </md-radio-button>
*
* </hljs>
*
*/
function mdRadioButtonDirective($mdAria, $mdUtil, $mdTheming) {
var CHECKED_CSS = 'md-checked';
return {
restrict: 'E',
require: '^mdRadioGroup',
transclude: true,
template: '<div class="md-container" md-ink-ripple md-ink-ripple-checkbox>' +
'<div class="md-off"></div>' +
'<div class="md-on"></div>' +
'</div>' +
'<div ng-transclude class="md-label"></div>',
link: link
};
function link(scope, element, attr, rgCtrl) {
var lastChecked;
$mdTheming(element);
configureAria(element, scope);
// ngAria overwrites the aria-checked inside a $watch for ngValue.
// We should defer the initialization until all the watches have fired.
// This can also be fixed by removing the `lastChecked` check, but that'll
// cause more DOM manipulation on each digest.
if (attr.ngValue) {
$mdUtil.nextTick(initialize, false);
} else {
initialize();
}
/**
* Initializes the component.
*/
function initialize() {
if (!rgCtrl) {
throw 'RadioButton: No RadioGroupController could be found.';
}
rgCtrl.add(render);
attr.$observe('value', render);
element
.on('click', listener)
.on('$destroy', function() {
rgCtrl.remove(render);
});
}
/**
* On click functionality.
*/
function listener(ev) {
if (element[0].hasAttribute('disabled') || rgCtrl.isDisabled()) return;
scope.$apply(function() {
rgCtrl.setViewValue(attr.value, ev && ev.type);
});
}
/**
* Add or remove the `.md-checked` class from the RadioButton (and conditionally its parent).
* Update the `aria-activedescendant` attribute.
*/
function render() {
var checked = rgCtrl.getViewValue() == attr.value;
if (checked === lastChecked) return;
if (element[0].parentNode.nodeName.toLowerCase() !== 'md-radio-group') {
// If the radioButton is inside a div, then add class so highlighting will work
element.parent().toggleClass(CHECKED_CSS, checked);
}
if (checked) {
rgCtrl.setActiveDescendant(element.attr('id'));
}
lastChecked = checked;
element
.attr('aria-checked', checked)
.toggleClass(CHECKED_CSS, checked);
}
/**
* Inject ARIA-specific attributes appropriate for each radio button
*/
function configureAria(element, scope){
element.attr({
id: attr.id || 'radio_' + $mdUtil.nextUid(),
role: 'radio',
'aria-checked': 'false'
});
$mdAria.expectWithText(element, 'aria-label');
}
}
}
})(window, window.angular); | mit |
fog/fog-brightbox | lib/fog/brightbox/requests/compute/get_database_snapshot.rb | 735 | module Fog
module Brightbox
class Compute
class Real
# @param [String] identifier Unique reference to identify the resource
# @param [Hash] options
# @option options [Boolean] :nested passed through with the API request. When true nested resources are expanded.
#
# @return [Hash] if successful Hash version of JSON object
#
# @see https://api.gb1.brightbox.com/1.0/#database_snapshot_get_database_snapshot
#
def get_database_snapshot(identifier, options = {})
return nil if identifier.nil? || identifier == ""
wrapped_request("get", "/1.0/database_snapshots/#{identifier}", [200], options)
end
end
end
end
end
| mit |