repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
plopcas/example-protractor | example-oauth-oidc-api/src/main/java/com/example/demo/FooController.java | 2222 | package com.example.demo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;
import java.util.HashMap;
import java.util.Optional;
import java.util.Random;
@Controller("foobar")
public class FooController {
@GetMapping
public ResponseEntity<?> getFoobar(HttpServletRequest request) throws IOException {
System.out.println("Foobar called: " + request.getRequestURL());
String authorization = request.getHeader("Authorization");
if (authorization == null || !isValid(authorization)) {
return ResponseEntity.status(401).build();
} else {
String[] array = new String[]{"foo", "bar"};
return ResponseEntity.of(Optional.of(array[new Random().nextInt(array.length)]));
}
}
private Boolean isValid(String authorization) throws IOException {
String accessToken = authorization.replace("Bearer ", "");
String[] tokenParts = accessToken.split("\\.");
if (tokenParts.length != 3) {
System.err.println("Not a JWT");
return false;
}
String accessTokenPayload = accessToken.split("\\.")[1];
byte[] decodedAccessTokenPayloadBytes = Base64.getDecoder().decode(accessTokenPayload);
String decodedAccessTokenPayload = new String(decodedAccessTokenPayloadBytes);
HashMap<String, Object> accessTokenClaims = new ObjectMapper().readValue(decodedAccessTokenPayload, HashMap.class);
Integer expirationDate = (Integer) accessTokenClaims.get("exp");
LocalDateTime expirationLocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.valueOf(expirationDate)), ZoneId.systemDefault());
if (LocalDateTime.now().isAfter(expirationLocalDateTime)) {
System.err.println("Token expired: " + expirationLocalDateTime);
return false;
}
return true;
}
}
| mit |
Steve-Himself/obd2net | src/Obd2Net/Decoders/PercentCenteredDecoder.cs | 571 | using Obd2Net.Infrastructure;
using Obd2Net.InfrastructureContracts;
using Obd2Net.InfrastructureContracts.Enums;
using Obd2Net.InfrastructureContracts.Protocols;
using Obd2Net.InfrastructureContracts.Response;
namespace Obd2Net.Decoders
{
internal sealed class PercentCenteredDecoder : IDecoder<decimal>
{
public IOBDResponse<decimal> Execute(params IMessage[] messages)
{
var d = messages[0].Data;
var v = (d[0] - 128) * 100.0m / 128.0m;
return new OBDResponse<decimal>(v, Unit.Percent);
}
}
} | mit |
davidchang/yo-in-flux | src/scripts/actions/YoActions.js | 1239 | /*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* YoActions
*/
var AppDispatcher = require('../dispatcher/AppDispatcher');
var YoConstants = require('../constants/YoConstants');
var YoActions = {
addPerson: function(person) {
AppDispatcher.handleViewAction({
actionType: YoConstants.ADD_PERSON,
person: person
});
},
addPersonChangeName: function(name) {
AppDispatcher.handleViewAction({
actionType: YoConstants.ADD_PERSON_CHANGE_NAME,
name: name
});
},
sendYo: function(person) {
AppDispatcher.handleViewAction({
actionType: YoConstants.YO_SEND_YO,
person: person
});
},
userAuthenticated: function(person) {
AppDispatcher.handleViewAction({
actionType: YoConstants.YO_USER_AUTHENTICATED,
person: person
});
},
userUnauthenticated: function() {
AppDispatcher.handleViewAction({
actionType: YoConstants.YO_USER_UNAUTHENTICATED
});
}
};
module.exports = YoActions; | mit |
sebas77/Svelto.ECS | com.sebaslab.svelto.ecs/Extensions/Unity/DOTS/Native/NativeEGIDMapper.cs | 3822 | #if UNITY_NATIVE
using System;
using System.Runtime.CompilerServices;
using Svelto.Common;
using Svelto.DataStructures;
using Svelto.DataStructures.Native;
namespace Svelto.ECS.Native
{
/// <summary>
/// Note: this class should really be ref struct by design. It holds the reference of a dictionary that can become
/// invalid. Unfortunately it can be a ref struct, because Jobs needs to hold if by paramater. So the deal is
/// that a job can use it as long as nothing else is modifying the entities database and the NativeEGIDMapper
/// is disposed right after the use.
/// </summary>
public readonly struct NativeEGIDMapper<T> : IEGIDMapper where T : unmanaged, IEntityComponent
{
public NativeEGIDMapper
(ExclusiveGroupStruct groupStructId
, SveltoDictionary<uint, T, NativeStrategy<SveltoDictionaryNode<uint>>, NativeStrategy<T>, NativeStrategy<int>>
toNative) : this()
{
groupID = groupStructId;
_map = new SveltoDictionaryNative<uint, T>();
_map.UnsafeCast(toNative);
}
public int count => _map.count;
public Type entityType => TypeCache<T>.type;
public ExclusiveGroupStruct groupID { get; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref T Entity(uint entityID)
{
#if DEBUG
if (_map.TryFindIndex(entityID, out var findIndex) == false)
throw new Exception("Entity not found in this group ".FastConcat(typeof(T).ToString()));
#else
_map.TryFindIndex(entityID, out var findIndex);
#endif
return ref _map.GetDirectValueByRef(findIndex);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryGetEntity(uint entityID, out T value)
{
if (_map.count > 0 && _map.TryFindIndex(entityID, out var index))
unsafe
{
value = Unsafe.AsRef<T>(Unsafe.Add<T>((void*) _map.GetValues(out _).ToNativeArray(out _)
, (int) index));
return true;
}
value = default;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public NB<T> GetArrayAndEntityIndex(uint entityID, out uint index)
{
if (_map.TryFindIndex(entityID, out index))
return new NB<T>(_map.GetValues(out var count).ToNativeArray(out _), count);
#if DEBUG
throw new ECSException("Entity not found");
#else
return default;
#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryGetArrayAndEntityIndex(uint entityID, out uint index, out NB<T> array)
{
index = 0;
if (_map.count > 0 && _map.TryFindIndex(entityID, out index))
{
array = new NB<T>(_map.GetValues(out var count).ToNativeArray(out _), count);
return true;
}
array = default;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Exists(uint idEntityId)
{
return _map.count > 0 && _map.TryFindIndex(idEntityId, out _);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint GetIndex(uint entityID)
{
return _map.GetIndex(entityID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool FindIndex(uint valueKey, out uint index)
{
return _map.TryFindIndex(valueKey, out index);
}
readonly SveltoDictionaryNative<uint, T> _map;
}
}
#endif | mit |
luis-sousa/GC-v1.1b | src/controller/GerarAvisoControllerPT1.java | 4836 | package controller;
/*
* ESTGF - Escola Superior de Tecnologia e Gestão de Felgueiras */
/* IPP - Instituto Politécnico do Porto */
/* LEI - Licenciatura em Engenharia Informática*/
/* Projeto Final 2013/2014 /*
*/
import application.GerarAvisoPT1;
import application.GerarAvisoPT2;
import dao.OrcamentoDAO;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import model.Orcamento;
/**
* Classe GerarAvisoControllerPT1 está responsável pelo controlo dos eventos
* relativos á Stage que permite escolher um Orçamento para que em seguida possa
* seguir para a Stage de gerar Avisos (GerarAvisoControllerPT2)
*
* @author Luís Sousa - 8090228
*/
public class GerarAvisoControllerPT1 implements Initializable {
@FXML
private TableColumn clVersao;
@FXML
private TableColumn clData;
@FXML
private TableColumn clAno;
@FXML
private Button btProximo;
@FXML
private TableView tbOrcamento;
@FXML
private ObservableList<Orcamento> orcamento;
private int idOrcamentoSel;
private int positionOrcamentoTable;
private OrcamentoDAO dao;
/**
* Método que permite ir para a stage seguinte para gerar os avisos para o
* orçamento que foi escolhido aqui
*
* @param event evento
* @throws ClassNotFoundException erro de classe
* @throws SQLException erro de sql
* @throws IOException erro input/output
*/
@FXML
private void btNextFired(ActionEvent event) throws ClassNotFoundException, SQLException, IOException {
new GerarAvisoControllerPT2().setIdOrc(getIdOrcamentoSel());
GerarAvisoPT1.getStage().close();
new GerarAvisoPT2().start(new Stage());
}
/**
* Método que devolve o orçamento seleccionado na tabela
*
* @return um Orcamento
*/
private Orcamento getTableOrcamentoSeleccionado() {
if (tbOrcamento != null) {
List<Orcamento> tabela = tbOrcamento.getSelectionModel().getSelectedItems();
if (tabela.size() == 1) {
final Orcamento orcamentoSeleccionado = tabela.get(0);
return orcamentoSeleccionado;
}
}
return null;
}
/**
* Listener tableview que entra em ação quando muda o orcamento selecionado
* na tabela
*/
private final ListChangeListener<Orcamento> selectorTableOrcamento
= new ListChangeListener<Orcamento>() {
@Override
public void onChanged(ListChangeListener.Change<? extends Orcamento> c) {
getIdOrcamentoSel();
btProximo.setDisable(false);
}
};
/**
* Prepara a tabela
*/
private void iniciarTableView() {
clVersao.setCellValueFactory(new PropertyValueFactory<Orcamento, String>("versao"));
clAno.setCellValueFactory(new PropertyValueFactory<Orcamento, Integer>("ano"));
clData.setCellValueFactory(new PropertyValueFactory<Orcamento, String>("data"));
orcamento = FXCollections.observableArrayList();
tbOrcamento.setItems(orcamento);
}
/**
* Inicia a classe GerarAvisoControllerPT1.
*
* @param url url
* @param rb resourceBundle
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
this.iniciarTableView();
btProximo.setDisable(true);
final ObservableList<Orcamento> tabelaOrcamentoSel = tbOrcamento.getSelectionModel().getSelectedItems();
tabelaOrcamentoSel.addListener(selectorTableOrcamento);
dao = new OrcamentoDAO();
for (Orcamento orc : dao.getAllOrcamentos()) {
if (orc.getEstado().equals("Definitivo")) {
orcamento.add(orc);
}
}
}
/**
* Método que retorna o id do Orçamento Seleccionado
*
* @return id do Orçamento
*/
private int getIdOrcamentoSel() {
dao = new OrcamentoDAO();
int id;
try {
id = dao.getOrcamentoId(getTableOrcamentoSeleccionado().getVersao(), getTableOrcamentoSeleccionado().getAno());
} catch (Exception ex) {
id = -1;
}
this.idOrcamentoSel = id;
//System.out.println("ID SEL" + idOrcamentoSel);
dao.close();
return id;
}
}
| mit |
dancoates/frontend-starter | grunt/options/autoprefixer.js | 374 | (function(){
"use strict";
module.exports = function(option, grunt) {
var config = {
options: {
map : true,
browsers: ['last 2 versions','> 1%', 'ie 8', 'ie 9']
},
dist: {
src : "dist/css/*.css"
}
};
return config;
};
})();
| mit |
jwilk/anorack | tests/test_warn.py | 1632 | # Copyright © 2016-2021 Jakub Wilk <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import io
import unittest.mock
from tests.tools import (
assert_equal,
testcase,
)
import lib.misc as M
@testcase
def test_warn():
stderr = io.StringIO()
with unittest.mock.patch('sys.stderr', stderr):
with unittest.mock.patch('sys.argv', ['/usr/bin/anorack']):
M.warn('NOBODY expects the Spanish Inquisition!')
assert_equal(
stderr.getvalue(),
'anorack: warning: NOBODY expects the Spanish Inquisition!\n'
)
del testcase
# vim:ts=4 sts=4 sw=4 et
| mit |
stivalet/PHP-Vulnerability-test-suite | XSS/CWE_79/unsafe/CWE_79__shell_exec__func_rawurlencode__Unsafe_use_untrusted_data-tag_Name.php | 1285 | <!--
Unsafe sample
input : use shell_exec to cat /tmp/tainted.txt
SANITIZE : use of rawurlencode
File : unsafe, use of untrusted data in an tag name
-->
<!--Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.-->
<!DOCTYPE html>
<html>
<head/>
<body>
<?php
$tainted = shell_exec('cat /tmp/tainted.txt');
$tainted = rawurlencode($tainted);
//flaw
echo "<". $tainted ." href= \"/bob\" />" ;
?>
<h1>Hello World!</h1>
</body>
</html> | mit |
cdnjs/cdnjs | ajax/libs/single-spa/5.3.3/umd/single-spa.dev.js | 58508 | /* [email protected] - UMD - dev */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.singleSpa = {}));
}(this, (function (exports) { 'use strict';
var singleSpa = /*#__PURE__*/Object.freeze({
__proto__: null,
get start () { return start; },
get ensureJQuerySupport () { return ensureJQuerySupport; },
get setBootstrapMaxTime () { return setBootstrapMaxTime; },
get setMountMaxTime () { return setMountMaxTime; },
get setUnmountMaxTime () { return setUnmountMaxTime; },
get setUnloadMaxTime () { return setUnloadMaxTime; },
get registerApplication () { return registerApplication; },
get getMountedApps () { return getMountedApps; },
get getAppStatus () { return getAppStatus; },
get unloadApplication () { return unloadApplication; },
get checkActivityFunctions () { return checkActivityFunctions; },
get getAppNames () { return getAppNames; },
get navigateToUrl () { return navigateToUrl; },
get triggerAppChange () { return triggerAppChange; },
get addErrorHandler () { return addErrorHandler; },
get removeErrorHandler () { return removeErrorHandler; },
get mountRootParcel () { return mountRootParcel; },
get NOT_LOADED () { return NOT_LOADED; },
get LOADING_SOURCE_CODE () { return LOADING_SOURCE_CODE; },
get NOT_BOOTSTRAPPED () { return NOT_BOOTSTRAPPED; },
get BOOTSTRAPPING () { return BOOTSTRAPPING; },
get NOT_MOUNTED () { return NOT_MOUNTED; },
get MOUNTING () { return MOUNTING; },
get UPDATING () { return UPDATING; },
get LOAD_ERROR () { return LOAD_ERROR; },
get MOUNTED () { return MOUNTED; },
get UNMOUNTING () { return UNMOUNTING; },
get SKIP_BECAUSE_BROKEN () { return SKIP_BECAUSE_BROKEN; }
});
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
var NativeCustomEvent = commonjsGlobal.CustomEvent;
function useNative () {
try {
var p = new NativeCustomEvent('cat', { detail: { foo: 'bar' } });
return 'cat' === p.type && 'bar' === p.detail.foo;
} catch (e) {
}
return false;
}
/**
* Cross-browser `CustomEvent` constructor.
*
* https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent.CustomEvent
*
* @public
*/
var customEvent = useNative() ? NativeCustomEvent :
// IE >= 9
'undefined' !== typeof document && 'function' === typeof document.createEvent ? function CustomEvent (type, params) {
var e = document.createEvent('CustomEvent');
if (params) {
e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);
} else {
e.initCustomEvent(type, false, false, void 0);
}
return e;
} :
// IE <= 8
function CustomEvent (type, params) {
var e = document.createEventObject();
e.type = type;
if (params) {
e.bubbles = Boolean(params.bubbles);
e.cancelable = Boolean(params.cancelable);
e.detail = params.detail;
} else {
e.bubbles = false;
e.cancelable = false;
e.detail = void 0;
}
return e;
};
var errorHandlers = [];
function handleAppError(err, app, newStatus) {
var transformedErr = transformErr(err, app, newStatus);
if (errorHandlers.length) {
errorHandlers.forEach(function (handler) {
return handler(transformedErr);
});
} else {
setTimeout(function () {
throw transformedErr;
});
}
}
function addErrorHandler(handler) {
if (typeof handler !== "function") {
throw Error(formatErrorMessage(28, "a single-spa error handler must be a function"));
}
errorHandlers.push(handler);
}
function removeErrorHandler(handler) {
if (typeof handler !== "function") {
throw Error(formatErrorMessage(29, "a single-spa error handler must be a function"));
}
var removedSomething = false;
errorHandlers = errorHandlers.filter(function (h) {
var isHandler = h === handler;
removedSomething = removedSomething || isHandler;
return !isHandler;
});
return removedSomething;
}
function formatErrorMessage(code, msg) {
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
return "single-spa minified message #".concat(code, ": ").concat(msg ? msg + " " : "", "See https://single-spa.js.org/error/?code=").concat(code).concat(args.length ? "&arg=".concat(args.join("&arg=")) : "");
}
function transformErr(ogErr, appOrParcel, newStatus) {
var errPrefix = "".concat(objectType(appOrParcel), " '").concat(toName(appOrParcel), "' died in status ").concat(appOrParcel.status, ": ");
var result;
if (ogErr instanceof Error) {
try {
ogErr.message = errPrefix + ogErr.message;
} catch (err) {
/* Some errors have read-only message properties, in which case there is nothing
* that we can do.
*/
}
result = ogErr;
} else {
console.warn(formatErrorMessage(30, "While ".concat(appOrParcel.status, ", '").concat(toName(appOrParcel), "' rejected its lifecycle function promise with a non-Error. This will cause stack traces to not be accurate."), appOrParcel.status, toName(appOrParcel)));
try {
result = Error(errPrefix + JSON.stringify(ogErr));
} catch (err) {
// If it's not an Error and you can't stringify it, then what else can you even do to it?
result = ogErr;
}
}
result.appOrParcelName = toName(appOrParcel); // We set the status after transforming the error so that the error message
// references the state the application was in before the status change.
appOrParcel.status = newStatus;
return result;
}
var NOT_LOADED = "NOT_LOADED";
var LOADING_SOURCE_CODE = "LOADING_SOURCE_CODE";
var NOT_BOOTSTRAPPED = "NOT_BOOTSTRAPPED";
var BOOTSTRAPPING = "BOOTSTRAPPING";
var NOT_MOUNTED = "NOT_MOUNTED";
var MOUNTING = "MOUNTING";
var MOUNTED = "MOUNTED";
var UPDATING = "UPDATING";
var UNMOUNTING = "UNMOUNTING";
var UNLOADING = "UNLOADING";
var LOAD_ERROR = "LOAD_ERROR";
var SKIP_BECAUSE_BROKEN = "SKIP_BECAUSE_BROKEN";
function isActive(app) {
return app.status === MOUNTED;
}
function isntActive(app) {
return !isActive(app);
}
function isLoaded(app) {
return app.status !== NOT_LOADED && app.status !== LOADING_SOURCE_CODE && app.status !== LOAD_ERROR;
}
function isntLoaded(app) {
return !isLoaded(app);
}
function shouldBeActive(app) {
try {
return app.activeWhen(window.location);
} catch (err) {
handleAppError(err, app, SKIP_BECAUSE_BROKEN);
}
}
function shouldntBeActive(app) {
try {
return !shouldBeActive(app);
} catch (err) {
handleAppError(err, app, SKIP_BECAUSE_BROKEN);
}
}
function notSkipped(item) {
return item !== SKIP_BECAUSE_BROKEN && (!item || item.status !== SKIP_BECAUSE_BROKEN);
}
function withoutLoadErrors(app) {
return app.status === LOAD_ERROR ? new Date().getTime() - app.loadErrorTime >= 200 : true;
}
function toName(app) {
return app.name;
}
function isParcel(appOrParcel) {
return Boolean(appOrParcel.unmountThisParcel);
}
function objectType(appOrParcel) {
return isParcel(appOrParcel) ? "parcel" : "application";
}
// Object.assign() is not available in IE11. And the babel compiled output for object spread
// syntax checks a bunch of Symbol stuff and is almost a kb. So this function is the smaller replacement.
function assign() {
for (var i = arguments.length - 1; i > 0; i--) {
for (var key in arguments[i]) {
if (key === "__proto__") {
continue;
}
arguments[i - 1][key] = arguments[i][key];
}
}
return arguments[0];
}
/* the array.prototype.find polyfill on npmjs.com is ~20kb (not worth it)
* and lodash is ~200kb (not worth it)
*/
function find(arr, func) {
for (var i = 0; i < arr.length; i++) {
if (func(arr[i])) {
return arr[i];
}
}
return null;
}
function validLifecycleFn(fn) {
return fn && (typeof fn === "function" || isArrayOfFns(fn));
function isArrayOfFns(arr) {
return Array.isArray(arr) && !find(arr, function (item) {
return typeof item !== "function";
});
}
}
function flattenFnArray(appOrParcel, lifecycle) {
var fns = appOrParcel[lifecycle] || [];
fns = Array.isArray(fns) ? fns : [fns];
if (fns.length === 0) {
fns = [function () {
return Promise.resolve();
}];
}
var type = objectType(appOrParcel);
var name = toName(appOrParcel);
return function (props) {
return fns.reduce(function (resultPromise, fn, index) {
return resultPromise.then(function () {
var thisPromise = fn(props);
return smellsLikeAPromise(thisPromise) ? thisPromise : Promise.reject(formatErrorMessage(15, "Within ".concat(type, " ").concat(name, ", the lifecycle function ").concat(lifecycle, " at array index ").concat(index, " did not return a promise"), type, name, lifecycle, index));
});
}, Promise.resolve());
};
}
function smellsLikeAPromise(promise) {
return promise && typeof promise.then === "function" && typeof promise.catch === "function";
}
function toBootstrapPromise(appOrParcel, hardFail) {
return Promise.resolve().then(function () {
if (appOrParcel.status !== NOT_BOOTSTRAPPED) {
return appOrParcel;
}
appOrParcel.status = BOOTSTRAPPING;
return reasonableTime(appOrParcel, "bootstrap").then(function () {
appOrParcel.status = NOT_MOUNTED;
return appOrParcel;
}).catch(function (err) {
if (hardFail) {
throw transformErr(err, appOrParcel, SKIP_BECAUSE_BROKEN);
} else {
handleAppError(err, appOrParcel, SKIP_BECAUSE_BROKEN);
return appOrParcel;
}
});
});
}
function toUnmountPromise(appOrParcel, hardFail) {
return Promise.resolve().then(function () {
if (appOrParcel.status !== MOUNTED) {
return appOrParcel;
}
appOrParcel.status = UNMOUNTING;
var unmountChildrenParcels = Object.keys(appOrParcel.parcels).map(function (parcelId) {
return appOrParcel.parcels[parcelId].unmountThisParcel();
});
return Promise.all(unmountChildrenParcels).then(unmountAppOrParcel, function (parcelError) {
// There is a parcel unmount error
return unmountAppOrParcel().then(function () {
// Unmounting the app/parcel succeeded, but unmounting its children parcels did not
var parentError = Error(parcelError.message);
if (hardFail) {
throw transformErr(parentError, appOrParcel, SKIP_BECAUSE_BROKEN);
} else {
handleAppError(parentError, appOrParcel, SKIP_BECAUSE_BROKEN);
}
});
}).then(function () {
return appOrParcel;
});
function unmountAppOrParcel() {
// We always try to unmount the appOrParcel, even if the children parcels failed to unmount.
return reasonableTime(appOrParcel, "unmount").then(function () {
// The appOrParcel needs to stay in a broken status if its children parcels fail to unmount
{
appOrParcel.status = NOT_MOUNTED;
}
}).catch(function (err) {
if (hardFail) {
throw transformErr(err, appOrParcel, SKIP_BECAUSE_BROKEN);
} else {
handleAppError(err, appOrParcel, SKIP_BECAUSE_BROKEN);
}
});
}
});
}
var beforeFirstMountFired = false;
var firstMountFired = false;
function toMountPromise(appOrParcel, hardFail) {
return Promise.resolve().then(function () {
if (appOrParcel.status !== NOT_MOUNTED) {
return appOrParcel;
}
if (!beforeFirstMountFired) {
window.dispatchEvent(new customEvent("single-spa:before-first-mount"));
beforeFirstMountFired = true;
}
return reasonableTime(appOrParcel, "mount").then(function () {
appOrParcel.status = MOUNTED;
if (!firstMountFired) {
window.dispatchEvent(new customEvent("single-spa:first-mount"));
firstMountFired = true;
}
return appOrParcel;
}).catch(function (err) {
// If we fail to mount the appOrParcel, we should attempt to unmount it before putting in SKIP_BECAUSE_BROKEN
// We temporarily put the appOrParcel into MOUNTED status so that toUnmountPromise actually attempts to unmount it
// instead of just doing a no-op.
appOrParcel.status = MOUNTED;
return toUnmountPromise(appOrParcel, true).then(setSkipBecauseBroken, setSkipBecauseBroken);
function setSkipBecauseBroken() {
if (!hardFail) {
handleAppError(err, appOrParcel, SKIP_BECAUSE_BROKEN);
return appOrParcel;
} else {
throw transformErr(err, appOrParcel, SKIP_BECAUSE_BROKEN);
}
}
});
});
}
function toUpdatePromise(parcel) {
return Promise.resolve().then(function () {
if (parcel.status !== MOUNTED) {
throw Error(formatErrorMessage(32, "Cannot update parcel '".concat(toName(parcel), "' because it is not mounted"), toName(parcel)));
}
parcel.status = UPDATING;
return reasonableTime(parcel, "update").then(function () {
parcel.status = MOUNTED;
return parcel;
}).catch(function (err) {
throw transformErr(err, parcel, SKIP_BECAUSE_BROKEN);
});
});
}
var parcelCount = 0;
var rootParcels = {
parcels: {}
}; // This is a public api, exported to users of single-spa
function mountRootParcel() {
return mountParcel.apply(rootParcels, arguments);
}
function mountParcel(config, customProps) {
var owningAppOrParcel = this; // Validate inputs
if (!config || _typeof(config) !== "object" && typeof config !== "function") {
throw Error(formatErrorMessage(2, "Cannot mount parcel without a config object or config loading function"));
}
if (config.name && typeof config.name !== "string") {
throw Error(formatErrorMessage(3, "Parcel name must be a string, if provided. Was given ".concat(_typeof(config.name)), _typeof(config.name)));
}
if (_typeof(customProps) !== "object") {
throw Error(formatErrorMessage(4, "Parcel ".concat(name, " has invalid customProps -- must be an object but was given ").concat(_typeof(customProps)), name, _typeof(customProps)));
}
if (!customProps.domElement) {
throw Error(formatErrorMessage(5, "Parcel ".concat(name, " cannot be mounted without a domElement provided as a prop"), name));
}
var id = parcelCount++;
var passedConfigLoadingFunction = typeof config === "function";
var configLoadingFunction = passedConfigLoadingFunction ? config : function () {
return Promise.resolve(config);
}; // Internal representation
var parcel = {
id: id,
parcels: {},
status: passedConfigLoadingFunction ? LOADING_SOURCE_CODE : NOT_BOOTSTRAPPED,
customProps: customProps,
parentName: toName(owningAppOrParcel),
unmountThisParcel: function unmountThisParcel() {
if (parcel.status !== MOUNTED) {
throw Error(formatErrorMessage(6, "Cannot unmount parcel '".concat(name, "' -- it is in a ").concat(parcel.status, " status"), name, parcel.status));
}
return toUnmountPromise(parcel, true).then(function (value) {
if (parcel.parentName) {
delete owningAppOrParcel.parcels[parcel.id];
}
return value;
}).then(function (value) {
resolveUnmount(value);
return value;
}).catch(function (err) {
parcel.status = SKIP_BECAUSE_BROKEN;
rejectUnmount(err);
throw err;
});
}
}; // We return an external representation
var externalRepresentation; // Add to owning app or parcel
owningAppOrParcel.parcels[id] = parcel;
var loadPromise = configLoadingFunction();
if (!loadPromise || typeof loadPromise.then !== "function") {
throw Error(formatErrorMessage(7, "When mounting a parcel, the config loading function must return a promise that resolves with the parcel config"));
}
loadPromise = loadPromise.then(function (config) {
if (!config) {
throw Error(formatErrorMessage(8, "When mounting a parcel, the config loading function returned a promise that did not resolve with a parcel config"));
}
var name = config.name || "parcel-".concat(id);
if (!validLifecycleFn(config.bootstrap)) {
throw Error(formatErrorMessage(9, "Parcel ".concat(name, " must have a valid bootstrap function"), name));
}
if (!validLifecycleFn(config.mount)) {
throw Error(formatErrorMessage(10, "Parcel ".concat(name, " must have a valid mount function"), name));
}
if (!validLifecycleFn(config.unmount)) {
throw Error(formatErrorMessage(11, "Parcel ".concat(name, " must have a valid unmount function"), name));
}
if (config.update && !validLifecycleFn(config.update)) {
throw Error(formatErrorMessage(12, "Parcel ".concat(name, " provided an invalid update function"), name));
}
var bootstrap = flattenFnArray(config, "bootstrap");
var mount = flattenFnArray(config, "mount");
var unmount = flattenFnArray(config, "unmount");
parcel.status = NOT_BOOTSTRAPPED;
parcel.name = name;
parcel.bootstrap = bootstrap;
parcel.mount = mount;
parcel.unmount = unmount;
parcel.timeouts = ensureValidAppTimeouts(config.timeouts);
if (config.update) {
parcel.update = flattenFnArray(config, "update");
externalRepresentation.update = function (customProps) {
parcel.customProps = customProps;
return promiseWithoutReturnValue(toUpdatePromise(parcel));
};
}
}); // Start bootstrapping and mounting
// The .then() causes the work to be put on the event loop instead of happening immediately
var bootstrapPromise = loadPromise.then(function () {
return toBootstrapPromise(parcel, true);
});
var mountPromise = bootstrapPromise.then(function () {
return toMountPromise(parcel, true);
});
var resolveUnmount, rejectUnmount;
var unmountPromise = new Promise(function (resolve, reject) {
resolveUnmount = resolve;
rejectUnmount = reject;
});
externalRepresentation = {
mount: function mount() {
return promiseWithoutReturnValue(Promise.resolve().then(function () {
if (parcel.status !== NOT_MOUNTED) {
throw Error(formatErrorMessage(13, "Cannot mount parcel '".concat(name, "' -- it is in a ").concat(parcel.status, " status"), name, parcel.status));
} // Add to owning app or parcel
owningAppOrParcel.parcels[id] = parcel;
return toMountPromise(parcel);
}));
},
unmount: function unmount() {
return promiseWithoutReturnValue(parcel.unmountThisParcel());
},
getStatus: function getStatus() {
return parcel.status;
},
loadPromise: promiseWithoutReturnValue(loadPromise),
bootstrapPromise: promiseWithoutReturnValue(bootstrapPromise),
mountPromise: promiseWithoutReturnValue(mountPromise),
unmountPromise: promiseWithoutReturnValue(unmountPromise)
};
return externalRepresentation;
}
function promiseWithoutReturnValue(promise) {
return promise.then(function () {
return null;
});
}
function getProps(appOrParcel) {
var result = assign({}, appOrParcel.customProps, {
name: toName(appOrParcel),
mountParcel: mountParcel.bind(appOrParcel),
singleSpa: singleSpa
});
if (isParcel(appOrParcel)) {
result.unmountSelf = appOrParcel.unmountThisParcel;
}
return result;
}
var defaultWarningMillis = 1000;
var globalTimeoutConfig = {
bootstrap: {
millis: 4000,
dieOnTimeout: false,
warningMillis: defaultWarningMillis
},
mount: {
millis: 3000,
dieOnTimeout: false,
warningMillis: defaultWarningMillis
},
unmount: {
millis: 3000,
dieOnTimeout: false,
warningMillis: defaultWarningMillis
},
unload: {
millis: 3000,
dieOnTimeout: false,
warningMillis: defaultWarningMillis
},
update: {
millis: 3000,
dieOnTimeout: false,
warningMillis: defaultWarningMillis
}
};
function setBootstrapMaxTime(time, dieOnTimeout, warningMillis) {
if (typeof time !== "number" || time <= 0) {
throw Error(formatErrorMessage(16, "bootstrap max time must be a positive integer number of milliseconds"));
}
globalTimeoutConfig.bootstrap = {
millis: time,
dieOnTimeout: dieOnTimeout,
warningMillis: warningMillis || defaultWarningMillis
};
}
function setMountMaxTime(time, dieOnTimeout, warningMillis) {
if (typeof time !== "number" || time <= 0) {
throw Error(formatErrorMessage(17, "mount max time must be a positive integer number of milliseconds"));
}
globalTimeoutConfig.mount = {
millis: time,
dieOnTimeout: dieOnTimeout,
warningMillis: warningMillis || defaultWarningMillis
};
}
function setUnmountMaxTime(time, dieOnTimeout, warningMillis) {
if (typeof time !== "number" || time <= 0) {
throw Error(formatErrorMessage(18, "unmount max time must be a positive integer number of milliseconds"));
}
globalTimeoutConfig.unmount = {
millis: time,
dieOnTimeout: dieOnTimeout,
warningMillis: warningMillis || defaultWarningMillis
};
}
function setUnloadMaxTime(time, dieOnTimeout, warningMillis) {
if (typeof time !== "number" || time <= 0) {
throw Error(formatErrorMessage(19, "unload max time must be a positive integer number of milliseconds"));
}
globalTimeoutConfig.unload = {
millis: time,
dieOnTimeout: dieOnTimeout,
warningMillis: warningMillis || defaultWarningMillis
};
}
function reasonableTime(appOrParcel, lifecycle) {
var timeoutConfig = appOrParcel.timeouts[lifecycle];
var warningPeriod = timeoutConfig.warningMillis;
var type = objectType(appOrParcel);
return new Promise(function (resolve, reject) {
var finished = false;
var errored = false;
appOrParcel[lifecycle](getProps(appOrParcel)).then(function (val) {
finished = true;
resolve(val);
}).catch(function (val) {
finished = true;
reject(val);
});
setTimeout(function () {
return maybeTimingOut(1);
}, warningPeriod);
setTimeout(function () {
return maybeTimingOut(true);
}, timeoutConfig.millis);
var errMsg = formatErrorMessage(31, "Lifecycle function ".concat(lifecycle, " for ").concat(type, " ").concat(toName(appOrParcel), " lifecycle did not resolve or reject for ").concat(timeoutConfig.millis, " ms."), lifecycle, type, toName(appOrParcel), timeoutConfig.millis);
function maybeTimingOut(shouldError) {
if (!finished) {
if (shouldError === true) {
errored = true;
if (timeoutConfig.dieOnTimeout) {
reject(Error(errMsg));
} else {
console.error(errMsg); //don't resolve or reject, we're waiting this one out
}
} else if (!errored) {
var numWarnings = shouldError;
var numMillis = numWarnings * warningPeriod;
console.warn(errMsg);
if (numMillis + warningPeriod < timeoutConfig.millis) {
setTimeout(function () {
return maybeTimingOut(numWarnings + 1);
}, warningPeriod);
}
}
}
}
});
}
function ensureValidAppTimeouts(timeouts) {
var result = {};
for (var key in globalTimeoutConfig) {
result[key] = assign({}, globalTimeoutConfig[key], timeouts && timeouts[key] || {});
}
return result;
}
function toLoadPromise(app) {
return Promise.resolve().then(function () {
if (app.loadPromise) {
return app.loadPromise;
}
if (app.status !== NOT_LOADED && app.status !== LOAD_ERROR) {
return app;
}
app.status = LOADING_SOURCE_CODE;
var appOpts, isUserErr;
return app.loadPromise = Promise.resolve().then(function () {
var loadPromise = app.loadApp(getProps(app));
if (!smellsLikeAPromise(loadPromise)) {
// The name of the app will be prepended to this error message inside of the handleAppError function
isUserErr = true;
throw Error(formatErrorMessage(33, "single-spa loading function did not return a promise. Check the second argument to registerApplication('".concat(toName(app), "', loadingFunction, activityFunction)"), toName(app)));
}
return loadPromise.then(function (val) {
app.loadErrorTime = null;
appOpts = val;
var validationErrMessage, validationErrCode;
if (_typeof(appOpts) !== "object") {
validationErrCode = 34;
{
validationErrMessage = "does not export anything";
}
}
if (!validLifecycleFn(appOpts.bootstrap)) {
validationErrCode = 35;
{
validationErrMessage = "does not export a bootstrap function or array of functions";
}
}
if (!validLifecycleFn(appOpts.mount)) {
validationErrCode = 36;
{
validationErrMessage = "does not export a bootstrap function or array of functions";
}
}
if (!validLifecycleFn(appOpts.unmount)) {
validationErrCode = 37;
{
validationErrMessage = "does not export a bootstrap function or array of functions";
}
}
var type = objectType(appOpts);
if (validationErrCode) {
var appOptsStr;
try {
appOptsStr = JSON.stringify(appOpts);
} catch (_unused) {}
console.error(formatErrorMessage(validationErrCode, "The loading function for single-spa ".concat(type, " '").concat(toName(app), "' resolved with the following, which does not have bootstrap, mount, and unmount functions"), type, toName(app), appOptsStr), appOpts);
handleAppError(validationErrMessage, app, SKIP_BECAUSE_BROKEN);
return app;
}
if (appOpts.devtools && appOpts.devtools.overlays) {
app.devtools.overlays = assign({}, app.devtools.overlays, appOpts.devtools.overlays);
}
app.status = NOT_BOOTSTRAPPED;
app.bootstrap = flattenFnArray(appOpts, "bootstrap");
app.mount = flattenFnArray(appOpts, "mount");
app.unmount = flattenFnArray(appOpts, "unmount");
app.unload = flattenFnArray(appOpts, "unload");
app.timeouts = ensureValidAppTimeouts(appOpts.timeouts);
delete app.loadPromise;
return app;
});
}).catch(function (err) {
delete app.loadPromise;
var newStatus;
if (isUserErr) {
newStatus = SKIP_BECAUSE_BROKEN;
} else {
newStatus = LOAD_ERROR;
app.loadErrorTime = new Date().getTime();
}
handleAppError(err, app, newStatus);
return app;
});
});
}
var isInBrowser = typeof window !== "undefined";
/* We capture navigation event listeners so that we can make sure
* that application navigation listeners are not called until
* single-spa has ensured that the correct applications are
* unmounted and mounted.
*/
var capturedEventListeners = {
hashchange: [],
popstate: []
};
var routingEventsListeningTo = ["hashchange", "popstate"];
function navigateToUrl(obj) {
var url;
if (typeof obj === "string") {
url = obj;
} else if (this && this.href) {
url = this.href;
} else if (obj && obj.currentTarget && obj.currentTarget.href && obj.preventDefault) {
url = obj.currentTarget.href;
obj.preventDefault();
} else {
throw Error(formatErrorMessage(14, "singleSpaNavigate/navigateToUrl must be either called with a string url, with an <a> tag as its context, or with an event whose currentTarget is an <a> tag"));
}
var current = parseUri(window.location.href);
var destination = parseUri(url);
if (url.indexOf("#") === 0) {
window.location.hash = destination.hash;
} else if (current.host !== destination.host && destination.host) {
{
window.location.href = url;
}
} else if (destination.pathname === current.pathname && destination.search === current.pathname) {
window.location.hash = destination.hash;
} else {
// different path, host, or query params
window.history.pushState(null, null, url);
}
}
function callCapturedEventListeners(eventArguments) {
var _this = this;
if (eventArguments) {
var eventType = eventArguments[0].type;
if (routingEventsListeningTo.indexOf(eventType) >= 0) {
capturedEventListeners[eventType].forEach(function (listener) {
try {
// The error thrown by application event listener should not break single-spa down.
// Just like https://github.com/single-spa/single-spa/blob/85f5042dff960e40936f3a5069d56fc9477fac04/src/navigation/reroute.js#L140-L146 did
listener.apply(_this, eventArguments);
} catch (e) {
setTimeout(function () {
throw e;
});
}
});
}
}
}
var urlRerouteOnly;
function setUrlRerouteOnly(val) {
urlRerouteOnly = val;
}
function urlReroute() {
reroute([], arguments);
}
if (isInBrowser) {
// We will trigger an app change for any routing events.
window.addEventListener("hashchange", urlReroute);
window.addEventListener("popstate", urlReroute); // Monkeypatch addEventListener so that we can ensure correct timing
var originalAddEventListener = window.addEventListener;
var originalRemoveEventListener = window.removeEventListener;
window.addEventListener = function (eventName, fn) {
if (typeof fn === "function") {
if (routingEventsListeningTo.indexOf(eventName) >= 0 && !find(capturedEventListeners[eventName], function (listener) {
return listener === fn;
})) {
capturedEventListeners[eventName].push(fn);
return;
}
}
return originalAddEventListener.apply(this, arguments);
};
window.removeEventListener = function (eventName, listenerFn) {
if (typeof listenerFn === "function") {
if (routingEventsListeningTo.indexOf(eventName) >= 0) {
capturedEventListeners[eventName] = capturedEventListeners[eventName].filter(function (fn) {
return fn !== listenerFn;
});
return;
}
}
return originalRemoveEventListener.apply(this, arguments);
};
window.history.pushState = patchedUpdateState(window.history.pushState);
window.history.replaceState = patchedUpdateState(window.history.replaceState);
function patchedUpdateState(updateState) {
return function () {
var urlBefore = window.location.href;
var result = updateState.apply(this, arguments);
var urlAfter = window.location.href;
if (!urlRerouteOnly || urlBefore !== urlAfter) {
urlReroute(createPopStateEvent(window.history.state));
}
return result;
};
}
function createPopStateEvent(state) {
// https://github.com/single-spa/single-spa/issues/224 and https://github.com/single-spa/single-spa-angular/issues/49
// We need a popstate event even though the browser doesn't do one by default when you call replaceState, so that
// all the applications can reroute.
try {
return new PopStateEvent("popstate", {
state: state
});
} catch (err) {
// IE 11 compatibility https://github.com/single-spa/single-spa/issues/299
// https://docs.microsoft.com/en-us/openspecs/ie_standards/ms-html5e/bd560f47-b349-4d2c-baa8-f1560fb489dd
var evt = document.createEvent("PopStateEvent");
evt.initPopStateEvent("popstate", false, false, state);
return evt;
}
}
/* For convenience in `onclick` attributes, we expose a global function for navigating to
* whatever an <a> tag's href is.
*/
window.singleSpaNavigate = navigateToUrl;
}
function parseUri(str) {
var anchor = document.createElement("a");
anchor.href = str;
return anchor;
}
var hasInitialized = false;
function ensureJQuerySupport() {
var jQuery = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.jQuery;
if (!jQuery) {
if (window.$ && window.$.fn && window.$.fn.jquery) {
jQuery = window.$;
}
}
if (jQuery && !hasInitialized) {
var originalJQueryOn = jQuery.fn.on;
var originalJQueryOff = jQuery.fn.off;
jQuery.fn.on = function (eventString, fn) {
return captureRoutingEvents.call(this, originalJQueryOn, window.addEventListener, eventString, fn, arguments);
};
jQuery.fn.off = function (eventString, fn) {
return captureRoutingEvents.call(this, originalJQueryOff, window.removeEventListener, eventString, fn, arguments);
};
hasInitialized = true;
}
}
function captureRoutingEvents(originalJQueryFunction, nativeFunctionToCall, eventString, fn, originalArgs) {
if (typeof eventString !== "string") {
return originalJQueryFunction.apply(this, originalArgs);
}
var eventNames = eventString.split(/\s+/);
eventNames.forEach(function (eventName) {
if (routingEventsListeningTo.indexOf(eventName) >= 0) {
nativeFunctionToCall(eventName, fn);
eventString = eventString.replace(eventName, "");
}
});
if (eventString.trim() === "") {
return this;
} else {
return originalJQueryFunction.apply(this, originalArgs);
}
}
var appsToUnload = {};
function toUnloadPromise(app) {
return Promise.resolve().then(function () {
var unloadInfo = appsToUnload[toName(app)];
if (!unloadInfo) {
/* No one has called unloadApplication for this app,
*/
return app;
}
if (app.status === NOT_LOADED) {
/* This app is already unloaded. We just need to clean up
* anything that still thinks we need to unload the app.
*/
finishUnloadingApp(app, unloadInfo);
return app;
}
if (app.status === UNLOADING) {
/* Both unloadApplication and reroute want to unload this app.
* It only needs to be done once, though.
*/
return unloadInfo.promise.then(function () {
return app;
});
}
if (app.status !== NOT_MOUNTED) {
/* The app cannot be unloaded until it is unmounted.
*/
return app;
}
app.status = UNLOADING;
return reasonableTime(app, "unload").then(function () {
finishUnloadingApp(app, unloadInfo);
return app;
}).catch(function (err) {
errorUnloadingApp(app, unloadInfo, err);
return app;
});
});
}
function finishUnloadingApp(app, unloadInfo) {
delete appsToUnload[toName(app)]; // Unloaded apps don't have lifecycles
delete app.bootstrap;
delete app.mount;
delete app.unmount;
delete app.unload;
app.status = NOT_LOADED;
/* resolve the promise of whoever called unloadApplication.
* This should be done after all other cleanup/bookkeeping
*/
unloadInfo.resolve();
}
function errorUnloadingApp(app, unloadInfo, err) {
delete appsToUnload[toName(app)]; // Unloaded apps don't have lifecycles
delete app.bootstrap;
delete app.mount;
delete app.unmount;
delete app.unload;
handleAppError(err, app, SKIP_BECAUSE_BROKEN);
unloadInfo.reject(err);
}
function addAppToUnload(app, promiseGetter, resolve, reject) {
appsToUnload[toName(app)] = {
app: app,
resolve: resolve,
reject: reject
};
Object.defineProperty(appsToUnload[toName(app)], "promise", {
get: promiseGetter
});
}
function getAppUnloadInfo(appName) {
return appsToUnload[appName];
}
function getAppsToUnload() {
return Object.keys(appsToUnload).map(function (appName) {
return appsToUnload[appName].app;
}).filter(isntActive);
}
var apps = [];
function getMountedApps() {
return apps.filter(isActive).map(toName);
}
function getAppNames() {
return apps.map(toName);
} // used in devtools, not (currently) exposed as a single-spa API
function getRawAppData() {
return [].concat(apps);
}
function getAppStatus(appName) {
var app = find(apps, function (app) {
return toName(app) === appName;
});
return app ? app.status : null;
}
function registerApplication(appNameOrConfig, appOrLoadApp, activeWhen, customProps) {
var registration = sanitizeArguments(appNameOrConfig, appOrLoadApp, activeWhen, customProps);
if (getAppNames().indexOf(registration.name) !== -1) throw Error(formatErrorMessage(21, "There is already an app registered with name ".concat(registration.name), registration.name));
apps.push(assign({
loadErrorTime: null,
status: NOT_LOADED,
parcels: {},
devtools: {
overlays: {
options: {},
selectors: []
}
}
}, registration));
if (isInBrowser) {
ensureJQuerySupport();
reroute();
}
}
function checkActivityFunctions(location) {
return apps.filter(function (app) {
return app.activeWhen(location);
}).map(toName);
}
function getAppsToLoad() {
return apps.filter(notSkipped).filter(withoutLoadErrors).filter(isntLoaded).filter(shouldBeActive);
}
function getAppsToUnmount() {
return apps.filter(notSkipped).filter(isActive).filter(shouldntBeActive);
}
function getAppsToMount() {
return apps.filter(notSkipped).filter(isntActive).filter(isLoaded).filter(shouldBeActive);
}
function unregisterApplication(appName) {
if (!apps.find(function (app) {
return toName(app) === appName;
})) {
throw Error(formatErrorMessage(25, "Cannot unregister application '".concat(appName, "' because no such application has been registered"), appName));
}
return unloadApplication(appName).then(function () {
var appIndex = apps.findIndex(function (app) {
return toName(app) === appName;
});
apps.splice(appIndex, 1);
});
}
function unloadApplication(appName) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
waitForUnmount: false
};
if (typeof appName !== "string") {
throw Error(formatErrorMessage(26, "unloadApplication requires a string 'appName'"));
}
var app = find(apps, function (App) {
return toName(App) === appName;
});
if (!app) {
throw Error(formatErrorMessage(27, "Could not unload application '".concat(appName, "' because no such application has been registered"), appName));
}
var appUnloadInfo = getAppUnloadInfo(toName(app));
if (opts && opts.waitForUnmount) {
// We need to wait for unmount before unloading the app
if (appUnloadInfo) {
// Someone else is already waiting for this, too
return appUnloadInfo.promise;
} else {
// We're the first ones wanting the app to be resolved.
var promise = new Promise(function (resolve, reject) {
addAppToUnload(app, function () {
return promise;
}, resolve, reject);
});
return promise;
}
} else {
/* We should unmount the app, unload it, and remount it immediately.
*/
var resultPromise;
if (appUnloadInfo) {
// Someone else is already waiting for this app to unload
resultPromise = appUnloadInfo.promise;
immediatelyUnloadApp(app, appUnloadInfo.resolve, appUnloadInfo.reject);
} else {
// We're the first ones wanting the app to be resolved.
resultPromise = new Promise(function (resolve, reject) {
addAppToUnload(app, function () {
return resultPromise;
}, resolve, reject);
immediatelyUnloadApp(app, resolve, reject);
});
}
return resultPromise;
}
}
function immediatelyUnloadApp(app, resolve, reject) {
toUnmountPromise(app).then(toUnloadPromise).then(function () {
resolve();
setTimeout(function () {
// reroute, but the unload promise is done
reroute();
});
}).catch(reject);
}
function validateRegisterWithArguments(name, appOrLoadApp, activeWhen, customProps) {
if (typeof name !== "string" || name.length === 0) throw Error(formatErrorMessage(20, "The 1st argument to registerApplication must be a non-empty string 'appName'"));
if (!appOrLoadApp) throw Error(formatErrorMessage(23, "The 2nd argument to registerApplication must be an application or loading application function"));
if (typeof activeWhen !== "function") throw Error(formatErrorMessage(24, "The 3rd argument to registerApplication must be an activeWhen function"));
if (!!customProps && (_typeof(customProps) !== "object" || Array.isArray(customProps))) throw Error(formatErrorMessage(22, "The optional 4th argument is a customProps and must be an object"));
}
function validateRegisterWithConfig(config) {
if (Array.isArray(config) || config === null) throw Error(formatErrorMessage(39, "Configuration object can't be an Array or null!"));
var validKeys = ["name", "app", "activeWhen", "customProps"];
var invalidKeys = Object.keys(config).reduce(function (invalidKeys, prop) {
return validKeys.includes(prop) ? invalidKeys : invalidKeys.concat(prop);
}, []);
if (invalidKeys.length !== 0) throw Error(formatErrorMessage(38, "The configuration object accepts only: ".concat(validKeys.join(", "), ". Invalid keys: ").concat(invalidKeys.join(", "), "."), validKeys.join(", "), invalidKeys.join(", ")));
if (typeof config.name !== "string" || config.name.length === 0) throw Error(formatErrorMessage(20, "The config.name on registerApplication must be a non-empty string"));
if (_typeof(config.app) !== "object" && typeof config.app !== "function") throw Error(formatErrorMessage(20, "The config.app on registerApplication must be an application or a loading function"));
var allowsStringAndFunction = function allowsStringAndFunction(activeWhen) {
return typeof activeWhen === "string" || typeof activeWhen === "function";
};
if (!allowsStringAndFunction(config.activeWhen) && !(Array.isArray(config.activeWhen) && config.activeWhen.every(allowsStringAndFunction))) throw Error(formatErrorMessage(24, "The config.activeWhen on registerApplication must be a string, function or an array with both"));
if (!(!config.customProps || _typeof(config.customProps) === "object" && !Array.isArray(config.customProps))) throw Error(formatErrorMessage(22, "The optional config.customProps must be an object"));
}
function sanitizeArguments(appNameOrConfig, appOrLoadApp, activeWhen, customProps) {
var usingObjectAPI = _typeof(appNameOrConfig) === "object";
var registration = {
name: null,
loadApp: null,
activeWhen: null,
customProps: null
};
if (usingObjectAPI) {
validateRegisterWithConfig(appNameOrConfig);
registration.name = appNameOrConfig.name;
registration.loadApp = appNameOrConfig.app;
registration.activeWhen = appNameOrConfig.activeWhen;
registration.customProps = appNameOrConfig.customProps;
} else {
validateRegisterWithArguments(appNameOrConfig, appOrLoadApp, activeWhen, customProps);
registration.name = appNameOrConfig;
registration.loadApp = appOrLoadApp;
registration.activeWhen = activeWhen;
registration.customProps = customProps;
}
registration.loadApp = sanitizeLoadApp(registration.loadApp);
registration.customProps = sanitizeCustomProps(registration.customProps);
registration.activeWhen = sanitizeActiveWhen(registration.activeWhen);
return registration;
}
function sanitizeLoadApp(loadApp) {
if (typeof loadApp !== "function") {
return function () {
return Promise.resolve(loadApp);
};
}
return loadApp;
}
function sanitizeCustomProps(customProps) {
return customProps ? customProps : {};
}
function sanitizeActiveWhen(activeWhen) {
var activeWhenArray = Array.isArray(activeWhen) ? activeWhen : [activeWhen];
activeWhenArray = activeWhenArray.map(function (activeWhenOrPath) {
return typeof activeWhenOrPath === "function" ? activeWhenOrPath : pathToActiveWhen(activeWhenOrPath);
});
return function (location) {
return activeWhenArray.some(function (activeWhen) {
return activeWhen(location);
});
};
}
function pathToActiveWhen(path) {
var regex = toDynamicPathValidatorRegex(path);
return function (location) {
var route = location.href.replace(location.origin, "");
return regex.test(route);
};
}
function toDynamicPathValidatorRegex(path) {
var lastIndex = 0,
inDynamic = false,
regexStr = "^";
for (var charIndex = 0; charIndex < path.length; charIndex++) {
var char = path[charIndex];
var startOfDynamic = !inDynamic && char === ":";
var endOfDynamic = inDynamic && char === "/";
if (startOfDynamic || endOfDynamic) {
appendToRegex(charIndex);
}
}
appendToRegex(path.length);
return new RegExp(regexStr, "i");
function appendToRegex(index) {
var anyCharMaybeTrailingSlashRegex = "[^/]+/?";
var commonStringSubPath = escapeStrRegex(path.slice(lastIndex, index));
regexStr += inDynamic ? anyCharMaybeTrailingSlashRegex : commonStringSubPath;
inDynamic = !inDynamic;
lastIndex = index;
}
function escapeStrRegex(str) {
// borrowed from https://github.com/sindresorhus/escape-string-regexp/blob/master/index.js
return str.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
}
}
var appChangeUnderway = false,
peopleWaitingOnAppChange = [];
function triggerAppChange() {
// Call reroute with no arguments, intentionally
return reroute();
}
function reroute() {
var pendingPromises = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var eventArguments = arguments.length > 1 ? arguments[1] : undefined;
if (appChangeUnderway) {
return new Promise(function (resolve, reject) {
peopleWaitingOnAppChange.push({
resolve: resolve,
reject: reject,
eventArguments: eventArguments
});
});
}
var appsThatChanged = [];
if (isStarted()) {
appChangeUnderway = true;
return performAppChanges();
} else {
return loadApps();
}
function addChangedApps(apps) {
appsThatChanged.push.apply(appsThatChanged, _toConsumableArray(apps));
return apps;
}
function loadApps() {
return Promise.resolve().then(function () {
var loadPromises = addChangedApps(getAppsToLoad()).map(toLoadPromise);
return Promise.all(loadPromises).then(callAllEventListeners) // there are no mounted apps, before start() is called, so we always return []
.then(function () {
return [];
}).catch(function (err) {
callAllEventListeners();
throw err;
});
});
}
function performAppChanges() {
return Promise.resolve().then(function () {
window.dispatchEvent(new customEvent("single-spa:before-routing-event", getCustomEventDetail()));
var unloadPromises = addChangedApps(getAppsToUnload()).map(toUnloadPromise);
var unmountUnloadPromises = addChangedApps(getAppsToUnmount()).map(toUnmountPromise).map(function (unmountPromise) {
return unmountPromise.then(toUnloadPromise);
});
var allUnmountPromises = unmountUnloadPromises.concat(unloadPromises);
var unmountAllPromise = Promise.all(allUnmountPromises);
var appsToLoad = addChangedApps(getAppsToLoad());
/* We load and bootstrap apps while other apps are unmounting, but we
* wait to mount the app until all apps are finishing unmounting
*/
var loadThenMountPromises = appsToLoad.map(function (app) {
return toLoadPromise(app).then(toBootstrapPromise).then(function (app) {
return unmountAllPromise.then(function () {
return toMountPromise(app);
});
});
});
/* These are the apps that are already bootstrapped and just need
* to be mounted. They each wait for all unmounting apps to finish up
* before they mount.
*/
var mountPromises = getAppsToMount().filter(function (appToMount) {
return appsToLoad.indexOf(appToMount) < 0;
}).map(function (appToMount) {
appsThatChanged.push(appToMount);
return toBootstrapPromise(appToMount).then(function () {
return unmountAllPromise;
}).then(function () {
return toMountPromise(appToMount);
});
});
return unmountAllPromise.catch(function (err) {
callAllEventListeners();
throw err;
}).then(function () {
/* Now that the apps that needed to be unmounted are unmounted, their DOM navigation
* events (like hashchange or popstate) should have been cleaned up. So it's safe
* to let the remaining captured event listeners to handle about the DOM event.
*/
callAllEventListeners();
return Promise.all(loadThenMountPromises.concat(mountPromises)).catch(function (err) {
pendingPromises.forEach(function (promise) {
return promise.reject(err);
});
throw err;
}).then(finishUpAndReturn);
});
});
}
function finishUpAndReturn() {
var returnValue = getMountedApps();
pendingPromises.forEach(function (promise) {
return promise.resolve(returnValue);
});
try {
var appChangeEventName = appsThatChanged.length === 0 ? "single-spa:no-app-change" : "single-spa:app-change";
window.dispatchEvent(new customEvent(appChangeEventName, getCustomEventDetail()));
window.dispatchEvent(new customEvent("single-spa:routing-event", getCustomEventDetail()));
} catch (err) {
/* We use a setTimeout because if someone else's event handler throws an error, single-spa
* needs to carry on. If a listener to the event throws an error, it's their own fault, not
* single-spa's.
*/
setTimeout(function () {
throw err;
});
}
/* Setting this allows for subsequent calls to reroute() to actually perform
* a reroute instead of just getting queued behind the current reroute call.
* We want to do this after the mounting/unmounting is done but before we
* resolve the promise for the `reroute` function.
*/
appChangeUnderway = false;
if (peopleWaitingOnAppChange.length > 0) {
/* While we were rerouting, someone else triggered another reroute that got queued.
* So we need reroute again.
*/
var nextPendingPromises = peopleWaitingOnAppChange;
peopleWaitingOnAppChange = [];
reroute(nextPendingPromises);
}
return returnValue;
}
/* We need to call all event listeners that have been delayed because they were
* waiting on single-spa. This includes haschange and popstate events for both
* the current run of performAppChanges(), but also all of the queued event listeners.
* We want to call the listeners in the same order as if they had not been delayed by
* single-spa, which means queued ones first and then the most recent one.
*/
function callAllEventListeners() {
pendingPromises.forEach(function (pendingPromise) {
callCapturedEventListeners(pendingPromise.eventArguments);
});
callCapturedEventListeners(eventArguments);
}
function getCustomEventDetail() {
var _appsByNewStatus;
var newAppStatuses = {};
var appsByNewStatus = (_appsByNewStatus = {}, _defineProperty(_appsByNewStatus, MOUNTED, []), _defineProperty(_appsByNewStatus, NOT_MOUNTED, []), _defineProperty(_appsByNewStatus, NOT_LOADED, []), _defineProperty(_appsByNewStatus, SKIP_BECAUSE_BROKEN, []), _appsByNewStatus);
appsThatChanged.forEach(function (app) {
var appName = toName(app);
var status = getAppStatus(appName);
newAppStatuses[appName] = status;
var statusArr = appsByNewStatus[status] = appsByNewStatus[status] || [];
statusArr.push(appName);
});
return {
detail: {
newAppStatuses: newAppStatuses,
appsByNewStatus: appsByNewStatus,
totalAppChanges: appsThatChanged.length,
originalEvent: eventArguments === null || eventArguments === void 0 ? void 0 : eventArguments[0]
}
};
}
}
var started = false;
function start(opts) {
started = true;
if (opts && opts.urlRerouteOnly) {
setUrlRerouteOnly(opts.urlRerouteOnly);
}
if (isInBrowser) {
reroute();
}
}
function isStarted() {
return started;
}
if (isInBrowser) {
setTimeout(function () {
if (!started) {
console.warn(formatErrorMessage(1, "singleSpa.start() has not been called, 5000ms after single-spa was loaded. Before start() is called, apps can be declared and loaded, but not bootstrapped or mounted."));
}
}, 5000);
}
var devtools = {
getRawAppData: getRawAppData,
reroute: reroute,
NOT_LOADED: NOT_LOADED,
toLoadPromise: toLoadPromise,
toBootstrapPromise: toBootstrapPromise,
unregisterApplication: unregisterApplication
};
if (isInBrowser && window.__SINGLE_SPA_DEVTOOLS__) {
window.__SINGLE_SPA_DEVTOOLS__.exposedMethods = devtools;
}
exports.BOOTSTRAPPING = BOOTSTRAPPING;
exports.LOADING_SOURCE_CODE = LOADING_SOURCE_CODE;
exports.LOAD_ERROR = LOAD_ERROR;
exports.MOUNTED = MOUNTED;
exports.MOUNTING = MOUNTING;
exports.NOT_BOOTSTRAPPED = NOT_BOOTSTRAPPED;
exports.NOT_LOADED = NOT_LOADED;
exports.NOT_MOUNTED = NOT_MOUNTED;
exports.SKIP_BECAUSE_BROKEN = SKIP_BECAUSE_BROKEN;
exports.UNMOUNTING = UNMOUNTING;
exports.UPDATING = UPDATING;
exports.addErrorHandler = addErrorHandler;
exports.checkActivityFunctions = checkActivityFunctions;
exports.ensureJQuerySupport = ensureJQuerySupport;
exports.getAppNames = getAppNames;
exports.getAppStatus = getAppStatus;
exports.getMountedApps = getMountedApps;
exports.mountRootParcel = mountRootParcel;
exports.navigateToUrl = navigateToUrl;
exports.registerApplication = registerApplication;
exports.removeErrorHandler = removeErrorHandler;
exports.setBootstrapMaxTime = setBootstrapMaxTime;
exports.setMountMaxTime = setMountMaxTime;
exports.setUnloadMaxTime = setUnloadMaxTime;
exports.setUnmountMaxTime = setUnmountMaxTime;
exports.start = start;
exports.triggerAppChange = triggerAppChange;
exports.unloadApplication = unloadApplication;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=single-spa.dev.js.map
| mit |
Travellerme/Booker | src/Ens/BookerBundle/Repository/RoomsRepository.php | 596 | <?php
namespace Ens\BookerBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* RoomsRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class RoomsRepository extends EntityRepository
{
public function getRooms(){
$query = $this->getEntityManager()
->createQuery('SELECT r.id,r.name FROM EnsBookerBundle:Rooms r');
$data = $query->getResult();
$result = array();
foreach($data as $key=>$val){
$result[$val['id']] = array('id'=>$val['id'],'name'=>$val['name']);
}
return $result;
}
}
| mit |
zjhiphop/iot-font-icons | src/icons/sign-in.js | 558 | import Icon from '../components/Icon.vue'
Icon.register({"sign-in":{"width":1536,"height":1792,"paths":[{"d":"M1184 896q0 26-19 45l-544 544q-19 19-45 19t-45-19-19-45v-288h-448q-26 0-45-19t-19-45v-384q0-26 19-45t45-19h448v-288q0-26 19-45t45-19 45 19l544 544q19 19 19 45zM1536 544v704q0 119-84.5 203.5t-203.5 84.5h-320q-13 0-22.5-9.5t-9.5-22.5q0-4-1-20t-0.5-26.5 3-23.5 10-19.5 20.5-6.5h320q66 0 113-47t47-113v-704q0-66-47-113t-113-47h-288-11-13t-11.5-1-11.5-3-8-5.5-7-9-2-13.5q0-4-1-20t-0.5-26.5 3-23.5 10-19.5 20.5-6.5h320q119 0 203.5 84.5t84.5 203.5z"}]}}) | mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2020_03_01/src/main/java/com/microsoft/azure/management/network/v2020_03_01/MetricSpecification.java | 9726 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2020_03_01;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Description of metrics specification.
*/
public class MetricSpecification {
/**
* The name of the metric.
*/
@JsonProperty(value = "name")
private String name;
/**
* The display name of the metric.
*/
@JsonProperty(value = "displayName")
private String displayName;
/**
* The description of the metric.
*/
@JsonProperty(value = "displayDescription")
private String displayDescription;
/**
* Units the metric to be displayed in.
*/
@JsonProperty(value = "unit")
private String unit;
/**
* The aggregation type.
*/
@JsonProperty(value = "aggregationType")
private String aggregationType;
/**
* List of availability.
*/
@JsonProperty(value = "availabilities")
private List<Availability> availabilities;
/**
* Whether regional MDM account enabled.
*/
@JsonProperty(value = "enableRegionalMdmAccount")
private Boolean enableRegionalMdmAccount;
/**
* Whether gaps would be filled with zeros.
*/
@JsonProperty(value = "fillGapWithZero")
private Boolean fillGapWithZero;
/**
* Pattern for the filter of the metric.
*/
@JsonProperty(value = "metricFilterPattern")
private String metricFilterPattern;
/**
* List of dimensions.
*/
@JsonProperty(value = "dimensions")
private List<Dimension> dimensions;
/**
* Whether the metric is internal.
*/
@JsonProperty(value = "isInternal")
private Boolean isInternal;
/**
* The source MDM account.
*/
@JsonProperty(value = "sourceMdmAccount")
private String sourceMdmAccount;
/**
* The source MDM namespace.
*/
@JsonProperty(value = "sourceMdmNamespace")
private String sourceMdmNamespace;
/**
* The resource Id dimension name override.
*/
@JsonProperty(value = "resourceIdDimensionNameOverride")
private String resourceIdDimensionNameOverride;
/**
* Get the name of the metric.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name of the metric.
*
* @param name the name value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withName(String name) {
this.name = name;
return this;
}
/**
* Get the display name of the metric.
*
* @return the displayName value
*/
public String displayName() {
return this.displayName;
}
/**
* Set the display name of the metric.
*
* @param displayName the displayName value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the description of the metric.
*
* @return the displayDescription value
*/
public String displayDescription() {
return this.displayDescription;
}
/**
* Set the description of the metric.
*
* @param displayDescription the displayDescription value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withDisplayDescription(String displayDescription) {
this.displayDescription = displayDescription;
return this;
}
/**
* Get units the metric to be displayed in.
*
* @return the unit value
*/
public String unit() {
return this.unit;
}
/**
* Set units the metric to be displayed in.
*
* @param unit the unit value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withUnit(String unit) {
this.unit = unit;
return this;
}
/**
* Get the aggregation type.
*
* @return the aggregationType value
*/
public String aggregationType() {
return this.aggregationType;
}
/**
* Set the aggregation type.
*
* @param aggregationType the aggregationType value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withAggregationType(String aggregationType) {
this.aggregationType = aggregationType;
return this;
}
/**
* Get list of availability.
*
* @return the availabilities value
*/
public List<Availability> availabilities() {
return this.availabilities;
}
/**
* Set list of availability.
*
* @param availabilities the availabilities value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withAvailabilities(List<Availability> availabilities) {
this.availabilities = availabilities;
return this;
}
/**
* Get whether regional MDM account enabled.
*
* @return the enableRegionalMdmAccount value
*/
public Boolean enableRegionalMdmAccount() {
return this.enableRegionalMdmAccount;
}
/**
* Set whether regional MDM account enabled.
*
* @param enableRegionalMdmAccount the enableRegionalMdmAccount value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withEnableRegionalMdmAccount(Boolean enableRegionalMdmAccount) {
this.enableRegionalMdmAccount = enableRegionalMdmAccount;
return this;
}
/**
* Get whether gaps would be filled with zeros.
*
* @return the fillGapWithZero value
*/
public Boolean fillGapWithZero() {
return this.fillGapWithZero;
}
/**
* Set whether gaps would be filled with zeros.
*
* @param fillGapWithZero the fillGapWithZero value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withFillGapWithZero(Boolean fillGapWithZero) {
this.fillGapWithZero = fillGapWithZero;
return this;
}
/**
* Get pattern for the filter of the metric.
*
* @return the metricFilterPattern value
*/
public String metricFilterPattern() {
return this.metricFilterPattern;
}
/**
* Set pattern for the filter of the metric.
*
* @param metricFilterPattern the metricFilterPattern value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withMetricFilterPattern(String metricFilterPattern) {
this.metricFilterPattern = metricFilterPattern;
return this;
}
/**
* Get list of dimensions.
*
* @return the dimensions value
*/
public List<Dimension> dimensions() {
return this.dimensions;
}
/**
* Set list of dimensions.
*
* @param dimensions the dimensions value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withDimensions(List<Dimension> dimensions) {
this.dimensions = dimensions;
return this;
}
/**
* Get whether the metric is internal.
*
* @return the isInternal value
*/
public Boolean isInternal() {
return this.isInternal;
}
/**
* Set whether the metric is internal.
*
* @param isInternal the isInternal value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withIsInternal(Boolean isInternal) {
this.isInternal = isInternal;
return this;
}
/**
* Get the source MDM account.
*
* @return the sourceMdmAccount value
*/
public String sourceMdmAccount() {
return this.sourceMdmAccount;
}
/**
* Set the source MDM account.
*
* @param sourceMdmAccount the sourceMdmAccount value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withSourceMdmAccount(String sourceMdmAccount) {
this.sourceMdmAccount = sourceMdmAccount;
return this;
}
/**
* Get the source MDM namespace.
*
* @return the sourceMdmNamespace value
*/
public String sourceMdmNamespace() {
return this.sourceMdmNamespace;
}
/**
* Set the source MDM namespace.
*
* @param sourceMdmNamespace the sourceMdmNamespace value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withSourceMdmNamespace(String sourceMdmNamespace) {
this.sourceMdmNamespace = sourceMdmNamespace;
return this;
}
/**
* Get the resource Id dimension name override.
*
* @return the resourceIdDimensionNameOverride value
*/
public String resourceIdDimensionNameOverride() {
return this.resourceIdDimensionNameOverride;
}
/**
* Set the resource Id dimension name override.
*
* @param resourceIdDimensionNameOverride the resourceIdDimensionNameOverride value to set
* @return the MetricSpecification object itself.
*/
public MetricSpecification withResourceIdDimensionNameOverride(String resourceIdDimensionNameOverride) {
this.resourceIdDimensionNameOverride = resourceIdDimensionNameOverride;
return this;
}
}
| mit |
simokhov/schemas44 | src/main/java/ru/gov/zakupki/oos/types/_1/ZfcsComplaintType.java | 11248 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.02 at 03:35:23 PM MSK
//
package ru.gov.zakupki.oos.types._1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Информация по жалобе
*
* <p>Java class for zfcs_complaintType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="zfcs_complaintType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="commonInfo">
* <complexType>
* <complexContent>
* <extension base="{http://zakupki.gov.ru/oos/types/1}zfcs_complaintCommonInfoType">
* </extension>
* </complexContent>
* </complexType>
* </element>
* <element name="indicted" type="{http://zakupki.gov.ru/oos/types/1}zfcs_complaintSubjectType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="applicant" type="{http://zakupki.gov.ru/oos/types/1}zfcs_applicantType" minOccurs="0"/>
* <element name="applicantNew" type="{http://zakupki.gov.ru/oos/types/1}zfcs_applicantNewType" minOccurs="0"/>
* <element name="object" type="{http://zakupki.gov.ru/oos/types/1}zfcs_complaintObjectType" minOccurs="0"/>
* <element name="text" type="{http://zakupki.gov.ru/oos/types/1}zfcs_longTextType" minOccurs="0"/>
* <element name="printForm" type="{http://zakupki.gov.ru/oos/types/1}zfcs_printFormType" minOccurs="0"/>
* <element name="extPrintForm" type="{http://zakupki.gov.ru/oos/types/1}zfcs_extPrintFormType" minOccurs="0"/>
* <element name="attachments" type="{http://zakupki.gov.ru/oos/types/1}zfcs_controlRegistersAttachmentListType"/>
* <element name="returnInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_complaintReturnInfoType" minOccurs="0"/>
* <element name="cancelInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_complaintCancelPrintFormType" minOccurs="0"/>
* </sequence>
* <attribute name="schemeVersion" use="required" type="{http://zakupki.gov.ru/oos/base/1}schemeVersionType" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "zfcs_complaintType", propOrder = {
"commonInfo",
"indicted",
"applicant",
"applicantNew",
"object",
"text",
"printForm",
"extPrintForm",
"attachments",
"returnInfo",
"cancelInfo"
})
public class ZfcsComplaintType {
@XmlElement(required = true)
protected ZfcsComplaintType.CommonInfo commonInfo;
protected List<ZfcsComplaintSubjectType> indicted;
protected ZfcsApplicantType applicant;
protected ZfcsApplicantNewType applicantNew;
protected ZfcsComplaintObjectType object;
protected String text;
protected ZfcsPrintFormType printForm;
protected ZfcsExtPrintFormType extPrintForm;
@XmlElement(required = true)
protected ZfcsControlRegistersAttachmentListType attachments;
protected ZfcsComplaintReturnInfoType returnInfo;
protected ZfcsComplaintCancelPrintFormType cancelInfo;
@XmlAttribute(name = "schemeVersion", required = true)
protected String schemeVersion;
/**
* Gets the value of the commonInfo property.
*
* @return
* possible object is
* {@link ZfcsComplaintType.CommonInfo }
*
*/
public ZfcsComplaintType.CommonInfo getCommonInfo() {
return commonInfo;
}
/**
* Sets the value of the commonInfo property.
*
* @param value
* allowed object is
* {@link ZfcsComplaintType.CommonInfo }
*
*/
public void setCommonInfo(ZfcsComplaintType.CommonInfo value) {
this.commonInfo = value;
}
/**
* Gets the value of the indicted property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the indicted property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getIndicted().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ZfcsComplaintSubjectType }
*
*
*/
public List<ZfcsComplaintSubjectType> getIndicted() {
if (indicted == null) {
indicted = new ArrayList<ZfcsComplaintSubjectType>();
}
return this.indicted;
}
/**
* Gets the value of the applicant property.
*
* @return
* possible object is
* {@link ZfcsApplicantType }
*
*/
public ZfcsApplicantType getApplicant() {
return applicant;
}
/**
* Sets the value of the applicant property.
*
* @param value
* allowed object is
* {@link ZfcsApplicantType }
*
*/
public void setApplicant(ZfcsApplicantType value) {
this.applicant = value;
}
/**
* Gets the value of the applicantNew property.
*
* @return
* possible object is
* {@link ZfcsApplicantNewType }
*
*/
public ZfcsApplicantNewType getApplicantNew() {
return applicantNew;
}
/**
* Sets the value of the applicantNew property.
*
* @param value
* allowed object is
* {@link ZfcsApplicantNewType }
*
*/
public void setApplicantNew(ZfcsApplicantNewType value) {
this.applicantNew = value;
}
/**
* Gets the value of the object property.
*
* @return
* possible object is
* {@link ZfcsComplaintObjectType }
*
*/
public ZfcsComplaintObjectType getObject() {
return object;
}
/**
* Sets the value of the object property.
*
* @param value
* allowed object is
* {@link ZfcsComplaintObjectType }
*
*/
public void setObject(ZfcsComplaintObjectType value) {
this.object = value;
}
/**
* Gets the value of the text property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getText() {
return text;
}
/**
* Sets the value of the text property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setText(String value) {
this.text = value;
}
/**
* Gets the value of the printForm property.
*
* @return
* possible object is
* {@link ZfcsPrintFormType }
*
*/
public ZfcsPrintFormType getPrintForm() {
return printForm;
}
/**
* Sets the value of the printForm property.
*
* @param value
* allowed object is
* {@link ZfcsPrintFormType }
*
*/
public void setPrintForm(ZfcsPrintFormType value) {
this.printForm = value;
}
/**
* Gets the value of the extPrintForm property.
*
* @return
* possible object is
* {@link ZfcsExtPrintFormType }
*
*/
public ZfcsExtPrintFormType getExtPrintForm() {
return extPrintForm;
}
/**
* Sets the value of the extPrintForm property.
*
* @param value
* allowed object is
* {@link ZfcsExtPrintFormType }
*
*/
public void setExtPrintForm(ZfcsExtPrintFormType value) {
this.extPrintForm = value;
}
/**
* Gets the value of the attachments property.
*
* @return
* possible object is
* {@link ZfcsControlRegistersAttachmentListType }
*
*/
public ZfcsControlRegistersAttachmentListType getAttachments() {
return attachments;
}
/**
* Sets the value of the attachments property.
*
* @param value
* allowed object is
* {@link ZfcsControlRegistersAttachmentListType }
*
*/
public void setAttachments(ZfcsControlRegistersAttachmentListType value) {
this.attachments = value;
}
/**
* Gets the value of the returnInfo property.
*
* @return
* possible object is
* {@link ZfcsComplaintReturnInfoType }
*
*/
public ZfcsComplaintReturnInfoType getReturnInfo() {
return returnInfo;
}
/**
* Sets the value of the returnInfo property.
*
* @param value
* allowed object is
* {@link ZfcsComplaintReturnInfoType }
*
*/
public void setReturnInfo(ZfcsComplaintReturnInfoType value) {
this.returnInfo = value;
}
/**
* Gets the value of the cancelInfo property.
*
* @return
* possible object is
* {@link ZfcsComplaintCancelPrintFormType }
*
*/
public ZfcsComplaintCancelPrintFormType getCancelInfo() {
return cancelInfo;
}
/**
* Sets the value of the cancelInfo property.
*
* @param value
* allowed object is
* {@link ZfcsComplaintCancelPrintFormType }
*
*/
public void setCancelInfo(ZfcsComplaintCancelPrintFormType value) {
this.cancelInfo = value;
}
/**
* Gets the value of the schemeVersion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSchemeVersion() {
return schemeVersion;
}
/**
* Sets the value of the schemeVersion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSchemeVersion(String value) {
this.schemeVersion = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://zakupki.gov.ru/oos/types/1}zfcs_complaintCommonInfoType">
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class CommonInfo
extends ZfcsComplaintCommonInfoType
{
}
}
| mit |
aoziczero/tcode | include/tcode/time/util.hpp | 796 | #ifndef __tcode_time_util_h__
#define __tcode_time_util_h__
#include <tcode/time/timestamp.hpp>
#include <tcode/time/systemtime.hpp>
namespace tcode { namespace time {
bool is_leap_year( int year );
int number_of_days_between( int year_start , int year_end );
int number_of_days_between( int year , int mon_start , int mon_end );
int number_of_days( int year , int month );
void convert_to( const tcode::timestamp& st , time_t& out);
void convert_to( const tcode::timestamp& st , tm& out);
void convert_to( const tcode::timestamp& st , timeval& out);
void convert_to( const tcode::timestamp& st , timespec& out);
void convert_to( const tcode::timestamp& st , filetime& out);
void convert_to( const tcode::timestamp& st , systemtime& out);
}}
#endif
| mit |
koofka/singleproperty_redux | property-data/reducer-71-stinky-gulch.js | 19103 | /*
* HomeReducer
*
* The reducer takes care of our data. Using actions, we can change our
* application state.
* To add a new action, add it to the switch statement in the reducer function
*
* Example:
* case YOUR_ACTION_CONSTANT:
* return state.set('yourStateVariable', true);
*/
/* disable eslint for storage */
/* eslint-disable */
import { fromJS } from 'immutable';
import { colors } from 'global-colors';
import { markers } from 'global-markers';
import {
CHANGE_SLIDER_IMAGE_AUTO,
NEXT_SLIDER_IMAGE,
NEXT_SLIDER_IMAGE_AUTO,
PREV_SLIDER_IMAGE,
CHANGE_DETAIL_PANEL_USER,
CHANGE_DETAIL_PANEL_AUTO,
CHANGE_MARKER_OBJECT_USER,
CHANGE_MARKER_OBJECT_AUTO,
UPDATE_MARKER_MILEAGE,
NAV_SET_SCROLL_SECTION,
} from './constants';
// The initial state of the App
const initialState = fromJS({
previoussliderobject: {},
currentsliderobject: {},
nextsliderobject: {},
slidermouseover: false,
agentinformation: {
agentfullname: 'Jackie Jones',
agentcellphone: '303.250.7353',
agentcellphoneicon: markers.MOBILEPHONE,
agentdirectphone: '303.952.3068',
agentdirectphoneicon: markers.PHONE,
agentemail: '[email protected]',
agentemailicon: markers.EMAIL,
agentfacebook: 'fb.com/homeinthemountains',
agentfacebookicon: markers.FACEBOOK,
imagepath: './assets/img/home/jackiejonesremax.png',
},
metainformation: {
title: '71 Stinky Gulch Road, Nederland, Colorado, 80466 - Mountain Property For Sale',
description: 'Mountain Property For Sale at 71 Stinky Gulch Road, Nederland, Colorado, 80466 - Listed by Jackie Jones Re/Max Alliance Nederland',
keywords: '71 Stinky Gulch Road, Nederland, Colorado, 80466, residential, property, for sale, real estate, mountain, property, northern colorado, home for sale, homes, realtor, real estate agent, jackie jones, boulder, fort collins, gilpin, greeley, jamestown, pinecliffe, loveland, lyons, lafayette, windsor, berthoud, wellington, mead, longmont, nederland, niwot, estes park, johnstown, milliken, platteville',
ogtype: 'website',
ogurl: 'http://71stinkygulch.homeinthemountains.com',
gaID: 'UA-50017714-5',
},
propertyinformation: {
street: '71 Stinky Gulch Road',
city: 'Nederland',
state: 'Colorado',
stateabbr: 'CO',
zip: '80466',
price: '$585,000',
ires: '836894',
matrix: '',
theme: 'house',
},
// current feature icon types: Bed, Bath, SqFeet, Acres, Garage, Built
propertyfeatures: [
{
featuretitle: 'bedrooms',
featurevalue: '1',
featureicon: markers.BEDROOMS,
},
{
featuretitle: 'bathrooms',
featurevalue: '1',
featureicon: markers.BATHROOMS,
},
{
featuretitle: 'sq. feet',
featurevalue: '956',
featureicon: markers.SQFEET,
},
{
featuretitle: 'acreage',
featurevalue: '9.02',
featureicon: markers.ACERAGE,
},
{
featuretitle: 'parking',
featurevalue: '2',
featureicon: markers.GARAGE,
},
{
featuretitle: 'built',
featurevalue: '1970',
featureicon: markers.HOUSE,
},
],
propertydetails: {
propertydetailcopy: 'Over 9 acres inside Nederland town limits to consider for possible subdivision/PUD. Close enough to walk to town yet very private with expansive back range, town, & Barker Reservoir views from the upper portion of the property. An open & creatively designed A-frame home currently occupies the property but needs work. Very special property and opportunity, perfect for the developer buyer who knows the subdivision process when Nederland needs housing. Current residence sold in as is condition.',
propertydetailpanelindex: '',
propertydetailcontent: [
{
detailclass: 'Taxes & Fees',
detaillabel: 'Taxes',
detailvalue: '$2,580',
},
{
detailclass: 'Taxes & Fees',
detaillabel: 'Tax Year',
detailvalue: '2016',
},
{
detailclass: 'Schools',
detaillabel: 'School District',
detailvalue: 'Bldr Valley Dist RE2',
},
{
detailclass: 'Schools',
detaillabel: 'Elementary',
detailvalue: 'Nederland',
},
{
detailclass: 'Schools',
detaillabel: 'Middle/Jr High',
detailvalue: 'Nederland',
},
{
detailclass: 'Schools',
detaillabel: 'Senior High',
detailvalue: 'Nederland',
},
{
detailclass: 'Design Features',
detaillabel: '',
detailvalue: 'Cathedral/Vaulted Ceilings',
},
{
detailclass: 'Design Features',
detaillabel: '',
detailvalue: 'Wood Floors',
},
{
detailclass: 'Design Features',
detaillabel: '',
detailvalue: 'Skylights',
},
{
detailclass: 'Design Features',
detaillabel: '',
detailvalue: 'Washer/Dryer Hookups',
},
{
detailclass: 'Fireplace',
detaillabel: '',
detailvalue: 'Freestanding Fireplace',
},
{
detailclass: 'Fireplace',
detaillabel: '',
detailvalue: 'Family/Recreation Room Fireplace',
},
{
detailclass: 'Inclusions',
detaillabel: '',
detailvalue: 'Gas Range/Oven, Refrigerator',
},
{
detailclass: 'Inclusions',
detaillabel: '',
detailvalue: 'Clothes Washer',
},
{
detailclass: 'Inclusions',
detaillabel: '',
detailvalue: 'Clothes Dryer',
},
{
detailclass: 'Outdoor & Energy Features',
detaillabel: '',
detailvalue: 'Storage Buildings',
},
{
detailclass: 'Outdoor & Energy Features',
detaillabel: '',
detailvalue: 'Southern Exposure',
},
{
detailclass: 'Outdoor & Energy Features',
detaillabel: '',
detailvalue: 'Deck',
},
{
detailclass: 'Outdoor & Energy Features',
detaillabel: '',
detailvalue: 'RV/Boat Parking',
},
{
detailclass: 'Lot Features',
detaillabel: '',
detailvalue: 'Wooded Lot',
},
{
detailclass: 'Lot Features',
detaillabel: '',
detailvalue: 'Sloping Lot',
},
{
detailclass: 'Lot Features',
detaillabel: '',
detailvalue: 'Evergreen Trees',
},
{
detailclass: 'Lot Features',
detaillabel: '',
detailvalue: 'Rock Out-Croppings',
},
{
detailclass: 'Lot Features',
detaillabel: '',
detailvalue: 'Level Lot',
},
{
detailclass: 'Lot Features',
detaillabel: '',
detailvalue: 'Steep Lot',
},
{
detailclass: 'Lot Features',
detaillabel: '',
detailvalue: 'Outbuildings',
},
{
detailclass: 'Lot Features',
detaillabel: '',
detailvalue: 'Within City Limits',
},
],
},
propertyflyerinformation: {
flyerpath: './assets/flyer/71-Stinky-Gulch-Nederland-Colorado-Listing-Flyer.pdf',
},
slideshowimages: [
{
id: 0,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_01_039.jpg',
imagedescription: 'Finish this fixer upper to your own taste',
},
{
id: 1,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_02_040.jpg',
imagedescription: 'Welcome home',
},
{
id: 2,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_03_034.jpg',
imagedescription: 'Barker Reservoir views',
},
{
id: 3,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_04_051.jpg',
imagedescription: 'Fantastic views throughout the property',
},
{
id: 4,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_05_013.jpg',
imagedescription: 'Home entrance',
},
{
id: 5,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_06_003.jpg',
imagedescription: 'Full kitchen with rustic wood floors',
},
{
id: 6,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_07_007.jpg',
imagedescription: 'Nook area near the wood fireplace',
},
{
id: 7,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_08_005.jpg',
imagedescription: 'Bedroom off nook/fireplace area',
},
{
id: 8,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_09_008.jpg',
imagedescription: 'Lower level living area',
},
{
id: 9,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_10_001.jpg',
imagedescription: 'New bathtub area',
},
{
id: 10,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_11_010.jpg',
imagedescription: 'Shared bathroom',
},
{
id: 11,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_12_011.jpg',
imagedescription: 'Newer washer/dryer',
},
{
id: 12,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_13_012.jpg',
imagedescription: 'Storage in laundry area',
},
{
id: 13,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_14_014.jpg',
imagedescription: 'Upper level meditation/yoga room',
},
{
id: 14,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_15_017.jpg',
imagedescription: 'Part A-frame',
},
{
id: 15,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_16_021.jpg',
imagedescription: 'Shed on property for extra storage',
},
{
id: 16,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_17_036.jpg',
imagedescription: 'Walk to the bus stop',
},
{
id: 17,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_18_037.jpg',
imagedescription: 'Walk everywhere in town',
},
{
id: 18,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_19_046.jpg',
imagedescription: 'Sloping meadows',
},
{
id: 19,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_20_047.jpg',
imagedescription: 'Plentiful evergreens',
},
{
id: 20,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_21_032.jpg',
imagedescription: 'Privacy close to town',
},
{
id: 21,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_22_029.jpg',
imagedescription: 'Unbelievable Continental Divide views',
},
{
id: 22,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_23_027.jpg',
imagedescription: 'Continental Divide views from multiple areas on property',
},
{
id: 23,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_24_043.jpg',
imagedescription: 'So many possibilities',
},
{
id: 24,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_25_023.jpg',
imagedescription: 'Great views of town',
},
{
id: 25,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_26_025.jpg',
imagedescription: 'Lookout point',
},
{
id: 26,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_27_026.jpg',
imagedescription: 'Numerous level spots',
},
{
id: 27,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_28_018.jpg',
imagedescription: 'Tons of natural light',
},
{
id: 28,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_29_019.jpg',
imagedescription: 'So much potential',
},
{
id: 29,
imagepath: './assets/img/slideshow/Stinky_Gulch_71_30_033.jpg',
imagedescription: 'Road to property',
},
],
propertydirections: {
directionscopy: 'From Boulder, CO-119 W, left to East St (you will see Peak to Peak Imports and East Street Garage) stay to right at fork in the road and property will be on right hand side, AWD/4WD recommended in winter months.',
currentmarkerobject: {},
markers: [
{
id: 0,
type: 'Property',
title: 'Your New Home',
icon: markers.HOUSE,
position: [39.968425, -105.505267],
anchor: [20, 20],
labelanchor: [20, 45],
primarycolor: `rgb(${colors.primaryred})`,
secondarycolor: `rgb(${colors.primaryblue})`,
zoom: 18,
mileagetext: '',
contentString: '',
},
{
id: 1,
type: 'RTD Station',
title: 'Nederland Park and Ride',
icon: markers.BUS,
position: [39.962284, -105.512915],
anchor: [20, 20],
labelanchor: [20, 50],
primarycolor: `rgb(${colors.primaryred})`,
secondarycolor: `rgb(${colors.primaryblue})`,
zoom: 18,
mileagetext: '',
contentString: '',
},
{
id: 2,
type: 'Ski Resort',
title: 'Eldora Mountain Resort',
icon: markers.WINTER,
position: [39.937203, -105.582568],
anchor: [20, 20],
labelanchor: [20, 45],
primarycolor: `rgb(${colors.primaryred})`,
secondarycolor: `rgb(${colors.primaryblue})`,
zoom: 14,
mileagetext: '',
contentString: '',
},
{
id: 3,
type: 'School',
title: 'Nederland Middle-High School',
icon: markers.SCHOOL,
position: [39.9527528, -105.525521],
anchor: [20, 20],
labelanchor: [20, 45],
primarycolor: `rgb(${colors.primaryred})`,
secondarycolor: `rgb(${colors.primaryblue})`,
zoom: 15,
mileagetext: '',
contentString: '',
},
/*
{
id: 4,
type: 'School',
title: 'Nederland Elementary School',
icon: 'School',
iconpath: markers.SCHOOL,
position: [39.969428, -105.5179872],
anchor: [20, 20],
labelanchor: [20, 45],
primarycolor: `rgb(${colors.primaryred})`,
secondarycolor: `rgb(${colors.primaryblue})`,
zoom: 14,
mileagetext: '',
contentString: '',
},
*/
],
},
mainnavigation: {
navheight: 40,
activescrollsection: 'PHOTOS',
},
calloutdetail: {
callouttext: '',
calloutstart: new Date(),
calloutend: new Date(),
},
});
function homeReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_SLIDER_IMAGE_AUTO: {
const object = state.get('slideshowimages').filter((obj) => { return obj.get('id') === action.actionindex; }).first(); // eslint-disable-line
const nextTgtIndex = ((object.get('id') + 1) < state.get('slideshowimages').size) ? object.get('id') + 1 : 0;
const nextobject = state.get('slideshowimages').filter((obj) => { return obj.get('id') === nextTgtIndex; }).first(); // eslint-disable-line
const prevTgtIndex = ((object.get('id') - 1) >= 0) ? object.get('id') - 1 : state.get('slideshowimages').size - 1;
const prevobject = state.get('slideshowimages').filter((obj) => { return obj.get('id') === prevTgtIndex; }).first(); // eslint-disable-line
return state
.set('previoussliderobject', prevobject)
.set('currentsliderobject', object)
.set('nextsliderobject', nextobject);
}
case NEXT_SLIDER_IMAGE_AUTO:
case NEXT_SLIDER_IMAGE: {
const tgtIndex = ((state.get('currentsliderobject').get('id') + 1) < state.get('slideshowimages').size) ? state.get('currentsliderobject').get('id') + 1 : 0;
const object = state.get('slideshowimages').filter((obj) => { return obj.get('id') === tgtIndex; }).first(); // eslint-disable-line
const nextTgtIndex = ((object.get('id') + 1) < state.get('slideshowimages').size) ? object.get('id') + 1 : 0;
const nextobject = state.get('slideshowimages').filter((obj) => { return obj.get('id') === nextTgtIndex; }).first(); // eslint-disable-line
const prevTgtIndex = ((object.get('id') - 1) >= 0) ? object.get('id') - 1 : state.get('slideshowimages').size - 1;
const prevobject = state.get('slideshowimages').filter((obj) => { return obj.get('id') === prevTgtIndex; }).first(); // eslint-disable-line
return state
.set('previoussliderobject', prevobject)
.set('currentsliderobject', object)
.set('nextsliderobject', nextobject);
}
case PREV_SLIDER_IMAGE: {
const tgtIndex = ((state.get('currentsliderobject').get('id') - 1) >= 0) ? state.get('currentsliderobject').get('id') - 1 : state.get('slideshowimages').size - 1;
const object = state.get('slideshowimages').filter((obj) => { return obj.get('id') === tgtIndex; }).first(); // eslint-disable-line
const nextTgtIndex = ((object.get('id') + 1) < state.get('slideshowimages').size) ? object.get('id') + 1 : 0;
const nextobject = state.get('slideshowimages').filter((obj) => { return obj.get('id') === nextTgtIndex; }).first(); // eslint-disable-line
const prevTgtIndex = ((object.get('id') - 1) >= 0) ? object.get('id') - 1 : state.get('slideshowimages').size - 1;
const prevobject = state.get('slideshowimages').filter((obj) => { return obj.get('id') === prevTgtIndex; }).first(); // eslint-disable-line
return state
.set('previoussliderobject', prevobject)
.set('currentsliderobject', object)
.set('nextsliderobject', nextobject);
}
case CHANGE_DETAIL_PANEL_AUTO:
case CHANGE_DETAIL_PANEL_USER: {
return state
.setIn(['propertydetails', 'propertydetailpanelindex'], action.actionindex);
}
case CHANGE_MARKER_OBJECT_USER:
case CHANGE_MARKER_OBJECT_AUTO: {
const object = state.getIn(['propertydirections', 'markers']).filter((obj) => { return obj.get('id') === action.actionindex; }).first(); // eslint-disable-line
const newmarkersmap = state.getIn(['propertydirections', 'markers']).map((mrk) => mrk.set('mileagetext', '----'));
return state
.setIn(['propertydirections', 'currentmarkerobject'], object)
.setIn(['propertydirections', 'markers'], newmarkersmap); // eslint-disable-line
}
case UPDATE_MARKER_MILEAGE: {
const receivedArray = action.actionarray;
const newmarkersmap = state.getIn(['propertydirections', 'markers']).map((mrk, i) => mrk.set('mileagetext', receivedArray[i].distance.value === 0 ? '----' : receivedArray[i].distance.text));
return state
.setIn(['propertydirections', 'markers'], newmarkersmap);
}
case NAV_SET_SCROLL_SECTION: {
return state
.setIn(['mainnavigation', 'activescrollsection'], action.activesection);
}
default:
return state;
}
}
export default homeReducer;
| mit |
sigma/vmw.vco | setup.py | 1271 | from setuptools import setup, find_packages
import os
import sys
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
if sys.version_info < (2, 7):
setup_requires_version = ['unittest2']
else:
setup_requires_version = []
setup(
name = "vmw.vco",
version = "0.3.1",
license = "MIT",
package_dir = {'': 'src'},
packages = find_packages('src'),
namespace_packages = ['vmw',],
install_requires = ['vmw.ZSI',
'setuptools',
'zope.interface',
],
extra_requires = {'async': 'Twisted',
'doc': 'sphinx'},
setup_requires = ['jinja2',
] + setup_requires_version,
description = "Python bindings for the VMware Orchestrator",
long_description=read('README'),
author = "VMware, Inc.",
author_email = "[email protected]",
url = "http://sigma.github.com/vmw.vco",
keywords = "vmware bindings",
classifiers=[
"Development Status :: 4 - Beta",
"Framework :: Twisted",
"Intended Audience :: Developers",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
test_suite = 'unittest2.collector'
)
| mit |
henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Objects/Post/Syncs/Collection/Responses/Json/Writer/SyncCollectionPostResponseObjectJsonWriter.cs | 2612 | namespace TraktApiSharp.Objects.Post.Syncs.Collection.Responses.Json.Writer
{
using Newtonsoft.Json;
using Objects.Json;
using Syncs.Responses.Json.Writer;
using System;
using System.Threading;
using System.Threading.Tasks;
internal class SyncCollectionPostResponseObjectJsonWriter : AObjectJsonWriter<ITraktSyncCollectionPostResponse>
{
public override async Task WriteObjectAsync(JsonTextWriter jsonWriter, ITraktSyncCollectionPostResponse obj, CancellationToken cancellationToken = default)
{
if (jsonWriter == null)
throw new ArgumentNullException(nameof(jsonWriter));
var syncPostResponseGroupObjectJsonWriter = new SyncPostResponseGroupObjectJsonWriter();
await jsonWriter.WriteStartObjectAsync(cancellationToken).ConfigureAwait(false);
if (obj.Added != null)
{
await jsonWriter.WritePropertyNameAsync(JsonProperties.SYNC_COLLECTION_POST_RESPONSE_PROPERTY_NAME_ADDED, cancellationToken).ConfigureAwait(false);
await syncPostResponseGroupObjectJsonWriter.WriteObjectAsync(jsonWriter, obj.Added, cancellationToken).ConfigureAwait(false);
}
if (obj.Updated != null)
{
await jsonWriter.WritePropertyNameAsync(JsonProperties.SYNC_COLLECTION_POST_RESPONSE_PROPERTY_NAME_UPDATED, cancellationToken).ConfigureAwait(false);
await syncPostResponseGroupObjectJsonWriter.WriteObjectAsync(jsonWriter, obj.Updated, cancellationToken).ConfigureAwait(false);
}
if (obj.Existing != null)
{
await jsonWriter.WritePropertyNameAsync(JsonProperties.SYNC_COLLECTION_POST_RESPONSE_PROPERTY_NAME_EXISTING, cancellationToken).ConfigureAwait(false);
await syncPostResponseGroupObjectJsonWriter.WriteObjectAsync(jsonWriter, obj.Existing, cancellationToken).ConfigureAwait(false);
}
if (obj.NotFound != null)
{
var syncCollectionPostResponseNotFoundGroupObjectJsonWriter = new SyncPostResponseNotFoundGroupObjectJsonWriter();
await jsonWriter.WritePropertyNameAsync(JsonProperties.SYNC_COLLECTION_POST_RESPONSE_PROPERTY_NAME_NOT_FOUND, cancellationToken).ConfigureAwait(false);
await syncCollectionPostResponseNotFoundGroupObjectJsonWriter.WriteObjectAsync(jsonWriter, obj.NotFound, cancellationToken).ConfigureAwait(false);
}
await jsonWriter.WriteEndObjectAsync(cancellationToken).ConfigureAwait(false);
}
}
}
| mit |
kulakowka/rest-api-request | tests/express.js | 2584 | 'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const builder = require('./builder')
const preview = require('./preview')
const getUrl = require('./getUrl')
var app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', (req, res, next) => {
let demoUrl = builder.getUrl()
let scripts = '<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/styles/github.min.css"><script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/highlight.min.js"></script><script>hljs.initHighlightingOnLoad();</script>'
res.send(`
${scripts}
<h2>Full example</h2>
<br>
<pre><code class="javascript">
Model
.find({name: 'kulakowka'})
.where({isAdmin: true})
.where({gender: 'female'})
.populate('comments')
.populate('user', 'name fullname')
.populate({
path: 'owner',
select: 'name',
match: {
color: 'black'
},
options: {
sort: {
name: -1
}
}
})
.populate('car1 car2 car3')
.select('name age +notselected')
.select('name age -password')
.select({
name: 1,
user: 1,
source: -1
})
.sort({ createdAt: -1, name: -1 })
.limit(10)
.skip(10)
</code></pre>
<p>GET: <a href="${demoUrl}">${decodeURIComponent(demoUrl)}</a></p>
<br>
<pre><code class="javascript">Model.find({name: 'testname'}).getUrl()</code></pre>
<p>GET: <a href="${getUrl.indexUrl}">${decodeURIComponent(getUrl.indexUrl)}</a></p>
<br>
<pre><code class="javascript">Model.findOne({name: 'testname'}).getUrl()</code></pre>
<p>GET: <a href="${getUrl.showUrl}">${decodeURIComponent(getUrl.showUrl)}</a></p>
<br>
<pre><code class="javascript">Model.create().getUrl()</code></pre>
<p>POST: <a hrer="${getUrl.createUrl}">${decodeURIComponent(getUrl.createUrl)}</a></p>
<br>
<pre><code class="javascript">Model.update({name: 'testname'}, {name: 'new name'}).getUrl()</code></pre>
<p>PUT: <a href="${getUrl.updateUrl}">${decodeURIComponent(getUrl.updateUrl)}</a></p>
<br>
<pre><code class="javascript">Model.delete({name: 'testname'}).getUrl()</code></pre>
<p>DELETE: <a href="${getUrl.deleteUrl}">${decodeURIComponent(getUrl.deleteUrl)}</a></p>
`)
})
app.get('/:model/:action', (req, res, next) => {
// Mongoose query builder
let queryText = preview.previewQuery(req)
// res.json(req.query)
res.send(queryText)
})
app.listen(3333, function () {
console.log('Example app listening on port 3333!')
})
module.exports = app | mit |
anderssonfilip/angular-country-map | app/js/controllers.js | 322 | 'use strict';
/* Controllers */
angular.module('myApp.controllers', [])
.controller('Search', function($scope, $http) {
$http.get('countries.json').success(function(data) {
$scope.countries = data;
})
})
.controller('Wiki', ['$scope',
function($scope) {
}
]); | mit |
xiao-T/vue-5253 | src/js/game-list.js | 3065 | /**
* Create by xiaoT
* at 2015-11-23
*/
;(function(){
var GameList = function(){
var _this = this;
_this.tagId = 0;
_this.pageIndex = 0;
_this.gameList = $('#js-game-list');
_this.loadMoreBtn = _this.gameList.siblings('.load-more');
_this.filterBtn = $('#js-game-list-filter-btn');
_this.filter = $('#js-game-list-filter-tag');
_this.tagLists = _this.filter.find('.filter-tag-list');
_this.init = function(){
if(common.isAndroid) {
$('.game-list').css('minHeight', $(window).height() - $('.footer').height() - $('.header').height() + 'px');
}
common.goBack();
common.filterSwitch(_this.filterBtn, _this.filter);
_this.getList();
_this.loadMore();
}
_this.getList = function() {
var url;
url = common.domain + '/gameGroup/list.action?pageIndex='+ _this.pageIndex +'&tag=' + _this.tagId;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data){
render(data);
if(_this.pageIndex === 0) {
renderTagList(data.data.subNav);
}
if(_this.pageIndex == data.nextIndex) {
_this.loadMoreBtn.hide();
} else {
_this.pageIndex = data.nextIndex;
_this.loadMoreBtn.show();
}
}
})
}
function render(data){
var html = template('gameList', data);
// console.log(html);
if(_this.pageIndex === 0) {
_this.gameList.html(html);
} else {
_this.gameList.append(html);
}
}
function renderTagList(data) {
var html = '';
html = '<a data-id="0" class="span2 '+ (_this.tagId == 0 ? 'on' : '') +'" href="javascript:;">全部</a>';
data.forEach(function(item, index, arr){
html += '<a data-id="' + item['typeId'] + '" class="span2 '+ (_this.tagId == item['typeId'] ? 'on' : '') +'" href="javascript:;">'+ item['name'] +'</a>';
})
// console.log(html);
_this.tagLists.html(html);
_this.filterChange();
}
_this.filterChange = function() {
var filterName = _this.tagLists.find('a');
filterName.tap(function(){
// console.log("TO DO");
_this.pageIndex = 0;
_this.tagId = $(this).data('id');
_this.getList();
})
}
_this.loadMore = function() {
_this.loadMoreBtn.tap(function(){
_this.getList();
})
}
return {
'init': _this.init
}
}
var gameList = new GameList();
gameList.init();
})($)
| mit |
tpstps/ncertsolutions | resources/views/blog/layouts/triangles-10.blade.php | 74117 | @extends('blog.layouts.math')
@section('content')
<br/>
<br/>
<div class="alert alert-danger" role="alert"> If you are seeing MATH PROCESSING ERROR,try ctrl + F5(hard refresh),if that doesnt solve ,clear the cache of your browser</div>
<p><strong><em>Exercise 6.2</em></strong></p>
<p><strong>Question 1:<br/>
1. In Fig. 6.17, (i) and (ii), DE || BC. Find EC in (i) and AD in (ii).
Fig. 6.17</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-1.png" alt="8" width="600" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>i)It is given that DE || BC,then using basic proportionality theorem </p>
<p>\( \frac{AD}{DB} = \frac{AE}{EC} \)</p>
<p>\( \frac{1.5}{3} = \frac{1}{EC} \)</p>
<p>EC = 2 cm </p>
<p>ii)\( \frac{AD}{DB} = \frac{AE}{EC} \)</p>
<p>\( \frac{AD}{7.2} = \frac{1.8}{5.4} \)</p>
<p>AD = 2.4 cm </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 2:<br/>
E and F are points on the sides PQ and PR
respectively of a Δ PQR. For each of the following
cases, state whether EF || QR :
(i) PE = 3.9 cm, EQ = 3 cm, PF = 3.6 cm and FR = 2.4 cm
(ii) PE = 4 cm, QE = 4.5 cm, PF = 8 cm and RF = 9 cm
Fig. 6.18
(iii) PQ = 1.28 cm, PR = 2.56 cm, PE = 0.18 cm and PF = 0.36 cm</strong></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>i) \( \frac{PE}{EQ} = \frac{3.9}{3} = 1.3 ,\frac{PF}{FR} = \frac{3.6}{2.4} = 1.5 \) </p>
<p>Since \( \frac{PE}{EQ} \ne \frac{PF}{FR} \) </p>
<p>ii) \( \frac{PE}{EQ} = \frac{4}{4.5} = \frac{8}{9} ,\frac{PF}{FR} = \frac{8}{9} \) </p>
<p>Since \( \frac{PE}{EQ} = \frac{PF}{FR} ,EF || QR \)
<p>iii) \( \frac{PE}{EQ} = \frac{1.28}{2.56} = \frac{1}{2} ,\frac{PF}{FR} = \frac{.18}{0.36} = \frac{1}{2} \) </p>
<p>Since \( \frac{PE}{EQ} = \frac{PF}{FR} ,EF || QR \)
</div>
<p> </p>
<p> </p>
<p><strong>Question 3:<br/>
In Fig. 6.18, if LM || CB and LN || CD, prove that
\( \frac{AM}{AN} = \frac{AB}{AD} \)
</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-3.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>In ACB,LM || CB</p>
<p>Using basic proportionality theorem </p>
<p>\( \frac{AL}{LC} = \frac{AM}{MB} ...(1) \) </p>
<p>In ACD,LN || CD</p>
<p>Using basic proportionality theorem </p>
<p>\( \frac{AN}{ND} = \frac{AL}{LC} ...(2) \) </p>
<p>From i) and ii) </p>
<p>\( \frac{AN}{ND} = \frac{AM}{MB} \)</p>
<p>\( \frac{AN}{AD - AN} = \frac{AM}{AB - AM} \)</p>
<p>\( \frac{AD - AN}{AN} = \frac{AB - AM}{AM} \)</p>
<p>\( \frac{AD}{AN} - 1 = \frac{AB}{AM} - 1 \)</p>
<p>\( \frac{AD}{AN} = \frac{AB}{AM} \)</p>
<p>\( \frac{AN}{AD} = \frac{AM}{AB} \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 4:<br/>
In Fig. 6.19, DE || AC and DF || AE. Prove that
\( \frac{BF}{BE} = \frac {BE}{EC} \) </strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-4.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>DE || AC </p>
<p>By basic proportionality theorem</p>
<p>\( \frac{BE}{EC} = \frac{BD}{DA} ....(1) \)</p>
<p>Also </p>
<p>DF || AE </p>
<p>By basic proportionality theorem</p>
<p>\( \frac{BD}{DA} = \frac{BF}{FE} ...(2) \)</p>
<p>from 1 and 2 </p>
<p>\( \frac{BF}{FE} = \frac{BE}{EC} \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 5:<br/>
In Fig. 6.20, DE || OQ and DF || OR. Show that
EF || QR.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-5.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>Consider triangle PQO ,DE || OQ</p>
<p>By basic proportionality theorem </p>
<p>\( \frac{PE}{EQ} = \frac{PD}{DO} ...(1) \)</p>
<p>Consider triangle POR,DF || OR </p>
<p> \( \frac{PD}{DO} = \frac{PF}{FR} ....(2) \) </p>
<p>From 1 and 2 </p>
<p>\( \frac{PE}{EQ} = \frac{PF}{FR} \)</p>
<p>Now consider triangle PQR,E and F are two points on sides PQ and PR such that
\( \frac{PE}{EQ} = \frac{PF}{FR} \)</p>
<p>So by converse of basic proportionality theorem </p>
<p>EF || QR </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 6:<br/>
In Fig. 6.21, A, B and C are points on OP, OQ and
OR respectively such that AB || PQ and AC || PR.
Show that BC || QR.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-6.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>Consider triangle OPQ ,AB || PQ</p>
<p>By basic proportionality theorem </p>
<p>\( \frac{OA}{AP} = \frac{OB}{BQ} ...(1) \)</p>
<p>Consider triangle OPR,AC || PR </p>
<p> \( \frac{OA}{AP} = \frac{OC}{OR} ....(2) \) </p>
<p>From 1 and 2 </p>
<p>\( \frac{OB}{BQ} = \frac{OC}{OR} \)</p>
<p>Now consider triangle OQR,B and C are two points on sides OQ and OR such that
\( \frac{OB}{BQ} = \frac{OC}{OR} \)</p>
<p>So by converse of basic proportionality theorem </p>
<p>BC || QR </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 7:<br/>
Using Theorem 6.1, prove that a line drawn through
the mid-point of one side of a triangle parallel to
another side bisects the third side. (Recall that you
have proved it in Class IX)</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-7.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>Consider triangle ABC ,PQ || CD</p>
<p>By basic proportionality theorem </p>
<p>\( \frac{AP}{PB} = \frac{AQ}{QC} ...(1) \)</p>
<p> \( \frac{AP}{PB} = \frac{AP}{AP} = 1 ....(2) \) </p>
<p>\( \frac{AQ}{QC} = 1,AQ = QC \)</p>
<p>Hence prooved.</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 8:<br/>
Using Theorem 6.2, prove that the line joining the
mid-points of any two sides of a triangle is parallel
to the third side. (Recall that you have done it in
Class IX).</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-7.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>It is given that AP = PB and AQ = QC</p>
<p>\( \frac{AP}{PB} = 1 \)</p>
<p>\( \frac{AQ}{QC} = 1 \)</p>
<p>So P and Q are two points on side AB and AC such that
\( \frac{AP}{PB} = \frac{AQ}{QC} \)</p>
<p>so by converse of basic proportionality theorem </p>
<p>The line joining mid points i.e PQ is parallel to BC</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 9:<br/>
ABCD is a trapezium in which AB || DC and its
diagonals intersect each other at the point O. Show
that
\( \frac{AO}{BO} = \frac{CO}{DO} \)</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-9.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is a good question,at this point we know we are doing exercise on basic proportionality theorem
and it becomes easy to solve questions based on that,but in the exams we will not know which question is
from which exercise and is based on what concept so we should have some idea on which theorem can be helpful in the question</p>
<p>In this question we have to prove two ratios to be equal and we know only one such theorem which deals
with ratio is basic proportionality theorem </p>
<p>Now we need \( \frac{A0}{CO} \),for that we will have to draw a line EF || CD </p>
<p>Consider triangle ADC , EO || CD</p>
<p>\( \frac{AE}{ED} = \frac{AO}{OC} \) ...(1) </p>
<p>Consider triangle ADB , EO || CD</p>
<p>\( \frac{AE}{ED} = \frac{BO}{OD} \) ...(2) </p>
<p>From 1 and 2,we get </p>
<p>\( \frac{AO}{OC} = \frac{BO}{OD} \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 10:<br/>
The diagonals of a quadrilateral ABCD intersect each other at the point O such that
\( \frac{AO}{BO} = \frac{CO}{DO} \). Show that ABCD is a trapezium.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-9.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is converse of previous question </p>
<p>Draw a line EO || AB </p>
<p>EO || CD </p>
<p>By using proportionality theorem </p>
<p>\( \frac{AE}{ED} = \frac{BO}{OD} \) ... (1)</p>
<p>But it is given that,</p>
<p>\( \frac{AO}{OC} = \frac{OB}{OD} \) .... (2)</p>
<p>from 1 and 2 </p>
<p>\( \frac{AE}{ED} = \frac{AO}{OC} \)</p>
<p>Now in ADC ,E and O are such points such that</p>
<p>\( \frac{AE}{ED} = \frac{AO}{OC} \)</p>
<p>so by converse of basic proportionality theorem </p>
<p>EO || CD but EO || AB too</p>
<p>so AB || CD,hence the given quadrilateral is a trapezium </p>
</div>
<p> </p>
<p> </p>
<p><strong><em>Exercise 6.3</em></strong></p>
<p><strong>Question 1:<br/>
State which pairs of triangles in Fig. 6.34 are similar. Write the similarity criterion used by
you for answering the question and also write the pairs of similar triangles in the symbolic
form.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-1-1.png" alt="8" width="400" height="300" /></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-1-2.png" alt="8" width="400" height="300" /></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-1-3.png" alt="8" width="400" height="300" /></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-1-4.png" alt="8" width="400" height="300" /></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-1-5.png" alt="8" width="400" height="300" /></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-1-6.png" alt="8" width="400" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>We have two rule for similarity of triangles,one is AAA similarity and other is SAS similarity</p>
<p>Make sure you have read the proof of these AA and SAS rule from ncert</p>
<p>(i)</p>
<p>∠A=∠P = 60<sup>o </sup>(Given)</p>
<p>∠B =∠Q = 80<sup>o</sup>(Given)</p>
<p>∠C =∠R = 40<sup>o</sup>(given)</p>
<p>∴ Δ ABC ~ ΔPQR (AAA similarity criteria)</p>
<p>(ii)</p>
<p>AC/PQ = BC/PR = AB/QR<br />
∴ ΔACB ~ ΔQPR (SSS similarity criterion)</p>
<p> </p>
<p>(iii)<br/>
The given triangles are not similar as corresponding sides are not in proportion </p>
<p>iv)</p>
<p>∠M = ∠Q</p>
<p>\( \frac{MN}{PQ} = \frac{ML}{QR} \)</p>
<p>Since one angle and sides containing that angle are in proportion</p>
<p>∴ ΔNML ~ ΔPQR (By SSS similarity criterion)</p>
<p>v)The given triangles BAC ,DEF are not similar to as though <br/>
<p>∠A = ∠F</p>
<p>\( but \frac{BA}{DF} = \frac{1}{2} and \frac{AC}{FE} is not known asa length of AC is not known \)</p>
<p>vi)</p>
<p>∠F = 180 - 150 = 30</p>
<p>∠E = ∠Q = 80<sup>o </sup>(Given)</p>
<p>∠F =∠R = 70<sup>o</sup>(Given)</p>
<p>∠D =∠P = 30<sup>o</sup>(given)</p>
<p>Therefore by AAA similarity ΔEFD ~ ΔQRP </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 2:<br/>
In Fig. 6.35, Δ ODC ~ Δ OBA, ∠ BOC = 125° and ∠ CDO = 70°. Find ∠ DOC, ∠ DCO and
∠ OAB.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-2.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p><strong><em> </em></strong>DOB is a straight line.<br />
Thus, ∠DOC + ∠ COB = 180°<br />
⇒ ∠DOC = 180° – 125°<br />
= 55°</p>
<p>In ΔDOC,<br />
∠DCO+ ∠ CDO + ∠ DOC = 180°<br />
(Sum of the measures of the angles of a triangle is 180º.)<br />
⇒ ∠DCO + 70º + 55º = 180°<br />
⇒ ∠DCO = 55°<br />
Given that ΔODC ~ ΔOBA.</p>
<p>∴ ∠OAB = ∠OCD (Corresponding angles are equal in similar triangles)<br />
⇒ ∠ OAB = 55°<br />
∴ ∠OAB= ∠OCD (Corresponding angles are equal in similar triangles)</p>
<p>⇒ ∠OAB= 55°</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 3:<br/>
Diagonals AC and BD of a trapezium ABCD with AB || DC intersect each other at the
point O. Using a similarity criterion for two triangles, show that
\( \frac{OA}{OC} = \frac{OB}{OD} \).</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-9.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>In ΔCOD and ΔAOB,<br />
∠DCO = ∠ABO (Alternate interior angles as AB || DC)<br />
∠CDO = ∠BAO (Alternate interior angles as AB || DC)<br />
∠COD = ∠BOA (Vertically opposite angles)<br />
∴ ΔCOD ~ ΔBOA (AAA similarity criterion)</p>
<p>∴ CO/BO = OD/OA (Corresponding sides are proportional)</p>
<p>⇒ OA/OD = OB/OC</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 4:<br/>
In fig 6.36 ∠ 1 = ∠ 2 and \( \frac{OA}{OC} = \frac{OB}{OD} \).Show that Δ PQS ~ Δ TQR </p></strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-2-9.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>We have to prove Δ PQS ~ Δ TQR ,we are also given a ratio,so it should be clear we will be using SAS
congruence condition </p>
<p>We are given one more condition also ,∠ 1 = ∠ 2 ,so we may want to use that information </p>
<p>Now if you consider Δ PQS and Δ TQR</p>
<p>We have ∠ 1 = ∠ 1 (common)</p>
<p>Now if we can prove that the ratio of sides including the angle 1 is also equal ,then we can
prove the traingles similarity by SAS congruence condition </p>
<p>We want to proove </p>
<p>\( \frac{PQ}{TQ} = \frac{SQ}{RQ} \)</p>
<p>We are given \( \frac{QR}{QS} = \frac{QT}{PR} \)</p>
<p>\( \frac{QS}{QR} = \frac{PR}{QT} \) </p>
<p>\( \frac{QS}{QR} = \frac{PQ}{QT} \) (Since ∠ 1 = ∠ 2 so PQ = PR) </p>
<p>So by SAS similarity condition Δ PQS ~ Δ TQR </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 5:<br/>
S and T are points on sides PR and QR of
Δ PQR such that ∠ P = ∠ RTS. Show that
Δ RPQ ~ Δ RTS.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-5.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>In ΔRPQ and ΔRST,<br />
∠R = ∠R (Common angle)<br />
∠RTS = ∠QPS (Given)<br />
∴ ΔRPQ ~ ΔRTS (By AA similarity criterion)</p>
<p>Take care of symbolic notation,otherwise examiner may give you no marks at all</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 6:<br/>
In Fig. 6.37, if Δ ABE ≅ Δ ACD, show that
Δ ADE ~ Δ ABC.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-6.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>Given, that ΔABE ≅ ΔACD.<br />
∴ AB = AC [By cpct] … (i)<br />
Also, AD = AE [By cpct] … (ii)<br />
In ΔADE and ΔABC,</p>
<p>AD/AB = AE/AC [Dividing equation (ii) by (i)]</p>
<p>∠A = ∠A [Common angle]<br />
∴ ΔADE ~ ΔABC [By SAS similarity criterion]</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 7:<br/>
In Fig. 6.38, altitudes AD and CE of Δ ABC
intersect each other at the point P. Show
that:
(i) Δ AEP ~ Δ CDP
(ii) Δ ABD ~ Δ CBE
(iii) Δ AEP ~ Δ ADB
(iv) Δ PDC ~ Δ BEC.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-7.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>(i) In ΔAEP and ΔCDP,</p>
<p>∠AEP = ∠CDP (Each 90°)</p>
<p>∠APE = ∠CPD (Vertically opposite angles)</p>
<p>Thus, by using AA similarity criterion,</p>
<p>ΔAEP ~ ΔCDP</p>
<p>(ii) In ΔABD and ΔCBE,</p>
<p>∠ADB = ∠CEB (Each 90°)</p>
<p>∠ABD = ∠CBE (Bommon)</p>
<p>Hence, by using AA similarity criterion,</p>
<p>ΔABD ~ ΔCBE</p>
<p>(iii) In ΔAEP and ΔADB,</p>
<p>∠AEP = ∠ADB (Each 90°)</p>
<p>∠PAE = ∠DAB (Bommon)</p>
<p>Hence, by using AA similarity criterion,</p>
<p>ΔAEP ~ ΔADB</p>
<p>(iv) In ΔPDC and ΔBEC,</p>
<p>∠PDB = ∠BEB (Each 90°)</p>
<p>∠PCD = ∠BCE (Bommon angle)</p>
<p>Hence, by using AA similarity criterion,</p>
<p>ΔPDC ~ ΔBEC</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 8:<br/>
E is a point on the side AD produced of a
parallelogram ABCD and BE intersects CD
at F. Show that Δ ABE ~ Δ CFB..</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-8.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
In ΔABE and ΔCFB,
∠A = ∠C (Opposite angles of a parallelogram)
∠AEB = ∠CBF (Alternate interior angles as AE || BC)
∴ ΔABE ~ ΔCFB (By AA similarity criterion)
</div>
<p> </p>
<p> </p>
<p><strong>Question 9:<br/>
In Fig. 6.39, ABC and AMP are two right
triangles, right angled at B and M
respectively. Prove that:
(i) Δ ABC ~ Δ AMP
(ii)
CA BC
PA MP.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-9.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
p>(i) In ΔABC and ΔAMP, we have</p>
<p>∠A= ∠A (common angle)</p>
<p>∠ABC = ∠AMP = 90° (each 90°)</p>
<p>∴ ΔABC ~ ΔAMP (By AA similarity criterion)</p>
<p> </p>
<p>(ii) Since, ΔABC ~ ΔAMP (By AA similarity criterion)</p>
<p>If two triangles are similar then the corresponding sides are equal,</p>
<p>Hence, CA/PA = BC/MP</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 10:<br/>
CD and GH are respectively the bisectors
of ∠ ACB and ∠ EGF such that D and H lie
on sides AB and FE of Δ ABC and Δ EFG
respectively. If Δ ABC ~ Δ FEG, show that:
(i)
CD AC
GH
FG
(ii) Δ DCB ~ Δ HGE
(iii) Δ DCA ~ Δ HGF</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-10.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
(i) Given that ΔABC ~ ΔFEG
∴ ∠A = ∠F, ∠B = ∠G, and ∠ACB = ∠FEG
∠ACB = ∠FEG
∴ ∠ACD = ∠FGH (Angle bisector)
And, ∠DCB = ∠HEG (Angle bisector)
In ΔDAC and ΔFEH,
∠A = ∠F (Proved above)
∠DCA = ∠FEH (Proved above)
∴ ΔDAC ~ ΔFEH (By AA similarity criterion)
⇒ CD/EH = AC/FE
(ii) In ΔBCD and ΔHEG,
∠BCD = ∠HE; (Proved above)
∠B = ∠G (Proved above)
∴ ΔBCD ~ ΔHEG (By AA similarity criterion)
(iii) In ΔACD and ΔHFE
∠DCA = ∠FEH (Proved above)
∠A = ∠F (Proved above)
∴ ΔACD ~ ΔHFE (By AA similarity criterion)
</div>
<p> </p>
<p> </p>
<p><strong>Question 11:<br/>
In Fig. 6.40, E is a point on side CB
produced of an isosceles triangle ABC
with AB = AC. If AD ⊥ BC and EF ⊥ AC,
prove that Δ ABD ~ Δ ECF..</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-11.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>It is given that ABC is an isosceles triangle.<br />
∴ AB = AC<br />
⇒ ∠ABD = ∠ECF<br />
In ΔABD and ΔECF,<br />
∠ADB = ∠EFC (Each 90°)<br />
∠BAD = ∠CEF (Proved above)<br />
∴ ΔABD ~ ΔECF (By using AA similarity criterion)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 12:<br/>
Sides AB and BC and median AD of a
triangle ABC are respectively propor-
tional to sides PQ and QR and median
PM of Δ PQR (see Fig. 6.41). Show that
Δ ABC ~ Δ PQR..</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-12.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>It is given that:</p>
<p>ΔACB and ΔPQN, AB, CB and median AD of ΔACB are proportional to sides PQ, QN and median PM of ΔPQN</p>
<p>Or, AB/PQ = BC/QR= AD/PM </p>
<p>To Prove: ΔACB ~ ΔPQN</p>
<p> </p>
<p>Proof:\( \frac{AB}{PQ} = \frac{BC}{QN} =\frac{AD}{PM} \)</p>
<p> </p>
<p>⇒\( \frac{AB}{PQ} = \frac{AD}{PM} = \frac{\frac{1}{2}BC}{\frac{1}{2}QN} = \frac{BD}{QM}\) (D is the mid-point of BC and M is the midpoint of QN)</p>
<p>⇒ ΔABD ~ ΔPQM [SSS similarity criterion]</p>
<p>∴ ∠ABD = ∠PQM [Corresponding angles of two similar triangles are equal]</p>
<p>⇒ ∠ABC = ∠PQN</p>
<p>In ΔABC and ΔPQR</p>
<p>AB/PQ = BC/QN ….(i)</p>
<p>∠ABC = ∠PQR….. (ii)</p>
<p>Hence, from equation (i) and (ii), we get</p>
<p>ΔABC ~ ΔPQR [By SAS similarity criterion]</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 13:<br/>
D is a point on the side BC of a triangle
ABC such that ∠ ADC = ∠ BAC. Show
that \( CA^{2} = CB.CD \)</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-13.png" alt="8" width="500" height="500" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>In ΔCAD and ΔABC,<br />
∠CDA = ∠CAB (Given)<br />
∠ACD = ∠BCA (Common angle)<br />
∴ ΔADC ~ ΔBAC (By AA similarity criterion)<br />
We know that corresponding sides of similar triangles are in proportion.</p>
<p>∴ CA/BC =CD/AC</p>
<p>⇒ CA<sup>2</sup> = CB.DC.</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 14:<br/>
Sides AB and AC and median AD of a
triangle ABC are respectively
proportional to sides PQ and PR and
median PM of another triangle PQR.
Show that Δ ABC ~ Δ PQR..</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-14.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>It is given that:</p>
<p>Two triangles ΔABC and ΔPQR in which AD and PM are medians such that AB/PQ = CA/PR = AD/PM</p>
<p>To Prove: ΔABC ~ ΔPQR</p>
<p>Construction: Produce AD to E such that AD = DE. Connect CE. Similarly produce PM to L so that PM = ML, also connect RL.</p>
<p> </p>
<p>Proof:</p>
<p>In ΔABD and ΔDCE, we have</p>
<p> </p>
<p>AD = DE [By Construction]</p>
<p>BD = DC [∴ AP is the median]</p>
<p>And, ∠ADB = ∠CDE [Vertically opp. angles]</p>
<p>∴ ΔADB ≅ ΔCDE [By SAS criterion of congruence]</p>
<p>⇒ AB = CE [CPCT] ….. (i)</p>
<p> </p>
<p>Also, in ΔPQM and ΔMLR, we have</p>
<p>PM = ML [By Construction]</p>
<p>QM = MR [∴ PM is the median]</p>
<p>and, ∠PMQ = ∠LMR [Vertically opposite angles]</p>
<p>∴ ΔPMQ = ΔMRL [By SAS criterion of congruence]</p>
<p>⇒ PQ = RL [CPCT] …. (ii)</p>
<p>Low, AB/PQ = AC/PR = AD/PM</p>
<p>⇒ CE/RL = AC/PR = AD/PM … [Erom (i) and (ii)]</p>
<p>⇒ CE/RL = AC/PR = 2AD/2PM</p>
<p>⇒ CE/RL = AC/PR = AE/PL [∴ 2AD = AE and 2PM = PL]</p>
<p>∴ ΔACE ~ ΔPRL [By SSS similarity criterion]</p>
<p>Therefore, ∠DAC = ∠MPR</p>
<p>Similarly, ∠BAC = ∠QPM</p>
<p>∴ ∠BAC + ∠DAC = ∠QPM + ∠MPR</p>
<p>⇒ ∠A = ∠P … (iii)</p>
<p>Now, In ΔABC and ΔPQR, we have</p>
<p>AB/PQ = AC/PR (Given)</p>
<p>∠A = ∠P [Erom (iii)]</p>
<p>∴ ΔABC ~ ΔPQR [By SAS similarity criterion]</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 15:<br/>
A vertical pole of length 6 m casts a shadow 4 m long on the ground and at the same time
a tower casts a shadow 28 m long. Find the height of the tower.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>Length of the vertical pole = 6m (Given)</p>
<p>Shadow of the pole = 4 m (Given)</p>
<p>Let Height of tower = <em>h</em> m</p>
<p>Length of shadow of the tower = 28 m (Given)</p>
<p>In ΔABC and ΔPRQ,</p>
<p>∠C = ∠R (angular elevation of sum)</p>
<p>∠B = ∠Q = 90°</p>
<p>∴ ΔABC ~ ΔPRQ (By AA similarity criterion)</p>
<p>∴ AB/PQ = BC/RQ (when two triangles are similar corresponding sides are proportional)</p>
<p>∴ 6/<em>h</em> = 4/28</p>
<p>⇒ <em>h</em> = 6×28/4</p>
<p>⇒ <em>h</em> = 6 × 7</p>
<p>⇒ <em>h </em>= 42 m</p>
<p>Therefore, the height of the tower is 42 m.</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 16:<br/>
If AD and PM are medians of triangles ABC and PQR, respectively where
AB AD
Δ ABC ~ Δ PQR, prove that PQ PM</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-3-15.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>It is given that: ΔABC ~ ΔPQR </p>
<p>We know that, the corresponding sides of similar triangles are in proportion</p>
<p>∴ AB/PQ = AC/PR = BC/QR … (i)</p>
<p>Also, ∠ A= ∠P, ∠B = ∠Q, ∠C = ∠R …(ii)</p>
<p>As AD and PM are medians, their opposite sides will be divided by them<?p>
<p>∴ BD = BC/2 and QM = QR/2 …(iii)</p>
<p>From equations (i) and (iii), we have</p>
<p>AB/PQ = BD/QM …(iv)</p>
<p>In ΔABD and ΔPQM,</p>
<p>∠B = ∠Q [Using equation (ii)]</p>
<p>AB/PQ = BD/QM [Using equation (iv)]</p>
<p>∴ ΔABD ~ ΔPQM (By SAS similarity criterion)</p>
<p>⇒ AB/PQ = BD/QM = AD/PM.</p>
</div>
<p> </p>
<p> </p>
<p><strong><em>Exercise 6.4</em></strong></p>
<p><strong>Question 1:<br/>
Let Δ ABC ~ Δ DEF and their areas be, respectively, 64 cm 2 and 121 cm 2 . If EF =
15.4 cm, find BC.</strong></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>Given,</p>
<p>The area of a ∆ ABC = 64 cm<sup>2</sup></p>
<p>The area of a ∆ DEF = 121 cm<sup>2</sup></p>
<p>EF = 15.4 cm</p>
<p>And ∆ ABC ~ ∆ DEF</p>
<p>Therefore, area of triangle ABC/ Area of triangle DEF = AB<sup>2</sup> / DE<sup>2</sup></p>
<p>= BC<sup>2</sup> / EF<sup>2</sup> = CA<sup>2</sup> / DF<sup>2</sup> – – – – – – – – – – (1)</p>
<p>[If the two triangles are similar then the ratio of their areas are said to be equal to the square of the ratio of their corresponding sides]</p>
<p>Therefore, 64 / 121 = BC<sup>2</sup> / EF<sup>2</sup></p>
<p>=> (8/11)<sup>2 </sup>= (BC`/15.4)<sup>2</sup></p>
<p>=> 8/11 = BC / 15.4</p>
<p>=> BC = 8 x 15.4 / 11</p>
<p>=> BC = 8 x 1.4</p>
<p>BC = 11.2 cm</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 2:<br/>
Diagonals of a trapezium ABCD with AB || DC intersect each other at the point O.
If AB = 2 CD, find the ratio of the areas of triangles AOB and COD.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-4-2.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>ABCD is a trapezium having AB ǁ DC. The diagonals AB and CD intersect each other at a point O.</p>
<p>In ∆ OAB and ∆ COD, we have</p>
\(\angle OAB = \angle OCD (Alternate\:\, angles)\)<br/>
\(\angle OBA = \angle ODC \, (Alternate\, angles)\)<br/>
\(\angle AOB=\angle COD\, (Vertically\, opposite\, angle)\) <br/>
<p>Therefore, ∆ ABO ~ ∆ CDO [By AAA similarity criterion]</p>
<p>Now, Area of (∆ABO) / Area of (∆CDO)</p>
<p>= AB<sup>2</sup> / CD<sup>2 </sup>[If two triangles are similar then the ratio of their areas are equal to the square of the ratio of their corresponding sides]</p>
<p>= (2CD)<sup>2 </sup>/ CD<sup>2 </sup>[Therefore, PQ=RS]</p>
<p>Therefore, Area of (∆ PAQ)/ Area of (∆RAS)</p>
<p>= 4AB<sup>2</sup>/ CD = 4/1</p>
<p>Hence, the required ratio of the area of ∆ABO and ∆CDO = 4:1</p>
<p> </p>
<p> </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 3:<br/>
In Fig. 6.44, ABC and DBC are two triangles on the
same base BC. If AD intersects BC at O, show that
\( \frac{ar (ABC)}{ar (DBC)} = \frac{A0}{DO} .</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-4-3.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>After seeing the question,we realize we have to proove something on ratio of area</br>
We know a result for ratio of areas which is equal to the square of corresponding sides but for that the two triangles
need to be similar </p>
<p>There is only one thing we can make use of that traingles are on same base </p>
<p>Draw perpeniculars AP and DM </p>
<p>\( \frac{ar (ABC)}{ar (DBC)} = \frac {\frac{1}{2}\times BC\times AP } {\frac{1}{2}\times DM\times BC } \)</p>
<p>\( \frac{ar (ABC)}{ar (DBC)} = \frac{AP}{DM} \) ... (1)</p>
<p>Now in triangle APO and DMO </p>
<p>APO = DMO = 90 </p>
<p>AOP = DOM (Vertically opposite angles) </p>
<p>APO ~ DMO (By AA Similarity criterion) </p>
<p>\( \frac{AP}{DM} = \frac{AO}{DO} \)</p>
<p>From 1, \( \frac{ar (ABC)}{ar (DBC)} = \frac{AO}{DO} \) </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 4:<br/>
If the areas of two similar triangles are equal, prove
that they are congruent.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-4-3.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is simple too,we know ratio of area of traingles is equal to ratio of square of sides,since areas
are equal then we have square of each side of triangle = square of another side of triangle,hence
we can show that all corresponding sides of trinagles are equal </p>
<p>\( \frac{area ABC}{area PQR} = (\frac{AB}{PQ})^{2} = (\frac{BC}{QR})^{2} = (\frac{AC}{PR})^{2} \)</p>
<p>\( 1 = (\frac{AB}{PQ})^{2} = (\frac{BC}{QR})^{2} = (\frac{AC}{PR})^{2} \)</p>
<p>AB = PQ,BC = QR ,AC = PR </p>
<p>Hence triangles are congruent </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 5:<br/>
D, E and F are respectively the mid-points of sides AB, BC and CA of Δ ABC. Find the
ratio of the areas of Δ DEF and Δ ABC.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-4-5.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is a good question: </p>
<p>D and E are mid points of ABC </p>
<p>Therefore \( \frac{AD}{DB} = \frac{BE}{EC} = 1 \)</p>
<p>So by basic proportionality theorem </p>
<p>DE || AC </p>
<p>In triangle BDE and BAC </p>
<p>\( B = B (Common) \)</p>
<p>BED = BCA (Corresponding angles ) </p>
<p>So by AA similarity criterion,trinagles BED ~ BCA</p>
<p>\( \frac{BE}{BC} = \frac{DE}{AC} = \frac{1}{2} \)</p>
<p>Also \( \frac{area BED}{area BCA} = (\frac{DE}{AC})^{2} = = \frac{1}{4} \) </p>
<p>Similarly \( \frac{area CEF}{area BCA} = \frac{1}{4} \) </p>
<p>\( \frac{area ADE}{area BCA} = \frac{1}{4} \) </p>
<p>area of DEF = area of ABC - (area ADE + area BDE + area FEC) = area of ABC - \( \frac{3}{4}\times area of ABC = \frac{1}{4}\times area of ABC \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 6:<br/>
Prove that the ratio of the areas of two similar triangles is equal to the square of the ratio
of their corresponding medians.</strong></p>
<p><img class="alignone wp-image-2112" src="/images/10/0/triangles/10-0-6-4-6.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>We have done a similar kind of question in previous exercise,where we have prooved
that ratio of sides of similar triangles = equal to ratio of their corresponding medians ,after that its trivial</p>
<p>Since AD is the median BD = \( \frac{1}{2}BC \) </p>
<p>Also PS is the median so QS = \( \frac{1}{2}QR \)</p>
<p>Since triangles are similar \( \frac{AB}{PQ} = \frac{BC}{QR} = \frac{\frac{1}{2}\times BC }{\frac{1}{2}\times QR} = \frac{BD}{QS} \)</p>
<p>In triangles ABD and PQS </p>
<p>B = Q </p>
<p>\( \frac{AB}{PQ} = \frac{BD}{QS} \)</p>
<p>So by SAS similarity citerion </p>
<p>ABD PQS </p>
<p>\( \frac{AB}{PQ} = \frac{AD}{PS} \)</p>
<p>\( \frac{area ABC}{area PQR} = (\frac{AB}{PQ})^{2} = (\frac{AD}{PS})^{2} \)</p>
<p>Hence prooved </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 7:<br/>
Prove that the area of an equilateral triangle described on one side of a square is equal
to half the area of the equilateral triangle described on one of its diagonals..</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-4-7.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is actually a very good question and at the same time simple too </p>
<p>Let the side of square be a </p>
<p>Then we have side of equialteral trianagle described on one side is a </p>
<p>Length of side of equilateral triangle on diagonal = \( \sqrt{a^{2} + a^{2}} = \sqrt{2}\times a \)</p>
<p>All equilateral triangles are similar as all have angles of 60 </p>
<p>ratio of area of described on side to described on diagonal = \( (\frac{a}{\sqrt{2a}})^{2} = 1:2 \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 8:<br/>
Tick the correct answer and justify :
ABC and BDE are two equilateral triangles such that D is the mid-point of BC. Ratio of
the areas of triangles ABC and BDE is
(A) 2 : 1
(B) 1 : 2
(C) 4 : 1
(D) 1 : 4.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-4-9.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>It is given both are eui triangles so all angles are 60 </p>
<p>Let length of side of ∆ ABC is a </p>
<p>Length of side of ∆ BDE is \( \frac{a}{2} \) </p>
<p> Ratio of the areas of ∆ ABC and BDE = \( (\frac{a}{\frac{a}{2}})^{2} = \frac{1}{4} \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 9:<br/>
Tick the correct answer and justify :
Sides of two similar triangles are in the ratio 4 : 9. Areas of these triangles are in the ratio
(A) 2 : 3
(B) 4 : 9
(C) 81 : 16
(D) 16 : 81.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-4-9.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is simple.Correct answer 16:81 </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 1:<br/>
Sides of triangles are given below. Determine which of them are right triangles.
In case of a right triangle, write the length of its hypotenuse.
(i) 7 cm, 24 cm, 25 cm
(ii) 3 cm, 8 cm, 6 cm
(iii) 50 cm, 80 cm, 100 cm
(iv) 13 cm, 12 cm, 5 cm.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-1.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>In right angle triangle,the hypotenuse is the largest side and square of its sum is equal to the sum of square of
other two sides</p>
<p>i) \( 25^{2} = 625,7^{2} + 24^{2} = 675,Since 7^{2} + 24^{2} = 25^{2}\) ,the triangle is right angle,hypotenuse length is 25 cm </p>
<p>ii)\( 8^{2} = 64,3^{2} + 6^{2} = 9 + 36 = 45,Since 6^{2} + 3^{2} \ne 8^{2} \),its not a right triangle </p>
<p>iii) \( 100^{2} = 10000, 50^{2} + 80^{2} = 2500 + 6400 = 8900,Since 60^{2} + 80^{2} \ne 100^{2} \),its not a right triangle </p>
<p>iv) \( 13^{2} = 169,12^{2} + 5^{2} = 169,Since 12^{2} + 5^{2} = 13^{2} \),the triangle is right angle,hypotenuse length is 13 cm</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 2:<br/>
PQR is a triangle right angled at P and M is a point on QR such that PM ⊥ QR. Show that
\( PM^{2} = QM . MR \).</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-2.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>The first impression is can we use RHS congruence condition or some similarity of triangles</p>
<p>∆ PMR is similar to triangle PQR and so is PMQ,can we use the ratio of sides of these triangles to any use </p>
<p>But since we have square of PM ,we may try prooving similarity of triangles PMR and PMQ </p>
<p>MPR = x </p>
<p>then MQP = 180 - 90 - (90 - x) = x.
<p>In triangles MPR and MQP </p>
<p>PMR = PMQ = 90 </p>
<p>MPR = PQM </p>
<p>so by AA similarity </p>
<p>MPR ~ MQP </p>
<p>\( \frac{PM}{MR} = \frac{QM}{PM} \)</p>
<p>\( PM^{2} = QM . MR \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 3:<br/>
In Fig. 6.53, ABD is a triangle right angled at A
and AC ⊥ BD. Show that
(i) \( AB^{2} = BC . BD \)
(ii)\( AC^{2} = BC . DC \)
(iii)\( AD^{2} = BD . CD \)
Fig. 6.53.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-3.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is similar to question 2,the approach is exactly similar,the second part is identical so we will skip it.
<p>i)Since we have a term of \( AB^{2} \) ,consider triangle ABC and ABD </p>
<p>ACB = BAD </p>
<p>B = B (common)</p>
<p>By AA similarity condition </p>
<p> ABC ~ DBA </p>
<p>\( \frac{AB}{BC} = \frac{BD}{AB} \)</p>
<p>\( AB^{2} = BC . BD \)</p>
<p>ii)Similar to question 2<p>
<p>iii)Similar to i) part,take traingles ACD and ABD and apply AA and then proove</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 4:<br/>
ABC is an isosceles triangle right angled at C. Prove that \( AB^{2} = AC^{2} \)</strong></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is a very simple question,you just need apply pythagoras </p>
<p>Just a little attention or you can say common sense needed </p>
<p>ABC is an isosceles triangle ,right angle at C so AC is hypotenuse,so we cant have any other side
equal to largest side in triangle </p>
<p>so AC = CB </p>
<p>Using pythagoras we have </p>
<p>\( AB^{2} = AC^{2} + CB^{2} \)</p>
<p>\( AB^{2} = AC^{2} + AC^{2} = 2AC^{2} \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 5:<br/>
ABC is an equilateral triangle of side 2a. Find each of its altitudes./strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-5.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is a good question,its simple too </p>
<p>In right angle ∆ ABD and ACD (Since AD is an altitude) </p>
<p> AB = AC </p>
<p> AD= AD (Common) </p>
<p>So by RHS congruence condition </p>
<p>ABC ACD </p>
<p>BD = DC </p> (By C.P.C.T)
<p>BD + DC = 2a,BD + BD = 2a,2BD = 2a,BD = a </p>
<p>In ∆ ABD,using pythagoras </p>
<p>\( AB^{2} = AD^{2} + BD^{2} \)</p>
<p>\( (2a)^{2} = AD^{2} + a^{2} \)</p>
<p>\( 4a^{2} = AD^{2} + a^{2},AD = 3a^{2} = \sqrt{3}\times a \)</p>
<p>Similarlt length of all other altitude also \( \sqrt{3}\times a \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 6:<br/>
ABC is an isosceles triangle with AC = BC. If \( AB^{2} = 2 AC^{2} \) , prove that ABC is a right
triangle</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-6.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>\( AB^{2} = 2 AC^{2} \)</p>
<p>\( AB^{2} = AC^{2} + AC^{2} \)</p>
<p>\( AB^{2} = AC^{2} + BC^{2} \)</p>
<p>therefore ABC is a right triangle </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 7:<br/>
Prove that the sum of the squares of the sides of a rhombus is equal to the sum of the
squares of its diagonals.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-7.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This looks a difficult question but its easy to proove ,but you need to remember properties of rhombus </p>
<p>In rhombus,diagonals bisect each other at right angles </p>
<p>Rest is trivial,just apply pythagoras in all 4 triangles formed and add them </p>
<p>In ∆ OAB </p>
<p>\( AB^{2} = OA^{2} + OB^{2} \)</p>
<p>In ∆ OBC </p>
<p>\( BC^{2} = OB^{2} + OC^{2} \)</p>
<p>In ∆ OCD </p>
<p>\( CD^{2} = OC^{2} + OD^{2} \)</p>
<p>In ∆ ODA </p>
<p>\( AD^{2} = OA^{2} + OD^{2} \)</p>
<p>Adding all of them </p>
<p>\( AB^{2} + BC^{2} + CD^{2} + AD^{2} = OA^{2} + OB^{2} + OB^{2} + OC^{2} + OC^{2} + OD^{2} + OA^{2} + OD^{2} \)</p>
<p>\( AB^{2} + BC^{2} + CD^{2} + AD^{2} = 2( OA^{2} + OB^{2} + OC^{2} + OD^{2} ) \)</p>
<p>\( AB^{2} + BC^{2} + CD^{2} + AD^{2} = 2( OA^{2} + OB^{2} + OC^{2} + OD^{2} ) \)</p>
<p>\( AB^{2} + BC^{2} + CD^{2} + AD^{2} = 2( (\frac{AC}{2})^{2} + (\frac{AC}{2})^{2} + (\frac{BD}{2})^{2} + (\frac{BD}{2})^{2} ) \)</p>
<p>\( AB^{2} + BC^{2} + CD^{2} + AD^{2} = AC^{2} + BD^{2} \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 8:<br/>
In Fig. 6.54, O is a point in the interior of a triangle
ABC, OD ⊥ BC, OE ⊥ AC and OF ⊥ AB. Show that
(i) OA 2 + OB 2 + OC 2 – OD 2 – OE 2 – OF 2 = AF 2 + BD 2 + CE 2 ,
(ii) AF 2 + BD 2 + CE 2 = AE 2 + CD 2 + BF 2</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-8.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is simple too,we just have to apply pythagoras </p>
<p>In ∆ AOF </p>
<p>\( AO^{2} = OF^{2} + AF^{2} \)</p>
<p>In ∆ BOD </p>
<p>\( OB^{2} = OD^{2} + BD^{2} \)</p>
<p>In ∆ COE </p>
<p>\( OC^{2} = OE^{2} + EC^{2} \)</p>
<p>Adding these </p>
<p>\( AO^{2}+ OB^{2} + OC^{2} = OE^{2} + EC^{2} + OD^{2} + BD^{2} + OF^{2} + AF^{2} \)</p>
<p>\( AO^{2}+ OB^{2} + OC^{2} - OD^{2} - OE^{2} - OF^{2} = + EC^{2} + BD^{2} + AF^{2} \)</p>
<p>ii)From i) part</p>
<p>\( AF^{2} + BD^{2} + EC^{2} = AE^{2} + CD^{2} + BF^{2} \) </p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 9:<br/>
A ladder 10 m long reaches a window 8 m above the
ground. Find the distance of the foot of the ladder
from base of the wall.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-10.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is just plain and simple pythagoras </p>
<p>From the figure </p>
<p>\( 10^{2} = 8^{2} + x^{2} \)</p>
<p>\( 10^{2} - 8^{2} = x^{2} \)</p>
<p>\( x^{2} = 36 ,x = 6 \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 10:<br/>
A guy wire attached to a vertical pole of height 18 m
is 24 m long and has a stake attached to the other
end. How far from the base of the pole should the
stake be driven so that the wire will be taut?.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-9.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>Its also similar to previous question </p>
<p>A guy wire is attached from top of pole to a point in ground to provide stability to the pole </p>
<p>Its similar to various wires that are attached on ships </p>
<p>Using pythagoras theorem </p>
<p>\( 24^{2} = 18^{2} + x^{2} \)</p>
<p>\( 24^{2} - 18^{2} = x^{2} \)</p>
<p>\( x^{2} = 24^{2} - 18^{2} = 253 = 6\sqrt{7} m \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 11:<br/>
An aeroplane leaves an airport and flies due north at a speed of 1000 km per hour. At the
same time, another aeroplane leaves the same airport and flies due west at a speed of
1200 km per hour. How far apart will be the two planes after \( 1\times\frac{1}{2} \) hours??.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-11.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>Distance covered by plane flying at speed of 1000 km per hour = \( 1.5\times 1000 = 1500 \)</p>
<p>Distance travelled by plane flying at speed of 1200 km per hour = \(1.5\times 1200 = 1800 \) </p>
<p>Now since north and west and at right angle,we just need to use pythagoras theorem to fnd distance between them </p>
<p>Distance between them = \( 1500^{2} + 1800^{2} = 300\times \sqrt{61} \) </p>
</div>
<p> </p
<p> </p>
<p><strong>Question 12:<br/>
Two poles of heights 6 m and 11 m stand on a
plane ground. If the distance between the feet
of the poles is 12 m, find the distance between
their tops.?.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-12.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This question will become clear the moment you draw it </p>
<p>Using pythagoras theorem </p>
<p>Distnace between tops = \( \sqrt{5^{2} + 12^{2}} = \sqrt{169} = 13 \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 13:<br/>
D and E are points on the sides CA and CB
respectively of a triangle ABC right angled at C.
Prove that \( AE^{2} + BD^{2} = AB^{2} + DE^{2} \)</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-13.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>Since we need to proove \( AE^{2} + BD^{2},lets find their values \)</p>
<p>\( AE^{2} = AC^{2} + CF^{2} \)</p>
<p>\( BD^{2} = CD^{2} + BC^{2} \)</p>
<p>\( AE^{2} + BD^{2} = AC^{2} + CE^{2} + CD^{2} + BC^{2} \)</p>
<p>\( AE^{2} + BD^{2} = AC^{2} + BC^{2} + CD^{2} + CE^{2} \)</p>
<p>\( AE^{2} + BD^{2} = AB^{2} + DE^{2} \) (Applying pythagoras in ∆ ACE and DCE )</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 14:<br/>
The perpendicular from A on side BC of a
Δ ABC intersects BC at D such that DB = 3 CD
(see Fig. 6.55). Prove that \( 2AB^{2} = 2AC^{2} + BC^{2} \)</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-14.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>DB + CD = BC </p>
<p>3CD + CD = BC </p>
<p>CD = \( \frac{BC}{4} \)</p>
<p>BD = BC - CD = BC - \frac{BC}{4} = \frac{3BC}{4} </p>
<p>Using pythagoras in ∆ ACD</p>
<p>\( AC^{2} = AD^{2} + CD^{2} \)</p>
<p>\( AC^{2} = AD^{2} + (\frac{BC}{4})^{2} \) ...(1) </p>
<p>Using pythagoras in ∆ ABD</p>
<p>\( AB^{2} = AD^{2} + BD^{2} \)</p>
<p>\( AB^{2} = AD^{2} + (\frac{3BC}{4})^{2} \)</p>
<p>Now we dont need a term involving AD,so we will substitue AD value from 1 in 2 </p>
<p>\( AB^{2} = AD^{2} + (\frac{3BC}{4})^{2} \)</p>
<p>\( AB^{2} = AC^{2} - (\frac{BC}{4})^{2} + (\frac{3BC}{4})^{2} \)</p>
<p>\( AB^{2} = AC^{2} + \frac{BC^{2}}{2} \)</p>
<p>\( 2AB^{2} = 2AC^{2} + BC^{2} \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 15:<br/>
In an equilateral ∆ ABC, D is a point on side BC such that BD =
\( \frac{1}{3}\times BC \) ,proove \(9 AD^{2} = 7AB^{2} \).</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-15.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is the best question of this exercise,I remember a person used to teach tutions when I was doing my 12,and
then he was stuck in this question,and he was asking everybody in the neighbourhood to solve the question,
so slowly slowly the question came to me and finally I gave a solution to the question </p>
<p>Now this question is extension to the previous question ,but the problem is why so many stidents and teachers
fail to solve this question is we are not given perpendicular drawn,that we have to draw ourself and then
start the proceedings from there </p>
<p>Draw a perpendicular AE to BC </p>
<p>Consider right angle ∆ ABE and ∆ ACE </p>
<p>AB = AC </p>
<p>AD = AD (Common) </p>
<p>By RHS congruence condition </p>
<p>ABE ≅ ACE</p>
<p>BE = EC (By C.P.C.T) </p>
<p>Now we need a relation between AD and AB </p>
<p>In triangle ADE </p>
<p>\( AD^{2} = AE^{2} + DE^{2} \) ....(1)</p>
<p>In triange ABE </p>
<p>\( AB^{2} = AE^{2} + BE^{2} ....(2) \)</p>
<p>We dont need AE so we can put AE value from 2 in 1 </p>
<p>\( AD^{2} = AB^{2} - BE^{2} + DE^{2} \)</p>
<p>Now we can write BE and DE in terms of BC and since triangle is equilateral,
we can reqrite BC as AB </p>
<p>Now DE = BE - BD = \( \frac{BC}{2} - \frac{BC}{3} = \frac{BC}{6} \) </p>
<p>\( AD^{2} = AB^{2} - BE^{2} + DE^{2} \)</p>
<p>\( AD^{2} = AB^{2} - (\frac{BC}{2})^{2} + (\frac{BC}{6})^{2} \)</p>
<p>\( AD^{2} = AB^{2} - {BC^{2}}{4} + {BC^{2}}{36} \)</p>
<p>\( AD^{2} = AB^{2} - {AB^{2}}{4} + {AB^{2}}{36} \)</p>
<p>\( 9AD^{2} = 7AB^{2} \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 16:<br/>
In an equilateral triangle,prove that three times the square of one side is equal to four
times the square of one of its altitudes.
</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>This is simple from previous question we know BE = EC for AE as altitide on side BC</p>
<p>so, \( AB^{2} = AD^{2} + (\frac{BC}{2})^{2} \)</p>
<p>\( AB^{2} = AD^{2} + \frac{BC^{2}}{4} \)</p>
<p>Since triangle is equilateral AB = BC </p>
<p>\( AB^{2} = AD^{2} + \frac{AB^{2}}{4} \)</p>
<p>\( 3AB^{2} = 4AD^{2} \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 17:<br/>
Tick the correct answer and justify : In Δ ABC, AB = \(6\times \sqrt{3} \) cm, AC = 12 cm and BC = 6 cm.
The angle B is :
(A) 120° (B) 60°
(C) 90° (D) 45°.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
<p>\( AB^{2} = (6\times \sqrt{3})^{2} = 108 ,AC^{2} = 144,BC^{2} = 36,AB^{2} + BC^{2} = AC^{2} \)
<p>\( Since AB^{2} + BC^{2} = AC^{2}, angle B = 90 \)</p>
</div>
<p> </p>
<p> </p>
<p><strong>Question 1:<br/>
1. In Fig. 6.56, PS is the bisector of ∠ QPR of Δ PQR. Prove that
Fig. 6.56
QS PQ
SR
PR</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 2:<br/>
2. In Fig. 6.57, D is a point on hypotenuse AC of Δ ABC, such that BD ⊥ AC, DM ⊥ BC and
DN ⊥ AB. Prove that :
(i) DM 2 = DN . MC
(ii) DN 2 = DM . AN</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 3:<br/>
3. In Fig. 6.58, ABC is a triangle in which ∠ ABC > 90° and AD ⊥ CB produced. Prove that
AC 2 = AB 2 + BC 2 + 2 BC . BD.
Fig. 6.58
Fig. 6.59</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 4:<br/>
In Fig. 6.59, ABC is a triangle in which ∠ ABC < 90° and AD ⊥ BC. Prove that
AC 2 = AB 2 + BC 2 – 2 BC . BD.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 5:<br/>
In Fig. 6.60, AD is a median of a triangle ABC and
AM ⊥ BC. Prove that :
BC
(i) AC 2 = AD 2 + BC . DM +
2 BC
(ii) AB 2 = AD 2 – BC . DM +
2
2
(iii) AC 2 + AB 2 = 2 AD 2 +
1
BC 22</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 6:<br/>
Prove that the sum of the squares of the diagonals of parallelogram is equal to the sum
of the squares of its sides.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 7:<br/>
In Fig. 6.61, two chords AB and CD intersect each other at the point P. Prove that :
(i) Δ APC ~ Δ DPB
(ii) AP . PB = CP . DP
Fig. 6.61
Fig. 6.62</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 8:<br/>
In Fig. 6.62, two chords AB and CD of a circle intersect each other at the point P
(when produced) outside the circle. Prove that
(i) Δ PAC ~ Δ PDB
(ii) PA . PB = PC . PD</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p><strong>Question 9:<br/>
In Fig. 6.62, two chords AB and CD of a circle intersect each other at the point P
(when produced) outside the circle. Prove that
(i) Δ PAC ~ Δ PDB
(ii) PA . PB = PC . PD</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 10:<br/>
In Fig. 6.63, D is a point on side BC of Δ ABC
BD AB
Prove that AD is the
CD AC
bisector of ∠ BAC.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 10:<br/>
In Fig. 6.63, D is a point on side BC of Δ ABC
BD AB
Prove that AD is the
CD AC
bisector of ∠ BAC.</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
<p><strong>Question 10:<br/>
Nazima is fly fishing in a stream. The tip of
her fishing rod is 1.8 m above the surface
of the water and the fly at the end of the
string rests on the water 3.6 m away and
2.4 m from a point directly under the tip of
the rod. Assuming that her string
(from the tip of her rod to the fly) is taut,
how much string does she have out
(see Fig. 6.64)? If she pulls in the string at
the rate of 5 cm per second, what will be
the horizontal distance of the fly from her
after 12 seconds?
Fig. 6.63
Fig..</strong></p>
<p><img class="alignnone wp-image-2112" src="/images/10/0/triangles/10-0-6-5-16.png" alt="8" width="300" height="300" /></p>
<h3 class="azc_tsh_toggle" style="border: 1px solid #cccccc; background-color: #f2f2f2; background-image: none !important; padding-left: 10px; "><a href="#" style="font-size: 14px; 14px">Show Answer</a></h3>
<div class="azc_tsh_toggle_container" style="border: 1px solid rgb(204, 204, 204); font-size: 14px;margin-left:14px"><br>
</div>
<p> </p>
<p> </p>
@stop | mit |
nkbt/react-works | packages/swap/example/Clickable/Clickable.js | 356 | import React from 'react';
import {On} from '../On';
import {Off} from '../Off';
import {ReactSwap} from '../../src/Component';
export function Clickable() {
return (
<div data-e2e="clickable">
<h2>Clickable</h2>
<ReactSwap>
<Off data-swap-handler={1} />
<On data-swap-handler={1} />
</ReactSwap>
</div>
);
}
| mit |
dbohn/holger | src/Modules/DeviceInfo.php | 926 | <?php
namespace Holger\Modules;
use Holger\HasEndpoint;
class DeviceInfo
{
protected $endpoint = [
'controlUri' => '/upnp/control/deviceinfo',
'uri' => 'urn:dslforum-org:service:DeviceInfo:1',
'scpdurl' => '/deviceinfoSCPD.xml',
];
use HasEndpoint;
/**
* Fetch info like manufacturer, model name, serial number,
* firmware version....
*
* @return array
*/
public function info()
{
return $this->prepareRequest()->GetInfo();
}
/**
* Fetch the latest device log entries.
*
* @return string
*/
public function deviceLog()
{
return $this->prepareRequest()->GetDeviceLog();
}
/**
* Fetch the port number to use for a secure connection.
*
* @return int
*/
public function securityPort()
{
return intval($this->prepareRequest()->GetSecurityPort());
}
}
| mit |
twenzel/SonyCameraRemoteControl | Test/Form1.cs | 4291 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Rssdp;
using SonyCameraRemoteControl;
namespace Test
{
public partial class Form1 : Form
{
SonyCameraDevice _device;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
txtDeviceInfo.Text = "searching ...";
_device = RemoteControl.FindDevice(txtuuid.Text);
printDeviceInfos();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
txtDeviceInfo.Text = "searching ...";
_device = RemoteControl.SearchDevice(10000);
printDeviceInfos();
}
private void printDeviceInfos()
{
if (_device != null)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Friendly name: " + _device.FriendlyName);
sb.AppendLine("ModelDescription: " + _device.ModelDescription);
sb.AppendLine("ModelName: " + _device.ModelName);
sb.AppendLine("ModelNumber: " + _device.ModelNumber);
sb.AppendLine("Uuid: " + _device.Uuid);
sb.AppendLine("\r\nEndpoints: ");
foreach (var pair in _device.Endpoints)
sb.AppendLine(String.Format("{0}: {1}", pair.Key, pair.Value));
txtDeviceInfo.Text = sb.ToString();
} else
txtDeviceInfo.Text = "No device found";
}
SsdpDeviceLocator _BroadcastListener;
private void button3_Click(object sender, EventArgs e)
{
if (_BroadcastListener != null)
{
_BroadcastListener.DeviceAvailable -= _BroadcastListener_DeviceAvailable;
_BroadcastListener.StopListeningForNotifications();
_BroadcastListener.Dispose();
_BroadcastListener = null;
txtDeviceInfo.Text += "\r\nstopped";
}
else
{
txtDeviceInfo.Text = "listen...";
_BroadcastListener = new SsdpDeviceLocator();
_BroadcastListener.DeviceAvailable += _BroadcastListener_DeviceAvailable;
_BroadcastListener.StartListeningForNotifications();
}
}
void _BroadcastListener_DeviceAvailable(object sender, DeviceAvailableEventArgs e)
{
if (e.IsNewlyDiscovered)
{
this.Invoke((MethodInvoker) delegate { txtDeviceInfo.Text += e.DiscoveredDevice.DescriptionLocation + "\r\n";});
var t = SonyCameraDevice.GetSonyDevice(e.DiscoveredDevice);
var r = t.Result;
}
}
private async void button2_Click_1(object sender, EventArgs e)
{
var result = await _device.StartRecMode();
showError(result);
}
private void showError(ResultBase result)
{
if (result.HasError)
MessageBox.Show(result.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private async void button4_Click(object sender, EventArgs e)
{
var result = await _device.StartLiveView();
showError(result);
if (!result.HasError)
axWindowsMediaPlayer1.URL = result.Value;
}
private async void button5_Click(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = "";
var result = await _device.SetShootMode("still");
showError(result);
}
private async void button6_Click(object sender, EventArgs e)
{
var result = await _device.TakePicture();
showError(result);
if (!result.HasError && result.Value.Length > 0)
pictureBox1.LoadAsync(result.Value[0]);
}
}
}
| mit |
codehangar/agenda-codehangar | src/services/agenda.service.js | 1099 | (function() {
"use strict";
angular
.module('utils.codehangar')
.factory('AgendaSvc', function($http, Session) {
var _this = this
this.createAgenda = function(agenda){
console.log('agendaService', agenda)
return $http
.post('http://localhost:9999/api/v1/agenda', {
headers: {
'x-access-token': Session.userToken
},
'agenda': agenda}
)
.then(function(res) {
console.log('createAgenda res', res)
// Session.create(res.data.token, res.data.user);
return res.data.agenda;
});
}
this.getAgendas = function(){
return $http
.get('http://localhost:9999/api/v1/agenda', {
headers: {
'x-access-token': Session.userToken
}
})
.then(function(res) {
console.log('getAgendas res', res)
// Session.create(res.data.token, res.data.user);
return res.data.agendas;
});
}
return this;
});
})();
| mit |
drakang4/creative-project-manager | src/utils/projectConfig.js | 562 | // @flow
import path from 'path';
import JsonFile from './JsonFile';
export default class ProjectConfig {
constructor(projectRoot) {
this.configFile = new JsonFile(path.join(projectRoot, 'project.json'));
}
async loadProjectConfig() {
try {
return await this.configFile.readAsync();
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error('project.json 파일을 찾을 수 없습니다.');
}
throw error;
}
}
async saveProjectConfig(data) {
await this.configFile.writeAsync(data);
}
}
| mit |
Orasik/monolog-middleware | src/MonologMiddleware/Loggable/LoggableProvider.php | 7361 | <?php
namespace MonologMiddleware\Loggable;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Psr7;
/**
* This class is copyright to Guzzle Library, I have modified it to extract loggables for monolog middleware
* as its a great idea for assign which data to log without changing the code.
* @see https://github.com/guzzle/guzzle
*
* Formats log messages using variable substitutions for requests, responses,
* and other transactional data.
*
* The following variable substitutions are supported:
*
* - {request}: Full HTTP request message
* - {response}: Full HTTP response message
* - {ts}: ISO 8601 date in GMT
* - {date_iso_8601} ISO 8601 date in GMT
* - {date_common_log} Apache common log date using the configured timezone.
* - {host}: Host of the request
* - {method}: Method of the request
* - {uri}: URI of the request
* - {host}: Host of the request
* - {version}: Protocol version
* - {target}: Request target of the request (path + query + fragment)
* - {hostname}: Hostname of the machine that sent the request
* - {code}: Status code of the response (if available)
* - {phrase}: Reason phrase of the response (if available)
* - {error}: Any error messages (if available)
* - {req_header_*}: Replace `*` with the lowercased name of a request header to add to the message
* - {res_header_*}: Replace `*` with the lowercased name of a response header to add to the message
* - {req_headers}: Request headers
* - {res_headers}: Response headers
* - {req_body}: Request body
* - {res_body}: Response body
*/
class LoggableProvider
{
/**
* Apache Common Log Format.
* @link http://httpd.apache.org/docs/2.4/logs.html#common
* @var string
*/
const CLF = "{request} / {response}";
/** @var string Template used to format log messages */
private $template;
/**
* @param string $template Log message template
*/
public function __construct($template = self::CLF)
{
$this->template = $template ?: self::CLF;
}
/**
* Returns a formatted message string.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface $response Response that was received
* @param \Exception $error Exception that was received
*
* @return string
*/
public function format(
RequestInterface $request,
ResponseInterface $response = null,
\Exception $error = null
): string
{
$cache = [];
return preg_replace_callback(
'/{\s*([A-Za-z_\-\.0-9]+)\s*}/',
function (array $matches) use ($request, $response, $error, &$cache) {
if (isset($cache[$matches[1]])) {
return $cache[$matches[1]];
}
$result = '';
switch ($matches[1]) {
case 'request':
$result = Psr7\str($request);
break;
case 'response':
$result = $response ? Psr7\str($response) : '';
break;
case 'req_headers':
$result = trim(
$request->getMethod()
.' '.$request->getRequestTarget()
)
.' HTTP/'.$request->getProtocolVersion()."\r\n"
.$this->headers($request);
break;
case 'res_headers':
$result = $response ?
sprintf(
'HTTP/%s %d %s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
)."\r\n".$this->headers($response)
: 'NULL';
break;
case 'req_body':
$result = $request->getBody();
break;
case 'res_body':
$result = $response ? $response->getBody() : 'NULL';
break;
case 'ts':
case 'date_iso_8601':
$result = gmdate('c');
break;
case 'date_common_log':
$result = date('d/M/Y:H:i:s O');
break;
case 'method':
$result = $request->getMethod();
break;
case 'version':
$result = $request->getProtocolVersion();
break;
case 'uri':
case 'url':
$result = $request->getUri();
break;
case 'target':
$result = $request->getRequestTarget();
break;
case 'req_version':
$result = $request->getProtocolVersion();
break;
case 'res_version':
$result = $response
? $response->getProtocolVersion()
: 'NULL';
break;
case 'host':
$result = $request->getHeaderLine('Host');
break;
case 'hostname':
$result = gethostname();
break;
case 'code':
$result = $response ? $response->getStatusCode() : 'NULL';
break;
case 'phrase':
$result = $response ? $response->getReasonPhrase() : 'NULL';
break;
case 'error':
$result = $error ? $error->getMessage() : 'NULL';
break;
default:
// handle prefixed dynamic headers
if (strpos($matches[1], 'req_header_') === 0) {
$result = $request->getHeaderLine(substr($matches[1], 11));
} elseif (strpos($matches[1], 'res_header_') === 0) {
$result = $response
? $response->getHeaderLine(substr($matches[1], 11))
: 'NULL';
}
}
$cache[$matches[1]] = $result;
return $result;
},
$this->template
);
}
/**
* @param MessageInterface $message
* @return string
*/
private function headers(MessageInterface $message): string
{
$result = '';
foreach ($message->getHeaders() as $name => $values) {
$result .= $name.': '.implode(', ', $values)."\r\n";
}
return trim($result);
}
}
| mit |
lingtalfi/bee | bee/modules/MacBee/Component/Rotator/Exception/RotatorException.php | 399 | <?php
/*
* This file is part of the Bee package.
*
* (c) Ling Talfi <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace MacBee\Component\Rotator\Exception;
/**
* RotatorException
* @author Lingtalfi
* 2015-07-03
*
*/
class RotatorException extends \Exception{
}
| mit |
MDE4CPP/MDE4CPP | src/uml/src_gen/uml/impl/BroadcastSignalActionImpl.hpp | 5909 | //********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************
#ifndef UML_BROADCASTSIGNALACTIONBROADCASTSIGNALACTIONIMPL_HPP
#define UML_BROADCASTSIGNALACTIONBROADCASTSIGNALACTIONIMPL_HPP
//*********************************
// generated Includes
//Model includes
#include "../BroadcastSignalAction.hpp"
#include "uml/impl/InvocationActionImpl.hpp"
//*********************************
namespace uml
{
class BroadcastSignalActionImpl : virtual public InvocationActionImpl, virtual public BroadcastSignalAction
{
public:
BroadcastSignalActionImpl(const BroadcastSignalActionImpl & obj);
virtual std::shared_ptr<ecore::EObject> copy() const;
private:
BroadcastSignalActionImpl& operator=(BroadcastSignalActionImpl const&) = delete;
protected:
friend class umlFactoryImpl;
BroadcastSignalActionImpl();
virtual std::shared_ptr<BroadcastSignalAction> getThisBroadcastSignalActionPtr() const;
virtual void setThisBroadcastSignalActionPtr(std::weak_ptr<BroadcastSignalAction> thisBroadcastSignalActionPtr);
//Additional constructors for the containments back reference
BroadcastSignalActionImpl(std::weak_ptr<uml::Activity > par_activity);
//Additional constructors for the containments back reference
BroadcastSignalActionImpl(std::weak_ptr<uml::StructuredActivityNode > par_inStructuredNode);
//Additional constructors for the containments back reference
BroadcastSignalActionImpl(std::weak_ptr<uml::Namespace > par_namespace);
//Additional constructors for the containments back reference
BroadcastSignalActionImpl(std::weak_ptr<uml::Element > par_owner);
public:
//destructor
virtual ~BroadcastSignalActionImpl();
//*********************************
// Operations
//*********************************
/*!
A BroadcaseSignalAction may not specify onPort.
onPort=null
*/
virtual bool no_onport(Any diagnostics,std::map < Any, Any > context) ;
/*!
The number of argument InputPins must be the same as the number of attributes in the signal.
argument->size() = signal.allAttributes()->size()
*/
virtual bool number_of_arguments(Any diagnostics,std::map < Any, Any > context) ;
/*!
The type, ordering, and multiplicity of an argument InputPin must be the same as the corresponding attribute of the signal.
let attribute: OrderedSet(Property) = signal.allAttributes() in
Sequence{1..argument->size()}->forAll(i |
argument->at(i).type.conformsTo(attribute->at(i).type) and
argument->at(i).isOrdered = attribute->at(i).isOrdered and
argument->at(i).compatibleWith(attribute->at(i)))
*/
virtual bool type_ordering_multiplicity(Any diagnostics,std::map < Any, Any > context) ;
//*********************************
// Attributes Getter Setter
//*********************************
//*********************************
// Reference
//*********************************
/*!
The Signal whose instances are to be sent.
<p>From package UML::Actions.</p>
*/
virtual std::shared_ptr<uml::Signal > getSignal() const ;
/*!
The Signal whose instances are to be sent.
<p>From package UML::Actions.</p>
*/
virtual void setSignal(std::shared_ptr<uml::Signal> _signal) ;
//*********************************
// Union Getter
//*********************************
/*!
ActivityGroups containing the ActivityNode.
<p>From package UML::Activities.</p>
*/
virtual std::shared_ptr<Union<uml::ActivityGroup>> getInGroup() const ;/*!
The ordered set of InputPins representing the inputs to the Action.
<p>From package UML::Actions.</p>
*/
virtual std::shared_ptr<SubsetUnion<uml::InputPin, uml::Element>> getInput() const ;/*!
The Elements owned by this Element.
<p>From package UML::CommonStructure.</p>
*/
virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const ;/*!
The Element that owns this Element.
<p>From package UML::CommonStructure.</p>
*/
virtual std::weak_ptr<uml::Element > getOwner() const ;/*!
The RedefinableElement that is being redefined by this element.
<p>From package UML::Classification.</p>
*/
virtual std::shared_ptr<Union<uml::RedefinableElement>> getRedefinedElement() const ;
//*********************************
// Structural Feature Getter/Setter
//*********************************
virtual std::shared_ptr<ecore::EObject> eContainer() const ;
//*********************************
// Persistence Functions
//*********************************
virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) ;
virtual void loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list);
virtual void loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler);
virtual void resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) ;
virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const ;
virtual void saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const;
protected:
virtual std::shared_ptr<ecore::EClass> eStaticClass() const;
virtual Any eGet(int featureID, bool resolve, bool coreType) const ;
virtual bool internalEIsSet(int featureID) const ;
virtual bool eSet(int featureID, Any newValue) ;
private:
std::weak_ptr<BroadcastSignalAction> m_thisBroadcastSignalActionPtr;
};
}
#endif /* end of include guard: UML_BROADCASTSIGNALACTIONBROADCASTSIGNALACTIONIMPL_HPP */
| mit |
AntonPetrov/jmolTools | docs/jsmol/j2s/JM/Model.js | 8996 | Clazz.declarePackage ("JM");
Clazz.load (["JU.BS", "$.SB"], "JM.Model", ["java.util.Hashtable", "JU.AU", "JU.BSUtil"], function () {
c$ = Clazz.decorateAsClass (function () {
this.ms = null;
this.modelIndex = 0;
this.fileIndex = 0;
this.hydrogenCount = 0;
this.isBioModel = false;
this.isPdbWithMultipleBonds = false;
this.hasRasmolHBonds = false;
this.loadState = "";
this.loadScript = null;
this.isModelKit = false;
this.dataFrames = null;
this.dataSourceFrame = -1;
this.jmolData = null;
this.jmolFrameType = null;
this.firstAtomIndex = 0;
this.ac = 0;
this.bsAtoms = null;
this.bsAtomsDeleted = null;
this.trajectoryBaseIndex = 0;
this.isTrajectory = false;
this.selectedTrajectory = -1;
this.bondCount = -1;
this.firstMoleculeIndex = 0;
this.moleculeCount = 0;
this.nAltLocs = 0;
this.nInsertions = 0;
this.groupCount = -1;
this.chainCount = 0;
this.chains = null;
this.biosymmetryCount = 0;
this.auxiliaryInfo = null;
this.properties = null;
this.defaultRotationRadius = 0;
this.defaultStructure = null;
this.biosymmetry = null;
this.orientation = null;
this.structureTainted = false;
this.isJmolDataFrame = false;
this.frameDelay = 0;
this.simpleCage = null;
this.dssrCache = null;
Clazz.instantialize (this, arguments);
}, JM, "Model");
Clazz.prepareFields (c$, function () {
this.loadScript = new JU.SB ();
this.bsAtoms = new JU.BS ();
this.bsAtomsDeleted = new JU.BS ();
this.chains = new Array (8);
});
Clazz.defineMethod (c$, "getModelSet",
function () {
return this.ms;
});
Clazz.defineMethod (c$, "isModelkit",
function () {
return this.isModelKit;
});
Clazz.defineMethod (c$, "getTrueAtomCount",
function () {
return this.bsAtoms.cardinality () - this.bsAtomsDeleted.cardinality ();
});
Clazz.defineMethod (c$, "resetBoundCount",
function () {
this.bondCount = -1;
});
Clazz.defineMethod (c$, "getBondCount",
function () {
if (this.bondCount >= 0) return this.bondCount;
var bonds = this.ms.bo;
this.bondCount = 0;
for (var i = this.ms.bondCount; --i >= 0; ) if (bonds[i].atom1.mi == this.modelIndex) this.bondCount++;
return this.bondCount;
});
Clazz.makeConstructor (c$,
function () {
});
Clazz.defineMethod (c$, "set",
function (modelSet, modelIndex, trajectoryBaseIndex, jmolData, properties, auxiliaryInfo) {
this.ms = modelSet;
this.dataSourceFrame = this.modelIndex = modelIndex;
this.isTrajectory = (trajectoryBaseIndex >= 0);
this.trajectoryBaseIndex = (this.isTrajectory ? trajectoryBaseIndex : modelIndex);
if (auxiliaryInfo == null) {
auxiliaryInfo = new java.util.Hashtable ();
}this.auxiliaryInfo = auxiliaryInfo;
if (auxiliaryInfo.containsKey ("biosymmetryCount")) {
this.biosymmetryCount = (auxiliaryInfo.get ("biosymmetryCount")).intValue ();
this.biosymmetry = auxiliaryInfo.get ("biosymmetry");
}this.properties = properties;
if (jmolData == null) {
this.jmolFrameType = "modelSet";
} else {
this.jmolData = jmolData;
this.isJmolDataFrame = true;
auxiliaryInfo.put ("jmolData", jmolData);
auxiliaryInfo.put ("title", jmolData);
this.jmolFrameType = (jmolData.indexOf ("ramachandran") >= 0 ? "ramachandran" : jmolData.indexOf ("quaternion") >= 0 ? "quaternion" : "data");
}return this;
}, "JM.ModelSet,~N,~N,~S,java.util.Properties,java.util.Map");
Clazz.defineMethod (c$, "getChainCount",
function (countWater) {
if (this.chainCount > 1 && !countWater) for (var i = 0; i < this.chainCount; i++) if (this.chains[i].chainID == 0) return this.chainCount - 1;
return this.chainCount;
}, "~B");
Clazz.defineMethod (c$, "getGroupCountHetero",
function (isHetero) {
var n = 0;
for (var i = this.chainCount; --i >= 0; ) for (var j = this.chains[i].groupCount; --j >= 0; ) if (this.chains[i].groups[j].isHetero () == isHetero) n++;
return n;
}, "~B");
Clazz.defineMethod (c$, "calcSelectedGroupsCount",
function (bsSelected) {
for (var i = this.chainCount; --i >= 0; ) this.chains[i].calcSelectedGroupsCount (bsSelected);
}, "JU.BS");
Clazz.defineMethod (c$, "getGroupCount",
function () {
if (this.groupCount < 0) {
this.groupCount = 0;
for (var i = this.chainCount; --i >= 0; ) this.groupCount += this.chains[i].groupCount;
}return this.groupCount;
});
Clazz.defineMethod (c$, "getChainAt",
function (i) {
return (i < this.chainCount ? this.chains[i] : null);
}, "~N");
Clazz.defineMethod (c$, "getChain",
function (chainID) {
for (var i = this.chainCount; --i >= 0; ) {
var chain = this.chains[i];
if (chain.chainID == chainID) return chain;
}
return null;
}, "~N");
Clazz.defineMethod (c$, "fixIndices",
function (modelIndex, nAtomsDeleted, bsDeleted) {
this.fixIndicesM (modelIndex, nAtomsDeleted, bsDeleted);
}, "~N,~N,JU.BS");
Clazz.defineMethod (c$, "fixIndicesM",
function (modelIndex, nAtomsDeleted, bsDeleted) {
if (this.dataSourceFrame > modelIndex) this.dataSourceFrame--;
if (this.trajectoryBaseIndex > modelIndex) this.trajectoryBaseIndex--;
this.firstAtomIndex -= nAtomsDeleted;
for (var i = 0; i < this.chainCount; i++) this.chains[i].fixIndices (nAtomsDeleted, bsDeleted);
JU.BSUtil.deleteBits (this.bsAtoms, bsDeleted);
JU.BSUtil.deleteBits (this.bsAtomsDeleted, bsDeleted);
}, "~N,~N,JU.BS");
Clazz.defineMethod (c$, "freeze",
function () {
this.freezeM ();
});
Clazz.defineMethod (c$, "freezeM",
function () {
this.chains = JU.AU.arrayCopyObject (this.chains, this.chainCount);
this.groupCount = -1;
this.getGroupCount ();
for (var i = 0; i < this.chainCount; ++i) this.chains[i].groups = JU.AU.arrayCopyObject (this.chains[i].groups, this.chains[i].groupCount);
});
Clazz.defineMethod (c$, "getPdbData",
function (vwr, type, ctype, isDraw, bsSelected, out, tokens, pdbCONECT, bsWritten) {
}, "JV.Viewer,~S,~S,~B,JU.BS,JU.OC,~A,JU.SB,JU.BS");
Clazz.defineMethod (c$, "getBioBranches",
function (bioBranches) {
return bioBranches;
}, "JU.Lst");
Clazz.defineMethod (c$, "clearBioPolymers",
function () {
});
Clazz.defineMethod (c$, "getAllPolymerInfo",
function (bs, finalInfo, modelVector) {
}, "JU.BS,java.util.Map,JU.Lst");
Clazz.defineMethod (c$, "getBioPolymerCount",
function () {
return 0;
});
Clazz.defineMethod (c$, "calculateStructures",
function (asDSSP, doReport, dsspIgnoreHydrogen, setStructure, includeAlpha) {
return "";
}, "~B,~B,~B,~B,~B");
Clazz.defineMethod (c$, "setStructureList",
function (structureList) {
}, "java.util.Map");
Clazz.defineMethod (c$, "getChimeInfo",
function (sb, nHetero) {
this.getChimeInfoM (sb, nHetero);
}, "JU.SB,~N");
Clazz.defineMethod (c$, "getChimeInfoM",
function (sb, nHetero) {
sb.append ("\nNumber of Atoms ..... " + (this.ms.ac - nHetero));
if (nHetero > 0) sb.append (" (" + nHetero + ")");
sb.append ("\nNumber of Bonds ..... " + this.ms.bondCount);
sb.append ("\nNumber of Models ...... " + this.ms.mc);
}, "JU.SB,~N");
Clazz.defineMethod (c$, "setConformation",
function (bsConformation) {
}, "JU.BS");
Clazz.defineMethod (c$, "getPdbConformation",
function (bsConformation, conformationIndex) {
return false;
}, "JU.BS,~N");
Clazz.defineMethod (c$, "getFullPDBHeader",
function () {
return null;
});
Clazz.defineMethod (c$, "getSequenceBits",
function (ms, specInfo, bs) {
return null;
}, "JM.ModelSet,~S,JU.BS");
Clazz.defineMethod (c$, "getBasePairBits",
function (ms, specInfo) {
return null;
}, "JM.ModelSet,~S");
Clazz.defineMethod (c$, "resetRasmolBonds",
function (model, bs) {
}, "JM.Model,JU.BS");
Clazz.defineMethod (c$, "calcRasmolHydrogenBonds",
function (ms, bsA, bsB, vHBonds, nucleicOnly, nMax, dsspIgnoreHydrogens, bsHBonds) {
}, "JM.ModelSet,JU.BS,JU.BS,JU.Lst,~B,~N,~B,JU.BS");
Clazz.defineMethod (c$, "getFullProteinStructureState",
function (modelSet, bsAtoms2, taintedOnly, needPhiPsi, mode) {
return null;
}, "JM.ModelSet,JU.BS,~B,~B,~N");
Clazz.defineMethod (c$, "calculateAllPolymers",
function (ms, groups, groupCount2, baseGroupIndex, modelsExcluded) {
}, "JM.ModelSet,~A,~N,~N,JU.BS");
Clazz.defineMethod (c$, "getGroupsWithinAll",
function (ms, nResidues, bs) {
return null;
}, "JM.ModelSet,~N,JU.BS");
Clazz.defineMethod (c$, "getSelectCodeRange",
function (ms, specInfo) {
return null;
}, "JM.ModelSet,~A");
Clazz.defineMethod (c$, "calculateStruts",
function (ms, bs1, bs2) {
return 0;
}, "JM.ModelSet,JU.BS,JU.BS");
Clazz.defineMethod (c$, "getPolymerPointsAndVectors",
function (bs, vList, isTraceAlpha, sheetSmoothing) {
}, "JU.BS,JU.Lst,~B,~N");
Clazz.defineMethod (c$, "recalculatePoints",
function (ms, modelIndex) {
}, "JM.ModelSet,~N");
Clazz.defineMethod (c$, "getDefaultLargePDBRendering",
function (sb, maxAtoms) {
}, "JU.SB,~N");
Clazz.defineMethod (c$, "calcSelectedMonomersCount",
function (bsSelected) {
}, "JU.BS");
Clazz.defineMethod (c$, "getBioPolymerCountInModel",
function (ms, modelIndex) {
return 0;
}, "JM.ModelSet,~N");
Clazz.defineMethod (c$, "calculateStraightnessAll",
function (ms) {
}, "JM.ModelSet");
});
| mit |
natac13/london-ontario-data | app/constants/directionMap.js | 275 | import { fromJS } from 'immutable'
export default fromJS({
1: {
direction: 'East',
arrow: 'right'
},
2: {
direction: 'North',
arrow: 'up'
},
3: {
direction: 'South',
arrow: 'down'
},
4: {
direction: 'West',
arrow: 'left'
}
})
| mit |
tlbdk/wsdl2ts | src/tsutils.js | 2948 | 'use strict';
var CodeGenUtils = require('./codegenutils');
class TypeScriptCodeGen extends CodeGenUtils {
generateClient() {
// TODO: Find all operations and make then unique across service/binding
// TODO: Foreach operation lookup message
}
}
function _definitionToInterface(rootName, definitions, indentation = 4) {
var types = [[rootName, definitions]];
var whitespace = " ".repeat(indentation);
var results = [];
while(types.length > 0) {
let type = types.shift();
let result = [];
let [name, definition] = type;
result.push("export interface " + name + " {")
Object.keys(definition).forEach(function (key) {
if(key.endsWith("$type")) {
let type;
if(Array.isArray(definition[key])) {
type = _xsdTypeLookup(definition[key][0]) + "[]";
} else {
type = _xsdTypeLookup(definition[key]);
}
if(type.startsWith("empty")) { // TODO: Support empty by defining an empty interface
type = "any";
}
result.push(whitespace + key.replace(/\$type$/, '') + (rootName === name ? "?" : "") + ": " + type + ";");
} else if(key.indexOf("$") === -1 && typeof definition[key] === 'object') {
types.push([key, definition[key]]);
result.push(whitespace + key + (rootName === name ? "?" : "") + ": " + key + ";");
}
});
result.push("}");
results.push(result.join("\n"));
};
return results;
}
function _xsdTypeLookup(type) {
// http://www.xml.dvint.com/docs/SchemaDataTypesQR-2.pdf
switch(type) {
case "boolean": return "boolean";
case "base64Binary": return "string";
case "hexBinary": return "string";
case "anyURI": return "string";
case "language": return "string";
case "normalizedString": return "string";
case "string": return "string";
case "token": return "string";
case "byte": return "number";
case "decimal": return "number";
case "double": return "number";
case "float": return "number";
case "int": return "number";
case "integer": return "number";
case "long": return "number";
case "negativeInteger": return "number";
case "nonNegativeInteger": return "number";
case "nonPositiveInteger": return "number";
case "short": return "number";
case "unsignedByte": return "number";
case "unsignedInt": return "number";
case "unsignedLong": return "number";
case "unsignedShort": return "number";
case "empty": return "empty";
case "any": return "any";
default: throw new Error("Unknown XSD type '" + type + "'");
}
}
module.exports.definitionToInterface = _definitionToInterface;
| mit |
kswoll/npeg | PEG/SyntaxTree/CharacterSet.cs | 1452 | using System.Collections.Generic;
using System.Linq;
namespace PEG.SyntaxTree
{
public class CharacterSet : Expression
{
public IEnumerable<CharacterTerminal> Characters { get; set; }
public CharacterTerminal[] CharacterTable { get; set; }
public CharacterSet(params CharacterTerminal[] characters) : this((IEnumerable<CharacterTerminal>)characters)
{
}
public CharacterSet(IEnumerable<CharacterTerminal> characters)
{
Characters = characters;
CharacterTerminal[] orderedCharacters = characters.OrderBy(o => o.Character).ToArray();
int maxCharacter = orderedCharacters.Last().Character;
CharacterTable = new CharacterTerminal[maxCharacter + 1];
foreach (CharacterTerminal c in orderedCharacters)
CharacterTable[c.Character] = c;
}
public override IEnumerable<OutputRecord> Execute(ParseEngine engine)
{
Terminal current = engine.Current;
if (current is CharacterTerminal && ((CharacterTerminal)current).Character < CharacterTable.Length && CharacterTable[((CharacterTerminal)current).Character] != null)
return current.Execute(engine);
else
return null;
}
public override void Accept<T>(IExpressionVisitor<T> visitor, T context)
{
visitor.Visit(this, context);
}
}
} | mit |
JeroenBosmans/nabu | nabu/neuralnetworks/trainers/ctctrainer.py | 2367 | '''@file ctctrainer.py
contains the CTCTrainer'''
import tensorflow as tf
import trainer
from nabu.neuralnetworks import ops
class CTCTrainer(trainer.Trainer):
'''A trainer that minimises the CTC loss, the output sequences'''
def compute_loss(self, targets, logits, logit_seq_length,
target_seq_length):
'''
Compute the loss
Creates the operation to compute the CTC loss for every input
frame (if you want to have a different loss function, overwrite this
method)
Args:
targets: a tupple of targets, the first one being a
[batch_size, max_target_length] tensor containing the real
targets, the second one being a [batch_size, max_audioseq_length]
tensor containing the audio samples or other extra information.
logits: a [batch_size, max_logit_length, dim] tensor containing the
logits
logit_seq_length: the length of all the logit sequences as a
[batch_size] vector
target_seq_length: the length of all the target sequences as a
tupple of two [batch_size] vectors, both for one of the elements
in the targets tupple
Returns:
a scalar value containing the loss
'''
with tf.name_scope('CTC_loss'):
#get the batch size
targets = tf.expand_dims(targets[0], 2)
batch_size = int(targets.get_shape()[0])
#convert the targets into a sparse tensor representation
indices = tf.concat([tf.concat(
[tf.expand_dims(tf.tile([s], [target_seq_length[s]]), 1),
tf.expand_dims(tf.range(target_seq_length[s]), 1)], 1)
for s in range(batch_size)], 0)
values = tf.reshape(
ops.seq2nonseq(targets, target_seq_length), [-1])
shape = [batch_size, int(targets.get_shape()[1])]
sparse_targets = tf.SparseTensor(tf.cast(indices, tf.int64), values,
shape)
loss = tf.reduce_mean(tf.nn.ctc_loss(sparse_targets, logits,
logit_seq_length,
time_major=False))
return loss
| mit |
gumacs92/dataprocessor | src/Rules/OptionalRule.php | 1048 | <?php
namespace Processor\Rules;
use Processor\DataProcessor;
use Processor\Rules\Abstraction\AbstractEmptyRule;
/**
* Created by PhpStorm.
* User: Gumacs
* Date: 2016-11-04
* Time: 03:35 PM
*/
class OptionalRule extends AbstractEmptyRule
{
/* @var DataProcessor $processor */
protected $processor;
public function __construct($processor)
{
parent::__construct();
$this->processor = $this->typeCheck($processor, DataProcessor::class);
}
public function rule()
{
if (!isset($this->data) || empty($this->data)) {
return true;
} else {
$this->processor->setName($this->name);
$result = $this->processor->process($this->data, $this->feedback, true);
if (!$result->isSuccess()) {
$this->addResultErrorNewLevel($result->getErrors());
} else {
$this->data = $result->getData();
}
return $result->isSuccess();
}
}
} | mit |
etdev/algorithms | 0_code_wars/is_a_number_prime.rb | 224 | # http://www.codewars.com/kata/5262119038c0985a5b00029f
# --- iteration 1 ---
# Test if number is prime
def isPrime(num)
return false if num < 2
(2..(Math.sqrt(num))).each do |x|
return false if num % x == 0
end
true
end
| mit |
greenfieldhq/greenfield_rails | lib/greenfield_rails.rb | 126 | require 'greenfield_rails/version'
require 'greenfield_rails/generators/app_generator'
require 'greenfield_rails/app_builder'
| mit |
Lcaracol/ideasbox.lan | ideasbox/serveradmin/utils.py | 451 | import subprocess
def call_service(service):
args = ['sudo', 'service', service['name'], service['action']]
process = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
to_return = {'status': True}
if process.returncode:
to_return = {'status': False}
if stderr:
to_return['error'] = stderr
return to_return
| mit |
eventEmitter/em-session-identity-cookie | test.js | 434 |
var Webservice = require( "../ee-webservice" )
, Identity = require( "./" );
var service = new Webservice( {
http: {
interface: Webservice.Webserver.IF_ANY
, port: 12001
}
} );
var i = new Identity();
service.use( { request: function( request, response, next ){
i.set( request, response, function( identiy, sid ){
console.log( sid );
} );
response.send();
} } );
service.listen(); | mit |
jjenki11/blaze-chem-rendering | qca_designer/lib/pnetlib-0.8.0/tests/System.Xml/TestXmlSignificantWhitespace.cs | 3673 | /*
* TestXmlSignificantWhitespace.cs - Tests for the
* "System.Xml.TestXmlSignificantWhitespace" class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* 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
*/
using CSUnit;
using System;
using System.Xml;
#if !ECMA_COMPAT
public class TestXmlSignificantWhitespace : TestCase
{
// Internal state.
private XmlDocument doc;
// Constructor.
public TestXmlSignificantWhitespace(String name)
: base(name)
{
// Nothing to do here.
}
// Set up for the tests.
protected override void Setup()
{
doc = new XmlDocument();
}
// Clean up after the tests.
protected override void Cleanup()
{
// Nothing to do here.
}
// Check the properties on a newly constructed whitespace node.
private void CheckProperties(String msg, XmlSignificantWhitespace white,
String value, bool failXml)
{
String temp;
AssertEquals(msg + " [1]",
"#significant-whitespace", white.LocalName);
AssertEquals(msg + " [2]",
"#significant-whitespace", white.Name);
AssertEquals(msg + " [3]", String.Empty, white.Prefix);
AssertEquals(msg + " [4]", String.Empty, white.NamespaceURI);
AssertEquals(msg + " [5]",
XmlNodeType.SignificantWhitespace, white.NodeType);
AssertEquals(msg + " [6]", value, white.Data);
AssertEquals(msg + " [7]", value, white.Value);
AssertEquals(msg + " [8]", value, white.InnerText);
AssertEquals(msg + " [9]", value.Length, white.Length);
AssertEquals(msg + " [10]", String.Empty, white.InnerXml);
if(failXml)
{
try
{
temp = white.OuterXml;
Fail(msg + " [11]");
}
catch(ArgumentException)
{
// Success
}
}
else
{
AssertEquals(msg + " [12]", value, white.OuterXml);
}
}
// Test the construction of whitespace nodes.
public void TestXmlSignificantWhitespaceConstruct()
{
// Valid significant whitespace strings.
CheckProperties("Construct (1)",
doc.CreateSignificantWhitespace(null),
String.Empty, false);
CheckProperties("Construct (2)",
doc.CreateSignificantWhitespace(String.Empty),
String.Empty, false);
CheckProperties("Construct (3)",
doc.CreateSignificantWhitespace(" \f\t\r\n\v"),
" \f\t\r\n\v", false);
// Invalid significant whitespace strings.
try
{
doc.CreateWhitespace("abc");
Fail("Construct (4)");
}
catch(ArgumentException)
{
// Success
}
}
// Test the setting of whitespace values.
public void TestXmlSignificantWhitespaceSetValue()
{
XmlSignificantWhitespace white;
white = doc.CreateSignificantWhitespace(null);
white.Value = String.Empty;
white.Value = " \f\t\r\n\v";
white.Value = null;
try
{
white.Value = "abc";
Fail("SetValue (1)");
}
catch(ArgumentException)
{
// Success
}
}
}; // class TestXmlSignificantWhitespace
#endif // !ECMA_COMPAT
| mit |
jkereako/fish-species-leaderboard | app/models/species.rb | 957 | # Species
#
# The data source for this model is a static YAML file located in
# `config/data/species.yml`
class Species
FILE_PATH = Rails.root.join('config', 'data', 'species.yml')
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name
validates :name, presence: true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
# Return the species list as 1 array
def self.all
(freshwater + saltwater).sort
end
# Find only the saltwater species
def self.saltwater
load_data['saltwater'].sort
end
# Find only the freshwater species
def self.freshwater
load_data['freshwater'].sort
end
private
def self.load_data
YAML.load_file FILE_PATH
end
# Raise an exception if this method is called from a public context
private_class_method :load_data
end
| mit |
Algogator/RSSreddit | docs/conf.py | 8401 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# RSSreddit documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import RSSreddit
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'RSSreddit'
copyright = u"2017, Algogator"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = RSSreddit.__version__
# The full version, including alpha/beta/rc tags.
release = RSSreddit.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'RSSredditdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'RSSreddit.tex',
u'RSSreddit Documentation',
u'Algogator', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'RSSreddit',
u'RSSreddit Documentation',
[u'Algogator'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'RSSreddit',
u'RSSreddit Documentation',
u'Algogator',
'RSSreddit',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| mit |
anniyananeesh/avenirevents | application/views/administrator/banners_management/delete.php | 4067 | <div class="page">
<?php echo form_open(HOST_URL."/".$folder_name."/delete", 'name="frmListing" id="frmListing"'); ?>
<div id="module">
<div class="icon"><img src="<?=ADMIN_IMG_PATH?>/icon_<?php echo $folder_name; ?>.png" alt="<?=$module_name?>" /></div>
<div><a href="<?=HOST_URL?>/<?=$folder_name?>" class="module_nameBig"><?php echo $module_name; ?> : Delete Record</a></div>
<div class="buttons">
<ul class="actions">
<li><input type="submit" name="btnsubmit" id="btnsubmit" value="Delete" class="btn_delete" ></li>
<a href="<?=HOST_URL?>/<?=$folder_name?>"><li>
<div class="icon_back"> </div>
<div class="action_text">Back</div>
</li></a>
</ul>
</div>
</div>
<div> </div>
<? if (isset($MSG)){ ?>
<div class="<? if (isset($Error) && $Error=="Y"){ echo "alert"; }else{ echo "success"; } ?>"><?php echo $MSG; ?></div>
<? } ?>
<div class="contents">
<div id="list">
<div class="list_header">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="30" align="center" valign="middle"><input name="AC" type="checkbox" onclick="CheckAll();" checked="checked" /></td>
<td width="10" align="center" valign="middle"> </td>
<td align="left" valign="middle"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="left" valign="middle">Banner Title</td>
</tr>
</table></td>
<td width="60" align="center" valign="middle">Image</td>
<td width="110" align="center" valign="middle">Date</td>
<? if (isset($is_featured)){ ?>
<td width="90" align="center" valign="middle">Featured</td>
<? } ?>
<td width="70" align="center" valign="middle">Status</td>
<td width="50" align="center" valign="middle">ID</td>
</tr>
</table>
</div>
<div class="list">
<?php
foreach($data_list as $key=>$value){
if (!isset($is_featured)){ $is_featured= "";}
$image1_name = $value->image1;
$is_active = $value->is_active;
$is_featured = $value->is_featured;
$featured_img = (($is_featured=="Y")? '<img src="'.ADMIN_IMG_PATH.'/featured.png" alt="Featured">' : '');
$status_img = (($is_active=="Y")? '<img src="'.ADMIN_IMG_PATH.'/publish.png" alt="Publish">' :
'<img src="'.ADMIN_IMG_PATH.'/unpublish.png" alt="Unpublish">');
$image_path = (!empty($image1_name) ? $this->thumb_show_path.'/'.$image1_name : ADMIN_IMG_PATH."/no_admin_image.png");
$bgClass = (($bgClass=="bgcolor1") ? "bgcolor2" : "bgcolor1");
?>
<div class="listitem selected <?=$bgClass?>">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="30" height="34" align="center" valign="middle"><input name="EditBox[]" type="checkbox" onclick="UnCheckAll();" value="<?php echo $value->id; ?>" checked="checked" /></td>
<td width="10" align="left" valign="middle"> </td>
<td align="left" valign="middle"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="left" valign="middle"><? echo $value->title_en; ?></td>
</tr>
</table></td>
<td width="60" align="center" valign="middle"><img src="<?=$image_path?>" width="35" class="thumb" border="0" /></td>
<td width="110" align="center" valign="middle"><?php echo dateFormat($value->added_date); ?></td>
<? if (isset($is_featured)){ ?>
<td width="90" align="center" valign="middle"><?php echo $featured_img; ?></td>
<? } ?>
<td width="70" align="center" valign="middle"><?php echo $status_img; ?></td>
<td width="50" align="center" valign="middle"><?php echo $value->id; ?></td>
</tr>
</table>
</div>
<? } ?>
</div>
<div class="list_footer"> </div>
<div class="spacer"> </div>
<div class=""><?=$links?></div>
</div>
</div>
<? echo form_hidden('is_order', ''); ?>
<? echo form_close(); ?>
</div>
<script src="<?=JS_PATH?>/admin_validation.js"></script> | mit |
leiyangyou/Arpeggio | setup.py | 1923 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Name: arpeggio.py
# Purpose: PEG parser interpreter
# Author: Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com>
# Copyright: (c) 2009-2016 Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com>
# License: MIT License
#
# Arpeggio is an implementation of packrat parser interpreter based on PEG
# grammars.
# Parsers are defined using python language construction or PEG language.
###############################################################################
__author__ = "Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com>"
__version__ = "1.4"
from setuptools import setup
NAME = 'Arpeggio'
VERSION = __version__
DESC = 'Packrat parser interpreter'
AUTHOR = 'Igor R. Dejanovic'
AUTHOR_EMAIL = 'igor DOT dejanovic AT gmail DOT com'
LICENSE = 'MIT'
URL = 'https://github.com/igordejanovic/Arpeggio'
DOWNLOAD_URL = 'https://github.com/igordejanovic/Arpeggio/archive/v{}.tar.gz'\
.format(VERSION)
setup(
name = NAME,
version = VERSION,
description = DESC,
author = AUTHOR,
author_email = AUTHOR_EMAIL,
maintainer = AUTHOR,
maintainer_email = AUTHOR_EMAIL,
license = LICENSE,
url = URL,
download_url = DOWNLOAD_URL,
packages = ["arpeggio"],
keywords = "parser packrat peg",
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'Topic :: Software Development :: Interpreters',
'Topic :: Software Development :: Compilers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python'
]
)
| mit |
bmaland/hostconnect | lib/hostconnect/builders/option_info_builder.rb | 1742 | module HostConnect
class OptionInfoBuilder < AbstractBuilder
def initialize(options = {})
@valid_options = [ :agent_id, :password, :opt, :option_number, :info,
:date_from, :date_to, :scu_qty, :a_cache, :rate_convert, :room_configs,
:minimum_availability, :sort_field, :ascending, :index_first_option,
:maximum_options, :note_category, :location_code, :locality_description,
:class_description, :description, :supplier_name, :rate_per_scu ].freeze
super(options)
end
def to_xml
x = bare
x.Request {
x.OptionInfoRequest {
# TODO: probably need to validate sanity of Info / RateConvert here,
# and raise exceptions if they are invalid
# Has to substract from @valid_options instead of @options, because
# we have to guarantee the order of elements.
(@valid_options - [ :room_configs, :opt, :option_number ]).each do |opt|
# Requestify turns Id into ID
# TODO: I guess this could be done with less eval usage.
# Basically, we build xml only for those options that are non-blank
val = eval "#{opt}"
eval "x.#{opt.camelize.requestify} #{opt}" unless val.blank?
end
if @opt
@opt.each { |o| x.Opt o }
end
if @option_number
@option_number.each { |o| x.OptionNumber o }
end
if @room_configs
# Stack the room configs onto the request
x.RoomConfigs { |i|
@room_configs.each { |room| i << room.to_xml.target! }
}
end
}
}
x
end
end
end
| mit |
SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Data/EmployerAccountsDbContext.cs | 4468 | using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Threading.Tasks;
using SFA.DAS.EAS.Domain.Models.Account;
using SFA.DAS.EAS.Domain.Models.AccountTeam;
using SFA.DAS.EAS.Domain.Models.PAYE;
using SFA.DAS.EAS.Domain.Models.TransferConnections;
using SFA.DAS.EAS.Domain.Models.UserProfile;
namespace SFA.DAS.EAS.Infrastructure.Data
{
[DbConfigurationType(typeof(SqlAzureDbConfiguration))]
public class EmployerAccountsDbContext : DbContext
{
public virtual DbSet<AccountLegalEntity> AccountLegalEntities { get; set; }
public virtual DbSet<Account> Accounts { get; set; }
public virtual DbSet<AccountHistory> AccountHistory { get; set; }
public virtual DbSet<EmployerAgreement> Agreements { get; set; }
public virtual DbSet<AgreementTemplate> AgreementTemplates { get; set; }
public virtual DbSet<LegalEntity> LegalEntities { get; set; }
public virtual DbSet<Membership> Memberships { get; set; }
public virtual DbSet<TransferConnectionInvitation> TransferConnectionInvitations { get; set; }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<UserAccountSetting> UserAccountSettings { get; set; }
public virtual DbSet<Paye> Payees { get; set; }
static EmployerAccountsDbContext()
{
Database.SetInitializer<EmployerAccountsDbContext>(null);
}
public EmployerAccountsDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public EmployerAccountsDbContext(DbConnection connection, DbTransaction transaction = null)
: base(connection, false)
{
if (transaction != null) Database.UseTransaction(transaction);
else Database.BeginTransaction();
}
protected EmployerAccountsDbContext()
{
}
public virtual Task<List<T>> SqlQueryAsync<T>(string query, params object[] parameters)
{
return Database.SqlQuery<T>(query, parameters).ToListAsync();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.HasDefaultSchema("employer_account");
modelBuilder.Entity<Account>().Ignore(a => a.Role).Ignore(a => a.RoleName);
modelBuilder.Entity<Account>().HasMany(a => a.AccountLegalEntities);
modelBuilder.Entity<Account>().HasMany(a => a.ReceivedTransferConnectionInvitations).WithRequired(i => i.ReceiverAccount);
modelBuilder.Entity<Account>().HasMany(a => a.SentTransferConnectionInvitations).WithRequired(i => i.SenderAccount);
modelBuilder.Entity<AccountLegalEntity>().HasMany(ale => ale.Agreements);
modelBuilder.Entity<AccountLegalEntity>().HasRequired(ale => ale.Account);
modelBuilder.Entity<AccountLegalEntity>().HasRequired(ale => ale.LegalEntity);
modelBuilder.Entity<AccountLegalEntity>().HasOptional(ale => ale.SignedAgreement).WithMany().HasForeignKey(ale => ale.SignedAgreementId);
modelBuilder.Entity<AccountLegalEntity>().HasOptional(ale => ale.PendingAgreement).WithMany().HasForeignKey(ale => ale.PendingAgreementId);
modelBuilder.Entity<AgreementTemplate>().ToTable("EmployerAgreementTemplate").HasMany(t => t.Agreements);
modelBuilder.Entity<EmployerAgreement>().HasRequired(a => a.AccountLegalEntity);
modelBuilder.Entity<EmployerAgreement>().HasRequired(a => a.Template);
modelBuilder.Entity<Membership>().HasKey(m => new { m.AccountId, m.UserId });
modelBuilder.Entity<Paye>().Ignore(a => a.AccountId);
modelBuilder.Entity<TransferConnectionInvitation>().HasRequired(i => i.ReceiverAccount);
modelBuilder.Entity<TransferConnectionInvitation>().HasRequired(i => i.SenderAccount);
modelBuilder.Entity<User>().Ignore(u => u.FullName).Ignore(u => u.UserRef).Property(u => u.Ref).HasColumnName(nameof(User.UserRef));
modelBuilder.Entity<UserAccountSetting>().HasRequired(u => u.Account);
modelBuilder.Entity<UserAccountSetting>().HasRequired(u => u.User);
modelBuilder.Entity<UserAccountSetting>().ToTable("UserAccountSettings");
}
}
} | mit |
shaotao/Leetcode | algorithm/720_longest_word_in_dictionary/LongestWordInDictionary.java | 2973 | import java.io.*;
import java.util.*;
class LongestWordInDictionary
{
public static void main(String[] args)
{
System.out.println("=== Longest Word in Dictionary ===");
Solution solution = new Solution();
String[][] input = {{"w","wo","wor","worl", "world"},
{"a", "banana", "app", "appl", "ap", "apply", "apple"}};
for (String[] words : input) {
System.out.println("words = "+Arrays.toString(words));
System.out.println("longest word = "+solution.longestWord(words));
}
}
}
class Node {
String ch;
Map<String, Node> children;
boolean isWord;
public Node(String ch) {
this.ch = ch;
this.children = new HashMap<>();
this.isWord = false;
}
public boolean isWord() {
return isWord;
}
public String getCh() {
return ch;
}
public Node getChild(String label) {
Node child = children.get(label);
if (child == null) {
child = new Node(label);
this.children.put(label, child);
}
return child;
}
public void addWord(String word) {
if (word.length() == 0) {
this.isWord = true;
} else {
String label = word.substring(0, 1);
Node child = getChild(label);
child.addWord(word.substring(1));
}
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(ch+":"+isWord+") "+children.keySet());
return buf.toString();
}
public void trace() {
System.out.println(ch+":"+isWord+")"+children.keySet());
for (String key : children.keySet()) {
Node child = children.get(key);
child.trace();
}
}
public void longest(List<String> longestWords, String word, int depth) {
if (isWord) {
if (longestWords.isEmpty() || depth == longestWords.get(0).length()
) {
longestWords.add(word);
} else if (depth > longestWords.get(0).length()) {
longestWords.clear();
longestWords.add(word);
}
}
for (String key : children.keySet()) {
Node child = children.get(key);
if (child.isWord()) {
child.longest(longestWords, word+child.getCh(), depth+1);
}
}
}
}
class Solution
{
public String longestWord(String[] words) {
String ret = null;
//System.out.println("words = "+Arrays.toString(words));
Node root = new Node("");
for (String word : words) {
root.addWord(word);
}
List<String> longestWords = new ArrayList<>();
root.longest(longestWords, "", 0);
//System.out.println("longest words = "+longestWords);
Collections.sort(longestWords);
return longestWords.get(0);
}
}
| mit |
goyy/goyy | util/crypto/hmac/doc.go | 484 | // Copyright 2014 The goyy Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as
// defined in U.S. Federal Information Processing Standards Publication 198.
// An HMAC is a cryptographic hash that uses a key to sign a message.
// The receiver verifies the hash by recomputing it using the same key.
package hmac
| mit |
guisrx/railroad-services | src/main/java/com/selau/thoughtworks/railroad/services/RailroadService.java | 737 | package com.selau.thoughtworks.railroad.services;
import com.selau.thoughtworks.railroad.domain.Railroad;
import com.selau.thoughtworks.railroad.domain.Town;
/**
* Interface of a collection of railroad services available for invocation.
* @author selau
*
*/
public interface RailroadService {
int calculatePathDistance(Railroad railroad, Town... path);
int calculateShortestRouteDistance(Railroad railroad, Town from, Town to);
int countTotalPathsThroughEachStep(Railroad railroad, Town from, Town to, int maxStops);
int countTotalPathsInTheLastStep(Railroad railroad, Town from, Town to, int maxStops);
int countTotalPathsWithLessThanMaxDistance(Railroad railroad, Town from, Town to, int maxDistance);
} | mit |
Verurteilt/core | tests/translate.parser.spec.ts | 2202 | import {TranslateParser, DefaultTranslateParser} from '../src/translate.parser';
describe('Parser', () => {
let parser: TranslateParser;
beforeEach(() => {
parser = new DefaultTranslateParser();
});
it('is defined', () => {
expect(TranslateParser).toBeDefined();
expect(parser instanceof TranslateParser).toBeTruthy();
});
it('should interpolate', () => {
expect(parser.interpolate("This is a {{ key }}", {key: "value"})).toEqual("This is a value");
});
it('should interpolate with falsy values', () => {
expect(parser.interpolate("This is a {{ key }}", {key: ""})).toEqual("This is a ");
expect(parser.interpolate("This is a {{ key }}", {key: 0})).toEqual("This is a 0");
});
it('should interpolate with object properties', () => {
expect(parser.interpolate("This is a {{ key1.key2 }}", {key1: {key2: "value2"}})).toEqual("This is a value2");
expect(parser.interpolate("This is a {{ key1.key2.key3 }}", {key1: {key2: {key3: "value3"}}})).toEqual("This is a value3");
});
it('should get the addressed value', () => {
expect(parser.getValue({key1: {key2: "value2"}}, 'key1.key2')).toEqual("value2");
expect(parser.getValue({key1: {key2: "value"}}, 'keyWrong.key2')).not.toBeDefined();
expect(parser.getValue({key1: {key2: {key3: "value3"}}}, 'key1.key2.key3')).toEqual("value3");
expect(parser.getValue({key1: {key2: {key3: "value3"}}}, 'key1.keyWrong.key3')).not.toBeDefined();
expect(parser.getValue({key1: {key2: {key3: "value3"}}}, 'key1.key2.keyWrong')).not.toBeDefined();
expect(parser.getValue({'key1.key2': {key3: "value3"}}, 'key1.key2.key3')).toEqual("value3");
expect(parser.getValue({key1: {'key2.key3': "value3"}}, 'key1.key2.key3')).toEqual("value3");
expect(parser.getValue({'key1.key2.key3': "value3"}, 'key1.key2.key3')).toEqual("value3");
expect(parser.getValue({'key1.key2': {key3: "value3"}}, 'key1.key2.keyWrong')).not.toBeDefined();
expect(parser.getValue({
'key1': "value1",
'key1.key2': "value2"
}, 'key1.key2')).toEqual("value2");
});
});
| mit |
zambezi/fun | test/property_test.js | 1240 | import { strictEqual } from 'assert'
import { property } from '../src'
describe('property', () => {
it('should generate a named property accessor for the provided string key', () => {
const o = { a: 1, b: 2 }
strictEqual(property('a')(o), 1)
strictEqual(property('b')(o), 2)
})
it('should generate a property accessor that will return undefined for undefined properties', () => {
const o = { a: 1, b: 2 }
strictEqual(property('c')(o), undefined)
})
it('should generate a property accessor that will return undefined if call on an undefined object', () => {
strictEqual(property('c')(undefined), undefined)
})
it('should generate property accessors that support dot notation for subproperties', () => {
const o = { a: { aa: { aaa: 1 }, ab: 2 } }
strictEqual(property('a.aa.aaa')(o), 1)
strictEqual(property('a.ab')(o), 2)
})
it('should generate property accessors that return undefined if the accessor path is broken', () => {
const o = { a: 1 }
strictEqual(property('b.c.e')(o), undefined)
})
it('should return the full object if key is not provided', () => {
const o = { a: 1 }
strictEqual(property()(o), o)
strictEqual(property(null)(o), o)
})
})
| mit |
meteo-ubonn/meanie3D | python/meanie3D/resources/tracks_visit.py | 2101 | #!/usr/bin/python
'''
The MIT License (MIT)
(c) Juergen Simon 2014 ([email protected])
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.
'''
__author__ = "Juergen Simon"
__email__ = "[email protected]"
__version__ = "1.5.4"
# This is a template for a python script to be created with
# template variables replaced and then executed inside of
# Visit. The purpose is to visualise tracks from .vtk files
# produced by meanie3D-trackstats --write-center-tracks-as-vtk
# Parameters
_TRACKS_DIR = "P_TRACKS_DIR"
_M3D_HOME = "P_M3D_HOME"
_CONFIG_FILE = "P_CONFIGURATION_FILE"
_RESUME = "P_RESUME"
# Import modules
import os
import pdb
import sys
sys.path.append(_M3D_HOME)
import meanie3D.app.utils
import meanie3D.visualisation.tracks
# Parse configuration data
configuration = meanie3D.app.utils.load_configuration(_CONFIG_FILE)
# Add parsed parameters
configuration["meanie3d_home"] = _M3D_HOME
configuration["tracks_dir"] = _TRACKS_DIR
configuration['resume'] = meanie3D.app.utils.strToBool(_RESUME)
# run it
# pdb.set_trace()
meanie3D.visualisation.tracks.run(configuration)
quit() | mit |
sveljko/base41 | js/base41.js | 607 | function base41_decode(input) {
var rslt = []
var n = input.length
for (var i = 0; i < n; i += 3) {
var x = (input.charCodeAt(i) - 41) + 41 * (input.charCodeAt(i+1) - 41) + 1681*(input.charCodeAt(i+2) - 41);
rslt.push(x % 256, Math.floor(x / 256))
}
return rslt
}
function base41_encode(input) {
var rslt = ""
var n = input.length
for (var i = 0; i < n; i += 2) {
var x = input[i] + 256 * input[i+1];
rslt = rslt.concat(String.fromCharCode((x % 41) + 41))
x /= 41;
rslt = rslt.concat(String.fromCharCode((x % 41) + 41), String.fromCharCode((x / 41) + 41))
}
return rslt
}
| mit |
Uepsilon/consumo | app/models/order_item.rb | 959 | # == Schema Information
#
# Table name: order_items
#
# id :integer not null, primary key
# amount :integer
# order_id :integer not null
# delivery_id :integer not null
# created_at :datetime
# updated_at :datetime
#
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :delivery
delegate :user, to: :order
delegate :booking, to: :order
validates :amount, presence: true, numericality: true
before_validation :validate_order_item_amount
before_save :update_order_amount
scope :by_realm, -> (current_realm_id) { joins(order: :booking).where('bookings.realm_id = ?', current_realm_id) }
def total
amount * delivery.unit_price
end
private
def validate_order_item_amount
fail NotEnoughInventory if amount > delivery.remaining
end
def update_order_amount
booking.update_amount total
end
end
class OrderItem::NotEnoughInventory < StandardError; end
| mit |
Daivuk/onut | src/Shader.cpp | 44418 | // Onut
#include <onut/ContentManager.h>
#include <onut/Log.h>
#include <onut/Files.h>
#include <onut/Shader.h>
#include <onut/Strings.h>
// STL
#include <cassert>
#include <map>
#include <regex>
// --BEGIN--
#define STB_C_LEX_C_DECIMAL_INTS Y // "0|[1-9][0-9]*" CLEX_intlit
#define STB_C_LEX_C_HEX_INTS Y // "0x[0-9a-fA-F]+" CLEX_intlit
#define STB_C_LEX_C_OCTAL_INTS Y // "[0-7]+" CLEX_intlit
#define STB_C_LEX_C_DECIMAL_FLOATS Y // "[0-9]*(.[0-9]*([eE][-+]?[0-9]+)?) CLEX_floatlit
#define STB_C_LEX_C99_HEX_FLOATS N // "0x{hex}+(.{hex}*)?[pP][-+]?{hex}+ CLEX_floatlit
#define STB_C_LEX_C_IDENTIFIERS Y // "[_a-zA-Z][_a-zA-Z0-9]*" CLEX_id
#define STB_C_LEX_C_DQ_STRINGS N // double-quote-delimited strings with escapes CLEX_dqstring
#define STB_C_LEX_C_SQ_STRINGS N // single-quote-delimited strings with escapes CLEX_ssstring
#define STB_C_LEX_C_CHARS N // single-quote-delimited character with escape CLEX_charlits
#define STB_C_LEX_C_COMMENTS Y // "/* comment */"
#define STB_C_LEX_CPP_COMMENTS Y // "// comment to end of line\n"
#define STB_C_LEX_C_COMPARISONS Y // "==" CLEX_eq "!=" CLEX_noteq "<=" CLEX_lesseq ">=" CLEX_greatereq
#define STB_C_LEX_C_LOGICAL Y // "&&" CLEX_andand "||" CLEX_oror
#define STB_C_LEX_C_SHIFTS Y // "<<" CLEX_shl ">>" CLEX_shr
#define STB_C_LEX_C_INCREMENTS Y // "++" CLEX_plusplus "--" CLEX_minusminus
#define STB_C_LEX_C_ARROW N // "->" CLEX_arrow
#define STB_C_LEX_EQUAL_ARROW N // "=>" CLEX_eqarrow
#define STB_C_LEX_C_BITWISEEQ Y // "&=" CLEX_andeq "|=" CLEX_oreq "^=" CLEX_xoreq
#define STB_C_LEX_C_ARITHEQ Y // "+=" CLEX_pluseq "-=" CLEX_minuseq
// "*=" CLEX_muleq "/=" CLEX_diveq "%=" CLEX_modeq
// if both STB_C_LEX_SHIFTS & STB_C_LEX_ARITHEQ:
// "<<=" CLEX_shleq ">>=" CLEX_shreq
#define STB_C_LEX_PARSE_SUFFIXES N // letters after numbers are parsed as part of those numbers, and must be in suffix list below
#define STB_C_LEX_DECIMAL_SUFFIXES "" // decimal integer suffixes e.g. "uUlL" -- these are returned as-is in string storage
#define STB_C_LEX_HEX_SUFFIXES "" // e.g. "uUlL"
#define STB_C_LEX_OCTAL_SUFFIXES "" // e.g. "uUlL"
#define STB_C_LEX_FLOAT_SUFFIXES "" //
#define STB_C_LEX_0_IS_EOF N // if Y, ends parsing at '\0'; if N, returns '\0' as token
#define STB_C_LEX_INTEGERS_AS_DOUBLES Y // parses integers as doubles so they can be larger than 'int', but only if STB_C_LEX_STDLIB==N
#define STB_C_LEX_MULTILINE_DSTRINGS N // allow newlines in double-quoted strings
#define STB_C_LEX_MULTILINE_SSTRINGS N // allow newlines in single-quoted strings
#define STB_C_LEX_USE_STDLIB Y // use strtod,strtol for parsing #s; otherwise inaccurate hack
#define STB_C_LEX_DOLLAR_IDENTIFIER N // allow $ as an identifier character
#define STB_C_LEX_FLOAT_NO_DECIMAL Y // allow floats that have no decimal point if they have an exponent
#define STB_C_LEX_DEFINE_ALL_TOKEN_NAMES N // if Y, all CLEX_ token names are defined, even if never returned
// leaving it as N should help you catch config bugs
#define STB_C_LEX_DISCARD_PREPROCESSOR Y // discard C-preprocessor directives (e.g. after prepocess
// still have #line, #pragma, etc)
//#define STB_C_LEX_ISWHITE(str) ... // return length in bytes of whitespace characters if first char is whitespace
#define STB_C_LEXER_DEFINITIONS // This line prevents the header file from replacing your definitions
// --END--
// Third party
#define STB_C_LEXER_IMPLEMENTATION
#include <stb/stb_c_lexer.h>
namespace onut
{
static std::string readShaderFileContent(const std::string& filename)
{
FILE* pFic;
#if defined(WIN32)
fopen_s(&pFic, filename.c_str(), "rb");
#else
pFic = fopen(filename.c_str(), "rb");
#endif
if (!pFic) OLogE("Failed to load " + filename);
assert(pFic);
fseek(pFic, 0, SEEK_END);
auto filesize = static_cast<size_t>(ftell(pFic));
fseek(pFic, 0, SEEK_SET);
std::string content;
content.resize(filesize + 1);
fread(const_cast<char*>(content.data()), 1, filesize, pFic);
content[filesize] = '\0';
fclose(pFic);
return std::move(content);
}
OShaderRef Shader::createFromFile(const std::string& filename, const OContentManagerRef& pContentManager)
{
// Set the shader type
auto ext = onut::getExtension(filename);
if (ext == "VS" || ext == "ONUTVS")
{
return createFromSourceFile(filename, OVertexShader);
}
else if (ext == "PS" || ext == "ONUTPS")
{
return createFromSourceFile(filename, OPixelShader);
}
else
{
assert(false);
}
return nullptr;
}
OShaderRef Shader::createFromSourceFile(const std::string& filename, Type in_type, const VertexElements& vertexElements)
{
auto content = readShaderFileContent(filename);
return createFromSource(content, in_type, vertexElements);
}
Shader::VertexElement::VertexElement(VarType in_type, const std::string& in_semanticName)
: type(in_type)
, semanticName(in_semanticName)
{
}
Shader::Shader()
{
}
Shader::~Shader()
{
}
Shader::Type Shader::getType() const
{
return m_type;
}
uint32_t Shader::getVertexSize() const
{
return m_vertexSize;
}
Shader::ParsedTextures Shader::parseTextures(std::string& content)
{
ParsedTextures ret;
std::smatch match;
size_t offset = 0;
while (std::regex_search(content.cbegin() + offset, content.cend(), match, std::regex("Texture([\\d]+)\\s+([\\w]+)\\s+\\{")))
{
ParsedTexture texture;
texture.index = std::stoi(match[1].str());
texture.name = match[2].str();
std::smatch match2;
size_t propsStart = offset + match.position() + match.length();
if (std::regex_search(content.cbegin() + propsStart, content.cend(), match2, std::regex("\\}")))
{
auto propsEnd = propsStart + match2.position() + match2.length();
std::smatch matchProperty;
while (std::regex_search(content.cbegin() + propsStart, content.cbegin() + propsEnd, matchProperty, std::regex("([\\w]+)\\s*=\\s*([\\w]+)\\s*;")))
{
const auto& propName = matchProperty[1].str();
const auto& propValue = matchProperty[2].str();
if (propName == "filter")
{
if (propValue == "nearest")
{
texture.filter = sample::Filtering::Nearest;
}
else if (propValue == "linear")
{
texture.filter = sample::Filtering::Linear;
}
else if (propValue == "bilinear")
{
texture.filter = sample::Filtering::Bilinear;
}
else if (propValue == "trilinear")
{
texture.filter = sample::Filtering::Trilinear;
}
else if (propValue == "anisotropic")
{
texture.filter = sample::Filtering::Anisotropic;
}
else assert(false); // Invalid filter
}
else if (propName == "repeat")
{
if (propValue == "clamp")
{
texture.repeatX = texture.repeatY = sample::AddressMode::Clamp;
}
else if (propValue == "wrap")
{
texture.repeatX = texture.repeatY = sample::AddressMode::Wrap;
}
else assert(false); // Invalid repeat
}
else if (propName == "repeatX")
{
if (propValue == "clamp")
{
texture.repeatX = sample::AddressMode::Clamp;
}
else if (propValue == "wrap")
{
texture.repeatX = sample::AddressMode::Wrap;
}
else assert(false); // Invalid repeat
}
else if (propName == "repeatY")
{
if (propValue == "clamp")
{
texture.repeatY = sample::AddressMode::Clamp;
}
else if (propValue == "wrap")
{
texture.repeatY = sample::AddressMode::Wrap;
}
else assert(false); // Invalid repeat
}
else assert(false); // Invalid texture sampler property
propsStart += matchProperty.position() + matchProperty.length();
}
propsStart = propsEnd;
}
else assert(false); // No matching closing } to texture sample
content[offset + match.position()] = '/';
content[offset + match.position() + 1] = '*';
content[propsStart - 2] = '*';
content[propsStart - 1] = '/';
offset += match.position() + match.length() + match2.position() + match2.length();
ret.push_back(texture);
}
return std::move(ret);
}
static void shaderError(stb_lexer& lexer, const std::string& msg)
{
stb_lex_location loc;
stb_c_lexer_get_location(&lexer, lexer.where_firstchar, &loc);
OLogE("(" + std::to_string(loc.line_number) + "," + std::to_string(loc.line_offset) + ") " + msg);
}
static bool parseElement(Shader::ParsedElement& element, stb_lexer& lexer)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected type");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected type");
return false;
}
if (strcmp(lexer.string, "float") == 0) element.type = Shader::VarType::Float;
else if (strcmp(lexer.string, "float2") == 0) element.type = Shader::VarType::Float2;
else if (strcmp(lexer.string, "float3") == 0) element.type = Shader::VarType::Float3;
else if (strcmp(lexer.string, "float4") == 0) element.type = Shader::VarType::Float4;
else
{
shaderError(lexer, "Expected type of float, float2, float3 or float4");
return false;
}
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected identifier");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected identifier");
return false;
}
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ;");
return false;
}
if ((char)lexer.token != ';')
{
shaderError(lexer, "Expected ;");
return false;
}
element.name = lexer.string;
return true;
}
static bool parseUniform(Shader::ParsedUniform& uniform, stb_lexer& lexer)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected type");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected type");
return false;
}
if (strcmp(lexer.string, "float") == 0) uniform.type = Shader::VarType::Float;
else if (strcmp(lexer.string, "float2") == 0) uniform.type = Shader::VarType::Float2;
else if (strcmp(lexer.string, "float3") == 0) uniform.type = Shader::VarType::Float3;
else if (strcmp(lexer.string, "float4") == 0) uniform.type = Shader::VarType::Float4;
else if (strcmp(lexer.string, "matrix") == 0) uniform.type = Shader::VarType::Matrix;
else
{
shaderError(lexer, "Expected type of float, float2, float3, float4 or matrix");
return false;
}
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected identifier");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected identifier");
return false;
}
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ;");
return false;
}
if ((char)lexer.token == '[')
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected array size");
return false;
}
uniform.count = lexer.int_number;
if (uniform.count < 0)
{
shaderError(lexer, "Expected array size > 0");
return false;
}
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ]");
return false;
}
if ((char)lexer.token != ']')
{
shaderError(lexer, "Expected ]");
return false;
}
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ;");
return false;
}
}
if ((char)lexer.token != ';')
{
shaderError(lexer, "Expected ;");
return false;
}
uniform.name = lexer.string;
return true;
}
static bool parseTexture(Shader::ParsedTexture& texture, stb_lexer& lexer)
{
texture.index = (int)lexer.string[7] - (int)'0';
// Name
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected identifier");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected identifier");
return false;
}
texture.name = lexer.string;
// If that's it, leave it to defaults
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ;");
return false;
}
if ((char)lexer.token == ';')
{
return true;
}
if ((char)lexer.token != '{')
{
shaderError(lexer, "Expected ; or {");
return false;
}
while (true)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected }");
return false;
}
if ((char)lexer.token == '}')
{
break; // All good so far
}
// Property name
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected identifier");
return false;
}
std::string propName = onut::toLower(lexer.string);
// =
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected =");
return false;
}
if ((char)lexer.token != '=')
{
shaderError(lexer, "Expected =");
return false;
}
// Property value
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected identifier");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected identifier");
return false;
}
std::string propValue = onut::toLower(lexer.string);
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ;");
return false;
}
if ((char)lexer.token != ';')
{
shaderError(lexer, "Expected ;");
return false;
}
// Set property
if (propName == "filter")
{
if (propValue == "nearest")
{
texture.filter = sample::Filtering::Nearest;
}
else if (propValue == "linear")
{
texture.filter = sample::Filtering::Linear;
}
else if (propValue == "bilinear")
{
texture.filter = sample::Filtering::Bilinear;
}
else if (propValue == "trilinear")
{
texture.filter = sample::Filtering::Trilinear;
}
else if (propValue == "anisotropic")
{
texture.filter = sample::Filtering::Anisotropic;
}
else
{
shaderError(lexer, "Invalid filter");
return false;
}
}
else if (propName == "repeat")
{
if (propValue == "clamp")
{
texture.repeatX = texture.repeatY = sample::AddressMode::Clamp;
}
else if (propValue == "wrap")
{
texture.repeatX = texture.repeatY = sample::AddressMode::Wrap;
}
else
{
shaderError(lexer, "Invalid repeat");
return false;
}
}
else if (propName == "repeatx")
{
if (propValue == "clamp")
{
texture.repeatX = sample::AddressMode::Clamp;
}
else if (propValue == "wrap")
{
texture.repeatX = sample::AddressMode::Wrap;
}
else
{
shaderError(lexer, "Invalid repeat");
return false;
}
}
else if (propName == "repeaty")
{
if (propValue == "clamp")
{
texture.repeatY = sample::AddressMode::Clamp;
}
else if (propValue == "wrap")
{
texture.repeatY = sample::AddressMode::Wrap;
}
else
{
shaderError(lexer, "Invalid repeat");
return false;
}
}
else
{
shaderError(lexer, "Invalid texture sampler property");
return false;
}
}
return true;
}
static bool parseStruct(Shader::Struct& _struct, stb_lexer& lexer)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected identifier");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected identifier");
return false;
}
_struct.name = lexer.string;
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected {");
return false;
}
if ((char)lexer.token != '{')
{
shaderError(lexer, "Expected {");
return false;
}
while (true)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected }");
return false;
}
if ((char)lexer.token == '}')
{
if (_struct.members.empty())
{
shaderError(lexer, "Expected members");
return false;
}
break; // All good so far
}
// Member type
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected type");
return false;
}
Shader::StructMember member;
if (strcmp(lexer.string, "float") == 0) member.type = Shader::VarType::Float;
else if (strcmp(lexer.string, "float2") == 0) member.type = Shader::VarType::Float2;
else if (strcmp(lexer.string, "float3") == 0) member.type = Shader::VarType::Float3;
else if (strcmp(lexer.string, "float4") == 0) member.type = Shader::VarType::Float4;
else if (strcmp(lexer.string, "matrix") == 0) member.type = Shader::VarType::Matrix;
else
{
member.type = Shader::VarType::Unknown;
member.typeName = lexer.string;
}
// Member name
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected identifier");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected identifier");
return false;
}
member.name = lexer.string;
// Check if we don't already have a member of the same name...
for (const auto& otherMember : _struct.members)
{
if (otherMember.name == member.name)
{
shaderError(lexer, "Duplicated member");
return false;
}
}
_struct.members.push_back(member);
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ;");
return false;
}
if ((char)lexer.token != ';')
{
shaderError(lexer, "Expected ;");
return false;
}
}
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ;");
return false;
}
if ((char)lexer.token != ';')
{
shaderError(lexer, "Expected ;");
return false;
}
return true;
}
struct IntrinsicDesc
{
Shader::Intrinsic intrinsic;
int argCount;
};
static std::map<std::string, IntrinsicDesc> INTRINSIC_DESCS = {
{ "radians",{ Shader::Intrinsic::Radians, 1 } },
{ "degrees",{ Shader::Intrinsic::Degrees, 1 } },
{ "sin",{ Shader::Intrinsic::Sin, 1 } },
{ "cos",{ Shader::Intrinsic::Cos, 1 } },
{ "tan",{ Shader::Intrinsic::Tan, 1 } },
{ "asin",{ Shader::Intrinsic::ASin, 1 } },
{ "acos",{ Shader::Intrinsic::ACos, 1 } },
{ "atan",{ Shader::Intrinsic::ATan, 1 } },
{ "atan2",{ Shader::Intrinsic::ATan2, 2 } },
{ "pow",{ Shader::Intrinsic::Pow, 2 } },
{ "exp",{ Shader::Intrinsic::Exp, 1 } },
{ "log",{ Shader::Intrinsic::Log, 1 } },
{ "exp2",{ Shader::Intrinsic::Exp2, 1 } },
{ "log2",{ Shader::Intrinsic::Log2, 1 } },
{ "sqrt",{ Shader::Intrinsic::Sqrt, 1 } },
{ "rsqrt",{ Shader::Intrinsic::RSqrt, 1 } },
{ "abs",{ Shader::Intrinsic::Abs, 1 } },
{ "sign",{ Shader::Intrinsic::Sign, 1 } },
{ "floor",{ Shader::Intrinsic::Floor, 1 } },
{ "ceil",{ Shader::Intrinsic::Ceil, 1 } },
{ "frac",{ Shader::Intrinsic::Frac, 1 } },
{ "mod",{ Shader::Intrinsic::Mod, 2 } },
{ "min",{ Shader::Intrinsic::Min, 2 } },
{ "max",{ Shader::Intrinsic::Max, 2 } },
{ "clamp",{ Shader::Intrinsic::Clamp, 3 } },
{ "saturate",{ Shader::Intrinsic::Saturate, 1 } },
{ "lerp",{ Shader::Intrinsic::Lerp, 3 } },
{ "step",{ Shader::Intrinsic::Step, 2 } },
{ "smoothstep",{ Shader::Intrinsic::SmoothStep, 3 } },
{ "length",{ Shader::Intrinsic::Length, 1 } },
{ "distance",{ Shader::Intrinsic::Distance, 2 } },
{ "dot",{ Shader::Intrinsic::Dot, 2 } },
{ "cross",{ Shader::Intrinsic::Cross, 2 } },
{ "normalize",{ Shader::Intrinsic::Normalize, 1 } },
{ "faceforward",{ Shader::Intrinsic::FaceForward, 3 } },
{ "reflect",{ Shader::Intrinsic::Reflect, 2 } },
{ "refract",{ Shader::Intrinsic::Refract, 3 } },
{ "any",{ Shader::Intrinsic::Any, 1 } },
{ "all",{ Shader::Intrinsic::All, 1 } },
{ "mul",{ Shader::Intrinsic::Mul, 2 } },
{ "round",{ Shader::Intrinsic::Round, 1 } }
};
static bool parseIntrinsic(Shader::Token& token, int argCount, stb_lexer& lexer);
static bool parseToken(Shader::Token& token, stb_lexer& lexer, std::vector<onut::Shader::Token>& tokens)
{
token.intrinsic = Shader::Intrinsic::None;
token.type = Shader::VarType::Unknown;
if (lexer.token == CLEX_id)
{
token.str = lexer.string;
auto it = INTRINSIC_DESCS.find(lexer.string);
// Check if we call an instrinsic function
if (it != INTRINSIC_DESCS.end())
{
token.intrinsic = it->second.intrinsic;
if (!parseIntrinsic(token, it->second.argCount, lexer)) return false;
}
else if (strcmp(lexer.string, "float") == 0) token.type = Shader::VarType::Float;
else if (strcmp(lexer.string, "float2") == 0) token.type = Shader::VarType::Float2;
else if (strcmp(lexer.string, "float3") == 0) token.type = Shader::VarType::Float3;
else if (strcmp(lexer.string, "float4") == 0) token.type = Shader::VarType::Float4;
else if (strcmp(lexer.string, "matrix") == 0) token.type = Shader::VarType::Matrix;
}
else if (lexer.token == CLEX_intlit)
{
if (!tokens.empty() && tokens.back().str == ".")
{
tokens.back().str = "0." + std::to_string(lexer.int_number);;
token.str = "";
}
else
{
token.str = std::to_string(lexer.int_number) + ".0";
}
}
else if (lexer.token == CLEX_floatlit)
{
token.str = std::to_string(lexer.real_number);
}
else if (lexer.token == CLEX_eq) token.str = "==";
else if (lexer.token == CLEX_noteq) token.str = "!=";
else if (lexer.token == CLEX_lesseq) token.str = "<=";
else if (lexer.token == CLEX_greatereq) token.str = ">=";
else if (lexer.token == CLEX_andand) token.str = "&&";
else if (lexer.token == CLEX_oror) token.str = "||";
else if (lexer.token == CLEX_shl) token.str = "<<";
else if (lexer.token == CLEX_shr) token.str = ">>";
else if (lexer.token == CLEX_plusplus) token.str = "++";
else if (lexer.token == CLEX_minusminus) token.str = "--";
else if (lexer.token == CLEX_pluseq) token.str = "+=";
else if (lexer.token == CLEX_minuseq) token.str = "-=";
else if (lexer.token == CLEX_muleq) token.str = "*=";
else if (lexer.token == CLEX_diveq) token.str = "/=";
else if (lexer.token == CLEX_modeq)
{
shaderError(lexer, "Modulo operator % is unsupported. Use mod(x, y) intrinsic instead");
return false;
}
else if (lexer.token == CLEX_andeq) token.str = "&=";
else if (lexer.token == CLEX_oreq) token.str = "|=";
else if (lexer.token == CLEX_xoreq) token.str = "^=";
else
{
token.str = std::string() + (char)lexer.token;
}
return true;
}
static bool parseIntrinsic(Shader::Token& token, int argCount, stb_lexer& lexer)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected (");
return false;
}
if ((char)lexer.token != '(')
{
shaderError(lexer, "Expected (");
return false;
}
int deep = 1;
while (true)
{
std::vector<Shader::Token> argument;
while (true)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Unexpected end of file");
return false;
}
if ((char)lexer.token == ',' && deep == 1)
{
if (argument.empty())
{
shaderError(lexer, "Expected tokens");
return false;
}
token.intrinsicArguments.push_back(argument);
break; // Go for the next argument
}
if ((char)lexer.token == '(')
{
++deep;
}
if ((char)lexer.token == ')')
{
--deep;
if (deep <= 0)
{
token.intrinsicArguments.push_back(argument);
break;
}
}
Shader::Token subToken;
if (!parseToken(subToken, lexer, argument)) return false;
argument.push_back(subToken);
}
if (deep <= 0) break; // All good so far
}
if ((int)token.intrinsicArguments.size() != argCount)
{
shaderError(lexer, "Wrong argument count");
return false;
}
return true;
}
static bool parseConst(Shader::Const& _const, stb_lexer& lexer)
{
// Const type
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected type");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected type");
return false;
}
else if (strcmp(lexer.string, "float") == 0) _const.type = Shader::VarType::Float;
else if (strcmp(lexer.string, "float2") == 0) _const.type = Shader::VarType::Float2;
else if (strcmp(lexer.string, "float3") == 0) _const.type = Shader::VarType::Float3;
else if (strcmp(lexer.string, "float4") == 0) _const.type = Shader::VarType::Float4;
else if (strcmp(lexer.string, "matrix") == 0) _const.type = Shader::VarType::Matrix;
else
{
_const.type = Shader::VarType::Unknown;
_const.typeName = lexer.string;
}
// const name
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected identifier");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected identifier");
return false;
}
_const.name = lexer.string;
// Check if it's an array
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected identifier");
return false;
}
if ((char)lexer.token == '[')
{
_const.isArray = true;
while (true)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ]");
return false;
}
if ((char)lexer.token == ']')
{
if (_const.arrayArguments.empty())
{
shaderError(lexer, "Expected array size");
return false;
}
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected =");
return false;
}
break;
}
Shader::Token token;
if (!parseToken(token, lexer, _const.arrayArguments)) return false;
_const.arrayArguments.push_back(token);
}
}
else
{
_const.isArray = false;
}
if ((char)lexer.token != '=')
{
shaderError(lexer, "Expected =");
return false;
}
if (_const.isArray)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected { array initializer");
return false;
}
if ((char)lexer.token != '{')
{
shaderError(lexer, "Expected { array initializer");
return false;
}
}
while (true)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ;");
return false;
}
if ((char)lexer.token == ';')
{
if (_const.arguments.empty())
{
shaderError(lexer, "Expected value");
return false;
}
break;
}
if ((char)lexer.token == '}' && _const.isArray)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected ;");
return false;
}
if ((char)lexer.token == ';')
{
if (_const.arguments.empty())
{
shaderError(lexer, "Expected value");
return false;
}
break;
}
else
{
shaderError(lexer, "Expected ;");
return false;
}
}
Shader::Token token;
if (!parseToken(token, lexer, _const.arguments)) return false;
_const.arguments.push_back(token);
}
return true;
}
static bool parseFunction(Shader::Function& _function, stb_lexer& lexer)
{
// Return type
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected type");
return false;
}
else if (strcmp(lexer.string, "float") == 0) _function.type = Shader::VarType::Float;
else if (strcmp(lexer.string, "float2") == 0) _function.type = Shader::VarType::Float2;
else if (strcmp(lexer.string, "float3") == 0) _function.type = Shader::VarType::Float3;
else if (strcmp(lexer.string, "float4") == 0) _function.type = Shader::VarType::Float4;
else if (strcmp(lexer.string, "matrix") == 0) _function.type = Shader::VarType::Matrix;
else
{
_function.type = Shader::VarType::Unknown;
_function.typeName = lexer.string;
}
// Function name
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected identifier");
return false;
}
if (lexer.token != CLEX_id)
{
shaderError(lexer, "Expected identifier");
return false;
}
_function.name = lexer.string;
// Arguments
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected (");
return false;
}
if ((char)lexer.token != '(')
{
shaderError(lexer, "Expected (");
return false;
}
if (_function.name == "main")
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected )");
return false;
}
if ((char)lexer.token != ')')
{
shaderError(lexer, "Expected ), main function has no arguments");
return false;
}
}
else
{
while (true)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected )");
return false;
}
if ((char)lexer.token == ')')
{
break; // All good so far
}
Shader::Token token;
if (!parseToken(token, lexer, _function.arguments)) return false;
_function.arguments.push_back(token);
}
}
// Body
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Expected {");
return false;
}
if ((char)lexer.token != '{')
{
shaderError(lexer, "Expected {");
return false;
}
int deep = 1;
while (true)
{
if (!stb_c_lexer_get_token(&lexer))
{
shaderError(lexer, "Unexpected end of file");
return false;
}
if ((char)lexer.token == '{')
{
++deep;
}
if ((char)lexer.token == '}')
{
--deep;
if (deep <= 0) break; // All good so far
}
Shader::Token token;
if (!parseToken(token, lexer, _function.body)) return false;
_function.body.push_back(token);
}
return true;
}
Shader::ParsedVS Shader::parseVertexShader(const std::string& in_content)
{
ParsedVS ret;
stb_lexer lexer;
char* string_store = new char[1024];
stb_c_lexer_init(&lexer, in_content.c_str(), in_content.c_str() + in_content.size(), string_store, 1024);
while (stb_c_lexer_get_token(&lexer))
{
char tokenC = (char)lexer.token;
if (strcmp(lexer.string, "input") == 0)
{
ParsedElement input;
if (!parseElement(input, lexer)) break;
ret.inputs.push_back(input);
}
else if (strcmp(lexer.string, "output") == 0)
{
ParsedElement output;
if (!parseElement(output, lexer)) break;
ret.outputs.push_back(output);
}
else if (strcmp(lexer.string, "extern") == 0)
{
ParsedUniform uniform;
if (!parseUniform(uniform, lexer)) break;
ret.uniforms.push_back(uniform);
}
else if (strcmp(lexer.string, "const") == 0)
{
Const _const;
if (!parseConst(_const, lexer)) break;
ret.consts.push_back(_const);
}
else if (strcmp(lexer.string, "struct") == 0)
{
Struct _struct;
if (!parseStruct(_struct, lexer)) break;
ret.structs.push_back(_struct);
}
#if defined(WIN32)
else if (_strnicmp(lexer.string, "texture", 7) == 0)
#else
else if (strncasecmp(lexer.string, "texture", 7) == 0)
#endif
{
std::string texI = lexer.string;
if (texI.size() == 8 && texI[7] >= '0' && texI[7] <= '9')
{
ParsedTexture texture;
if (!parseTexture(texture, lexer)) break;
ret.textures.push_back(texture);
}
else
{
shaderError(lexer, "Expected texture index [0, 8]");
break;
}
}
else if (strcmp(lexer.string, "void") == 0)
{
// This has to be the main function
auto where = lexer.where_firstchar;
if (!parseFunction(ret.mainFunction, lexer)) break;
if (ret.mainFunction.name != "main")
{
lexer.where_firstchar = where;
shaderError(lexer, "Only the main function have void as return type");
break;
}
}
else if ((char)lexer.token == ';' ||
(char)lexer.token == '\0')
{
// That's fine, ignore it
}
else
{
// Nothing else than a function ca be here
Function _function;
if (!parseFunction(_function, lexer)) break;
ret.functions.push_back(_function);
}
}
delete[] string_store;
return std::move(ret);
}
Shader::ParsedPS Shader::parsePixelShader(const std::string& in_content)
{
ParsedPS ret;
stb_lexer lexer;
char* string_store = new char[1024];
stb_c_lexer_init(&lexer, in_content.c_str(), in_content.c_str() + in_content.size(), string_store, 1024);
while (stb_c_lexer_get_token(&lexer))
{
char tokenC = (char)lexer.token;
if (strcmp(lexer.string, "input") == 0)
{
ParsedElement input;
if (!parseElement(input, lexer)) break;
ret.inputs.push_back(input);
}
else if (strcmp(lexer.string, "extern") == 0)
{
ParsedUniform uniform;
if (!parseUniform(uniform, lexer)) break;
ret.uniforms.push_back(uniform);
}
else if (strcmp(lexer.string, "struct") == 0)
{
Struct _struct;
if (!parseStruct(_struct, lexer)) break;
ret.structs.push_back(_struct);
}
else if (strcmp(lexer.string, "const") == 0)
{
Const _const;
if (!parseConst(_const, lexer)) break;
ret.consts.push_back(_const);
}
#if defined(WIN32)
else if (_strnicmp(lexer.string, "texture", 7) == 0)
#else
else if (strncasecmp(lexer.string, "texture", 7) == 0)
#endif
{
std::string texI = lexer.string;
if (texI.size() == 8 && texI[7] >= '0' && texI[7] <= '9')
{
ParsedTexture texture;
if (!parseTexture(texture, lexer)) break;
ret.textures.push_back(texture);
}
else
{
shaderError(lexer, "Expected texture index [0, 8]");
break;
}
}
else if (strcmp(lexer.string, "void") == 0)
{
// This has to be the main function
auto where = lexer.where_firstchar;
if (!parseFunction(ret.mainFunction, lexer)) break;
if (ret.mainFunction.name != "main")
{
lexer.where_firstchar = where;
shaderError(lexer, "Only the main function have void as return type");
break;
}
}
else if ((char)lexer.token == ';' ||
(char)lexer.token == '\0')
{
// That's fine, ignore it
}
else
{
// Nothing else than a function can be here
Function _function;
if (!parseFunction(_function, lexer)) break;
ret.functions.push_back(_function);
}
}
delete[] string_store;
return std::move(ret);
}
};
OShaderRef OGetShader(const std::string& name)
{
return oContentManager->getResourceAs<OShader>(name);
}
| mit |
elastacloud/parquet-dotnet | src/SharpArrow/Flatbuffers/org/apache/arrow/flatbuf/TimeUnit.cs | 255 | // <auto-generated>
// automatically generated by the FlatBuffers compiler, do not modify
// </auto-generated>
namespace org.apache.arrow.flatbuf
{
public enum TimeUnit : short
{
SECOND = 0,
MILLISECOND = 1,
MICROSECOND = 2,
NANOSECOND = 3,
};
}
| mit |
baretata/CSharpPartOne | 02.Primitive Data Types and Variables/Null assigenment/Program.cs | 585 | using System;
class NullAssigenment
{
static void Main()
{
int? intNum = null;
Console.WriteLine("Integer null: {0}", intNum);
Console.WriteLine("Integer null + 5: {0}", intNum + 5);
intNum = 5;
Console.WriteLine("Integer null with assigned value: {0}", intNum);
double? doubleNum = null;
Console.WriteLine("Double null: {0}", doubleNum);
Console.WriteLine("Double null + 5: {0}", doubleNum + 5);
doubleNum = 2.2;
Console.WriteLine("Double null with assigned value: {0}", doubleNum);
}
}
| mit |
medcat/command-runner | spec/spawn_spec.rb | 1266 | describe Command::Runner::Backends::Spawn do
next unless Process.respond_to?(:spawn) && !(RUBY_PLATFORM == "java" && RUBY_VERSION =~ /\A1\.9/)
it("is safe") { expect(described_class).to_not be_unsafe }
it "is available" do
expect(Command::Runner::Backends::Spawn).to be_available
end
it "returns a message" do
value = subject.call("echo", ["hello"])
expect(value).to be_instance_of Command::Runner::Message
expect(value).to be_executed
end
it "doesn't block" do
start_time = Time.now
value = subject.call("sleep", ["0.5"])
end_time = Time.now
expect(end_time - start_time).to be_within((1.0/100)).of(0)
expect(value.time).to be_within((3.0/100)).of(0.5)
end
it "doesn't expose arguments to the shell" do
value = subject.call("echo", ["`uname -a`"])
expect(value.stdout).to eq "`uname -a`\n"
end
it "can be unsafe" do
value = subject.call("echo", ["`uname -a`"], {}, unsafe: true)
expect(value.stdout).to_not eq "`uname -a`\n"
end
it "can not be available" do
allow(Command::Runner::Backends::Spawn).to receive(:available?).and_return(false)
expect {
Command::Runner::Backends::Spawn.new
}.to raise_error(Command::Runner::NotAvailableBackendError)
end
end
| mit |
zifeiyusama/zifeiyu | config.py | 911 | import os
_basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
ADMINS = frozenset(['[email protected]'])
SECRET_KEY = 'f2f49908291696b8a4bb7d36b83589995cdca626'
# SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'apptest5.db')
SQLALCHEMY_DATABASE_URI = 'mysql://root:dpfyl@localhost:3306/zifeiyu'
# SQLALCHEMY_DATABASE_URI = create_engine('mysql://scott:tiger@localhost/foo')
# SQLALCHEMY_DATABASE_URI = 'postgres://zfjoxmtggitxte:KRrDVUAz0bt6WMpfMrzYPggmSx@ec2-54-83-198-111.compute-1.amazonaws.com:5432/dkiccm559kf32'
DATABASE_CONNECT_OPTIONS = {}
# THREADS_PER_PAGE = 8
WTF_CSRF_ENABLED = True
WTF_CSRF_SECRET_KEY = "8f37f2a475fc1cdcdb9496337244b760456f0646"
# RECAPTCHA_USE_SSL = False
# RECAPTCHA_PUBLIC_KEY = '6LeYIbsSAAAAACRPIllxA7wvXjIE411PfdB2gt2J'
# RECAPTCHA_PRIVATE_KEY = '6LeYIbsSAAAAAJezaIq3Ft_hSTo0YtyeFG-JgRtu'
# RECAPTCHA_OPTIONS = {'theme': 'white'}
| mit |
rajananusha/swhacks2017 | Assets/Scripts/AsteroidManager.cs | 1331 | using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class AsteroidManager : MonoBehaviour {
//public GameObject AstroExplosion;
int x,y,z;
EnemyManager e;
bool flag;
// Use this for initialization
void Start () {
x = Random.Range (-30, 30);
y = Random.Range (-30, 30);
z = Random.Range (-30, 30);
flag = true;
}
// Update is called once per frame
void Update()
{
if (flag)
{
float speed = 0.01f * (GameObject.Find("Managers").GetComponent<ScoreManager>().score + 1);
Vector3 tempPosition = new Vector3(-0.1378743f, -0.100489f, 0.2082129f) - transform.position;
if (tempPosition.sqrMagnitude < 1f)
{
flag = false;
//GameObject.Find ("Managers").GetComponent<ScoreManager>.WriteScore ();
SceneManager.LoadScene("Finish");
//StartCoroutine (EndGame);
}
transform.position = Vector3.Lerp(transform.position, new Vector3(-0.1378743f, -0.100489f, 0.2082129f), Time.deltaTime * speed);
transform.Rotate(x * Time.deltaTime * 2, y * Time.deltaTime * 2, z * Time.deltaTime * 2);
}
}
/*IEnumerator EndGame() {
yield return new WaitForSeconds (2f);
SceneManager.LoadScene("Finish");
}*/
}
| mit |
lpatalas/NhLogAnalyzer | NhLogAnalyzer/Properties/Resources.Designer.cs | 2437 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18034
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NhLogAnalyzer.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NhLogAnalyzer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| mit |
justinmarentette11/Tower-Defense-Galaxy | core/src/com/logicmaster63/tdgalaxy/networking/packets/ConfirmSession.java | 236 | package com.logicmaster63.tdgalaxy.networking.packets;
public class ConfirmSession {
public String session;
public ConfirmSession(String session) {
this.session = session;
}
public ConfirmSession() {
}
}
| mit |
hgoebl/DavidWebb | src/main/java/com/goebl/david/WebbUtils.java | 14223 | package com.goebl.david;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* Static utility method and tools for HTTP traffic parsing and encoding.
*
* @author hgoebl
*/
public class WebbUtils {
protected WebbUtils() {}
/**
* Convert a Map to a query string.
* @param values the map with the values
* <code>null</code> will be encoded as empty string, all other objects are converted to
* String by calling its <code>toString()</code> method.
* @return e.g. "key1=value&key2=&email=max%40example.com"
*/
public static String queryString(Map<String, Object> values) {
StringBuilder sbuf = new StringBuilder();
String separator = "";
for (Map.Entry<String, Object> entry : values.entrySet()) {
Object entryValue = entry.getValue();
if (entryValue instanceof Object[]) {
for (Object value : (Object[]) entryValue) {
appendParam(sbuf, separator, entry.getKey(), value);
separator = "&";
}
} else if (entryValue instanceof Iterable) {
for (Object multiValue : (Iterable) entryValue) {
appendParam(sbuf, separator, entry.getKey(), multiValue);
separator = "&";
}
} else {
appendParam(sbuf, separator, entry.getKey(), entryValue);
separator = "&";
}
}
return sbuf.toString();
}
private static void appendParam(StringBuilder sbuf, String separator, String entryKey, Object value) {
String sValue = value == null ? "" : String.valueOf(value);
sbuf.append(separator);
sbuf.append(urlEncode(entryKey));
sbuf.append('=');
sbuf.append(urlEncode(sValue));
}
/**
* Convert a byte array to a JSONObject.
* @param bytes a UTF-8 encoded string representing a JSON object.
* @return the parsed object
* @throws WebbException in case of error (usually a parsing error due to invalid JSON)
*/
public static JSONObject toJsonObject(byte[] bytes) {
String json;
try {
json = new String(bytes, Const.UTF8);
return new JSONObject(json);
} catch (UnsupportedEncodingException e) {
throw new WebbException(e);
} catch (JSONException e) {
throw new WebbException("payload is not a valid JSON object", e);
}
}
/**
* Convert a byte array to a JSONArray.
* @param bytes a UTF-8 encoded string representing a JSON array.
* @return the parsed JSON array
* @throws WebbException in case of error (usually a parsing error due to invalid JSON)
*/
public static JSONArray toJsonArray(byte[] bytes) {
String json;
try {
json = new String(bytes, Const.UTF8);
return new JSONArray(json);
} catch (UnsupportedEncodingException e) {
throw new WebbException(e);
} catch (JSONException e) {
throw new WebbException("payload is not a valid JSON array", e);
}
}
/**
* Read an <code>InputStream</code> into <code>byte[]</code> until EOF.
* <br>
* Does not close the InputStream!
*
* @param is the stream to read the bytes from
* @return all read bytes as an array
* @throws IOException when read or write operation fails
*/
public static byte[] readBytes(InputStream is) throws IOException {
if (is == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copyStream(is, baos);
return baos.toByteArray();
}
/**
* Copy complete content of <code>InputStream</code> to <code>OutputStream</code> until EOF.
* <br>
* Does not close the InputStream nor OutputStream!
*
* @param input the stream to read the bytes from
* @param output the stream to write the bytes to
* @throws IOException when read or write operation fails
*/
public static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int count;
while ((count = input.read(buffer)) != -1) {
output.write(buffer, 0, count);
}
}
/**
* Creates a new instance of a <code>DateFormat</code> for RFC1123 compliant dates.
* <br>
* Should be stored for later use but be aware that this DateFormat is not Thread-safe!
* <br>
* If you have to deal with dates in this format with JavaScript, it's easy, because the JavaScript
* Date object has a constructor for strings formatted this way.
* @return a new instance
*/
public static DateFormat getRfc1123DateFormat() {
DateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
format.setLenient(false);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
return format;
}
static String urlEncode(String value) {
try {
return URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
return value;
}
}
static void addRequestProperties(HttpURLConnection connection, Map<String, Object> map) {
if (map == null || map.isEmpty()) {
return;
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
addRequestProperty(connection, entry.getKey(), entry.getValue());
}
}
static void addRequestProperty(HttpURLConnection connection, String name, Object value) {
if (name == null || name.length() == 0 || value == null) {
throw new IllegalArgumentException("name and value must not be empty");
}
String valueAsString;
if (value instanceof Date) {
valueAsString = getRfc1123DateFormat().format((Date) value);
} else if (value instanceof Calendar) {
valueAsString = getRfc1123DateFormat().format(((Calendar) value).getTime());
} else {
valueAsString = value.toString();
}
connection.addRequestProperty(name, valueAsString);
}
static void ensureRequestProperty(HttpURLConnection connection, String name, Object value) {
if (!connection.getRequestProperties().containsKey(name)) {
addRequestProperty(connection, name, value);
}
}
static byte[] getPayloadAsBytesAndSetContentType(
HttpURLConnection connection,
Request request,
boolean compress,
int jsonIndentFactor) throws JSONException, UnsupportedEncodingException {
byte[] requestBody = null;
String bodyStr = null;
if (request.params != null) {
WebbUtils.ensureRequestProperty(connection, Const.HDR_CONTENT_TYPE, Const.APP_FORM);
bodyStr = WebbUtils.queryString(request.params);
} else if (request.payload == null) {
return null;
} else if (request.payload instanceof JSONObject) {
WebbUtils.ensureRequestProperty(connection, Const.HDR_CONTENT_TYPE, Const.APP_JSON);
bodyStr = jsonIndentFactor >= 0
? ((JSONObject) request.payload).toString(jsonIndentFactor)
: request.payload.toString();
} else if (request.payload instanceof JSONArray) {
WebbUtils.ensureRequestProperty(connection, Const.HDR_CONTENT_TYPE, Const.APP_JSON);
bodyStr = jsonIndentFactor >= 0
? ((JSONArray) request.payload).toString(jsonIndentFactor)
: request.payload.toString();
} else if (request.payload instanceof byte[]) {
WebbUtils.ensureRequestProperty(connection, Const.HDR_CONTENT_TYPE, Const.APP_BINARY);
requestBody = (byte[]) request.payload;
} else {
WebbUtils.ensureRequestProperty(connection, Const.HDR_CONTENT_TYPE, Const.TEXT_PLAIN);
bodyStr = request.payload.toString();
}
if (bodyStr != null) {
requestBody = bodyStr.getBytes(Const.UTF8);
}
if (requestBody == null) {
throw new IllegalStateException();
}
// only compress if the new body is smaller than uncompressed body
if (compress && requestBody.length > Const.MIN_COMPRESSED_ADVANTAGE) {
byte[] compressedBody = gzip(requestBody);
if (requestBody.length - compressedBody.length > Const.MIN_COMPRESSED_ADVANTAGE) {
requestBody = compressedBody;
connection.setRequestProperty(Const.HDR_CONTENT_ENCODING, "gzip");
}
}
connection.setFixedLengthStreamingMode(requestBody.length);
return requestBody;
}
static void setContentTypeAndLengthForStreaming(
HttpURLConnection connection,
Request request,
boolean compress) {
long length;
if (request.payload instanceof File) {
length = compress ? -1L : ((File) request.payload).length();
} else if (request.payload instanceof InputStream) {
length = -1L;
} else {
throw new IllegalStateException();
}
if (length > Integer.MAX_VALUE) {
length = -1L; // use chunked streaming mode
}
WebbUtils.ensureRequestProperty(connection, Const.HDR_CONTENT_TYPE, Const.APP_BINARY);
if (length < 0) {
connection.setChunkedStreamingMode(-1); // use default chunk size
if (compress) {
connection.setRequestProperty(Const.HDR_CONTENT_ENCODING, "gzip");
}
} else {
connection.setFixedLengthStreamingMode((int) length);
}
}
static byte[] gzip(byte[] input) {
GZIPOutputStream gzipOS = null;
try {
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
gzipOS = new GZIPOutputStream(byteArrayOS);
gzipOS.write(input);
gzipOS.flush();
gzipOS.close();
gzipOS = null;
return byteArrayOS.toByteArray();
} catch (Exception e) {
throw new WebbException(e);
} finally {
if (gzipOS != null) {
try { gzipOS.close(); } catch (Exception ignored) {}
}
}
}
static InputStream wrapStream(String contentEncoding, InputStream inputStream) throws IOException {
if (contentEncoding == null || "identity".equalsIgnoreCase(contentEncoding)) {
return inputStream;
}
if ("gzip".equalsIgnoreCase(contentEncoding)) {
return new GZIPInputStream(inputStream);
}
if ("deflate".equalsIgnoreCase(contentEncoding)) {
return new InflaterInputStream(inputStream, new Inflater(false), 512);
}
throw new WebbException("unsupported content-encoding: " + contentEncoding);
}
static <T> void parseResponseBody(Class<T> clazz, Response<T> response, InputStream responseBodyStream)
throws UnsupportedEncodingException, IOException {
if (responseBodyStream == null || clazz == Void.class) {
return;
} else if (clazz == InputStream.class) {
response.setBody(responseBodyStream);
return;
}
byte[] responseBody = WebbUtils.readBytes(responseBodyStream);
// we are ignoring headers describing the content type of the response, instead
// try to force the content based on the type the client is expecting it (clazz)
if (clazz == String.class) {
response.setBody(new String(responseBody, Const.UTF8));
} else if (clazz == Const.BYTE_ARRAY_CLASS) {
response.setBody(responseBody);
} else if (clazz == JSONObject.class) {
response.setBody(WebbUtils.toJsonObject(responseBody));
} else if (clazz == JSONArray.class) {
response.setBody(WebbUtils.toJsonArray(responseBody));
}
}
static <T> void parseErrorResponse(Class<T> clazz, Response<T> response, InputStream responseBodyStream)
throws UnsupportedEncodingException, IOException {
if (responseBodyStream == null) {
return;
} else if (clazz == InputStream.class) {
response.errorBody = responseBodyStream;
return;
}
byte[] responseBody = WebbUtils.readBytes(responseBodyStream);
String contentType = response.connection.getContentType();
if (contentType == null || contentType.startsWith(Const.APP_BINARY) || clazz == Const.BYTE_ARRAY_CLASS) {
response.errorBody = responseBody;
return;
}
if (contentType.startsWith(Const.APP_JSON) && clazz == JSONObject.class) {
try {
response.errorBody = WebbUtils.toJsonObject(responseBody);
return;
} catch (Exception ignored) {
// ignored - was just a try!
}
}
// fallback to String if bytes are valid UTF-8 characters ...
try {
response.errorBody = new String(responseBody, Const.UTF8);
return;
} catch (Exception ignored) {
// ignored - was just a try!
}
// last fallback - return error object as byte[]
response.errorBody = responseBody;
}
}
| mit |
ronnyek/linq2db | Tests/Linq/DataProvider/SqlServerTests.cs | 66176 | using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using LinqToDB;
using LinqToDB.Common;
using LinqToDB.Data;
using LinqToDB.DataProvider.SqlServer;
using LinqToDB.Mapping;
#if !NETSTANDARD1_6
using Microsoft.SqlServer.Types;
using SqlServerTypes;
#endif
using NUnit.Framework;
namespace Tests.DataProvider
{
[TestFixture]
public class SqlServerTests : DataProviderTestBase
{
#if !NETSTANDARD1_6 && !MONO
[OneTimeSetUp]
protected void InitializeFixture()
{
// load spatial types support
//Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);
}
#endif
[Test]
public void TestParameters([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
Assert.That(conn.Execute<string>("SELECT @p", new { p = 1 }), Is.EqualTo("1"));
Assert.That(conn.Execute<string>("SELECT @p", new { p = "1" }), Is.EqualTo("1"));
Assert.That(conn.Execute<int> ("SELECT @p", new { p = new DataParameter { Value = 1 } }), Is.EqualTo(1));
Assert.That(conn.Execute<string>("SELECT @p1", new { p1 = new DataParameter { Value = "1" } }), Is.EqualTo("1"));
Assert.That(conn.Execute<int> ("SELECT @p1 + @p2", new { p1 = 2, p2 = 3 }), Is.EqualTo(5));
Assert.That(conn.Execute<int> ("SELECT @p2 + @p1", new { p2 = 2, p1 = 3 }), Is.EqualTo(5));
}
}
[Test]
public void TestDataTypes([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
Assert.That(TestType<long?> (conn, "bigintDataType", DataType.Int64), Is.EqualTo(1000000L));
Assert.That(TestType<decimal?> (conn, "numericDataType", DataType.Decimal), Is.EqualTo(9999999m));
Assert.That(TestType<bool?> (conn, "bitDataType", DataType.Boolean), Is.EqualTo(true));
Assert.That(TestType<short?> (conn, "smallintDataType", DataType.Int16), Is.EqualTo(25555));
Assert.That(TestType<decimal?> (conn, "decimalDataType", DataType.Decimal), Is.EqualTo(2222222m));
Assert.That(TestType<decimal?> (conn, "smallmoneyDataType", DataType.SmallMoney,
skipUndefinedNull : context == ProviderName.SqlServer2000), Is.EqualTo(100000m));
Assert.That(TestType<int?> (conn, "intDataType", DataType.Int32), Is.EqualTo(7777777));
Assert.That(TestType<sbyte?> (conn, "tinyintDataType", DataType.SByte), Is.EqualTo(100));
Assert.That(TestType<decimal?> (conn, "moneyDataType", DataType.Money,
skipUndefinedNull : context == ProviderName.SqlServer2000), Is.EqualTo(100000m));
Assert.That(TestType<double?> (conn, "floatDataType", DataType.Double), Is.EqualTo(20.31d));
Assert.That(TestType<float?> (conn, "realDataType", DataType.Single), Is.EqualTo(16.2f));
Assert.That(TestType<DateTime?>(conn, "datetimeDataType", DataType.DateTime), Is.EqualTo(new DateTime(2012, 12, 12, 12, 12, 12)));
Assert.That(TestType<DateTime?>(conn, "smalldatetimeDataType", DataType.SmallDateTime), Is.EqualTo(new DateTime(2012, 12, 12, 12, 12, 00)));
Assert.That(TestType<char?> (conn, "charDataType", DataType.Char), Is.EqualTo('1'));
Assert.That(TestType<string> (conn, "varcharDataType", DataType.VarChar), Is.EqualTo("234"));
Assert.That(TestType<string> (conn, "ncharDataType", DataType.NVarChar), Is.EqualTo("23233"));
Assert.That(TestType<string> (conn, "nvarcharDataType", DataType.NVarChar), Is.EqualTo("3323"));
Assert.That(TestType<string> (conn, "textDataType", DataType.Text, skipPass:true), Is.EqualTo("567"));
Assert.That(TestType<string> (conn, "ntextDataType", DataType.NText, skipPass:true), Is.EqualTo("111"));
Assert.That(TestType<byte[]> (conn, "binaryDataType", DataType.Binary), Is.EqualTo(new byte[] { 1 }));
Assert.That(TestType<byte[]> (conn, "varbinaryDataType", DataType.VarBinary), Is.EqualTo(new byte[] { 2 }));
Assert.That(TestType<byte[]> (conn, "imageDataType", DataType.Image, skipPass:true), Is.EqualTo(new byte[] { 0, 0, 0, 3 }));
Assert.That(TestType<Guid?> (conn, "uniqueidentifierDataType", DataType.Guid), Is.EqualTo(new Guid("{6F9619FF-8B86-D011-B42D-00C04FC964FF}")));
Assert.That(TestType<object> (conn, "sql_variantDataType", DataType.Variant), Is.EqualTo(10));
Assert.That(TestType<string> (conn, "nvarchar_max_DataType", DataType.NVarChar), Is.EqualTo("22322"));
Assert.That(TestType<string> (conn, "varchar_max_DataType", DataType.VarChar), Is.EqualTo("3333"));
Assert.That(TestType<byte[]> (conn, "varbinary_max_DataType", DataType.VarBinary), Is.EqualTo(new byte[] { 0, 0, 9, 41 }));
Assert.That(TestType<string> (conn, "xmlDataType", DataType.Xml, skipPass:true),
Is.EqualTo(context == ProviderName.SqlServer2000 ?
"<root><element strattr=\"strvalue\" intattr=\"12345\"/></root>" :
"<root><element strattr=\"strvalue\" intattr=\"12345\" /></root>"));
Assert.That(conn.Execute<byte[]>("SELECT timestampDataType FROM AllTypes WHERE ID = 1").Length, Is.EqualTo(8));
}
}
[Test]
public void TestDataTypes2([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
using (var conn = new DataConnection(context))
{
Assert.That(TestType<DateTime?> (conn, "dateDataType", DataType.Date, "AllTypes2"), Is.EqualTo(new DateTime(2012, 12, 12)));
Assert.That(TestType<DateTimeOffset?>(conn, "datetimeoffsetDataType", DataType.DateTimeOffset, "AllTypes2"), Is.EqualTo(new DateTimeOffset(2012, 12, 12, 12, 12, 12, 12, new TimeSpan(5, 0, 0))));
Assert.That(TestType<DateTime?> (conn, "datetime2DataType", DataType.DateTime2, "AllTypes2"), Is.EqualTo(new DateTime(2012, 12, 12, 12, 12, 12, 12)));
Assert.That(TestType<TimeSpan?> (conn, "timeDataType", DataType.Time, "AllTypes2"), Is.EqualTo(new TimeSpan(0, 12, 12, 12, 12)));
#if !NETSTANDARD1_6
Assert.That(TestType<SqlHierarchyId?>(conn, "hierarchyidDataType", tableName:"AllTypes2"), Is.EqualTo(SqlHierarchyId.Parse("/1/3/")));
Assert.That(TestType<SqlGeography> (conn, "geographyDataType", skipPass:true, tableName:"AllTypes2").ToString(), Is.EqualTo("LINESTRING (-122.36 47.656, -122.343 47.656)"));
Assert.That(TestType<SqlGeometry> (conn, "geometryDataType", skipPass:true, tableName:"AllTypes2").ToString(), Is.EqualTo("LINESTRING (100 100, 20 180, 180 180)"));
#endif
}
}
static void TestNumeric<T>(DataConnection conn, T expectedValue, DataType dataType, string skip = "")
{
var skipTypes = skip.Split(' ');
foreach (var sqlType in new[]
{
"bigint",
"bit",
"decimal",
"decimal(38)",
"int",
"money",
"numeric",
"numeric(38)",
"smallint",
"smallmoney",
"tinyint",
"float",
"real"
}.Except(skipTypes))
{
var sqlValue = expectedValue is bool ? (bool)(object)expectedValue? 1 : 0 : (object)expectedValue;
var sql = string.Format(CultureInfo.InvariantCulture, "SELECT Cast({0} as {1})", sqlValue ?? "NULL", sqlType);
Debug.WriteLine(sql + " -> " + typeof(T));
Assert.That(conn.Execute<T>(sql), Is.EqualTo(expectedValue));
}
Debug.WriteLine("{0} -> DataType.{1}", typeof(T), dataType);
Assert.That(conn.Execute<T>("SELECT @p", new DataParameter { Name = "p", DataType = dataType, Value = expectedValue }), Is.EqualTo(expectedValue));
Debug.WriteLine("{0} -> auto", typeof(T));
Assert.That(conn.Execute<T>("SELECT @p", new DataParameter { Name = "p", Value = expectedValue }), Is.EqualTo(expectedValue));
Debug.WriteLine("{0} -> new", typeof(T));
Assert.That(conn.Execute<T>("SELECT @p", new { p = expectedValue }), Is.EqualTo(expectedValue));
}
static void TestSimple<T>(DataConnection conn, T expectedValue, DataType dataType)
where T : struct
{
TestNumeric<T> (conn, expectedValue, dataType);
TestNumeric<T?>(conn, expectedValue, dataType);
TestNumeric<T?>(conn, (T?)null, dataType);
}
[Test]
public void TestNumerics([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
TestSimple<bool> (conn, true, DataType.Boolean);
TestSimple<sbyte> (conn, 1, DataType.SByte);
TestSimple<short> (conn, 1, DataType.Int16);
TestSimple<int> (conn, 1, DataType.Int32);
TestSimple<long> (conn, 1L, DataType.Int64);
TestSimple<byte> (conn, 1, DataType.Byte);
TestSimple<ushort> (conn, 1, DataType.UInt16);
TestSimple<uint> (conn, 1u, DataType.UInt32);
TestSimple<ulong> (conn, 1ul, DataType.UInt64);
TestSimple<float> (conn, 1, DataType.Single);
TestSimple<double> (conn, 1d, DataType.Double);
TestSimple<decimal>(conn, 1m, DataType.Decimal);
TestSimple<decimal>(conn, 1m, DataType.VarNumeric);
TestSimple<decimal>(conn, 1m, DataType.Money);
TestSimple<decimal>(conn, 1m, DataType.SmallMoney);
TestNumeric(conn, sbyte.MinValue, DataType.SByte, "bit tinyint");
TestNumeric(conn, sbyte.MaxValue, DataType.SByte, "bit");
TestNumeric(conn, short.MinValue, DataType.Int16, "bit tinyint");
TestNumeric(conn, short.MaxValue, DataType.Int16, "bit tinyint");
TestNumeric(conn, int.MinValue, DataType.Int32, "bit smallint smallmoney tinyint");
TestNumeric(conn, int.MaxValue, DataType.Int32, "bit smallint smallmoney tinyint real");
TestNumeric(conn, long.MinValue, DataType.Int64, "bit decimal int money numeric smallint smallmoney tinyint");
TestNumeric(conn, long.MaxValue, DataType.Int64, "bit decimal int money numeric smallint smallmoney tinyint float real");
TestNumeric(conn, byte.MaxValue, DataType.Byte, "bit");
TestNumeric(conn, ushort.MaxValue, DataType.UInt16, "bit smallint tinyint");
TestNumeric(conn, uint.MaxValue, DataType.UInt32, "bit int smallint smallmoney tinyint real");
TestNumeric(conn, ulong.MaxValue, DataType.UInt64, "bigint bit decimal int money numeric smallint smallmoney tinyint float real");
TestNumeric(conn, -3.40282306E+38f, DataType.Single, "bigint bit decimal decimal(38) int money numeric numeric(38) smallint smallmoney tinyint");
TestNumeric(conn, 3.40282306E+38f, DataType.Single, "bigint bit decimal decimal(38) int money numeric numeric(38) smallint smallmoney tinyint");
TestNumeric(conn, -1.79E+308d, DataType.Double, "bigint bit decimal decimal(38) int money numeric numeric(38) smallint smallmoney tinyint real");
TestNumeric(conn, 1.79E+308d, DataType.Double, "bigint bit decimal decimal(38) int money numeric numeric(38) smallint smallmoney tinyint real");
TestNumeric(conn, decimal.MinValue, DataType.Decimal, "bigint bit decimal int money numeric smallint smallmoney tinyint float real");
TestNumeric(conn, decimal.MaxValue, DataType.Decimal, "bigint bit decimal int money numeric smallint smallmoney tinyint float real");
TestNumeric(conn, decimal.MinValue, DataType.VarNumeric, "bigint bit decimal int money numeric smallint smallmoney tinyint float real");
TestNumeric(conn, decimal.MaxValue, DataType.VarNumeric, "bigint bit decimal int money numeric smallint smallmoney tinyint float real");
TestNumeric(conn, -922337203685477m, DataType.Money, "bit int smallint smallmoney tinyint real");
TestNumeric(conn, +922337203685477m, DataType.Money, "bit int smallint smallmoney tinyint real");
TestNumeric(conn, -214748m, DataType.SmallMoney, "bit smallint tinyint");
TestNumeric(conn, +214748m, DataType.SmallMoney, "bit smallint tinyint");
}
}
[Test]
public void TestDate([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
using (var conn = new DataConnection(context))
{
var dateTime = new DateTime(2012, 12, 12);
Assert.That(conn.Execute<DateTime> ("SELECT Cast('2012-12-12' as date)"), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime?>("SELECT Cast('2012-12-12' as date)"), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime> ("SELECT @p", DataParameter.Date("p", dateTime)), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime?>("SELECT @p", new DataParameter("p", dateTime, DataType.Date)), Is.EqualTo(dateTime));
}
}
[Test]
public void TestSmallDateTime([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
var dateTime = new DateTime(2012, 12, 12, 12, 12, 00);
Assert.That(conn.Execute<DateTime> ("SELECT Cast('2012-12-12 12:12:00' as smalldatetime)"), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime?>("SELECT Cast('2012-12-12 12:12:00' as smalldatetime)"), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime> ("SELECT @p", DataParameter.SmallDateTime("p", dateTime)), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime?>("SELECT @p", new DataParameter("p", dateTime, DataType.SmallDateTime)), Is.EqualTo(dateTime));
}
}
[Test]
public void TestDateTime([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
var dateTime = new DateTime(2012, 12, 12, 12, 12, 12);
Assert.That(conn.Execute<DateTime> ("SELECT Cast('2012-12-12 12:12:12' as datetime)"), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime?>("SELECT Cast('2012-12-12 12:12:12' as datetime)"), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime> ("SELECT @p", DataParameter.DateTime("p", dateTime)), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime?>("SELECT @p", new DataParameter("p", dateTime)), Is.EqualTo(dateTime));
Assert.That(conn.Execute<DateTime?>("SELECT @p", new DataParameter("p", dateTime, DataType.DateTime)), Is.EqualTo(dateTime));
}
}
[Test]
public void TestDateTime2([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
using (var conn = new DataConnection(context))
{
var dateTime2 = new DateTime(2012, 12, 12, 12, 12, 12, 12);
Assert.That(conn.Execute<DateTime> ("SELECT Cast('2012-12-12 12:12:12.012' as datetime2)"), Is.EqualTo(dateTime2));
Assert.That(conn.Execute<DateTime?>("SELECT Cast('2012-12-12 12:12:12.012' as datetime2)"), Is.EqualTo(dateTime2));
Assert.That(conn.Execute<DateTime> ("SELECT @p", DataParameter.DateTime2("p", dateTime2)), Is.EqualTo(dateTime2));
Assert.That(conn.Execute<DateTime> ("SELECT @p", DataParameter.Create ("p", dateTime2)), Is.EqualTo(dateTime2));
Assert.That(conn.Execute<DateTime?>("SELECT @p", new DataParameter("p", dateTime2, DataType.DateTime2)), Is.EqualTo(dateTime2));
}
}
[Test]
public void TestDateTimeOffset([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
using (var conn = new DataConnection(context))
{
var dto = new DateTimeOffset(2012, 12, 12, 12, 12, 12, 12, new TimeSpan( 5, 0, 0));
var lto = new DateTimeOffset(2012, 12, 12, 13, 12, 12, 12, new TimeSpan(-4, 0, 0));
Assert.That(conn.Execute<DateTimeOffset>(
"SELECT Cast('2012-12-12 12:12:12.012' as datetime2)"),
Is.EqualTo(new DateTimeOffset(2012, 12, 12, 12, 12, 12, 12, TimeZoneInfo.Local.GetUtcOffset(new DateTime(2012, 12, 12, 12, 12, 12)))));
Assert.That(conn.Execute<DateTimeOffset?>(
"SELECT Cast('2012-12-12 12:12:12.012' as datetime2)"),
Is.EqualTo(new DateTimeOffset(2012, 12, 12, 12, 12, 12, 12, TimeZoneInfo.Local.GetUtcOffset(new DateTime(2012, 12, 12, 12, 12, 12)))));
Assert.That(conn.Execute<DateTime>(
"SELECT Cast('2012-12-12 13:12:12.012 -04:00' as datetimeoffset)"),
Is.EqualTo(lto.LocalDateTime));
Assert.That(conn.Execute<DateTime?>(
"SELECT Cast('2012-12-12 13:12:12.012 -04:00' as datetimeoffset)"),
Is.EqualTo(lto.LocalDateTime));
Assert.That(conn.Execute<DateTimeOffset>(
"SELECT Cast('2012-12-12 12:12:12.012 +05:00' as datetimeoffset)"),
Is.EqualTo(dto));
Assert.That(conn.Execute<DateTimeOffset?>(
"SELECT Cast('2012-12-12 12:12:12.012 +05:00' as datetimeoffset)"),
Is.EqualTo(dto));
Assert.That(conn.Execute<DateTime>(
"SELECT Cast(NULL as datetimeoffset)"),
Is.EqualTo(default(DateTime)));
Assert.That(conn.Execute<DateTime?>(
"SELECT Cast(NULL as datetimeoffset)"),
Is.EqualTo(default(DateTime?)));
Assert.That(conn.Execute<DateTimeOffset> ("SELECT @p", DataParameter.DateTimeOffset("p", dto)), Is.EqualTo(dto));
Assert.That(conn.Execute<DateTimeOffset> ("SELECT @p", DataParameter.Create ("p", dto)), Is.EqualTo(dto));
Assert.That(conn.Execute<DateTimeOffset?>("SELECT @p", new DataParameter("p", dto)), Is.EqualTo(dto));
Assert.That(conn.Execute<DateTimeOffset?>("SELECT @p", new DataParameter("p", dto, DataType.DateTimeOffset)), Is.EqualTo(dto));
}
}
[Test]
public void TestTimeSpan([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
using (var conn = new DataConnection(context))
{
var time = new TimeSpan(12, 12, 12);
Assert.That(conn.Execute<TimeSpan> ("SELECT Cast('12:12:12' as time)"), Is.EqualTo(time));
Assert.That(conn.Execute<TimeSpan?>("SELECT Cast('12:12:12' as time)"), Is.EqualTo(time));
Assert.That(conn.Execute<TimeSpan> ("SELECT @p", DataParameter.Time ("p", time)), Is.EqualTo(time));
Assert.That(conn.Execute<TimeSpan> ("SELECT @p", DataParameter.Create("p", time)), Is.EqualTo(time));
Assert.That(conn.Execute<TimeSpan?>("SELECT @p", new DataParameter("p", time, DataType.Time)), Is.EqualTo(time));
Assert.That(conn.Execute<TimeSpan?>("SELECT @p", new DataParameter("p", time)), Is.EqualTo(time));
}
}
[Test]
public void TestChar([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
Assert.That(conn.Execute<char> ("SELECT Cast('1' as char)"), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast('1' as char)"), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT Cast('1' as char(1))"), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast('1' as char(1))"), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT Cast('1' as varchar)"), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast('1' as varchar)"), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT Cast('1' as varchar(20))"), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast('1' as varchar(20))"), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT Cast('1' as nchar)"), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast('1' as nchar)"), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT Cast('1' as nchar(20))"), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast('1' as nchar(20))"), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT Cast('1' as nvarchar)"), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast('1' as nvarchar)"), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT Cast('1' as nvarchar(20))"), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast('1' as nvarchar(20))"), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT @p", DataParameter.Char("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT @p", DataParameter.Char("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT Cast(@p as char)", DataParameter.Char("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast(@p as char)", DataParameter.Char("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT Cast(@p as char(1))", DataParameter.Char("@p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT Cast(@p as char(1))", DataParameter.Char("@p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT @p", DataParameter.VarChar ("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT @p", DataParameter.VarChar ("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT @p", DataParameter.NChar ("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT @p", DataParameter.NChar ("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT @p", DataParameter.NVarChar("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT @p", DataParameter.NVarChar("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT @p", DataParameter.Create ("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT @p", DataParameter.Create ("p", '1')), Is.EqualTo('1'));
Assert.That(conn.Execute<char> ("SELECT @p", new DataParameter { Name = "p", Value = '1' }), Is.EqualTo('1'));
Assert.That(conn.Execute<char?>("SELECT @p", new DataParameter { Name = "p", Value = '1' }), Is.EqualTo('1'));
}
}
[Test]
public void TestString([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
Assert.That(conn.Execute<string>("SELECT Cast('12345' as char)"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast('12345' as char(20))"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(NULL as char(20))"), Is.Null);
Assert.That(conn.Execute<string>("SELECT Cast('12345' as varchar)"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast('12345' as varchar(20))"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(NULL as varchar(20))"), Is.Null);
var isScCollation = conn.Execute<int>("SELECT COUNT(*) FROM sys.Databases WHERE database_id = DB_ID() AND collation_name LIKE '%_SC'") > 0;
if (isScCollation)
{
// explicit collation set for legacy text types as they doesn't support *_SC collations
Assert.That(conn.Execute<string>("SELECT Cast('12345' COLLATE Latin1_General_CI_AS as text)"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(CAST(NULL as nvarchar) COLLATE Latin1_General_CI_AS as text)"), Is.Null);
}
else
{
Assert.That(conn.Execute<string>("SELECT Cast('12345' as text)"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(NULL as text)"), Is.Null);
}
if (context != ProviderName.SqlServer2000)
{
Assert.That(conn.Execute<string>("SELECT Cast('12345' as varchar(max))"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(NULL as varchar(max))"), Is.Null);
}
Assert.That(conn.Execute<string>("SELECT Cast('12345' as nchar)"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast('12345' as nchar(20))"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(NULL as nchar(20))"), Is.Null);
Assert.That(conn.Execute<string>("SELECT Cast('12345' as nvarchar)"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast('12345' as nvarchar(20))"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(NULL as nvarchar(20))"), Is.Null);
if (isScCollation)
{
// explicit collation set for legacy text types as they doesn't support *_SC collations
Assert.That(conn.Execute<string>("SELECT Cast('12345' COLLATE Latin1_General_CI_AS as ntext)"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(CAST(NULL as nvarchar) COLLATE Latin1_General_CI_AS as ntext)"), Is.Null);
}
else
{
Assert.That(conn.Execute<string>("SELECT Cast('12345' as ntext)"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(NULL as ntext)"), Is.Null);
}
if (context != ProviderName.SqlServer2000)
{
Assert.That(conn.Execute<string>("SELECT Cast('12345' as nvarchar(max))"), Is.EqualTo("12345"));
Assert.That(conn.Execute<string>("SELECT Cast(NULL as nvarchar(max))"), Is.Null);
}
Assert.That(conn.Execute<string>("SELECT @p", DataParameter.Char ("p", "123")), Is.EqualTo("123"));
Assert.That(conn.Execute<string>("SELECT @p", DataParameter.VarChar ("p", "123")), Is.EqualTo("123"));
Assert.That(conn.Execute<string>("SELECT @p", DataParameter.Text ("p", "123")), Is.EqualTo("123"));
Assert.That(conn.Execute<string>("SELECT @p", DataParameter.NChar ("p", "123")), Is.EqualTo("123"));
Assert.That(conn.Execute<string>("SELECT @p", DataParameter.NVarChar("p", "123")), Is.EqualTo("123"));
Assert.That(conn.Execute<string>("SELECT @p", DataParameter.NText ("p", "123")), Is.EqualTo("123"));
Assert.That(conn.Execute<string>("SELECT @p", DataParameter.Create ("p", "123")), Is.EqualTo("123"));
Assert.That(conn.Execute<string>("SELECT @p", DataParameter.Create("p", (string)null)), Is.EqualTo(null));
Assert.That(conn.Execute<string>("SELECT @p", new DataParameter { Name = "p", Value = "1" }), Is.EqualTo("1"));
}
}
[Test]
public void TestBinary([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
var arr1 = new byte[] { 48, 57 };
var arr2 = new byte[] { 0, 0, 48, 57 };
using (var conn = new DataConnection(context))
{
Assert.That(conn.Execute<byte[]>("SELECT Cast(12345 as binary(2))"), Is.EqualTo( arr1));
Assert.That(conn.Execute<Binary>("SELECT Cast(12345 as binary(4))"), Is.EqualTo(new Binary(arr2)));
Assert.That(conn.Execute<byte[]>("SELECT Cast(12345 as varbinary(2))"), Is.EqualTo( arr1));
Assert.That(conn.Execute<Binary>("SELECT Cast(12345 as varbinary(4))"), Is.EqualTo(new Binary(arr2)));
Assert.That(conn.Execute<byte[]>("SELECT Cast(NULL as image)"), Is.EqualTo(null));
Assert.That(conn.Execute<byte[]>(
context == ProviderName.SqlServer2000 ? "SELECT Cast(12345 as varbinary(4000))" : "SELECT Cast(12345 as varbinary(max))"),
Is.EqualTo(arr2));
Assert.That(conn.Execute<byte[]>("SELECT @p", DataParameter.Binary ("p", arr1)), Is.EqualTo(arr1));
Assert.That(conn.Execute<byte[]>("SELECT @p", DataParameter.VarBinary("p", arr1)), Is.EqualTo(arr1));
Assert.That(conn.Execute<byte[]>("SELECT @p", DataParameter.Create ("p", arr1)), Is.EqualTo(arr1));
Assert.That(conn.Execute<byte[]>("SELECT @p", DataParameter.VarBinary("p", null)), Is.EqualTo(null));
Assert.That(conn.Execute<byte[]>("SELECT Cast(@p as binary(1))", DataParameter.Binary("p", new byte[0])), Is.EqualTo(new byte[] {0}));
Assert.That(conn.Execute<byte[]>("SELECT @p", DataParameter.Binary ("p", new byte[0])), Is.EqualTo(new byte[8000]));
Assert.That(conn.Execute<byte[]>("SELECT @p", DataParameter.VarBinary("p", new byte[0])), Is.EqualTo(new byte[0]));
Assert.That(conn.Execute<byte[]>("SELECT @p", DataParameter.Image ("p", new byte[0])), Is.EqualTo(new byte[0]));
Assert.That(conn.Execute<byte[]>("SELECT @p", new DataParameter { Name = "p", Value = arr1 }), Is.EqualTo(arr1));
Assert.That(conn.Execute<byte[]>("SELECT @p", DataParameter.Create ("p", new Binary(arr1))), Is.EqualTo(arr1));
Assert.That(conn.Execute<byte[]>("SELECT @p", new DataParameter("p", new Binary(arr1))), Is.EqualTo(arr1));
}
}
[Test]
public void TestSqlTypes([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
var arr = new byte[] { 48, 57 };
Assert.That(conn.Execute<SqlBinary> ("SELECT Cast(12345 as binary(2))").Value, Is.EqualTo(arr));
Assert.That(conn.Execute<SqlBoolean>("SELECT Cast(1 as bit)"). Value, Is.EqualTo(true));
Assert.That(conn.Execute<SqlByte> ("SELECT Cast(1 as tinyint)"). Value, Is.EqualTo((byte)1));
Assert.That(conn.Execute<SqlDecimal>("SELECT Cast(1 as decimal)"). Value, Is.EqualTo(1));
Assert.That(conn.Execute<SqlDouble> ("SELECT Cast(1 as float)"). Value, Is.EqualTo(1.0));
Assert.That(conn.Execute<SqlInt16> ("SELECT Cast(1 as smallint)"). Value, Is.EqualTo((short)1));
Assert.That(conn.Execute<SqlInt32> ("SELECT Cast(1 as int)"). Value, Is.EqualTo((int)1));
Assert.That(conn.Execute<SqlInt64> ("SELECT Cast(1 as bigint)"). Value, Is.EqualTo(1L));
Assert.That(conn.Execute<SqlMoney> ("SELECT Cast(1 as money)"). Value, Is.EqualTo(1m));
Assert.That(conn.Execute<SqlSingle> ("SELECT Cast(1 as real)"). Value, Is.EqualTo((float)1));
Assert.That(conn.Execute<SqlString> ("SELECT Cast('12345' as char(6))"). Value, Is.EqualTo("12345 "));
if (context != ProviderName.SqlServer2000)
Assert.That(conn.Execute<SqlXml>("SELECT Cast('<xml/>' as xml)"). Value, Is.EqualTo("<xml />"));
Assert.That(
conn.Execute<SqlDateTime>("SELECT Cast('2012-12-12 12:12:12' as datetime)").Value,
Is.EqualTo(new DateTime(2012, 12, 12, 12, 12, 12)));
Assert.That(
conn.Execute<SqlGuid>("SELECT Cast('6F9619FF-8B86-D011-B42D-00C04FC964FF' as uniqueidentifier)").Value,
Is.EqualTo(new Guid("6F9619FF-8B86-D011-B42D-00C04FC964FF")));
Assert.That(conn.Execute<SqlBinary> ("SELECT @p", new DataParameter("p", new SqlBinary(arr))). Value, Is.EqualTo(arr));
Assert.That(conn.Execute<SqlBinary> ("SELECT @p", new DataParameter("p", new SqlBinary(arr), DataType.VarBinary)).Value, Is.EqualTo(arr));
Assert.That(conn.Execute<SqlBoolean>("SELECT @p", new DataParameter("p", true)). Value, Is.EqualTo(true));
Assert.That(conn.Execute<SqlBoolean>("SELECT @p", new DataParameter("p", true, DataType.Boolean)).Value, Is.EqualTo(true));
if (context != ProviderName.SqlServer2000)
{
var conv = conn.MappingSchema.GetConverter<string,SqlXml>();
Assert.That(conn.Execute<SqlXml>("SELECT @p", new DataParameter("p", conv("<xml/>"))). Value, Is.EqualTo("<xml />"));
Assert.That(conn.Execute<SqlXml>("SELECT @p", new DataParameter("p", conv("<xml/>"), DataType.Xml)).Value, Is.EqualTo("<xml />"));
}
}
}
[Test]
public void TestGuid([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
Assert.That(
conn.Execute<Guid>("SELECT Cast('6F9619FF-8B86-D011-B42D-00C04FC964FF' as uniqueidentifier)"),
Is.EqualTo(new Guid("6F9619FF-8B86-D011-B42D-00C04FC964FF")));
Assert.That(
conn.Execute<Guid?>("SELECT Cast('6F9619FF-8B86-D011-B42D-00C04FC964FF' as uniqueidentifier)"),
Is.EqualTo(new Guid("6F9619FF-8B86-D011-B42D-00C04FC964FF")));
var guid = Guid.NewGuid();
Assert.That(conn.Execute<Guid>("SELECT @p", DataParameter.Create("p", guid)), Is.EqualTo(guid));
Assert.That(conn.Execute<Guid>("SELECT @p", new DataParameter { Name = "p", Value = guid }), Is.EqualTo(guid));
}
}
[Test]
public void TestTimestamp([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
var arr = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1 };
Assert.That(conn.Execute<byte[]>("SELECT Cast(1 as timestamp)"), Is.EqualTo(arr));
Assert.That(conn.Execute<byte[]>("SELECT Cast(1 as rowversion)"), Is.EqualTo(arr));
Assert.That(conn.Execute<byte[]>("SELECT @p", DataParameter.Timestamp("p", arr)), Is.EqualTo(arr));
Assert.That(conn.Execute<byte[]>("SELECT @p", new DataParameter("p", arr, DataType.Timestamp)), Is.EqualTo(arr));
}
}
[Test]
public void TestSqlVariant([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
Assert.That(conn.Execute<object>("SELECT Cast(1 as sql_variant)"), Is.EqualTo(1));
Assert.That(conn.Execute<int> ("SELECT Cast(1 as sql_variant)"), Is.EqualTo(1));
Assert.That(conn.Execute<int?> ("SELECT Cast(1 as sql_variant)"), Is.EqualTo(1));
Assert.That(conn.Execute<string>("SELECT Cast(1 as sql_variant)"), Is.EqualTo("1"));
Assert.That(conn.Execute<string>("SELECT @p", DataParameter.Variant("p", 1)), Is.EqualTo("1"));
}
}
#if !NETSTANDARD1_6
[Test]
public void TestHierarchyID([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
using (var conn = new DataConnection(context))
{
var id = SqlHierarchyId.Parse("/1/3/");
Assert.That(conn.Execute<SqlHierarchyId> ("SELECT Cast('/1/3/' as hierarchyid)"), Is.EqualTo(id));
Assert.That(conn.Execute<SqlHierarchyId?>("SELECT Cast('/1/3/' as hierarchyid)"), Is.EqualTo(id));
Assert.That(conn.Execute<SqlHierarchyId> ("SELECT Cast(NULL as hierarchyid)"), Is.EqualTo(SqlHierarchyId.Null));
Assert.That(conn.Execute<SqlHierarchyId?>("SELECT Cast(NULL as hierarchyid)"), Is.EqualTo(null));
Assert.That(conn.Execute<SqlHierarchyId>("SELECT @p", new DataParameter("p", id)), Is.EqualTo(id));
}
}
[Test]
public void TestGeometry([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
using (var conn = new DataConnection(context))
{
var id = SqlGeometry.Parse("LINESTRING (100 100, 20 180, 180 180)");
Assert.That(conn.Execute<SqlGeometry>("SELECT Cast(geometry::STGeomFromText('LINESTRING (100 100, 20 180, 180 180)', 0) as geometry)")
.ToString(), Is.EqualTo(id.ToString()));
Assert.That(conn.Execute<SqlGeometry>("SELECT Cast(NULL as geometry)").ToString(),
Is.EqualTo(SqlGeometry.Null.ToString()));
Assert.That(conn.Execute<SqlGeometry>("SELECT @p", new DataParameter("p", id)).ToString(), Is.EqualTo(id.ToString()));
Assert.That(conn.Execute<SqlGeometry>("SELECT @p", new DataParameter("p", id, DataType.Udt)).ToString(), Is.EqualTo(id.ToString()));
Assert.That(conn.Execute<SqlGeometry>("SELECT @p", DataParameter.Udt("p", id)).ToString(), Is.EqualTo(id.ToString()));
}
}
[Test]
public void TestGeography([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
using (var conn = new DataConnection(context))
{
var id = SqlGeography.Parse("LINESTRING (-122.36 47.656, -122.343 47.656)");
Assert.That(conn.Execute<SqlGeography>("SELECT Cast(geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656)', 4326) as geography)")
.ToString(), Is.EqualTo(id.ToString()));
Assert.That(conn.Execute<SqlGeography>("SELECT Cast(NULL as geography)").ToString(),
Is.EqualTo(SqlGeography.Null.ToString()));
Assert.That(conn.Execute<SqlGeography>("SELECT @p", new DataParameter("p", id)).ToString(), Is.EqualTo(id.ToString()));
Assert.That(conn.Execute<SqlGeography>("SELECT @p", new DataParameter("p", id, DataType.Udt)).ToString(), Is.EqualTo(id.ToString()));
Assert.That(conn.Execute<SqlGeography>("SELECT @p", DataParameter.Udt("p", id)).ToString(), Is.EqualTo(id.ToString()));
}
}
#endif
[Test]
public void TestXml([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
if (context != ProviderName.SqlServer2000)
{
Assert.That(conn.Execute<string> ("SELECT Cast('<xml/>' as xml)"), Is.EqualTo("<xml/>").Or.EqualTo("<xml />"));
Assert.That(conn.Execute<XDocument> ("SELECT Cast('<xml/>' as xml)").ToString(), Is.EqualTo("<xml/>").Or.EqualTo("<xml />"));
Assert.That(conn.Execute<XmlDocument>("SELECT Cast('<xml/>' as xml)").InnerXml, Is.EqualTo("<xml/>").Or.EqualTo("<xml />"));
}
var xdoc = XDocument.Parse("<xml/>");
var xml = Convert<string,XmlDocument>.Lambda("<xml/>");
Assert.That(conn.Execute<string> ("SELECT @p", DataParameter.Xml("p", "<xml/>")), Is.EqualTo("<xml/>").Or.EqualTo("<xml />"));
Assert.That(conn.Execute<XDocument> ("SELECT @p", DataParameter.Xml("p", xdoc)).ToString(), Is.EqualTo("<xml/>").Or.EqualTo("<xml />"));
Assert.That(conn.Execute<XmlDocument>("SELECT @p", DataParameter.Xml("p", xml)). InnerXml, Is.EqualTo("<xml/>").Or.EqualTo("<xml />"));
Assert.That(conn.Execute<XDocument> ("SELECT @p", new DataParameter("p", xdoc)).ToString(), Is.EqualTo("<xml/>").Or.EqualTo("<xml />"));
Assert.That(conn.Execute<XDocument> ("SELECT @p", new DataParameter("p", xml)). ToString(), Is.EqualTo("<xml/>").Or.EqualTo("<xml />"));
}
}
enum TestEnum
{
[MapValue("A")] AA,
[MapValue(ProviderName.SqlServer2008, "C")]
[MapValue("B")] BB,
}
[Test]
public void TestEnum1([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
Assert.That(conn.Execute<TestEnum> ("SELECT 'A'"), Is.EqualTo(TestEnum.AA));
Assert.That(conn.Execute<TestEnum?>("SELECT 'A'"), Is.EqualTo(TestEnum.AA));
var sql = context == ProviderName.SqlServer2008 ? "SELECT 'C'" : "SELECT 'B'";
Assert.That(conn.Execute<TestEnum> (sql), Is.EqualTo(TestEnum.BB));
Assert.That(conn.Execute<TestEnum?>(sql), Is.EqualTo(TestEnum.BB));
}
}
[Test]
public void TestEnum2([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var conn = new DataConnection(context))
{
Assert.That(conn.Execute<string>("SELECT @p", new { p = TestEnum.AA }), Is.EqualTo("A"));
Assert.That(conn.Execute<string>("SELECT @p", new { p = (TestEnum?)TestEnum.BB }),
Is.EqualTo(context == ProviderName.SqlServer2008 ? "C" : "B"));
Assert.That(conn.Execute<string>("SELECT @p", new { p = ConvertTo<string>.From((TestEnum?)TestEnum.AA) }), Is.EqualTo("A"));
Assert.That(conn.Execute<string>("SELECT @p", new { p = ConvertTo<string>.From(TestEnum.AA) }), Is.EqualTo("A"));
Assert.That(conn.Execute<string>("SELECT @p", new { p = conn.MappingSchema.GetConverter<TestEnum?,string>()(TestEnum.AA) }), Is.EqualTo("A"));
}
}
[Table(Schema = "dbo", Name = "LinqDataTypes")]
class DataTypes
{
[Column] public int ID;
[Column] public decimal MoneyValue;
[Column] public DateTime DateTimeValue;
[Column] public bool BoolValue;
[Column] public Guid GuidValue;
[Column] public Binary BinaryValue;
[Column] public short SmallIntValue;
}
[Test]
public void BulkCopyLinqTypesMultipleRows([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db = new DataConnection(context))
{
db.BulkCopy(
new BulkCopyOptions
{
BulkCopyType = BulkCopyType.MultipleRows,
RowsCopiedCallback = copied => Debug.WriteLine(copied.RowsCopied)
},
Enumerable.Range(0, 10).Select(n =>
new DataTypes
{
ID = 4000 + n,
MoneyValue = 1000m + n,
DateTimeValue = new DateTime(2001, 1, 11, 1, 11, 21, 100),
BoolValue = true,
GuidValue = Guid.NewGuid(),
SmallIntValue = (short)n
}
));
db.GetTable<DataTypes>().Delete(p => p.ID >= 4000);
}
}
[Test]
public void BulkCopyLinqTypesProviderSpecific([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db = new DataConnection(context))
{
db.BulkCopy(
new BulkCopyOptions
{
BulkCopyType = BulkCopyType.ProviderSpecific,
RowsCopiedCallback = copied => Debug.WriteLine(copied.RowsCopied)
},
Enumerable.Range(0, 10).Select(n =>
new DataTypes
{
ID = 4000 + n,
MoneyValue = 1000m + n,
DateTimeValue = new DateTime(2001, 1, 11, 1, 11, 21, 100),
BoolValue = true,
GuidValue = Guid.NewGuid(),
SmallIntValue = (short)n
}
));
db.GetTable<DataTypes>().Delete(p => p.ID >= 4000);
}
}
[Table]
class AllTypes
{
[Identity]
[Column(DataType=DataType.Int32), NotNull] public int ID { get; set; }
[Column(DataType=DataType.Int64), Nullable] public long? bigintDataType { get; set; }
[Column(DataType=DataType.Decimal), Nullable] public decimal? numericDataType { get; set; }
[Column(DataType=DataType.Boolean), Nullable] public bool? bitDataType { get; set; }
[Column(DataType=DataType.Int16), Nullable] public short? smallintDataType { get; set; }
[Column(DataType=DataType.Decimal), Nullable] public decimal? decimalDataType { get; set; }
[Column(DataType=DataType.SmallMoney), Nullable] public decimal? smallmoneyDataType { get; set; }
[Column(DataType=DataType.Int32), Nullable] public int? intDataType { get; set; }
[Column(DataType=DataType.Byte), Nullable] public byte? tinyintDataType { get; set; }
[Column(DataType=DataType.Money), Nullable] public decimal? moneyDataType { get; set; }
[Column(DataType=DataType.Double), Nullable] public double? floatDataType { get; set; }
[Column(DataType=DataType.Single), Nullable] public float? realDataType { get; set; }
[Column(DataType=DataType.DateTime), Nullable] public DateTime? datetimeDataType { get; set; }
[Column(DataType=DataType.SmallDateTime), Nullable] public DateTime? smalldatetimeDataType { get; set; }
[Column(DataType=DataType.Char, Length=1), Nullable] public char? charDataType { get; set; }
[Column(DataType=DataType.VarChar, Length=20), Nullable] public string varcharDataType { get; set; }
[Column(DataType=DataType.Text), Nullable] public string textDataType { get; set; }
[Column(DataType=DataType.NChar, Length=20), Nullable] public string ncharDataType { get; set; }
[Column(DataType=DataType.NVarChar, Length=20), Nullable] public string nvarcharDataType { get; set; }
[Column(DataType=DataType.NText), Nullable] public string ntextDataType { get; set; }
[Column(DataType=DataType.Binary), Nullable] public byte[] binaryDataType { get; set; }
[Column(DataType=DataType.VarBinary), Nullable] public byte[] varbinaryDataType { get; set; }
[Column(DataType=DataType.Image), Nullable] public byte[] imageDataType { get; set; }
[Column(DataType=DataType.Timestamp,SkipOnInsert=true), Nullable] public byte[] timestampDataType { get; set; }
[Column(DataType=DataType.Guid), Nullable] public Guid? uniqueidentifierDataType { get; set; }
[Column(DataType=DataType.Variant), Nullable] public object sql_variantDataType { get; set; }
[Column(DataType=DataType.NVarChar, Length=int.MaxValue), Nullable] public string nvarchar_max_DataType { get; set; }
[Column(DataType=DataType.VarChar, Length=int.MaxValue), Nullable] public string varchar_max_DataType { get; set; }
[Column(DataType=DataType.VarBinary, Length=int.MaxValue), Nullable] public byte[] varbinary_max_DataType { get; set; }
[Column(DataType=DataType.Xml), Nullable] public string xmlDataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTime2), Nullable] public DateTime? datetime2DataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTimeOffset), Nullable] public DateTimeOffset? datetimeoffsetDataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTimeOffset,Scale=0), Nullable] public DateTimeOffset? datetimeoffset0DataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTimeOffset,Scale=1), Nullable] public DateTimeOffset? datetimeoffset1DataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTimeOffset,Scale=2), Nullable] public DateTimeOffset? datetimeoffset2DataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTimeOffset,Scale=3), Nullable] public DateTimeOffset? datetimeoffset3DataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTimeOffset,Scale=4), Nullable] public DateTimeOffset? datetimeoffset4DataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTimeOffset,Scale=5), Nullable] public DateTimeOffset? datetimeoffset5DataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTimeOffset,Scale=6), Nullable] public DateTimeOffset? datetimeoffset6DataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.DateTimeOffset,Scale=7), Nullable] public DateTimeOffset? datetimeoffset7DataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.Date), Nullable] public DateTime? dateDataType { get; set; }
[Column(Configuration=ProviderName.SqlServer2000, DataType=DataType.VarChar)]
[Column(Configuration=ProviderName.SqlServer2005, DataType=DataType.VarChar)]
[Column(DataType=DataType.Time), Nullable] public TimeSpan? timeDataType { get; set; }
}
static readonly AllTypes[] _allTypeses =
{
#region data
new AllTypes
{
ID = 700,
bigintDataType = 1,
numericDataType = 1.1m,
bitDataType = true,
smallintDataType = 1,
decimalDataType = 1.1m,
smallmoneyDataType = 1.1m,
intDataType = 1,
tinyintDataType = 1,
moneyDataType = 1.1m,
floatDataType = 1.1d,
realDataType = 1.1f,
datetimeDataType = new DateTime(2014, 12, 17, 21, 2, 58, 123),
smalldatetimeDataType = new DateTime(2014, 12, 17, 21, 3, 0),
charDataType = 'E',
varcharDataType = "E",
textDataType = "E",
ncharDataType = "Ё",
nvarcharDataType = "Ё",
ntextDataType = "Ё",
binaryDataType = new byte[] { 1 },
varbinaryDataType = new byte[] { 1 },
imageDataType = new byte[] { 1, 2, 3, 4, 5 },
uniqueidentifierDataType = new Guid(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
sql_variantDataType = "1",
nvarchar_max_DataType = "1",
varchar_max_DataType = "1",
varbinary_max_DataType = new byte[] { 1, 2, 3, 4, 50 },
xmlDataType = "<xml />",
datetime2DataType = new DateTime(2014, 12, 17, 21, 2, 58, 123),
datetimeoffsetDataType = new DateTimeOffset(2014, 12, 17, 21, 2, 58, 123, new TimeSpan(5, 0, 0)),
datetimeoffset0DataType = new DateTimeOffset(2014, 12, 17, 21, 2, 58, 0, new TimeSpan(5, 0, 0)),
datetimeoffset1DataType = new DateTimeOffset(2014, 12, 17, 21, 2, 58, 100, new TimeSpan(5, 0, 0)),
datetimeoffset2DataType = new DateTimeOffset(2014, 12, 17, 21, 2, 58, 120, new TimeSpan(5, 0, 0)),
datetimeoffset3DataType = new DateTimeOffset(2014, 12, 17, 21, 2, 58, 123, new TimeSpan(5, 0, 0)),
datetimeoffset4DataType = new DateTimeOffset(2014, 12, 17, 21, 2, 58, 123, new TimeSpan(5, 0, 0)),
datetimeoffset5DataType = new DateTimeOffset(2014, 12, 17, 21, 2, 58, 123, new TimeSpan(5, 0, 0)),
datetimeoffset6DataType = new DateTimeOffset(2014, 12, 17, 21, 2, 58, 123, new TimeSpan(5, 0, 0)),
datetimeoffset7DataType = new DateTimeOffset(2014, 12, 17, 21, 2, 58, 123, new TimeSpan(5, 0, 0)),
dateDataType = new DateTime(2014, 12, 17),
timeDataType = new TimeSpan(0, 10, 11, 12, 567),
},
new AllTypes
{
ID = 701,
},
#endregion
};
void BulkCopyAllTypes(string context, BulkCopyType bulkCopyType)
{
using (var db = new DataConnection(context))
{
db.CommandTimeout = 60;
db.GetTable<AllTypes>().Delete(p => p.ID >= _allTypeses[0].ID);
db.BulkCopy(
new BulkCopyOptions
{
BulkCopyType = bulkCopyType,
RowsCopiedCallback = copied => Debug.WriteLine(copied.RowsCopied),
KeepIdentity = true,
},
_allTypeses);
var ids = _allTypeses.Select(at => at.ID).ToArray();
var list = db.GetTable<AllTypes>().Where(t => ids.Contains(t.ID)).OrderBy(t => t.ID).ToList();
db.GetTable<AllTypes>().Delete(p => p.ID >= _allTypeses[0].ID);
Assert.That(list.Count, Is.EqualTo(_allTypeses.Length));
for (var i = 0; i < list.Count; i++)
CompareObject(db.MappingSchema, list[i], _allTypeses[i]);
}
}
[Test]
public void BulkCopyAllTypesMultipleRows([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
BulkCopyAllTypes(context, BulkCopyType.MultipleRows);
}
[Test]
public void BulkCopyAllTypesProviderSpecific([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
BulkCopyAllTypes(context, BulkCopyType.ProviderSpecific);
}
void CompareObject<T>(MappingSchema mappingSchema, T actual, T test)
{
var ed = mappingSchema.GetEntityDescriptor(typeof(T));
foreach (var column in ed.Columns)
{
var actualValue = column.GetValue(mappingSchema, actual);
var testValue = column.GetValue(mappingSchema, test);
// timestampDataType autogenerated
if (column.MemberName == "timestampDataType")
continue;
#if !NETSTANDARD1_6
if (actualValue is SqlGeometry)
{
Assert.That(actualValue == null || ((SqlGeometry) actualValue).IsNull ? null : actualValue.ToString(),
Is.EqualTo(testValue == null || ((SqlGeometry) testValue).IsNull ? null : testValue.ToString()),
"Column : {0}", column.MemberName);
}
else if (actualValue is SqlGeography)
{
Assert.That(actualValue == null || ((SqlGeography) actualValue).IsNull ? null : actualValue.ToString(),
Is.EqualTo(testValue == null || ((SqlGeography) testValue).IsNull ? null : testValue.ToString()),
"Column : {0}", column.MemberName);
}
else
#endif
Assert.That(actualValue, Is.EqualTo(testValue),
actualValue is DateTimeOffset
? "Column : {0} {1:yyyy-MM-dd HH:mm:ss.fffffff zzz} {2:yyyy-MM-dd HH:mm:ss.fffffff zzz}"
: "Column : {0}",
column.MemberName,
actualValue,
testValue);
}
}
[Table(Name="AllTypes2")]
class AllTypes2
{
[Column(DbType="int"), PrimaryKey, Identity] public int ID { get; set; } // int
[Column(DbType="date"), Nullable] public DateTime? dateDataType { get; set; } // date
[Column(DbType="datetimeoffset(7)"), Nullable] public DateTimeOffset? datetimeoffsetDataType { get; set; } // datetimeoffset(7)
[Column(DbType="datetime2(7)"), Nullable] public DateTime? datetime2DataType { get; set; } // datetime2(7)
[Column(DbType="time(7)"), Nullable] public TimeSpan? timeDataType { get; set; } // time(7)
#if !NETSTANDARD1_6
[Column(DbType="hierarchyid"), Nullable] public SqlHierarchyId hierarchyidDataType { get; set; } // hierarchyid
[Column(DbType="geography"), Nullable] public SqlGeography geographyDataType { get; set; } // geography
[Column(DbType="geometry"), Nullable] public SqlGeometry geometryDataType { get; set; } // geometry
#endif
}
IEnumerable<AllTypes2> GenerateAllTypes2(int startId, int count)
{
for (int i = 0; i < count; i++)
{
yield return new AllTypes2
{
ID = startId + i,
dateDataType = DateTime.Today.AddDays(i),
datetimeoffsetDataType = DateTime.Now.AddMinutes(i),
datetime2DataType = DateTime.Today.AddDays(i),
timeDataType = TimeSpan.FromSeconds(i),
#if !NETSTANDARD1_6
hierarchyidDataType = SqlHierarchyId.Parse("/1/3/"),
geographyDataType = SqlGeography.Parse("LINESTRING (-122.36 47.656, -122.343 47.656)"),
geometryDataType = SqlGeometry.Parse("LINESTRING (100 100, 20 180, 180 180)"),
#endif
};
}
}
void BulkCopyAllTypes2(string context, BulkCopyType bulkCopyType)
{
using (var db = new DataConnection(context))
{
db.CommandTimeout = 60;
db.GetTable<AllTypes2>().Delete(p => p.ID >= 3);
var allTypes2 = GenerateAllTypes2(3, 10).ToArray();
db.BulkCopy(
new BulkCopyOptions
{
BulkCopyType = bulkCopyType,
RowsCopiedCallback = copied => Debug.WriteLine(copied.RowsCopied),
KeepIdentity = true,
},
allTypes2);
var loaded = db.GetTable<AllTypes2>().Where(p => p.ID >= 3).OrderBy(p=> p.ID).ToArray();
Assert.That(loaded.Count, Is.EqualTo(allTypes2.Length));
for (var i = 0; i < loaded.Length; i++)
CompareObject(db.MappingSchema, loaded[i], allTypes2[i]);
}
}
#if !NETSTANDARD1_6
[Test]
public void BulkCopyAllTypes2MultipleRows([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
BulkCopyAllTypes2(context, BulkCopyType.MultipleRows);
}
[Test]
public void BulkCopyAllTypes2ProviderSpecific([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
BulkCopyAllTypes2(context, BulkCopyType.ProviderSpecific);
}
#endif
[Test]
public void CreateAllTypes([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db = new DataConnection(context))
{
var ms = new MappingSchema();
db.AddMappingSchema(ms);
ms.GetFluentMappingBuilder()
.Entity<AllTypes>()
.HasTableName("AllTypeCreateTest");
try
{
db.DropTable<AllTypes>();
}
catch
{
}
var table = db.CreateTable<AllTypes>();
var list = table.ToList();
db.DropTable<AllTypes>();
}
}
#if !NETSTANDARD1_6
[Test]
public void CreateAllTypes2([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
{
using (var db = new DataConnection(context))
{
var ms = new MappingSchema();
db.AddMappingSchema(ms);
ms.GetFluentMappingBuilder()
.Entity<AllTypes2>()
.HasTableName("AllType2CreateTest");
try
{
db.DropTable<AllTypes2>();
}
catch
{
}
var table = db.CreateTable<AllTypes2>();
var list = table.ToList();
db.DropTable<AllTypes2>();
}
}
#endif
[Table("#TempTable")]
class TempTable
{
[PrimaryKey] public int ID;
}
[Test]
public void CreateTempTable([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db = new DataConnection(context))
{
db.CreateTable<TempTable>();
db.DropTable<TempTable>();
db.CreateTable<TempTable>();
}
}
[Test]
public void CreateTempTable2([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db1 = new DataConnection(context))
using (var db2 = new DataConnection(context))
{
db1.CreateTable<TempTable>();
db2.CreateTable<TempTable>();
}
}
[Table("DecimalOverflow")]
class DecimalOverflow
{
[Column] public decimal Decimal1;
[Column] public decimal Decimal2;
[Column] public decimal Decimal3;
}
[Test]
public void OverflowTest([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
var func = SqlServerTools.DataReaderGetDecimal;
try
{
SqlServerTools.DataReaderGetDecimal = GetDecimal;
using (var db = new DataConnection(context))
{
var list = db.GetTable<DecimalOverflow>().ToList();
}
}
finally
{
SqlServerTools.DataReaderGetDecimal = func;
}
}
const int ClrPrecision = 29;
static decimal GetDecimal(IDataReader rd, int idx)
{
try
{
var value = ((SqlDataReader)rd).GetSqlDecimal(idx);
if (value.Precision > ClrPrecision)
{
var str = value.ToString();
var val = decimal.Parse(str, CultureInfo.InvariantCulture);
return val;
}
return value.Value;
}
catch (Exception)
{
var vvv= rd.GetValue(idx);
throw;
}
}
[Table("DecimalOverflow")]
class DecimalOverflow2
{
[Column] public SqlDecimal Decimal1;
[Column] public SqlDecimal Decimal2;
[Column] public SqlDecimal Decimal3;
}
[Test]
public void OverflowTest2([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
var func = SqlServerTools.DataReaderGetDecimal;
try
{
SqlServerTools.DataReaderGetDecimal = (rd, idx) => { throw new Exception(); };
using (var db = new DataConnection(context))
{
var list = db.GetTable<DecimalOverflow2>().ToList();
}
}
finally
{
SqlServerTools.DataReaderGetDecimal = func;
}
}
[Test]
public void SelectTableWithHintTest([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db = GetDataContext(context))
{
AreEqual(Person, db.Person.With("TABLOCK"));
}
}
[Test]
public void UpdateTableWithHintTest([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db = GetDataContext(context))
{
Assert.AreEqual(Person.Count(), db.Person.Set(_ => _.FirstName, _ => _.FirstName).Update());
Assert.AreEqual(Person.Count(), db.Person.With("TABLOCK").Set(_ => _.FirstName, _ => _.FirstName).Update());
}
}
[Test]
public void InOutProcedureTest([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db = (DataConnection)GetDataContext(context))
{
var dbName = TestUtils.GetDatabaseName(db);
var inputID = 1234;
var inputStr = "InputStr";
int? outputID = 5678;
int? inputOutputID = 9012;
string outputStr = "OuputStr";
string inputOutputStr = "InputOutputStr";
var parameters = new []
{
new DataParameter("@ID", inputID, DataType.Int32),
new DataParameter("@outputID", outputID, DataType.Int32) { Direction = ParameterDirection.InputOutput },
new DataParameter("@inputOutputID", inputOutputID, DataType.Int32) { Direction = ParameterDirection.InputOutput },
new DataParameter("@str", inputStr, DataType.VarChar),
new DataParameter("@outputStr", outputStr, DataType.VarChar) { Direction = ParameterDirection.InputOutput, Size = 50 },
new DataParameter("@inputOutputStr", inputOutputStr, DataType.VarChar) { Direction = ParameterDirection.InputOutput, Size = 50 }
};
var ret = db.ExecuteProc($"[{dbName}]..[OutRefTest]", parameters);
outputID = Converter.ChangeTypeTo<int?> (parameters[1].Value);
inputOutputID = Converter.ChangeTypeTo<int?> (parameters[2].Value);
outputStr = Converter.ChangeTypeTo<string>(parameters[4].Value);
inputOutputStr = Converter.ChangeTypeTo<string>(parameters[5].Value);
Assert.That(outputID, Is.EqualTo(inputID));
Assert.That(inputOutputID, Is.EqualTo(9012 + inputID));
Assert.That(outputStr, Is.EqualTo(inputStr));
Assert.That(inputOutputStr, Is.EqualTo(inputStr + "InputOutputStr"));
}
}
[Test]
public async Task InOutProcedureTestAsync([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db = (DataConnection)GetDataContext(context))
{
var dbName = TestUtils.GetDatabaseName(db);
var inputID = 1234;
var inputStr = "InputStr";
int? outputID = 5678;
int? inputOutputID = 9012;
string outputStr = "OuputStr";
string inputOutputStr = "InputOutputStr";
var parameters = new []
{
new DataParameter("@ID", inputID, DataType.Int32),
new DataParameter("@outputID", outputID, DataType.Int32) { Direction = ParameterDirection.InputOutput },
new DataParameter("@inputOutputID", inputOutputID, DataType.Int32) { Direction = ParameterDirection.InputOutput },
new DataParameter("@str", inputStr, DataType.VarChar),
new DataParameter("@outputStr", outputStr, DataType.VarChar) { Direction = ParameterDirection.InputOutput, Size = 50 },
new DataParameter("@inputOutputStr", inputOutputStr, DataType.VarChar) { Direction = ParameterDirection.InputOutput, Size = 50 }
};
var ret = await db.ExecuteProcAsync($"[{dbName}]..[OutRefTest]", parameters);
outputID = Converter.ChangeTypeTo<int?> (parameters[1].Value);
inputOutputID = Converter.ChangeTypeTo<int?> (parameters[2].Value);
outputStr = Converter.ChangeTypeTo<string>(parameters[4].Value);
inputOutputStr = Converter.ChangeTypeTo<string>(parameters[5].Value);
Assert.That(outputID, Is.EqualTo(inputID));
Assert.That(inputOutputID, Is.EqualTo(9012 + inputID));
Assert.That(outputStr, Is.EqualTo(inputStr));
Assert.That(inputOutputStr, Is.EqualTo(inputStr + "InputOutputStr"));
}
}
#if !NETSTANDARD1_6
[Test]
public void TestIssue1144([IncludeDataSources(TestProvName.AllSqlServer)] string context)
{
using (var db = (DataConnection)GetDataContext(context))
{
var schema = db.DataProvider.GetSchemaProvider().GetSchema(db, TestUtils.GetDefaultSchemaOptions(context));
var table = schema.Tables.Where(_ => _.TableName == "Issue1144").Single();
Assert.AreEqual(1, table.Columns.Count);
}
}
#endif
}
}
| mit |
vassildinev/CSharp-OOP | 05.OOPPrinciples2Homework/Shapes/Properties/AssemblyInfo.cs | 1388 | 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("Shapes")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Shapes")]
[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("ebc233fc-b594-4861-be5d-4d8893661de9")]
// 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 |
rwjblue/ember-suave | tests/fixtures/disallow-operator-before-line-break/bad/expression.js | 27 | var x = 4 + 5 +
12 + 13;
| mit |
RocketLeagueLatvia/discord-bot | commands/event/closeCheckin.js | 1349 | const { Command } = require('discord.js-commando');
const Event = require('../../lib/event');
module.exports = class CloseCheckInCommand extends Command {
constructor(client) {
super(client, {
name: 'event-check-in-close',
aliases: ['close-check-in'],
group: 'event',
memberName: 'check-in-close',
description: 'Closes the check-in to the specified event.',
examples: ['closecheckin RLL Online 3v3 Teambuilder #4'],
args: [
{
key: 'name',
prompt: 'What event do you want to close the check-in to?',
type: 'string',
default: ''
}
]
});
}
hasPermission(msg) {
if (!this.client.isOwner(msg.author)) return 'Only the bot owner(s) may use this command.';
return true;
}
async run(msg, { name }) {
let event;
if (name !== '') {
event = await Event.findByName(name);
} else {
event = await Event.findCurrentEvent();
}
if (!event) {
return msg.say(`Sorry, but I could not find the event.`);
}
await event.closeCheckIn();
return msg.say(`Check-in to event ${event.name} closed.`);
}
};
| mit |
blrchen/CVF | CVF/src/CVF.App/Program.cs | 449 | using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace CVF.App
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| mit |
SHAMMY1/Telerik-Academy | Homeworks/CSharpPartOne/05.ConditionalStatements/05.Conditional-Statements-HW/09.PlayWithIntDoubleAndString/PlayWithIntDoubleAndString.cs | 2159 | //Problem 9. Play with Int, Double and String
//Write a program that, depending on the user’s choice, inputs an int, double or string variable.
//If the variable is int or double, the program increases it by one.
//If the variable is a string, the program appends * at the end.
//Print the result at the console. Use switch statement.
//Example 1:
//program user
//Please choose a type:
//1 --> int
//2 --> double
//3 --> string 3
//Please enter a string: hello
//hello*
//Example 2:
//program user
//Please choose a type:
//1 --> int
//2 --> double 2
//3 --> string
//Please enter a double: 1.5
//2.5
using System;
class PlayWithIntDoubleAndString
{
static void Main()
{
string task = "Problem 9. Play with Int, Double and String\n\nWrite a program that, depending on the user’s choice, inputs an int, double or string variable.\nIf the variable is int or double, the program increases it by one.\nIf the variable is a string, the program appends * at the end.\nPrint the result at the console. Use switch statement.\nExample 1:\nprogram user\nPlease choose a type: \n1 --> int \n2 --> double \n3 --> string 3\nPlease enter a string: hello\nhello* \nExample 2:\nprogram user\nPlease choose a type: \n1 --> int \n2 --> double 2\n3 --> string \nPlease enter a double: 1.5\n2.5 \n";
string separator = new string('*', Console.WindowWidth);
Console.WriteLine(task);
Console.WriteLine(separator);
Console.Write("1 --> int\n2 --> double\n3 --> string\nPlease choose a type: ");
string choice = Console.ReadLine();
switch (choice)
{
case "1": choice = "int"; break;
case "2": choice = "double"; break;
case "3": choice = "string"; break;
default:
break;
}
Console.Write("Please enter a {0}: ", choice);
string input = Console.ReadLine();
Console.Write("Result: ");
switch (choice)
{
case "int": Console.WriteLine(int.Parse(input) + 1); break;
case "double": Console.WriteLine(double.Parse(input) + 1); break;
case "string": Console.WriteLine(input + '*'); break;
default: Console.WriteLine("Invalid choice"); break;
}
}
}
| mit |
MikeBulte/inleiding_java | src/h14multimedia/Opdr14dot2KaartVerdelen.java | 4106 | package h14multimedia;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.Random;
/**
* Created by Mike on 17-03-17.
* Deze applet deelt een aantal kaarten via de random functie uit, maar de deckArray springt een ArrayIndexOutOfBoundsException
* na de eerste keer.
*/
public class Opdr14dot2KaartVerdelen extends Applet {
private boolean checkBoolean = false;
private int arraysLengthCombined;
private AudioClip sound;
private String deckArray[];
private String kaartKleurArray[] = {
"Harten", "Klaver", "Ruiten", "Schoppen"
};
private String kaartNummerArray[] = {
"Een", "Twee", "Drie", "Vier", "Vijf", "Zes", "Zeven",
"Acht", "Negen", "Tien", "Boer", "Vrouw", "Heer"
};
private String player1Array[], player2Array[], player3Array[], player4Array[];
@Override
public void init() {
super.init();
setSize(500, 400);
URL path = Opdr14dot2KaartVerdelen.class.getResource("/sound/");
sound = getAudioClip(path, "carddrawing.wav");
Button deelKnop = new Button("Deel Kaarten");
add(deelKnop);
deelKnop.addActionListener(new DeelKnopActionListener());
player1Array = new String[13];
player2Array = new String[player1Array.length];
player3Array = new String[player1Array.length];
player4Array = new String[player1Array.length];
arraysLengthCombined = player1Array.length + player2Array.length + player3Array.length + player4Array.length;
deckArray = new String[arraysLengthCombined];
}
@Override
public void paint(Graphics g) {
super.paint(g);
int player1X = 50, player2X = 150, player3X = 250, player4X = 350, playerY = 50;
if (checkBoolean) {
for (int i = 0; i < player1Array.length; i++) {
if (i == 0) {
g.drawString("Player 1 heeft ", player1X, playerY);
g.drawString("Player 2 heeft ", player2X, playerY);
g.drawString("Player 3 heeft ", player3X, playerY);
g.drawString("Player 4 heeft ", player4X, playerY);
playerY += 20;
} // Einde if- condition
g.drawString("" + player1Array[i], player1X, playerY);
g.drawString("" + player2Array[i], player2X, playerY);
g.drawString("" + player3Array[i], player3X, playerY);
g.drawString("" + player4Array[i], player4X, playerY);
playerY += 20;
}
}
}
private String deelKaart() {
int random = new Random().nextInt(deckArray.length);
String kaart = deckArray[random];
//vervang de inhoud van deck
String[] hulpLijst = new String[deckArray.length - 1];
int hulpindex = 0;
for (int i = 0; i < deckArray.length; i++) {
if (i != random) {
hulpLijst[hulpindex] = deckArray[i];
hulpindex++;
}
}
deckArray = hulpLijst;
return kaart;
}
private class DeelKnopActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
checkBoolean = true;
int teller1 = 0, teller2 = 0;
for (int i = 0; i < arraysLengthCombined; i++) {
if (teller1 == kaartKleurArray.length) {
teller1 = 0;
teller2++;
}
deckArray[i] = (kaartKleurArray[teller1] + " " + kaartNummerArray[teller2]);
teller1++;
}
for (int i = 0; i < player1Array.length; i++) {
player1Array[i] = deelKaart();
player2Array[i] = deelKaart();
player3Array[i] = deelKaart();
player4Array[i] = deelKaart();
}
sound.play();
repaint();
}
}
}
| mit |
dissident/mayak_shop | config/environments/development.rb | 1986 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Mailer settings.
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :letter_opener
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Slim markup language setting.
# Slim::Engine.set_default_options pretty: true, sort_attrs: false
# Init Seo module on reload, not only on restart
# ActiveSupport::Dependencies.explicitly_unloadable_constants << 'Seo'
end
| mit |
fredatgithub/GitAutoUpdate | GitAutoUpdateGUI/AboutBoxApplication.Designer.cs | 9462 | namespace GitAutoUpdateGUI
{
partial class AboutBoxApplication
{
/// <summary>
/// Variable nécessaire au concepteur.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Nettoyage des ressources utilisées.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Code généré par le Concepteur Windows Form
/// <summary>
/// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
/// le contenu de cette méthode avec l'éditeur de code.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutBoxApplication));
this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.logoPictureBox = new System.Windows.Forms.PictureBox();
this.labelProductName = new System.Windows.Forms.Label();
this.labelVersion = new System.Windows.Forms.Label();
this.labelCopyright = new System.Windows.Forms.Label();
this.labelCompanyName = new System.Windows.Forms.Label();
this.textBoxDescription = new System.Windows.Forms.TextBox();
this.okButton = new System.Windows.Forms.Button();
this.tableLayoutPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel
//
this.tableLayoutPanel.ColumnCount = 2;
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 67F));
this.tableLayoutPanel.Controls.Add(this.logoPictureBox, 0, 0);
this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0);
this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1);
this.tableLayoutPanel.Controls.Add(this.labelCopyright, 1, 2);
this.tableLayoutPanel.Controls.Add(this.labelCompanyName, 1, 3);
this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4);
this.tableLayoutPanel.Controls.Add(this.okButton, 1, 5);
this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel.Location = new System.Drawing.Point(9, 9);
this.tableLayoutPanel.Name = "tableLayoutPanel";
this.tableLayoutPanel.RowCount = 6;
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.Size = new System.Drawing.Size(417, 265);
this.tableLayoutPanel.TabIndex = 0;
//
// logoPictureBox
//
this.logoPictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.logoPictureBox.Image = ((System.Drawing.Image)(resources.GetObject("logoPictureBox.Image")));
this.logoPictureBox.Location = new System.Drawing.Point(3, 3);
this.logoPictureBox.Name = "logoPictureBox";
this.tableLayoutPanel.SetRowSpan(this.logoPictureBox, 6);
this.logoPictureBox.Size = new System.Drawing.Size(131, 259);
this.logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.logoPictureBox.TabIndex = 12;
this.logoPictureBox.TabStop = false;
//
// labelProductName
//
this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelProductName.Location = new System.Drawing.Point(143, 0);
this.labelProductName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelProductName.MaximumSize = new System.Drawing.Size(0, 17);
this.labelProductName.Name = "labelProductName";
this.labelProductName.Size = new System.Drawing.Size(271, 17);
this.labelProductName.TabIndex = 19;
this.labelProductName.Text = "Nom du produit";
this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelVersion
//
this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelVersion.Location = new System.Drawing.Point(143, 26);
this.labelVersion.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelVersion.MaximumSize = new System.Drawing.Size(0, 17);
this.labelVersion.Name = "labelVersion";
this.labelVersion.Size = new System.Drawing.Size(271, 17);
this.labelVersion.TabIndex = 0;
this.labelVersion.Text = "Version";
this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCopyright
//
this.labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCopyright.Location = new System.Drawing.Point(143, 52);
this.labelCopyright.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelCopyright.MaximumSize = new System.Drawing.Size(0, 17);
this.labelCopyright.Name = "labelCopyright";
this.labelCopyright.Size = new System.Drawing.Size(271, 17);
this.labelCopyright.TabIndex = 21;
this.labelCopyright.Text = "Copyright";
this.labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCompanyName
//
this.labelCompanyName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCompanyName.Location = new System.Drawing.Point(143, 78);
this.labelCompanyName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelCompanyName.MaximumSize = new System.Drawing.Size(0, 17);
this.labelCompanyName.Name = "labelCompanyName";
this.labelCompanyName.Size = new System.Drawing.Size(271, 17);
this.labelCompanyName.TabIndex = 22;
this.labelCompanyName.Text = "Nom de la société";
this.labelCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// textBoxDescription
//
this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxDescription.Location = new System.Drawing.Point(143, 107);
this.textBoxDescription.Margin = new System.Windows.Forms.Padding(6, 3, 3, 3);
this.textBoxDescription.Multiline = true;
this.textBoxDescription.Name = "textBoxDescription";
this.textBoxDescription.ReadOnly = true;
this.textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxDescription.Size = new System.Drawing.Size(271, 126);
this.textBoxDescription.TabIndex = 23;
this.textBoxDescription.TabStop = false;
this.textBoxDescription.Text = "Description";
//
// okButton
//
this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.okButton.Location = new System.Drawing.Point(339, 240);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 22);
this.okButton.TabIndex = 24;
this.okButton.Text = "&OK";
this.okButton.Click += new System.EventHandler(this.okButton_Click);
//
// AboutBoxApplication
//
this.AcceptButton = this.okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(435, 283);
this.Controls.Add(this.tableLayoutPanel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AboutBoxApplication";
this.Padding = new System.Windows.Forms.Padding(9);
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "AboutBoxApplication";
this.tableLayoutPanel.ResumeLayout(false);
this.tableLayoutPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
private System.Windows.Forms.PictureBox logoPictureBox;
private System.Windows.Forms.Label labelProductName;
private System.Windows.Forms.Label labelVersion;
private System.Windows.Forms.Label labelCopyright;
private System.Windows.Forms.Label labelCompanyName;
private System.Windows.Forms.TextBox textBoxDescription;
private System.Windows.Forms.Button okButton;
}
}
| mit |
codenothing/single-ddm | src/jquery.single-ddm.js | 2195 | /*
* Single Drop Down Menu [VERSION]
* [DATE]
* Corey Hart @ http://www.codenothing.com
*/
(function( $, undefined ){
// bgiframe is needed to fix z-index problem for IE6 users.
// For applications that don't have bgiframe plugin installed, create a useless
// function that doesn't break the chain
function emptyfn(){
return this;
}
// Drop Menu Plugin
$.fn.singleDropMenu = function( options ) {
return this.each(function(){
// Default Settings
var $main = $(this), timer, $menu, $li, el,
settings = $.extend({
timer: 500,
parentMO: undefined,
childMO: undefined,
bgiframe: undefined,
show: 'show',
hide: 'hide'
}, options || {}, $.metadata ? $main.metadata() : {} ),
// bgiframe replica
bgiframe = $.fn.bgiframe || $.fn.bgIframe || emptyfn;
// Run Menu
$main.delegate( 'li', 'mouseenter.single-ddm', function(){
// Clear any open menus
if ( $.data( el = this, 'single-ddm-toplevel' ) !== true ) {
$( el ).children('a').addClass( settings.childMO );
return true;
}
else if ( ! $menu || $menu[0] !== el ) {
closemenu();
$( el ).children('a').addClass( settings.parentMO ).siblings('ul')[ settings.show ]();
}
else {
$menu = false;
if ( timer ) {
timer = clearTimeout( timer );
}
}
})
.delegate('li', 'mouseleave.single-ddm', function(){
if ( $.data( el = this, 'single-ddm-toplevel' ) !== true ) {
$( el ).children('a').removeClass( settings.childMO );
return true;
}
if ( timer ) {
clearTimeout( timer );
}
$menu = $( el );
timer = setTimeout( closemenu, settings.timer );
});
// Each nested list needs to be wrapper with bgiframe if possible
bgiframe.call(
$main.children('li').data( 'single-ddm-toplevel', true ).children('ul'),
settings.bgiframe
);
// Function to close set menu
function closemenu(){
if ( $menu && timer ){
$menu.children('a').removeClass( settings.parentMO ).siblings('ul')[ settings.hide ]();
timer = clearTimeout( timer );
$menu = false;
}
}
// Closes any open menus when mouse click occurs anywhere else on the page
$(document).click( closemenu );
});
};
})( jQuery );
| mit |
gaochundong/Redola | Redola/Redola.ActorModel/Actor/Channel/IActorChannel.cs | 1090 | using System;
namespace Redola.ActorModel
{
public interface IActorChannel
{
string Identifier { get; }
ActorIdentity LocalActor { get; }
ActorIdentity RemoteActor { get; }
bool Active { get; }
void Open();
void Close();
event EventHandler<ActorChannelConnectedEventArgs> ChannelConnected;
event EventHandler<ActorChannelDisconnectedEventArgs> ChannelDisconnected;
event EventHandler<ActorChannelDataReceivedEventArgs> ChannelDataReceived;
void Send(string identifier, byte[] data);
void Send(string identifier, byte[] data, int offset, int count);
void BeginSend(string identifier, byte[] data);
void BeginSend(string identifier, byte[] data, int offset, int count);
IAsyncResult BeginSend(string identifier, byte[] data, AsyncCallback callback, object state);
IAsyncResult BeginSend(string identifier, byte[] data, int offset, int count, AsyncCallback callback, object state);
void EndSend(string identifier, IAsyncResult asyncResult);
}
}
| mit |
xirqlz/blueprint41 | Datastore.Generated/Relationships/CURRENCYRATE_HAS_CURRENCY.cs | 3894 | using System;
using Blueprint41;
using Blueprint41.Query;
namespace Domain.Data.Query
{
public partial class CURRENCYRATE_HAS_CURRENCY_REL : RELATIONSHIP, IFromIn_CURRENCYRATE_HAS_CURRENCY_REL, IFromOut_CURRENCYRATE_HAS_CURRENCY_REL {
public override string NEO4J_TYPE
{
get
{
return "HAS_CURRENCY";
}
}
public override AliasResult RelationshipAlias { get; protected set; }
internal CURRENCYRATE_HAS_CURRENCY_REL(Blueprint41.Query.Node parent, DirectionEnum direction) : base(parent, direction) { }
public CURRENCYRATE_HAS_CURRENCY_REL Alias(out CURRENCYRATE_HAS_CURRENCY_ALIAS alias)
{
alias = new CURRENCYRATE_HAS_CURRENCY_ALIAS(this);
RelationshipAlias = alias;
return this;
}
public CURRENCYRATE_HAS_CURRENCY_REL Repeat(int maxHops)
{
return Repeat(1, maxHops);
}
public CURRENCYRATE_HAS_CURRENCY_REL Repeat(int minHops, int maxHops)
{
return this;
}
IFromIn_CURRENCYRATE_HAS_CURRENCY_REL IFromIn_CURRENCYRATE_HAS_CURRENCY_REL.Alias(out CURRENCYRATE_HAS_CURRENCY_ALIAS alias)
{
return Alias(out alias);
}
IFromOut_CURRENCYRATE_HAS_CURRENCY_REL IFromOut_CURRENCYRATE_HAS_CURRENCY_REL.Alias(out CURRENCYRATE_HAS_CURRENCY_ALIAS alias)
{
return Alias(out alias);
}
IFromIn_CURRENCYRATE_HAS_CURRENCY_REL IFromIn_CURRENCYRATE_HAS_CURRENCY_REL.Repeat(int maxHops)
{
return Repeat(maxHops);
}
IFromIn_CURRENCYRATE_HAS_CURRENCY_REL IFromIn_CURRENCYRATE_HAS_CURRENCY_REL.Repeat(int minHops, int maxHops)
{
return Repeat(minHops, maxHops);
}
IFromOut_CURRENCYRATE_HAS_CURRENCY_REL IFromOut_CURRENCYRATE_HAS_CURRENCY_REL.Repeat(int maxHops)
{
return Repeat(maxHops);
}
IFromOut_CURRENCYRATE_HAS_CURRENCY_REL IFromOut_CURRENCYRATE_HAS_CURRENCY_REL.Repeat(int minHops, int maxHops)
{
return Repeat(minHops, maxHops);
}
public CURRENCYRATE_HAS_CURRENCY_IN In { get { return new CURRENCYRATE_HAS_CURRENCY_IN(this); } }
public class CURRENCYRATE_HAS_CURRENCY_IN
{
private CURRENCYRATE_HAS_CURRENCY_REL Parent;
internal CURRENCYRATE_HAS_CURRENCY_IN(CURRENCYRATE_HAS_CURRENCY_REL parent)
{
Parent = parent;
}
public CurrencyRateNode CurrencyRate { get { return new CurrencyRateNode(Parent, DirectionEnum.In); } }
}
public CURRENCYRATE_HAS_CURRENCY_OUT Out { get { return new CURRENCYRATE_HAS_CURRENCY_OUT(this); } }
public class CURRENCYRATE_HAS_CURRENCY_OUT
{
private CURRENCYRATE_HAS_CURRENCY_REL Parent;
internal CURRENCYRATE_HAS_CURRENCY_OUT(CURRENCYRATE_HAS_CURRENCY_REL parent)
{
Parent = parent;
}
public CurrencyNode Currency { get { return new CurrencyNode(Parent, DirectionEnum.Out); } }
}
}
public interface IFromIn_CURRENCYRATE_HAS_CURRENCY_REL
{
IFromIn_CURRENCYRATE_HAS_CURRENCY_REL Alias(out CURRENCYRATE_HAS_CURRENCY_ALIAS alias);
IFromIn_CURRENCYRATE_HAS_CURRENCY_REL Repeat(int maxHops);
IFromIn_CURRENCYRATE_HAS_CURRENCY_REL Repeat(int minHops, int maxHops);
CURRENCYRATE_HAS_CURRENCY_REL.CURRENCYRATE_HAS_CURRENCY_OUT Out { get; }
}
public interface IFromOut_CURRENCYRATE_HAS_CURRENCY_REL
{
IFromOut_CURRENCYRATE_HAS_CURRENCY_REL Alias(out CURRENCYRATE_HAS_CURRENCY_ALIAS alias);
IFromOut_CURRENCYRATE_HAS_CURRENCY_REL Repeat(int maxHops);
IFromOut_CURRENCYRATE_HAS_CURRENCY_REL Repeat(int minHops, int maxHops);
CURRENCYRATE_HAS_CURRENCY_REL.CURRENCYRATE_HAS_CURRENCY_IN In { get; }
}
public class CURRENCYRATE_HAS_CURRENCY_ALIAS : AliasResult
{
private CURRENCYRATE_HAS_CURRENCY_REL Parent;
internal CURRENCYRATE_HAS_CURRENCY_ALIAS(CURRENCYRATE_HAS_CURRENCY_REL parent)
{
Parent = parent;
}
}
}
| mit |
hoovercj/vscode | src/vs/editor/test/common/model/textModelSearch.test.ts | 23596 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { getMapForWordSeparators } from 'vs/editor/common/controller/wordCharacterClassifier';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { EndOfLineSequence, FindMatch } from 'vs/editor/common/model';
import { TextModel } from 'vs/editor/common/model/textModel';
import { SearchData, SearchParams, TextModelSearch, isMultilineRegexSource } from 'vs/editor/common/model/textModelSearch';
import { USUAL_WORD_SEPARATORS } from 'vs/editor/common/model/wordHelper';
import { createTextModel } from 'vs/editor/test/common/editorTestUtils';
// --------- Find
suite('TextModelSearch', () => {
const usualWordSeparators = getMapForWordSeparators(USUAL_WORD_SEPARATORS);
function assertFindMatch(actual: FindMatch | null, expectedRange: Range, expectedMatches: string[] | null = null): void {
assert.deepEqual(actual, new FindMatch(expectedRange, expectedMatches));
}
function _assertFindMatches(model: TextModel, searchParams: SearchParams, expectedMatches: FindMatch[]): void {
let actual = TextModelSearch.findMatches(model, searchParams, model.getFullModelRange(), false, 1000);
assert.deepEqual(actual, expectedMatches, 'findMatches OK');
// test `findNextMatch`
let startPos = new Position(1, 1);
let match = TextModelSearch.findNextMatch(model, searchParams, startPos, false);
assert.deepEqual(match, expectedMatches[0], `findNextMatch ${startPos}`);
for (const expectedMatch of expectedMatches) {
startPos = expectedMatch.range.getStartPosition();
match = TextModelSearch.findNextMatch(model, searchParams, startPos, false);
assert.deepEqual(match, expectedMatch, `findNextMatch ${startPos}`);
}
// test `findPrevMatch`
startPos = new Position(model.getLineCount(), model.getLineMaxColumn(model.getLineCount()));
match = TextModelSearch.findPreviousMatch(model, searchParams, startPos, false);
assert.deepEqual(match, expectedMatches[expectedMatches.length - 1], `findPrevMatch ${startPos}`);
for (const expectedMatch of expectedMatches) {
startPos = expectedMatch.range.getEndPosition();
match = TextModelSearch.findPreviousMatch(model, searchParams, startPos, false);
assert.deepEqual(match, expectedMatch, `findPrevMatch ${startPos}`);
}
}
function assertFindMatches(text: string, searchString: string, isRegex: boolean, matchCase: boolean, wordSeparators: string | null, _expected: [number, number, number, number][]): void {
let expectedRanges = _expected.map(entry => new Range(entry[0], entry[1], entry[2], entry[3]));
let expectedMatches = expectedRanges.map(entry => new FindMatch(entry, null));
let searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);
let model = createTextModel(text);
_assertFindMatches(model, searchParams, expectedMatches);
model.dispose();
let model2 = createTextModel(text);
model2.setEOL(EndOfLineSequence.CRLF);
_assertFindMatches(model2, searchParams, expectedMatches);
model2.dispose();
}
let regularText = [
'This is some foo - bar text which contains foo and bar - as in Barcelona.',
'Now it begins a word fooBar and now it is caps Foo-isn\'t this great?',
'And here\'s a dull line with nothing interesting in it',
'It is also interesting if it\'s part of a word like amazingFooBar',
'Again nothing interesting here'
];
test('Simple find', () => {
assertFindMatches(
regularText.join('\n'),
'foo', false, false, null,
[
[1, 14, 1, 17],
[1, 44, 1, 47],
[2, 22, 2, 25],
[2, 48, 2, 51],
[4, 59, 4, 62]
]
);
});
test('Case sensitive find', () => {
assertFindMatches(
regularText.join('\n'),
'foo', false, true, null,
[
[1, 14, 1, 17],
[1, 44, 1, 47],
[2, 22, 2, 25]
]
);
});
test('Whole words find', () => {
assertFindMatches(
regularText.join('\n'),
'foo', false, false, USUAL_WORD_SEPARATORS,
[
[1, 14, 1, 17],
[1, 44, 1, 47],
[2, 48, 2, 51]
]
);
});
test('/^/ find', () => {
assertFindMatches(
regularText.join('\n'),
'^', true, false, null,
[
[1, 1, 1, 1],
[2, 1, 2, 1],
[3, 1, 3, 1],
[4, 1, 4, 1],
[5, 1, 5, 1]
]
);
});
test('/$/ find', () => {
assertFindMatches(
regularText.join('\n'),
'$', true, false, null,
[
[1, 74, 1, 74],
[2, 69, 2, 69],
[3, 54, 3, 54],
[4, 65, 4, 65],
[5, 31, 5, 31]
]
);
});
test('/.*/ find', () => {
assertFindMatches(
regularText.join('\n'),
'.*', true, false, null,
[
[1, 1, 1, 74],
[2, 1, 2, 69],
[3, 1, 3, 54],
[4, 1, 4, 65],
[5, 1, 5, 31]
]
);
});
test('/^$/ find', () => {
assertFindMatches(
[
'This is some foo - bar text which contains foo and bar - as in Barcelona.',
'',
'And here\'s a dull line with nothing interesting in it',
'',
'Again nothing interesting here'
].join('\n'),
'^$', true, false, null,
[
[2, 1, 2, 1],
[4, 1, 4, 1]
]
);
});
test('multiline find 1', () => {
assertFindMatches(
[
'Just some text text',
'Just some text text',
'some text again',
'again some text'
].join('\n'),
'text\\n', true, false, null,
[
[1, 16, 2, 1],
[2, 16, 3, 1],
]
);
});
test('multiline find 2', () => {
assertFindMatches(
[
'Just some text text',
'Just some text text',
'some text again',
'again some text'
].join('\n'),
'text\\nJust', true, false, null,
[
[1, 16, 2, 5]
]
);
});
test('multiline find 3', () => {
assertFindMatches(
[
'Just some text text',
'Just some text text',
'some text again',
'again some text'
].join('\n'),
'\\nagain', true, false, null,
[
[3, 16, 4, 6]
]
);
});
test('multiline find 4', () => {
assertFindMatches(
[
'Just some text text',
'Just some text text',
'some text again',
'again some text'
].join('\n'),
'.*\\nJust.*\\n', true, false, null,
[
[1, 1, 3, 1]
]
);
});
test('multiline find with line beginning regex', () => {
assertFindMatches(
[
'if',
'else',
'',
'if',
'else'
].join('\n'),
'^if\\nelse', true, false, null,
[
[1, 1, 2, 5],
[4, 1, 5, 5]
]
);
});
test('matching empty lines using boundary expression', () => {
assertFindMatches(
[
'if',
'',
'else',
' ',
'if',
' ',
'else'
].join('\n'),
'^\\s*$\\n', true, false, null,
[
[2, 1, 3, 1],
[4, 1, 5, 1],
[6, 1, 7, 1]
]
);
});
test('matching lines starting with A and ending with B', () => {
assertFindMatches(
[
'a if b',
'a',
'ab',
'eb'
].join('\n'),
'^a.*b$', true, false, null,
[
[1, 1, 1, 7],
[3, 1, 3, 3]
]
);
});
test('multiline find with line ending regex', () => {
assertFindMatches(
[
'if',
'else',
'',
'if',
'elseif',
'else'
].join('\n'),
'if\\nelse$', true, false, null,
[
[1, 1, 2, 5],
[5, 5, 6, 5]
]
);
});
test('issue #4836 - ^.*$', () => {
assertFindMatches(
[
'Just some text text',
'',
'some text again',
'',
'again some text'
].join('\n'),
'^.*$', true, false, null,
[
[1, 1, 1, 20],
[2, 1, 2, 1],
[3, 1, 3, 16],
[4, 1, 4, 1],
[5, 1, 5, 16],
]
);
});
test('multiline find for non-regex string', () => {
assertFindMatches(
[
'Just some text text',
'some text text',
'some text again',
'again some text',
'but not some'
].join('\n'),
'text\nsome', false, false, null,
[
[1, 16, 2, 5],
[2, 11, 3, 5],
]
);
});
test('issue #3623: Match whole word does not work for not latin characters', () => {
assertFindMatches(
[
'я',
'компилятор',
'обфускация',
':я-я'
].join('\n'),
'я', false, false, USUAL_WORD_SEPARATORS,
[
[1, 1, 1, 2],
[4, 2, 4, 3],
[4, 4, 4, 5],
]
);
});
test('issue #27459: Match whole words regression', () => {
assertFindMatches(
[
'this._register(this._textAreaInput.onKeyDown((e: IKeyboardEvent) => {',
' this._viewController.emitKeyDown(e);',
'}));',
].join('\n'),
'((e: ', false, false, USUAL_WORD_SEPARATORS,
[
[1, 45, 1, 50]
]
);
});
test('issue #27594: Search results disappear', () => {
assertFindMatches(
[
'this.server.listen(0);',
].join('\n'),
'listen(', false, false, USUAL_WORD_SEPARATORS,
[
[1, 13, 1, 20]
]
);
});
test('findNextMatch without regex', () => {
let model = createTextModel('line line one\nline two\nthree');
let searchParams = new SearchParams('line', false, false, null);
let actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), false);
assertFindMatch(actual, new Range(1, 1, 1, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(1, 6, 1, 10));
actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 3), false);
assertFindMatch(actual, new Range(1, 6, 1, 10));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(2, 1, 2, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(1, 1, 1, 5));
model.dispose();
});
test('findNextMatch with beginning boundary regex', () => {
let model = createTextModel('line one\nline two\nthree');
let searchParams = new SearchParams('^line', true, false, null);
let actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), false);
assertFindMatch(actual, new Range(1, 1, 1, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(2, 1, 2, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 3), false);
assertFindMatch(actual, new Range(2, 1, 2, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(1, 1, 1, 5));
model.dispose();
});
test('findNextMatch with beginning boundary regex and line has repetitive beginnings', () => {
let model = createTextModel('line line one\nline two\nthree');
let searchParams = new SearchParams('^line', true, false, null);
let actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), false);
assertFindMatch(actual, new Range(1, 1, 1, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(2, 1, 2, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 3), false);
assertFindMatch(actual, new Range(2, 1, 2, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(1, 1, 1, 5));
model.dispose();
});
test('findNextMatch with beginning boundary multiline regex and line has repetitive beginnings', () => {
let model = createTextModel('line line one\nline two\nline three\nline four');
let searchParams = new SearchParams('^line.*\\nline', true, false, null);
let actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), false);
assertFindMatch(actual, new Range(1, 1, 2, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(3, 1, 4, 5));
actual = TextModelSearch.findNextMatch(model, searchParams, new Position(2, 1), false);
assertFindMatch(actual, new Range(2, 1, 3, 5));
model.dispose();
});
test('findNextMatch with ending boundary regex', () => {
let model = createTextModel('one line line\ntwo line\nthree');
let searchParams = new SearchParams('line$', true, false, null);
let actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), false);
assertFindMatch(actual, new Range(1, 10, 1, 14));
actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 4), false);
assertFindMatch(actual, new Range(1, 10, 1, 14));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(2, 5, 2, 9));
actual = TextModelSearch.findNextMatch(model, searchParams, actual!.range.getEndPosition(), false);
assertFindMatch(actual, new Range(1, 10, 1, 14));
model.dispose();
});
test('findMatches with capturing matches', () => {
let model = createTextModel('one line line\ntwo line\nthree');
let searchParams = new SearchParams('(l(in)e)', true, false, null);
let actual = TextModelSearch.findMatches(model, searchParams, model.getFullModelRange(), true, 100);
assert.deepEqual(actual, [
new FindMatch(new Range(1, 5, 1, 9), ['line', 'line', 'in']),
new FindMatch(new Range(1, 10, 1, 14), ['line', 'line', 'in']),
new FindMatch(new Range(2, 5, 2, 9), ['line', 'line', 'in']),
]);
model.dispose();
});
test('findMatches multiline with capturing matches', () => {
let model = createTextModel('one line line\ntwo line\nthree');
let searchParams = new SearchParams('(l(in)e)\\n', true, false, null);
let actual = TextModelSearch.findMatches(model, searchParams, model.getFullModelRange(), true, 100);
assert.deepEqual(actual, [
new FindMatch(new Range(1, 10, 2, 1), ['line\n', 'line', 'in']),
new FindMatch(new Range(2, 5, 3, 1), ['line\n', 'line', 'in']),
]);
model.dispose();
});
test('findNextMatch with capturing matches', () => {
let model = createTextModel('one line line\ntwo line\nthree');
let searchParams = new SearchParams('(l(in)e)', true, false, null);
let actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), true);
assertFindMatch(actual, new Range(1, 5, 1, 9), ['line', 'line', 'in']);
model.dispose();
});
test('findNextMatch multiline with capturing matches', () => {
let model = createTextModel('one line line\ntwo line\nthree');
let searchParams = new SearchParams('(l(in)e)\\n', true, false, null);
let actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), true);
assertFindMatch(actual, new Range(1, 10, 2, 1), ['line\n', 'line', 'in']);
model.dispose();
});
test('findPreviousMatch with capturing matches', () => {
let model = createTextModel('one line line\ntwo line\nthree');
let searchParams = new SearchParams('(l(in)e)', true, false, null);
let actual = TextModelSearch.findPreviousMatch(model, searchParams, new Position(1, 1), true);
assertFindMatch(actual, new Range(2, 5, 2, 9), ['line', 'line', 'in']);
model.dispose();
});
test('findPreviousMatch multiline with capturing matches', () => {
let model = createTextModel('one line line\ntwo line\nthree');
let searchParams = new SearchParams('(l(in)e)\\n', true, false, null);
let actual = TextModelSearch.findPreviousMatch(model, searchParams, new Position(1, 1), true);
assertFindMatch(actual, new Range(2, 5, 3, 1), ['line\n', 'line', 'in']);
model.dispose();
});
test('\\n matches \\r\\n', () => {
let model = createTextModel('a\r\nb\r\nc\r\nd\r\ne\r\nf\r\ng\r\nh\r\ni');
assert.equal(model.getEOL(), '\r\n');
let searchParams = new SearchParams('h\\n', true, false, null);
let actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), true);
actual = TextModelSearch.findMatches(model, searchParams, model.getFullModelRange(), true, 1000)[0];
assertFindMatch(actual, new Range(8, 1, 9, 1), ['h\n']);
searchParams = new SearchParams('g\\nh\\n', true, false, null);
actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), true);
actual = TextModelSearch.findMatches(model, searchParams, model.getFullModelRange(), true, 1000)[0];
assertFindMatch(actual, new Range(7, 1, 9, 1), ['g\nh\n']);
searchParams = new SearchParams('\\ni', true, false, null);
actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), true);
actual = TextModelSearch.findMatches(model, searchParams, model.getFullModelRange(), true, 1000)[0];
assertFindMatch(actual, new Range(8, 2, 9, 2), ['\ni']);
model.dispose();
});
test('\\r can never be found', () => {
let model = createTextModel('a\r\nb\r\nc\r\nd\r\ne\r\nf\r\ng\r\nh\r\ni');
assert.equal(model.getEOL(), '\r\n');
let searchParams = new SearchParams('\\r\\n', true, false, null);
let actual = TextModelSearch.findNextMatch(model, searchParams, new Position(1, 1), true);
assert.equal(actual, null);
assert.deepEqual(TextModelSearch.findMatches(model, searchParams, model.getFullModelRange(), true, 1000), []);
model.dispose();
});
function assertParseSearchResult(searchString: string, isRegex: boolean, matchCase: boolean, wordSeparators: string | null, expected: SearchData | null): void {
let searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);
let actual = searchParams.parseSearchRequest();
if (expected === null) {
assert.ok(actual === null);
} else {
assert.deepEqual(actual!.regex, expected.regex);
assert.deepEqual(actual!.simpleSearch, expected.simpleSearch);
if (wordSeparators) {
assert.ok(actual!.wordSeparators !== null);
} else {
assert.ok(actual!.wordSeparators === null);
}
}
}
test('parseSearchRequest invalid', () => {
assertParseSearchResult('', true, true, USUAL_WORD_SEPARATORS, null);
assertParseSearchResult('(', true, false, null, null);
});
test('parseSearchRequest non regex', () => {
assertParseSearchResult('foo', false, false, null, new SearchData(/foo/giu, null, null));
assertParseSearchResult('foo', false, false, USUAL_WORD_SEPARATORS, new SearchData(/foo/giu, usualWordSeparators, null));
assertParseSearchResult('foo', false, true, null, new SearchData(/foo/gu, null, 'foo'));
assertParseSearchResult('foo', false, true, USUAL_WORD_SEPARATORS, new SearchData(/foo/gu, usualWordSeparators, 'foo'));
assertParseSearchResult('foo\\n', false, false, null, new SearchData(/foo\\n/giu, null, null));
assertParseSearchResult('foo\\\\n', false, false, null, new SearchData(/foo\\\\n/giu, null, null));
assertParseSearchResult('foo\\r', false, false, null, new SearchData(/foo\\r/giu, null, null));
assertParseSearchResult('foo\\\\r', false, false, null, new SearchData(/foo\\\\r/giu, null, null));
});
test('parseSearchRequest regex', () => {
assertParseSearchResult('foo', true, false, null, new SearchData(/foo/giu, null, null));
assertParseSearchResult('foo', true, false, USUAL_WORD_SEPARATORS, new SearchData(/foo/giu, usualWordSeparators, null));
assertParseSearchResult('foo', true, true, null, new SearchData(/foo/gu, null, null));
assertParseSearchResult('foo', true, true, USUAL_WORD_SEPARATORS, new SearchData(/foo/gu, usualWordSeparators, null));
assertParseSearchResult('foo\\n', true, false, null, new SearchData(/foo\n/gimu, null, null));
assertParseSearchResult('foo\\\\n', true, false, null, new SearchData(/foo\\n/giu, null, null));
assertParseSearchResult('foo\\r', true, false, null, new SearchData(/foo\r/gimu, null, null));
assertParseSearchResult('foo\\\\r', true, false, null, new SearchData(/foo\\r/giu, null, null));
});
test('issue #53415. \W should match line break.', () => {
assertFindMatches(
[
'text',
'180702-',
'180703-180704'
].join('\n'),
'\\d{6}-\\W', true, false, null,
[
[2, 1, 3, 1]
]
);
assertFindMatches(
[
'Just some text',
'',
'Just'
].join('\n'),
'\\W', true, false, null,
[
[1, 5, 1, 6],
[1, 10, 1, 11],
[1, 15, 2, 1],
[2, 1, 3, 1]
]
);
// Line break doesn't affect the result as we always use \n as line break when doing search
assertFindMatches(
[
'Just some text',
'',
'Just'
].join('\r\n'),
'\\W', true, false, null,
[
[1, 5, 1, 6],
[1, 10, 1, 11],
[1, 15, 2, 1],
[2, 1, 3, 1]
]
);
assertFindMatches(
[
'Just some text',
'\tJust',
'Just'
].join('\n'),
'\\W', true, false, null,
[
[1, 5, 1, 6],
[1, 10, 1, 11],
[1, 15, 2, 1],
[2, 1, 2, 2],
[2, 6, 3, 1],
]
);
// line break is seen as one non-word character
assertFindMatches(
[
'Just some text',
'',
'Just'
].join('\n'),
'\\W{2}', true, false, null,
[
[1, 5, 1, 7],
[1, 16, 3, 1]
]
);
// even if it's \r\n
assertFindMatches(
[
'Just some text',
'',
'Just'
].join('\r\n'),
'\\W{2}', true, false, null,
[
[1, 5, 1, 7],
[1, 16, 3, 1]
]
);
});
test('issue #65281. \w should match line break.', () => {
assertFindMatches(
[
'this/is{',
'a test',
'}',
].join('\n'),
'this/\\w*[^}]*', true, false, null,
[
[1, 1, 3, 1]
]
);
});
test('Simple find using unicode escape sequences', () => {
assertFindMatches(
regularText.join('\n'),
'\\u{0066}\\u006f\\u006F', true, false, null,
[
[1, 14, 1, 17],
[1, 44, 1, 47],
[2, 22, 2, 25],
[2, 48, 2, 51],
[4, 59, 4, 62]
]
);
});
test('isMultilineRegexSource', () => {
assert(!isMultilineRegexSource('foo'));
assert(!isMultilineRegexSource(''));
assert(!isMultilineRegexSource('foo\\sbar'));
assert(!isMultilineRegexSource('\\\\notnewline'));
assert(isMultilineRegexSource('foo\\nbar'));
assert(isMultilineRegexSource('foo\\nbar\\s'));
assert(isMultilineRegexSource('foo\\r\\n'));
assert(isMultilineRegexSource('\\n'));
assert(isMultilineRegexSource('foo\\W'));
});
test('issue #74715. \\d* finds empty string and stops searching.', () => {
let model = createTextModel('10.243.30.10');
let searchParams = new SearchParams('\\d*', true, false, null);
let actual = TextModelSearch.findMatches(model, searchParams, model.getFullModelRange(), true, 100);
assert.deepEqual(actual, [
new FindMatch(new Range(1, 1, 1, 3), ['10']),
new FindMatch(new Range(1, 3, 1, 3), ['']),
new FindMatch(new Range(1, 4, 1, 7), ['243']),
new FindMatch(new Range(1, 7, 1, 7), ['']),
new FindMatch(new Range(1, 8, 1, 10), ['30']),
new FindMatch(new Range(1, 10, 1, 10), ['']),
new FindMatch(new Range(1, 11, 1, 13), ['10'])
]);
model.dispose();
});
test('issue #100134. Zero-length matches should properly step over surrogate pairs', () => {
// 1[Laptop]1 - there shoud be no matches inside of [Laptop] emoji
assertFindMatches('1\uD83D\uDCBB1', '()', true, false, null,
[
[1, 1, 1, 1],
[1, 2, 1, 2],
[1, 4, 1, 4],
[1, 5, 1, 5],
]
);
// 1[Hacker Cat]1 = 1[Cat Face][ZWJ][Laptop]1 - there shoud be matches between emoji and ZWJ
// there shoud be no matches inside of [Cat Face] and [Laptop] emoji
assertFindMatches('1\uD83D\uDC31\u200D\uD83D\uDCBB1', '()', true, false, null,
[
[1, 1, 1, 1],
[1, 2, 1, 2],
[1, 4, 1, 4],
[1, 5, 1, 5],
[1, 7, 1, 7],
[1, 8, 1, 8]
]
);
});
});
| mit |
FIRST-Team-339/2016 | src/org/usfirst/frc/team339/Vision/operators/HSLColorThresholdOperator.java | 1376 | package org.usfirst.frc.team339.Vision.operators;
import com.ni.vision.NIVision;
import com.ni.vision.NIVision.Image;
import com.ni.vision.NIVision.ImageType;
public class HSLColorThresholdOperator
implements VisionOperatorInterface
{
private final NIVision.Range hueRange;
private final NIVision.Range satRange;
private final NIVision.Range lumRange;
public HSLColorThresholdOperator (int hueMin, int hueMax, int satMin,
int satMax, int luminanceMin, int luminanceMax)
{
hueRange = new NIVision.Range(hueMin, hueMax);
satRange = new NIVision.Range(satMin, satMax);
lumRange = new NIVision.Range(luminanceMin, luminanceMax);
}
public HSLColorThresholdOperator (NIVision.Range hueRange,
NIVision.Range satRange, NIVision.Range lumRange)
{
this.hueRange = hueRange;
this.satRange = satRange;
this.lumRange = lumRange;
}
@Override
public Image operate (Image source)
{
// Creating new monocolor image with no border
final Image thresholdImage = NIVision
.imaqCreateImage(ImageType.IMAGE_U8, 0);
// @TODO: Store NIVision.Range instead of integers so we don't make a
// new one every time.
NIVision.imaqColorThreshold(thresholdImage, source, 255,
NIVision.ColorMode.HSL, this.hueRange, this.satRange,
this.lumRange);
source.free();
return thresholdImage;
}
}
| mit |
tochyvn/aeafm-project | resources/views/domaine/edit.blade.php | 763 | @extends("admin/admin")
@section('contentAdmin')
<div class="large-12 medium-12 columns contentAdmin" >
<div class="Formclass large-5 medium-12 columns">
<h4> editer le domaine {{$domaine->name}} </h4>
@if (Session::has('success'))
<span class="help-block success">
<strong>{{ Session::get('success')}}</strong>
</span>
@endif
{!! Form::open(array('method'=>'put' ,'url' => route('domaine.update',$domaine))) !!}
<div class="form-group">
{!! Form::label('Domaine name', 'name') !!}
{!! Form::text('name',$domaine->name, ['class'=>'form-control']) !!}
</div>
<button class="btn btn-primary">Envoiyer</button>
{!! Form::close() !!}
</div>
</div>
@endsection | mit |
EasyExpress/Easylink | Utilities/Encryptor.cs | 2586 | using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
namespace Utilities
{
public class Encryptor
{
private static byte[] _key;
private static byte[] _iv;
public static Encryptor CreateEncryptorA()
{
return new Encryptor("AdfwR4$128jK");
}
public static Encryptor CreateEncryptorB()
{
return new Encryptor("OKZXR4!128jG");
}
private Encryptor(string encryptionKey)
{
var salt= Encoding.ASCII.GetBytes(encryptionKey);
var keyGenerator = new Rfc2898DeriveBytes(encryptionKey, salt);
_key = keyGenerator.GetBytes(32);
_iv = keyGenerator.GetBytes(16);
}
public string Encrypt(string text)
{
var rijndaelCipher = new RijndaelManaged { Key = _key, IV = _iv };
byte[] plainText = Encoding.Unicode.GetBytes(text);
using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor())
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}
public string Decrypt(string encrypted)
{
var rijndaelCipher = new RijndaelManaged();
byte[] encryptedData = Convert.FromBase64String(encrypted);
using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(_key, _iv))
{
using (var memoryStream = new MemoryStream(encryptedData))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainText = new byte[encryptedData.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
}
}
}
}
}
}
| mit |
EasyExpress/Easylink | Easylink.Tests/SearchPostgreSqlTest.cs | 5445 | using Easylink.Tests.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Easylink.Tests
{
[TestClass]
public class SearchPostgreSqlTest : SearchTest
{
[TestInitialize]
public void Test_Initialization()
{
DatabaseFactory.Initialize(
new DbConfig()
{
ConnectionString =
"Server=localhost;Port=5432;Database=Easylink;Pooling =false; User Id=postgres;Password=1197344;",
DatabaseType = DatabaseType.PostgreSql,
SchemaName = "public",
AuditRecordType =typeof(AuditRecord)
});
database = DatabaseFactory.Create();
Mapping.SetNextId<Employee>(NextIdOption.Sequence, "employee_seq");
Mapping.SetNextId<Program>(NextIdOption.Sequence, "program_seq");
Mapping.SetNextId<EmployeeProgram>(NextIdOption.Sequence, "employee_program_seq");
Mapping.SetNextId<Address>(NextIdOption.Sequence, "address_seq");
Mapping.SetNextId<FinancialInfo>(NextIdOption.Sequence, "financial_info_seq");
Mapping.SetNextId<AdditionalInfo>(NextIdOption.Sequence, "additional_info_seq");
Mapping.SetNextId<Lookup>(NextIdOption.Sequence, "lookup_seq");
Mapping.SetNextId<AuditRecord>(NextIdOption.Sequence, "audit_seq");
}
[TestMethod]
public void postgreSql_server_employee_search_all()
{
employee_search_all();
}
[TestMethod]
public void postgreSql_employee_search_by_equal_id()
{
employee_search_by_equal_id();
}
[TestMethod]
public void postgreSql_employee_search_by_equal_identifier()
{
employee_search_by_equal_identifier();
}
[TestMethod]
public void postgreSql_employee_search_by_multiple_conditions()
{
employee_search_by_multiple_conditions();
}
[TestMethod]
public void postgreSql_employee_search_by_not_equal_id()
{
employee_search_by_not_equal_id();
}
[TestMethod]
public void postgreSql_employee_search_by_equal_date()
{
employee_search_by_equal_date();
}
[TestMethod]
public void postgreSql_employee_search_by_not_equal_date()
{
employee_search_by_not_equal_date();
}
[TestMethod]
public void postgreSql_employee_search_by_greater_date()
{
employee_search_by_greater_date();
}
[TestMethod]
public void postgreSql_employee_search_by_less_date()
{
employee_search_by_less_date();
}
[TestMethod]
public void postgreSql_employee_search_by_equal_bool()
{
employee_search_by_equal_bool();
}
[TestMethod]
public void postgreSql_employee_search_by_not_equal_bool()
{
employee_search_by_not_equal_bool();
}
[TestMethod]
public void postgreSql_employee_search_by_equal_decimal()
{
employee_search_by_equal_decimal();
}
[TestMethod]
public void postgreSql_employee_search_by_not_equal_decimal()
{
employee_search_by_not_equal_decimal();
}
[TestMethod]
public void postgreSql_employee_search_by_greater_decimal()
{
employee_search_by_greater_decimal();
}
[TestMethod]
public void postgreSql_employee_search_by_less_decimal()
{
employee_search_by_less_decimal();
}
[TestMethod]
public void postgreSql_employee_search_by_equal_text()
{
employee_search_by_equal_text();
}
[TestMethod]
public void postgreSql_employee_search_by_not_equal_text()
{
employee_search_by_not_equal_text();
}
[TestMethod]
public void postgreSql_employee_search_by_startswith_text()
{
employee_search_by_starts_with_text();
}
[TestMethod]
public void postgreSql_employee_search_by_endswith_text()
{
employee_search_by_endswith_text();
}
[TestMethod]
public void postgreSql_employee_search_by_contains_text()
{
employee_search_by_contains_text();
}
[TestMethod]
public void postgreSql_employee_search_by_contains_text_case_sensitive()
{
employee_search_by_contains_text_case_sensitive();
}
[TestMethod]
public void postgreSql_employee_search_by_in_list()
{
employee_search_by_in_list();
}
[TestMethod]
public void postgreSql_employee_search_by_role_name()
{
employee_search_by_role_name();
}
[TestMethod]
public void postgreSql_employee_search_by_country()
{
employee_search_by_country();
}
}
} | mit |
isudzumi/playSound | playSound/App.xaml.cs | 1668 | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Threading;
namespace playSound
{
using System.Windows;
/// <summary>
/// App.xaml の相互作用ロジック
/// </summary>
public partial class App : Application
{
///<summary>
///タスクトレイに表示するアイコン
///</summary>
private NotifyIconWrapper notifyIcon;
///<summary>
///System.Windows.Application.Startupイベントを発生させる
///</summary>
protected override void OnStartup(StartupEventArgs e)
{
//多重起動チェック
App._mutex = new Mutex(false, "playSound");
if(!App._mutex.WaitOne(0, false))
{
App._mutex.Close();
App._mutex = null;
this.Shutdown();
return;
}
base.OnStartup(e);
this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
this.notifyIcon = new NotifyIconWrapper();
}
///<summary>
///System.Windows.Application.Exitイベントを発生させる
/// </summary>
protected override void OnExit(ExitEventArgs e)
{
if (App._mutex == null)
{
return;
}
App._mutex.ReleaseMutex();
App._mutex.Close();
App._mutex = null;
base.OnExit(e);
this.notifyIcon.Dispose();
}
private static Mutex _mutex;
}
}
| mit |
yoship1639/Scanner | ScannerTestForm/Properties/AssemblyInfo.cs | 1406 | 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("ScannerTestForm")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ScannerTestForm")]
[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("1d8e4678-d195-45ad-833d-025463e3a941")]
// 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 |
brucewar/poem | Infrastructure/BackEnd/node_modules/orm/lib/Instance.js | 17161 | var Property = require("./Property");
var Hook = require("./Hook");
var enforce = require("enforce");
exports.Instance = Instance;
function Instance(Model, opts) {
opts = opts || {};
opts.data = opts.data || {};
opts.extra = opts.extra || {};
opts.id = opts.id || "id";
opts.changes = (opts.is_new ? Object.keys(opts.data) : []);
opts.extrachanges = [];
var instance_saving = false;
var events = {};
var instance = {};
var emitEvent = function () {
var args = Array.prototype.slice.apply(arguments);
var event = args.shift();
if (!events.hasOwnProperty(event)) return;
events[event].map(function (cb) {
cb.apply(instance, args);
});
};
var handleValidations = function (cb) {
var pending = [], errors = [], required;
Hook.wait(instance, opts.hooks.beforeValidation, function (err) {
var k, i;
if (err) {
return saveError(cb, err);
}
for (i = 0; i < opts.one_associations.length; i++) {
for (k in opts.one_associations[i].field) {
if (opts.one_associations[i].required && opts.data[k] === null) {
var err = new Error("Property required");
err.field = k;
err.value = opts.data[k];
err.msg = "Property required";
err.type = "validation";
err.model = Model.table;
if (!Model.settings.get("instance.returnAllErrors")) {
return cb(err);
}
errors.push(err);
}
}
}
var checks = new enforce.Enforce({
returnAllErrors : Model.settings.get("instance.returnAllErrors")
});
for (k in opts.validations) {
required = false;
if (Model.properties[k]) {
required = Model.properties[k].required;
} else {
for (i = 0; i < opts.one_associations.length; i++) {
if (opts.one_associations[i].field === k) {
required = opts.one_associations[i].required;
break;
}
}
}
if (!required && instance[k] == null) {
continue; // avoid validating if property is not required and is "empty"
}
for (i = 0; i < opts.validations[k].length; i++) {
checks.add(k, opts.validations[k][i]);
}
}
checks.context("instance", instance);
checks.context("model", Model);
checks.context("driver", opts.driver);
return checks.check(instance, cb);
});
};
var saveError = function (cb, err) {
instance_saving = false;
emitEvent("save", err, instance);
Hook.trigger(instance, opts.hooks.afterSave, false);
if (typeof cb === "function") {
cb(err, instance);
}
};
var saveInstance = function (cb, saveOptions) {
// what this condition means:
// - If the instance is in state mode
// - AND it's not an association that is asking it to save
// -> return has already saved
if (instance_saving && !(saveOptions.saveAssociations === false)) {
return cb(null, instance);
}
instance_saving = true;
handleValidations(function (err) {
if (err) {
return saveError(cb, err);
}
if (opts.is_new) {
waitHooks([ "beforeCreate", "beforeSave" ], function (err) {
if (err) {
return saveError(cb, err);
}
return saveNew(cb, saveOptions, getInstanceData());
});
} else {
waitHooks([ "beforeSave" ], function (err) {
if (err) {
return saveError(cb, err);
}
if (opts.changes.length === 0) {
if (saveOptions.saveAssociations === false) {
return saveInstanceExtra(cb);
}
return saveAssociations(function (err) {
return afterSave(cb, false, err);
});
}
return savePersisted(cb, saveOptions, getInstanceData());
});
}
});
};
var afterSave = function (cb, create, err) {
instance_saving = false;
emitEvent("save", err, instance);
if (create) {
Hook.trigger(instance, opts.hooks.afterCreate, !err);
}
Hook.trigger(instance, opts.hooks.afterSave, !err);
if (!err) {
saveInstanceExtra(cb);
}
};
var getInstanceData = function () {
var data = {}, prop;
for (var k in opts.data) {
if (!opts.data.hasOwnProperty(k)) continue;
prop = Model.allProperties[k];
if (prop) {
if (prop.type === 'serial' && opts.data[k] == null) continue;
data[k] = Property.validate(opts.data[k], prop);
if (opts.driver.propertyToValue) {
data[k] = opts.driver.propertyToValue(data[k], prop);
}
} else {
data[k] = opts.data[k];
}
}
return data;
};
var waitHooks = function (hooks, next) {
var nextHook = function () {
if (hooks.length === 0) {
return next();
}
Hook.wait(instance, opts.hooks[hooks.shift()], function (err) {
if (err) {
return next(err);
}
return nextHook();
});
};
return nextHook();
};
var saveNew = function (cb, saveOptions, data) {
var next = afterSave.bind(this, cb, true);
opts.driver.insert(opts.table, data, opts.id, function (save_err, info) {
if (save_err) {
return saveError(cb, save_err);
}
opts.changes.length = 0;
for (var i = 0; i < opts.id.length; i++) {
opts.data[opts.id[i]] = info.hasOwnProperty(opts.id[i]) ? info[opts.id[i]] : data[opts.id[i]];
}
opts.is_new = false;
if (saveOptions.saveAssociations === false) {
return next();
}
return saveAssociations(next);
});
};
var savePersisted = function (cb, saveOptions, data) {
var next = afterSave.bind(this, cb, false);
var changes = {}, conditions = {};
for (var i = 0; i < opts.changes.length; i++) {
changes[opts.changes[i]] = data[opts.changes[i]];
}
for (i = 0; i < opts.id.length; i++) {
conditions[opts.id[i]] = data[opts.id[i]];
}
opts.driver.update(opts.table, changes, conditions, function (save_err) {
if (save_err) {
return saveError(cb, save_err);
}
opts.changes.length = 0;
if (saveOptions.saveAssociations === false) {
return next();
}
return saveAssociations(next);
});
};
var saveAssociations = function (cb) {
var pending = 1, errored = false, i, j;
var saveAssociation = function (accessor, instances) {
pending += 1;
instance[accessor](instances, function (err) {
if (err) {
if (errored) return;
errored = true;
return cb(err);
}
if (--pending === 0) {
return cb();
}
});
};
var _saveOneAssociation = function (assoc) {
if (!instance[assoc.name] || typeof instance[assoc.name] !== "object") return;
if (assoc.reversed) {
// reversed hasOne associations should behave like hasMany
if (!Array.isArray(instance[assoc.name])) {
instance[assoc.name] = [ instance[assoc.name] ];
}
for (var i = 0; i < instance[assoc.name].length; i++) {
if (!instance[assoc.name][i].isInstance) {
instance[assoc.name][i] = new assoc.model(instance[assoc.name][i]);
}
saveAssociation(assoc.setAccessor, instance[assoc.name][i]);
}
return;
}
if (!instance[assoc.name].isInstance) {
instance[assoc.name] = new assoc.model(instance[assoc.name]);
}
saveAssociation(assoc.setAccessor, instance[assoc.name]);
};
for (i = 0; i < opts.one_associations.length; i++) {
_saveOneAssociation(opts.one_associations[i]);
}
var _saveManyAssociation = function (assoc) {
if (!instance.hasOwnProperty(assoc.name)) return;
if (!Array.isArray(instance[assoc.name])) {
instance[assoc.name] = [ instance[assoc.name] ];
}
for (j = 0; j < instance[assoc.name].length; j++) {
if (!instance[assoc.name][j].isInstance) {
instance[assoc.name][j] = new assoc.model(instance[assoc.name][j]);
}
}
return saveAssociation(assoc.setAccessor, instance[assoc.name]);
};
for (i = 0; i < opts.many_associations.length; i++) {
_saveManyAssociation(opts.many_associations[i]);
}
if (--pending === 0) {
return cb();
}
};
var saveInstanceExtra = function (cb) {
if (opts.extrachanges.length === 0) {
if (cb) return cb(null, instance);
else return;
}
var data = {};
var conditions = {};
for (var i = 0; i < opts.extrachanges.length; i++) {
if (!opts.data.hasOwnProperty(opts.extrachanges[i])) continue;
if (opts.extra[opts.extrachanges[i]]) {
data[opts.extrachanges[i]] = Property.validate(opts.data[opts.extrachanges[i]], opts.extra[opts.extrachanges[i]]);
if (opts.driver.propertyToValue) {
data[opts.extrachanges[i]] = opts.driver.propertyToValue(data[opts.extrachanges[i]], opts.extra[opts.extrachanges[i]]);
}
} else {
data[opts.extrachanges[i]] = opts.data[opts.extrachanges[i]];
}
}
for (i = 0; i < opts.extra_info.id.length; i++) {
conditions[opts.extra_info.id_prop[i]] = opts.extra_info.id[i];
conditions[opts.extra_info.assoc_prop[i]] = opts.data[opts.id[i]];
}
opts.driver.update(opts.extra_info.table, data, conditions, function (err) {
if (cb) return cb(err, instance);
});
};
var removeInstance = function (cb) {
if (opts.is_new) {
return cb(null);
}
var conditions = {};
for (var i = 0; i < opts.id.length; i++) {
conditions[opts.id[i]] = opts.data[opts.id[i]];
}
Hook.wait(instance, opts.hooks.beforeRemove, function (err) {
if (err) {
emitEvent("remove", err, instance);
if (typeof cb === "function") {
cb(err, instance);
}
return;
}
emitEvent("beforeRemove", instance);
opts.driver.remove(opts.table, conditions, function (err, data) {
Hook.trigger(instance, opts.hooks.afterRemove, !err);
emitEvent("remove", err, instance);
if (typeof cb === "function") {
cb(err, instance);
}
instance = undefined;
});
});
};
var saveInstanceProperty = function (key, value) {
var changes = {}, conditions = {};
changes[key] = value;
if (Model.properties[key]) {
changes[key] = Property.validate(changes[key], Model.properties[key]);
if (opts.driver.propertyToValue) {
changes[key] = opts.driver.propertyToValue(changes[key], Model.properties[key]);
}
}
for (var i = 0; i < opts.id.length; i++) {
conditions[opts.id[i]] = opts.data[opts.id[i]];
}
Hook.wait(instance, opts.hooks.beforeSave, function (err) {
if (err) {
Hook.trigger(instance, opts.hooks.afterSave, false);
emitEvent("save", err, instance);
return;
}
opts.driver.update(opts.table, changes, conditions, function (err) {
if (!err) {
opts.data[key] = value;
}
Hook.trigger(instance, opts.hooks.afterSave, !err);
emitEvent("save", err, instance);
});
});
};
var setInstanceProperty = function (key, value) {
var prop = Model.allProperties[key] || opts.extra[key];
if (prop) {
if ('valueToProperty' in opts.driver) {
value = opts.driver.valueToProperty(value, prop);
}
if (opts.data[key] !== value) {
opts.data[key] = value;
return true;
}
}
return false;
}
var addInstanceProperty = function (key) {
var defaultValue = null;
var prop = Model.allProperties[key];
// This code was first added, and then commented out in a later commit.
// Its presence doesn't affect tests, so I'm just gonna log if it ever gets called.
// If someone complains about noise, we know it does something, and figure it out then.
if (instance.hasOwnProperty(key)) console.log("Overwriting instance property");
if (key in opts.data) {
defaultValue = opts.data[key];
} else if (prop && 'defaultValue' in prop) {
defaultValue = prop.defaultValue;
}
setInstanceProperty(key, defaultValue);
Object.defineProperty(instance, key, {
get: function () {
return opts.data[key];
},
set: function (val) {
if (Model.allProperties[key].key === true && opts.data[key] != null) {
return;
}
if (!setInstanceProperty(key, val)) {
return;
}
if (opts.autoSave) {
saveInstanceProperty(key, val);
} else if (opts.changes.indexOf(key) === -1) {
opts.changes.push(key);
}
},
enumerable: true
});
};
var addInstanceExtraProperty = function (key) {
if (!instance.hasOwnProperty("extra")) {
instance.extra = {};
}
Object.defineProperty(instance.extra, key, {
get: function () {
return opts.data[key];
},
set: function (val) {
setInstanceProperty(key, val);
/*if (opts.autoSave) {
saveInstanceProperty(key, val);
}*/if (opts.extrachanges.indexOf(key) === -1) {
opts.extrachanges.push(key);
}
},
enumerable: true
});
};
var i, k;
for (k in Model.allProperties) {
addInstanceProperty(k);
}
for (k in opts.extra) {
addInstanceProperty(k);
}
for (k in opts.methods) {
Object.defineProperty(instance, k, {
value : opts.methods[k].bind(instance),
enumerable : false,
writeable : true
});
}
for (k in opts.extra) {
addInstanceExtraProperty(k);
}
Object.defineProperty(instance, "on", {
value: function (event, cb) {
if (!events.hasOwnProperty(event)) {
events[event] = [];
}
events[event].push(cb);
return this;
},
enumerable: false
});
Object.defineProperty(instance, "save", {
value: function () {
var arg = null, objCount = 0;
var data = {}, saveOptions = {}, callback = null;
while (arguments.length > 0) {
arg = Array.prototype.shift.call(arguments);
switch (typeof arg) {
case 'object':
switch (objCount) {
case 0:
data = arg;
break;
case 1:
saveOptions = arg;
break;
}
objCount++;
break;
case 'function':
callback = arg;
break;
default:
var err = new Error("Unknown parameter type '" + (typeof arg) + "' in Instance.save()");
err.model = Model.table;
throw err;
}
}
for (var k in data) {
if (data.hasOwnProperty(k)) {
this[k] = data[k];
}
}
saveInstance(callback, saveOptions);
return this;
},
enumerable: false
});
Object.defineProperty(instance, "saved", {
value: function () {
return opts.changes.length === 0;
},
enumerable: false
});
Object.defineProperty(instance, "remove", {
value: function (cb) {
removeInstance(cb);
return this;
},
enumerable: false
});
Object.defineProperty(instance, "isInstance", {
value: true,
enumerable: false
});
Object.defineProperty(instance, "isPersisted", {
value: function () {
return !opts.is_new;
},
enumerable: false
});
Object.defineProperty(instance, "isShell", {
value: function () {
return opts.isShell;
},
enumerable: false
});
Object.defineProperty(instance, "validate", {
value: function (cb) {
handleValidations(function (errors) {
cb(null, errors || false);
});
},
enumerable: false
});
Object.defineProperty(instance, "__singleton_uid", {
value: function (cb) {
return opts.uid;
},
enumerable: false
});
Object.defineProperty(instance, "model", {
value: function (cb) {
return Model;
},
enumerable: false
});
for (i = 0; i < opts.id.length; i++) {
if (!opts.data.hasOwnProperty(opts.id[i])) {
opts.changes = Object.keys(opts.data);
break;
}
}
for (i = 0; i < opts.one_associations.length; i++) {
var asc = opts.one_associations[i];
if (!asc.reversed && !asc.extension) {
for (k in opts.one_associations[i].field) {
if (!opts.data.hasOwnProperty(k)) {
addInstanceProperty(k);
}
}
}
if (opts.data.hasOwnProperty(asc.name)) {
if (opts.data[asc.name] instanceof Object) {
if (opts.data[asc.name].isInstance) {
instance[asc.name] = opts.data[asc.name];
} else {
var instanceInit = {};
var usedChance = false;
for (k in opts.one_associations[i].id) {
if (!data.hasOwnProperty(k) && !usedChance) {
instanceInit[k] = opts.data[asc.name];
usedChance = true;
} else {
instanceInit[k] = opts.data[k];
}
}
instance[asc.name] = new opts.one_associations[i].model(instanceInit);
}
}
delete opts.data[asc.name];
}
}
for (i = 0; i < opts.many_associations.length; i++) {
if (opts.data.hasOwnProperty(opts.many_associations[i].name)) {
instance[opts.many_associations[i].name] = opts.data[opts.many_associations[i].name];
delete opts.data[opts.many_associations[i].name];
}
}
Hook.wait(instance, opts.hooks.afterLoad, function (err) {
process.nextTick(function () {
emitEvent("ready", err);
});
});
return instance;
}
| mit |
aidiss/disciplines | disciplines/theory/biglan.py | 3158 | # -*- coding: utf-8 -*-
"""
Biglans classification
This can be used for machine learning.
3 dimensions are investigated by Biglan:
pure - applied
hard - soft
life - non-life
"""
author = 'Biglan'
authors = author
concepts = []
data = []
claim = []
theory = '''
'''
approach = ''
reading = '''
1. Ruth Neumann, Disciplinarity, In Tight Malcolm, Ka Ho Mok, Jeroen Huisman, Christopher C. Morphew (Ed.), The Rutledge International Handbook of Higher Education, Routledge, USA, pp 487-500, 2009.
2. Yonghong Jade Xu, Faculty Turnover: Discipline-Specific Attention is Warranted, Res earsch in High Educ ation. Springer, Vol. 49, pp 40–61, Feb 2008.
3. Matthew Kwok, Disciplinary Differences in the Development of Employability Skills of Recent University Graduates in Manitoba: Some Initial Findings. Higher Education Perspectives, volume 1, issue 1, pp.60-77, 2004.
4. Biglan, A., The characteristics of subject matter in academic areas, Journal of Applied Psychology, 57, 195–203, 1973.
5. Malaney, G. D., Differentiation in graduate education, Research in Higher Education, 25(1), pp 82–96, 1986.
6. Design of Interventions for Instructional Reform in Software Development Education for Competency Enhancement: Summary of PhD Thesis
7. Assess Your Curriculum and Courses Using Harden’s Taxonomy of Curriculum Integration
8. Software Development Education: Breadth Courses for Developing Domain Competence and Systems Thinking
'''
urls = 'http://goelsan.wordpress.com/2010/07/27/biglans-classification-of-disciplines/'
further = [
'http://cpr.iub.edu/uploads/AACU2008Tables.pdf',
'Effective Educational Practices and Essential Learning Outcomes in General Education Courses: Differences by Discipline']
the_classification = [
[['Biology', 'Biochemistry', 'Genetics', 'Physiology'], {'pure':True, 'hard':True, 'life':True}],
[['Mathematics', 'Physics', 'Chemistry', 'Geology', 'Astronomy', 'Oceanography'], {'pure':True, 'hard':True, 'life':False}],
[['Psychology', 'Sociology', 'Anthropology', 'Political Science', 'Area Study'], {'pure':True, 'hard':False, 'life':True}],
[['Linguistics', 'Literature', 'Communications', 'Creative Writing', 'Economics', 'Philosophy', 'Archaeology', 'History', 'Geography'], {'pure':True, 'hard':False, 'life':True}],
[['Agriculture', 'Psychiatry', 'Medicine', 'Pharmacy', 'Dentistry', 'Horticulture'], {'pure':False, 'hard':True, 'life':True}],
[['Civil Engineering', 'Telecommunication Engineering', 'Mechanical Engineering', 'Chemical Engineering', 'Electrical Engineering', 'Computer science'], {'pure':False, 'hard':True, 'life':False}],
[['Recreation', 'Arts', 'Education', 'Nursing', 'Conservation', 'Counseling', 'HR Management'], {'pure':False, 'hard':False, 'life':True}],
[['Finance', 'Accounting', 'Banking', 'Marketing', 'Journalism', 'Library And Archival Science', 'Law', 'Architecture', 'Interior Design', 'Crafts', 'Arts', 'Dance', 'Music'], {'pure':False, 'hard':False, 'life':False}]
]
#it is interesting that he himself does outline "etc." what doe 'etc' mean here?
#notebook should contain link to the table itself | mit |
jdanyow/aurelia-breeze-sample | jspm_packages/npm/[email protected]/test/constructor.js | 3805 | /* */
(function(process) {
var B = require("../../[email protected]").Buffer;
var test = require("tape");
if (process.env.OBJECT_IMPL)
B.TYPED_ARRAY_SUPPORT = false;
test('new buffer from array', function(t) {
t.equal(new B([1, 2, 3]).toString(), '\u0001\u0002\u0003');
t.end();
});
test('new buffer from array w/ negatives', function(t) {
t.equal(new B([-1, -2, -3]).toString('hex'), 'fffefd');
t.end();
});
test('new buffer from array with mixed signed input', function(t) {
t.equal(new B([-255, 255, -128, 128, 512, -512, 511, -511]).toString('hex'), '01ff80800000ff01');
t.end();
});
test('new buffer from string', function(t) {
t.equal(new B('hey', 'utf8').toString(), 'hey');
t.end();
});
test('new buffer from buffer', function(t) {
var b1 = new B('asdf');
var b2 = new B(b1);
t.equal(b1.toString('hex'), b2.toString('hex'));
t.end();
});
test('new buffer from Uint8Array', function(t) {
if (typeof Uint8Array !== 'undefined') {
var b1 = new Uint8Array([0, 1, 2, 3]);
var b2 = new B(b1);
t.equal(b1.length, b2.length);
t.equal(b1[0], 0);
t.equal(b1[1], 1);
t.equal(b1[2], 2);
t.equal(b1[3], 3);
t.equal(b1[4], undefined);
}
t.end();
});
test('new buffer from Uint16Array', function(t) {
if (typeof Uint16Array !== 'undefined') {
var b1 = new Uint16Array([0, 1, 2, 3]);
var b2 = new B(b1);
t.equal(b1.length, b2.length);
t.equal(b1[0], 0);
t.equal(b1[1], 1);
t.equal(b1[2], 2);
t.equal(b1[3], 3);
t.equal(b1[4], undefined);
}
t.end();
});
test('new buffer from Uint32Array', function(t) {
if (typeof Uint32Array !== 'undefined') {
var b1 = new Uint32Array([0, 1, 2, 3]);
var b2 = new B(b1);
t.equal(b1.length, b2.length);
t.equal(b1[0], 0);
t.equal(b1[1], 1);
t.equal(b1[2], 2);
t.equal(b1[3], 3);
t.equal(b1[4], undefined);
}
t.end();
});
test('new buffer from Int16Array', function(t) {
if (typeof Int16Array !== 'undefined') {
var b1 = new Int16Array([0, 1, 2, 3]);
var b2 = new B(b1);
t.equal(b1.length, b2.length);
t.equal(b1[0], 0);
t.equal(b1[1], 1);
t.equal(b1[2], 2);
t.equal(b1[3], 3);
t.equal(b1[4], undefined);
}
t.end();
});
test('new buffer from Int32Array', function(t) {
if (typeof Int32Array !== 'undefined') {
var b1 = new Int32Array([0, 1, 2, 3]);
var b2 = new B(b1);
t.equal(b1.length, b2.length);
t.equal(b1[0], 0);
t.equal(b1[1], 1);
t.equal(b1[2], 2);
t.equal(b1[3], 3);
t.equal(b1[4], undefined);
}
t.end();
});
test('new buffer from Float32Array', function(t) {
if (typeof Float32Array !== 'undefined') {
var b1 = new Float32Array([0, 1, 2, 3]);
var b2 = new B(b1);
t.equal(b1.length, b2.length);
t.equal(b1[0], 0);
t.equal(b1[1], 1);
t.equal(b1[2], 2);
t.equal(b1[3], 3);
t.equal(b1[4], undefined);
}
t.end();
});
test('new buffer from Float64Array', function(t) {
if (typeof Float64Array !== 'undefined') {
var b1 = new Float64Array([0, 1, 2, 3]);
var b2 = new B(b1);
t.equal(b1.length, b2.length);
t.equal(b1[0], 0);
t.equal(b1[1], 1);
t.equal(b1[2], 2);
t.equal(b1[3], 3);
t.equal(b1[4], undefined);
}
t.end();
});
test('new buffer from buffer.toJSON() output', function(t) {
if (typeof JSON === 'undefined') {
t.end();
return ;
}
var buf = new B('test');
var json = JSON.stringify(buf);
var obj = JSON.parse(json);
var copy = new B(obj);
t.ok(buf.equals(copy));
t.end();
});
})(require("process"));
| mit |
jxm262/btc-stats | lib/btc-stats.js | 5143 | "use strict";
var xchange = require("xchange.js")
,async = require("async")
,config = require("../config.js");
function BtcStats(exchanges){
this.exchanges(exchanges);
}
BtcStats.prototype.exchanges = function(excs) {
excs = excs || config.defaultExchanges;
this._exchanges = excs.reduce(function(exchange, name, idx){
exchange[name] = xchange[name].ticker;
return exchange;
}, {});
};
function tickersResp(callback) {
async.map(Object.keys(this._exchanges), function(item, cb){
xchange[item].ticker(function(error, resp){
if (error || !resp) {
return cb(error, null);
} else if(resp) {
resp.ticker = item;
return cb(error, resp);
} else {
return cb(error, null);
}
});
}, callback);
}
function midpoint(a) {
var ask = a.ask ? a.ask : 0;
var bid = a.bid ? a.bid : 0;
return (ask + bid) / 2;
}
BtcStats.prototype.avg = function(callback) {
tickersResp.call(this, function(err, resp){
if(err && !resp) callback(err,null)
if(!err && !resp) callback(null, null)
var res = resp.reduce(function(a, b){
return {
price: (a && b) ? a.price + midpoint(b): 0
};
}, {price: 0});
res.price = (res.price / resp.length).toFixed(2);
callback(null, res);
});
};
BtcStats.prototype.weightedAvg = function(callback) {
tickersResp.call(this, function(err, resp){
if(err){
callback(err);
} else {
var totalVol = resp.reduce(function(a, b){
return a + ((b.volume) ? b.volume : 0);
}, 0);
var res = resp.reduce(function(a, b){
return {
price: a.price + midpoint(b) * ((b.volume) ? b.volume : 0) / totalVol
};
}, {price: 0});
res.price = (res.price).toFixed(2);
callback(null, res);
}
});
};
BtcStats.prototype.min = function(callback) {
tickersResp.call(this, function(err, resp){
if(err){
callback(err);
} else {
var min = resp.reduce(function(a, b){
return (midpoint(a) < midpoint(b)) ? a : b;
});
callback(null, {price: midpoint(min).toFixed(2), exchange: min.ticker});
}
});
};
BtcStats.prototype.max = function(callback) {
tickersResp.call(this, function(err, resp){
if(err){
callback(err);
} else {
var max = resp.reduce(function(a, b){
return (midpoint(a) > midpoint(b)) ? a : b;
});
callback(null, {price: midpoint(max).toFixed(2), exchange: max.ticker});
}
});
};
BtcStats.prototype.minVolume = function(callback) {
tickersResp.call(this, function(err, resp){
if(err){
callback(err);
} else {
var min = resp.reduce(function(a, b){
return (a.volume < b.volume) ? a : b;
});
callback(null, {volume: (min.volume).toFixed(2), exchange: min.ticker});
}
});
};
BtcStats.prototype.maxVolume = function(callback) {
tickersResp.call(this, function(err, resp){
if(err){
callback(err);
} else {
var max = resp.reduce(function(a, b){
return (a.volume > b.volume) ? a : b;
});
callback(null, {volume: (max.volume).toFixed(2), exchange: max.ticker});
}
});
};
BtcStats.prototype.maxSpread = function(callback) {
tickersResp.call(this, function(err, resp){
if(err){
callback(err);
} else {
var min = resp.reduce(function(a, b){
return (a.bid < b.bid) ? a : b;
});
var max = resp.reduce(function(a, b){
return (a.ask > b.ask) ? a : b;
});
var spread = {spread: (max.ask - min.bid).toFixed(2),
bid: min.bid,
ask: max.ask,
bidExchange: min.ticker,
askExchange: max.ticker};
callback(null, spread);
}
});
};
BtcStats.prototype.minSpread = function(callback) {
tickersResp.call(this, function(err, resp){
if(err){
callback(err);
} else {
var max = resp.reduce(function(a, b){
return (a.bid > b.bid) ? a : b;
});
var min = resp.reduce(function(a, b){
return (a.ask < b.ask) ? a : b;
});
var spread = {spread: (min.ask - max.bid).toFixed(2),
bid: max.bid,
ask: min.ask,
bidExchange: max.ticker,
askExchange: min.ticker};
callback(null, spread);
}
});
};
BtcStats.prototype.exchangeMaxSpread = function(callback) {
tickersResp.call(this, function(err, resp){
if(err){
callback(err);
} else {
var max = resp.reduce(function(a, b){
return ((a.ask - a.bid) > (b.ask - b.bid)) ? a : b;
});
var spread = {spread: (max.ask - max.bid).toFixed(2),
bid: max.bid,
ask: max.ask,
exchange: max.ticker};
callback(null, spread);
}
});
};
BtcStats.prototype.exchangeMinSpread = function(callback) {
tickersResp.call(this, function(err, resp){
if(err){
callback(err);
} else {
var min = resp.reduce(function(a, b){
return ((a.ask - a.bid) < (b.ask - b.bid)) ? a : b;
});
var spread = {spread: (min.ask - min.bid).toFixed(2),
bid: min.bid,
ask: min.ask,
exchange: min.ticker};
callback(null, spread);
}
});
};
module.exports = new BtcStats();
| mit |
Aprogiena/StratisBitcoinFullNode | src/Stratis.SmartContracts.CLR/SmartContractState.cs | 1624 | using System;
namespace Stratis.SmartContracts.CLR
{
/// <summary>
/// Smart contract state that gets injected into the smart contract by the <see cref="ReflectionVirtualMachine"/>.
/// </summary>
public sealed class SmartContractState : ISmartContractState
{
public SmartContractState(
IBlock block,
IMessage message,
IPersistentState persistentState,
ISerializer serializer,
IGasMeter gasMeter,
IContractLogger contractLogger,
IInternalTransactionExecutor internalTransactionExecutor,
IInternalHashHelper internalHashHelper,
Func<ulong> getBalance)
{
this.Block = block;
this.Message = message;
this.PersistentState = persistentState;
this.Serializer = serializer;
this.GasMeter = gasMeter;
this.ContractLogger = contractLogger;
this.InternalTransactionExecutor = internalTransactionExecutor;
this.InternalHashHelper = internalHashHelper;
this.GetBalance = getBalance;
}
public IBlock Block { get; }
public IMessage Message { get; }
public IPersistentState PersistentState { get; }
public ISerializer Serializer { get; }
public IGasMeter GasMeter { get; }
public IContractLogger ContractLogger { get; }
public IInternalTransactionExecutor InternalTransactionExecutor { get; }
public IInternalHashHelper InternalHashHelper { get; }
public Func<ulong> GetBalance { get; }
}
} | mit |
jimmyz/fs-familytree-v1 | lib/communicator.rb | 864 | require 'fs_communicator'
module FsFamilytreeV1
# This method gets mixed into the FsCommunicator so that
# you can make calls on the fs_familytree_v1 module
def fs_familytree_v1
@com ||= Communicator.new self # self at this point refers to the FsCommunicator instance
end
class Communicator
Base = '/familytree/v1/'
# ==params
# fs_communicator: FsCommunicator instance
def initialize(fs_communicator)
@fs_communicator = fs_communicator
end
def person(id, options = {})
url = Base + 'person/' + id
response = @fs_communicator.get(url)
familytree = Familytree.parse response.body
person = familytree.persons.person.find{|p| p.requestedId == id }
end
end
end
# Mix in the module so that the fs_familytree_v1 can be called
class FsCommunicator
include FsFamilytreeV1
end | mit |
symmetricapi/django-symmetric | symmetric/management/codeemitter.py | 947 | from __future__ import print_function
class CodeEmitter(object):
def __init__(self, fobj, indent=0):
if isinstance(fobj, (str, unicode)):
fobj = open(fobj, 'w')
self.fobj = fobj
self.indent = ' ' * indent if indent else '\t'
self.level = 0
def __call__(self, *lines):
for line in lines:
line = line.strip()
if not line:
print('', file=self.fobj)
else:
if line[0] == '}' or line[0] == ']':
self.level = self.level - 1
if line.startswith('case '):
print((self.indent * (self.level - 1)) + line, file=self.fobj)
else:
print((self.indent * self.level) + line, file=self.fobj)
if line[-1] == '{' or line[-1] == '[':
self.level = self.level + 1
def close(self):
self.fobj.close()
| mit |
kolok/projectasaservice | modules/users/client/controllers/authentication.client.controller.js | 2076 | 'use strict';
angular.module('users').controller('AuthenticationController', ['$scope', '$state', '$http', '$location', '$window', 'Authentication',
function ($scope, $state, $http, $location, $window, Authentication) {
$scope.authentication = Authentication;
// Get an eventual error defined in the URL query string:
$scope.error = $location.search().err;
// If user is signed in then redirect back home
if ($scope.authentication.user) {
$location.path('/');
}
$scope.signup = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'userForm');
return false;
}
$http.post('/api/auth/signup', $scope.credentials).success(function (response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the previous or home page
$state.go($state.previous.state.name || 'home', $state.previous.params);
}).error(function (response) {
$scope.error = response.message;
});
};
$scope.signin = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'userForm');
return false;
}
$http.post('/api/auth/signin', $scope.credentials).success(function (response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the previous or home page
$state.go($state.previous.state.name || 'home', $state.previous.params);
}).error(function (response) {
$scope.error = response.message;
});
};
// OAuth provider request
$scope.callOauthProvider = function (url) {
if ($state.previous && $state.previous.href) {
url += '?redirect_to=' + encodeURIComponent($state.previous.href);
}
// Effectively call OAuth authentication route:
$window.location.href = url;
};
}
]);
| mit |
thibault-martinez/iota.lib.cpp | docs/html/search/classes_8.js | 209 | var searchData=
[
['neighbor',['Neighbor',['../class_i_o_t_a_1_1_models_1_1_neighbor.html',1,'IOTA::Models']]],
['network',['Network',['../class_i_o_t_a_1_1_errors_1_1_network.html',1,'IOTA::Errors']]]
];
| mit |
kgryte/npm-list-author-packages | lib/ls.js | 657 | 'use strict';
// MODULES //
var factory = require( './factory.js' );
// LIST //
/**
* FUNCTION: list( options, clbk )
* Lists an author's packages.
*
* @param {Object} options - function options
* @param {String} options.username - author user name
* @param {String} [options.registry="registry.npmjs.org"] - registry
* @param {Number} [options.port=443] - registry port
* @param {String} [options.protocol="https"] - registry protocol
* @param {Function} clbk - callback to invoke upon query completion
* @returns {Void}
*/
function list( options, clbk ) {
factory( options, clbk )();
} // end FUNCTION list()
// EXPORTS //
module.exports = list;
| mit |
TwilioDevEd/api-snippets | video/rest/rooms/list-rooms-multiple-filters/list-rooms-multiple-filters.3.x.js | 665 | // NOTE: This example uses the next generation Twilio helper library - for more
// information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/node
const apiKeySid = 'SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const apiKeySecret = 'your_api_key_secret';
// To set up environmental variables, see http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const Twilio = require('twilio');
const client = new Twilio(apiKeySid, apiKeySecret, { accountSid: accountSid });
client.video.rooms
.list({
status: 'completed',
uniqueName: 'DailyStandup',
})
.then(room => {
console.log(room.sid);
});
| mit |
Answeror/torabot | torabot/frontend/response.py | 415 | import mimeparse
from flask import request, json, jsonify
def make_response_content(formats):
return formats[mimeparse.best_match(formats, request.headers['accept'])]()
def make_response(formats):
return formats[mimeparse.best_match(formats, request.headers['accept'])]()
def make_ok_response_content():
return json.dumps(dict(ok=True))
def make_ok_response():
return jsonify(dict(ok=True))
| mit |
pshrmn/curi | packages/vue/types/AsyncLink.d.ts | 372 | import Vue from "vue";
import { ComponentOptions } from "vue";
export interface AsyncLinkComponent extends Vue {
name: string;
params?: object;
hash?: string;
query?: any;
state?: any;
url: string;
click(e: MouseEvent): void;
navigating: boolean;
}
declare let Link: ComponentOptions<AsyncLinkComponent>;
export default Link;
| mit |
tessin/Tessin.Tin | Tessin.Tin.Models/Extensions/StringExtensions.cs | 1352 | using System;
namespace Tessin.Tin.Models.Extensions
{
public static class StringExtensions
{
public static int? ToNullableInteger(this string value)
{
try
{
return int.Parse(value);
}
catch (Exception)
{
return null;
}
}
public static int ToInteger(this string value)
{
return int.Parse(value);
}
public static TinCountry ToTinCountry(this string value)
{
if (string.IsNullOrWhiteSpace(value)) return TinCountry.Unknown;
var country = value.Trim().ToLower();
switch (country)
{
case "se":
case "swe":
case "sverige":
case "sweden": return TinCountry.Sweden;
case "no":
case "nor":
case "norge":
case "norway": return TinCountry.Norway;
case "fi":
case "fin":
case "finland": return TinCountry.Finland;
case "dk":
case "dnk":
case "danmark":
case "denmark": return TinCountry.Denmark;
default: return TinCountry.Unknown;
}
}
}
}
| mit |
denkGroot/spina-example-plugin | test/dummy/config/application.rb | 881 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
require "reviews"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
| mit |
danylaporte/arewefaster | src/presenters/md.js | 1684 | var fs = require('fs');
var path = require('path');
var utils = require('../utils');
function present(data, cb) {
switch (data.type) {
case 'suite-result':
cb(null, renderSuite(data, 0));
break;
case 'test-result':
cb(null, renderTest(data));
break;
default:
cb(new Error('type of data not supported for presentation.'));
}
};
function testInfo(test) {
return utils.formatNumber(1000 / test.avg) + ' ops ± ' + test.err + '%';
}
function header(title, indent) {
var s = '##';
for (var i = 0; i < indent; i++) {
s += '#';
}
s += title;
return s;
}
function renderSuite(suite, indent) {
var s = suite.name ? header(suite.name, indent) + '\r\n' : '';
var i;
if (suite.tests && suite.tests.length) {
s += '\r\n|name|time ± error margin|';
s += '\r\n|---|-----|';
for (i = 0; i < suite.tests.length; i++) {
var test = suite.tests[i];
s += '\r\n|' + test.name + '|' + testInfo(test) + '|';
}
if (suite.tests.length > 1) s += '\r\n' + utils.fastestVsSecond(suite.tests);
s += '\r\n';
}
if (suite.suites && suite.suites.length) {
for (i = 0; i < suite.suites.length; i++) {
s += '\r\n' + renderSuite(suite.suites[i], indent + 1);
}
}
return s;
}
function renderTest(test) {
return test.name + ': ' + testInfo(test);
}
present.writeFile = function (filename) {
filename = path.resolve(filename);
return function (data, cb) {
present(data, function (err, value) {
value = '#Performance'
+ '\r\nStats are provided by [arewefaster](https://github.com/danylaporte/arewefaster)\r\n\r\n'
+ value;
err ? cb && cb(err) : fs.writeFile(filename, value, cb);
});
};
};
module.exports = present; | mit |
crmauceri/VisualCommonSense | code/database_builder/core/timing.py | 194 | import time;
start = time.time();
def tic():
start = time.time();
def toc():
print("elapse time: " + str(time.time()-start));
if __name__ == "__main__":
tic();
toc();
| mit |
TAurelien/accountingApp | src/components/generalLedgers/src/controller/index.js | 680 | /**
* @module General ledgers Controller
*
* @access private
* @author TAurelien
* @date 2015-05-01
* @version 1.0.0
*/
'use strict';
module.exports = function (options, imports, emitter, GeneralLedgers) {
var api = require('../api')(options, imports, emitter);
// Sockets management =====================================================
require('./socket')(options, imports, api, GeneralLedgers);
// REST API management ====================================================
require('./restApi')(options, imports, api);
//Backend events management ===============================================
require('./events')(options, imports, api);
}; | mit |