code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloPowerBiServiceApi.Models {
public class Report {
public string id { get; set; }
public string name { get; set; }
public string webUrl { get; set; }
public string embedUrl { get; set; }
public bool isOwnedByMe { get; set; }
public string datasetId { get; set; }
}
public class ReportCollection {
public List<Report> value { get; set; }
}
}
| CriticalPathTraining/PBD365 | Modules/04_PBIServiceApi/Demo/HelloPowerBiServiceApi/HelloPowerBiServiceApi/Models/JsonConverterClasses.cs | C# | mit | 491 |
<?php
/*
* @author M2E Pro Developers Team
* @copyright M2E LTD
* @license Commercial use is forbidden
*/
class Ess_M2ePro_Block_Adminhtml_Wizard_InstallationAmazon_Notification
extends Ess_M2ePro_Block_Adminhtml_Wizard_Notification
{
//########################################
//########################################
}
| portchris/NaturalRemedyCompany | src/app/code/community/Ess/M2ePro/Block/Adminhtml/Wizard/InstallationAmazon/Notification.php | PHP | mit | 350 |
var Icon = require('../icon');
var element = require('magic-virtual-element');
var clone = require('../clone');
exports.render = function render(component) {
var props = clone(component.props);
delete props.children;
return element(
Icon,
props,
element('path', { d: 'M3 21h2v-2H3v2zM5 7H3v2h2V7zM3 17h2v-2H3v2zm4 4h2v-2H7v2zM5 3H3v2h2V3zm4 0H7v2h2V3zm8 0h-2v2h2V3zm-4 4h-2v2h2V7zm0-4h-2v2h2V3zm6 14h2v-2h-2v2zm-8 4h2v-2h-2v2zm-8-8h18v-2H3v2zM19 3v2h2V3h-2zm0 6h2V7h-2v2zm-8 8h2v-2h-2v2zm4 4h2v-2h-2v2zm4 0h2v-2h-2v2z' })
);
}; | goto-bus-stop/deku-material-svg-icons | lib/editor/border-horizontal.js | JavaScript | mit | 548 |
/*++
NASM Assembly Language Plugin
Copyright (c) 2017-2019 Aidan Khoury. All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>.
--*/
package com.nasmlanguage;
import com.intellij.lang.Commenter;
import org.jetbrains.annotations.Nullable;
public class NASMCommenter implements Commenter {
@Nullable
@Override
public String getLineCommentPrefix() {
return ";";
}
@Nullable
@Override
public String getBlockCommentPrefix() {
return null;
}
@Nullable
@Override
public String getBlockCommentSuffix() {
return null;
}
@Nullable
@Override
public String getCommentedBlockCommentPrefix() {
return null;
}
@Nullable
@Override
public String getCommentedBlockCommentSuffix() {
return null;
}
}
| dude719/JetBrains-NASM-Language | src/com/nasmlanguage/NASMCommenter.java | Java | mit | 1,389 |
// ****************************************************************************
// <copyright file="IntExtensions.cs" company="Pedro Lamas">
// Copyright © Pedro Lamas 2011
// </copyright>
// ****************************************************************************
// <author>Pedro Lamas</author>
// <email>pedrolamas@gmail.com</email>
// <date>05-01-2012</date>
// <project>Cimbalino.Phone.Toolkit.Background</project>
// <web>http://www.pedrolamas.com</web>
// <license>
// See license.txt in this solution or http://www.pedrolamas.com/license_MIT.txt
// </license>
// ****************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cimbalino.Phone.Toolkit.Extensions
{
/// <summary>
/// Provides a set of static (Shared in Visual Basic) methods for <see cref="int"/> instances.
/// </summary>
public static class IntExtensions
{
/// <summary>
/// Repeats the specified <see cref="Action"/> the number of times.
/// </summary>
/// <param name="input">The number of times to repeat the <see cref="Action"/>.</param>
/// <param name="action">The <see cref="Action"/> to repeat.</param>
public static void Times(this int input, Action action)
{
while (input-- > 0)
{
action();
}
}
/// <summary>
/// Repeats the specified <see cref="Action{Int32}"/> the number of times.
/// </summary>
/// <param name="input">The number of times to repeat the <see cref="Action{Int32}"/>.</param>
/// <param name="action">The <see cref="Action{Int32}"/> to repeat.</param>
public static void Times(this int input, Action<int> action)
{
var count = 0;
while (count < input)
{
action(count);
count++;
}
}
/// <summary>
/// Repeats the specified <see cref="Func{T}"/> the number of times.
/// </summary>
/// <param name="input">The number of times to repeat the <see cref="Action"/>.</param>
/// <param name="function">The <see cref="Func{T}"/> to repeat.</param>
/// <typeparam name="T">The return value type.</typeparam>
/// <returns>An enumerable with the results.</returns>
public static IEnumerable<T> Times<T>(this int input, Func<T> function)
{
while (input-- > 0)
{
yield return function();
}
}
/// <summary>
/// Repeats the specified <see cref="Func{Int32,T}"/> the number of times.
/// </summary>
/// <param name="input">The number of times to repeat the <see cref="Action"/>.</param>
/// <param name="function">The <see cref="Func{Int32,T}"/> to repeat.</param>
/// <typeparam name="T">The return value type.</typeparam>
/// <returns>An enumerable with the results.</returns>
public static IEnumerable<T> Times<T>(this int input, Func<int, T> function)
{
var count = 0;
while (count < input)
{
yield return function(count);
count++;
}
}
/// <summary>
/// Generates a sequence of integral numbers within a specified range.
/// </summary>
/// <param name="first">The value of the first integer in the sequence.</param>
/// <param name="count">The number of sequential integers to generate.</param>
/// <returns>An <see cref="IEnumerable{Int32}"/> that contains a range of sequential integral numbers.</returns>
public static IEnumerable<int> Range(this int first, int count)
{
return Enumerable.Range(first, count);
}
/// <summary>
/// Generates a sequence of integral numbers within a specified range.
/// </summary>
/// <param name="first">The value of the first integer in the sequence.</param>
/// <param name="last">The value of the last integer in the sequence.</param>
/// <returns>An <see cref="IEnumerable{Int32}"/> that contains a range of sequential integral numbers.</returns>
public static IEnumerable<int> To(this int first, int last)
{
return first.Range(last - first + 1);
}
}
} | Cimbalino/Cimbalino-Phone-Toolkit | src/Cimbalino.Phone.Toolkit.Background (WP71)/Extensions/IntExtensions.cs | C# | mit | 4,435 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class AddLastNameToPeopleTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('people', function(Blueprint $table)
{
$table->dropColumn('name');
$table->string('first_name')->after('id');
$table->string('last_name')->after('first_name');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('people', function(Blueprint $table)
{
$table->string('name')->after('id');
$table->dropColumn('first_name');
$table->dropColumn('last_name');
});
}
}
| svpernova09/SvperCRM | app/database/migrations/2014_09_14_020434_add_last_name_to_people_table.php | PHP | mit | 748 |
<?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 4/6/14
* Time: 2:46 PM
*/
namespace Nfq\NomNomBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class AddUsersToEventType extends AbstractType
{
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
public function getName()
{
return 'adduserstoevent';
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('user', 'genemu_jqueryselect2_entity', array(
'class' => 'NfqNomNomBundle:User',
'property' => 'username',
))
->add('submit', 'submit');;
}
} | nfqakademija/nomnom | src/Nfq/NomNomBundle/Form/Type/AddUsersToEventType.php | PHP | mit | 744 |
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "your_auth_token";
$client = new Services_Twilio($sid, $token);
// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$message = $client->account->messages->get("MM800f449d0399ed014aae2bcc0cc2f2ec");
echo $message->body;
| teoreteetik/api-snippets | rest/message/instance-get-example-1/instance-get-example-1.4.x.php | PHP | mit | 546 |
/// -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*-
///
/// \file subject.cpp
/// \author Martin Reddy
/// \brief The subject of an observer relationship.
///
/// Copyright (c) 2010, Martin Reddy. All rights reserved.
/// Distributed under the X11/MIT License. See LICENSE.txt.
/// See http://APIBook.com/ for the latest version.
///
#include "subject.h"
| goodspeed24e/Programming | DesignInterface/observer/subject.cpp | C++ | mit | 372 |
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <stdio.h>
using namespace muduo;
using namespace muduo::net;
void runInThread()
{
printf("runInThread(): pid = %d, tid = %d\n",
getpid(), CurrentThread::tid());
}
int main()
{
printf("main(): pid = %d, tid = %d\n",
getpid(), CurrentThread::tid());
EventLoopThread loopThread;
EventLoop* loop = loopThread.startLoop();
// 异步调用runInThread,即将runInThread添加到loop对象所在IO线程,让该IO线程执行
loop->runInLoop(runInThread);
sleep(1);
// runAfter内部也调用了runInLoop,所以这里也是异步调用
loop->runAfter(2, runInThread);
sleep(3);
loop->quit();
printf("exit main().\n");
} | JnuSimba/muduo_tests | Reactor_test06.cc | C++ | mit | 745 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KDCLLC.Web.Models.Data
{
public class SalesOrder : IObjectWithState
{
public SalesOrder()
{
SalesOrderItems = new List<SalesOrderItem>();
}
public int SalesOrderId { get; set; }
public string CustomerName { get; set; }
public string PONumber { get; set; }
public virtual List<SalesOrderItem> SalesOrderItems { get; set; }
public ObjectState ObjectState { get; set; }
public byte[] RowVersion { get; set; }
}
}
| kdcllc/KDCLLCWeb | KDCLLC.Web.Models/Data/SalesOrder.cs | C# | mit | 640 |
define(['./alasqlportfoliodividenddata', './monthstaticvalues', './bankdatadividend', './dateperiod'], function(alasqlportfoliodividenddata, monthstaticvalues, bankdatadividend, dateperiod) {
var gridData = [];
var gridId;
var months = monthstaticvalues.getMonthWithLettersValues();
var currentMonth = new Date().getMonth();
var selectedYear = new Date().getFullYear();
function setId(fieldId) {
gridId = fieldId;
}
function setData(year) {
selectedYear = year;
var result = alasqlportfoliodividenddata.getPortfolioDividends(selectedYear);
var data = [];
var id = 0;
result.forEach(function(entry) {
if(entry == null) return;
var månad = months[entry.Månad -1];
var land = entry.Land == null ? "x" : entry.Land.toLowerCase();
data.push({
Id: id,
Name : entry.Värdepapper,
Antal : entry.Antal,
Typ: entry.Typ,
Månad: månad,
Utdelningsdatum : entry.Utdelningsdag,
Utdelningsbelopp : entry.UtdelningaktieValuta,
Utdelningtotal: entry.Belopp,
Valuta: entry.Valuta,
ValutaKurs: entry.ValutaKurs,
Land: land,
UtdelningDeklarerad: entry.UtdelningDeklarerad,
Utv: entry.Utv
});
id++;
});
gridData = data;
}
function onDataBound(e) {
var columns = e.sender.columns;
var dataItems = e.sender.dataSource.view();
var today = new Date().toISOString();
for (var j = 0; j < dataItems.length; j++) {
if(dataItems[j].items == null) return;
for (var i = 0; i < dataItems[j].items.length; i++) {
var utdelningsdatum = new Date(dataItems[j].items[i].get("Utdelningsdatum")).toISOString();
var utdelningdeklarerad = dataItems[j].items[i].get("UtdelningDeklarerad");
var row = e.sender.tbody.find("[data-uid='" + dataItems[j].items[i].uid + "']");
if(utdelningsdatum <= today)
row.addClass("grid-ok-row");
if(utdelningdeklarerad == "N")
row.addClass("grid-yellow-row");
}
}
}
function load() {
var today = new Date().toISOString().slice(0, 10);
var grid = $(gridId).kendoGrid({
toolbar: ["excel", "pdf"],
excel: {
fileName: "förväntade_utdelningar" + "_" + today + ".xlsx",
filterable: true
},
pdf: {
fileName: "förväntade_utdelningar" + "_" + today + ".pdf",
allPages: true,
avoidLinks: true,
paperSize: "A4",
margin: { top: "2cm", left: "1cm", right: "1cm", bottom: "1cm" },
landscape: true,
repeatHeaders: true,
scale: 0.8
},
theme: "bootstrap",
dataBound: onDataBound,
dataSource: {
data: gridData,
schema: {
model: {
fields: {
Name: { type: "string" },
Antal: { type: "number" },
Typ: { type: "string" },
Utdelningsdatum: { type: "date" },
Utdelningsbelopp: { type: "string" },
Utdelningtotal: { type: "number"},
Land: {type: "string" },
ValutaKurs: { type: "string"},
Valuta: {type: "string" }
}
}
},
group: {
field: "Månad", dir: "asc", aggregates: [
{ field: "Månad", aggregate: "sum" },
{ field: "Name", aggregate: "count" },
{ field: "Utdelningtotal", aggregate: "sum"}
]
},
aggregate: [ { field: "Månad", aggregate: "sum" },
{ field: "Name", aggregate: "count" },
{ field: "Utdelningtotal", aggregate: "sum" }
],
sort: ({ field: "Utdelningsdatum", dir: "asc" }),
pageSize: gridData.length
},
scrollable: true,
sortable: true,
filterable: true,
groupable: true,
pageable: false,
columns: [
{ field: "Månad", groupHeaderTemplate: "#= value.substring(2, value.length) #", hidden: true },
{ field: "UtdelningDeklarerad", hidden: true },
{ field: "Name", title: "Värdepapper", template: "<div class='gridportfolio-country-picture' style='background-image: url(/styles/images/#:data.Land#.png);'></div><div class='gridportfolio-country-name'>#: Name #</div>", width: "150px", aggregates: ["count"], footerTemplate: "Totalt antal förväntade utdelningar: #=count# st", groupFooterTemplate: gridNameGroupFooterTemplate },
{ field: "Utdelningsdatum", title: "Utd/Handl. utan utd", format: "{0:yyyy-MM-dd}", width: "75px" },
{ field: "Typ", title: "Typ", width: "70px" },
{ field: "Antal", title: "Antal", format: "{0} st", width: "40px" },
{ field: "Utdelningsbelopp", title: "Utdelning/aktie", width: "60px" },
{ title: "Utv.", template: '<span class="#= gridPortfolioDividendDivChangeClass(data) #"></span>', width: "15px" },
{ field: "Utdelningtotal", title: "Belopp", width: "110px", format: "{0:n2} kr", aggregates: ["sum"], footerTemplate: gridUtdelningtotalFooterTemplate, groupFooterTemplate: gridUtdelningtotalGroupFooterTemplate },
{ title: "", template: '<span class="k-icon k-i-info" style="#= gridPortfolioDividendInfoVisibility(data) #"></span>', width: "15px" }
],
excelExport: function(e) {
var sheet = e.workbook.sheets[0];
for (var i = 0; i < sheet.columns.length; i++) {
sheet.columns[i].width = getExcelColumnWidth(i);
}
}
}).data("kendoGrid");
grid.thead.kendoTooltip({
filter: "th",
content: function (e) {
var target = e.target;
return $(target).text();
}
});
addTooltipForColumnFxInfo(grid, gridId);
addTooltipForColumnUtvInfo(grid, gridId);
}
function addTooltipForColumnUtvInfo(grid, gridId) {
$(gridId).kendoTooltip({
show: function(e){
if(this.content.text().length > 1){
this.content.parent().css("visibility", "visible");
}
},
hide:function(e){
this.content.parent().css("visibility", "hidden");
},
filter: "td:nth-child(9)",
position: "left",
width: 200,
content: function(e) {
var dataItem = grid.dataItem(e.target.closest("tr"));
if(dataItem == null || e.target[0].parentElement.className == "k-group-footer" || dataItem.Utv == 0) return "";
var content = "Utdelningsutveckling jmf fg utdelning: " + dataItem.Utv.replace('.', ',') + " %";
return content
}
}).data("kendoTooltip");
}
function addTooltipForColumnFxInfo(grid, gridId) {
$(gridId).kendoTooltip({
show: function(e){
if(this.content.text().length > 1){
this.content.parent().css("visibility", "visible");
}
},
hide:function(e){
this.content.parent().css("visibility", "hidden");
},
filter: "td:nth-child(11)",
position: "left",
width: 200,
content: function(e) {
var dataItem = grid.dataItem(e.target.closest("tr"));
if(dataItem == null || dataItem.ValutaKurs <= 1 || e.target[0].parentElement.className == "k-group-footer") return "";
var content = "Förväntat belopp beräknat med " + dataItem.Valuta + " växelkurs: " + (dataItem.ValutaKurs).replace(".", ",") + "kr";
return content
}
}).data("kendoTooltip");
}
window.gridPortfolioDividendDivChangeClass = function gridPortfolioDividendDivChangeClass(data) {
if(data.Utv == 0 || data.Utv == null)
return "hidden";
else if(data.Utv > 0)
return "k-icon k-i-arrow-up";
else
return "k-icon k-i-arrow-down";
}
window.gridPortfolioDividendInfoVisibility = function gridPortfolioDividendInfoVisibility(data) {
return data.ValutaKurs > 1 ? "" : "display: none;";
}
function getExcelColumnWidth(index) {
var columnWidth = 150;
switch(index) {
case 0: // Månad
columnWidth = 80;
break;
case 1: // Värdepapper
columnWidth = 220;
break;
case 2: // Datum
columnWidth = 80;
break;
case 3: // Typ
columnWidth = 130;
break;
case 4: // Antal
columnWidth = 70;
break;
case 5: // Utdelning/aktie
columnWidth = 120;
break;
case 6: // Belopp
columnWidth = 260;
break;
default:
columnWidth = 150;
}
return columnWidth;
}
function gridNameGroupFooterTemplate(e) {
var groupNameValue = e.Månad.sum;
if(typeof e.Name.group !== 'undefined')
groupNameValue = e.Name.group.value;
var groupMonthValue = months.indexOf(groupNameValue);
if(currentMonth <= groupMonthValue) {
return "Antal förväntade utdelningar: " + e.Name.count + " st";
}
else {
return "Antal erhållna utdelningar: " + e.Name.count + " st";
}
}
function gridUtdelningtotalFooterTemplate(e) {
var startPeriod = dateperiod.getStartOfYear((selectedYear -1));
var endPeriod = dateperiod.getEndOfYear((selectedYear -1));
var isTaxChecked = $('#checkboxTax').is(":checked");
var selectedYearTotalNumeric = e.Utdelningtotal.sum;
var selectedYearTotal = kendo.toString(selectedYearTotalNumeric, 'n2') + " kr";
var lastYearTotalNumeric = bankdatadividend.getTotalDividend(startPeriod, endPeriod, isTaxChecked);
var lastYearTotal = kendo.toString(lastYearTotalNumeric, 'n2') + " kr";
var growthValueNumeric = calculateGrowthChange(selectedYearTotalNumeric, lastYearTotalNumeric);
var growthValue = kendo.toString(growthValueNumeric, 'n2').replace(".", ",") + "%";
var spanChange = buildSpanChangeArrow(selectedYearTotalNumeric, lastYearTotalNumeric);
return "Totalt förväntat belopp: " + selectedYearTotal + " " + spanChange + growthValue + " (" + lastYearTotal + ")";
}
function gridUtdelningtotalGroupFooterTemplate(e) {
var groupNameValue = e.Månad.sum;
if(typeof e.Name.group !== 'undefined')
groupNameValue = e.Name.group.value;
var groupMonthValue = months.indexOf(groupNameValue);
var isTaxChecked = $('#checkboxTax').is(":checked");
var lastYearValueNumeric = bankdatadividend.getDividendMonthSumBelopp((selectedYear -1), (groupMonthValue +1), isTaxChecked);
var selectedYearValueNumeric = e.Utdelningtotal.sum;
var lastYearValue = kendo.toString(lastYearValueNumeric, 'n2') + " kr";
var selectedYearValue = kendo.toString(selectedYearValueNumeric, 'n2') + " kr";
var monthName = groupNameValue.substring(3, groupNameValue.length).toLowerCase();
var spanChange = buildSpanChangeArrow(selectedYearValueNumeric, lastYearValueNumeric);
var growthValueNumeric = calculateGrowthChange(selectedYearValueNumeric, lastYearValueNumeric);
var growthValue = kendo.toString(growthValueNumeric, 'n2').replace(".", ",") + "%";
if(months.includes(groupNameValue)) {
if(currentMonth <= groupMonthValue) {
return "Förväntat belopp " + monthName + ": " + selectedYearValue + " " + spanChange + growthValue + " (" + lastYearValue + ")";
}
else {
return "Erhållet belopp " + monthName + ": " + selectedYearValue + " " + spanChange + growthValue + " (" + lastYearValue + ")";
}
}
else {
return "Förväntat belopp " + groupNameValue + ": " + selectedYearValue + " " + spanChange + growthValue + " (" + lastYearValue + ")";
}
}
function buildSpanChangeArrow(current, last) {
var spanArrowClass = current > last ? "k-i-arrow-up" : "k-i-arrow-down";
var titleText = current > last ? "To the moon" : "Back to earth";
return "<span class='k-icon " + spanArrowClass + "' title='" + titleText + "'></span>";
}
function calculateGrowthChange(current, last) {
if(last == 0) return 0;
var changeValue = current - last;
return ((changeValue / last) * 100).toFixed(2);
}
return {
setId: setId,
setData: setData,
load: load
};
}); | nnava/nnava.github.io | js/gridportfoliodividend.js | JavaScript | mit | 13,859 |
/* eslint-disable global-require */
// polyfills and vendors
if (!window._babelPolyfill) {
require('babel-polyfill')
}
| ri/news-emote | src/vendor.js | JavaScript | mit | 123 |
/*
* This file is part of ThermalRecycling, licensed under the MIT License (MIT).
*
* Copyright (c) OreCruncher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.blockartistry.mod.ThermalRecycling.support.recipe.accessor;
import java.util.List;
import forestry.api.recipes.IFabricatorRecipe;
import net.minecraft.item.ItemStack;
public class ForestryFabricatorRecipeAccessor extends RecipeAccessorBase {
@Override
public ItemStack getInput(final Object recipe) {
final IFabricatorRecipe r = (IFabricatorRecipe) recipe;
return r.getRecipeOutput().copy();
}
@Override
public List<ItemStack> getOutput(final Object recipe) {
final IFabricatorRecipe r = (IFabricatorRecipe) recipe;
return RecipeUtil.projectForgeRecipeList(r.getIngredients());
}
}
| OreCruncher/ThermalRecycling | src/main/java/org/blockartistry/mod/ThermalRecycling/support/recipe/accessor/ForestryFabricatorRecipeAccessor.java | Java | mit | 1,809 |
import json
import logging
from foxglove import glove
from httpx import Response
from .settings import Settings
logger = logging.getLogger('ext')
def lenient_json(v):
if isinstance(v, (str, bytes)):
try:
return json.loads(v)
except (ValueError, TypeError):
pass
return v
class ApiError(RuntimeError):
def __init__(self, method, url, status, response_text):
self.method = method
self.url = url
self.status = status
self.body = response_text
def __str__(self):
return f'{self.method} {self.url}, unexpected response {self.status}'
class ApiSession:
def __init__(self, root_url, settings: Settings):
self.settings = settings
self.root = root_url.rstrip('/') + '/'
async def get(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('GET', uri, allowed_statuses=allowed_statuses, **data)
async def delete(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('DELETE', uri, allowed_statuses=allowed_statuses, **data)
async def post(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('POST', uri, allowed_statuses=allowed_statuses, **data)
async def put(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('PUT', uri, allowed_statuses=allowed_statuses, **data)
async def _request(self, method, uri, allowed_statuses=(200, 201), **data) -> Response:
method, url, data = self._modify_request(method, self.root + str(uri).lstrip('/'), data)
kwargs = {}
headers = data.pop('headers_', None)
if headers is not None:
kwargs['headers'] = headers
if timeout := data.pop('timeout_', None):
kwargs['timeout'] = timeout
r = await glove.http.request(method, url, json=data or None, **kwargs)
if isinstance(allowed_statuses, int):
allowed_statuses = (allowed_statuses,)
if allowed_statuses != '*' and r.status_code not in allowed_statuses:
data = {
'request_real_url': str(r.request.url),
'request_headers': dict(r.request.headers),
'request_data': data,
'response_headers': dict(r.headers),
'response_content': lenient_json(r.text),
}
logger.warning(
'%s unexpected response %s /%s -> %s',
self.__class__.__name__,
method,
uri,
r.status_code,
extra={'data': data} if self.settings.verbose_http_errors else {},
)
raise ApiError(method, url, r.status_code, r.text)
else:
logger.debug('%s /%s -> %s', method, uri, r.status_code)
return r
def _modify_request(self, method, url, data):
return method, url, data
class Mandrill(ApiSession):
def __init__(self, settings):
super().__init__(settings.mandrill_url, settings)
def _modify_request(self, method, url, data):
data['key'] = self.settings.mandrill_key
return method, url, data
class MessageBird(ApiSession):
def __init__(self, settings):
super().__init__(settings.messagebird_url, settings)
def _modify_request(self, method, url, data):
data['headers_'] = {'Authorization': f'AccessKey {self.settings.messagebird_key}'}
return method, url, data
| tutorcruncher/morpheus | src/ext.py | Python | mit | 3,555 |
/*
Copyright (C) 2003-2013 by Kristina Simpson <sweet.kristas@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "asserts.hpp"
#include "css_parser.hpp"
#include "css_properties.hpp"
#include "unit_test.hpp"
namespace css
{
namespace
{
// rules
class AtRule : public Token
{
public:
AtRule(const std::string& name) : Token(TokenId::AT_RULE_TOKEN), name_(name) {}
std::string toString() const override {
std::ostringstream ss;
for(auto& p : getParameters()) {
ss << " " << p->toString();
}
return formatter() << "@" << name_ << "(" << ss.str() << ")";
}
private:
std::string name_;
};
class RuleToken : public Token
{
public:
RuleToken() : Token(TokenId::RULE_TOKEN) {}
std::string toString() const override {
std::ostringstream ss;
for(auto& p : getParameters()) {
ss << " " << p->toString();
}
return formatter() << "QualifiedRule(" << ss.str() << ")";
}
private:
};
class BlockToken : public Token
{
public:
BlockToken() : Token(TokenId::BLOCK_TOKEN) {}
explicit BlockToken(const std::vector<TokenPtr>& params)
: Token(TokenId::BLOCK_TOKEN)
{
addParameters(params);
}
std::string toString() const override {
std::ostringstream ss;
for(auto& p : getParameters()) {
ss << " " << p->toString();
}
return formatter() << "BlockToken(" << ss.str() << ")";
}
variant value() override { return variant(); }
private:
};
class SelectorToken : public Token
{
public:
SelectorToken() : Token(TokenId::SELECTOR_TOKEN) {}
std::string toString() const override {
std::ostringstream ss;
for(auto& p : getParameters()) {
ss << " " << p->toString();
}
return formatter() << "Selector(" << ss.str() << ")";
};
};
class DeclarationParser
{
public:
DeclarationParser(Tokenizer::const_iterator begin, Tokenizer::const_iterator end)
: it_(begin),
end_(end),
pp_()
{
while(isToken(TokenId::WHITESPACE)) {
advance();
}
if(isToken(TokenId::IDENT)) {
parseDeclarationList(&pp_);
} else if(isToken(TokenId::BLOCK_TOKEN)) {
auto old_it = it_;
auto old_end = end_;
it_ = (*old_it)->getParameters().begin();
end_ = (*old_it)->getParameters().end();
parseDeclarationList(&pp_);
it_ = old_it;
end_ = old_end;
advance();
} else if(isToken(TokenId::LBRACE)) {
advance();
parseDeclarationList(&pp_);
} else if(isToken(TokenId::EOF_TOKEN)) {
throw ParserError("expected block declaration");
}
}
static PropertyList parseTokens(const std::vector<TokenPtr>& tokens) {
//std::vector<TokenPtr> toks = preProcess(tokens.begin(), tokens.end());
DeclarationParser p(tokens.begin(), tokens.end());
return p.getProperties();
}
PropertyList getProperties() { return pp_.getPropertyList(); }
static std::vector<TokenPtr> preProcess(Tokenizer::const_iterator it, Tokenizer::const_iterator end) {
std::vector<TokenPtr> res;
while(it != end) {
auto tok = *it;
if(tok->id() == TokenId::FUNCTION) {
auto fn_token = tok;
++it;
bool done = false;
while(!done && it != end) {
tok = *it;
if(tok->id() == TokenId::EOF_TOKEN || tok->id() == TokenId::RPAREN || tok->id() == TokenId::SEMICOLON) {
++it;
done = true;
} else {
// this is a cut-down
fn_token->addParameter(tok);
++it;
}
}
res.emplace_back(fn_token);
} else {
res.emplace_back(tok);
++it;
}
}
return res;
}
private:
PropertyParser pp_;
void advance(int n = 1) {
if(it_ == end_) {
return;
}
it_ += n;
}
bool isToken(TokenId value) {
if(it_ == end_ ) {
return value == TokenId::EOF_TOKEN ? true : false;
}
return (*it_)->id() == value;
}
bool isNextToken(TokenId value) {
auto next = it_+1;
if(next == end_) {
return false;
}
return (*next)->id() == value;
}
void parseDeclarationList(PropertyParser* pp) {
while(true) {
while(isToken(TokenId::WHITESPACE)) {
advance();
}
if(isToken(TokenId::RBRACE)) {
advance();
return;
}
if(isToken(TokenId::EOF_TOKEN) || it_ == end_) {
return;
}
try {
parseDeclaration(pp);
} catch (ParserError& e) {
LOG_ERROR("Dropping declaration: " << e.what());
while(!isToken(TokenId::SEMICOLON) && !isToken(TokenId::RBRACE) && !isToken(TokenId::EOF_TOKEN)) {
advance();
}
}
while(isToken(TokenId::WHITESPACE)) {
advance();
}
if(isToken(TokenId::SEMICOLON)) {
advance();
} else if(!isToken(TokenId::RBRACE) && !isToken(TokenId::EOF_TOKEN)) {
throw ParserError("Expected semicolon.");
}
}
}
void parseDeclaration(PropertyParser* pp) {
// assume first token is ident
std::string property = (*it_)->getStringValue();
advance();
while(isToken(TokenId::WHITESPACE)) {
advance();
}
if(!isToken(TokenId::COLON)) {
throw ParserError(formatter() << "Expected ':' in declaration, while parsing property: " << property);
}
advance();
while(isToken(TokenId::WHITESPACE)) {
advance();
}
// check for 'inherit' which is common to all properties
if(isToken(TokenId::IDENT) && (*it_)->getStringValue() == "inherit") {
advance();
pp->inheritProperty(property);
} else {
it_ = pp->parse(property, it_, end_);
}
while(isToken(TokenId::WHITESPACE)) {
advance();
}
if(isTokenDelimiter("!")) {
advance();
while(isToken(TokenId::WHITESPACE)) {
advance();
}
if(isToken(TokenId::IDENT)) {
const std::string ref = (*it_)->getStringValue();
advance();
if(ref == "important") {
// add important tag to the rule in plist.
// XXX this should apply to only the last member added!
for(auto& pl : pp->getPropertyList()) {
pl.second.style->setImportant(true);
}
}
}
}
}
bool isTokenDelimiter(const std::string& ch) {
return isToken(TokenId::DELIM) && (*it_)->getStringValue() == ch;
}
std::vector<TokenPtr>::const_iterator it_;
std::vector<TokenPtr>::const_iterator end_;
};
}
Parser::Parser(StyleSheetPtr ss, const std::vector<TokenPtr>& tokens)
: style_sheet_(ss),
tokens_(tokens),
token_(tokens_.begin()),
end_(tokens_.end())
{
}
void Parser::parse(StyleSheetPtr ss, const std::string& str)
{
css::Tokenizer tokens(str);
Parser p(ss, tokens.getTokens());
p.init();
}
TokenId Parser::currentTokenType()
{
if(token_ == end_) {
return TokenId::EOF_TOKEN;
}
return (*token_)->id();
}
void Parser::advance(int n)
{
if(token_ != end_) {
std::advance(token_, n);
}
}
std::vector<TokenPtr> Parser::pasrseRuleList(int level)
{
std::vector<TokenPtr> rules;
while(true) {
if(currentTokenType() == TokenId::WHITESPACE) {
advance();
continue;
} else if(currentTokenType() == TokenId::EOF_TOKEN) {
return rules;
} else if(currentTokenType() == TokenId::CDO || currentTokenType() == TokenId::CDC) {
if(level == 0) {
advance();
continue;
}
rules.emplace_back(parseQualifiedRule());
} else if(currentTokenType() == TokenId::AT) {
rules.emplace_back(parseAtRule());
} else {
rules.emplace_back(parseQualifiedRule());
}
}
return rules;
}
TokenPtr Parser::parseAtRule()
{
variant value = (*token_)->value();
auto rule = std::make_shared<AtRule>(value.as_string());
advance();
while(true) {
if(currentTokenType() == TokenId::SEMICOLON || currentTokenType() == TokenId::EOF_TOKEN) {
return rule;
} else if(currentTokenType() == TokenId::LBRACE) {
advance();
rule->addParameters(parseBraceBlock());
} else if(currentTokenType() == TokenId::LPAREN) {
advance();
rule->addParameters(parseParenBlock());
} else if(currentTokenType() == TokenId::LBRACKET) {
advance();
rule->addParameters(parseBracketBlock());
}
}
return nullptr;
}
TokenPtr Parser::parseQualifiedRule()
{
auto rule = std::make_shared<RuleToken>();
while(true) {
if(currentTokenType() == TokenId::EOF_TOKEN) {
LOG_ERROR("EOF token while parsing qualified rule prelude.");
return nullptr;
} else if(currentTokenType() == TokenId::LBRACE) {
advance();
rule->setValue(std::make_shared<BlockToken>(parseBraceBlock()));
return rule;
} else {
rule->addParameter(parseComponentValue());
}
}
return nullptr;
}
PropertyList Parser::parseDeclarationList(const std::string& str)
{
css::Tokenizer tokens(str);
Parser p(nullptr, tokens.getTokens());
return DeclarationParser::parseTokens(p.parseBraceBlock());
}
StylePtr Parser::parseSingleDeclaration(const std::string& str)
{
css::Tokenizer tokens(str);
Parser p(nullptr, tokens.getTokens());
auto plist = DeclarationParser::parseTokens(p.parseBraceBlock());
if(plist.empty()) {
return nullptr;
}
return plist.begin()->second.style;
}
TokenPtr Parser::parseComponentValue()
{
if(currentTokenType() == TokenId::LBRACE) {
advance();
return std::make_shared<BlockToken>(parseBraceBlock());
} else if(currentTokenType() == TokenId::FUNCTION) {
return parseFunction();
}
auto tok = *token_;
advance();
return tok;
}
std::vector<TokenPtr> Parser::parseBraceBlock()
{
std::vector<TokenPtr> res;
while(true) {
if(currentTokenType() == TokenId::EOF_TOKEN || currentTokenType() == TokenId::RBRACE) {
advance();
return res;
} else {
res.emplace_back(parseComponentValue());
}
}
return res;
}
std::vector<TokenPtr> Parser::parseParenBlock()
{
std::vector<TokenPtr> res;
res.emplace_back(*token_);
while(true) {
if(currentTokenType() == TokenId::EOF_TOKEN || currentTokenType() == TokenId::RPAREN) {
advance();
return res;
} else {
res.emplace_back(parseComponentValue());
}
}
return res;
}
std::vector<TokenPtr> Parser::parseBracketBlock()
{
std::vector<TokenPtr> res;
res.emplace_back(*token_);
while(true) {
if(currentTokenType() == TokenId::EOF_TOKEN || currentTokenType() == TokenId::RBRACKET) {
advance();
return res;
} else {
res.emplace_back(parseComponentValue());
}
}
return res;
}
TokenPtr Parser::parseFunction()
{
auto fn_token = *token_;
advance();
while(true) {
if(currentTokenType() == TokenId::EOF_TOKEN || currentTokenType() == TokenId::RPAREN) {
advance();
return fn_token;
} else {
fn_token->addParameter(parseComponentValue());
}
}
return fn_token;
}
void Parser::init()
{
for(auto& token : pasrseRuleList(0)) {
try {
parseRule(token);
} catch(ParserError& e) {
LOG_DEBUG("Dropping rule: " << e.what() << " " << (token != nullptr ? token->toString() : ""));
}
}
}
void Parser::parseRule(TokenPtr rule)
{
if(rule == nullptr) {
throw ParserError("Trying to parse empty rule.");
}
auto prelude = rule->getParameters().begin();
while((*prelude)->id() == TokenId::WHITESPACE) {
++prelude;
}
if((*prelude)->id() == TokenId::AT_RULE_TOKEN) {
// parse at rule
// XXX temporarily skip @ rules.
//while(!(*prelude)->isToken(TokenId::SEMICOLON) && !(*prelude)->isToken(TokenId::RBRACE) && prelude != rule->getPrelude().end()) {
//}
ASSERT_LOG(false, "fix @ rules.");
} else {
CssRulePtr css_rule = std::make_shared<CssRule>();
css_rule->selectors = Selector::parseTokens(rule->getParameters());
css_rule->declaractions = DeclarationParser::parseTokens(rule->getValue()->getParameters());
// Go through the properties and mark any that need to be handled with transitions
//css_rule->declaractions.markTransitions();
style_sheet_->addRule(css_rule);
}
}
}
UNIT_TEST(css_declarations)
{
css::PropertyList pl = css::Parser::parseDeclarationList("color: rgb(100%,0,0);");
CHECK_EQ(pl.hasProperty(css::Property::COLOR), true);
/*pl = css::Parser::parseDeclarationList("background: rgb(128,64,64) url(radial_gradient.png) repeat; color: rgb(128,255,128);");
CHECK_EQ(pl.hasProperty(css::Property::COLOR), true);
CHECK_EQ(pl.hasProperty(css::Property::BACKGROUND_IMAGE), true);
CHECK_EQ(pl.hasProperty(css::Property::BACKGROUND_COLOR), true);
CHECK_EQ(pl.hasProperty(css::Property::BACKGROUND_REPEAT), true);*/
pl = css::Parser::parseDeclarationList("color: #ff0 !important; font-family: 'Arial'; color: hsl(360,0,0)");
CHECK_EQ(pl.hasProperty(css::Property::COLOR), true);
CHECK_EQ(pl.hasProperty(css::Property::FONT_FAMILY), true);
pl = css::Parser::parseDeclarationList("background: linear-gradient(45deg, blue, red)");
CHECK_EQ(pl.hasProperty(css::Property::BACKGROUND_IMAGE), true);
}
| sweetkristas/xhtml | src/xhtml/css_parser.cpp | C++ | mit | 13,689 |
package org.udger.parser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.URL;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CyclicBarrier;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class UdgerParserTest {
private UdgerParser parser;
private UdgerParser inMemoryParser;
private UdgerParser.ParserDbData parserDbData;
@Before
public void initialize() throws SQLException {
URL resource = this.getClass().getClassLoader().getResource("udgerdb_test_v3.dat");
parserDbData = new UdgerParser.ParserDbData(resource.getFile());
parser = new UdgerParser(parserDbData);
inMemoryParser = new UdgerParser(parserDbData, true, 0); // no cache
}
@After
public void close() throws IOException {
parser.close();
}
@Test
public void testUaString1() throws SQLException {
String uaQuery = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
UdgerUaResult qr = parser.parseUa(uaQuery);
assertEquals(qr.getUa(), "Firefox 40.0");
assertEquals(qr.getOs(), "Windows 10");
assertEquals(qr.getUaFamily(), "Firefox");
}
@Test
public void testIp() throws SQLException, UnknownHostException {
String ipQuery = "108.61.199.93";
UdgerIpResult qr = parser.parseIp(ipQuery);
assertEquals(qr.getIpClassificationCode(), "crawler");
}
@Test
public void testUaStringInMemoryParser() throws SQLException {
String uaQuery = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
UdgerUaResult qr = inMemoryParser.parseUa(uaQuery);
assertEquals(qr.getUa(), "Firefox 40.0");
assertEquals(qr.getOs(), "Windows 10");
assertEquals(qr.getUaFamily(), "Firefox");
}
@Test
public void testIpInMemoryParser() throws SQLException, UnknownHostException {
String ipQuery = "108.61.199.93";
UdgerIpResult qr = inMemoryParser.parseIp(ipQuery);
assertEquals(qr.getIpClassificationCode(), "crawler");
}
@Test
public void testParserDbDataThreadSafety() throws Throwable {
final int numThreads = 500;
final String uaQuery = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
final CyclicBarrier gate = new CyclicBarrier(numThreads);
final ConcurrentLinkedQueue<Throwable> failures = new ConcurrentLinkedQueue<>();
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
UdgerParser threadParser = new UdgerParser(parserDbData);
try {
gate.await();
for (int j = 0; j < 100; j++) {
UdgerUaResult qr = threadParser.parseUa(uaQuery);
assertEquals(qr.getUa(), "Firefox 40.0");
assertEquals(qr.getOs(), "Windows 10");
assertEquals(qr.getUaFamily(), "Firefox");
}
} catch (Throwable t) {
failures.add(t);
}
}
});
threads[i].start();
}
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
if (!failures.isEmpty()) {
for (Throwable throwable : failures) {
throwable.printStackTrace();
}
fail("Parsing threads failed, see printed exceptions");
}
}
}
| udger/udger-java | src/test/java/org/udger/parser/UdgerParserTest.java | Java | mit | 3,881 |
<?php namespace Illuminate\Database\Eloquent\Relations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class BelongsToMany extends Relation {
/**
* The intermediate table for the relation.
*
* @var string
*/
protected $table;
/**
* The foreign key of the parent model.
*
* @var string
*/
protected $foreignKey;
/**
* The associated key of the relation.
*
* @var string
*/
protected $otherKey;
/**
* The "name" of the relationship.
*
* @var string
*/
protected $relationName;
/**
* The pivot table columns to retrieve.
*
* @var array
*/
protected $pivotColumns = array();
/**
* Create a new has many relationship instance.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Model $parent
* @param string $table
* @param string $foreignKey
* @param string $otherKey
* @param string $relationName
* @return void
*/
public function __construct(Builder $query, Model $parent, $table, $foreignKey, $otherKey, $relationName = null)
{
$this->table = $table;
$this->otherKey = $otherKey;
$this->foreignKey = $foreignKey;
$this->relationName = $relationName;
parent::__construct($query, $parent);
}
/**
* Get the results of the relationship.
*
* @return mixed
*/
public function getResults()
{
return $this->get();
}
/**
* Set a where clause for a pivot table column.
*
* @param string $column
* @param string $operator
* @param mixed $value
* @param string $boolean
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function wherePivot($column, $operator = null, $value = null, $boolean = 'and')
{
return $this->where($this->table.'.'.$column, $operator, $value, $boolean);
}
/**
* Set an or where clause for a pivot table column.
*
* @param string $column
* @param string $operator
* @param mixed $value
* @param string $boolean
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function orWherePivot($column, $operator = null, $value = null)
{
return $this->wherePivot($column, $operator, $value, 'or');
}
/**
* Execute the query and get the first result.
*
* @param array $columns
* @return mixed
*/
public function first($columns = array('*'))
{
$results = $this->take(1)->get($columns);
return count($results) > 0 ? $results->first() : null;
}
/**
* Execute the query and get the first result or throw an exception.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|static
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function firstOrFail($columns = array('*'))
{
if ( ! is_null($model = $this->first($columns))) return $model;
throw new ModelNotFoundException;
}
/**
* Execute the query as a "select" statement.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Collection
*/
public function get($columns = array('*'))
{
// First we'll add the proper select columns onto the query so it is run with
// the proper columns. Then, we will get the results and hydrate out pivot
// models with the result of those columns as a separate model relation.
$select = $this->getSelectColumns($columns);
$models = $this->query->addSelect($select)->getModels();
$this->hydratePivotRelation($models);
// If we actually found models we will also eager load any relationships that
// have been specified as needing to be eager loaded. This will solve the
// n + 1 query problem for the developer and also increase performance.
if (count($models) > 0)
{
$models = $this->query->eagerLoadRelations($models);
}
return $this->related->newCollection($models);
}
/**
* Get a paginator for the "select" statement.
*
* @param int $perPage
* @param array $columns
* @return \Illuminate\Pagination\Paginator
*/
public function paginate($perPage = null, $columns = array('*'))
{
$this->query->addSelect($this->getSelectColumns($columns));
// When paginating results, we need to add the pivot columns to the query and
// then hydrate into the pivot objects once the results have been gathered
// from the database since this isn't performed by the Eloquent builder.
$pager = $this->query->paginate($perPage, $columns);
$this->hydratePivotRelation($pager->getItems());
return $pager;
}
/**
* Hydrate the pivot table relationship on the models.
*
* @param array $models
* @return void
*/
protected function hydratePivotRelation(array $models)
{
// To hydrate the pivot relationship, we will just gather the pivot attributes
// and create a new Pivot model, which is basically a dynamic model that we
// will set the attributes, table, and connections on so it they be used.
foreach ($models as $model)
{
$pivot = $this->newExistingPivot($this->cleanPivotAttributes($model));
$model->setRelation('pivot', $pivot);
}
}
/**
* Get the pivot attributes from a model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return array
*/
protected function cleanPivotAttributes(Model $model)
{
$values = array();
foreach ($model->getAttributes() as $key => $value)
{
// To get the pivots attributes we will just take any of the attributes which
// begin with "pivot_" and add those to this arrays, as well as unsetting
// them from the parent's models since they exist in a different table.
if (strpos($key, 'pivot_') === 0)
{
$values[substr($key, 6)] = $value;
unset($model->$key);
}
}
return $values;
}
/**
* Set the base constraints on the relation query.
*
* @return void
*/
public function addConstraints()
{
$this->setJoin();
if (static::$constraints) $this->setWhere();
}
/**
* Add the constraints for a relationship count query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Builder $parent
* @return \Illuminate\Database\Eloquent\Builder
*/
public function getRelationCountQuery(Builder $query, Builder $parent)
{
if ($parent->getQuery()->from == $query->getQuery()->from)
{
return $this->getRelationCountQueryForSelfJoin($query, $parent);
}
else
{
$this->setJoin($query);
return parent::getRelationCountQuery($query, $parent);
}
}
/**
* Add the constraints for a relationship count query on the same table.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Builder $parent
* @return \Illuminate\Database\Eloquent\Builder
*/
public function getRelationCountQueryForSelfJoin(Builder $query, Builder $parent)
{
$query->select(new \Illuminate\Database\Query\Expression('count(*)'));
$tablePrefix = $this->query->getQuery()->getConnection()->getTablePrefix();
$query->from($this->table.' as '.$tablePrefix.$hash = $this->getRelationCountHash());
$key = $this->wrap($this->getQualifiedParentKeyName());
return $query->where($hash.'.'.$this->foreignKey, '=', new \Illuminate\Database\Query\Expression($key));
}
/**
* Get a relationship join table hash.
*
* @return string
*/
public function getRelationCountHash()
{
return 'self_'.md5(microtime(true));
}
/**
* Set the select clause for the relation query.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
protected function getSelectColumns(array $columns = array('*'))
{
if ($columns == array('*'))
{
$columns = array($this->related->getTable().'.*');
}
return array_merge($columns, $this->getAliasedPivotColumns());
}
/**
* Get the pivot columns for the relation.
*
* @return array
*/
protected function getAliasedPivotColumns()
{
$defaults = array($this->foreignKey, $this->otherKey);
// We need to alias all of the pivot columns with the "pivot_" prefix so we
// can easily extract them out of the models and put them into the pivot
// relationships when they are retrieved and hydrated into the models.
$columns = array();
foreach (array_merge($defaults, $this->pivotColumns) as $column)
{
$columns[] = $this->table.'.'.$column.' as pivot_'.$column;
}
return array_unique($columns);
}
/**
* Set the join clause for the relation query.
*
* @param \Illuminate\Database\Eloquent\Builder|null
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
protected function setJoin($query = null)
{
$query = $query ?: $this->query;
// We need to join to the intermediate table on the related model's primary
// key column with the intermediate table's foreign key for the related
// model instance. Then we can set the "where" for the parent models.
$baseTable = $this->related->getTable();
$key = $baseTable.'.'.$this->related->getKeyName();
$query->join($this->table, $key, '=', $this->getOtherKey());
return $this;
}
/**
* Set the where clause for the relation query.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
protected function setWhere()
{
$foreign = $this->getForeignKey();
$this->query->where($foreign, '=', $this->parent->getKey());
return $this;
}
/**
* Set the constraints for an eager load of the relation.
*
* @param array $models
* @return void
*/
public function addEagerConstraints(array $models)
{
$this->query->whereIn($this->getForeignKey(), $this->getKeys($models));
}
/**
* Initialize the relation on a set of models.
*
* @param array $models
* @param string $relation
* @return void
*/
public function initRelation(array $models, $relation)
{
foreach ($models as $model)
{
$model->setRelation($relation, $this->related->newCollection());
}
return $models;
}
/**
* Match the eagerly loaded results to their parents.
*
* @param array $models
* @param \Illuminate\Database\Eloquent\Collection $results
* @param string $relation
* @return array
*/
public function match(array $models, Collection $results, $relation)
{
$dictionary = $this->buildDictionary($results);
// Once we have an array dictionary of child objects we can easily match the
// children back to their parent using the dictionary and the keys on the
// the parent models. Then we will return the hydrated models back out.
foreach ($models as $model)
{
if (isset($dictionary[$key = $model->getKey()]))
{
$collection = $this->related->newCollection($dictionary[$key]);
$model->setRelation($relation, $collection);
}
}
return $models;
}
/**
* Build model dictionary keyed by the relation's foreign key.
*
* @param \Illuminate\Database\Eloquent\Collection $results
* @return array
*/
protected function buildDictionary(Collection $results)
{
$foreign = $this->foreignKey;
// First we will build a dictionary of child models keyed by the foreign key
// of the relation so that we will easily and quickly match them to their
// parents without having a possibly slow inner loops for every models.
$dictionary = array();
foreach ($results as $result)
{
$dictionary[$result->pivot->$foreign][] = $result;
}
return $dictionary;
}
/**
* Touch all of the related models for the relationship.
*
* E.g.: Touch all roles associated with this user.
*
* @return void
*/
public function touch()
{
$key = $this->getRelated()->getKeyName();
$columns = $this->getRelatedFreshUpdate();
// If we actually have IDs for the relation, we will run the query to update all
// the related model's timestamps, to make sure these all reflect the changes
// to the parent models. This will help us keep any caching synced up here.
$ids = $this->getRelatedIds();
if (count($ids) > 0)
{
$this->getRelated()->newQuery()->whereIn($key, $ids)->update($columns);
}
}
/**
* Get all of the IDs for the related models.
*
* @return array
*/
public function getRelatedIds()
{
$related = $this->getRelated();
$fullKey = $related->getQualifiedKeyName();
return $this->getQuery()->select($fullKey)->lists($related->getKeyName());
}
/**
* Save a new model and attach it to the parent model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param array $joining
* @param bool $touch
* @return \Illuminate\Database\Eloquent\Model
*/
public function save(Model $model, array $joining = array(), $touch = true)
{
$model->save(array('touch' => false));
$this->attach($model->getKey(), $joining, $touch);
return $model;
}
/**
* Save an array of new models and attach them to the parent model.
*
* @param array $models
* @param array $joinings
* @return array
*/
public function saveMany(array $models, array $joinings = array())
{
foreach ($models as $key => $model)
{
$this->save($model, (array) array_get($joinings, $key), false);
}
$this->touchIfTouching();
return $models;
}
/**
* Create a new instance of the related model.
*
* @param array $attributes
* @param array $joining
* @param bool $touch
* @return \Illuminate\Database\Eloquent\Model
*/
public function create(array $attributes, array $joining = array(), $touch = true)
{
$instance = $this->related->newInstance($attributes);
// Once we save the related model, we need to attach it to the base model via
// through intermediate table so we'll use the existing "attach" method to
// accomplish this which will insert the record and any more attributes.
$instance->save(array('touch' => false));
$this->attach($instance->getKey(), $joining, $touch);
return $instance;
}
/**
* Create an array of new instances of the related models.
*
* @param array $records
* @param array $joinings
* @return \Illuminate\Database\Eloquent\Model
*/
public function createMany(array $records, array $joinings = array())
{
$instances = array();
foreach ($records as $key => $record)
{
$instances[] = $this->create($record, (array) array_get($joinings, $key), false);
}
$this->touchIfTouching();
return $instances;
}
/**
* Sync the intermediate tables with a list of IDs.
*
* @param array $ids
* @param bool $detaching
* @return array
*/
public function sync(array $ids, $detaching = true)
{
$changes = array(
'attached' => array(), 'detached' => array(), 'updated' => array()
);
// First we need to attach any of the associated models that are not currently
// in this joining table. We'll spin through the given IDs, checking to see
// if they exist in the array of current ones, and if not we will insert.
$current = $this->newPivotQuery()->lists($this->otherKey);
$records = $this->formatSyncList($ids);
$detach = array_diff($current, array_keys($records));
// Next, we will take the differences of the currents and given IDs and detach
// all of the entities that exist in the "current" array but are not in the
// the array of the IDs given to the method which will complete the sync.
if ($detaching && count($detach) > 0)
{
$this->detach($detach);
$changes['detached'] = (array) array_walk($detach, 'intval');
}
// Now we are finally ready to attach the new records. Note that we'll disable
// touching until after the entire operation is complete so we don't fire a
// ton of touch operations until we are totally done syncing the records.
$changes = array_merge(
$changes, $this->attachNew($records, $current, false)
);
$this->touchIfTouching();
return $changes;
}
/**
* Format the sync list so that it is keyed by ID.
*
* @param array $records
* @return array
*/
protected function formatSyncList(array $records)
{
$results = array();
foreach ($records as $id => $attributes)
{
if ( ! is_array($attributes))
{
list($id, $attributes) = array($attributes, array());
}
$results[$id] = $attributes;
}
return $results;
}
/**
* Attach all of the IDs that aren't in the current array.
*
* @param array $records
* @param array $current
* @param bool $touch
* @return array
*/
protected function attachNew(array $records, array $current, $touch = true)
{
$changes = array('attached' => array(), 'updated' => array());
foreach ($records as $id => $attributes)
{
// If the ID is not in the list of existing pivot IDs, we will insert a new pivot
// record, otherwise, we will just update this existing record on this joining
// table, so that the developers will easily update these records pain free.
if ( ! in_array($id, $current))
{
$this->attach($id, $attributes, $touch);
$changes['attached'][] = (int) $id;
}
elseif (count($attributes) > 0)
{
$this->updateExistingPivot($id, $attributes, $touch);
$changes['updated'][] = (int) $id;
}
}
return $changes;
}
/**
* Update an existing pivot record on the table.
*
* @param mixed $id
* @param array $attributes
* @param bool $touch
* @return void
*/
public function updateExistingPivot($id, array $attributes, $touch)
{
if (in_array($this->updatedAt(), $this->pivotColumns))
{
$attributes = $this->setTimestampsOnAttach($attributes, true);
}
$this->newPivotStatementForId($id)->update($attributes);
if ($touch) $this->touchIfTouching();
}
/**
* Attach a model to the parent.
*
* @param mixed $id
* @param array $attributes
* @param bool $touch
* @return void
*/
public function attach($id, array $attributes = array(), $touch = true)
{
if ($id instanceof Model) $id = $id->getKey();
$query = $this->newPivotStatement();
$query->insert($this->createAttachRecords((array) $id, $attributes));
if ($touch) $this->touchIfTouching();
}
/**
* Create an array of records to insert into the pivot table.
*
* @param array $ids
* @return void
*/
protected function createAttachRecords($ids, array $attributes)
{
$records = array();
$timed = in_array($this->createdAt(), $this->pivotColumns);
// To create the attachment records, we will simply spin through the IDs given
// and create a new record to insert for each ID. Each ID may actually be a
// key in the array, with extra attributes to be placed in other columns.
foreach ($ids as $key => $value)
{
$records[] = $this->attacher($key, $value, $attributes, $timed);
}
return $records;
}
/**
* Create a full attachment record payload.
*
* @param int $key
* @param mixed $value
* @param array $attributes
* @param bool $timed
* @return array
*/
protected function attacher($key, $value, $attributes, $timed)
{
list($id, $extra) = $this->getAttachId($key, $value, $attributes);
// To create the attachment records, we will simply spin through the IDs given
// and create a new record to insert for each ID. Each ID may actually be a
// key in the array, with extra attributes to be placed in other columns.
$record = $this->createAttachRecord($id, $timed);
return array_merge($record, $extra);
}
/**
* Get the attach record ID and extra attributes.
*
* @param mixed $key
* @param mixed $value
* @param array $attributes
* @return array
*/
protected function getAttachId($key, $value, array $attributes)
{
if (is_array($value))
{
return array($key, array_merge($value, $attributes));
}
else
{
return array($value, $attributes);
}
}
/**
* Create a new pivot attachment record.
*
* @param int $id
* @param bool $timed
* @return array
*/
protected function createAttachRecord($id, $timed)
{
$record[$this->foreignKey] = $this->parent->getKey();
$record[$this->otherKey] = $id;
// If the record needs to have creation and update timestamps, we will make
// them by calling the parent model's "freshTimestamp" method which will
// provide us with a fresh timestamp in this model's preferred format.
if ($timed)
{
$record = $this->setTimestampsOnAttach($record);
}
return $record;
}
/**
* Set the creation and update timstamps on an attach record.
*
* @param array $record
* @param bool $exists
* @return array
*/
protected function setTimestampsOnAttach(array $record, $exists = false)
{
$fresh = $this->parent->freshTimestamp();
if ( ! $exists) $record[$this->createdAt()] = $fresh;
$record[$this->updatedAt()] = $fresh;
return $record;
}
/**
* Detach models from the relationship.
*
* @param int|array $ids
* @param bool $touch
* @return int
*/
public function detach($ids = array(), $touch = true)
{
if ($ids instanceof Model) $ids = (array) $ids->getKey();
$query = $this->newPivotQuery();
// If associated IDs were passed to the method we will only delete those
// associations, otherwise all of the association ties will be broken.
// We'll return the numbers of affected rows when we do the deletes.
$ids = (array) $ids;
if (count($ids) > 0)
{
$query->whereIn($this->otherKey, $ids);
}
if ($touch) $this->touchIfTouching();
// Once we have all of the conditions set on the statement, we are ready
// to run the delete on the pivot table. Then, if the touch parameter
// is true, we will go ahead and touch all related models to sync.
$results = $query->delete();
return $results;
}
/**
* If we're touching the parent model, touch.
*
* @return void
*/
public function touchIfTouching()
{
if ($this->touchingParent()) $this->getParent()->touch();
if ($this->getParent()->touches($this->relationName)) $this->touch();
}
/**
* Determine if we should touch the parent on sync.
*
* @return bool
*/
protected function touchingParent()
{
return $this->getRelated()->touches($this->guessInverseRelation());
}
/**
* Attempt to guess the name of the inverse of the relation.
*
* @return string
*/
protected function guessInverseRelation()
{
return camel_case(str_plural(class_basename($this->getParent())));
}
/**
* Create a new query builder for the pivot table.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function newPivotQuery()
{
$query = $this->newPivotStatement();
return $query->where($this->foreignKey, $this->parent->getKey());
}
/**
* Get a new plain query builder for the pivot table.
*
* @return \Illuminate\Database\Query\Builder
*/
public function newPivotStatement()
{
return $this->query->getQuery()->newQuery()->from($this->table);
}
/**
* Get a new pivot statement for a given "other" ID.
*
* @param mixed $id
* @return \Illuminate\Database\Query\Builder
*/
public function newPivotStatementForId($id)
{
$pivot = $this->newPivotStatement();
$key = $this->parent->getKey();
return $pivot->where($this->foreignKey, $key)->where($this->otherKey, $id);
}
/**
* Create a new pivot model instance.
*
* @param array $attributes
* @param bool $exists
* @return \Illuminate\Database\Eloquent\Relations\Pivot
*/
public function newPivot(array $attributes = array(), $exists = false)
{
$pivot = $this->related->newPivot($this->parent, $attributes, $this->table, $exists);
return $pivot->setPivotKeys($this->foreignKey, $this->otherKey);
}
/**
* Create a new existing pivot model instance.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Relations\Pivot
*/
public function newExistingPivot(array $attributes = array())
{
return $this->newPivot($attributes, true);
}
/**
* Set the columns on the pivot table to retrieve.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function withPivot($columns)
{
$columns = is_array($columns) ? $columns : func_get_args();
$this->pivotColumns = array_merge($this->pivotColumns, $columns);
return $this;
}
/**
* Specify that the pivot table has creation and update timestamps.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function withTimestamps($createdAt = null, $updatedAt = null)
{
return $this->withPivot($createdAt ?: $this->createdAt(), $updatedAt ?: $this->updatedAt());
}
/**
* Get the related model's updated at column name.
*
* @return string
*/
public function getRelatedFreshUpdate()
{
return array($this->related->getUpdatedAtColumn() => $this->related->freshTimestamp());
}
/**
* Get the key for comparing against the pareny key in "has" query.
*
* @return string
*/
public function getHasCompareKey()
{
return $this->getForeignKey();
}
/**
* Get the fully qualified foreign key for the relation.
*
* @return string
*/
public function getForeignKey()
{
return $this->table.'.'.$this->foreignKey;
}
/**
* Get the fully qualified "other key" for the relation.
*
* @return string
*/
public function getOtherKey()
{
return $this->table.'.'.$this->otherKey;
}
/**
* Get the fully qualified parent key naem.
*
* @return string
*/
protected function getQualifiedParentKeyName()
{
return $this->parent->getQualifiedKeyName();
}
/**
* Get the intermediate table for the relationship.
*
* @return string
*/
public function getTable()
{
return $this->table;
}
/**
* Get the relationship name for the relationship.
*
* @return string
*/
public function getRelationName()
{
return $this->relationName;
}
}
| brunoalbano/uniac | src/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php | PHP | mit | 25,569 |
// Created by Ron 'Maxwolf' McDowell (ron.mcdowell@gmail.com)
// Timestamp 01/03/2016@1:50 AM
using System.Diagnostics.CodeAnalysis;
using OregonTrailDotNet.Event.Prefab;
using OregonTrailDotNet.Module.Director;
namespace OregonTrailDotNet.Event.Person
{
/// <summary>
/// Rocky Mountain spotted fever (RMSF), also known as blue disease, is the most lethal and most frequently reported
/// rickettsial illness in the United States.
/// </summary>
[DirectorEvent(EventCategory.Person)]
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public sealed class MountainFever : PersonInfect
{
/// <summary>Fired after the event has executed and the infection flag set on the person.</summary>
/// <param name="person">Person whom is now infected by whatever you say they are here.</param>
/// <returns>Name or type of infection the person is currently affected with.</returns>
protected override string OnPostInfection(Entity.Person.Person person)
{
return $"{person.Name} has mountain fever.";
}
}
} | Maxwolf/OregonTrail | src/Event/Person/MountainFever.cs | C# | mit | 1,107 |
import { Cursor } from '../diagram/Cursor';
import { DiagramElement } from '../diagram/DiagramElement';
import { Handle } from '../diagram/Handle';
import { AbstractCanvas } from './AbstractCanvas';
const zoomLevels = [1 / 8, 1 / 7, 1 / 6, 1 / 5, 1 / 4, 1 / 3, 1 / 2, 2 / 3, 1, 3 / 2, 2, 3, 4, 5, 6, 7, 8];
export abstract class InteractiveCanvas extends AbstractCanvas {
private _selectedElements: Set<DiagramElement<any>>;
private _handles: Map<DiagramElement<any>, Handle[]>;
private _resizeListeners: Map<DiagramElement<any>, Function>;
private _hoveredElement: DiagramElement<any> | null;
/**
* Sets the element being hovered over
*
* @param element The new element
*/
set hoveredElement(element: DiagramElement<any> | null) {
if (this._hoveredElement === element) return;
if (this._hoveredElement) {
this._hoveredElement.hover(false);
this._hoveredElement.onMouseLeave(this);
}
this._hoveredElement = element;
this.cursor = element ? element.cursor : 'default';
if (this._hoveredElement) this._hoveredElement.hover(true);
this.rerender();
}
get hoveredElement(): DiagramElement<any> | null {
return this._hoveredElement;
}
get selectedElements(): Set<DiagramElement<any>> {
return this._selectedElements;
}
/**
* Returns the current cursor
*/
abstract get cursor(): Cursor;
/**
* Sets the current cursor
*/
abstract set cursor(value: Cursor);
constructor(ctx: CanvasRenderingContext2D) {
super(ctx);
this._handles = new Map();
this._resizeListeners = new Map();
this._selectedElements = new Set();
this._hoveredElement = null;
}
/**
* Returns the element at the given position
*/
getElementByPosition(x: number, y: number): DiagramElement<any> | null {
const realX = x / this.zoom - this.offsetX;
const realY = y / this.zoom - this.offsetY;
const handleAtPos = this.getHandleByPosition(realX, realY);
if (handleAtPos) return handleAtPos;
return this.diagram && this.diagram.getElementAtPosition(this, realX, realY) || null;
}
/**
* Returns the handle at the given position
*/
getHandleByPosition(x: number, y: number): Handle | null {
for (const handles of this._handles.values()) {
for (const handle of handles) {
if (handle.containsPoint(x, y)) return handle;
}
}
return null;
}
/**
* Selects a given element
*/
addSelection(element: DiagramElement<any>): void {
this._selectedElements.add(element);
// Add handles of the element
element.select();
const onElementResize = () => {
this.updateHandles(element);
};
this._resizeListeners.set(element, onElementResize);
element.addListener('resize', onElementResize);
onElementResize();
}
/**
* Deselects a given element
*/
deleteSelection(element: DiagramElement<any>): boolean {
// Remove handles
this._handles.delete(element);
element.deselect();
element.removeListener('resize', this._resizeListeners.get(element)!);
return this._selectedElements.delete(element);
}
/**
* Moves an element on the canvas
*
* @param element The element to move
* @param dx Movement in X direction
* @param dy Movement in Y direction
*/
moveElement(element: DiagramElement<any>, dx: number, dy: number) {
element.move(dx, dy);
// Update the element's handles
if (this._handles.has(element)) {
this.updateHandles(element);
}
}
/**
* Tests whether an element is selected
*/
isSelected(element: DiagramElement<any>): boolean {
return this._selectedElements.has(element);
}
/**
* Clears the selection of all canvas elements
*/
clearSelection() {
for (const element of this._selectedElements) {
this.deleteSelection(element);
}
this._selectedElements.clear();
}
/**
* Zooms into the diagram
*/
zoomIn(x?: number, y?: number) {
this.zoomCanvas(zoomLevels[Math.min(zoomLevels.length - 1, zoomLevels.indexOf(this.zoom) + 1)], x, y);
}
/**
* Zooms out of the diagram
*/
zoomOut(x?: number, y?: number) {
this.zoomCanvas(zoomLevels[Math.max(0, zoomLevels.indexOf(this.zoom) - 1)], x, y);
}
/**
* Zooms 100%
*/
zoom100(x?: number, y?: number) {
this.zoomCanvas(1, x, y);
}
/**
* Renders the canvas
*/
protected render(): this {
super.render();
this.pushCanvasStack();
this._ctx.scale(this.zoom, this.zoom);
this._ctx.translate(this.offsetX, this.offsetY);
this._handles.forEach((handles) => handles.forEach((handle) => handle.render(this)));
this.popCanvasStack();
return this;
}
/**
* Updates the handles of a given element
*
* @param element The element who's handles are updated
*/
protected updateHandles(element: DiagramElement<any>) {
this._handles.set(element, element.createHandles(this));
}
}
| ksm2/metagram | modules/@metagram/framework/canvas/InteractiveCanvas.ts | TypeScript | mit | 4,938 |
#include "peerreview/vrf.h"
#define SUBSYSTEM "VrfExtInfoPolicy"
VrfExtInfoPolicy::VrfExtInfoPolicy(VerifiablePRNG *vprng) : ExtInfoPolicy()
{
this->vprng = vprng;
}
VrfExtInfoPolicy::~VrfExtInfoPolicy()
{
}
int VrfExtInfoPolicy::storeExtInfo(SecureHistory *history, long long followingSeq, unsigned char *buffer, unsigned int maxlen)
{
int extInfoLen = vprng->storeExtInfo(buffer, maxlen);
if (extInfoLen > 0) {
unsigned char ty = EVT_VRF;
int ne = history->findNextEntry(&ty, 1, followingSeq);
if (ne >= 0) {
//plog(3, "GETTING VRF @%d/%lld", ne, followingSeq);
extInfoLen = history->getEntry(ne, buffer, maxlen);
//plog(3, "=> %d", extInfoLen);
}
}
return extInfoLen;
}
| jdecouchant/PAG | ORPR/libpeerreview-1.0.9-light/src/vrf/extinfo.cc | C++ | mit | 724 |
const iNaturalistAPI = require( "../inaturalist_api" );
const ControlledTerm = require( "../models/controlled_term" );
const Observation = require( "../models/observation" );
const Project = require( "../models/project" );
const Taxon = require( "../models/taxon" );
const User = require( "../models/user" );
const observations = class observations {
static create( params, options ) {
return iNaturalistAPI.post( "observations", params, options )
.then( Observation.typifyInstanceResponse );
}
static update( params, options ) {
return iNaturalistAPI.put( "observations/:id", params, options )
.then( Observation.typifyInstanceResponse );
}
static delete( params, options ) {
return iNaturalistAPI.delete( "observations/:id", params, options );
}
static fave( params, options ) {
return observations.vote( params, options );
}
static unfave( params, options ) {
return observations.unvote( params, options );
}
static vote( params, options ) {
let endpoint = "votes/vote/observation/:id";
if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) {
endpoint = "observations/:id/vote";
}
return iNaturalistAPI.post( endpoint, params, options )
.then( Observation.typifyInstanceResponse );
}
static unvote( params, options ) {
let endpoint = "votes/unvote/observation/:id";
if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) {
endpoint = "observations/:id/vote";
}
return iNaturalistAPI.delete( endpoint, params, options );
}
static subscribe( params, options ) {
if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) {
return iNaturalistAPI.put( "observations/:id/subscription", params, options );
}
return iNaturalistAPI.post( "subscriptions/Observation/:id/subscribe", params, options );
}
static review( params, options ) {
const p = Object.assign( { }, params );
p.reviewed = "true";
return iNaturalistAPI.post( "observations/:id/review", p, options );
}
static unreview( params, options ) {
const p = Object.assign( { }, params );
return iNaturalistAPI.delete( "observations/:id/review", p, options );
}
static qualityMetrics( params, options ) {
return iNaturalistAPI.get( "observations/:id/quality_metrics", params, options );
}
static setQualityMetric( params, options ) {
return iNaturalistAPI.post( "observations/:id/quality/:metric", params, options );
}
static deleteQualityMetric( params, options ) {
return iNaturalistAPI.delete( "observations/:id/quality/:metric", params, options );
}
static fetch( ids, params ) {
return iNaturalistAPI.fetch( "observations", ids, params )
.then( Observation.typifyResultsResponse );
}
static search( params, opts = { } ) {
return iNaturalistAPI.get( "observations", params, { ...opts, useAuth: true } )
.then( Observation.typifyResultsResponse );
}
static identifiers( params ) {
return iNaturalistAPI.get( "observations/identifiers", params )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { user: new User( r.user ) } )
) );
}
return response;
} );
}
static observers( params ) {
return iNaturalistAPI.get( "observations/observers", params )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { user: new User( r.user ) } )
) );
}
return response;
} );
}
static speciesCounts( params, opts = { } ) {
return iNaturalistAPI.get( "observations/species_counts", params, { ...opts, useAuth: true } )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } )
) );
}
return response;
} );
}
static iconicTaxaCounts( params, opts = { } ) {
return iNaturalistAPI.get( "observations/iconic_taxa_counts", params, { ...opts, useAuth: true } )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } )
) );
}
return response;
} );
}
static iconicTaxaSpeciesCounts( params, opts = { } ) {
return iNaturalistAPI.get( "observations/iconic_taxa_species_counts", params, { ...opts, useAuth: true } )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } )
) );
}
return response;
} );
}
static popularFieldValues( params ) {
return iNaturalistAPI.get( "observations/popular_field_values", params )
.then( response => {
if ( response.results ) {
response.results = response.results.map( res => {
const r = Object.assign( { }, res );
r.controlled_attribute = new ControlledTerm( r.controlled_attribute );
r.controlled_value = new ControlledTerm( r.controlled_value );
return r;
} );
}
return response;
} );
}
static umbrellaProjectStats( params ) {
return iNaturalistAPI.get( "observations/umbrella_project_stats", params )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { project: new Project( r.project ) } )
) );
}
return response;
} );
}
static histogram( params ) {
return iNaturalistAPI.get( "observations/histogram", params );
}
static qualityGrades( params ) {
return iNaturalistAPI.get( "observations/quality_grades", params );
}
static subscriptions( params, options ) {
return iNaturalistAPI.get( "observations/:id/subscriptions", params,
iNaturalistAPI.optionsUseAuth( options ) );
}
static taxonSummary( params ) {
return iNaturalistAPI.get( "observations/:id/taxon_summary", params );
}
static updates( params, options ) {
return iNaturalistAPI.get( "observations/updates", params,
iNaturalistAPI.optionsUseAuth( options ) );
}
static viewedUpdates( params, options ) {
return iNaturalistAPI.put( "observations/:id/viewed_updates", params,
iNaturalistAPI.optionsUseAuth( options ) );
}
static identificationCategories( params ) {
return iNaturalistAPI.get( "observations/identification_categories", params );
}
static taxonomy( params ) {
return iNaturalistAPI.get( "observations/taxonomy", params )
.then( Taxon.typifyResultsResponse );
}
static similarSpecies( params, opts ) {
const options = Object.assign( { }, opts || { } );
options.useAuth = true;
return iNaturalistAPI.get( "observations/similar_species", params, options )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } )
) );
}
return response;
} );
}
static taxa( params ) {
return iNaturalistAPI.get( "observations/taxa", params );
}
};
module.exports = observations;
| inaturalist/inaturalistjs | lib/endpoints/observations.js | JavaScript | mit | 7,513 |
package dk.itu.ejuuragr.tests;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.anji.util.Properties;
import dk.itu.ejuuragr.turing.MinimalTuringMachine;
public class MinimalTuringMachineTest {
MinimalTuringMachine tm;
@Before
public void before(){
Properties props = new Properties();
props.setProperty("tm.m", "2");
props.setProperty("tm.shift.length", "3");
tm = new MinimalTuringMachine(props);
}
@Test
public void testShift(){
double[] tmstim = new double[]{
0, 1, //Write
1, //Write interpolation
0, //Content jump
1, 0, 0 //Shift
};
double[] result = tm.processInput(tmstim)[0];
Assert.assertArrayEquals(new double[]{0, 0}, result, 0.0);
tmstim = new double[]{
0, 0, //Write
0, //Write interpolation
0, //Content jump
0, 0, 1 //Shift
};
result = tm.processInput(tmstim)[0];
Assert.assertArrayEquals(new double[]{0, 1}, result, 0.0);
}
@Test
public void testContentBasedJump(){
//Write jump target
double[] tmstim = new double[]{
0, 1, //Write
1, //Write interpolation
0, //Content jump
0, 0, 1 //Shift
};
double[] result = tm.processInput(tmstim)[0];
//Write jump result
tmstim = new double[]{
1, 0, //Write
1, //Write interpolation
0, //Content jump
0, 0, 1 //Shift
};
result = tm.processInput(tmstim)[0];
//Jump, shift, and read
tmstim = new double[]{
0, 1, //Write
0, //Write interpolation
1, //Content jump
0, 0, 1 //Shift
};
result = tm.processInput(tmstim)[0];
Assert.assertArrayEquals(new double[]{1, 0}, result, 0.0);
}
@Test
public void testContentBasedJumpLonger(){
//Write jump target
double[] tmstim = new double[]{
0, 1, //Write
1, //Write interpolation
0, //Content jump
0, 0, 1 //Shift
};
double[] result = tm.processInput(tmstim)[0];
//Write jump result
tmstim = new double[]{
1, 0, //Write
1, //Write interpolation
0, //Content jump
0, 0, 1 //Shift
};
result = tm.processInput(tmstim)[0];
//Move right
for (int k = 0; k < 10; k++){
tmstim = new double[]{
0, 0, //Write
0, //Write interpolation
0, //Content jump
0, 0, 1 //Shift
};
result = tm.processInput(tmstim)[0];
}
//Jump, shift, and read
tmstim = new double[]{
0, 1, //Write
0, //Write interpolation
1, //Content jump
0, 0, 1 //Shift
};
result = tm.processInput(tmstim)[0];
Assert.assertArrayEquals(new double[]{1, 0}, result, 0.0);
}
@Test
public void testCopyTaskSimple(){
double[][] seq = new double[][]{
{0,1,0}, //Start
{1,0,0}, //Data
{0,0,0}, //Data
{0,0,0}, //Data
{1,0,0}, //Data
{1,0,0}, //Data
{0,0,1}, //End
{0,0,0}, //Poll
{0,0,0}, //Poll
{0,0,0}, //Poll
{0,0,0}, //Poll
{0,0,0}, //Poll
};
double[] lastRoundRead = new double[]{0,0};
for (int round = 0; round < seq.length; round++){
double d = seq[round][0];
double s = seq[round][1];
double b = seq[round][2];
lastRoundRead = act(d + lastRoundRead[0],s + b + lastRoundRead[1], 1-b, b, 0, b ,1-b);
double roundResult = lastRoundRead[0];
if (round > 6){
double verify = seq[round-6][0];
Assert.assertEquals(verify, roundResult, 0.00);
}
}
}
private double[] act(double d1, double d2, double write, double jump, double shiftLeft, double shiftStay, double shiftRight){
return tm.processInput(new double[]{
d1, d2, //Write
write, //Write interpolation
jump, //Content jump
shiftLeft, shiftStay, shiftRight //Shift
})[0];
}
}
| Fumaloko92/MSc-Thesis | 17-05-2017/neuralturingmachines-master/src/dk/itu/ejuuragr/tests/MinimalTuringMachineTest.java | Java | mit | 3,649 |
package meta_test
import (
"reflect"
"testing"
"time"
"github.com/archsaber/influxdb/influxql"
"github.com/archsaber/influxdb/services/meta"
)
func Test_Data_DropDatabase(t *testing.T) {
data := &meta.Data{
Databases: []meta.DatabaseInfo{
{Name: "db0"},
{Name: "db1"},
{Name: "db2"},
{Name: "db4"},
{Name: "db5"},
},
Users: []meta.UserInfo{
{Name: "user1", Privileges: map[string]influxql.Privilege{"db1": influxql.ReadPrivilege, "db2": influxql.ReadPrivilege}},
{Name: "user2", Privileges: map[string]influxql.Privilege{"db2": influxql.ReadPrivilege}},
},
}
// Dropping the first database removes it from the Data object.
expDbs := make([]meta.DatabaseInfo, 4)
copy(expDbs, data.Databases[1:])
if err := data.DropDatabase("db0"); err != nil {
t.Fatal(err)
} else if got, exp := data.Databases, expDbs; !reflect.DeepEqual(got, exp) {
t.Fatalf("got %v, expected %v", got, exp)
}
// Dropping a middle database removes it from the data object.
expDbs = []meta.DatabaseInfo{{Name: "db1"}, {Name: "db2"}, {Name: "db5"}}
if err := data.DropDatabase("db4"); err != nil {
t.Fatal(err)
} else if got, exp := data.Databases, expDbs; !reflect.DeepEqual(got, exp) {
t.Fatalf("got %v, expected %v", got, exp)
}
// Dropping the last database removes it from the data object.
expDbs = []meta.DatabaseInfo{{Name: "db1"}, {Name: "db2"}}
if err := data.DropDatabase("db5"); err != nil {
t.Fatal(err)
} else if got, exp := data.Databases, expDbs; !reflect.DeepEqual(got, exp) {
t.Fatalf("got %v, expected %v", got, exp)
}
// Dropping a database also drops all the user privileges associated with
// it.
expUsers := []meta.UserInfo{
{Name: "user1", Privileges: map[string]influxql.Privilege{"db1": influxql.ReadPrivilege}},
{Name: "user2", Privileges: map[string]influxql.Privilege{}},
}
if err := data.DropDatabase("db2"); err != nil {
t.Fatal(err)
} else if got, exp := data.Users, expUsers; !reflect.DeepEqual(got, exp) {
t.Fatalf("got %v, expected %v", got, exp)
}
}
func Test_Data_CreateRetentionPolicy(t *testing.T) {
data := meta.Data{}
err := data.CreateDatabase("foo")
if err != nil {
t.Fatal(err)
}
err = data.CreateRetentionPolicy("foo", &meta.RetentionPolicyInfo{
Name: "bar",
ReplicaN: 1,
Duration: 24 * time.Hour,
}, false)
if err != nil {
t.Fatal(err)
}
rp, err := data.RetentionPolicy("foo", "bar")
if err != nil {
t.Fatal(err)
}
if rp == nil {
t.Fatal("creation of retention policy failed")
}
// Try to recreate the same RP with default set to true, should fail
err = data.CreateRetentionPolicy("foo", &meta.RetentionPolicyInfo{
Name: "bar",
ReplicaN: 1,
Duration: 24 * time.Hour,
}, true)
if err == nil || err != meta.ErrRetentionPolicyConflict {
t.Fatalf("unexpected error. got: %v, exp: %s", err, meta.ErrRetentionPolicyConflict)
}
// Creating the same RP with the same specifications should succeed
err = data.CreateRetentionPolicy("foo", &meta.RetentionPolicyInfo{
Name: "bar",
ReplicaN: 1,
Duration: 24 * time.Hour,
}, false)
if err != nil {
t.Fatal(err)
}
}
func TestData_AdminUserExists(t *testing.T) {
data := meta.Data{}
// No users means no admin.
if data.AdminUserExists() {
t.Fatal("no admin user should exist")
}
// Add a non-admin user.
if err := data.CreateUser("user1", "a", false); err != nil {
t.Fatal(err)
}
if got, exp := data.AdminUserExists(), false; got != exp {
t.Fatalf("got %v, expected %v", got, exp)
}
// Add an admin user.
if err := data.CreateUser("admin1", "a", true); err != nil {
t.Fatal(err)
}
if got, exp := data.AdminUserExists(), true; got != exp {
t.Fatalf("got %v, expected %v", got, exp)
}
// Remove the original user
if err := data.DropUser("user1"); err != nil {
t.Fatal(err)
}
if got, exp := data.AdminUserExists(), true; got != exp {
t.Fatalf("got %v, expected %v", got, exp)
}
// Add another admin
if err := data.CreateUser("admin2", "a", true); err != nil {
t.Fatal(err)
}
if got, exp := data.AdminUserExists(), true; got != exp {
t.Fatalf("got %v, expected %v", got, exp)
}
// Revoke privileges of the first admin
if err := data.SetAdminPrivilege("admin1", false); err != nil {
t.Fatal(err)
}
if got, exp := data.AdminUserExists(), true; got != exp {
t.Fatalf("got %v, expected %v", got, exp)
}
// Add user1 back.
if err := data.CreateUser("user1", "a", false); err != nil {
t.Fatal(err)
}
// Revoke remaining admin.
if err := data.SetAdminPrivilege("admin2", false); err != nil {
t.Fatal(err)
}
// No longer any admins
if got, exp := data.AdminUserExists(), false; got != exp {
t.Fatalf("got %v, expected %v", got, exp)
}
// Make user1 an admin
if err := data.SetAdminPrivilege("user1", true); err != nil {
t.Fatal(err)
}
if got, exp := data.AdminUserExists(), true; got != exp {
t.Fatalf("got %v, expected %v", got, exp)
}
// Drop user1...
if err := data.DropUser("user1"); err != nil {
t.Fatal(err)
}
if got, exp := data.AdminUserExists(), false; got != exp {
t.Fatalf("got %v, expected %v", got, exp)
}
}
func TestUserInfo_AuthorizeDatabase(t *testing.T) {
emptyUser := &meta.UserInfo{}
if !emptyUser.AuthorizeDatabase(influxql.NoPrivileges, "anydb") {
t.Fatal("expected NoPrivileges to be authorized but it wasn't")
}
if emptyUser.AuthorizeDatabase(influxql.ReadPrivilege, "anydb") {
t.Fatal("expected ReadPrivilege to prevent authorization, but it was authorized")
}
adminUser := &meta.UserInfo{Admin: true}
if !adminUser.AuthorizeDatabase(influxql.AllPrivileges, "anydb") {
t.Fatalf("expected admin to be authorized but it wasn't")
}
}
| archsaber/influxdb | services/meta/data_test.go | GO | mit | 5,658 |
<?php
use awheel\App;
use Monolog\Logger;
use awheel\Support\Arr;
use awheel\Http\Request;
use awheel\Http\Response;
use awheel\Routing\Router;
use awheel\Http\Kernel as HttpKernel;
use awheel\Console\Kernel as ConsoleKernel;
/**
* 返回应用实例, 或应用组件
*
* @param $make
*
* @return App|Router|Request|Response|HttpKernel|ConsoleKernel|Logger
*/
function app($make = null)
{
if (is_null($make)) {
return App::getInstance();
}
return App::make($make);
}
/**
* 路由名称转为 url, 参数为路由定义时的参数, 多余的使用 http query 链接
*
* @param $name
* @param array $params
*
* @return mixed|string
*/
function route($name, $params = [])
{
$namedRoutes = app('router')->namedRoutes;
if (!isset($namedRoutes[$name])) return $name;
$uri = $namedRoutes[$name];
$uri = preg_replace_callback('/\{(.*?)(:.*?)?(\{[0-9,]+\})?\}/', function ($m) use (&$params) {
return isset($params[$m[1]]) ? Arr::pull($params, $m[1]) : $m[0];
}, $uri);
if (! empty($params)) {
$uri .= '?'.http_build_query($params);
}
return rtrim(app()->configGet('app.base_url'), '/').$uri;
}
/**
* 获取 basePath 或基于 basePath 的目录
*
* @param string $path
*
* @return string
*/
function base_path($path = '')
{
return app()->basePath.($path ? '/'.ltrim($path, '/') : '');
}
| awheel/framework | src/Support/Helpers.php | PHP | mit | 1,379 |
package examples
const JSONExample_User = `{
"name": "calavera"
}`
| calavera/json_generate | examples/simple.go | GO | mit | 69 |
#include "../widgetslib.h"
#include "button.h"
#include "Meta/math/vector4.h"
#include "vertex.h"
#include "Meta/keyvalue/metatable_impl.h"
#include "Meta/serialize/serializetable_impl.h"
#include "fontloader.h"
#include "imageloader.h"
METATABLE_BEGIN_BASE(Engine::Widgets::Button, Engine::Widgets::WidgetBase)
MEMBER(mText)
MEMBER(mFontSize)
MEMBER(mPivot)
PROPERTY(Font, font, setFont)
PROPERTY(Image, image, setImage)
METATABLE_END(Engine::Widgets::Button)
SERIALIZETABLE_INHERIT_BEGIN(Engine::Widgets::Button, Engine::Widgets::WidgetBase)
FIELD(mText)
FIELD(mFontSize)
FIELD(mPivot)
ENCAPSULATED_FIELD(mFont, fontName, setFontName)
ENCAPSULATED_FIELD(Image, imageName, setImageName)
SERIALIZETABLE_END(Engine::Widgets::Button)
namespace Engine {
namespace Widgets {
void Button::setImageName(std::string_view name)
{
setImage(Resources::ImageLoader::getSingleton().get(name));
}
void Button::setImage(Resources::ImageLoader::ResourceType *image)
{
mImage = image;
}
std::string_view Button::imageName() const
{
return mImage ? mImage->name() : "";
}
Resources::ImageLoader::ResourceType *Button::image() const
{
return mImage;
}
Resources::ImageLoader::ResourceType *Button::resource() const
{
return mImage;
}
Threading::SignalStub<> &Button::clickEvent()
{
return mClicked;
}
std::vector<std::pair<std::vector<Vertex>, TextureSettings>> Button::vertices(const Vector3 &screenSize)
{
std::vector<std::pair<std::vector<Vertex>, TextureSettings>> returnSet;
std::vector<Vertex> result;
Vector3 pos = (getEffectivePosition() * screenSize) / screenSize;
Vector3 size = (getEffectiveSize() * screenSize) / screenSize;
pos.z = depth();
Vector4 color = mHovered ? Vector4 { 1.0f, 0.1f, 0.1f, 1.0f } : Vector4 { 0.4f, 0.4f, 0.4f, 1.0f };
Vector3 v = pos;
result.push_back({ v, color, { 0.0f, 0.0f } });
v.x += size.x;
result.push_back({ v, color, { 1.0f, 0.0f } });
v.y += size.y;
result.push_back({ v, color, { 1.0f, 1.0f } });
result.push_back({ v, color, { 1.0f, 1.0f } });
v.x -= size.x;
result.push_back({ v, color, { 0.0f, 1.0f } });
v.y -= size.y;
result.push_back({ v, color, { 0.0f, 0.0f } });
returnSet.push_back({ result, {} });
if (mFont.available() /*&& mFont->mTexture.available()*/) {
//mFont->setPersistent(true);
std::pair<std::vector<Vertex>, TextureSettings> fontVertices = renderText(mText, pos, size.xy(), mFont, size.z * mFontSize, mPivot, screenSize);
if (!fontVertices.first.empty())
returnSet.push_back(fontVertices);
}
return returnSet;
}
bool Button::injectPointerEnter(const Input::PointerEventArgs &arg)
{
mHovered = true;
return true;
}
bool Button::injectPointerLeave(const Input::PointerEventArgs &arg)
{
mHovered = false;
mClicking = false;
return true;
}
bool Button::injectPointerPress(const Input::PointerEventArgs &arg)
{
mClicking = true;
return true;
}
bool Button::injectPointerRelease(const Input::PointerEventArgs &arg)
{
if (mClicking)
emitClicked();
return true;
}
void Button::emitClicked()
{
mClicked.emit();
}
WidgetClass Button::getClass() const
{
return WidgetClass::BUTTON;
}
std::string_view Button::fontName() const
{
return mFont.name();
}
void Button::setFontName(std::string_view name)
{
mFont.load(name);
}
Render::FontLoader::ResourceType *Button::font() const
{
return mFont.resource();
}
void Button::setFont(Render::FontLoader::HandleType font)
{
mFont = std::move(font);
}
}
} | MadManRises/Madgine | plugins/core/widgets/src/Madgine/widgets/button.cpp | C++ | mit | 3,973 |
// Copyright 2014 The Gogs 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 base
import (
"container/list"
"encoding/json"
"fmt"
"html/template"
"runtime"
"strings"
"time"
"golang.org/x/net/html/charset"
"golang.org/x/text/transform"
"github.com/gogits/chardet"
"github.com/pecastro/gogs/modules/setting"
)
func Safe(raw string) template.HTML {
return template.HTML(raw)
}
func Str2html(raw string) template.HTML {
return template.HTML(Sanitizer.Sanitize(raw))
}
func Range(l int) []int {
return make([]int, l)
}
func List(l *list.List) chan interface{} {
e := l.Front()
c := make(chan interface{})
go func() {
for e != nil {
c <- e.Value
e = e.Next()
}
close(c)
}()
return c
}
func Sha1(str string) string {
return EncodeSha1(str)
}
func ShortSha(sha1 string) string {
if len(sha1) == 40 {
return sha1[:10]
}
return sha1
}
func DetectEncoding(content []byte) (string, error) {
detector := chardet.NewTextDetector()
result, err := detector.DetectBest(content)
if result.Charset != "UTF-8" && len(setting.AnsiCharset) > 0 {
return setting.AnsiCharset, err
}
return result.Charset, err
}
func ToUtf8WithErr(content []byte) (error, string) {
charsetLabel, err := DetectEncoding(content)
if err != nil {
return err, ""
}
if charsetLabel == "UTF-8" {
return nil, string(content)
}
encoding, _ := charset.Lookup(charsetLabel)
if encoding == nil {
return fmt.Errorf("unknow char decoder %s", charsetLabel), string(content)
}
result, n, err := transform.String(encoding.NewDecoder(), string(content))
// If there is an error, we concatenate the nicely decoded part and the
// original left over. This way we won't loose data.
if err != nil {
result = result + string(content[n:])
}
return err, result
}
func ToUtf8(content string) string {
_, res := ToUtf8WithErr([]byte(content))
return res
}
// RenderCommitMessage renders commit message with XSS-safe and special links.
func RenderCommitMessage(msg, urlPrefix string) template.HTML {
return template.HTML(string(RenderIssueIndexPattern([]byte(template.HTMLEscapeString(msg)), urlPrefix)))
}
var mailDomains = map[string]string{
"gmail.com": "gmail.com",
}
var TemplateFuncs template.FuncMap = map[string]interface{}{
"GoVer": func() string {
return strings.Title(runtime.Version())
},
"AppName": func() string {
return setting.AppName
},
"AppSubUrl": func() string {
return setting.AppSubUrl
},
"AppVer": func() string {
return setting.AppVer
},
"AppDomain": func() string {
return setting.Domain
},
"DisableGravatar": func() bool {
return setting.DisableGravatar
},
"LoadTimes": func(startTime time.Time) string {
return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
},
"AvatarLink": AvatarLink,
"Safe": Safe,
"Str2html": Str2html,
"TimeSince": TimeSince,
"RawTimeSince": RawTimeSince,
"FileSize": FileSize,
"Subtract": Subtract,
"Add": func(a, b int) int {
return a + b
},
"ActionIcon": ActionIcon,
"DateFmtLong": func(t time.Time) string {
return t.Format(time.RFC1123Z)
},
"DateFmtShort": func(t time.Time) string {
return t.Format("Jan 02, 2006")
},
"List": List,
"Mail2Domain": func(mail string) string {
if !strings.Contains(mail, "@") {
return "try.gogs.io"
}
suffix := strings.SplitN(mail, "@", 2)[1]
domain, ok := mailDomains[suffix]
if !ok {
return "mail." + suffix
}
return domain
},
"SubStr": func(str string, start, length int) string {
if len(str) == 0 {
return ""
}
end := start + length
if length == -1 {
end = len(str)
}
if len(str) < end {
return str
}
return str[start:end]
},
"DiffTypeToStr": DiffTypeToStr,
"DiffLineTypeToStr": DiffLineTypeToStr,
"Sha1": Sha1,
"ShortSha": ShortSha,
"Md5": EncodeMd5,
"ActionContent2Commits": ActionContent2Commits,
"Oauth2Icon": Oauth2Icon,
"Oauth2Name": Oauth2Name,
"ToUtf8": ToUtf8,
"EscapePound": func(str string) string {
return strings.Replace(strings.Replace(str, "%", "%25", -1), "#", "%23", -1)
},
"RenderCommitMessage": RenderCommitMessage,
}
type Actioner interface {
GetOpType() int
GetActUserName() string
GetActEmail() string
GetRepoUserName() string
GetRepoName() string
GetRepoPath() string
GetRepoLink() string
GetBranch() string
GetContent() string
GetCreate() time.Time
GetIssueInfos() []string
}
// ActionIcon accepts a int that represents action operation type
// and returns a icon class name.
func ActionIcon(opType int) string {
switch opType {
case 1, 8: // Create, transfer repository.
return "repo"
case 5, 9: // Commit repository.
return "git-commit"
case 6: // Create issue.
return "issue-opened"
case 10: // Comment issue.
return "comment"
default:
return "invalid type"
}
}
type PushCommit struct {
Sha1 string
Message string
AuthorEmail string
AuthorName string
}
type PushCommits struct {
Len int
Commits []*PushCommit
CompareUrl string
}
func ActionContent2Commits(act Actioner) *PushCommits {
var push *PushCommits
if err := json.Unmarshal([]byte(act.GetContent()), &push); err != nil {
return nil
}
return push
}
func DiffTypeToStr(diffType int) string {
diffTypes := map[int]string{
1: "add", 2: "modify", 3: "del",
}
return diffTypes[diffType]
}
func DiffLineTypeToStr(diffType int) string {
switch diffType {
case 2:
return "add"
case 3:
return "del"
case 4:
return "tag"
}
return "same"
}
func Oauth2Icon(t int) string {
switch t {
case 1:
return "fa-github-square"
case 2:
return "fa-google-plus-square"
case 3:
return "fa-twitter-square"
case 4:
return "fa-qq"
case 5:
return "fa-weibo"
}
return ""
}
func Oauth2Name(t int) string {
switch t {
case 1:
return "GitHub"
case 2:
return "Google+"
case 3:
return "Twitter"
case 4:
return "腾讯 QQ"
case 5:
return "Weibo"
}
return ""
}
| pecastro/gogs | modules/base/template.go | GO | mit | 6,062 |
/**
* @author Adam Meadows <adam.meadows@gmail.com>
* @copyright 2015 Adam Meadows. All rights reserved.
*/
'use strict';
/* eslint-disable max-nested-callbacks */
let $ = require('jquery');
let main = require('aiw-ui');
describe('main', () => {
let $container;
beforeEach(() => {
$container = $('<div/>');
main.render($container[0]);
});
it('renders template', () => {
expect($('.main p', $container)).toHaveText('This is my first webpack project!');
});
});
| jobsquad/aiw-ui | spec/karma/index-spec.6.js | JavaScript | mit | 513 |
import {Sample} from './sample'
import {context} from './init_audio'
let instanceIndex = 0
export class SampleOscillator extends Sample{
constructor(sampleData, event){
super(sampleData, event)
this.id = `${this.constructor.name}_${instanceIndex++}_${new Date().getTime()}`
if(this.sampleData === -1){
// create dummy source
this.source = {
start(){},
stop(){},
connect(){},
}
}else{
// @TODO add type 'custom' => PeriodicWave
let type = this.sampleData.type
this.source = context.createOscillator()
switch(type){
case 'sine':
case 'square':
case 'sawtooth':
case 'triangle':
this.source.type = type
break
default:
this.source.type = 'square'
}
this.source.frequency.value = event.frequency
}
this.output = context.createGain()
this.volume = event.data2 / 127
this.output.gain.value = this.volume
this.source.connect(this.output)
//this.output.connect(context.destination)
}
}
| abudaan/qambi | src/sample_oscillator.js | JavaScript | mit | 1,076 |
require "spec_helper"
describe TecDoc::DateParser do
describe "#to_date" do
it "should convert 199904 to April 1st, 1999" do
TecDoc::DateParser.new("199904").to_date.should == Date.new(1999, 4, 1)
end
it "should convert 201012 to December 1st, 2012" do
TecDoc::DateParser.new("201012").to_date.should == Date.new(2010, 12, 1)
end
it "should return nil when nil" do
TecDoc::DateParser.new(nil).to_date.should == nil
end
end
end
| mak-it/tec_doc | spec/tec_doc/date_parser_spec.rb | Ruby | mit | 476 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.datalakestore.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.UUID;
/** The encryption identity properties. */
@Fluent
public class EncryptionIdentity {
@JsonIgnore private final ClientLogger logger = new ClientLogger(EncryptionIdentity.class);
/*
* The type of encryption being used. Currently the only supported type is
* 'SystemAssigned'.
*/
@JsonProperty(value = "type", required = true)
private String type;
/*
* The principal identifier associated with the encryption.
*/
@JsonProperty(value = "principalId", access = JsonProperty.Access.WRITE_ONLY)
private UUID principalId;
/*
* The tenant identifier associated with the encryption.
*/
@JsonProperty(value = "tenantId", access = JsonProperty.Access.WRITE_ONLY)
private UUID tenantId;
/** Creates an instance of EncryptionIdentity class. */
public EncryptionIdentity() {
type = "SystemAssigned";
}
/**
* Get the type property: The type of encryption being used. Currently the only supported type is 'SystemAssigned'.
*
* @return the type value.
*/
public String type() {
return this.type;
}
/**
* Set the type property: The type of encryption being used. Currently the only supported type is 'SystemAssigned'.
*
* @param type the type value to set.
* @return the EncryptionIdentity object itself.
*/
public EncryptionIdentity withType(String type) {
this.type = type;
return this;
}
/**
* Get the principalId property: The principal identifier associated with the encryption.
*
* @return the principalId value.
*/
public UUID principalId() {
return this.principalId;
}
/**
* Get the tenantId property: The tenant identifier associated with the encryption.
*
* @return the tenantId value.
*/
public UUID tenantId() {
return this.tenantId;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| Azure/azure-sdk-for-java | sdk/datalakestore/azure-resourcemanager-datalakestore/src/main/java/com/azure/resourcemanager/datalakestore/models/EncryptionIdentity.java | Java | mit | 2,508 |
<div id="center">
<div class="col-md-6 center">
<div id="notification" class="notification row">
<ul class="nav nav-tabs">
<li role="presentation" class="active"><a data-toggle="pill" href="#noti1">Notification</a></li>
<li role="presentation"><a data-toggle="pill" href="#events1">Assignment</a></li>
<li role="presentation"><a data-toggle="pill" href="#files1">Event</a></li>
</ul>
<div class="tab-content">
<div id="noti1" class="tab-pane fade in active">
</div>
<div id="events1" class="tab-pane fade e1">
<h3>Calender</h3>
<p>Calendar Goes Here</p>
</div>
<div id="files1" class="tab-pane fade f1">
</div>
</div>
</div>
<div class="top-btn ">
<?php if($this->session->userdata('role')== "teacher"){
echo '
<div class="btn-group">
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#add_notification">Post Notification</button>
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#add_event">Add Event</button>
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#upload_file">Upload File</button>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="upload_file" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Upload File</h4>
</div>
<div class="modal-body">
<!-- Form -->
<form id="form_id" class="form-horizontal add-file" role="form" enctype="multipart/form-data" accept-charset="utf-8" metho="post" action="">
<div class="form-group">
<!--<label class="col-sm-3 control-label">File</label>-->
<div class="col-sm-10">
<input type="file" name="file_name" size="20" />
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="text" id="sub_list1" name="subject_name" readonly>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<div class="btn-group">
<button type="button" class="btn btn-primary btn-sm">Select Subject</button>
<button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul id="subject_list1" class="dropdown-menu" role="menu">';
foreach ($subject as $row) {
echo
'<li><a href="#">'.$row['subject_name'].'</a></li>';
}
echo '</ul>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<button class="btn btn-primary btn-sm" id="hello1" onClick="upload();">Upload</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<a href="index.php/upload/do_upload">Close</a>
</div>
</div>
</div>
</div>
<div class="modal fade" id="add_event" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Event</h4>
</div>
<div class="modal-body">
<!-- Form -->
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-3 control-label">Subject</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="subject_code" placeholder="Subject Code"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-10">
<button type="submit" class="btn btn-default">Add</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="add_notification" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Post Notification</h4>
</div>
<div class="modal-body">
<!-- Form -->
<form class="form-horizontal notification1" role="form">
<div class="form-group">
<div class="col-sm-12">
<textarea class="form-control" rows="5" name="notification_content" placeholder="Notification Content"/></textarea>
</div>
</div>
<input type="hidden" name="user_id" value="'.$this->session->userdata('user_id').'"/>
<div class="form-group">
<div class="col-sm-10">
<input type="text" id="sub_list" name="subject_name" readonly>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<div class="btn-group">
<button id="hello" type="button" class="btn btn-primary btn-sm">Select Subject</button>
<button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul id="subject_list" class="dropdown-menu" role="menu">';
foreach ($subject as $row) {
echo
'<li><a href="#">'.$row['subject_name'].'</a></li>';
}
echo '</ul>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<button type="button" class="btn btn-primary btn-sm" id="add_noti">Post</button>
</div>
</div>
</form>
<!-- Form End -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>'; }?>
<div id="notification" class="notification row">
<ul class="nav nav-pills nav-justified">
<li role="presentation" class="active"><a data-toggle="pill" href="#noti"><span class="glyphicon glyphicon-envelope"></span>Notification</a></li>
<li role="presentation"><a data-toggle="pill" href="#events"><span class="glyphicon glyphicon-calendar"></span>Calender</a></li>
<li role="presentation"><a data-toggle="pill" href="#files"><span class="glyphicon glyphicon-file"></span>Files</a></li>
</ul>
<div class="tab-content">
<div id="noti" class="tab-pane fade in active">
<ul class="ul1 whole">
<?php
foreach($notification as $row)
{
// echo $row['notification_content'];
echo
'<li class="li1 clearfix">
<div class="col-md-2">
<img class="img2" src='.$row['img_location'].'>
</div>
<div class="col-md-10 noti-content">
<h4>'.$row['user_name'].'</h4>
<p>'.$row['notification_content'].'</p>
</div>
</li>';
}
?>
</ul>
<div class="more"><a href="#">Load more</a></div>
</div>
<div id="events" class="tab-pane fade e1">
<h3>Calender</h3>
<p>Calendar Goes Here</p>
</div>
<div id="files" class="tab-pane fade f1">
<ul class="list-group">
<?php
foreach ($folder as $row) {
$map = directory_map('files/'.$row['folder_name']);
foreach ($map as $value) {
echo '<li class="list-group-item">'.$value.'<a class="btn btn-primary btn-sm pull-right" href="index.php/download?name='.$value.'">Download</a></li>';
}
}
?>
</ul>
</div>
</div>
</div>
</div>
</div> | babirali/myproject | application/views/layouts/center.php | PHP | mit | 8,464 |
import { Client } from 'discord.js';
import { isFunction, isRegExp, isString } from 'lodash/lang';
import CommandRegistry from '../command/CommandRegistry';
import Dispatcher from './dispatcher/Dispatcher';
import ServiceContainer from './services/ServiceContainer';
/**
* @external {ClientOptions} https://discord.js.org/#/docs/main/stable/typedef/ClientOptions
*/
/**
* @desc The Ghastly client.
* @extends Client
*/
export default class Ghastly extends Client {
/**
* Constructor.
* @param {ClientOptions} options - The options for the client.
* @param {PrefixType} options.prefix - The prefix for the client's dispatcher.
* If a function is provided, it is given a received `Message` as an argument
* and must return a `boolean` indicating if it passes the filter.
* @throws {TypeError} Thrown if any option is of the wrong type.
*/
constructor(options) {
const { prefix, ...rest } = options;
if (!isString(prefix) && !isRegExp(prefix) && !isFunction(prefix)) {
throw new TypeError('Expected prefix to be a string, RegExp or function.');
}
super(rest);
/**
* The command registry for the client.
* @type {CommandRegistry}
*/
this.commands = new CommandRegistry();
/**
* The client's service container.
* @type {ServiceContainer}
*/
this.services = new ServiceContainer();
/**
* The client's dispatcher.
* @type {Dispatcher}
* @private
*/
this.dispatcher = new Dispatcher({ client: this, prefix });
}
}
| hkwu/ghastly | src/client/Ghastly.js | JavaScript | mit | 1,545 |
/*
* Copyright (c) 2010 Simon Hardijanto
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package magefortress.jobs.subtasks;
import magefortress.core.MFEDirection;
import magefortress.core.MFLocation;
import magefortress.core.MFUnexpectedStateException;
import magefortress.creatures.behavior.movable.MFCapability;
import magefortress.creatures.behavior.movable.MFIMovable;
import magefortress.map.MFPath;
import magefortress.map.MFPathFinder;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class MFGotoLocationSubtaskTest
{
private MFGotoLocationSubtask gotoTask;
private MFIMovable mockOwner;
private MFPathFinder mockPathFinder;
@Before
public void setUp()
{
this.mockOwner = mock(MFIMovable.class);
this.mockPathFinder = mock(MFPathFinder.class);
this.gotoTask = new MFGotoLocationSubtask(this.mockOwner, this.mockPathFinder);
MFLocation start = new MFLocation(4,4,4);
MFLocation goal = new MFLocation(2,2,2);
when(this.mockOwner.getLocation()).thenReturn(start);
when(this.mockOwner.getCurrentHeading()).thenReturn(goal);
}
@Test
public void shouldStartPathSearchFirstThing() throws MFSubtaskCanceledException
{
gotoTask.update();
verify(mockPathFinder).enqueuePathSearch(any(MFLocation.class),
any(MFLocation.class), anyInt(), any(MFCapability.class), eq(gotoTask));
}
@Test
public void shouldStartPathSearchIfPathIsInvalid() throws MFSubtaskCanceledException
{
// path that's first valid and then invalid
MFPath path = mock(MFPath.class);
when(path.isPathValid()).thenReturn(true).thenReturn(false);
gotoTask.update();
gotoTask.pathSearchFinished(path);
gotoTask.update();
verify(mockPathFinder).enqueuePathSearch(any(MFLocation.class),
any(MFLocation.class), anyInt(), any(MFCapability.class), eq(gotoTask));
gotoTask.update();
verify(mockPathFinder, times(2)).enqueuePathSearch(any(MFLocation.class),
any(MFLocation.class), anyInt(), any(MFCapability.class), eq(gotoTask));
}
@Test(expected=MFNoPathFoundException.class)
public void shouldCancelIfNoPathWasFound() throws MFSubtaskCanceledException
{
gotoTask.update();
gotoTask.pathSearchFinished(null);
gotoTask.update();
}
@Test
public void shouldBeginToMoveOwnerWhenPathWasFound() throws MFSubtaskCanceledException
{
// never-ending path northwards
MFPath path = mock(MFPath.class);
when(path.isPathValid()).thenReturn(true);
when(path.hasNext()).thenReturn(true);
when(path.next()).thenReturn(MFEDirection.N);
gotoTask.update();
gotoTask.pathSearchFinished(path);
gotoTask.update();
verify(mockOwner).move(any(MFEDirection.class));
}
@Test
public void shouldMoveOwnerAccordingToHisSpeed() throws MFSubtaskCanceledException
{
// never-ending path northwards
MFPath path = mock(MFPath.class);
when(path.isPathValid()).thenReturn(true);
when(path.hasNext()).thenReturn(true);
when(path.next()).thenReturn(MFEDirection.N);
when(mockOwner.getSpeed()).thenReturn(3);
gotoTask.update();
gotoTask.pathSearchFinished(path);
gotoTask.update();
verify(mockOwner).move(any(MFEDirection.class));
gotoTask.update();
verify(mockOwner).move(any(MFEDirection.class));
gotoTask.update();
verify(mockOwner).move(any(MFEDirection.class));
gotoTask.update();
verify(mockOwner, times(2)).move(any(MFEDirection.class));
}
@Test
public void shouldBeDoneWhenGoalWasReached() throws MFSubtaskCanceledException
{
MFLocation goal = new MFLocation(1, 2, 3);
// 2-tile path northwards
MFPath path = mock(MFPath.class);
when(path.isPathValid()).thenReturn(true);
when(path.hasNext()).thenReturn(true);
when(path.next()).thenReturn(MFEDirection.N);
when(mockOwner.getSpeed()).thenReturn(3);
when(mockOwner.getCurrentHeading()).thenReturn(goal);
boolean done = true;
done = gotoTask.update();
assertFalse(done);
gotoTask.pathSearchFinished(path);
// 1st move
done = gotoTask.update();
assertFalse(done);
done = gotoTask.update();
assertFalse(done);
done = gotoTask.update();
assertFalse(done);
// 2nd move
when(mockOwner.getLocation()).thenReturn(goal);
when(path.hasNext()).thenReturn(true).thenReturn(false);
done = gotoTask.update();
assertTrue(done);
}
@Test(expected=MFUnexpectedStateException.class)
public void shouldThrowExceptionWhenPathEndsNotAtGoal() throws MFSubtaskCanceledException
{
MFLocation goal = new MFLocation(1, 2, 3);
// 2-tile path northwards
MFPath path = mock(MFPath.class);
when(path.isPathValid()).thenReturn(true);
when(path.hasNext()).thenReturn(true);
when(path.next()).thenReturn(MFEDirection.N);
when(mockOwner.getSpeed()).thenReturn(3);
when(mockOwner.getCurrentHeading()).thenReturn(goal);
gotoTask.update();
gotoTask.pathSearchFinished(path);
// 1st move
gotoTask.update();
gotoTask.update();
gotoTask.update();
// 2nd move
when(mockOwner.getLocation()).thenReturn(new MFLocation(1,1,3));
when(path.hasNext()).thenReturn(true).thenReturn(false);
gotoTask.update();
}
@Test(expected=MFUnexpectedStateException.class)
public void shouldThrowExceptionAfterGoalWasReached() throws MFSubtaskCanceledException
{
MFLocation goal = new MFLocation(1, 2, 3);
// 2-tile path northwards
MFPath path = mock(MFPath.class);
when(path.isPathValid()).thenReturn(true);
when(path.hasNext()).thenReturn(true);
when(path.next()).thenReturn(MFEDirection.N);
when(mockOwner.getSpeed()).thenReturn(3);
when(mockOwner.getCurrentHeading()).thenReturn(goal);
gotoTask.update();
gotoTask.pathSearchFinished(path);
// 1st move
gotoTask.update();
gotoTask.update();
gotoTask.update();
// 2nd move
when(mockOwner.getLocation()).thenReturn(goal);
when(path.hasNext()).thenReturn(true).thenReturn(false);
boolean done = gotoTask.update();
assertTrue(done);
gotoTask.update();
}
@Test
public void shouldSetHeadingWhenSearchingForAPath() throws MFSubtaskCanceledException
{
MFLocation goal = new MFLocation(1,2,3);
gotoTask = new MFGotoLocationSubtask(mockOwner, goal, mockPathFinder);
MFLocation prevGoal = new MFLocation (3,2,1);
when(mockOwner.getCurrentHeading()).thenReturn(prevGoal);
gotoTask.update();
verify(mockOwner).setCurrentHeading(goal);
}
@Test
public void shouldNotSearchPathIfAlreadyThere() throws MFSubtaskCanceledException
{
MFLocation goal = new MFLocation(1,2,3);
when(this.mockOwner.getCurrentHeading()).thenReturn(goal);
when(this.mockOwner.getLocation()).thenReturn(goal);
this.gotoTask = new MFGotoLocationSubtask(this.mockOwner, this.mockPathFinder);
this.gotoTask.update();
verify(this.mockPathFinder, never()).enqueuePathSearch(any(MFLocation.class),
any(MFLocation.class), anyInt(), any(MFCapability.class), eq(gotoTask));
}
} | metaluna/magefortress | test/magefortress/jobs/subtasks/MFGotoLocationSubtaskTest.java | Java | mit | 8,185 |
using System;
using System.Runtime.CompilerServices;
using Pantheon.Core.MessageRouting;
namespace Pantheon.Core
{
public class MessageCallback
{
private ulong _callback;
private MessageCode _expected;
private Message _request;
private Message _response;
private MessageRouter _router;
private DateTime _timeout;
public Message Response
{
get { return _response; }
set { _response = value; }
}
internal MessageCode Expected
{
get { return _expected; }
}
public MessageCallback(MessageRouter router, Message message, int timeout)
{
_timeout = DateTime.Now + new TimeSpan(0, 0, 0, 0, timeout);
_callback = message.From;
_request = message;
_router = router;
}
public class MessageCallbackAwaiter : INotifyCompletion
{
private ulong _channel;
private MessageCallback _message;
private Message _response;
private MessageRouter _router;
public bool IsCompleted
{
get { return _response != null || DateTime.Now > _message._timeout; }
}
public MessageCallbackAwaiter(MessageRouter router, MessageCallback callback, ulong channel)
{
_router = router;
_message = callback;
_channel = channel;
_response = null;
router.RegisterRoute(OnReceive, channel);
router.MessageDirector.QueueSend(callback._request);
}
public MessageCallbackAwaiter GetAwaiter()
{
return this;
}
public Message GetResult()
{
return _response;
}
public void OnCompleted(Action continuation)
{
while (!IsCompleted) ;
_router.DestroyRoute(m => m.Target == this);
if (continuation != null)
{
continuation();
}
}
private void OnReceive(Message message)
{
if (_message._expected > 0)
{
var code = message.ReadMessageCode();
message.Position -= 4;
if (code != _message._expected)
{
return;
}
}
_message.Response = message;
_response = message;
}
}
public MessageCallback Expect(MessageCode expectedHeader)
{
_expected = expectedHeader;
return this;
}
public MessageCallbackAwaiter GetAwaiter()
{
var awaiter = new MessageCallbackAwaiter(_router, this, _callback);
return awaiter;
}
}
} | seaboy1234/Pantheon | Pantheon.Core/MessageCallback.cs | C# | mit | 3,007 |
var React = require('react'),
cx = require('classnames'),
constants = require('./constants');
var Preloader = React.createClass({
propTypes: {
size: React.PropTypes.oneOf(constants.SCALES),
active: React.PropTypes.bool,
colors: React.PropTypes.array
},
getDefaultProps() {
return {
active: true,
colors: ['blue', 'red', 'yellow', 'green']
};
},
render() {
var classes = {
'preloader-wrapper': true,
active: this.props.active
};
if (this.props.size) {
classes[this.props.size] = true;
}
return (
<div className={cx(this.props.className, classes)}>
{this.props.colors.map(color => {
var spinnerClasses = {
'spinner-layer': true
};
spinnerClasses['spinner-' + color] = true;
return (
<div className={cx(spinnerClasses)}>
<div className="circle-clipper left">
<div className="circle"></div>
</div><div className="gap-patch">
<div className="circle"></div>
</div><div className="circle-clipper right">
<div className="circle"></div>
</div>
</div>
);
})}
</div>
);
}
});
module.exports = Preloader;
| openmaphub/react-materialize | src/Preloader.js | JavaScript | mit | 1,309 |
class DotenvHaiku
# Dotenv Railtie for using Dotenv to load environment from a file into
# Ruby applications
class App
# Public: Load dotenv
#
# Manually call `Dotenv::Railtie.load` in your app's config
def load(options = {})
Dotenv.load(*to_load(options))
end
# Internal: Try the `RAILS_ROOT` environment variable,
# or the current working directory.
def root
Pathname.new(ENV["RAILS_ROOT"] || Dir.pwd)
end
def to_load(options = {})
options = {
:app_root => root
}.merge(options)
DotenvHaiku::Loader.new(options)
end
# Rails uses `#method_missing` to delegate all class methods to the
# instance, which means `Kernel#load` gets called here. We don't want that.
def self.load(options = {})
new.load(options)
end
end
end
| metavida/dotenv-haiku | lib/dotenv-haiku/to_load/generic.rb | Ruby | mit | 835 |
#include "nilConfig.h"
#include "nil.h"
#include "nilUtil.h"
#include "nilWindows.h"
#ifdef NIL_PLATFORM_WINDOWS
#define NIL_FIELD_OFFSET(type, field) ((LONG_PTR)&(((type*)0)->field))
#define NIL_DIJ2OFS_BUTTON(n) (NIL_FIELD_OFFSET(DIJOYSTATE2, rgbButtons)+(n))
#define NIL_DIJ2OFS_POV(n) (NIL_FIELD_OFFSET(DIJOYSTATE2, rgdwPOV)+(n)*sizeof(DWORD))
#define NIL_DIJ2OFS_SLIDER0(n) (NIL_FIELD_OFFSET(DIJOYSTATE2, rglSlider)+(n)*sizeof(LONG))
#define NIL_DIJ2OFS_SLIDER1(n) (NIL_FIELD_OFFSET(DIJOYSTATE2, rglVSlider)+(n)*sizeof(LONG))
#define NIL_DIJ2OFS_SLIDER2(n) (NIL_FIELD_OFFSET(DIJOYSTATE2, rglASlider)+(n)*sizeof(LONG))
#define NIL_DIJ2OFS_SLIDER3(n) (NIL_FIELD_OFFSET(DIJOYSTATE2, rglFSlider)+(n)*sizeof(LONG))
namespace nil {
const unsigned long cJoystickEvents = 64;
DirectInputController::DirectInputController( DirectInputDevice* device,
const Cooperation coop ):
Controller( device->getSystem(), device ), diDevice_( nullptr ),
axisEnum_( 0 ), coop_( coop )
{
HRESULT hr = device->getSystem()->dinput_->CreateDevice(
device->getInstanceID(), &diDevice_, nullptr );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not create DirectInput8 device" );
hr = diDevice_->SetDataFormat( &c_dfDIJoystick2 );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not set DirectInput8 device data format" );
// Force feedback, to be implemented later, requires exclusive access.
hr = diDevice_->SetCooperativeLevel( device->getSystem()->window_,
( coop_ == Cooperation::Background )
? DISCL_BACKGROUND | DISCL_EXCLUSIVE
: DISCL_FOREGROUND | DISCL_EXCLUSIVE );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not set DirectInput8 device cooperation level" );
DIPROPDWORD bufsize;
bufsize.diph.dwSize = sizeof( DIPROPDWORD );
bufsize.diph.dwHeaderSize = sizeof( DIPROPHEADER );
bufsize.diph.dwObj = 0;
bufsize.diph.dwHow = DIPH_DEVICE;
bufsize.dwData = cJoystickEvents;
hr = diDevice_->SetProperty( DIPROP_BUFFERSIZE, &bufsize.diph );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not set DirectInput8 device buffer size" );
diCaps_.dwSize = sizeof( DIDEVCAPS );
hr = diDevice_->GetCapabilities( &diCaps_ );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not get DirectInput8 device capabilities" );
// Identify a more specific controller type, if available
switch ( diCaps_.dwDevType )
{
case DI8DEVTYPE_JOYSTICK:
type_ = Controller::Controller_Joystick;
break;
case DI8DEVTYPE_GAMEPAD:
type_ = Controller::Controller_Gamepad;
break;
case DI8DEVTYPE_1STPERSON:
type_ = Controller::Controller_Firstperson;
break;
case DI8DEVTYPE_DRIVING:
type_ = Controller::Controller_Driving;
break;
case DI8DEVTYPE_FLIGHT:
type_ = Controller::Controller_Flight;
break;
}
state_.povs.resize( (size_t)diCaps_.dwPOVs );
state_.buttons.resize( (size_t)diCaps_.dwButtons );
axisEnum_ = 0;
sliderEnum_ = 0;
diDevice_->EnumObjects( diComponentsEnumCallback, this, DIDFT_AXIS );
state_.axes.resize( axisEnum_ );
// TODO This is totally untested. I haven't found a single controller
// that actually reports sliders, so this code _could_ crash and burn.
// Let me know if it does. :)
if ( sliderEnum_ > 0 )
{
sliderEnum_ /= 2;
state_.sliders.resize( sliderEnum_ );
}
}
BOOL CALLBACK DirectInputController::diComponentsEnumCallback(
LPCDIDEVICEOBJECTINSTANCEW component, LPVOID referer )
{
auto controller = static_cast<DirectInputController*>( referer );
if ( component->guidType == GUID_Slider )
{
controller->sliderEnum_++;
}
else
{
DIPROPPOINTER prop;
prop.diph.dwSize = sizeof( DIPROPPOINTER );
prop.diph.dwHeaderSize = sizeof( DIPROPHEADER );
prop.diph.dwHow = DIPH_BYID;
prop.diph.dwObj = component->dwType;
prop.uData = 0x6E690000 | controller->axisEnum_;
HRESULT hr = controller->diDevice_->SetProperty( DIPROP_APPDATA, &prop.diph );
if ( FAILED( hr ) )
return DIENUM_CONTINUE;
controller->axisEnum_++;
}
DIPROPRANGE range;
range.diph.dwSize = sizeof( DIPROPRANGE );
range.diph.dwHeaderSize = sizeof( DIPROPHEADER );
range.diph.dwHow = DIPH_BYID;
range.diph.dwObj = component->dwType;
range.lMin = -32768;
range.lMax = 32767;
HRESULT hr = controller->diDevice_->SetProperty( DIPROP_RANGE, &range.diph );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not set axis range property on DirectInput8 device" );
return DIENUM_CONTINUE;
}
Real DirectInputController::filterAxis( int val )
{
if ( val < 0 )
{
Real ret = (Real)val / (Real)( 32767 );
return ( ret < NIL_REAL_MINUSONE ? NIL_REAL_MINUSONE : ret );
}
if ( val > 0 )
{
Real ret = (Real)val / (Real)( 32767 );
return ( ret > NIL_REAL_ONE ? NIL_REAL_ONE : ret );
}
return NIL_REAL_ZERO;
}
void DirectInputController::update()
{
DIDEVICEOBJECTDATA buffers[cJoystickEvents];
unsigned long entries = cJoystickEvents;
ControllerState lastState = state_;
bool done = false;
while ( !done )
{
HRESULT hr = diDevice_->Poll();
if ( hr == DI_OK )
hr = diDevice_->GetDeviceData( sizeof( DIDEVICEOBJECTDATA ), buffers, &entries, 0 );
if ( hr != DI_OK )
{
hr = diDevice_->Acquire();
while ( hr == DIERR_INPUTLOST )
hr = diDevice_->Acquire();
hr = diDevice_->Poll();
if ( FAILED( hr ) )
return;
hr = diDevice_->GetDeviceData( sizeof( DIDEVICEOBJECTDATA ), buffers, &entries, 0 );
if ( FAILED( hr ) )
return;
}
if ( entries < cJoystickEvents )
done = true;
for ( unsigned long i = 0; i < entries; i++ )
{
if ( (size_t)buffers[i].dwOfs >= NIL_DIJ2OFS_POV( 0 )
&& (size_t)buffers[i].dwOfs < NIL_DIJ2OFS_POV( state_.povs.size() ) )
{
size_t pov = (size_t)buffers[i].dwOfs - NIL_DIJ2OFS_POV( 0 );
if ( LOWORD( buffers[i].dwData ) == 0xFFFF )
state_.povs[pov].direction = POV::Centered;
else
{
switch ( buffers[i].dwData )
{
case 0: state_.povs[pov].direction = POV::North; break;
case 4500: state_.povs[pov].direction = POV::NorthEast; break;
case 9000: state_.povs[pov].direction = POV::East; break;
case 13500: state_.povs[pov].direction = POV::SouthEast; break;
case 18000: state_.povs[pov].direction = POV::South; break;
case 22500: state_.povs[pov].direction = POV::SouthWest; break;
case 27000: state_.povs[pov].direction = POV::West; break;
case 31500: state_.povs[pov].direction = POV::NorthWest; break;
}
}
}
else if ( (size_t)buffers[i].dwOfs >= NIL_DIJ2OFS_BUTTON( 0 )
&& (size_t)buffers[i].dwOfs < NIL_DIJ2OFS_BUTTON( state_.buttons.size() ) )
{
auto button = static_cast<size_t>( buffers[i].dwOfs - NIL_DIJ2OFS_BUTTON( 0 ) );
state_.buttons[button].pushed = ( buffers[i].dwData & 0x80 ? true : false );
}
else if ( (uint16_t)( buffers[i].uAppData >> 16 ) == 0x6E69 )
{
auto axis = static_cast<size_t>( 0x0000FFFF & buffers[i].uAppData );
state_.axes[axis].absolute = filterAxis( buffers[i].dwData );
}
else
{
switch ( buffers[i].dwOfs )
{
case NIL_DIJ2OFS_SLIDER0( 0 ):
state_.sliders[0].absolute.x = filterAxis( buffers[i].dwData );
break;
case NIL_DIJ2OFS_SLIDER0( 1 ):
state_.sliders[0].absolute.y = filterAxis( buffers[i].dwData );
break;
case NIL_DIJ2OFS_SLIDER1( 0 ):
state_.sliders[1].absolute.x = filterAxis( buffers[i].dwData );
break;
case NIL_DIJ2OFS_SLIDER1( 1 ):
state_.sliders[1].absolute.y = filterAxis( buffers[i].dwData );
break;
case NIL_DIJ2OFS_SLIDER2( 0 ):
state_.sliders[2].absolute.x = filterAxis( buffers[i].dwData );
break;
case NIL_DIJ2OFS_SLIDER2( 1 ):
state_.sliders[2].absolute.y = filterAxis( buffers[i].dwData );
break;
case NIL_DIJ2OFS_SLIDER3( 0 ):
state_.sliders[3].absolute.x = filterAxis( buffers[i].dwData );
break;
case NIL_DIJ2OFS_SLIDER3( 1 ):
state_.sliders[3].absolute.y = filterAxis( buffers[i].dwData );
break;
}
}
}
}
fireChanges( lastState );
}
DirectInputController::~DirectInputController()
{
if ( diDevice_ )
{
diDevice_->Unacquire();
diDevice_->Release();
}
}
}
#endif | noorus/nil | src/windows/directinput/DirectInputController.cpp | C++ | mit | 9,142 |
#include "processview.h"
ProcessView::ProcessView(QWidget *parent)
: QTableView(parent)
{
initialActions();
connect(m_refresh, SIGNAL(triggered()), this, SLOT(onRefreshActionTriggered()));
connect(m_modules, SIGNAL(triggered()), this, SLOT(onModulesActionTriggered()));
connect(m_threads, SIGNAL(triggered()), this, SLOT(onThreadsActionTriggered()));
connect(m_location, SIGNAL(triggered()), this, SLOT(onLocationActionTriggered()));
}
ProcessView::~ProcessView()
{
}
/*
* Reimplemented the virtual function QWidget::contextMenuEvent() since we want to
* create a context menu when the cursor hovered on the widget.
*/
void ProcessView::contextMenuEvent(QContextMenuEvent* e)
{
m_popmenu->clear();
QPoint pt = e->pos();
// retrieve the model index responding to the cursor position.
QModelIndex index = this->indexAt(pt);
if (index.isValid())
{
m_popmenu->addAction(m_refresh);
m_popmenu->addSeparator();
m_popmenu->addAction(m_threads);
m_popmenu->addAction(m_modules);
m_popmenu->addAction(m_location);
// show the context menu
m_popmenu->exec(QCursor::pos());
e->accept(); // stop the propagation of the QContextMenuEvent.
}
}
void ProcessView::initialActions()
{
m_popmenu = new QMenu(this);
m_refresh = new QAction(QStringLiteral("Refresh"), this);
m_modules = new QAction(QStringLiteral("Modules..."), this);
m_threads = new QAction(QStringLiteral("Theads..."), this);
m_location = new QAction(QStringLiteral("Open path..."), this);
}
void ProcessView::onRefreshActionTriggered()
{
// do nothing
QMessageBox::information(this, "TEST", "TEST", QMessageBox::Ok);
}
void ProcessView::onThreadsActionTriggered()
{
QMessageBox::information(this, "TEST", "TEST", QMessageBox::Ok);
}
void ProcessView::onModulesActionTriggered()
{
// Alternative way: currentIndex().row()
QModelIndexList indexList = this->selectionModel()->selectedRows();
unsigned int pid = model()->data(model()->index(indexList.first().row(), 1)).toUInt();
if (pid >= 0)
{
ModulesTableView mtv(pid);
mtv.exec();
}
}
void ProcessView::onLocationActionTriggered()
{
QMessageBox::information(this, "TEST", "TEST", QMessageBox::Ok);
} | martinkro/tutorial-qt | Beautiful/Process/src/processview.cpp | C++ | mit | 2,165 |
module Dominion
class Smithy < Action
def cost() 4 end
def to_s() 'Smithy' end
def play(turn)
turn.draw 3
end
end
end | jmckible/dominion | lib/dominion/action/base/smithy.rb | Ruby | mit | 167 |
from distutils.core import setup
setup(
name='sequencehelpers',
py_modules=['sequencehelpers'],
version='0.2.1',
description="A library consisting of functions for interacting with sequences and iterables.",
author='Zach Swift',
author_email='cras.zswift@gmail.com',
url='https://github.com/2achary/sequencehelpers',
download_url='https://github.com/2achary/sequence/tarball/0.2.1',
keywords=['sequence', 'single', 'distinct'],
classifiers=[],
)
| 2achary/sequencehelpers | setup.py | Python | mit | 467 |
require 'spec_helper'
require 'feature/testing'
describe 'Feature testing support' do
let(:repository) { Feature::Repository::SimpleRepository.new }
before(:each) do
repository.add_active_feature(:active_feature)
Feature.set_repository(repository)
end
it 'should execute code block with an deactivated feature' do
expect(Feature.active?(:another_feature)).to be_falsey
Feature.run_with_activated(:another_feature) do
expect(Feature.active?(:another_feature)).to be_truthy
end
expect(Feature.active?(:another_feature)).to be_falsey
end
it 'should execute code block with an deactivated feature' do
expect(Feature.active?(:active_feature)).to be_truthy
Feature.run_with_deactivated(:active_feature) do
expect(Feature.active?(:active_feature)).to be_falsey
end
expect(Feature.active?(:active_feature)).to be_truthy
end
context 'Multiple features' do
before(:each) do
repository.add_active_feature(:second_active_feature)
Feature.set_repository(repository)
end
it "should enable multiple deactivated features" do
expect(Feature.active?(:active_feature)).to be_truthy
expect(Feature.active?(:second_active_feature)).to be_truthy
end
it "should execute code block with multiple deactivated features" do
Feature.run_with_activated([:active_feature, :second_active_feature]) do
expect(Feature.active?(:active_feature)).to be_truthy
expect(Feature.active?(:second_active_feature)).to be_truthy
end
end
end
end
| moneyadviceservice/feature | spec/feature/testing_spec.rb | Ruby | mit | 1,561 |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kirppu', '0039_counter_private_key'),
]
operations = [
migrations.AlterUniqueTogether(
name='itemtype',
unique_together={('event', 'order')},
),
migrations.RemoveField(
model_name='itemtype',
name='key',
),
]
| jlaunonen/kirppu | kirppu/migrations/0040_remove_itemtype_key.py | Python | mit | 408 |
from django.contrib import admin
from .models import BackgroundImages, Widget
class WidgetAdmin(admin.ModelAdmin):
list_display = ('name', 'link', 'is_featured')
ordering = ('-id',)
class BackgroundAdmin(admin.ModelAdmin):
list_display = ('name', 'created_at')
ordering = ('-id',)
admin.site.register(Widget, WidgetAdmin)
admin.site.register(BackgroundImages, BackgroundAdmin)
| malikshahzad228/widget-jack | widgets/admin.py | Python | mit | 400 |
<?php
return [
'@class' => 'Grav\\Common\\File\\CompiledYamlFile',
'filename' => 'user/config/system.yaml',
'modified' => 1431195484,
'data' => [
'home' => [
'alias' => '/home'
],
'pages' => [
'theme' => 'deliver',
'markdown_extra' => false,
'process' => [
'markdown' => true,
'twig' => false
]
],
'cache' => [
'enabled' => false,
'check' => [
'method' => 'file'
],
'driver' => 'auto',
'prefix' => 'g'
],
'twig' => [
'cache' => true,
'debug' => true,
'auto_reload' => true,
'autoescape' => false
],
'assets' => [
'css_pipeline' => false,
'css_minify' => true,
'css_rewrite' => true,
'js_pipeline' => false,
'js_minify' => true
],
'debugger' => [
'enabled' => false,
'twig' => true,
'shutdown' => [
'close_connection' => true
]
]
]
];
| camoncal/julioewebsite | cache/compiled/files/50d05a56140aa6d4a1a465e38ca8c7a4.yaml.php | PHP | mit | 1,190 |
let userDao = require('../dao/userDao'),
articleDao = require('../dao/articleDao'),
commentDao = require('../dao/commentDao'),
starDao = require('../dao/starDao'),
messageDao = require('../dao/messageDao'),
voteDao = require('../dao/voteDao'),
settings = require('../config/settings'),
tools = require('../config/tools'),
jwt = require("jsonwebtoken"),
moment = require("moment"),
request = require('request'),
crypto = require('crypto'), //crypto 是 Node.js 的一个核心模块,我们用它生成散列值来加密密码
sha1 = crypto.createHash('sha1');
module.exports = app => {
function getAccToken(req, res) {
// let options = {
// uri: "https://api.weixin.qq.com/cgi-bin/token",
// method: "get",
// json: true,
// qs: {
// grant_type: "client_credential",
// appid: "wx7b739a344a69a410",
// secret: "9296286bb73ac0391d2eaf2b668c668a"
// }
// };
if (tools.isBlank(req.body.grant_type) || tools.isBlank(req.body.appid) || tools.isBlank(req.body.secret) || tools.isBlank(req.body.url)) {
res.json({
code: 500,
msg: '缺少参数'
})
return;
}
let options = {
uri: "https://api.weixin.qq.com/cgi-bin/token",
method: "get",
json: true,
qs: {
grant_type: req.body.grant_type,
appid: req.body.appid,
secret: req.body.secret
}
};
function callback(error, response, data) {
if (!error && response.statusCode == 200 && tools.isNotBlank(data) && tools.isNotBlank(data.access_token)) {
getTicket(req, res, data.access_token);
} else {
res.json({
code: 500,
msg: '获取access_token失败',
data: data
})
}
}
request(options, callback);
}
function getTicket(req, res, access_token) {
let options = {
uri: "https://api.weixin.qq.com/cgi-bin/ticket/getticket",
method: "get",
json: true,
qs: {
access_token: access_token,
type: "jsapi"
}
};
function callback(error, response, data) {
if (!error && response.statusCode == 200 && tools.isNotBlank(data) && data.errcode == 0 && tools.isNotBlank(data.ticket)) {
getSignature(req, res, access_token, data.ticket);
} else {
res.json({
code: 500,
msg: '获取ticket失败',
data: data
})
}
}
request(options, callback);
}
function getSignature(req, res, access_token, ticket) {
let jsapi_ticket = ticket,
nonceStr = tools.randomWord(false, 32),
timestamp = parseInt((new Date().getTime())/1000),
url = req.body.url;
let str = `jsapi_ticket=${jsapi_ticket}&noncestr=${nonceStr}×tamp=${timestamp}&url=${url}`
let signature = sha1.update(str).digest('hex');
res.json({
code: 200,
msg: 'ok',
ob: {
accessToken: access_token,
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature
}
})
}
//检查收到的参数确认是否来自微信调用
function checkSignature(req) {
let signature = req.query.signature,
timestamp = req.query.timestamp,
nonce = req.query.timestamp;
let arr = ['yourToken', timestamp, nonce];
let str = arr.sort().join('');
let sig = sha1.update(str).digest('hex');
if (sig === signature) {
return true;
} else {
return false;
}
}
//给微信调用
app.get('/forWechat', (req, res, next) => {
if (tools.isBlank(req.query.signature) || tools.isBlank(req.query.timestamp) || tools.isBlank(req.query.nonce) || tools.isBlank(req.query.echostr) || checkSignature(req)) {
next();
} else {
res.send(req.query.echostr);
}
});
//获取微信签名
app.post('/getAccToken', (req, res, next) => {
getAccToken(req, res);
});
app.get('/login', (req, res, next) => {
let user = {
id: '5902bc7cd7e7550ab6203037',
name: 'name',
level: '初级',
avatar: 'http://image.beekka.com/blog/2014/bg2014051201.png'
}
let authToken = jwt.sign({
user: user,
exp: moment().add('days', 30).valueOf(),
}, settings.jwtSecret);
res.json({
code: 200,
msg: 'ok',
token: authToken
});
});
app.get('/w', (req, res, next) => {
res.json({
code: 200,
msg: 'ok',
user: req.users
});
});
//添加用户
app.get('/addUser', (req, res, next) => {
userDao.addUser(req, res, next)
});
//获取用户
app.get('/getUser', (req, res, next) => {
userDao.getUser(req, res, next)
});
//删除用户
app.get('/removeUser', (req, res, next) => {
userDao.removeUser(req, res, next)
});
//发表文章
app.post('/addArticle', (req, res, next) => {
articleDao.addArticle(req, res, next)
});
//删除文章
app.get('/removeArticle', (req, res, next) => {
articleDao.removeArticle(req, res, next)
});
//更新文章 -- 暂时不做
// app.get('/updateArticle', (req, res, next) => {
// articleDao.updateArticle(req, res, next)
// });
//获取文章详情
app.get('/article', (req, res, next) => {
articleDao.getArticle(req, res, next)
});
//获取文章列表
app.get('/articleList', (req, res, next) => {
articleDao.getArticleList(req, res, next)
});
//获取精选文章
app.get('/handpickList', (req, res, next) => {
articleDao.getHandpickList(req, res, next)
});
//根据类型获取文章
app.get('/articleListByType', (req, res, next) => {
articleDao.getArticleListByType(req, res, next)
});
//获取用户文章
app.get('/articleListByUser', (req, res, next) => {
articleDao.getArticleListByUser(req, res, next)
});
//获取收藏的文章
app.get('/articleListByCollection', (req, res, next) => {
articleDao.getArticleListByCollection(req, res, next)
});
//收藏
app.post('/addCollection', (req, res, next) => {
articleDao.addArticleCollections(req, res, next)
});
//取消收藏
app.get('/removeCollection', (req, res, next) => {
articleDao.removeArticleCollections(req, res, next)
});
//发表评论
app.post('/addComment', (req, res, next) => {
commentDao.addComment(req, res, next)
});
//删除评论
app.get('/removeComment', (req, res, next) => {
commentDao.removeComment(req, res, next)
});
//评论列表
app.get('/commentList', (req, res, next) => {
commentDao.getCommentList(req, res, next)
});
//消息列表
app.get('/message', (req, res, next) => {
messageDao.getMessageList(req, res, next)
});
//点赞
app.post('/addStar', (req, res, next) => {
starDao.addStar(req, res, next)
});
//取消赞
app.get('/removeStar', (req, res, next) => {
starDao.removeStar(req, res, next)
});
//赞列表
app.get('/starList', (req, res, next) => {
starDao.getStarList(req, res, next)
});
//他人信息
app.get('/otherInfo', (req, res, next) => {
userDao.getOtherInfo(req, res, next)
});
//自己信息
app.get('/selfInfo', (req, res, next) => {
userDao.getUserInfo(req, res, next)
});
//添加投票
app.post('/addVote', (req, res, next) => {
voteDao.addVote(req, res, next)
});
//确定投票
app.post('/commitVote', (req, res, next) => {
voteDao.commitVote(req, res, next)
});
//获取投票详情
app.get('/vote', (req, res, next) => {
voteDao.getVote(req, res, next)
});
//获取投票列表
app.get('/voteList', (req, res, next) => {
voteDao.getVoteList(req, res, next)
});
//已投票用户列表
app.get('/voteUserList', (req, res, next) => {
voteDao.getVoteUserList(req, res, next)
});
//获取顶部3条,1条投票2条精选
app.get('/getTopList', (req, res, next) => {
articleDao.getTopList(req, res, next)
});
} | wayshon/community-server | routes/api.js | JavaScript | mit | 8,947 |
from pandac.PandaModules import *
from toontown.toonbase.ToonBaseGlobal import *
from DistributedMinigame import *
from direct.interval.IntervalGlobal import *
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from toontown.safezone import Walk
from toontown.toonbase import ToontownTimer
from direct.gui import OnscreenText
import MinigameAvatarScorePanel
from direct.distributed import DistributedSmoothNode
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from otp.otpbase import OTPGlobals
import TagGameGlobals
import Trajectory
class DistributedTagGame(DistributedMinigame):
DURATION = TagGameGlobals.DURATION
IT_SPEED_INCREASE = 1.3
IT_ROT_INCREASE = 1.3
def __init__(self, cr):
DistributedMinigame.__init__(self, cr)
self.gameFSM = ClassicFSM.ClassicFSM('DistributedTagGame', [State.State('off', self.enterOff, self.exitOff, ['play']), State.State('play', self.enterPlay, self.exitPlay, ['cleanup']), State.State('cleanup', self.enterCleanup, self.exitCleanup, ['off'])], 'off', 'off')
self.addChildGameFSM(self.gameFSM)
self.walkStateData = Walk.Walk('walkDone')
self.scorePanels = []
self.initialPositions = ((0, 10, 0, 180, 0, 0),
(10, 0, 0, 90, 0, 0),
(0, -10, 0, 0, 0, 0),
(-10, 0, 0, -90, 0, 0))
base.localAvatar.isIt = 0
self.modelCount = 4
def getTitle(self):
return TTLocalizer.TagGameTitle
def getInstructions(self):
return TTLocalizer.TagGameInstructions
def getMaxDuration(self):
return self.DURATION
def load(self):
self.notify.debug('load')
DistributedMinigame.load(self)
self.itText = OnscreenText.OnscreenText('itText', fg=(0.95, 0.95, 0.65, 1), scale=0.14, font=ToontownGlobals.getSignFont(), pos=(0.0, -0.8), wordwrap=15, mayChange=1)
self.itText.hide()
self.sky = loader.loadModel('phase_3.5/models/props/TT_sky')
self.ground = loader.loadModel('phase_4/models/minigames/tag_arena')
self.music = base.loadMusic('phase_4/audio/bgm/MG_toontag.ogg')
self.tagSfx = base.loadSfx('phase_4/audio/sfx/MG_Tag_C.ogg')
self.itPointer = loader.loadModel('phase_4/models/minigames/bboard-pointer')
self.tracks = []
self.IT = None
return
def unload(self):
self.notify.debug('unload')
DistributedMinigame.unload(self)
self.ignoreAll()
del self.tracks
del self.IT
self.sky.removeNode()
del self.sky
self.itPointer.removeNode()
del self.itPointer
self.ground.removeNode()
del self.ground
del self.music
del self.tagSfx
self.itText.cleanup()
del self.itText
self.removeChildGameFSM(self.gameFSM)
del self.gameFSM
def onstage(self):
self.notify.debug('onstage')
DistributedMinigame.onstage(self)
self.ground.reparentTo(render)
self.sky.reparentTo(render)
myPos = self.avIdList.index(self.localAvId)
base.localAvatar.setPosHpr(*self.initialPositions[myPos])
base.localAvatar.reparentTo(render)
base.localAvatar.loop('neutral')
camera.reparentTo(render)
camera.setPosHpr(0, -24, 16, 0, -30, 0)
base.camLens.setFar(450.0)
base.transitions.irisIn(0.4)
NametagGlobals.setMasterArrowsOn(1)
DistributedSmoothNode.activateSmoothing(1, 1)
self.IT = None
return
def offstage(self):
self.notify.debug('offstage')
DistributedSmoothNode.activateSmoothing(1, 0)
NametagGlobals.setMasterArrowsOn(0)
DistributedMinigame.offstage(self)
self.sky.reparentTo(hidden)
self.ground.reparentTo(hidden)
base.camLens.setFar(ToontownGlobals.DefaultCameraFar)
self.itText.hide()
def setGameReady(self):
if not self.hasLocalToon:
return
self.notify.debug('setGameReady')
if DistributedMinigame.setGameReady(self):
return
for avId in self.avIdList:
self.acceptTagEvent(avId)
myPos = self.avIdList.index(self.localAvId)
for i in xrange(self.numPlayers):
avId = self.avIdList[i]
avatar = self.getAvatar(avId)
if avatar:
avatar.startSmooth()
base.localAvatar.setPosHpr(*self.initialPositions[myPos])
base.localAvatar.d_clearSmoothing()
base.localAvatar.sendCurrentPosition()
base.localAvatar.b_setAnimState('neutral', 1)
base.localAvatar.b_setParent(ToontownGlobals.SPRender)
def setGameStart(self, timestamp):
if not self.hasLocalToon:
return
self.notify.debug('setGameStart')
DistributedMinigame.setGameStart(self, timestamp)
self.gameFSM.request('play')
def enterOff(self):
self.notify.debug('enterOff')
def exitOff(self):
pass
def enterPlay(self):
self.notify.debug('enterPlay')
for i in xrange(self.numPlayers):
avId = self.avIdList[i]
avName = self.getAvatarName(avId)
scorePanel = MinigameAvatarScorePanel.MinigameAvatarScorePanel(avId, avName)
scorePanel.setPos(-0.213, 0.0, 0.28 * i + 0.66)
scorePanel.reparentTo(base.a2dBottomRight)
self.scorePanels.append(scorePanel)
base.setCellsAvailable(base.rightCells, 0)
self.walkStateData.enter()
self.walkStateData.fsm.request('walking')
if base.localAvatar.isIt:
base.mouseInterfaceNode.setForwardSpeed(ToontownGlobals.ToonForwardSpeed * self.IT_SPEED_INCREASE)
base.mouseInterfaceNode.setRotateSpeed(ToontownGlobals.ToonRotateSpeed * self.IT_ROT_INCREASE)
self.timer = ToontownTimer.ToontownTimer()
self.timer.posInTopRightCorner()
self.timer.setTime(self.DURATION)
self.timer.countdown(self.DURATION, self.timerExpired)
base.playMusic(self.music, looping=1, volume=0.9)
base.localAvatar.setIdealCameraPos(Point3(0, -24, 8))
def exitPlay(self):
for task in self.tracks:
task.finish()
self.tracks = []
for avId in self.avIdList:
toon = self.getAvatar(avId)
if toon:
toon.getGeomNode().clearMat()
toon.scale = 1.0
toon.rescaleToon()
self.walkStateData.exit()
self.music.stop()
self.timer.destroy()
del self.timer
for panel in self.scorePanels:
panel.cleanup()
self.scorePanels = []
base.setCellsAvailable(base.rightCells, 1)
base.mouseInterfaceNode.setForwardSpeed(ToontownGlobals.ToonForwardSpeed)
base.mouseInterfaceNode.setRotateSpeed(ToontownGlobals.ToonRotateSpeed)
self.itPointer.reparentTo(hidden)
base.localAvatar.cameraIndex = 0
base.localAvatar.setCameraPositionByIndex(0)
def timerExpired(self):
self.notify.debug('local timer expired')
self.gameOver()
def enterCleanup(self):
self.notify.debug('enterCleanup')
self.gameFSM.request('off')
def exitCleanup(self):
pass
def setIt(self, avId):
if not self.hasLocalToon:
return
if self.gameFSM.getCurrentState().getName() != 'play':
self.notify.debug('Ignoring setIt after done playing')
return
self.itText.show()
self.notify.debug(str(avId) + ' is now it')
if avId == self.localAvId:
self.itText.setText(TTLocalizer.TagGameYouAreIt)
base.localAvatar.isIt = 1
base.localAvatar.controlManager.setSpeeds(OTPGlobals.ToonForwardSpeed * self.IT_SPEED_INCREASE, OTPGlobals.ToonJumpForce, OTPGlobals.ToonReverseSpeed * self.IT_SPEED_INCREASE, OTPGlobals.ToonRotateSpeed * self.IT_ROT_INCREASE)
else:
self.itText.setText(TTLocalizer.TagGameSomeoneElseIsIt % self.getAvatarName(avId))
base.localAvatar.isIt = 0
base.localAvatar.setWalkSpeedNormal()
avatar = self.getAvatar(avId)
if avatar:
self.itPointer.reparentTo(avatar)
self.itPointer.setZ(avatar.getHeight())
base.playSfx(self.tagSfx)
toon = self.getAvatar(avId)
duration = 0.6
if not toon:
return
spinTrack = LerpHprInterval(toon.getGeomNode(), duration, Point3(0, 0, 0), startHpr=Point3(-5.0 * 360.0, 0, 0), blendType='easeOut')
growTrack = Parallel()
gs = 2.5
for hi in xrange(toon.headParts.getNumPaths()):
head = toon.headParts[hi]
growTrack.append(LerpScaleInterval(head, duration, Point3(gs, gs, gs)))
def bounceFunc(t, trajectory, node = toon.getGeomNode()):
node.setZ(trajectory.calcZ(t))
def bounceCleanupFunc(node = toon.getGeomNode(), z = toon.getGeomNode().getZ()):
node.setZ(z)
bounceTrack = Sequence()
startZ = toon.getGeomNode().getZ()
tLen = 0
zVel = 30
decay = 0.6
while tLen < duration:
trajectory = Trajectory.Trajectory(0, Point3(0, 0, startZ), Point3(0, 0, zVel), gravMult=5.0)
dur = trajectory.calcTimeOfImpactOnPlane(startZ)
if dur <= 0:
break
bounceTrack.append(LerpFunctionInterval(bounceFunc, fromData=0.0, toData=dur, duration=dur, extraArgs=[trajectory]))
tLen += dur
zVel *= decay
bounceTrack.append(Func(bounceCleanupFunc))
tagTrack = Sequence(Func(toon.animFSM.request, 'off'), Parallel(spinTrack, growTrack, bounceTrack), Func(toon.animFSM.request, 'Happy'))
self.tracks.append(tagTrack)
tagTrack.start()
if self.IT:
it = self.getAvatar(self.IT)
shrinkTrack = Parallel()
for hi in xrange(it.headParts.getNumPaths()):
head = it.headParts[hi]
scale = ToontownGlobals.toonHeadScales[it.style.getAnimal()]
shrinkTrack.append(LerpScaleInterval(head, duration, scale))
self.tracks.append(shrinkTrack)
shrinkTrack.start()
self.IT = avId
def acceptTagEvent(self, avId):
self.accept('enterdistAvatarCollNode-' + str(avId), self.sendTagIfIt, [avId])
def sendTagIfIt(self, avId, collisionEntry):
if base.localAvatar.isIt:
self.notify.debug('Tagging ' + str(avId))
self.sendUpdate('tag', [avId])
else:
self.notify.debug('Bumped ' + str(avId))
def setTreasureScore(self, scores):
if not self.hasLocalToon:
return
self.notify.debug('setTreasureScore: %s' % scores)
for i in xrange(len(self.scorePanels)):
self.scorePanels[i].setScore(scores[i])
| ToonTownInfiniteRepo/ToontownInfinite | toontown/minigame/DistributedTagGame.py | Python | mit | 10,955 |
"""Pipeline configuration parameters."""
from os.path import dirname, abspath, join
from sqlalchemy import create_engine
OS_TYPES_URL = ('https://raw.githubusercontent.com/'
'openspending/os-types/master/src/os-types.json')
PIPELINE_FILE = 'pipeline-spec.yaml'
SOURCE_DATAPACKAGE_FILE = 'source.datapackage.json'
SOURCE_FILE = 'source.description.yaml'
STATUS_FILE = 'pipeline-status.json'
SCRAPER_FILE = 'scraper.py'
SOURCE_ZIP = 'source.datapackage.zip'
FISCAL_ZIP_FILE = 'fiscal.datapackage.zip'
SOURCE_DB = 'source.db.xlsx'
DATAPACKAGE_FILE = 'datapackage.json'
ROOT_DIR = abspath(join(dirname(__file__), '..'))
DATA_DIR = join(ROOT_DIR, 'data')
SPECIFICATIONS_DIR = join(ROOT_DIR, 'specifications')
PROCESSORS_DIR = join(ROOT_DIR, 'common', 'processors')
CODELISTS_DIR = join(ROOT_DIR, 'codelists')
DROPBOX_DIR = join(ROOT_DIR, 'dropbox')
GEOCODES_FILE = join(ROOT_DIR, 'geography', 'geocodes.nuts.csv')
FISCAL_SCHEMA_FILE = join(SPECIFICATIONS_DIR, 'fiscal.schema.yaml')
FISCAL_MODEL_FILE = join(SPECIFICATIONS_DIR, 'fiscal.model.yaml')
FISCAL_METADATA_FILE = join(SPECIFICATIONS_DIR, 'fiscal.metadata.yaml')
DEFAULT_PIPELINE_FILE = join(SPECIFICATIONS_DIR, 'default-pipeline-spec.yaml')
TEMPLATE_SCRAPER_FILE = join(PROCESSORS_DIR, 'scraper_template.py')
DESCRIPTION_SCHEMA_FILE = join(SPECIFICATIONS_DIR, 'source.schema.json')
TEMPLATE_SOURCE_FILE = join(SPECIFICATIONS_DIR, SOURCE_FILE)
LOCAL_PATH_EXTRACTOR = 'ingest_local_file'
REMOTE_CSV_EXTRACTOR = 'simple_remote_source'
REMOTE_EXCEL_EXTRACTOR = 'stream_remote_excel'
DATAPACKAGE_MUTATOR = 'mutate_datapackage'
DB_URI = 'sqlite:///{}/metrics.sqlite'
DB_ENGINE = create_engine(DB_URI.format(ROOT_DIR))
VERBOSE = False
LOG_SAMPLE_SIZE = 15
JSON_FORMAT = dict(indent=4, ensure_ascii=False, default=repr)
SNIFFER_SAMPLE_SIZE = 5000
SNIFFER_MAX_FAILURE_RATIO = 0.01
IGNORED_FIELD_TAG = '_ignored'
UNKNOWN_FIELD_TAG = '_unknown'
WARNING_CUTOFF = 10
NUMBER_FORMATS = [
{'format': 'default', 'bareNumber': False, 'decimalChar': '.', 'groupChar': ','},
{'format': 'default', 'bareNumber': False, 'decimalChar': ',', 'groupChar': '.'},
{'format': 'default', 'bareNumber': False, 'decimalChar': '.', 'groupChar': ' '},
{'format': 'default', 'bareNumber': False, 'decimalChar': ',', 'groupChar': ' '},
{'format': 'default', 'bareNumber': False, 'decimalChar': '.', 'groupChar': ''},
{'format': 'default', 'bareNumber': False, 'decimalChar': '.', 'groupChar': '`'},
{'format': 'default', 'bareNumber': False, 'decimalChar': ',', 'groupChar': '\''},
{'format': 'default', 'bareNumber': False, 'decimalChar': ',', 'groupChar': ' '},
]
DATE_FORMATS = [
{'format': '%Y'},
{'format': '%d/%m/%Y'},
{'format': '%d//%m/%Y'},
{'format': '%d-%b-%Y'}, # abbreviated month
{'format': '%d-%b-%y'}, # abbreviated month
{'format': '%d. %b %y'}, # abbreviated month
{'format': '%b %y'}, # abbreviated month
{'format': '%d/%m/%y'},
{'format': '%d-%m-%Y'},
{'format': '%Y-%m-%d'},
{'format': '%y-%m-%d'},
{'format': '%y.%m.%d'},
{'format': '%Y.%m.%d'},
{'format': '%d.%m.%Y'},
{'format': '%d.%m.%y'},
{'format': '%d.%m.%Y %H:%M'},
{'format': '%Y-%m-%d %H:%M:%S'},
{'format': '%Y-%m-%d %H:%M:%S.%f'},
{'format': '%Y-%m-%dT%H:%M:%SZ'},
{'format': '%m/%d/%Y'},
{'format': '%m/%Y'},
{'format': '%y'},
]
| Victordeleon/os-data-importers | eu-structural-funds/common/config.py | Python | mit | 3,382 |
/* @flow */
import * as React from 'react';
import cn from 'classnames';
import { StyleClasses } from '../theme/styleClasses';
type Props = {
// An optional inline-style to apply to the overlay.
style: ?Object,
// An optional css className to apply.
className: ?string,
// Boolean if this divider should be inset relative to it's container
inset: ?boolean,
// Boolean if the divider should be vertical instead of horizontal.
vertical: ?boolean,
};
const BASE_ELEMENT = StyleClasses.DIVIDER;
/**
* The divider component will pass all other props such as style or
* event listeners on to the component.
*/
class Divider extends React.PureComponent<Props, *> {
props: Props;
render() {
const { className, inset, vertical, ...props } = this.props;
const Component = vertical ? 'div' : 'hr';
return (
<Component
{...props}
className={cn(
BASE_ELEMENT,
{
'boldrui-divider__vertical': vertical,
'boldrui-divider__inset': inset,
},
className,
)}
/>
);
}
}
export default Divider;
| boldr/boldr-ui | src/Divider/Divider.js | JavaScript | mit | 1,118 |
<?php
/*
* This file is part of the FOSGoogleBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\GoogleBundle\Templating\Helper;
use Symfony\Component\Templating\Helper\Helper;
use Symfony\Component\Templating\EngineInterface;
class GoogleHelper extends Helper
{
protected $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
public function loginButton($parameters = array(), $name = null)
{
$name = $name ?: 'FOSGoogleBundle::loginButton.html.php';
return $this->templating->render($name, $parameters);
}
/**
* @codeCoverageIgnore
*/
public function getName()
{
return 'google';
}
}
| CaoPhiHung/CRM | vendor/bundles/FOS/GoogleBundle/Templating/Helper/GoogleHelper.php | PHP | mit | 950 |
import * as $ from 'jquery';
import { clearStyles } from '../util';
import { Article } from '..';
export const cleanup = () => {
$('#scrollDiv').remove();
}
export function parse(): Article {
let articleBody = clearStyles($('.article-text')[0].cloneNode(true));
let $subtitle = $('.subtitle', articleBody);
const subtitle = $subtitle.html();
$subtitle.remove();
$('.relation2-area', articleBody).remove();
const content = articleBody.innerHTML;
return {
title: $('#article_view_headline .title').text().trim(),
content: content,
subtitle: subtitle,
timestamp: (() => {
let $span = $('#article_view_headline .date-time span');
if ($span[0].childNodes[1].textContent!.replace(/-/g, '/'))
return {
created: new Date($span[0].childNodes[1].textContent!.replace(/-/g, '/')),
lastModified: $span[1] ? new Date($span[1].childNodes[1].textContent!.replace(/-/g, '/')) : undefined
};
else return undefined;
})(),
reporters: []
};
}
| disjukr/jews | src/impl/한겨레.ts | TypeScript | mit | 1,117 |
/*
* Author: 陈志杭 Caspar
* Contact: 279397942@qq.com qq:279397942
* Description: 数据接口契约文件
* 文件由模板生成,请不要直接修改文件,如需修改请创建一个对应的partial文件
*/
using System;
using System.Collections;
using Zh.DAL.Base.Define;
using Zh.DAL.Define.Entities;
using Zh.DAL.Define;
namespace Zh.DAL.Define.Contracts
{
/// <summary>
/// Member_Account(会员账号信息)表访问接口
/// </summary>
public partial interface IMemberAccountDao : IBaseDao<Member_Account>
{
}
} | Caspar12/Csharp | src/Zh.DAL.Define/Contracts/AutoCode/IMemberAccountDao.cs | C# | mit | 569 |
package com.aspose.spreadsheeteditor;
import java.util.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
/**
*
* @author Saqib Masood
*/
@Named(value = "msg")
@ApplicationScoped
public class MessageService {
private static final Logger LOGGER = Logger.getLogger(MessageService.class.getName());
public void sendMessage(String summary, String details) {
LOGGER.info(String.format("%s: %s", summary, details));
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(summary, details));
}
public void sendMessageDialog(String summary, String details) {
LOGGER.info(String.format("%s: %s", summary, details));
RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(summary, details));
}
}
| fahadadeel/Aspose.Cells-for-Java | Showcases/Html5_Spreadsheet_Editor_by_Aspose.Cells_for_Java/src/main/java/com/aspose/spreadsheeteditor/MessageService.java | Java | mit | 952 |
import {Task} from './task.model'
import {Injectable} from 'angular2/core'
import {Http, Response, Headers, RequestOptions} from 'angular2/http';
import {Observable} from "rxjs/Observable";
@Injectable()
export class TaskService {
constructor(
private http: Http
) { }
private _tasksUrl = 'api/tasks';
private defaultRequestOptions: RequestOptions = new RequestOptions({
headers: new Headers({ 'Content-Type': 'application/json' }),
});
getTasks(): Observable<Task[]> {
return this.http.get(this._tasksUrl)
.map(this.extractTasks)
.catch(this.handleError);
}
addTask(title: string): Observable<Task> {
let body = JSON.stringify({ title });
return this.http.post(this._tasksUrl, body, this.defaultRequestOptions)
.map(this.extractTask)
.catch(this.handleError);
}
updateTask(task: Task): Observable<Task> {
let body = JSON.stringify({ task });
return this.http.patch(`api/tasks/${task.id}`, body, this.defaultRequestOptions)
.map(this.extractTask)
.catch(this.handleError)
}
deleteTask(task: Task): Observable<Response> {
return this.http.delete(`api/tasks/${task.id}`, this.defaultRequestOptions)
.map(res => res)
.catch(this.handleError)
}
private extractTasks(res: Response) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
let body = res.json();
return body.tasks || {};
}
private extractTask(res: Response) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
let body = res.json();
return body || {};
}
private handleError(error: any) {
let errMsg = error.message || 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
}
| c-bata/kobin-example | front/ts/task.service.ts | TypeScript | mit | 2,019 |
class BusStopController < ApplicationController
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
def api
obj = params["data"]
p params["data"]
address = obj.split("','")[0]
bus_num = obj.split("','")[1]
bus_num = bus_num[0..-2]
response = Geokit::Geocoders::MultiGeocoder.do_geocode(address)
respond_to do |format|
format.html { }
format.json { render :json => BusStop.find_closest_by_coord_and_bus(response.longitude,response.latitude,bus_num) }
format.xml { }
end
end
end
| danasweet/somebody-stop-me | app/controllers/bus_stop_controller.rb | Ruby | mit | 585 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.item.properties;
import org.spongepowered.api.util.Coerce;
/**
* Represents an item property that has an integer value. Examples may include
* {@link FoodRestorationProperty}, {@link SaturationProperty} etc.
*/
public class DoubleProperty extends AbstractItemProperty<String, Double> {
/**
* Create a new integer property with the specified value.
*
* @param value value to match
*/
public DoubleProperty(double value) {
super(Coerce.toDouble(value));
}
/**
* Create a new integer property with the specified value and logical
* operator.
*
* @param value value to match
* @param operator logical operator to use when comparing to other
* properties
*/
public DoubleProperty(double value, Operator operator) {
super(value, operator);
}
/**
* Create a new integer property with the specified value and logical
* operator.
*
* @param value value to match
* @param operator logical operator to use when comparing to other
* properties
*/
public DoubleProperty(Object value, Operator operator) {
super(Coerce.toDouble(value), operator);
}
@Override
public int compareTo(ItemProperty<?, ?> other) {
return this.getValue().compareTo(other == null ? 1 : Coerce.toDouble(other.getValue()));
}
/**
* Create an DoubleProperty property which matches DoubleProperty properties with
* equal value.
*
* @param value value to match
* @return new property
*/
public static DoubleProperty of(Object value) {
return new DoubleProperty(value, Operator.EQUAL);
}
/**
* Create an DoubleProperty property which matches DoubleProperty properties with
* unequal value.
*
* @param value value to match
* @return new property
*/
public static DoubleProperty not(Object value) {
return new DoubleProperty(value, Operator.NOTEQUAL);
}
/**
* Create an DoubleProperty property which matches DoubleProperty properties with
* value greater than this value.
*
* @param value value to match
* @return new property
*/
public static DoubleProperty greaterThan(Object value) {
return new DoubleProperty(value, Operator.GREATER);
}
/**
* Create an DoubleProperty property which matches DoubleProperty properties with
* value greater than or equal to this value.
*
* @param value value to match
* @return new property
*/
public static DoubleProperty greaterThanOrEqual(Object value) {
return new DoubleProperty(value, Operator.GEQUAL);
}
/**
* Create an DoubleProperty property which matches DoubleProperty properties with
* value less than this value.
*
* @param value value to match
* @return new property
*/
public static DoubleProperty lessThan(Object value) {
return new DoubleProperty(value, Operator.LESS);
}
/**
* Create an DoubleProperty property which matches DoubleProperty properties with
* value less than or equal to this value.
*
* @param value value to match
* @return new property
*/
public static DoubleProperty lessThanOrEqual(Object value) {
return new DoubleProperty(value, Operator.LEQUAL);
}
/**
* Checks if this is a flowerpot.
*
* @return Whether this is a flowerpot
*/
public boolean isFlowerPot() {
return false;
}
}
| SpongeHistory/SpongeAPI-History | src/main/java/org/spongepowered/api/item/properties/DoubleProperty.java | Java | mit | 4,824 |
<?php
/**
* Copyright 2016 Sony Corporation
*/
namespace CdnPurge\Limelight;
use CdnPurge\Common\Enum\BasicEnum;
/**
* Limelight specific constants
*/
abstract class ApiConstants extends BasicEnum
{
/** constants root */
const CONST_ROOT = 'limelight';
/** Configuration related constants */
const CONF_SHORTNAME = 'shortname';
const CONF_PUBLISH_URL = 'publish_url';
const CONF_EVICT = 'evict';
const CONF_EXACT = 'exact';
const CONF_INCQS = 'incqs';
const CONF_EMAIL = 'email';
const CONF_EMAIL_SUBJECT = 'subject';
const CONF_EMAIL_TO = 'to';
const CONF_EMAIL_CC = 'cc';
const CONF_EMAIL_BCC = 'bcc';
const CONF_CALLBACK = 'callback';
const CONF_CALLBACK_URL = 'url';
const CONF_HTTP = 'http';
const CONF_PROXY = 'proxy';
/** Credential related constants */
const CREDENTIAL_USERNAME = 'username';
const CREDENTIAL_SHARED_KEY = 'shared_key';
/** Client related constants */
const LL_HOST = 'https://purge.llnw.com';
const LL_ENDPOINT = '/purge';
const LL_VERSION = '/v1';
const LL_PATH_PURGE_REQUEST = '/requests';
}
| sony/cdn-purge-control-php | src/Limelight/ApiConstants.php | PHP | mit | 1,130 |
package desktopvirtualization
// 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.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// OperationsClient is the client for the Operations methods of the Desktopvirtualization service.
type OperationsClient struct {
BaseClient
}
// NewOperationsClient creates an instance of the OperationsClient client.
func NewOperationsClient(subscriptionID string) OperationsClient {
return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this
// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// List list all of the available operations the Desktop Virtualization resource provider supports.
func (client OperationsClient) List(ctx context.Context) (result ResourceProviderOperationList, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.OperationsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "desktopvirtualization.OperationsClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.OperationsClient", "List", resp, "Failure responding to request")
return
}
return
}
// ListPreparer prepares the List request.
func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) {
const APIVersion = "2020-11-02-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/providers/Microsoft.DesktopVirtualization/operations"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client OperationsClient) ListResponder(resp *http.Response) (result ResourceProviderOperationList, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| Azure/azure-sdk-for-go | services/preview/desktopvirtualization/mgmt/2020-11-02-preview/desktopvirtualization/operations.go | GO | mit | 3,672 |
// File auto generated by STUHashTool
using static STULib.Types.Generic.Common;
namespace STULib.Types.Dump {
[STU(0x35AA91CE)]
public class STU_35AA91CE : STUInstance {
[STUField(0x4227DBDA, EmbeddedInstance = true)]
public STULib.Types.Dump.STU_7C27312D[] m_4227DBDA;
[STUField(0xD7A96218)]
public uint[] m_D7A96218;
[STUField(0x5E1BC440, EmbeddedInstance = true)]
public STULib.Types.Dump.STU_024ED1FF m_5E1BC440;
}
}
| kerzyte/OWLib | STULib/Types/Dump/STU_35AA91CE.cs | C# | mit | 484 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// This file enables 'go generate' to regenerate this specific SDK
//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/kubernetesconfiguration/armkubernetesconfiguration
package armkubernetesconfiguration
| Azure/azure-sdk-for-go | sdk/resourcemanager/kubernetesconfiguration/armkubernetesconfiguration/build.go | GO | mit | 436 |
var windowHeight = $(window).height();
var menuBarHeight = $('#codeplayer-menubar').height();
$('.codeplayer-code-container').css('height', (windowHeight - menuBarHeight) + 'px');
$('.codeplayer-toogle').click(function() {
$(this).toggleClass('codeplayer-selected');
var codeContainerDiv = '#codeplayer-' + $(this).html() + '-container';
$(codeContainerDiv).toggle();
var showingDivs = $('.codeplayer-code-container').filter(function() {
return $((this)).css('display') != 'none';
}).length;
var divWidthPercentage = 100 / showingDivs;
$('.codeplayer-code-container').css('width', divWidthPercentage + '%');
});
$('#codeplayer-runbuttondiv').click(function() {
var iframeContent = '<style>' +
$('#codeplayer-cssCode').val() +
'</style>' +
$('#codeplayer-htmlCode').val();
$('#codeplayer-iframe').contents().find('html').html(iframeContent);
document.getElementById('codeplayer-iframe').contentWindow. eval($('#codeplayer-jsCode').val())
}); | phillipemoreira/web-development | robpercival/4.jQuery/js/codeplayer.js | JavaScript | mit | 1,020 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using TAlex.MathCore.ExpressionEvaluation.Extensions;
using TAlex.MathCore.ExpressionEvaluation.Helpers;
namespace TAlex.MathCore.ExpressionEvaluation.Trees.Metadata
{
public class DefaultFunctionMetadataProvider : IFunctionMetadataProvider
{
#region IFunctionMetadataProvider Members
public FunctionMetadata GetMetadata(Type functionType)
{
FunctionMetadata functionMetadata = new FunctionMetadata(functionType);
functionMetadata.Id = MD5.GetHashString(functionType.FullName);
var displayNameAttr = functionType.GetCustomAttribute<DisplayNameAttribute>();
functionMetadata.DisplayName = displayNameAttr != null ? displayNameAttr.DisplayName : null;
var categoryAttr = functionType.GetCustomAttribute<CategoryAttribute>();
functionMetadata.Category = categoryAttr != null ? categoryAttr.Category : null;
var sectionAttr = functionType.GetCustomAttribute<SectionAttribute>();
functionMetadata.Section = sectionAttr != null ? sectionAttr.Name : null;
var descriptionAttr = functionType.GetCustomAttribute<DescriptionAttribute>();
functionMetadata.Description = descriptionAttr != null ? descriptionAttr.Description : null;
foreach (var signature in functionType.GetCustomAttributes<FunctionSignatureAttribute>())
{
functionMetadata.Signatures.Add(GetFunctionSignatureMetadata(signature));
}
foreach (var exampleUsage in functionType.GetCustomAttributes<ExampleUsageAttribute>())
{
functionMetadata.ExampleUsages.Add(new ExampleUsage(exampleUsage.Expression, exampleUsage.Result)
{
CanMultipleResults = exampleUsage.CanMultipleResults
});
}
return functionMetadata;
}
private FunctionSignature GetFunctionSignatureMetadata(FunctionSignatureAttribute signature)
{
IList<FunctionSignature.Argument> args = signature.Arguments.Select(x =>
{
var parts = x.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
string type = String.Join(" ", parts.Take(parts.Length - 1));
string name = parts.Last();
return new FunctionSignature.Argument(type, GetKnownArgType(type), name);
}).ToList();
return new FunctionSignature(signature.Name, args) { Description = signature.Description };
}
private FunctionSignature.KnownType GetKnownArgType(string type)
{
switch (type.ToUpper())
{
case "VARIABLE":
return FunctionSignature.KnownType.Variable;
case "EXPRESSION":
return FunctionSignature.KnownType.Expression;
default:
return FunctionSignature.KnownType.Unknown;
}
}
#endregion
}
}
| T-Alex/MathCore | src/TAlex.MathCore.ExpressionsBase/Trees/Metadata/DefaultFunctionMetadataProvider.cs | C# | mit | 3,158 |
/// <reference types="react" />
import * as React from "react";
import { ITab2Props, TabId } from "./tab2";
export interface ITabTitleProps extends ITab2Props {
/** Handler invoked when this tab is clicked. */
onClick: (id: TabId, event: React.MouseEvent<HTMLElement>) => void;
/** ID of the parent `Tabs` to which this tab belongs. Used to generate ID for ARIA attributes. */
parentId: TabId;
/** Whether the tab is currently selected. */
selected: boolean;
}
export declare class TabTitle extends React.Component<ITabTitleProps, {}> {
static displayName: string;
render(): JSX.Element;
private handleClick;
}
export declare function generateTabPanelId(parentId: TabId, tabId: TabId): string;
export declare function generateTabTitleId(parentId: TabId, tabId: TabId): string;
| aggiedefenders/aggiedefenders.github.io | node_modules/@blueprintjs/core/dist/components/tabs2/tabTitle.d.ts | TypeScript | mit | 813 |
var randomBytes = require('mz/crypto').randomBytes;
module.exports = function* trace(next) {
this.id = yield randomBytes(24);
var ctx = this;
var req = this.req;
var res = this.res;
// request start
this.trace('time.start');
// request end
req.once('end', this.trace.bind(this, 'time.end'));
// response headers
var writeHead = res.writeHead;
res.writeHead = function () {
ctx.trace('time.headers');
return writeHead.apply(this, arguments);
}
// response finish
res.once('finish', this.trace.bind(this, 'time.finish'));
yield* next;
} | phamann/wedding-holding-page | server/lib/middleware/trace.js | JavaScript | mit | 615 |
(function() {
'use strict';
angular.module('cd.app.registerForm')
.controller('RegisterFormController', RegisterFormController);
/* @ngInject */
function RegisterFormController ($location, StepsService) {
var $ctrl = this;
$ctrl.selectedPlatform = JSON.parse(localStorage.getItem('selectedPlatform'));
$ctrl.selectedPackage = JSON.parse(localStorage.getItem('selectedPackage'));
if (StepsService.currentStep < StepsService.REGISTER) {
$location.path('/package');
} else {
_init();
}
function _init () {
$ctrl.registerForm = {
nome: '',
email: '',
nascimento: '',
cpf: '',
telefone: ''
};
$ctrl.submit = submit;
function submit () {
console.groupCollapsed('Formulário Enviado');
console.log('Formulário de registro', $ctrl.registerForm);
console.log('Plano Selecionado', $ctrl.selectedPackage);
console.log('Plataforma Selecionada', $ctrl.selectedPlatform);
console.groupEnd();
};
};
};
})(); | RaphaelGuimaraes/celular-direto | src/pages/register-form/register-form.controller.js | JavaScript | mit | 1,265 |
class String
# Changes an underscored string into a class reference.
def _as_class
# classify expects self to be plural
self.classify.constantize
end
# For compatibility with the Symbol extensions.
alias :_singularize :singularize
alias :_pluralize :pluralize
alias :_classify :classify
end
class Symbol
# Changes an underscored symbol into a class reference.
def _as_class; self.to_s._as_class; end
# Changes a plural symbol into a singular symbol.
def _singularize; self.to_s.singularize.to_sym; end
# Changes a singular symbol into a plural symbol.
def _pluralize; self.to_s.pluralize.to_sym; end
# Changes a symbol into a class name string.
def _classify; self.to_s.classify; end
end
class Array
# Flattens the first level of self.
def _flatten_once
self.inject([]){|r, el| r + Array(el)}
end
# Rails 1.2.3 compatibility method. Copied from http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/core_ext/array/extract_options.rb?rev=7217
def _extract_options!
last.is_a?(::Hash) ? pop : {}
end
end
class Hash
# An implementation of select that returns a Hash.
def _select
if RUBY_VERSION >= "1.9"
Hash[*self.select {|k, v| yield k, v }.flatten]
else
Hash[*self.select do |key, value|
yield key, value
end._flatten_once]
end
end
end
class Object
# Returns the metaclass of self.
def _metaclass; (class << self; self; end); end
# Logger shortcut.
def _logger_debug s
s = "** has_many_polymorphs: #{s}"
RAILS_DEFAULT_LOGGER.debug(s) if RAILS_DEFAULT_LOGGER
end
# Logger shortcut.
def _logger_warn s
s = "** has_many_polymorphs: #{s}"
if RAILS_DEFAULT_LOGGER
RAILS_DEFAULT_LOGGER.warn(s)
else
$stderr.puts(s)
end
end
end
class ActiveRecord::Base
# Return the base class name as a string.
def _base_class_name
self.class.base_class.name.to_s
end
end
| charlotte-ruby/calagator_techclt | vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/support_methods.rb | Ruby | mit | 1,954 |
from pokemongo_bot.human_behaviour import sleep
from pokemongo_bot.base_task import BaseTask
class IncubateEggs(BaseTask):
SUPPORTED_TASK_API_VERSION = 1
last_km_walked = 0
def initialize(self):
self.ready_incubators = []
self.used_incubators = []
self.eggs = []
self.km_walked = 0
self.hatching_animation_delay = 4.20
self.max_iv = 45.0
self._process_config()
def _process_config(self):
self.longer_eggs_first = self.config.get("longer_eggs_first", True)
def work(self):
try:
self._check_inventory()
except:
return
if self.used_incubators and IncubateEggs.last_km_walked != self.km_walked:
self.used_incubators.sort(key=lambda x: x.get("km"))
km_left = self.used_incubators[0]['km']-self.km_walked
if km_left <= 0:
self._hatch_eggs()
else:
self.emit_event(
'next_egg_incubates',
formatted='Next egg ({km_needed} km) incubates in {distance_in_km:.2f} km',
data={
'km_needed': self.used_incubators[0]['km_needed'],
'distance_in_km': km_left
}
)
IncubateEggs.last_km_walked = self.km_walked
sorting = self.longer_eggs_first
self.eggs.sort(key=lambda x: x.get("km"), reverse=sorting)
if self.ready_incubators:
self._apply_incubators()
def _apply_incubators(self):
for incubator in self.ready_incubators:
if incubator.get('used', False):
continue
for egg in self.eggs:
if egg["used"] or egg["km"] == -1:
continue
self.emit_event(
'incubate_try',
level='debug',
formatted="Attempting to apply incubator {incubator_id} to egg {egg_id}",
data={
'incubator_id': incubator['id'],
'egg_id': egg['id']
}
)
ret = self.bot.api.use_item_egg_incubator(
item_id=incubator["id"],
pokemon_id=egg["id"]
)
if ret:
code = ret.get("responses", {}).get("USE_ITEM_EGG_INCUBATOR", {}).get("result", 0)
if code == 1:
self.emit_event(
'incubate',
formatted='Incubating a {distance_in_km} egg.',
data={
'distance_in_km': str(egg['km'])
}
)
egg["used"] = True
incubator["used"] = True
break
elif code == 5 or code == 7:
self.emit_event(
'incubator_already_used',
level='debug',
formatted='Incubator in use.',
)
incubator["used"] = True
break
elif code == 6:
self.emit_event(
'egg_already_incubating',
level='debug',
formatted='Egg already incubating',
)
egg["used"] = True
def _check_inventory(self, lookup_ids=[]):
inv = {}
response_dict = self.bot.get_inventory()
matched_pokemon = []
temp_eggs = []
temp_used_incubators = []
temp_ready_incubators = []
inv = reduce(
dict.__getitem__,
["responses", "GET_INVENTORY", "inventory_delta", "inventory_items"],
response_dict
)
for inv_data in inv:
inv_data = inv_data.get("inventory_item_data", {})
if "egg_incubators" in inv_data:
temp_used_incubators = []
temp_ready_incubators = []
incubators = inv_data.get("egg_incubators", {}).get("egg_incubator",[])
if isinstance(incubators, basestring): # checking for old response
incubators = [incubators]
for incubator in incubators:
if 'pokemon_id' in incubator:
start_km = incubator.get('start_km_walked', 9001)
km_walked = incubator.get('target_km_walked', 9001)
temp_used_incubators.append({
"id": incubator.get('id', -1),
"km": km_walked,
"km_needed": (km_walked - start_km)
})
else:
temp_ready_incubators.append({
"id": incubator.get('id', -1)
})
continue
if "pokemon_data" in inv_data:
pokemon = inv_data.get("pokemon_data", {})
if pokemon.get("is_egg", False) and "egg_incubator_id" not in pokemon:
temp_eggs.append({
"id": pokemon.get("id", -1),
"km": pokemon.get("egg_km_walked_target", -1),
"used": False
})
elif 'is_egg' not in pokemon and pokemon['id'] in lookup_ids:
pokemon.update({
"iv": [
pokemon.get('individual_attack', 0),
pokemon.get('individual_defense', 0),
pokemon.get('individual_stamina', 0)
]})
matched_pokemon.append(pokemon)
continue
if "player_stats" in inv_data:
self.km_walked = inv_data.get("player_stats", {}).get("km_walked", 0)
if temp_used_incubators:
self.used_incubators = temp_used_incubators
if temp_ready_incubators:
self.ready_incubators = temp_ready_incubators
if temp_eggs:
self.eggs = temp_eggs
return matched_pokemon
def _hatch_eggs(self):
response_dict = self.bot.api.get_hatched_eggs()
log_color = 'green'
try:
result = reduce(dict.__getitem__, ["responses", "GET_HATCHED_EGGS"], response_dict)
except KeyError:
return
pokemon_ids = []
if 'pokemon_id' in result:
pokemon_ids = [id for id in result['pokemon_id']]
stardust = result.get('stardust_awarded', "error")
candy = result.get('candy_awarded', "error")
xp = result.get('experience_awarded', "error")
sleep(self.hatching_animation_delay)
self.bot.latest_inventory = None
try:
pokemon_data = self._check_inventory(pokemon_ids)
for pokemon in pokemon_data:
# pokemon ids seem to be offset by one
if pokemon['pokemon_id']!=-1:
pokemon['name'] = self.bot.pokemon_list[(pokemon.get('pokemon_id')-1)]['Name']
else:
pokemon['name'] = "error"
except:
pokemon_data = [{"name":"error","cp":"error","iv":"error"}]
if not pokemon_ids or pokemon_data[0]['name'] == "error":
self.emit_event(
'egg_hatched',
data={
'pokemon': 'error',
'cp': 'error',
'iv': 'error',
'exp': 'error',
'stardust': 'error',
'candy': 'error',
}
)
return
for i in range(len(pokemon_data)):
msg = "Egg hatched with a {pokemon} (CP {cp} - IV {iv}), {exp} exp, {stardust} stardust and {candy} candies."
self.emit_event(
'egg_hatched',
formatted=msg,
data={
'pokemon': pokemon_data[i]['name'],
'cp': pokemon_data[i]['cp'],
'iv': "{} {}".format(
"/".join(map(str, pokemon_data[i]['iv'])),
sum(pokemon_data[i]['iv'])/self.max_iv
),
'exp': xp[i],
'stardust': stardust[i],
'candy': candy[i],
}
)
| Compjeff/PokemonGo-Bot | pokemongo_bot/cell_workers/incubate_eggs.py | Python | mit | 8,649 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Verify data doesn't have basic mistakes, like empty text fields or empty label
candidates.
## Examples
```shell
parlai verify_data --task convai2 --datatype valid
```
"""
from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent
from parlai.core.message import Message
from parlai.core.params import ParlaiParser
from parlai.utils.misc import TimeLogger, warn_once
from parlai.core.worlds import create_task
from parlai.core.script import ParlaiScript, register_script
import parlai.utils.logging as logging
def setup_args(parser=None):
if parser is None:
parser = ParlaiParser(True, True, 'Check tasks for common errors')
# Get command line arguments
parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2)
parser.add_argument('-d', '--display-examples', type='bool', default=False)
parser.set_defaults(datatype='train:stream:ordered')
return parser
def report(world, counts, log_time):
report = world.report()
log = {
'missing_text': counts['missing_text'],
'missing_labels': counts['missing_labels'],
'missing_label_candidates': counts['missing_label_candidates'],
'empty_string_label_candidates': counts['empty_string_label_candidates'],
'label_candidates_with_missing_label': counts[
'label_candidates_with_missing_label'
],
'did_not_return_message': counts['did_not_return_message'],
}
text, log = log_time.log(report['exs'], world.num_examples(), log)
return text, log
def warn(txt, act, opt):
if opt.get('display_examples'):
print(txt + ":\n" + str(act))
else:
warn_once(txt)
def verify(opt):
if opt['datatype'] == 'train':
logging.warning("changing datatype from train to train:ordered")
opt['datatype'] = 'train:ordered'
opt.log()
# create repeat label agent and assign it to the specified task
agent = RepeatLabelAgent(opt)
world = create_task(opt, agent)
log_every_n_secs = opt.get('log_every_n_secs', -1)
if log_every_n_secs <= 0:
log_every_n_secs = float('inf')
log_time = TimeLogger()
counts = {}
counts['missing_text'] = 0
counts['missing_labels'] = 0
counts['missing_label_candidates'] = 0
counts['empty_string_label_candidates'] = 0
counts['label_candidates_with_missing_label'] = 0
counts['did_not_return_message'] = 0
# Show some example dialogs.
while not world.epoch_done():
world.parley()
act = world.acts[0]
if not isinstance(act, Message):
counts['did_not_return_message'] += 1
if 'text' not in act and 'image' not in act:
warn("warning: missing text field:\n", act, opt)
counts['missing_text'] += 1
if 'labels' not in act and 'eval_labels' not in act:
warn("warning: missing labels/eval_labels field:\n", act, opt)
counts['missing_labels'] += 1
else:
if 'label_candidates' not in act:
counts['missing_label_candidates'] += 1
else:
labels = act.get('labels', act.get('eval_labels'))
is_label_cand = {}
for l in labels:
is_label_cand[l] = False
for c in act['label_candidates']:
if c == '':
warn("warning: empty string label_candidate:\n", act, opt)
counts['empty_string_label_candidates'] += 1
if c in is_label_cand:
if is_label_cand[c] is True:
warn(
"warning: label mentioned twice in candidate_labels:\n",
act,
opt,
)
is_label_cand[c] = True
for _, has in is_label_cand.items():
if has is False:
warn("warning: label missing in candidate_labels:\n", act, opt)
counts['label_candidates_with_missing_label'] += 1
if log_time.time() > log_every_n_secs:
text, log = report(world, counts, log_time)
print(text)
try:
# print dataset size if available
logging.info(
f'Loaded {world.num_episodes()} episodes with a '
f'total of {world.num_examples()} examples'
)
except AttributeError:
pass
counts['exs'] = int(world.report()['exs'])
return counts
def verify_data(opt):
counts = verify(opt)
print(counts)
return counts
@register_script('verify_data', hidden=True)
class VerifyData(ParlaiScript):
@classmethod
def setup_args(cls):
return setup_args()
def run(self):
return verify_data(self.opt)
if __name__ == '__main__':
VerifyData.main()
| facebookresearch/ParlAI | parlai/scripts/verify_data.py | Python | mit | 5,106 |
//******************************************************************************************************
// ChannelFrameCollectionBase.cs - Gbtc
//
// Copyright © 2012, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 01/14/2005 - J. Ritchie Carroll
// Generated original version of source code.
// 09/15/2009 - Stephen C. Wills
// Added new header and license agreement.
// 10/5/2012 - Gavin E. Holden
// Added new header and license agreement.
// 12/17/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
using System;
using System.Linq;
using System.Runtime.Serialization;
namespace GSF.PhasorProtocols
{
/// <summary>
/// Represents a protocol independent collection of <see cref="IChannelFrame"/> objects.
/// </summary>
/// <typeparam name="T">Specific <see cref="IChannelFrame"/> type that the <see cref="ChannelFrameCollectionBase{T}"/> contains.</typeparam>
[Serializable]
public abstract class ChannelFrameCollectionBase<T> : ChannelCollectionBase<T> where T : IChannelFrame
{
#region [ Constructors ]
/// <summary>
/// Creates a new <see cref="ChannelFrameCollectionBase{T}"/> using specified <paramref name="lastValidIndex"/>.
/// </summary>
/// <param name="lastValidIndex">Last valid index for the collection (i.e., maximum count - 1).</param>
/// <remarks>
/// <paramref name="lastValidIndex"/> is used instead of maximum count so that maximum type values may
/// be specified as needed. For example, if the protocol specifies a collection with a signed 16-bit
/// maximum length you can specify <see cref="short.MaxValue"/> (i.e., 32,767) as the last valid index
/// for the collection since total number of items supported would be 32,768.
/// </remarks>
protected ChannelFrameCollectionBase(int lastValidIndex)
: base(lastValidIndex)
{
}
/// <summary>
/// Creates a new <see cref="ChannelFrameCollectionBase{T}"/> from serialization parameters.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> with populated with data.</param>
/// <param name="context">The source <see cref="StreamingContext"/> for this deserialization.</param>
protected ChannelFrameCollectionBase(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
#region [ Properties ]
/// <summary>
/// Gets the length of the <see cref="ChannelCollectionBase{T}"/>.
/// </summary>
/// <remarks>
/// The length of the <see cref="ChannelFrameCollectionBase{T}"/> binary image is the combined length of all the items in the collection.
/// </remarks>
public override int BinaryLength
{
get
{
// It is expected that frames can be different lengths, so we manually sum lengths - this represents
// a change in behavior from the base class...
return this.Sum(frame => frame.BinaryLength);
}
}
#endregion
}
} | rmc00/gsf | Source/Libraries/GSF.PhasorProtocols/ChannelFrameCollectionBase.cs | C# | mit | 4,185 |
package gonfler
import (
"archive/tar"
"os"
)
type TarArchive struct {
handle *tar.Reader
file *os.File
}
func (archive TarArchive) Close() error {
return archive.file.Close()
}
func (archive TarArchive) Volumes() VolumeIterator {
var next func() VolumeIterator
next = func() VolumeIterator {
header, err := archive.handle.Next()
if err != nil {
return VolumeIterator{nil, nil}
} else {
return VolumeIterator{
volume: &Volume{archive.handle, header.Name},
next: next,
}
}
}
return next()
}
func openTar(name string) (Archive, error) {
file, e := os.Open(name)
if file != nil {
return TarArchive{tar.NewReader(file), file}, nil
} else {
return nil, e
}
}
| AlbanSeurat/gonfler | untar.go | GO | mit | 705 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", TestNet()));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new Bitcoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBook(keyID, strAccount, "receive");
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current Bitcoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value getrawchangeaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawchangeaddress\n"
"Returns a new Bitcoin address, for receiving change. "
"This is for use with raw transactions, NOT normal use.");
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
CReserveKey reservekey(pwalletMain);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Unable to obtain key for change");
reservekey.KeepKey();
CKeyID keyID = vchPubKey.GetID();
return CBitcoinAddress(keyID).ToString();
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <pangubiaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <pangubiaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
string strAccount;
map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty())
strAccount = (*mi).second.name;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <pangubiaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <pangubiaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <pangubiaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <pangubiaddress> [minconf=1]\n"
"Returns the total amount received by <pangubiaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!IsFinalTx(wtx))
continue;
int64 nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsConfirmed())
continue;
int64 allFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <topangubiaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Bitcoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
//
// Used by addmultisigaddress / createmultisig:
//
static CScript _createmultisig(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
return result;
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a Bitcoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBook(innerID, strAccount, "send");
return CBitcoinAddress(innerID).ToString();
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n"
"Creates a multi-signature address and returns a json object\n"
"with keys:\n"
"address : bitcoin address\n"
"redeemScript : hex-encoded redemption script";
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
struct tallyitem
{
int64 nAmount;
int nConf;
vector<uint256> txids;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second.name;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
Array transactions;
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& item, (*it).second.txids)
{
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included\n"
" \"txids\" : list of transactions with outputs to the address\n");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString()));
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first].name;
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString()));
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
entry.push_back(Pair("category", "receive"));
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second.name] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first].name] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all wallet transactions in blocks since block [blockhash], or all wallet transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about in-wallet transaction <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? GetValueOut(wtx) - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(wtx, "*", 0, false, details);
entry.push_back(Pair("details", details));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill [new-size]\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
unsigned int kpSize = max(GetArg("-keypool", 100), 0LL);
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(-8, "Invalid parameter, expected valid size");
kpSize = (unsigned int) params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(kpSize);
if (pwalletMain->GetKeyPoolSize() < kpSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
static void LockWallet(CWallet* pWallet)
{
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->Lock();
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
pwalletMain->TopUpKeyPool();
int64 nSleepTime = params[1].get_int64();
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = GetTime() + nSleepTime;
RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; Bitcoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <pangubiaddress>\n"
"Return information about <pangubiaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
}
return ret;
}
Value lockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock? [array-of-Objects]\n"
"Updates list of temporarily unspendable outputs.");
if (params.size() == 1)
RPCTypeCheck(params, list_of(bool_type));
else
RPCTypeCheck(params, list_of(bool_type)(array_type));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
Array outputs = params[1].get_array();
BOOST_FOREACH(Value& output, outputs)
{
if (output.type() != obj_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
const Object& o = output.get_obj();
RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
Value listlockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"Returns list of temporarily unspendable outputs.");
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
Array ret;
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
Object o;
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
| pangubi/pangubi | src/rpcwallet.cpp | C++ | mit | 53,760 |
import { Actor } from './game';
import { Point, Size } from './foundation';
export class Rectangle implements Actor {
public isAlive: boolean;
protected rectCenter: Point;
protected rectSize: Size;
protected horizontalDirection: number;
protected verticalDirection: number;
constructor(center: Point, size: Size) {
this.isAlive = true;
this.rectCenter = center;
this.rectSize = size;
this.horizontalDirection = 0;
this.verticalDirection = 0;
}
get center(): Point {
return this.rectCenter;
}
get size(): Size {
return this.rectSize;
}
public update(stageBounds: Size) {
if (this.isMovingToLeft()) {
if (!this.reachLeftLimit(stageBounds)) {
this.rectCenter.x -= 5;
} else {
this.horizontalDirection = 1;
}
} else {
if (!this.reachRightLimit(stageBounds)) {
this.rectCenter.x += 5;
} else {
this.horizontalDirection = 0;
}
}
if (this.isMovingToTop()) {
if (!this.reachTopLimit(stageBounds)) {
this.rectCenter.y -= 5;
} else {
this.verticalDirection = 1;
}
} else {
if (!this.reachBottomLimit(stageBounds)) {
this.rectCenter.y += 5;
} else {
this.verticalDirection = 0;
}
}
}
public paint(context: CanvasRenderingContext2D) {
context.fillStyle = 'rgb(255, 255, 255)';
context.fillRect(
this.rectCenter.x - this.rectSize.width / 2,
this.rectCenter.y - this.rectSize.height / 2,
this.rectSize.width,
this.rectSize.height);
}
protected isMovingToLeft(): boolean {
return this.horizontalDirection === 0;
}
// protected isMovingToRight(): boolean {
// return this.horizontalDirection === 1;
// }
protected isMovingToTop(): boolean {
return this.verticalDirection === 0;
}
// protected isMovingToBottom(): boolean {
// return this.verticalDirection === 1;
// }
protected reachLeftLimit(bounds: Size): boolean {
return this.rectCenter.x - this.rectSize.width / 2 <= 0;
}
protected reachRightLimit(bounds: Size): boolean {
return this.rectCenter.x + this.rectSize.width / 2 >= bounds.width;
}
protected reachTopLimit(bounds: Size): boolean {
return this.rectCenter.y - this.rectSize.height / 2 <= 0;
}
protected reachBottomLimit(bounds: Size): boolean {
return this.rectCenter.y + this.rectSize.height / 2 >= bounds.height;
}
} | garolard/graphic-toys | src/shapes.ts | TypeScript | mit | 2,760 |
#!/usr/bin/php
<?php
require "../api/Init.php";
require "../api/AbzuDB.php";
$AbzuDB = new AbzuDB($db);
echo $AbzuDB->get_gauge_to_date("7813517", "month", "2016-03") . "\n";
// $AbzuDB->get_meter_data("7813517", "week");
// $AbzuDB->insert_meter_data("042014", "01245", "10/Oct/2000:13:55:36 -0700");
?>
| jacobm001/independence_water | tools/test_AbzuDB.php | PHP | mit | 312 |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
namespace Hstar.Lara.Cache.Tests
{
[TestClass]
public class SimpleMemoryCacheTest
{
private static CacheItem<int> intCache;
private static int cacheValue = 1;
[ClassInitialize]
public static void Initialize(TestContext context)
{
intCache = SimpleMemoryCache.Create<int>(() =>
{
cacheValue++;
return Task.Run(() => cacheValue);
}, cacheValue);
}
[DataTestMethod]
[DataRow(null, 1)]
[DataRow(2, 2)]
[DataRow(99999, 99999)]
[DataRow(-1, -1)]
[DataRow(0, 0)]
public void Test_Get_Set_Cache_Value(int? value, int expected)
{
if (value != null)
{
var setValueTask = intCache.SetValue(value.Value);
setValueTask.Wait();
}
var task = intCache.GetValue();
task.Wait();
Assert.AreEqual(expected, task.Result);
}
}
} | hstarorg/Hstar.Core | test/Lara.Cache.Tests/SimpleMemoryCacheTest.cs | C# | mit | 1,099 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.desk.notifications import delete_notification_count_for
from frappe.core.doctype.user.user import STANDARD_USERS
from frappe.utils.user import get_enabled_system_users
from frappe.utils import cint
@frappe.whitelist()
def get_list(arg=None):
"""get list of messages"""
frappe.form_dict['limit_start'] = int(frappe.form_dict['limit_start'])
frappe.form_dict['limit_page_length'] = int(frappe.form_dict['limit_page_length'])
frappe.form_dict['user'] = frappe.session['user']
# set all messages as read
frappe.db.begin()
frappe.db.sql("""UPDATE `tabCommunication` set seen = 1
where
communication_type in ('Chat', 'Notification')
and reference_doctype = 'User'
and reference_name = %s""", frappe.session.user)
delete_notification_count_for("Messages")
frappe.local.flags.commit = True
if frappe.form_dict['contact'] == frappe.session['user']:
# return messages
return frappe.db.sql("""select * from `tabCommunication`
where
communication_type in ('Chat', 'Notification')
and reference_doctype ='User'
and (owner=%(contact)s
or reference_name=%(user)s
or owner=reference_name)
order by creation desc
limit %(limit_start)s, %(limit_page_length)s""", frappe.local.form_dict, as_dict=1)
else:
return frappe.db.sql("""select * from `tabCommunication`
where
communication_type in ('Chat', 'Notification')
and reference_doctype ='User'
and ((owner=%(contact)s and reference_name=%(user)s)
or (owner=%(contact)s and reference_name=%(contact)s))
order by creation desc
limit %(limit_start)s, %(limit_page_length)s""", frappe.local.form_dict, as_dict=1)
@frappe.whitelist()
def get_active_users():
data = frappe.db.sql("""select name,
(select count(*) from tabSessions where user=tabUser.name
and timediff(now(), lastupdate) < time("01:00:00")) as has_session
from tabUser
where enabled=1 and
ifnull(user_type, '')!='Website User' and
name not in ({})
order by first_name""".format(", ".join(["%s"]*len(STANDARD_USERS))), STANDARD_USERS, as_dict=1)
# make sure current user is at the top, using has_session = 100
users = [d.name for d in data]
if frappe.session.user in users:
data[users.index(frappe.session.user)]["has_session"] = 100
else:
# in case of administrator
data.append({"name": frappe.session.user, "has_session": 100})
return data
@frappe.whitelist()
def post(txt, contact, parenttype=None, notify=False, subject=None):
"""post message"""
d = frappe.new_doc('Communication')
d.communication_type = 'Notification' if parenttype else 'Chat'
d.subject = subject
d.content = txt
d.reference_doctype = 'User'
d.reference_name = contact
d.sender = frappe.session.user
d.insert(ignore_permissions=True)
delete_notification_count_for("Messages")
if notify and cint(notify):
if contact==frappe.session.user:
_notify([user.name for user in get_enabled_system_users()], txt)
else:
_notify(contact, txt, subject)
return d
@frappe.whitelist()
def delete(arg=None):
frappe.get_doc("Communication", frappe.form_dict['name']).delete()
def _notify(contact, txt, subject=None):
from frappe.utils import get_fullname, get_url
try:
if not isinstance(contact, list):
contact = [frappe.db.get_value("User", contact, "email") or contact]
frappe.sendmail(\
recipients=contact,
sender= frappe.db.get_value("User", frappe.session.user, "email"),
subject=subject or "New Message from " + get_fullname(frappe.session.user),
message=frappe.get_template("templates/emails/new_message.html").render({
"from": get_fullname(frappe.session.user),
"message": txt,
"link": get_url()
}),
bulk=True)
except frappe.OutgoingEmailError:
pass
| vCentre/vFRP-6233 | frappe/desk/page/messages/messages.py | Python | mit | 3,886 |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type DeviceRegisteredUsersCollectionReferencesRequest.
/// </summary>
public partial class DeviceRegisteredUsersCollectionReferencesRequest : BaseRequest, IDeviceRegisteredUsersCollectionReferencesRequest
{
/// <summary>
/// Constructs a new DeviceRegisteredUsersCollectionReferencesRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public DeviceRegisteredUsersCollectionReferencesRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified DirectoryObject to the collection via POST.
/// </summary>
/// <param name="directoryObject">The DirectoryObject to add.</param>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task AddAsync(DirectoryObject directoryObject)
{
return this.AddAsync(directoryObject, CancellationToken.None);
}
/// <summary>
/// Adds the specified DirectoryObject to the collection via POST.
/// </summary>
/// <param name="directoryObject">The DirectoryObject to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task AddAsync(DirectoryObject directoryObject, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
if (string.IsNullOrEmpty(directoryObject.Id))
{
throw new ServiceException(new Error { Code = "invalidRequest", Message = "ID is required to add a reference." });
}
var requestBody = new ReferenceRequestBody { ODataId = string.Format("{0}/directoryObjects/{1}", this.Client.BaseUrl, directoryObject.Id) };
return this.SendAsync(requestBody, cancellationToken);
}
}
}
| garethj-msft/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/DeviceRegisteredUsersCollectionReferencesRequest.cs | C# | mit | 2,890 |
import {CORE_DIRECTIVES} from 'angular2/common';
import {Component} from 'angular2/core';
import {OnInit} from 'angular2/core';
import {NotificationService} from '../../service/notification-service';
import {Alert} from 'ng2-bootstrap/ng2-bootstrap';
@Component({
selector: 'notification-center',
template: require('./notification-center.html'),
styles: [require('./notification-center.css')],
directives: [Alert, CORE_DIRECTIVES]
})
export class NotificationCenter implements OnInit {
constructor(private _notificationService: NotificationService) {
}
notifications: Array<Object> = [];
closeNotification(i: number) {
this.notifications.splice(i, 1);
}
ngOnInit() {
this._notificationService.eventBus.subscribe(notification =>
this.onNotificationReceived(notification));
}
private onNotificationReceived(notification) {
this.notifications.push(notification);
}
}
| z424brave/DKClient | src/app/common/directives/notification-center/notification-center.ts | TypeScript | mit | 967 |
'use strict';
function fixImports() {
let editor = atom.workspace.getActiveTextEditor()
if (editor) {
// fixImports(editor)
// editor.selectLinesContainingCursors()
}
}
module.exports = {
fixImports,
};
| madhusudhand/atom-angular2 | lib/command-handlers.js | JavaScript | mit | 231 |
using System.Threading.Tasks;
namespace _2.Thread_Save_Singleton
{
class Program
{
static void Main(string[] args)
{
Parallel.For(0, 6, x => LazyThreadSafeLogger.Instance.SaveToLog(x));
LazyThreadSafeLogger.Instance.PrintLog();
}
}
}
| VVoev/Telerik-Academy | 14.Design-Patterns/02. Design-Patterns/DesignPatternsDemo/2.Thread-Save-Singleton/Program.cs | C# | mit | 298 |
require 'json'
autoload :EbayItem, "ebay_ruby/ebay_item"
class EbayFindItem
def initialize(json)
@json = json
end
attr_reader :json
def parse
JSON.parse(json).values.first
end
def all_items
total_items = []
begin
parse.first["searchResult"].first["item"].each do |item|
ebay_item = EbayItem.new(item)
ebay_item.build_items_data
total_items << ebay_item
end
rescue
total_items = []
end
total_items.flatten
end
end
| rajcybage/ebay_ruby | lib/ebay_ruby/ebay_find_item.rb | Ruby | mit | 503 |
var $iterators = require('./es6.array.iterator')
, redefine = require('./_redefine')
, global = require('./_global')
, hide = require('./_hide')
, Iterators = require('./_iterators')
, wks = require('./_wks')
, CORRECT_SYMBOL = require('./_correct-symbol')
, ITERATOR = wks('iterator')
, TO_STRING_TAG = wks('toStringTag')
, ArrayValues = Iterators.Array;
require('./_').each.call((
'CSSRuleList,CSSStyleDeclaration,DOMStringList,DOMTokenList,FileList,HTMLCollection,MediaList,' +
'MimeTypeArray,NamedNodeMap,NodeList,NodeListOf,Plugin,PluginArray,StyleSheetList,TouchList'
).split(','), function(NAME){
var Collection = global[NAME]
, proto = Collection && Collection.prototype
, key;
if(proto){
if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
for(key in $iterators){
if(!CORRECT_SYMBOL || !proto[key])redefine(proto, key, $iterators[key], true);
}
}
}); | eteeselink/core-js | modules/web.dom.iterable.js | JavaScript | mit | 1,075 |
/* tslint:disable */
/* eslint-disable */
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type FairHeader_Test_QueryVariables = {};
export type FairHeader_Test_QueryResponse = {
readonly fair: {
readonly " $fragmentRefs": FragmentRefs<"FairHeader_fair">;
} | null;
};
export type FairHeader_Test_Query = {
readonly response: FairHeader_Test_QueryResponse;
readonly variables: FairHeader_Test_QueryVariables;
};
/*
query FairHeader_Test_Query {
fair(id: "example") {
...FairHeader_fair
id
}
}
fragment FairHeaderIcon_fair on Fair {
name
profile {
icon {
desktop: cropped(width: 100, height: 100, version: "square140") {
src
srcSet
}
mobile: cropped(width: 60, height: 60, version: "square140") {
src
srcSet
}
}
id
}
}
fragment FairHeader_fair on Fair {
...FairHeaderIcon_fair
name
exhibitionPeriod
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"kind": "Literal",
"name": "id",
"value": "example"
}
],
v1 = {
"kind": "Literal",
"name": "version",
"value": "square140"
},
v2 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "src",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "srcSet",
"storageKey": null
}
],
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "FairHeader_Test_Query",
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Fair",
"kind": "LinkedField",
"name": "fair",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "FairHeader_fair"
}
],
"storageKey": "fair(id:\"example\")"
}
],
"type": "Query"
},
"kind": "Request",
"operation": {
"argumentDefinitions": [],
"kind": "Operation",
"name": "FairHeader_Test_Query",
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Fair",
"kind": "LinkedField",
"name": "fair",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Profile",
"kind": "LinkedField",
"name": "profile",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "icon",
"plural": false,
"selections": [
{
"alias": "desktop",
"args": [
{
"kind": "Literal",
"name": "height",
"value": 100
},
(v1/*: any*/),
{
"kind": "Literal",
"name": "width",
"value": 100
}
],
"concreteType": "CroppedImageUrl",
"kind": "LinkedField",
"name": "cropped",
"plural": false,
"selections": (v2/*: any*/),
"storageKey": "cropped(height:100,version:\"square140\",width:100)"
},
{
"alias": "mobile",
"args": [
{
"kind": "Literal",
"name": "height",
"value": 60
},
(v1/*: any*/),
{
"kind": "Literal",
"name": "width",
"value": 60
}
],
"concreteType": "CroppedImageUrl",
"kind": "LinkedField",
"name": "cropped",
"plural": false,
"selections": (v2/*: any*/),
"storageKey": "cropped(height:60,version:\"square140\",width:60)"
}
],
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "exhibitionPeriod",
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": "fair(id:\"example\")"
}
]
},
"params": {
"id": null,
"metadata": {},
"name": "FairHeader_Test_Query",
"operationKind": "query",
"text": "query FairHeader_Test_Query {\n fair(id: \"example\") {\n ...FairHeader_fair\n id\n }\n}\n\nfragment FairHeaderIcon_fair on Fair {\n name\n profile {\n icon {\n desktop: cropped(width: 100, height: 100, version: \"square140\") {\n src\n srcSet\n }\n mobile: cropped(width: 60, height: 60, version: \"square140\") {\n src\n srcSet\n }\n }\n id\n }\n}\n\nfragment FairHeader_fair on Fair {\n ...FairHeaderIcon_fair\n name\n exhibitionPeriod\n}\n"
}
};
})();
(node as any).hash = 'd21850d49af37a798ce9cacad82ca4a2';
export default node;
| artsy/force-public | src/v2/__generated__/FairHeader_Test_Query.graphql.ts | TypeScript | mit | 5,927 |
// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
package watch
import (
"log"
"os"
"sync"
"syscall"
"github.com/hpcloud/tail/util"
"gopkg.in/fsnotify.v1"
)
type InotifyTracker struct {
mux sync.Mutex
watcher *fsnotify.Watcher
chans map[string]chan fsnotify.Event
done map[string]chan bool
watch chan *watchInfo
remove chan string
error chan error
}
type watchInfo struct {
fname string
}
var (
// globally shared InotifyTracker; ensures only one fsnotify.Watcher is used
shared *InotifyTracker
// these are used to ensure the shared InotifyTracker is run exactly once
once = sync.Once{}
goRun = func() {
shared = &InotifyTracker{
mux: sync.Mutex{},
chans: make(map[string]chan fsnotify.Event),
done: make(map[string]chan bool),
watch: make(chan *watchInfo),
remove: make(chan string),
error: make(chan error),
}
go shared.run()
}
logger = log.New(os.Stderr, "", log.LstdFlags)
)
// Watch signals the run goroutine to begin watching the input filename
func Watch(fname string) error {
// start running the shared InotifyTracker if not already running
once.Do(goRun)
shared.watch <- &watchInfo{
fname: fname,
}
return <-shared.error
}
// RemoveWatch signals the run goroutine to remove the watch for the input filename
func RemoveWatch(fname string) {
// start running the shared InotifyTracker if not already running
once.Do(goRun)
shared.mux.Lock()
done := shared.done[fname]
if done != nil {
delete(shared.done, fname)
close(done)
}
shared.mux.Unlock()
shared.remove <- fname
}
// Events returns a channel to which FileEvents corresponding to the input filename
// will be sent. This channel will be closed when removeWatch is called on this
// filename.
func Events(fname string) chan fsnotify.Event {
shared.mux.Lock()
defer shared.mux.Unlock()
return shared.chans[fname]
}
// Cleanup removes the watch for the input filename if necessary.
func Cleanup(fname string) {
RemoveWatch(fname)
}
// watchFlags calls fsnotify.WatchFlags for the input filename and flags, creating
// a new Watcher if the previous Watcher was closed.
func (shared *InotifyTracker) addWatch(fname string) error {
shared.mux.Lock()
defer shared.mux.Unlock()
if shared.chans[fname] == nil {
shared.chans[fname] = make(chan fsnotify.Event)
shared.done[fname] = make(chan bool)
}
return shared.watcher.Add(fname)
}
// removeWatch calls fsnotify.RemoveWatch for the input filename and closes the
// corresponding events channel.
func (shared *InotifyTracker) removeWatch(fname string) {
shared.mux.Lock()
defer shared.mux.Unlock()
if ch := shared.chans[fname]; ch != nil {
shared.watcher.Remove(fname)
delete(shared.chans, fname)
close(ch)
}
}
// sendEvent sends the input event to the appropriate Tail.
func (shared *InotifyTracker) sendEvent(event fsnotify.Event) {
shared.mux.Lock()
ch := shared.chans[event.Name]
done := shared.done[event.Name]
shared.mux.Unlock()
if ch != nil && done != nil {
select {
case ch <- event:
case <-done:
}
}
}
// run starts the goroutine in which the shared struct reads events from its
// Watcher's Event channel and sends the events to the appropriate Tail.
func (shared *InotifyTracker) run() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
util.Fatal("failed to create Watcher")
}
shared.watcher = watcher
for {
select {
case winfo := <-shared.watch:
shared.error <- shared.addWatch(winfo.fname)
case fname := <-shared.remove:
shared.removeWatch(fname)
case event, open := <-shared.watcher.Events:
if !open {
return
}
shared.sendEvent(event)
case err, open := <-shared.watcher.Errors:
if !open {
return
} else if err != nil {
sysErr, ok := err.(*os.SyscallError)
if !ok || sysErr.Err != syscall.EINTR {
logger.Printf("Error in Watcher Error channel: %s", err)
}
}
}
}
}
| millken/kaman | vendor/github.com/hpcloud/tail/watch/inotify_tracker.go | GO | mit | 3,931 |
/**
* Copyright (c) 2014 Famous Industries, Inc.
*
* 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.
*
* @license MIT
*/
/**
* HeaderFooterLayout
* ------------------
*
* HeaderFooterLayout is a layout which will arrange three renderables
* into a header and footer area of defined size and a content area
* of flexible size.
*
* In this example we create a basic HeaderFooterLayout and define a
* size for the header and footer
*/
define(function(require, exports, module) {
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var StateModifier = require('famous/modifiers/StateModifier');
var Transform = require('famous/core/Transform');
var HeaderFooterLayout = require('famous/views/HeaderFooterLayout');
var Easing = require('famous/transitions/Easing');
var RenderController = require("famous/views/RenderController");
var MenuView = require('./views/MenuView');
var PlayHeaderView = require('./views/PlayHeaderView');
var PlayBodyView = require('./views/PlayBodyView');
var PlayFooterView = require('./views/PlayFooterView');
var Transitionable = require('famous/transitions/Transitionable');
var SpringTransition = require('famous/transitions/SpringTransition');
Transitionable.registerMethod('spring', SpringTransition);
var mainContext = Engine.createContext();
var layout = new HeaderFooterLayout({
headerSize: 50,
footerSize: 50
});
layout.header.add(PlayHeaderView);
//position to the center
var bodyRenderController = new RenderController();
layout.content.add(bodyRenderController);
var bodySurfaces = [];
bodySurfaces.push(PlayBodyView);
bodySurfaces.push(MenuView);
bodyRenderController.show(bodySurfaces[0]);
PlayBodyView.eventHandler.on('seekToPosition', function(data) {
PlayHeaderView.setIsPlaying(false);
});
PlayBodyView.eventHandler.on('finishedSpeaking', function(data) {
PlayHeaderView.setIsPlaying(true);
});
var togglemenu = false;
PlayHeaderView.eventHandler.on('showMenu', function(data) {
bodySurfaces[1].toggle();
togglemenu = !togglemenu;
if (togglemenu) {
bodyRenderController.show(bodySurfaces[1]);
} else {
bodyRenderController.show(bodySurfaces[0]);
}
});
PlayHeaderView.eventHandler.on('shouldFlipViews', function(data) {
PlayBodyView.flip();
});
PlayHeaderView.eventHandler.on('shouldPlay', function(data) {
PlayBodyView.play();
});
PlayHeaderView.eventHandler.on('toTop', function(data) {
PlayBodyView.scrollTo(0);
});
MenuView.eventHandler.on('changeContent', function(title) {
PlayHeaderView.setTitle(title);
PlayHeaderView.setIsPlaying(true);
PlayHeaderView.showMenu();
PlayBodyView.switchContent(title);
});
layout.footer.add(PlayFooterView);
mainContext.add(layout);
});
| hemantasapkota/pdfspeaker | src/app/js/main.js | JavaScript | mit | 4,131 |
import React, { Component, PropTypes } from 'react';
import Select from 'react-select';
import { omit } from 'lodash';
import classNames from 'classnames';
import styles from './styles.scss';
import chevronIcon from '../../../assets/images/icons/chevron-down.svg';
export const THEMES = { OLD: 'old', INTERNAL: 'internal' };
export default class SelectField extends Component {
static propTypes = {
theme: PropTypes.string,
label: PropTypes.string,
error: PropTypes.string,
className: PropTypes.string,
};
static defaultProps = {
theme: THEMES.OLD,
};
constructor(props, context) {
super(props, context);
this.renderArrow = ::this.renderArrow;
}
renderArrow() {
return (
<div className={styles.selectArrow}>
<img src={chevronIcon} alt="chevron" />
</div>
);
}
renderOption(option, i) {
return (
<div key={i} className={styles.selectFieldOption}>{option.label}</div>
);
}
renderLabel() {
const labelStyles = classNames(styles.selectLabel, { [styles.selectLabelInvalid]: this.props.error });
return this.props.label ? (
<div className={labelStyles}>{this.props.label}</div>
) : null;
}
renderError() {
return this.props.error ? (
<div className={styles.selectFieldError}>
{this.props.error}
</div>
) : null;
}
renderSelectField() {
const selectStyles = classNames(styles.selectField, { [styles.selectFieldInvalid]: this.props.error });
const props = omit(this.props, ['error', 'label']);
return (
<div className={selectStyles}>
<Select {...props} arrowRenderer={this.renderArrow} optionRenderer={this.renderOption} />
{this.renderError()}
</div>
);
}
render() {
const selectStyles = classNames(styles.select, this.props.className, {
[styles.selectOld]: this.props.theme === THEMES.OLD,
[styles.selectInternal]: this.props.theme === THEMES.INTERNAL,
});
return (
<div className={selectStyles}>
{this.renderLabel()}
{this.renderSelectField()}
</div>
);
}
}
| singaporesamara/SOAS-DASHBOARD | app/components/UIKit/SelectField/index.js | JavaScript | mit | 2,115 |
<?php
declare(strict_types=1);
namespace Thunder\Currenz\Tests;
use PHPUnit\Framework\TestCase;
use Thunder\Currenz\Utility\Utility;
final class UtilityTest extends TestCase
{
public function testXmlToArray()
{
$this->assertCount(179, Utility::xmlToArray(file_get_contents(__DIR__.'/../data/list_one.xml')));
}
}
| thunderer/Currenz | tests/UtilityTest.php | PHP | mit | 335 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from snisi_core.models.Entities import AdministrativeEntity as AEntity
if PY2:
import unicodecsv as csv
else:
import csv
logger = logging.getLogger(__name__)
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('-f',
help='CSV file',
action='store',
dest='filename'),
)
def handle(self, *args, **options):
headers = ['name', 'region', 'cercle_commune', 'commune_quartier']
f = open(options.get('filename'), 'w')
csv_writer = csv.DictWriter(f, fieldnames=headers)
csv_writer.writeheader()
csv_writer.writerow({
'name': "label",
'region': "Région",
'cercle_commune': "Cercle",
'commune_quartier': "Commune",
})
for region in AEntity.objects.filter(type__slug='region'):
logger.info(region)
is_bko = region.name == 'BAMAKO'
for cercle in AEntity.objects.filter(parent=region):
logger.info(cercle)
for commune in AEntity.objects.filter(parent=cercle):
logger.info(commune)
if not is_bko:
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': cercle.name,
'commune_quartier': commune.name
})
continue
for vfq in AEntity.objects.filter(parent=commune):
for v in (region, cercle, commune, vfq):
if not len(v.name.strip()):
continue
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': commune.name,
'commune_quartier': vfq.name
})
f.close()
| yeleman/snisi | snisi_maint/management/commands/entities_to_cascades.py | Python | mit | 2,414 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# sl-ls.py: get information utility
# Created by NAKAJIMA Takaaki
# Last modified: Apr 16, 2014.
#
# Require: Python v3
#
# See also https://softlayer-api-python-client.readthedocs.org
#
# You should set env variables
# SL_USERNAME = YOUR_USERNAME
# SL_API_KEY = YOUR_API_KEY
import logging
import SoftLayer
client = SoftLayer.Client()
class IterableItems:
u"""Pagenate されているリストを全体を回せるようにする"""
def __init__(self, client, limit=10):
self.master_account = client['Account']
self.offset = 0
self.limit = limit
self.define_fetch_method()
self.fetched = self.fetch()
def define_fetch_method(self):
u"""継承側クラスで実装すること"""
# self.fetch_method に適切な pagenate メソッドを設定
raise NotImpementedError("Not implemented yet.")
def fetch(self):
items = self.fetch_method(limit=self.limit, offset=self.offset)
self.offset += self.limit
return items
def __iter__(self):
return self
def __next__(self):
if len(self.fetched) < 1:
raise StopIteration
item = self.fetched.pop()
if len(self.fetched) < 1: # prefetch for next
self.fetched = self.fetch()
return item
class Users(IterableItems):
u"""List of SoftLayer_User_Customer"""
def define_fetch_method(self):
self.fetch_method = self.master_account.getUsers
class VirtualGuests(IterableItems):
u"""List of SoftLayer_Virtual_Guest"""
def define_fetch_method(self):
self.fetch_method = self.master_account.getVirtualGuests
# --------------------------------------------------------------
try:
master_account = client['Account']
print("## Account information ##")
user_mask="id, firstName, lastName, email"
account_info = master_account.getObject(mask=user_mask)
print(account_info)
# all child users
#for user in master_account.getUsers(limit=10, offset=0):
print("## Users ##");
for user in Users(client):
print("id:%d, %s" % (user['id'], user['username']))
# Virtual guest OSes
# for vg in client['Account'].getVirtualGuests(limit=10, offset=0):
print("## Virtual guests ##");
for vg in VirtualGuests(client):
print("AccountId=%s, ID=%d, hostname=%s"
% (vg['accountId'], vg['id'], vg['hostname']))
print("## Instances ##");
cci_manager = SoftLayer.CCIManager(client)
for cci in cci_manager.list_instances():
print("FQDN=%s, IP_addrs=%s, %s"
% (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress']))
print("## Billing items ##")
billing_mask = "id, parentId, description, currentHourlyCharge"
print(master_account.getAllBillingItems(mask=billing_mask))
except SoftLayer.SoftLayerAPIError as e:
print("Unable to retrieve account information faultCode%s, faultString=%s"
% (e.faultCode, e.faultString))
exit(1)
| ryumei/softlayer-utility | sl-ls.py | Python | mit | 3,178 |
require "aop"
require "contracts"
class BankAccount < Struct.new(:number, :amount)
include Contracts
Contract BankAccount, Num => Num
def transfer(other, amount)
self.amount -= amount
other.amount += amount
end
end
@actual = nil
@expected = "Transfered 100 from 12345 to 98765"
Aop["BankAccount#transfer:after"].advice do |account, other, amount|
@actual = "Transfered #{amount} from #{account.number} to #{other.number}"
end
BankAccount[12345, 955].transfer(BankAccount[98765, 130], 100)
fail "\nExpected: #{@expected}\nActual: #{@actual}" unless @expected == @actual
| waterlink/aop | integration/contracts.rb | Ruby | mit | 595 |
from .View import View
class MethuselahView(View):
type = "Methuselah"
trans = {
"stableAfter": {"pick": "l"}
}
| mir3z/life.js | library-scrapper/views/Methuselah.py | Python | mit | 134 |
module Downsampler
module TimeExt
def floor(seconds = 60)
Time.at((self.to_f / seconds).floor * seconds)
end
end
end | omockler/downsampler | lib/downsampler/time_extensions.rb | Ruby | mit | 134 |
<?php
namespace Virgin\ChannelGuideBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Channel
*
* @ORM\Table(name="channel")
* @ORM\Entity(repositoryClass="Virgin\ChannelGuideBundle\Entity\ChannelRepository")
*/
class Channel implements ChannelInterface
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
* @ORM\Column(type="string")
*/
private $name;
/**
* @var number
* @ORM\Column(type="string")
*/
private $number;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setNumber($number)
{
$this->number = $number;
}
public function getNumber()
{
return $this->number;
}
public function __toString() {
return $this->getName();
}
}
| guided1/virgin-symfony-test | src/Virgin/ChannelGuideBundle/Entity/Channel.php | PHP | mit | 1,127 |
# coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class FeedbackList(ListResource):
def __init__(self, version, account_sid, message_sid):
"""
Initialize the FeedbackList
:param Version version: Version that contains the resource
:param account_sid: The account_sid
:param message_sid: The message_sid
:returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList
:rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList
"""
super(FeedbackList, self).__init__(version)
# Path Solution
self._solution = {
'account_sid': account_sid,
'message_sid': message_sid,
}
self._uri = '/Accounts/{account_sid}/Messages/{message_sid}/Feedback.json'.format(**self._solution)
def create(self, outcome=values.unset):
"""
Create a new FeedbackInstance
:param FeedbackInstance.Outcome outcome: The outcome
:returns: Newly created FeedbackInstance
:rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance
"""
data = values.of({
'Outcome': outcome,
})
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return FeedbackInstance(
self._version,
payload,
account_sid=self._solution['account_sid'],
message_sid=self._solution['message_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.FeedbackList>'
class FeedbackPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the FeedbackPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param account_sid: The account_sid
:param message_sid: The message_sid
:returns: twilio.rest.api.v2010.account.message.feedback.FeedbackPage
:rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackPage
"""
super(FeedbackPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of FeedbackInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance
:rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance
"""
return FeedbackInstance(
self._version,
payload,
account_sid=self._solution['account_sid'],
message_sid=self._solution['message_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.FeedbackPage>'
class FeedbackInstance(InstanceResource):
class Outcome(object):
CONFIRMED = "confirmed"
UMCONFIRMED = "umconfirmed"
def __init__(self, version, payload, account_sid, message_sid):
"""
Initialize the FeedbackInstance
:returns: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance
:rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance
"""
super(FeedbackInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload['account_sid'],
'message_sid': payload['message_sid'],
'outcome': payload['outcome'],
'date_created': deserialize.rfc2822_datetime(payload['date_created']),
'date_updated': deserialize.rfc2822_datetime(payload['date_updated']),
'uri': payload['uri'],
}
# Context
self._context = None
self._solution = {
'account_sid': account_sid,
'message_sid': message_sid,
}
@property
def account_sid(self):
"""
:returns: The account_sid
:rtype: unicode
"""
return self._properties['account_sid']
@property
def message_sid(self):
"""
:returns: The message_sid
:rtype: unicode
"""
return self._properties['message_sid']
@property
def outcome(self):
"""
:returns: The outcome
:rtype: FeedbackInstance.Outcome
"""
return self._properties['outcome']
@property
def date_created(self):
"""
:returns: The date_created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The date_updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def uri(self):
"""
:returns: The uri
:rtype: unicode
"""
return self._properties['uri']
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.FeedbackInstance>'
| angadpc/Alexa-Project- | twilio/rest/api/v2010/account/message/feedback.py | Python | mit | 5,676 |
require 'uri'
class SuperSearch
def self.url
"http://search.alaska.test/"
end
def self.query_param_for(item_name)
# item_name.gsub(/\s+/, '+')
URI.encode item_name
end
def self.url_for(item_name)
"#{SuperSearch.url}index.php?q=#{SuperSearch.query_param_for(item_name)}"
end
def self.url_for_engine(engine_key, item_name)
SuperSearch.url + engine_key + '/' + SuperSearch.query_param_for(item_name)
end
end
| allen-garvey/booklist-rails | lib/super_search.rb | Ruby | mit | 424 |
<?php
//common environment attributes including search paths. not specific to Learnosity
include_once '../../env_config.php';
//site scaffolding
include_once 'includes/header.php';
//common Learnosity config elements including API version control vars
include_once '../../lrn_config.php';
use LearnositySdk\Request\Init;
use LearnositySdk\Utils\Uuid;
$session_id = Uuid::generate();
$security = [
'user_id' => 'demo_student_123',
'domain' => $domain,
'consumer_key' => $consumer_key
];
$init = new Init('questions', $security, $consumer_secret, [
'id' => 'custom-shorttext',
'name' => 'Custom Short Text',
'type' => 'local_practice',
'state' => 'initial',
'session_id' => $session_id
]);
$request = '{
"response_id": "custom-shorttext-response-' . $session_id . '",
"type": "custom",
"js": {
"question":"//' . $_SERVER['HTTP_HOST'] . '/usecases/customquestions/custom_shorttext_q.js",
"scorer":"//' . $_SERVER['HTTP_HOST'] . '/usecases/customquestions/custom_shorttext_s.js"
},
"css": "//' . $_SERVER['HTTP_HOST'] . '/usecases/customquestions/custom_shorttext.css",
"stimulus": "What is the capital of Australia?",
"valid_response": "Canberra",
"score": 1
}';
?>
<style>
.custom-score {
position: absolute;
font-size: 17px;
margin-top: 5px;
}
.editor{
margin-bottom: 15px;
}
</style>
<div class="jumbotron section">
<div class="toolbar">
<ul class="list-inline">
<li data-toggle="tooltip" data-original-title="Visit the documentation"><a href="https://support.learnosity.com/hc/en-us/articles/360000758817-Creating-Custom-Questions" title="Documentation"><span class="glyphicon glyphicon-book"></span></a></li>
</ul>
</div>
<div class="overview">
<h1>Custom Question - Short Text</h1>
<p>Here is a demo which shows an example custom implementation of the Short Text question type. You can rewrite the question JSON to define your own custom questions.</p>
</div>
</div>
<div class="section">
<div class="row">
<div class="col-md-6">
<h2 class="page-heading">Question JSON</h2>
<div id="editor" class="editor"><?php echo htmlspecialchars($request);?></div>
</div>
<div class="col-md-6">
<h2 class="page-heading">Preview</h2>
<div id="custom_question_wrapper"></div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button class="btn btn-primary pull-right" id="render_custom_question">Render JSON</button>
</div>
<div class="col-md-6">
<div class="custom-score"><strong>Score: </strong> <span id="question_score">0</span> / <span id="question_max_score">0</span></div>
<button class="btn btn-primary pull-right" id="validate_question">Check Answer</button>
</div>
</div>
</div>
<script src="<?php echo $url_questions; ?>"></script>
<script src="/static/vendor/ace/ace-builds/src-min-noconflict/ace.js"></script>
<script>
var activity = <?php echo $init->generate(); ?>;
var editor = ace.edit('editor');
editor.setTheme('ace/theme/kuroir');
editor.getSession().setMode('ace/mode/json');
editor.setShowPrintMargin(false);
editor.setOptions({
maxLines: 25
});
editor.navigateFileEnd();
editor.focus();
$(function(){
function init() {
var json;
try {
json = JSON.parse(editor.getValue());
} catch (e) {
console.error('JSON is invalid');
return;
}
$('#custom_question_wrapper').html(
'<span class="learnosity-response question-'+json.response_id+'"></span>'
);
activity.questions = [json];
var questionsApp = window.questionsApp = LearnosityApp.init(activity, {
errorListener: window.widgetApiErrorListener,
readyListener: function () {
var question = questionsApp.question(json.response_id);
updateScores(question);
question.on('changed', function (r) {
updateScores(question);
});
$('#validate_question').off().click(function() {
questionsApp.validateQuestions();
});
}
});
}
function updateScores(question) {
var score = question.getScore();
$('#question_score').html((score && score.score) || 0);
$('#question_max_score').html((score && score.max_score) || 0);
}
init();
$('#render_custom_question').click(init);
});
</script>
<?php
include_once 'includes/footer.php';
| Learnosity/learnosity-demos | www/usecases/customquestions/custom.php | PHP | mit | 4,981 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.ProjectOxford.Video.Contract
{
/// <summary>
/// An individual event during FaceDetection action, returned in the <see cref="FaceDetectionResult"/> object.
/// </summary>
public class FaceEvent
{
/// <summary>
/// Gets or sets Id of face.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets or sets upper-left coordinate of the face, as a fraction of the overall frame width.
/// </summary>
public double X { get; set; }
/// <summary>
/// Gets or sets upper-left coordinate of the face, as a fraction of the overall frame height.
/// </summary>
public double Y { get; set; }
/// <summary>
/// Gets or sets width of the face, as a fraction of the overall frame width.
/// </summary>
public double Width { get; set; }
/// <summary>
/// Gets or sets height of the face, as a fraction of the overall frame height.
/// </summary>
public double Height { get; set; }
}
}
| Microsoft/ProjectOxford-ClientSDK | Video/Windows/ClientLibrary/Contract/FaceEvent.cs | C# | mit | 1,241 |
package openperipheral.adapter;
public interface IMethodCall {
public IMethodCall setEnv(String name, Object value);
public Object[] call(Object... args) throws Exception;
}
| OpenMods/OpenPeripheral | src/main/java/openperipheral/adapter/IMethodCall.java | Java | mit | 180 |
#pragma once
#include <glkernel/noise.h>
#include <glkernel/glm_compatability.h>
namespace
{
// From // JAVA REFERENCE IMPLEMENTATION OF IMPROVED NOISE - COPYRIGHT 2002 KEN PERLIN. (http://mrl.nyu.edu/~perlin/noise/)
// and (Improving Noise - Perlin - 2002) - http://mrl.nyu.edu/~perlin/paper445.pdf
const std::vector<unsigned char> perm =
{
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180
};
const std::vector<glm::vec3> grad =
{
{ 1.0, 1.0, 0.0 }, { -1.0, 1.0, 0.0 }, { 1.0, -1.0, 0.0 }, { -1.0, -1.0, 0.0 },
{ 1.0, 0.0, 1.0 }, { -1.0, 0.0, 1.0 }, { 1.0, 0.0, -1.0 }, { -1.0, 0.0, -1.0 },
{ 0.0, 1.0, 1.0 }, { 0.0, -1.0, 1.0 }, { 0.0, 1.0, -1.0 }, { 0.0, -1.0, -1.0 },
{ 1.0, 1.0, 0.0 }, { -1.0, 1.0, 0.0 }, { 0.0, -1.0, 0.0 }, { 0.0, -1.0, -1.0 }
};
unsigned char hash3(
const unsigned int x
, const unsigned int y
, const unsigned int z
, const unsigned int r)
{
// the values of x, y and z will be in [0, 1 << r]
// the frequency mask is used for returning equal values
// for the minimum and the maximum input to ensure tileability
unsigned int frequencyMask = 1 << r;
assert(frequencyMask <= perm.size());
return perm[(perm[(perm[x % frequencyMask] + y) % frequencyMask] + z) % frequencyMask];
}
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
glm::tvec3<T, glm::highp> grad3(
const unsigned int x
, const unsigned int y
, const unsigned int z
, const unsigned int r)
{
const auto p = hash3(x, y, z, r);
return glm::tvec3<T, glm::highp>(grad[p % 16]);
}
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
glm::tvec3<T, glm::highp> grad3(
glm::tvec3<unsigned int, glm::highp> v
, const unsigned int r)
{
const auto p = hash3(v.x, v.y, v.z, r);
return glm::tvec3<T, glm::highp>(grad[p % 16]);
}
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
T smootherstep(const T t)
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
T perlin3(
const T s
, const T t
, const T u
, const unsigned int r)
{
// scale according to frequency
const auto scaled_s = s * (1 << r);
const auto scaled_t = t * (1 << r);
const auto scaled_u = u * (1 << r);
const auto is = static_cast<unsigned int>(floor(scaled_s));
const auto it = static_cast<unsigned int>(floor(scaled_t));
const auto iu = static_cast<unsigned int>(floor(scaled_u));
const auto f = glm::fract(glm::tvec3<T, glm::highp>(scaled_s, scaled_t, scaled_u));
// range [-1;+1]
const auto aaa = glm::dot(grad3<T>(is + 0, it + 0, iu + 0, r), f);
const auto baa = glm::dot(grad3<T>(is + 1, it + 0, iu + 0, r), f - glm::tvec3<T, glm::highp>(1., 0., 0.));
const auto aba = glm::dot(grad3<T>(is + 0, it + 1, iu + 0, r), f - glm::tvec3<T, glm::highp>(0., 1., 0.));
const auto bba = glm::dot(grad3<T>(is + 1, it + 1, iu + 0, r), f - glm::tvec3<T, glm::highp>(1., 1., 0.));
const auto aab = glm::dot(grad3<T>(is + 0, it + 0, iu + 1, r), f - glm::tvec3<T, glm::highp>(0., 0., 1.));
const auto bab = glm::dot(grad3<T>(is + 1, it + 0, iu + 1, r), f - glm::tvec3<T, glm::highp>(1., 0., 1.));
const auto abb = glm::dot(grad3<T>(is + 0, it + 1, iu + 1, r), f - glm::tvec3<T, glm::highp>(0., 1., 1.));
const auto bbb = glm::dot(grad3<T>(is + 1, it + 1, iu + 1, r), f - glm::tvec3<T, glm::highp>(1., 1., 1.));
// interpolate noise values of the eight corners
const auto i = glm::mix(
glm::tvec4<T, glm::highp>(aaa, aab, aba, abb),
glm::tvec4<T, glm::highp>(baa, bab, bba, bbb),
smootherstep(f[0]));
const auto j = glm::mix(
glm::tvec2<T, glm::highp>(i[0], i[1]),
glm::tvec2<T, glm::highp>(i[2], i[3]),
smootherstep(f[1]));
return glm::mix(j[0], j[1], smootherstep(f[2]));
}
// adapted from example code by Stefan Gustavson (stegu@itn.liu.se)
// (http://webstaff.itn.liu.se/~stegu/simplexnoise/SimplexNoise.java)
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
T simplex3(
const T s
, const T t
, const T u
, const unsigned int r)
{
const T skew_constant = 1 / static_cast<T>(3);
const T unskew_constant = 1 / static_cast<T>(6);
// scale according to frequency
const glm::tvec3<T, glm::highp> pos = {s, t, u};
const glm::tvec3<T, glm::highp> scaled_pos = pos * static_cast<T>(1 << r);
// skew the input space to determine the simplex cell origin
const T skew_factor = (scaled_pos.x + scaled_pos.y + scaled_pos.z) * skew_constant;
const glm::tvec3<unsigned int, glm::highp> corner = glm::tvec3<unsigned int, glm::highp>(glm::floor(scaled_pos + skew_factor));
// unskew the cell origin back to (x,y,z) space
const T unskew_factor = (corner.x + corner.y + corner.z) * unskew_constant;
const glm::tvec3<T, glm::highp> v0 = scaled_pos + unskew_factor - static_cast<glm::tvec3<T, glm::highp>>(corner);
// for the 3D case, the simplex shape is a slightly irregular tetrahedron.
// determine corner offsets in skewed space for specific simplex
glm::tvec3<unsigned int, glm::highp> corner_offset1;
glm::tvec3<unsigned int, glm::highp> corner_offset2;
if (v0.x >= v0.y)
{
if (v0.y >= v0.z)
{
corner_offset1 = {1, 0, 0};
corner_offset2 = {1, 1, 0};
} // X Y Z order
else if (v0.x >= v0.z)
{
corner_offset1 = {1, 0, 0};
corner_offset2 = {1, 0, 1};
} // X Z Y order
else
{
corner_offset1 = {0, 0, 1};
corner_offset2 = {1, 0, 1};
} // Z X Y order
}
else
{ // v0.x < v0.y
if (v0.y < v0.z)
{
corner_offset1 = {0, 0, 1};
corner_offset2 = {0, 1, 1};
} // Z Y X order
else if (v0.x < v0.z)
{
corner_offset1 = {0, 1, 0};
corner_offset2 = {0, 1, 1};
} // Y Z X order
else
{
corner_offset1 = {0, 1, 0};
corner_offset2 = {1, 1, 0};
} // Y X Z order
}
// corner offsets in (x,y,z) space
const glm::tvec3<T, glm::highp> v1 = v0 + unskew_constant - static_cast<glm::tvec3<T, glm::highp>>(corner_offset1);
const glm::tvec3<T, glm::highp> v2 = v0 + 2 * unskew_constant - static_cast<glm::tvec3<T, glm::highp>>(corner_offset2);
const glm::tvec3<T, glm::highp> v3 = v0 + (3 * unskew_constant - 1);
// contribution factors
const T t0 = static_cast<T>(0.5) - glm::dot(v0, v0);
const T t1 = static_cast<T>(0.5) - glm::dot(v1, v1);
const T t2 = static_cast<T>(0.5) - glm::dot(v2, v2);
const T t3 = static_cast<T>(0.5) - glm::dot(v3, v3);
// Calculate the contribution from the four corners
const T n0 = (t0 < 0) ? 0 : (std::pow(t0, 4) * glm::dot(grad3<T>(corner, r), v0));
const T n1 = (t1 < 0) ? 0 : (std::pow(t1, 4) * glm::dot(grad3<T>(corner + corner_offset1, r), v1));
const T n2 = (t2 < 0) ? 0 : (std::pow(t2, 4) * glm::dot(grad3<T>(corner + corner_offset2, r), v2));
const T n3 = (t3 < 0) ? 0 : (std::pow(t3, 4) * glm::dot(grad3<T>(corner + 1u, r), v3));
// Add contributions from each corner to get the final noise value.
// The result is scaled to stay just inside [-1,1]
return 32 * (n0 + n1 + n2 + n3);
}
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
T get_octave_type_value(const glkernel::noise::OctaveType type
, const unsigned int octave
, const T noise_value
, const T octaved_noise)
{
switch (type)
{
case glkernel::noise::OctaveType::Standard:
return octave > 0 ? 0 : noise_value;
case glkernel::noise::OctaveType::Cloud:
return octaved_noise;
case glkernel::noise::OctaveType::CloudAbs:
return fabs(octaved_noise);
case glkernel::noise::OctaveType::Wood:
return octaved_noise * 8 - static_cast<int>(octaved_noise * 8);
case glkernel::noise::OctaveType::Paper:
return noise_value * noise_value * static_cast<T>(octaved_noise > 0 ? 1 : -1);
default:
return noise_value;
}
}
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
T get_noise_type_value(const glkernel::noise::GradientNoiseType type
, const T x
, const T y
, const T z
, const unsigned int octave)
{
switch (type)
{
case glkernel::noise::GradientNoiseType::Perlin:
return perlin3(x, y, z, octave);
case glkernel::noise::GradientNoiseType::Simplex:
return simplex3(x, y, z, octave);
default:
return 0;
}
}
} // namespace
namespace glkernel
{
namespace noise
{
template <typename T>
class uniform_operator
{
public:
template<typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr>
uniform_operator(size_t size, glm::length_t
, T range_min, T range_max);
template<typename V, typename std::enable_if<std::is_floating_point<typename V::value_type>::value>::type * = nullptr>
uniform_operator(size_t size, glm::length_t coefficient
, const V & range_min, const V & range_max);
T operator()(const size_t index);
protected:
std::mt19937_64 m_generator;
std::uniform_real_distribution<T> m_distribute;
};
template<typename T>
template<typename std::enable_if<std::is_floating_point<T>::value>::type *>
uniform_operator<T>::uniform_operator(const size_t, const glm::length_t
, const T range_min, const T range_max)
: m_generator{ std::random_device{ }() }
, m_distribute{ range_min, range_max }
{
}
template <typename T>
template<typename V, typename std::enable_if<std::is_floating_point<typename V::value_type>::value>::type *>
uniform_operator<T>::uniform_operator(const size_t size, const glm::length_t coefficient
, const V & range_min, const V & range_max)
: uniform_operator{ size, coefficient, range_min[coefficient], range_max[coefficient] }
{
}
template<typename T>
T uniform_operator<T>::operator()(const size_t)
{
return m_distribute(m_generator);
}
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type *>
void uniform(tkernel<T> & kernel, const T range_min, const T range_max)
{
kernel.template for_each<uniform_operator<T>>(range_min, range_max);
}
template<typename V, typename std::enable_if<std::is_floating_point<typename V::value_type>::value>::type *>
void uniform(tkernel<V> & kernel, const typename V::value_type range_min, const typename V::value_type range_max)
{
kernel.template for_each<uniform_operator<typename V::value_type>>(range_min, range_max);
}
template <typename V, typename std::enable_if<std::is_floating_point<typename V::value_type>::value>::type * = nullptr>
void uniform(tkernel<V> & kernel, const V & range_min, const V & range_max)
{
kernel.template for_each<uniform_operator<typename V::value_type>>(range_min, range_max);
}
template <typename T>
class normal_operator
{
public:
template <typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr>
normal_operator(size_t size, glm::length_t
, T mean, T stddev);
template <typename V, typename std::enable_if<std::is_floating_point<typename V::value_type>::value>::type * = nullptr>
normal_operator(size_t size, glm::length_t coefficient
, const V & mean, const V & stddev);
T operator()(const size_t index);
protected:
std::mt19937_64 m_generator;
std::uniform_real_distribution<T> m_distribute;
};
template <typename T>
template <typename std::enable_if<std::is_floating_point<T>::value>::type *>
normal_operator<T>::normal_operator(const size_t, const glm::length_t
, const T mean, const T stddev)
: m_generator{ std::random_device{}() }
, m_distribute{ mean, stddev }
{
}
template <typename T>
template <typename V, typename std::enable_if<std::is_floating_point<typename V::value_type>::value>::type *>
normal_operator<T>::normal_operator(const size_t size, const glm::length_t coefficient
, const V & mean, const V & stddev)
: normal_operator{ size, coefficient, mean[coefficient], stddev[coefficient] }
{
}
template<typename T>
T normal_operator<T>::operator()(const size_t)
{
return m_distribute(m_generator);
}
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type *>
void normal(tkernel<T> & kernel, const T mean, const T stddev)
{
kernel.template for_each<normal_operator<T>>(mean, stddev);
}
template <typename V, typename std::enable_if<std::is_floating_point<typename V::value_type>::value>::type * = nullptr>
void normal(tkernel<V> & kernel, const typename V::value_type mean, const typename V::value_type stddev)
{
kernel.template for_each<normal_operator<typename V::value_type>>(mean, stddev);
}
template <typename V, typename std::enable_if<std::is_floating_point<typename V::value_type>::value>::type * = nullptr>
void normal(tkernel<V> & kernel, const V & mean, const V & stddev)
{
kernel.template for_each<normal_operator<typename V::value_type>>(mean, stddev);
}
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type *>
void gradient(tkernel<T> & kernel
, const GradientNoiseType noise_type
, const OctaveType octave_type
, const unsigned int start_frequency
, const unsigned int octaves)
{
if (kernel.size() < 1)
return;
std::vector<T> fo(octaves);
for (unsigned int o = 0; o < octaves; ++o)
{
fo[o] = static_cast<T>(1.0 / (1 << o));
}
#pragma omp parallel for
for (long long i = 0; i < static_cast<long long>(kernel.size()); ++i)
{
const auto location = static_cast<glm::tvec3<T, glm::highp>>(kernel.position(i));
const auto x = location.x / kernel.width();
const auto y = location.y / kernel.height();
const auto z = location.z / kernel.depth();
// collect noise values over multiple octaves
T p = 0.5;
for (unsigned int o = 0; o < octaves; ++o)
{
const T po = get_noise_type_value(noise_type, x, y, z, o + start_frequency);
const T pf = fo[o] * po;
p += get_octave_type_value(octave_type, o, po, pf);
}
kernel[i] = p;
}
}
} // namespace noise
} // namespace glkernel
| cginternals/glkernel | source/glkernel/include/glkernel/noise.hpp | C++ | mit | 15,839 |
using System;
namespace MicrosoftGraph.Model
{
/// <summary>
/// Room
/// </summary>
[Serializable]
public class Room
{
/// <summary>
/// Room name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Room email
/// </summary>
public string Address { get; set; }
/// <summary>
/// Custom ToString method that returns room name
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name;
}
}
} | gled4er/doc-translator-api | MicrosoftGraph/Model/Room.cs | C# | mit | 599 |