code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
version https://git-lfs.github.com/spec/v1
oid sha256:3fe2372bec3008f9cab29eec1d438c62ef2cc056aacfc8f70c533ec50ba9b7f5
size 4224
|
yogeshsaroya/new-cdnjs
|
ajax/libs/jsforce/1.3.1/jsforce-api-apex.js
|
JavaScript
|
mit
| 129
|
package lila.irwin
import org.joda.time.DateTime
import reactivemongo.api.bson._
import reactivemongo.api.ReadPreference
import lila.analyse.Analysis
import lila.analyse.AnalysisRepo
import lila.common.Bus
import lila.db.dsl._
import lila.game.{ Game, GameRepo, Pov, Query }
import lila.report.{ Mod, ModId, Report, Reporter, Suspect, SuspectId }
import lila.tournament.{ Tournament, TournamentTop }
import lila.user.{ Holder, User, UserRepo }
final class IrwinApi(
reportColl: Coll,
gameRepo: GameRepo,
userRepo: UserRepo,
analysisRepo: AnalysisRepo,
modApi: lila.mod.ModApi,
reportApi: lila.report.ReportApi,
notifyApi: lila.notify.NotifyApi,
thresholds: lila.memo.SettingStore[IrwinThresholds]
)(implicit ec: scala.concurrent.ExecutionContext) {
import BSONHandlers._
def dashboard: Fu[IrwinDashboard] =
reportColl
.find($empty)
.sort($sort desc "date")
.cursor[IrwinReport]()
.list(20) dmap IrwinDashboard.apply
object reports {
def insert(report: IrwinReport) =
reportColl.update.one($id(report._id), report, upsert = true) >>
markOrReport(report) >>
notification(report) >>-
lila.mon.mod.irwin.ownerReport(report.owner).increment().unit
def get(user: User): Fu[Option[IrwinReport]] =
reportColl.find($id(user.id)).one[IrwinReport]
def withPovs(user: User): Fu[Option[IrwinReport.WithPovs]] =
get(user) flatMap {
_ ?? { report =>
gameRepo.gamesFromSecondary(report.games.map(_.gameId)) dmap { games =>
val povs = games.flatMap { g =>
Pov(g, user) map { g.id -> _ }
}.toMap
IrwinReport.WithPovs(report, povs).some
}
}
}
private def getSuspect(suspectId: User.ID) =
userRepo byId suspectId orFail s"suspect $suspectId not found" dmap Suspect.apply
private def markOrReport(report: IrwinReport): Funit =
userRepo.getTitle(report.suspectId.value) flatMap { title =>
if (report.activation >= thresholds.get().mark && title.isEmpty)
modApi.autoMark(report.suspectId, ModId.irwin, report.note) >>-
lila.mon.mod.irwin.mark.increment().unit
else if (report.activation >= thresholds.get().report) for {
suspect <- getSuspect(report.suspectId.value)
irwin <- userRepo byId "irwin" orFail s"Irwin user not found" dmap Mod.apply
_ <- reportApi.create(
Report.Candidate(
reporter = Reporter(irwin.user),
suspect = suspect,
reason = lila.report.Reason.Cheat,
text = s"${report.activation}% over ${report.games.size} games"
),
(_: Report.Score) => Report.Score(60)
)
} yield lila.mon.mod.irwin.report.increment().unit
else funit
}
}
object requests {
import IrwinRequest.Origin
def fromMod(suspect: Suspect, mod: Holder) = {
notification.add(suspect.id, ModId(mod.id))
insert(suspect, _.Moderator)
}
private[irwin] def insert(suspect: Suspect, origin: Origin.type => Origin): Funit =
for {
analyzed <- getAnalyzedGames(suspect, 15)
more <- getMoreGames(suspect, 20 - analyzed.size)
all = analyzed.map { case (game, analysis) =>
game -> analysis.some
} ::: more.map(_ -> none)
} yield Bus.publish(
IrwinRequest(
suspect = suspect,
origin = origin(Origin),
games = all
),
"irwin"
)
private[irwin] def fromTournamentLeaders(leaders: Map[Tournament, TournamentTop]): Funit =
lila.common.Future.applySequentially(leaders.toList) { case (tour, top) =>
userRepo byIds top.value.zipWithIndex
.filter(_._2 <= tour.nbPlayers * 2 / 100)
.map(_._1.userId)
.take(20) flatMap { users =>
lila.common.Future.applySequentially(users) { user =>
insert(Suspect(user), _.Tournament)
}
}
}
private[irwin] def fromLeaderboard(leaders: List[User]): Funit =
lila.common.Future.applySequentially(leaders) { user =>
insert(Suspect(user), _.Leaderboard)
}
import lila.game.BSONHandlers._
private def baseQuery(suspect: Suspect) =
Query.finished ++
Query.variantStandard ++
Query.rated ++
Query.user(suspect.id.value) ++
Query.turnsGt(20) ++
Query.createdSince(DateTime.now minusMonths 6)
private def getAnalyzedGames(suspect: Suspect, nb: Int): Fu[List[(Game, Analysis)]] =
gameRepo.coll
.find(baseQuery(suspect) ++ Query.analysed(true))
.sort(Query.sortCreated)
.cursor[Game](ReadPreference.secondaryPreferred)
.list(nb)
.flatMap(analysisRepo.associateToGames)
private def getMoreGames(suspect: Suspect, nb: Int): Fu[List[Game]] =
(nb > 0) ??
gameRepo.coll
.find(baseQuery(suspect) ++ Query.analysed(false))
.sort(Query.sortCreated)
.cursor[Game](ReadPreference.secondaryPreferred)
.list(nb)
}
object notification {
private var subs = Map.empty[SuspectId, Set[ModId]]
def add(suspectId: SuspectId, modId: ModId): Unit =
subs = subs.updated(suspectId, ~subs.get(suspectId) + modId)
private[IrwinApi] def apply(report: IrwinReport): Funit =
subs.get(report.suspectId) ?? { modIds =>
subs = subs - report.suspectId
import lila.notify.{ IrwinDone, Notification }
modIds
.map { modId =>
notifyApi.addNotification(
Notification.make(Notification.Notifies(modId.value), IrwinDone(report.suspectId.value))
)
}
.sequenceFu
.void
}
}
}
|
luanlv/lila
|
modules/irwin/src/main/IrwinApi.scala
|
Scala
|
mit
| 5,808
|
'use strict';
/** This file should be loaded via `import()` to be code-split into separate bundle. */
import { HiGlassComponent } from 'higlass/dist/hglib';
// import from just 'higlass-register' itself don't work, should update its package.json to have `"module": "src/index.js",` (or 'esm' or w/e it is) for that.
import { default as higlassRegister } from 'higlass-register/dist/higlass-register';
import { default as StackedBarTrack } from 'higlass-multivec/es/StackedBarTrack';
export {
HiGlassComponent,
higlassRegister,
StackedBarTrack
};
|
4dn-dcic/fourfront
|
src/encoded/static/components/item-pages/components/HiGlass/higlass-dependencies.js
|
JavaScript
|
mit
| 561
|
<?php
/*
* This file is part of PHP-CFG, a Control flow graph implementation for PHP
*
* @copyright 2015 Anthony Ferrara. All rights reserved
* @license MIT See LICENSE at the root of the project for more info
*/
namespace PHPCfg\Op;
use PHPCfg\Func;
interface CallableOp {
/** @returns Func */
public function getFunc();
}
|
Panalyzer/Panalyzer
|
src/getCFG/lib/PHPCfg/Op/CallableOp.php
|
PHP
|
mit
| 342
|
all:
g++ calcTempl.cpp -o calcTempl --std=c++11 -O2
|
mtrempoltsev/msu_cpp_autumn_2017
|
homework/Golenkov/07/Makefile
|
Makefile
|
mit
| 52
|
ABC ÆØÅ XYZ
|
fatso83/grunt-codekit
|
test/input/unicode_input.html
|
HTML
|
mit
| 15
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="Open Knowledge">
<meta name="description" content="The Global Open Data Index assesses the state of open government data around the world.
">
<meta name="keywords" content="Open Government, Open Data, Government Transparency, Open Knowledge
">
<meta property="og:type" content="website"/>
<meta property="og:title" content="Open Data Index - Open Knowledge"/>
<meta property="og:site_name" content="Open Data Index"/>
<meta property="og:description"
content="The Global Open Data Index assesses the state of open government data around the world."/>
<meta property="og:image" content="/static/images/favicon.ico"/>
<title>Albania | Global Open Data Index by Open Knowledge</title>
<base href="/">
<!--[if lt IE 9]>
<script src="/static/vendor/html5shiv.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="/static/css/site.css">
<link rel="icon" href="/static/images/favicon.ico">
<script>
var siteUrl = '';
</script>
</head>
<body class="na">
<div class="fixed-ok-panel">
<div id="ok-panel" class="closed">
<iframe src="http://assets.okfn.org/themes/okfn/okf-panel.html" scrolling="no"></iframe>
</div>
<a class="ok-ribbon"><img src="http://okfnlabs.org/ok-panel/assets/images/ok-ribbon.png" alt="Open Knowledge"></a>
</div>
<header id="header">
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<div>
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="logo">
<a href="/">
<img src="/static/images/logo2.png">
<span>Global<br/>Open Data Index</span>
</a>
</div>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav" style="margin-right: 132px;">
<li>
<a href="/place/" title="About the Open Data Index project">
Places
</a>
</li>
<li>
<a href="/dataset/" title="About the Open Data Index project">
Datasets
</a>
</li>
<li>
<a href="/download/" title="Download Open Data Index data">
Download
</a>
</li>
<li>
<a href="/insights/" title="Insights">
Insights
</a>
</li>
<li>
<a href="/methodology/"
title="The methodology behind the Open Data Index">
Methodology
</a>
</li>
<li>
<a href="/about/" title="About the Open Data Index project">
About
</a>
</li>
<li>
<a href="/press/"
title="Press information for the Open Data Index">
Press
</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
</header>
<div class="container">
<div class="content">
<div class="row">
<div class="col-md-12">
<ol class="breadcrumb">
<li>
<a href="/">Home</a>
</li>
<li class="active">Albania</li>
</ol>
<header class="page-header">
<h1>Albania</h1>
</header>
<h3>Sorry</h3>
<p>
There is no data available for Albania in the Index.
</p>
</div>
</div>
</div>
</div>
<footer id="footer">
<div class="container">
<div class="row">
<div class="footer-main col-md-8">
<div class="footer-attribution">
<p>
<a href="http://opendefinition.org/ossd/" title="Open Online Software Service">
<img src="http://assets.okfn.org/images/ok_buttons/os_80x15_orange_grey.png" alt=""
border=""/>
</a>
<a href="http://opendefinition.org/okd/" title="Open Online Software Service">
<img src="http://assets.okfn.org/images/ok_buttons/od_80x15_blue.png" alt="" border=""/>
</a>
<a href="http://opendefinition.org/okd/" title="Open Content">
<img src="http://assets.okfn.org/images/ok_buttons/oc_80x15_blue.png" alt="" border=""/>
</a>
–
<a href="http://creativecommons.org/licenses/by/3.0/"
title="Content Licensed under a CC Attribution"></a>
<a href="http://opendatacommons.org/licenses/pddl/1.0"
title="Data License (Public Domain)">Data License (Public
Domain)</a>
</p>
</div>
<div class="footer-meta">
<p>
This service is run by <a href="https://okfn.org/" title="Open Knowledge">Open Knowledge</a>
</p> <a class="naked" href="http://okfn.org/" title="Open Knowledge"><img
src="http://assets.okfn.org/p/okfn/img/okfn-logo-landscape-black-s.png" alt="" height="28"></a>
</div>
</div>
<div class="footer-links col-md-2">
<li><a href="http://okfn.org/" title="Open Knowledge">Open Knowledge</a></li>
<li><a href="http://okfn.org/opendata/" title="What is Open Data?">What is
Open Data?</a></li>
<li><a href="http://census.okfn.org/" title="Run your own Index">Run your
own Index</a></li>
<li><a href="https://github.com/okfn/opendataindex" title="The source code for Open Data Index">Source Code</a></li>
</div>
<div class="footer-links col-md-2">
<li><a href="/" title="Open Data Index home">Home</a></li>
<li><a href="/download/" title="Download data">Download</a></li>
<li><a href="/methodology/"
title="The methodology behind the Open Data Index">Methodology</a></li>
<li><a href="/faq/" title=" Open Data Index FAQ">FAQ</a></li>
<li><a href="/about/" title="About the Open Data Index">About</a></li>
<li><a href="/about/" title="Contact us">Contact</a></li>
<li><a href="/press/" title="Press">Press</a></li>
</div>
</div>
</div>
</footer>
<script data-main="/static/scripts/site" src="/static/scripts/require.js"></script>
</body>
</html>
|
okfn/opendataindex-2015
|
place/albania/2014/index.html
|
HTML
|
mit
| 8,038
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace WindowsService1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
|
protechdm/CompareCloudware
|
WindowsService1/Program.cs
|
C#
|
mit
| 556
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>FtpDelete</title>
<link rel="stylesheet" type="text/css" href="doc.css">
</head>
<body>
<h1>FtpDelete</h1>
<p>Removes a file from the remote system.</p>
<h2>SYNOPSIS</h2>
<pre>
#include <ftplib.h>
int FtpDelete(const char *fnm, netbuf *nControl);
</pre>
<h2>PARAMETERS</h2>
<dl>
<dt><b>fnm</b></dt>
<dd>The name of the file which is to be removed.</dd>
<dt><b>nControl</b></dt>
<dd>A handle returned by <a href="FtpConnect.html">FtpConnect()</a>.</dd>
</dl>
<h2>DESCRIPTION</h2>
<p>Requests that the server remove the specified file from the
remote file system.</p>
<h2>RETURN VALUE</h2>
<p>Returns 1 if successful or 0 on error.</p>
</body>
</html>
|
Mauricevb/FTPKit
|
Libraries/include/ftplib/html/FtpDelete.html
|
HTML
|
mit
| 727
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* A simple example demonstrating the use of subcommands.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
*/
// Include the Console_CommandLine package.
require_once 'Console/CommandLine.php';
// create the parser
$parser = new Console_CommandLine(array(
'description' => 'A great program that can foo and bar !',
'version' => '1.0.0'
));
// add a global option to make the program verbose
$parser->addOption('verbose', array(
'short_name' => '-v',
'long_name' => '--verbose',
'action' => 'StoreTrue',
'description' => 'turn on verbose output'
));
// add the foo subcommand
$foo_cmd = $parser->addCommand('foo', array(
'description' => 'output the given string with a foo prefix'
));
$foo_cmd->addOption('reverse', array(
'short_name' => '-r',
'long_name' => '--reverse',
'action' => 'StoreTrue',
'description' => 'reverse the given string before echoing it'
));
$foo_cmd->addArgument('text', array(
'description' => 'the text to output'
));
// add the bar subcommand with a "baz" alias
$bar_cmd = $parser->addCommand('bar', array(
'description' => 'output the given string with a bar prefix',
'aliases' => array('baz'),
));
$bar_cmd->addOption('reverse', array(
'short_name' => '-r',
'long_name' => '--reverse',
'action' => 'StoreTrue',
'description' => 'reverse the given string before echoing it'
));
$bar_cmd->addArgument('text', array(
'description' => 'the text to output'
));
// run the parser
try {
$result = $parser->parse();
if ($result->command_name) {
$st = $result->command->options['reverse']
? strrev($result->command->args['text'])
: $result->command->args['text'];
if ($result->command_name == 'foo') {
echo "Foo says: $st\n";
} else if ($result->command_name == 'bar') {
echo "Bar says: $st\n";
}
}
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>
|
georgehristov/EPESI
|
modules/CRM/Roundcube/RC/vendor/pear/console_commandline/docs/examples/ex3.php
|
PHP
|
mit
| 2,657
|
// 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.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Dictionary.
/// </summary>
public static partial class DictionaryExtensions
{
/// <summary>
/// Get complex types with dictionary property
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DictionaryWrapper GetValid(this IDictionary operations)
{
return operations.GetValidAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with dictionary property
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DictionaryWrapper> GetValidAsync(this IDictionary operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with dictionary property
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='defaultProgram'>
/// </param>
public static void PutValid(this IDictionary operations, IDictionary<string, string> defaultProgram = default(IDictionary<string, string>))
{
operations.PutValidAsync(defaultProgram).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with dictionary property
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='defaultProgram'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutValidAsync(this IDictionary operations, IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutValidWithHttpMessagesAsync(defaultProgram, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with dictionary property which is empty
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DictionaryWrapper GetEmpty(this IDictionary operations)
{
return operations.GetEmptyAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with dictionary property which is empty
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DictionaryWrapper> GetEmptyAsync(this IDictionary operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetEmptyWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with dictionary property which is empty
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='defaultProgram'>
/// </param>
public static void PutEmpty(this IDictionary operations, IDictionary<string, string> defaultProgram = default(IDictionary<string, string>))
{
operations.PutEmptyAsync(defaultProgram).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with dictionary property which is empty
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='defaultProgram'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutEmptyAsync(this IDictionary operations, IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutEmptyWithHttpMessagesAsync(defaultProgram, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with dictionary property which is null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DictionaryWrapper GetNull(this IDictionary operations)
{
return operations.GetNullAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with dictionary property which is null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DictionaryWrapper> GetNullAsync(this IDictionary operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get complex types with dictionary property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DictionaryWrapper GetNotProvided(this IDictionary operations)
{
return operations.GetNotProvidedAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with dictionary property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DictionaryWrapper> GetNotProvidedAsync(this IDictionary operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNotProvidedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
|
matthchr/autorest
|
src/generator/AutoRest.CSharp.Tests/Expected/AcceptanceTests/BodyComplex/DictionaryExtensions.cs
|
C#
|
mit
| 8,434
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// type_traits
// member_object_pointer
#include <type_traits>
template <class T>
void test_member_object_pointer_imp()
{
static_assert(!std::is_void<T>::value, "");
static_assert(!std::is_integral<T>::value, "");
static_assert(!std::is_floating_point<T>::value, "");
static_assert(!std::is_array<T>::value, "");
static_assert(!std::is_pointer<T>::value, "");
static_assert(!std::is_lvalue_reference<T>::value, "");
static_assert(!std::is_rvalue_reference<T>::value, "");
static_assert( std::is_member_object_pointer<T>::value, "");
static_assert(!std::is_member_function_pointer<T>::value, "");
static_assert(!std::is_enum<T>::value, "");
static_assert(!std::is_union<T>::value, "");
static_assert(!std::is_class<T>::value, "");
static_assert(!std::is_function<T>::value, "");
}
template <class T>
void test_member_object_pointer()
{
test_member_object_pointer_imp<T>();
test_member_object_pointer_imp<const T>();
test_member_object_pointer_imp<volatile T>();
test_member_object_pointer_imp<const volatile T>();
}
class Class
{
};
int main()
{
test_member_object_pointer<int Class::*>();
}
|
lunastorm/wissbi
|
3rd_party/libcxx/test/utilities/meta/meta.unary/meta.unary.cat/member_object_pointer.pass.cpp
|
C++
|
mit
| 1,526
|
require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
RSpec.describe BusinessesController, :type => :controller do
# This should return the minimal set of attributes required to create a valid
# Business. As you add validations to Business, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}
let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# BusinessesController. Be sure to keep this updated too.
let(:valid_session) { {} }
describe "GET index" do
it "assigns all businesses as @businesses" do
business = Business.create! valid_attributes
get :index, {}, valid_session
expect(assigns(:businesses)).to eq([business])
end
end
describe "GET show" do
it "assigns the requested business as @business" do
business = Business.create! valid_attributes
get :show, {:id => business.to_param}, valid_session
expect(assigns(:business)).to eq(business)
end
end
describe "GET new" do
it "assigns a new business as @business" do
get :new, {}, valid_session
expect(assigns(:business)).to be_a_new(Business)
end
end
describe "GET edit" do
it "assigns the requested business as @business" do
business = Business.create! valid_attributes
get :edit, {:id => business.to_param}, valid_session
expect(assigns(:business)).to eq(business)
end
end
describe "POST create" do
describe "with valid params" do
it "creates a new Business" do
expect {
post :create, {:business => valid_attributes}, valid_session
}.to change(Business, :count).by(1)
end
it "assigns a newly created business as @business" do
post :create, {:business => valid_attributes}, valid_session
expect(assigns(:business)).to be_a(Business)
expect(assigns(:business)).to be_persisted
end
it "redirects to the created business" do
post :create, {:business => valid_attributes}, valid_session
expect(response).to redirect_to(Business.last)
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved business as @business" do
post :create, {:business => invalid_attributes}, valid_session
expect(assigns(:business)).to be_a_new(Business)
end
it "re-renders the 'new' template" do
post :create, {:business => invalid_attributes}, valid_session
expect(response).to render_template("new")
end
end
end
describe "PUT update" do
describe "with valid params" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested business" do
business = Business.create! valid_attributes
put :update, {:id => business.to_param, :business => new_attributes}, valid_session
business.reload
skip("Add assertions for updated state")
end
it "assigns the requested business as @business" do
business = Business.create! valid_attributes
put :update, {:id => business.to_param, :business => valid_attributes}, valid_session
expect(assigns(:business)).to eq(business)
end
it "redirects to the business" do
business = Business.create! valid_attributes
put :update, {:id => business.to_param, :business => valid_attributes}, valid_session
expect(response).to redirect_to(business)
end
end
describe "with invalid params" do
it "assigns the business as @business" do
business = Business.create! valid_attributes
put :update, {:id => business.to_param, :business => invalid_attributes}, valid_session
expect(assigns(:business)).to eq(business)
end
it "re-renders the 'edit' template" do
business = Business.create! valid_attributes
put :update, {:id => business.to_param, :business => invalid_attributes}, valid_session
expect(response).to render_template("edit")
end
end
end
describe "DELETE destroy" do
it "destroys the requested business" do
business = Business.create! valid_attributes
expect {
delete :destroy, {:id => business.to_param}, valid_session
}.to change(Business, :count).by(-1)
end
it "redirects to the businesses list" do
business = Business.create! valid_attributes
delete :destroy, {:id => business.to_param}, valid_session
expect(response).to redirect_to(businesses_url)
end
end
end
|
behnaaz/rails-devise-tutorial
|
spec/controllers/businesses_controller_spec.rb
|
Ruby
|
mit
| 5,773
|
"""
A library of useful helper classes to the saxlib classes, for the
convenience of application and driver writers.
$Id: saxutils.py,v 1.19 2001/03/20 07:19:46 loewis Exp $
"""
import types, sys, urllib, urlparse, os, string
import handler, _exceptions, xmlreader
try:
_StringTypes = [types.StringType, types.UnicodeType]
except AttributeError: # 1.5 compatibility:UnicodeType not defined
_StringTypes = [types.StringType]
def escape(data, entities={}):
"""Escape &, <, and > in a string of data.
You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
data = string.replace(data, "&", "&")
data = string.replace(data, "<", "<")
data = string.replace(data, ">", ">")
for chars, entity in entities.items():
data = string.replace(data, chars, entity)
return data
# --- DefaultHandler
class DefaultHandler(handler.EntityResolver, handler.DTDHandler,
handler.ContentHandler, handler.ErrorHandler):
"""Default base class for SAX2 event handlers. Implements empty
methods for all callback methods, which can be overridden by
application implementors. Replaces the deprecated SAX1 HandlerBase
class."""
# --- Location
class Location:
"""Represents a location in an XML entity. Initialized by being passed
a locator, from which it reads off the current location, which is then
stored internally."""
def __init__(self, locator):
self.__col = locator.getColumnNumber()
self.__line = locator.getLineNumber()
self.__pubid = locator.getPublicId()
self.__sysid = locator.getSystemId()
def getColumnNumber(self):
return self.__col
def getLineNumber(self):
return self.__line
def getPublicId(self):
return self.__pubid
def getSystemId(self):
return self.__sysid
# --- ErrorPrinter
class ErrorPrinter:
"A simple class that just prints error messages to standard out."
def __init__(self, level=0, outfile=sys.stderr):
self._level = level
self._outfile = outfile
def warning(self, exception):
if self._level <= 0:
self._outfile.write("WARNING in %s: %s\n" %
(self.__getpos(exception),
exception.getMessage()))
def error(self, exception):
if self._level <= 1:
self._outfile.write("ERROR in %s: %s\n" %
(self.__getpos(exception),
exception.getMessage()))
def fatalError(self, exception):
if self._level <= 2:
self._outfile.write("FATAL ERROR in %s: %s\n" %
(self.__getpos(exception),
exception.getMessage()))
def __getpos(self, exception):
if isinstance(exception, _exceptions.SAXParseException):
return "%s:%s:%s" % (exception.getSystemId(),
exception.getLineNumber(),
exception.getColumnNumber())
else:
return "<unknown>"
# --- ErrorRaiser
class ErrorRaiser:
"A simple class that just raises the exceptions it is passed."
def __init__(self, level = 0):
self._level = level
def error(self, exception):
if self._level <= 1:
raise exception
def fatalError(self, exception):
if self._level <= 2:
raise exception
def warning(self, exception):
if self._level <= 0:
raise exception
# --- AttributesImpl now lives in xmlreader
from xmlreader import AttributesImpl
# --- XMLGenerator is the SAX2 ContentHandler for writing back XML
try:
import codecs
def _outputwrapper(stream,encoding):
writerclass = codecs.lookup(encoding)[3]
return writerclass(stream)
except ImportError: # 1.5 compatibility: fall back to do-nothing
def _outputwrapper(stream,encoding):
return stream
class XMLGenerator(handler.ContentHandler):
def __init__(self, out=None, encoding="iso-8859-1"):
if out is None:
import sys
out = sys.stdout
handler.ContentHandler.__init__(self)
self._out = _outputwrapper(out,encoding)
self._ns_contexts = [{}] # contains uri -> prefix dicts
self._current_context = self._ns_contexts[-1]
self._undeclared_ns_maps = []
self._encoding = encoding
# ContentHandler methods
def startDocument(self):
self._out.write('<?xml version="1.0" encoding="%s"?>\n' %
self._encoding)
def startPrefixMapping(self, prefix, uri):
self._ns_contexts.append(self._current_context.copy())
self._current_context[uri] = prefix
self._undeclared_ns_maps.append((prefix, uri))
def endPrefixMapping(self, prefix):
self._current_context = self._ns_contexts[-1]
del self._ns_contexts[-1]
def startElement(self, name, attrs):
self._out.write('<' + name)
for (name, value) in attrs.items():
self._out.write(' %s="%s"' % (name, escape(value)))
self._out.write('>')
def endElement(self, name):
self._out.write('</%s>' % name)
def startElementNS(self, name, qname, attrs):
if name[0] is None:
name = name[1]
elif self._current_context[name[0]] is None:
# default namespace
name = name[1]
else:
name = self._current_context[name[0]] + ":" + name[1]
self._out.write('<' + name)
for k,v in self._undeclared_ns_maps:
if k is None:
self._out.write(' xmlns="%s"' % v)
else:
self._out.write(' xmlns:%s="%s"' % (k,v))
self._undeclared_ns_maps = []
for (name, value) in attrs.items():
name = self._current_context[name[0]] + ":" + name[1]
self._out.write(' %s="%s"' % (name, escape(value)))
self._out.write('>')
def endElementNS(self, name, qname):
# XXX: if qname is not None, we better use it.
# Python 2.0b2 requires us to use the recorded prefix for
# name[0], though
if name[0] is None:
qname = name[1]
elif self._current_context[name[0]] is None:
qname = name[1]
else:
qname = self._current_context[name[0]] + ":" + name[1]
self._out.write('</%s>' % qname)
def characters(self, content):
self._out.write(escape(content))
def ignorableWhitespace(self, content):
self._out.write(content)
def processingInstruction(self, target, data):
self._out.write('<?%s %s?>' % (target, data))
# --- ContentGenerator is the SAX1 DocumentHandler for writing back XML
class ContentGenerator(XMLGenerator):
def characters(self, str, start, end):
# In SAX1, characters receives start and end; in SAX2, it receives
# a string. For plain strings, we may want to use a buffer object.
return XMLGenerator.characters(self, str[start:start+end])
# --- XMLFilterImpl
class XMLFilterBase(xmlreader.XMLReader):
"""This class is designed to sit between an XMLReader and the
client application's event handlers. By default, it does nothing
but pass requests up to the reader and events on to the handlers
unmodified, but subclasses can override specific methods to modify
the event stream or the configuration requests as they pass
through."""
# ErrorHandler methods
def error(self, exception):
self._err_handler.error(exception)
def fatalError(self, exception):
self._err_handler.fatalError(exception)
def warning(self, exception):
self._err_handler.warning(exception)
# ContentHandler methods
def setDocumentLocator(self, locator):
self._cont_handler.setDocumentLocator(locator)
def startDocument(self):
self._cont_handler.startDocument()
def endDocument(self):
self._cont_handler.endDocument()
def startPrefixMapping(self, prefix, uri):
self._cont_handler.startPrefixMapping(prefix, uri)
def endPrefixMapping(self, prefix):
self._cont_handler.endPrefixMapping(prefix)
def startElement(self, name, attrs):
self._cont_handler.startElement(name, attrs)
def endElement(self, name):
self._cont_handler.endElement(name)
def startElementNS(self, name, qname, attrs):
self._cont_handler.startElementNS(name, qname, attrs)
def endElementNS(self, name, qname):
self._cont_handler.endElementNS(name, qname)
def characters(self, content):
self._cont_handler.characters(content)
def ignorableWhitespace(self, chars):
self._cont_handler.ignorableWhitespace(chars)
def processingInstruction(self, target, data):
self._cont_handler.processingInstruction(target, data)
def skippedEntity(self, name):
self._cont_handler.skippedEntity(name)
# DTDHandler methods
def notationDecl(self, name, publicId, systemId):
self._dtd_handler.notationDecl(name, publicId, systemId)
def unparsedEntityDecl(self, name, publicId, systemId, ndata):
self._dtd_handler.unparsedEntityDecl(name, publicId, systemId, ndata)
# EntityResolver methods
def resolveEntity(self, publicId, systemId):
self._ent_handler.resolveEntity(publicId, systemId)
# XMLReader methods
def parse(self, source):
self._parent.setContentHandler(self)
self._parent.setErrorHandler(self)
self._parent.setEntityResolver(self)
self._parent.setDTDHandler(self)
self._parent.parse(source)
def setLocale(self, locale):
self._parent.setLocale(locale)
def getFeature(self, name):
return self._parent.getFeature(name)
def setFeature(self, name, state):
self._parent.setFeature(name, state)
def getProperty(self, name):
return self._parent.getProperty(name)
def setProperty(self, name, value):
self._parent.setProperty(name, value)
# FIXME: remove this backward compatibility hack when not needed anymore
XMLFilterImpl = XMLFilterBase
# --- BaseIncrementalParser
class BaseIncrementalParser(xmlreader.IncrementalParser):
"""This class implements the parse method of the XMLReader
interface using the feed, close and reset methods of the
IncrementalParser interface as a convenience to SAX 2.0 driver
writers."""
def parse(self, source):
source = prepare_input_source(source)
self.prepareParser(source)
self._cont_handler.startDocument()
# FIXME: what about char-stream?
inf = source.getByteStream()
buffer = inf.read(16384)
while buffer != "":
self.feed(buffer)
buffer = inf.read(16384)
self.close()
self.reset()
self._cont_handler.endDocument()
def prepareParser(self, source):
"""This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing."""
raise NotImplementedError("prepareParser must be overridden!")
# --- Utility functions
def prepare_input_source(source, base = ""):
"""This function takes an InputSource and an optional base URL and
returns a fully resolved InputSource object ready for reading."""
if type(source) in _StringTypes:
source = xmlreader.InputSource(source)
elif hasattr(source, "read"):
f = source
source = xmlreader.InputSource()
source.setByteStream(f)
if hasattr(f, "name"):
source.setSystemId(f.name)
if source.getByteStream() is None:
sysid = source.getSystemId()
if os.path.isfile(sysid):
basehead = os.path.split(os.path.normpath(base))[0]
source.setSystemId(os.path.join(basehead, sysid))
f = open(sysid, "rb")
else:
source.setSystemId(urlparse.urljoin(base, sysid))
f = urllib.urlopen(source.getSystemId())
source.setByteStream(f)
return source
# ===========================================================================
#
# DEPRECATED SAX 1.0 CLASSES
#
# ===========================================================================
# --- AttributeMap
class AttributeMap:
"""An implementation of AttributeList that takes an (attr,val) hash
and uses it to implement the AttributeList interface."""
def __init__(self, map):
self.map=map
def getLength(self):
return len(self.map.keys())
def getName(self, i):
try:
return self.map.keys()[i]
except IndexError,e:
return None
def getType(self, i):
return "CDATA"
def getValue(self, i):
try:
if type(i)==types.IntType:
return self.map[self.getName(i)]
else:
return self.map[i]
except KeyError,e:
return None
def __len__(self):
return len(self.map)
def __getitem__(self, key):
if type(key)==types.IntType:
return self.map.keys()[key]
else:
return self.map[key]
def items(self):
return self.map.items()
def keys(self):
return self.map.keys()
def has_key(self,key):
return self.map.has_key(key)
def get(self, key, alternative=None):
return self.map.get(key, alternative)
def copy(self):
return AttributeMap(self.map.copy())
def values(self):
return self.map.values()
# --- Event broadcasting object
class EventBroadcaster:
"""Takes a list of objects and forwards any method calls received
to all objects in the list. The attribute list holds the list and
can freely be modified by clients."""
class Event:
"Helper objects that represent event methods."
def __init__(self,list,name):
self.list=list
self.name=name
def __call__(self,*rest):
for obj in self.list:
apply(getattr(obj,self.name), rest)
def __init__(self,list):
self.list=list
def __getattr__(self,name):
return self.Event(self.list,name)
def __repr__(self):
return "<EventBroadcaster instance at %d>" % id(self)
# --- ESIS document handler
import saxlib
class ESISDocHandler(saxlib.HandlerBase):
"A SAX document handler that produces naive ESIS output."
def __init__(self,writer=sys.stdout):
self.writer=writer
def processingInstruction (self,target, remainder):
"""Receive an event signalling that a processing instruction
has been found."""
self.writer.write("?"+target+" "+remainder+"\n")
def startElement(self,name,amap):
"Receive an event signalling the start of an element."
self.writer.write("("+name+"\n")
for a_name in amap.keys():
self.writer.write("A"+a_name+" "+amap[a_name]+"\n")
def endElement(self,name):
"Receive an event signalling the end of an element."
self.writer.write(")"+name+"\n")
def characters(self,data,start_ix,length):
"Receive an event signalling that character data has been found."
self.writer.write("-"+data[start_ix:start_ix+length]+"\n")
# --- XML canonizer
class Canonizer(saxlib.HandlerBase):
"A SAX document handler that produces canonized XML output."
def __init__(self,writer=sys.stdout):
self.elem_level=0
self.writer=writer
def processingInstruction (self,target, remainder):
if not target=="xml":
self.writer.write("<?"+target+" "+remainder+"?>")
def startElement(self,name,amap):
self.writer.write("<"+name)
a_names=amap.keys()
a_names.sort()
for a_name in a_names:
self.writer.write(" "+a_name+"=\"")
self.write_data(amap[a_name])
self.writer.write("\"")
self.writer.write(">")
self.elem_level=self.elem_level+1
def endElement(self,name):
self.writer.write("</"+name+">")
self.elem_level=self.elem_level-1
def ignorableWhitespace(self,data,start_ix,length):
self.characters(data,start_ix,length)
def characters(self,data,start_ix,length):
if self.elem_level>0:
self.write_data(data[start_ix:start_ix+length])
def write_data(self,data):
"Writes datachars to writer."
data=string.replace(data,"&","&")
data=string.replace(data,"<","<")
data=string.replace(data,"\"",""")
data=string.replace(data,">",">")
data=string.replace(data,chr(9),"	")
data=string.replace(data,chr(10)," ")
data=string.replace(data,chr(13)," ")
self.writer.write(data)
# --- mllib
class mllib:
"""A re-implementation of the htmllib, sgmllib and xmllib interfaces as a
SAX DocumentHandler."""
# Unsupported:
# - setnomoretags
# - setliteral
# - translate_references
# - handle_xml
# - handle_doctype
# - handle_charref
# - handle_entityref
# - handle_comment
# - handle_cdata
# - tag_attributes
def __init__(self):
self.reset()
def reset(self):
import saxexts # only used here
self.parser=saxexts.XMLParserFactory.make_parser()
self.handler=mllib.Handler(self.parser,self)
self.handler.reset()
def feed(self,data):
self.parser.feed(data)
def close(self):
self.parser.close()
def get_stack(self):
return self.handler.get_stack()
# --- Handler methods (to be overridden)
def handle_starttag(self,name,method,atts):
method(atts)
def handle_endtag(self,name,method):
method()
def handle_data(self,data):
pass
def handle_proc(self,target,data):
pass
def unknown_starttag(self,name,atts):
pass
def unknown_endtag(self,name):
pass
def syntax_error(self,message):
pass
# --- The internal handler class
class Handler(saxlib.DocumentHandler,saxlib.ErrorHandler):
"""An internal class to handle SAX events and translate them to mllib
events."""
def __init__(self,driver,handler):
self.driver=driver
self.driver.setDocumentHandler(self)
self.driver.setErrorHandler(self)
self.handler=handler
self.reset()
def get_stack(self):
return self.stack
def reset(self):
self.stack=[]
# --- DocumentHandler methods
def characters(self, ch, start, length):
self.handler.handle_data(ch[start:start+length])
def endElement(self, name):
if hasattr(self.handler,"end_"+name):
self.handler.handle_endtag(name,
getattr(self.handler,"end_"+name))
else:
self.handler.unknown_endtag(name)
del self.stack[-1]
def ignorableWhitespace(self, ch, start, length):
self.handler.handle_data(ch[start:start+length])
def processingInstruction(self, target, data):
self.handler.handle_proc(target,data)
def startElement(self, name, atts):
self.stack.append(name)
if hasattr(self.handler,"start_"+name):
self.handler.handle_starttag(name,
getattr(self.handler,
"start_"+name),
atts)
else:
self.handler.unknown_starttag(name,atts)
# --- ErrorHandler methods
def error(self, exception):
self.handler.syntax_error(str(exception))
def fatalError(self, exception):
raise RuntimeError(str(exception))
|
Integral-Technology-Solutions/ConfigNOW
|
Lib/xml/sax/saxutils.py
|
Python
|
mit
| 20,106
|
#if defined(PEGASUS_OS_HPUX)
# include "UNIX_DatabaseSystemPrivate_HPUX.h"
#elif defined(PEGASUS_OS_LINUX)
# include "UNIX_DatabaseSystemPrivate_LINUX.h"
#elif defined(PEGASUS_OS_DARWIN)
# include "UNIX_DatabaseSystemPrivate_DARWIN.h"
#elif defined(PEGASUS_OS_AIX)
# include "UNIX_DatabaseSystemPrivate_AIX.h"
#elif defined(PEGASUS_OS_FREEBSD)
# include "UNIX_DatabaseSystemPrivate_FREEBSD.h"
#elif defined(PEGASUS_OS_SOLARIS)
# include "UNIX_DatabaseSystemPrivate_SOLARIS.h"
#elif defined(PEGASUS_OS_ZOS)
# include "UNIX_DatabaseSystemPrivate_ZOS.h"
#elif defined(PEGASUS_OS_VMS)
# include "UNIX_DatabaseSystemPrivate_VMS.h"
#elif defined(PEGASUS_OS_TRU64)
# include "UNIX_DatabaseSystemPrivate_TRU64.h"
#else
# include "UNIX_DatabaseSystemPrivate_STUB.h"
#endif
|
brunolauze/openpegasus-providers-old
|
src/Providers/UNIXProviders/DatabaseSystem/UNIX_DatabaseSystemPrivate.h
|
C
|
mit
| 765
|
var exports = module.exports;
exports.setup = function(callback) {
var write = process.stdout.write;
process.stdout.write = (function(stub) {
return function(string, encoding, fd) {
stub.apply(process.stdout, arguments);
callback(string, encoding, fd);
};
})(process.stdout.write);
return function() {
process.stdout.write = write;
};
};
|
Aconex/drakov
|
test/lib/stdout-hook.js
|
JavaScript
|
mit
| 410
|
//
// KPCAASaturnMoons.h
// SwiftAA
//
// Created by Cédric Foellmi on 10/07/15.
// Licensed under the MIT License (see LICENSE file)
//
#import <Foundation/Foundation.h>
#import "KPCAA3DCoordinate.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct KPCAASaturnMoonDetails {
KPCAA3DCoordinateComponents TrueRectangularCoordinateComponents;
KPCAA3DCoordinateComponents ApparentRectangularCoordinateComponents;
BOOL inTransit;
BOOL inOccultation;
BOOL inEclipse;
BOOL inShadowTransit;
} KPCAASaturnMoonDetails;
typedef struct KPCAASaturnMoonsDetails {
KPCAASaturnMoonDetails Satellite1;
KPCAASaturnMoonDetails Satellite2;
KPCAASaturnMoonDetails Satellite3;
KPCAASaturnMoonDetails Satellite4;
KPCAASaturnMoonDetails Satellite5;
KPCAASaturnMoonDetails Satellite6;
KPCAASaturnMoonDetails Satellite7;
KPCAASaturnMoonDetails Satellite8;
} KPCAASaturnMoonsDetails;
KPCAASaturnMoonsDetails KPCAASaturnMoonsDetails_Calculate(double JD, BOOL highPrecision);
#if __cplusplus
}
#endif
|
onekiloparsec/SwiftAA
|
Sources/ObjCAA/include/KPCAASaturnMoons.h
|
C
|
mit
| 1,045
|
import React from 'react'
class Shortest extends React.Component {
render() {
return (
<div>Shortest</div>
)
}
}
export default Shortest
|
hyy1115/react-redux-webpack2
|
src/pages/dynamic/Shortest/Shortest.js
|
JavaScript
|
mit
| 154
|
<?php
$eZTranslationCacheCodeDate = 1058863428;
$CacheInfo = array (
'charset' => 'utf-8',
);
$TranslationInfo = array (
'context' => 'kernel/workflow/edit',
);
$TranslationRoot = array (
'5c8f4bf6d3b395c887af90a424851f3e' =>
array (
'context' => 'kernel/workflow/edit',
'source' => 'New Workflow',
'comment' => NULL,
'translation' => 'Nuovo Workflow',
'key' => '5c8f4bf6d3b395c887af90a424851f3e',
),
);
?>
|
SnceGroup/snce-website
|
web/var/ezdemo_site/cache/translation/7ea3246ce3f3b0d74450a358f0d52a8c/ita-IT/0a3ffcb24aaf53d2768e6ec4e5e87de2.php
|
PHP
|
mit
| 440
|
using System;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime
{
internal sealed class GrainTimer : IGrainTimer
{
private Func<object, Task> asyncCallback;
private AsyncTaskSafeTimer timer;
private readonly TimeSpan dueTime;
private readonly TimeSpan timerFrequency;
private DateTime previousTickTime;
private int totalNumTicks;
private readonly ILogger logger;
private volatile Task currentlyExecutingTickTask;
private object currentlyExecutingTickTaskLock = new();
private readonly IGrainContext grainContext;
public string Name { get; }
private bool TimerAlreadyStopped { get { return timer == null || asyncCallback == null; } }
private GrainTimer(IGrainContext activationData, ILogger logger, Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period, string name)
{
var ctxt = RuntimeContext.Current;
if (ctxt is null)
{
throw new InvalidSchedulingContextException(
"Current grain context is null. "
+ "Please make sure you are not trying to create a Timer from outside Orleans Task Scheduler, "
+ "which will be the case if you create it inside Task.Run.");
}
this.grainContext = activationData;
this.logger = logger;
this.Name = name;
this.asyncCallback = asyncCallback;
timer = new AsyncTaskSafeTimer(logger,
stateObj => TimerTick(stateObj, ctxt),
state);
this.dueTime = dueTime;
timerFrequency = period;
previousTickTime = DateTime.UtcNow;
totalNumTicks = 0;
}
internal static IGrainTimer FromTaskCallback(
ILogger logger,
Func<object, Task> asyncCallback,
object state,
TimeSpan dueTime,
TimeSpan period,
string name = null,
IGrainContext activationData = null)
{
return new GrainTimer(activationData, logger, asyncCallback, state, dueTime, period, name);
}
public void Start()
{
if (TimerAlreadyStopped)
throw new ObjectDisposedException(String.Format("The timer {0} was already disposed.", GetFullName()));
timer.Start(dueTime, timerFrequency);
}
public void Stop()
{
asyncCallback = null;
}
private async Task TimerTick(object state, IGrainContext context)
{
if (TimerAlreadyStopped)
return;
try
{
// Schedule call back to grain context
await context.QueueNamedTask(() => ForwardToAsyncCallback(state), this.Name);
}
catch (InvalidSchedulingContextException exc)
{
logger.Error(ErrorCode.Timer_InvalidContext,
string.Format("Caught an InvalidSchedulingContextException on timer {0}, context is {1}. Going to dispose this timer!",
GetFullName(), context), exc);
DisposeTimer();
}
}
private async Task ForwardToAsyncCallback(object state)
{
// AsyncSafeTimer ensures that calls to this method are serialized.
if (TimerAlreadyStopped) return;
try
{
RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake.
lock (this.currentlyExecutingTickTaskLock)
{
if (TimerAlreadyStopped) return;
totalNumTicks++;
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace(ErrorCode.TimerBeforeCallback, "About to make timer callback for timer {0}", GetFullName());
currentlyExecutingTickTask = asyncCallback(state);
}
await currentlyExecutingTickTask;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerAfterCallback, "Completed timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Error(
ErrorCode.Timer_GrainTimerCallbackError,
string.Format( "Caught and ignored exception: {0} with message: {1} thrown from timer callback {2}",
exc.GetType(),
exc.Message,
GetFullName()),
exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
currentlyExecutingTickTask = null;
// if this is not a repeating timer, then we can
// dispose of the timer.
if (timerFrequency == Constants.INFINITE_TIMESPAN)
DisposeTimer();
}
}
public Task GetCurrentlyExecutingTickTask()
{
return currentlyExecutingTickTask ?? Task.CompletedTask;
}
private string GetFullName()
{
var callback = asyncCallback;
var callbackTarget = callback?.Target?.ToString() ?? string.Empty;
var callbackMethodInfo = callback?.GetMethodInfo()?.ToString() ?? string.Empty;
return $"GrainTimer.{this.Name ?? string.Empty} TimerCallbackHandler:{callbackTarget ?? string.Empty}->{callbackMethodInfo ?? string.Empty}";
}
// The reason we need to check CheckTimerFreeze on both the SafeTimer and this GrainTimer
// is that SafeTimer may tick OK (no starvation by .NET thread pool), but then scheduler.QueueWorkItem
// may not execute and starve this GrainTimer callback.
public bool CheckTimerFreeze(DateTime lastCheckTime)
{
if (TimerAlreadyStopped) return true;
// check underlying SafeTimer (checking that .NET thread pool does not starve this timer)
if (!timer.CheckTimerFreeze(lastCheckTime, () => Name)) return false;
// if SafeTimer failed the check, no need to check GrainTimer too, since it will fail as well.
// check myself (checking that scheduler.QueueWorkItem does not starve this timer)
return SafeTimerBase.CheckTimerDelay(previousTickTime, totalNumTicks,
dueTime, timerFrequency, logger, GetFullName, ErrorCode.Timer_TimerInsideGrainIsNotTicking, true);
}
public bool CheckTimerDelay()
{
return SafeTimerBase.CheckTimerDelay(previousTickTime, totalNumTicks,
dueTime, timerFrequency, logger, GetFullName, ErrorCode.Timer_TimerInsideGrainIsNotTicking, false);
}
public void Dispose()
{
DisposeTimer();
asyncCallback = null;
}
private void DisposeTimer()
{
var tmp = timer;
if (tmp == null) return;
Utils.SafeExecute(tmp.Dispose);
timer = null;
lock (this.currentlyExecutingTickTaskLock)
{
asyncCallback = null;
}
grainContext?.GetComponent<IGrainTimerRegistry>().OnTimerDisposed(this);
}
}
}
|
jthelin/orleans
|
src/Orleans.Runtime/Timers/GrainTimer.cs
|
C#
|
mit
| 7,570
|
{-
--Task 4
--power x*y =
--if x*y==0
--then 0
--else if (x*y) != 0
--then x+(x*(y-1))
--These are home tasks
--bb bmi
--| bmi <= 10 ="a"
--| bmi <= 5 = "b"
--| otherwise = bmi
slope (x1,y1) (x2,y2) = dy / dx
where dy = y2-y1
dx = x2 - x1
--Task 2
reci x = 1/x;
--Task 3
--abst x
--Task 4
sign x
| x<0 = -1
| x>0 = 1
| x==0 = 0
|otherwise = 0
signNum x =
if x>0
then 1
else if x<0
then -1
else 0
--Task 5
threeDifferent x y z
| x==y && y==z && x==z = True
| otherwise = False
--Task 6
maxofThree x y z
| x>y && x>z = x
| y>x && y>z = y
| otherwise = z
--Task 7
numString x
| x==1 ="One"
| x==2 ="Two"
| x==3 ="Three"
| x==4 ="Four"
| x==5 ="Five"
| otherwise = "Your input in not less than 6 "
(!) _ True = True
(!) True _ = True
--This is fibnanci funciton
fib:: Int -> Int
fib 0 = 1
fib 1 = 1
fib x = fib(x-1) + fib(x-2)
charName ::Char -> String
charName 'a' = "Albert"
charName 'b' = "Broseph"
cahrName 'c' = "Cecil"
-}
|
badarshahzad/Learn-Haskell
|
week 2 & 3/function.hs
|
Haskell
|
mit
| 974
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.ComponentModel;
namespace Azure.Search.Documents.Indexes.Models
{
/// <summary> Defines the type of a datasource. </summary>
public readonly partial struct SearchIndexerDataSourceType : IEquatable<SearchIndexerDataSourceType>
{
private readonly string _value;
/// <summary> Determines if two <see cref="SearchIndexerDataSourceType"/> values are the same. </summary>
/// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
public SearchIndexerDataSourceType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
private const string AzureSqlValue = "azuresql";
private const string CosmosDbValue = "cosmosdb";
private const string AzureBlobValue = "azureblob";
private const string AzureTableValue = "azuretable";
private const string MySqlValue = "mysql";
private const string AdlsGen2Value = "adlsgen2";
/// <summary> Indicates an Azure SQL datasource. </summary>
public static SearchIndexerDataSourceType AzureSql { get; } = new SearchIndexerDataSourceType(AzureSqlValue);
/// <summary> Indicates a CosmosDB datasource. </summary>
public static SearchIndexerDataSourceType CosmosDb { get; } = new SearchIndexerDataSourceType(CosmosDbValue);
/// <summary> Indicates an Azure Blob datasource. </summary>
public static SearchIndexerDataSourceType AzureBlob { get; } = new SearchIndexerDataSourceType(AzureBlobValue);
/// <summary> Indicates an Azure Table datasource. </summary>
public static SearchIndexerDataSourceType AzureTable { get; } = new SearchIndexerDataSourceType(AzureTableValue);
/// <summary> Indicates a MySql datasource. </summary>
public static SearchIndexerDataSourceType MySql { get; } = new SearchIndexerDataSourceType(MySqlValue);
/// <summary> Indicates an ADLS Gen2 datasource. </summary>
public static SearchIndexerDataSourceType AdlsGen2 { get; } = new SearchIndexerDataSourceType(AdlsGen2Value);
/// <summary> Determines if two <see cref="SearchIndexerDataSourceType"/> values are the same. </summary>
public static bool operator ==(SearchIndexerDataSourceType left, SearchIndexerDataSourceType right) => left.Equals(right);
/// <summary> Determines if two <see cref="SearchIndexerDataSourceType"/> values are not the same. </summary>
public static bool operator !=(SearchIndexerDataSourceType left, SearchIndexerDataSourceType right) => !left.Equals(right);
/// <summary> Converts a string to a <see cref="SearchIndexerDataSourceType"/>. </summary>
public static implicit operator SearchIndexerDataSourceType(string value) => new SearchIndexerDataSourceType(value);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is SearchIndexerDataSourceType other && Equals(other);
/// <inheritdoc />
public bool Equals(SearchIndexerDataSourceType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc />
public override string ToString() => _value;
}
}
|
jackmagic313/azure-sdk-for-net
|
sdk/search/Azure.Search.Documents/src/Generated/Models/SearchIndexerDataSourceType.cs
|
C#
|
mit
| 3,600
|
# hikers_sequiahack15
|
himadrisj/hikers_sequiahack15
|
README.md
|
Markdown
|
mit
| 23
|
<?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup Timeline Timeline
* @ingroup UnaModules
*
* @{
*/
class BxTimelineSearchResult extends BxBaseModNotificationsSearchResult
{
function __construct($sMode = '', $aParams = array())
{
parent::__construct($sMode, $aParams);
$this->aCurrent = array(
'name' => 'bx_timeline',
'module_name' => 'bx_timeline',
'object_metatags' => 'bx_timeline',
'title' => _t('_bx_timeline_page_title_browse'),
'table' => 'bx_timeline_events',
'ownFields' => array('id', 'owner_id', 'type', 'action', 'object_id', 'object_privacy_view', 'content', 'title', 'description', 'views', 'rate', 'votes', 'score', 'sc_up', 'sc_down', 'comments', 'reports', 'reposts', 'date', 'active', 'hidden', 'pinned', 'sticked', 'promoted'),
'searchFields' => array('title'),
'restriction' => array(
'internal' => array('value' => 'timeline_common_post', 'field' => 'type', 'operator' => '='),
'active' => array('value' => '1', 'field' => 'active', 'operator' => '='),
),
'paginate' => array('perPage' => getParam('bx_timeline_events_per_page'), 'start' => 0),
'sorting' => 'last',
'ident' => 'id',
);
$this->sFilterName = 'bx_timeline_filter';
$this->oModule = $this->getMain();
switch ($sMode) {
case '': // search results
$this->sBrowseUrl = BX_DOL_SEARCH_KEYWORD_PAGE;
$this->aCurrent['title'] = _t('_bx_timeline');
unset($this->aCurrent['paginate']['perPage'], $this->aCurrent['rss']);
break;
default:
$sMode = '';
$this->isError = true;
}
$this->setProcessPrivateContent(false);
}
function displayResultBlock ()
{
$sResult = parent::displayResultBlock();
if(empty($sResult))
return $sResult;
return $this->oModule->_oTemplate->getSearchBlock($sResult);
}
function getAlterOrder()
{
$aSql = array();
switch ($this->aCurrent['sorting']) {
case 'last':
$aSql['order'] = ' ORDER BY `bx_timeline_events`.`date` DESC';
break;
}
return $aSql;
}
}
/** @} */
|
unaio/una
|
modules/boonex/timeline/updates/9.0.10_9.0.11/source/classes/BxTimelineSearchResult.php
|
PHP
|
mit
| 2,507
|
function GameManager(size, InputManager, Actuator, StorageManager) {
this.size = size; // Size of the grid
this.inputManager = new InputManager;
this.storageManager = new StorageManager;
this.actuator = new Actuator;
this.startTiles = 2;
this.inputManager.on("move", this.move.bind(this));
this.inputManager.on("restart", this.restart.bind(this));
this.inputManager.on("keepPlaying", this.keepPlaying.bind(this));
this.setup();
}
// Restart the game
GameManager.prototype.restart = function () {
this.storageManager.clearGameState();
this.actuator.continueGame(); // Clear the game won/lost message
this.setup();
};
// Keep playing after winning (allows going over 2048)
GameManager.prototype.keepPlaying = function () {
this.keepPlaying = true;
this.actuator.continueGame(); // Clear the game won/lost message
};
// Return true if the game is lost, or has won and the user hasn't kept playing
GameManager.prototype.isGameTerminated = function () {
if (this.over || (this.won && !this.keepPlaying)) {
return true;
} else {
return false;
}
};
// Set up the game
GameManager.prototype.setup = function () {
var previousState = this.storageManager.getGameState();
// Reload the game from a previous game if present
if (previousState) {
this.grid = new Grid(previousState.grid.size,
previousState.grid.cells); // Reload grid
this.score = previousState.score;
this.over = previousState.over;
this.won = previousState.won;
this.keepPlaying = previousState.keepPlaying;
} else {
this.grid = new Grid(this.size);
this.score = 0;
this.over = false;
this.won = false;
this.keepPlaying = false;
// Add the initial tiles
this.addStartTiles();
}
// Update the actuator
this.actuate();
};
// Set up the initial tiles to start the game with
GameManager.prototype.addStartTiles = function () {
for (var i = 0; i < this.startTiles; i++) {
this.addRandomTile();
}
};
// Adds a tile in a random position
GameManager.prototype.addRandomTile = function () {
if (this.grid.cellsAvailable()) {
var value = Math.random() < 0.9 ? 2048: 1024;
var tile = new Tile(this.grid.randomAvailableCell(), value);
this.grid.insertTile(tile);
}
};
// Sends the updated grid to the actuator
GameManager.prototype.actuate = function () {
if (this.storageManager.getBestScore() < this.score) {
this.storageManager.setBestScore(this.score);
}
// Clear the state when the game is over (game over only, not win)
if (this.over) {
this.storageManager.clearGameState();
} else {
this.storageManager.setGameState(this.serialize());
}
this.actuator.actuate(this.grid, {
score: this.score,
over: this.over,
won: this.won,
bestScore: this.storageManager.getBestScore(),
terminated: this.isGameTerminated()
});
};
// Represent the current game as an object
GameManager.prototype.serialize = function () {
return {
grid: this.grid.serialize(),
score: this.score,
over: this.over,
won: this.won,
keepPlaying: this.keepPlaying
};
};
// Save all tile positions and remove merger info
GameManager.prototype.prepareTiles = function () {
this.grid.eachCell(function (x, y, tile) {
if (tile) {
tile.mergedFrom = null;
tile.savePosition();
}
});
};
// Move a tile and its representation
GameManager.prototype.moveTile = function (tile, cell) {
this.grid.cells[tile.x][tile.y] = null;
this.grid.cells[cell.x][cell.y] = tile;
tile.updatePosition(cell);
};
// Move tiles on the grid in the specified direction
GameManager.prototype.move = function (direction) {
// 0: up, 1: right, 2: down, 3: left
var self = this;
if (this.isGameTerminated()) return; // Don't do anything if the game's over
var cell, tile;
var vector = this.getVector(direction);
var traversals = this.buildTraversals(vector);
var moved = false;
// Save the current tile positions and remove merger information
this.prepareTiles();
// Traverse the grid in the right direction and move tiles
traversals.x.forEach(function (x) {
traversals.y.forEach(function (y) {
cell = { x: x, y: y };
tile = self.grid.cellContent(cell);
if (tile) {
var positions = self.findFarthestPosition(cell, vector);
var next = self.grid.cellContent(positions.next);
// Only one merger per row traversal?
if (next && next.value === tile.value && !next.mergedFrom) {
var merged = new Tile(positions.next, tile.value / 2);
merged.mergedFrom = [tile, next];
self.grid.insertTile(merged);
self.grid.removeTile(tile);
// Converge the two tiles' positions
tile.updatePosition(positions.next);
// Update the score
self.score += (2048/merged.value);
// The mighty 2048 tile
if (merged.value === 1) self.won = true;
} else {
self.moveTile(tile, positions.farthest);
}
if (!self.positionsEqual(cell, tile)) {
moved = true; // The tile moved from its original cell!
}
}
});
});
if (moved) {
this.addRandomTile();
if (!this.movesAvailable()) {
this.over = true; // Game over!
}
this.actuate();
}
};
// Get the vector representing the chosen direction
GameManager.prototype.getVector = function (direction) {
// Vectors representing tile movement
var map = {
0: { x: 0, y: -1 }, // Up
1: { x: 1, y: 0 }, // Right
2: { x: 0, y: 1 }, // Down
3: { x: -1, y: 0 } // Left
};
return map[direction];
};
// Build a list of positions to traverse in the right order
GameManager.prototype.buildTraversals = function (vector) {
var traversals = { x: [], y: [] };
for (var pos = 0; pos < this.size; pos++) {
traversals.x.push(pos);
traversals.y.push(pos);
}
// Always traverse from the farthest cell in the chosen direction
if (vector.x === 1) traversals.x = traversals.x.reverse();
if (vector.y === 1) traversals.y = traversals.y.reverse();
return traversals;
};
GameManager.prototype.findFarthestPosition = function (cell, vector) {
var previous;
// Progress towards the vector direction until an obstacle is found
do {
previous = cell;
cell = { x: previous.x + vector.x, y: previous.y + vector.y };
} while (this.grid.withinBounds(cell) &&
this.grid.cellAvailable(cell));
return {
farthest: previous,
next: cell // Used to check if a merge is required
};
};
GameManager.prototype.movesAvailable = function () {
return this.grid.cellsAvailable() || this.tileMatchesAvailable();
};
// Check for available matches between tiles (more expensive check)
GameManager.prototype.tileMatchesAvailable = function () {
var self = this;
var tile;
for (var x = 0; x < this.size; x++) {
for (var y = 0; y < this.size; y++) {
tile = this.grid.cellContent({ x: x, y: y });
if (tile) {
for (var direction = 0; direction < 4; direction++) {
var vector = self.getVector(direction);
var cell = { x: x + vector.x, y: y + vector.y };
var other = self.grid.cellContent(cell);
if (other && other.value === tile.value) {
return true; // These two tiles can be merged
}
}
}
}
}
return false;
};
GameManager.prototype.positionsEqual = function (first, second) {
return first.x === second.x && first.y === second.y;
};
|
ajnas/One
|
js/game_manager.js
|
JavaScript
|
mit
| 7,688
|
{{ $baseUrl := .Site.BaseURL }}
{{ if .IsNode }}
<ul class="pagination">
{{ with .Paginator }}
<li class="{{ if .HasPrev }}waves-effect{{ else }}disabled{{ end }}">
<a href="{{ if .HasPrev }}{{ $baseUrl }}{{ .Prev.URL }}{{ else }}#!{{ end }}">
<i class="fa fa-angle-left"></i>
</a>
</li>
{{ $currentPageNumber := .PageNumber }}
{{ range .Pagers }}
<li class="{{ if eq $currentPageNumber .PageNumber }}active{{ else }}waves-effect{{ end }}">
<a href="{{ $baseUrl }}{{ .URL }}">{{ .PageNumber }}</a>
</li>
{{ end }}
<li class="{{ if .HasNext }}waves-effect{{ else }}disabled{{ end }}">
<a href="{{ if .HasNext }}{{ $baseUrl }}{{ .Next.URL }}{{ else }}#!{{ end }}">
<i class="fa fa-angle-right"></i>
</a>
</li>
{{ end }}
</ul>
{{ end }}
|
chipsenkbeil/grid-side
|
layouts/partials/extra/pagination.html
|
HTML
|
mit
| 999
|
class CreateFilmsFilmActors < ActiveRecord::Migration
def change
create_table :film_actors_films, id: false do |t|
t.belongs_to :film
t.belongs_to :film_actor
end
add_index :film_actors_films, [:film_id, :film_actor_id]
end
end
|
dodoliu/FilmOcean
|
film_ocean/db/migrate/20151216150427_create_films_film_actors.rb
|
Ruby
|
mit
| 254
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>FindMPI — CMake 3.8.1 Documentation</title>
<link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '3.8.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="FindOpenAL" href="FindOpenAL.html" />
<link rel="prev" title="FindMPEG" href="FindMPEG.html" />
</head>
<body role="document">
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="FindOpenAL.html" title="FindOpenAL"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="FindMPEG.html" title="FindMPEG"
accesskey="P">previous</a> |</li>
<li>
<img src="../_static/cmake-logo-16.png" alt=""
style="vertical-align: middle; margin-top: -2px" />
</li>
<li>
<a href="https://cmake.org/">CMake</a> »
</li>
<li>
<a href="../index.html">3.8.1 Documentation</a> »
</li>
<li class="nav-item nav-item-1"><a href="../manual/cmake-modules.7.html" accesskey="U">cmake-modules(7)</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="findmpi">
<span id="module:FindMPI"></span><h1>FindMPI<a class="headerlink" href="#findmpi" title="Permalink to this headline">¶</a></h1>
<p>Find a Message Passing Interface (MPI) implementation</p>
<p>The Message Passing Interface (MPI) is a library used to write
high-performance distributed-memory parallel applications, and is
typically deployed on a cluster. MPI is a standard interface (defined
by the MPI forum) for which many implementations are available. All
of them have somewhat different include paths, libraries to link
against, etc., and this module tries to smooth out those differences.</p>
<div class="section" id="variables">
<h2>Variables<a class="headerlink" href="#variables" title="Permalink to this headline">¶</a></h2>
<p>This module will set the following variables per language in your
project, where <lang> is one of C, CXX, or Fortran:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">MPI_</span><span class="o"><</span><span class="n">lang</span><span class="o">></span><span class="n">_FOUND</span> <span class="n">TRUE</span> <span class="k">if</span> <span class="n">FindMPI</span> <span class="n">found</span> <span class="n">MPI</span> <span class="n">flags</span> <span class="k">for</span> <span class="o"><</span><span class="n">lang</span><span class="o">></span>
<span class="n">MPI_</span><span class="o"><</span><span class="n">lang</span><span class="o">></span><span class="n">_COMPILER</span> <span class="n">MPI</span> <span class="n">Compiler</span> <span class="n">wrapper</span> <span class="k">for</span> <span class="o"><</span><span class="n">lang</span><span class="o">></span>
<span class="n">MPI_</span><span class="o"><</span><span class="n">lang</span><span class="o">></span><span class="n">_COMPILE_FLAGS</span> <span class="n">Compilation</span> <span class="n">flags</span> <span class="k">for</span> <span class="n">MPI</span> <span class="n">programs</span>
<span class="n">MPI_</span><span class="o"><</span><span class="n">lang</span><span class="o">></span><span class="n">_INCLUDE_PATH</span> <span class="n">Include</span> <span class="n">path</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="n">MPI</span> <span class="n">header</span>
<span class="n">MPI_</span><span class="o"><</span><span class="n">lang</span><span class="o">></span><span class="n">_LINK_FLAGS</span> <span class="n">Linking</span> <span class="n">flags</span> <span class="k">for</span> <span class="n">MPI</span> <span class="n">programs</span>
<span class="n">MPI_</span><span class="o"><</span><span class="n">lang</span><span class="o">></span><span class="n">_LIBRARIES</span> <span class="n">All</span> <span class="n">libraries</span> <span class="n">to</span> <span class="n">link</span> <span class="n">MPI</span> <span class="n">programs</span> <span class="n">against</span>
</pre></div>
</div>
<p>Additionally, FindMPI sets the following variables for running MPI
programs from the command line:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">MPIEXEC</span> <span class="n">Executable</span> <span class="k">for</span> <span class="n">running</span> <span class="n">MPI</span> <span class="n">programs</span>
<span class="n">MPIEXEC_NUMPROC_FLAG</span> <span class="n">Flag</span> <span class="n">to</span> <span class="k">pass</span> <span class="n">to</span> <span class="n">MPIEXEC</span> <span class="n">before</span> <span class="n">giving</span>
<span class="n">it</span> <span class="n">the</span> <span class="n">number</span> <span class="n">of</span> <span class="n">processors</span> <span class="n">to</span> <span class="n">run</span> <span class="n">on</span>
<span class="n">MPIEXEC_PREFLAGS</span> <span class="n">Flags</span> <span class="n">to</span> <span class="k">pass</span> <span class="n">to</span> <span class="n">MPIEXEC</span> <span class="n">directly</span>
<span class="n">before</span> <span class="n">the</span> <span class="n">executable</span> <span class="n">to</span> <span class="n">run</span><span class="o">.</span>
<span class="n">MPIEXEC_POSTFLAGS</span> <span class="n">Flags</span> <span class="n">to</span> <span class="k">pass</span> <span class="n">to</span> <span class="n">MPIEXEC</span> <span class="n">after</span> <span class="n">other</span> <span class="n">flags</span>
</pre></div>
</div>
</div>
<div class="section" id="usage">
<h2>Usage<a class="headerlink" href="#usage" title="Permalink to this headline">¶</a></h2>
<p>To use this module, simply call FindMPI from a CMakeLists.txt file, or
run <code class="docutils literal"><span class="pre">find_package(MPI)</span></code>, then run CMake. If you are happy with the
auto-detected configuration for your language, then you’re done. If
not, you have two options:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="mf">1.</span> <span class="n">Set</span> <span class="n">MPI_</span><span class="o"><</span><span class="n">lang</span><span class="o">></span><span class="n">_COMPILER</span> <span class="n">to</span> <span class="n">the</span> <span class="n">MPI</span> <span class="n">wrapper</span> <span class="p">(</span><span class="n">mpicc</span><span class="p">,</span> <span class="n">etc</span><span class="o">.</span><span class="p">)</span> <span class="n">of</span> <span class="n">your</span>
<span class="n">choice</span> <span class="ow">and</span> <span class="n">reconfigure</span><span class="o">.</span> <span class="n">FindMPI</span> <span class="n">will</span> <span class="n">attempt</span> <span class="n">to</span> <span class="n">determine</span> <span class="nb">all</span> <span class="n">the</span>
<span class="n">necessary</span> <span class="n">variables</span> <span class="n">using</span> <span class="n">THAT</span> <span class="n">compiler</span><span class="s1">'s compile and link flags.</span>
<span class="mf">2.</span> <span class="n">If</span> <span class="n">this</span> <span class="n">fails</span><span class="p">,</span> <span class="ow">or</span> <span class="k">if</span> <span class="n">your</span> <span class="n">MPI</span> <span class="n">implementation</span> <span class="n">does</span> <span class="ow">not</span> <span class="n">come</span> <span class="k">with</span>
<span class="n">a</span> <span class="n">compiler</span> <span class="n">wrapper</span><span class="p">,</span> <span class="n">then</span> <span class="nb">set</span> <span class="n">both</span> <span class="n">MPI_</span><span class="o"><</span><span class="n">lang</span><span class="o">></span><span class="n">_LIBRARIES</span> <span class="ow">and</span>
<span class="n">MPI_</span><span class="o"><</span><span class="n">lang</span><span class="o">></span><span class="n">_INCLUDE_PATH</span><span class="o">.</span> <span class="n">You</span> <span class="n">may</span> <span class="n">also</span> <span class="nb">set</span> <span class="nb">any</span> <span class="n">other</span> <span class="n">variables</span>
<span class="n">listed</span> <span class="n">above</span><span class="p">,</span> <span class="n">but</span> <span class="n">these</span> <span class="n">two</span> <span class="n">are</span> <span class="n">required</span><span class="o">.</span> <span class="n">This</span> <span class="n">will</span> <span class="n">circumvent</span>
<span class="n">autodetection</span> <span class="n">entirely</span><span class="o">.</span>
</pre></div>
</div>
<p>When configuration is successful, <code class="docutils literal"><span class="pre">MPI_<lang>_COMPILER</span></code> will be set to
the compiler wrapper for <lang>, if it was found. <code class="docutils literal"><span class="pre">MPI_<lang>_FOUND</span></code>
and other variables above will be set if any MPI implementation was
found for <lang>, regardless of whether a compiler was found.</p>
<p>When using <code class="docutils literal"><span class="pre">MPIEXEC</span></code> to execute MPI applications, you should typically
use all of the <code class="docutils literal"><span class="pre">MPIEXEC</span></code> flags as follows:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>${MPIEXEC} ${MPIEXEC_NUMPROC_FLAG} PROCS
${MPIEXEC_PREFLAGS} EXECUTABLE ${MPIEXEC_POSTFLAGS} ARGS
</pre></div>
</div>
<p>where <code class="docutils literal"><span class="pre">PROCS</span></code> is the number of processors on which to execute the
program, <code class="docutils literal"><span class="pre">EXECUTABLE</span></code> is the MPI program, and <code class="docutils literal"><span class="pre">ARGS</span></code> are the arguments to
pass to the MPI program.</p>
</div>
<div class="section" id="backward-compatibility">
<h2>Backward Compatibility<a class="headerlink" href="#backward-compatibility" title="Permalink to this headline">¶</a></h2>
<p>For backward compatibility with older versions of FindMPI, these
variables are set, but deprecated:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">MPI_FOUND</span> <span class="n">MPI_COMPILER</span> <span class="n">MPI_LIBRARY</span>
<span class="n">MPI_COMPILE_FLAGS</span> <span class="n">MPI_INCLUDE_PATH</span> <span class="n">MPI_EXTRA_LIBRARY</span>
<span class="n">MPI_LINK_FLAGS</span> <span class="n">MPI_LIBRARIES</span>
</pre></div>
</div>
<p>In new projects, please use the <code class="docutils literal"><span class="pre">MPI_<lang>_XXX</span></code> equivalents.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">FindMPI</a><ul>
<li><a class="reference internal" href="#variables">Variables</a></li>
<li><a class="reference internal" href="#usage">Usage</a></li>
<li><a class="reference internal" href="#backward-compatibility">Backward Compatibility</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="FindMPEG.html"
title="previous chapter">FindMPEG</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="FindOpenAL.html"
title="next chapter">FindOpenAL</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/module/FindMPI.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="FindOpenAL.html" title="FindOpenAL"
>next</a> |</li>
<li class="right" >
<a href="FindMPEG.html" title="FindMPEG"
>previous</a> |</li>
<li>
<img src="../_static/cmake-logo-16.png" alt=""
style="vertical-align: middle; margin-top: -2px" />
</li>
<li>
<a href="https://cmake.org/">CMake</a> »
</li>
<li>
<a href="../index.html">3.8.1 Documentation</a> »
</li>
<li class="nav-item nav-item-1"><a href="../manual/cmake-modules.7.html" >cmake-modules(7)</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright 2000-2017 Kitware, Inc. and Contributors.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.2.
</div>
</body>
</html>
|
pipou/rae
|
builder/cmake/windows/doc/cmake/html/module/FindMPI.html
|
HTML
|
mit
| 14,987
|
# Import a whole load of stuff
from System.IO import *
from System.Drawing import *
from System.Runtime.Remoting import *
from System.Threading import *
from System.Windows.Forms import *
from System.Xml.Serialization import *
from System import *
from Analysis.EDM import *
from DAQ.Environment import *
from EDMConfig import *
def saveBlockConfig(path, config):
fs = FileStream(path, FileMode.Create)
s = XmlSerializer(BlockConfig)
s.Serialize(fs,config)
fs.Close()
def loadBlockConfig(path):
fs = FileStream(path, FileMode.Open)
s = XmlSerializer(BlockConfig)
bc = s.Deserialize(fs)
fs.Close()
return bc
def writeLatestBlockNotificationFile(cluster, blockIndex):
fs = FileStream(Environs.FileSystem.Paths["settingsPath"] + "\\BlockHead\\latestBlock.txt", FileMode.Create)
sw = StreamWriter(fs)
sw.WriteLine(cluster + "\t" + str(blockIndex))
sw.Close()
fs.Close()
def checkYAGAndFix():
interlockFailed = hc.YAGInterlockFailed;
if (interlockFailed):
bh.StopPattern();
bh.StartPattern();
def printWaveformCode(bc, name):
print(name + ": " + str(bc.GetModulationByName(name).Waveform.Code) + " -- " + str(bc.GetModulationByName(name).Waveform.Inverted))
def prompt(text):
sys.stdout.write(text)
return sys.stdin.readline().strip()
def measureParametersAndMakeBC(cluster, eState, bState, rfState, scramblerV, probePolAngle, pumpPolAngle):
fileSystem = Environs.FileSystem
print("Measuring parameters ...")
bh.StopPattern()
hc.UpdateRFPowerMonitor()
hc.UpdateRFFrequencyMonitor()
bh.StartPattern()
hc.UpdateBCurrentMonitor()
hc.UpdateVMonitor()
hc.UpdateI2AOMFreqMonitor()
print("V plus: " + str(hc.CPlusMonitorVoltage * hc.CPlusMonitorScale))
print("V minus: " + str(hc.CMinusMonitorVoltage * hc.CMinusMonitorScale))
print("Bias: " + str(hc.BiasCurrent))
print("B step: " + str(abs(hc.FlipStepCurrent)))
print("DB step: " + str(abs(hc.CalStepCurrent)))
# load a default BlockConfig and customise it appropriately
settingsPath = fileSystem.Paths["settingsPath"] + "\\BlockHead\\"
bc = loadBlockConfig(settingsPath + "default.xml")
bc.Settings["cluster"] = cluster
bc.Settings["eState"] = eState
bc.Settings["bState"] = bState
bc.Settings["rfState"] = rfState
bc.Settings["phaseScramblerV"] = scramblerV
bc.Settings["probePolarizerAngle"] = probePolAngle
bc.Settings["pumpPolarizerAngle"] = pumpPolAngle
bc.Settings["ePlus"] = hc.CPlusMonitorVoltage * hc.CPlusMonitorScale
bc.Settings["eMinus"] = hc.CMinusMonitorVoltage * hc.CMinusMonitorScale
bc.GetModulationByName("B").Centre = (hc.BiasCurrent)/1000
bc.GetModulationByName("B").Step = abs(hc.FlipStepCurrent)/1000
bc.GetModulationByName("DB").Step = abs(hc.CalStepCurrent)/1000
# these next 3, seemingly redundant, lines are to preserve backward compatibility
bc.GetModulationByName("B").PhysicalCentre = (hc.BiasCurrent)/1000
bc.GetModulationByName("B").PhysicalStep = abs(hc.FlipStepCurrent)/1000
bc.GetModulationByName("DB").PhysicalStep = abs(hc.CalStepCurrent)/1000
bc.GetModulationByName("RF1A").Centre = hc.RF1AttCentre
bc.GetModulationByName("RF1A").Step = hc.RF1AttStep
bc.GetModulationByName("RF1A").PhysicalCentre = hc.RF1PowerCentre
bc.GetModulationByName("RF1A").PhysicalStep = hc.RF1PowerStep
bc.GetModulationByName("RF2A").Centre = hc.RF2AttCentre
bc.GetModulationByName("RF2A").Step = hc.RF2AttStep
bc.GetModulationByName("RF2A").PhysicalCentre = hc.RF2PowerCentre
bc.GetModulationByName("RF2A").PhysicalStep = hc.RF2PowerStep
bc.GetModulationByName("RF1F").Centre = hc.RF1FMCentre
bc.GetModulationByName("RF1F").Step = hc.RF1FMStep
bc.GetModulationByName("RF1F").PhysicalCentre = hc.RF1FrequencyCentre
bc.GetModulationByName("RF1F").PhysicalStep = hc.RF1FrequencyStep
bc.GetModulationByName("RF2F").Centre = hc.RF2FMCentre
bc.GetModulationByName("RF2F").Step = hc.RF2FMStep
bc.GetModulationByName("RF2F").PhysicalCentre = hc.RF2FrequencyCentre
bc.GetModulationByName("RF2F").PhysicalStep = hc.RF2FrequencyStep
bc.GetModulationByName("LF1").Centre = hc.FLPZTVoltage
bc.GetModulationByName("LF1").Step = hc.FLPZTStep
bc.GetModulationByName("LF1").PhysicalCentre = hc.I2LockAOMFrequencyCentre
bc.GetModulationByName("LF1").PhysicalStep = hc.I2LockAOMFrequencyStep
# generate the waveform codes
print("Generating waveform codes ...")
eWave = bc.GetModulationByName("E").Waveform
eWave.Name = "E"
lf1Wave = bc.GetModulationByName("LF1").Waveform
lf1Wave.Name = "LF1"
ws = WaveformSetGenerator.GenerateWaveforms( (eWave, lf1Wave), ("B","DB","PI","RF1A","RF2A","RF1F","RF2F") )
bc.GetModulationByName("B").Waveform = ws["B"]
bc.GetModulationByName("DB").Waveform = ws["DB"]
bc.GetModulationByName("PI").Waveform = ws["PI"]
bc.GetModulationByName("RF1A").Waveform = ws["RF1A"]
bc.GetModulationByName("RF2A").Waveform = ws["RF2A"]
bc.GetModulationByName("RF1F").Waveform = ws["RF1F"]
bc.GetModulationByName("RF2F").Waveform = ws["RF2F"]
# change the inversions of the static codes E and LF1
bc.GetModulationByName("E").Waveform.Inverted = WaveformSetGenerator.RandomBool()
bc.GetModulationByName("LF1").Waveform.Inverted = WaveformSetGenerator.RandomBool()
# print the waveform codes
# printWaveformCode(bc, "E")
# printWaveformCode(bc, "B")
# printWaveformCode(bc, "DB")
# printWaveformCode(bc, "PI")
# printWaveformCode(bc, "RF1A")
# printWaveformCode(bc, "RF2A")
# printWaveformCode(bc, "RF1F")
# printWaveformCode(bc, "RF2F")
# printWaveformCode(bc, "LF1")
# store e-switch info in block config
print("Storing E switch parameters ...")
bc.Settings["eRampDownTime"] = hc.ERampDownTime
bc.Settings["eRampDownDelay"] = hc.ERampDownDelay
bc.Settings["eBleedTime"] = hc.EBleedTime
bc.Settings["eSwitchTime"] = hc.ESwitchTime
bc.Settings["eRampUpTime"] = hc.ERampUpTime
bc.Settings["eRampUpDelay"] = hc.ERampUpDelay
# this is for legacy analysis compatibility
bc.Settings["eDischargeTime"] = hc.ERampDownTime + hc.ERampDownDelay
bc.Settings["eChargeTime"] = hc.ERampUpTime + hc.ERampUpDelay
# store the E switch asymmetry in the block
bc.Settings["E0PlusBoost"] = hc.E0PlusBoost
return bc
# lock gains
# microamps of current per volt of control input
kSteppingBiasCurrentPerVolt = 1000.0
# max change in the b-bias voltage per block
kBMaxChange = 0.05
# volts of rf*a input required per cal's worth of offset
kRFAVoltsPerCal = 3.2
kRFAMaxChange = 0.1
# volts of rf*f input required per cal's worth of offset
kRFFVoltsPerCal = 8
kRFFMaxChange = 0.1
def updateLocks(bState):
pmtChannelValues = bh.DBlock.ChannelValues[0]
# note the weird python syntax for a one element list
sigIndex = pmtChannelValues.GetChannelIndex(("SIG",))
sigValue = pmtChannelValues.GetValue(sigIndex)
bIndex = pmtChannelValues.GetChannelIndex(("B",))
bValue = pmtChannelValues.GetValue(bIndex)
#bError = pmtChannelValues.GetError(bIndex)
dbIndex = pmtChannelValues.GetChannelIndex(("DB",))
dbValue = pmtChannelValues.GetValue(dbIndex)
#dbError = pmtChannelValues.GetError(dbIndex)
rf1aIndex = pmtChannelValues.GetChannelIndex(("RF1A","DB"))
rf1aValue = pmtChannelValues.GetValue(rf1aIndex)
#rf1aError = pmtChannelValues.GetError(rf1aIndex)
rf2aIndex = pmtChannelValues.GetChannelIndex(("RF2A","DB"))
rf2aValue = pmtChannelValues.GetValue(rf2aIndex)
#rf2aError = pmtChannelValues.GetError(rf2aIndex)
rf1fIndex = pmtChannelValues.GetChannelIndex(("RF1F","DB"))
rf1fValue = pmtChannelValues.GetValue(rf1fIndex)
#rf1fError = pmtChannelValues.GetError(rf1fIndex)
rf2fIndex = pmtChannelValues.GetChannelIndex(("RF2F","DB"))
rf2fValue = pmtChannelValues.GetValue(rf2fIndex)
#rf2fError = pmtChannelValues.GetError(rf2fIndex)
lf1Index = pmtChannelValues.GetChannelIndex(("LF1",))
lf1Value = pmtChannelValues.GetValue(lf1Index)
#lf1Error = pmtChannelValues.GetError(lf1Index)
lf1dbIndex = pmtChannelValues.GetChannelIndex(("LF1","DB"))
lf1dbValue = pmtChannelValues.GetValue(lf1dbIndex)
print "SIG: " + str(sigValue)
print "B: " + str(bValue) + " DB: " + str(dbValue)
print "RF1A: " + str(rf1aValue) + " RF2A: " + str(rf2aValue)
print "RF1F: " + str(rf1fValue) + " RF2F: " + str(rf2fValue)
print "LF1: " + str(lf1Value) + " LF1.DB: " + str(lf1dbValue)
# B bias lock
# the sign of the feedback depends on the b-state
if bState:
feedbackSign = 1
else:
feedbackSign = -1
deltaBias = - (1.0/8.0) * feedbackSign * (hc.CalStepCurrent * (bValue / dbValue)) / kSteppingBiasCurrentPerVolt
deltaBias = windowValue(deltaBias, -kBMaxChange, kBMaxChange)
print "Attempting to change stepping B bias by " + str(deltaBias) + " V."
newBiasVoltage = windowValue( hc.SteppingBiasVoltage - deltaBias, 0, 5)
hc.SetSteppingBBiasVoltage( newBiasVoltage )
# RFA locks
deltaRF1A = - (1.0/3.0) * (rf1aValue / dbValue) * kRFAVoltsPerCal
deltaRF1A = windowValue(deltaRF1A, -kRFAMaxChange, kRFAMaxChange)
print "Attempting to change RF1A by " + str(deltaRF1A) + " V."
newRF1A = windowValue( hc.RF1AttCentre - deltaRF1A, hc.RF1AttStep, 5 - hc.RF1AttStep)
hc.SetRF1AttCentre( newRF1A )
#
deltaRF2A = - (1.0/3.0) * (rf2aValue / dbValue) * kRFAVoltsPerCal
deltaRF2A = windowValue(deltaRF2A, -kRFAMaxChange, kRFAMaxChange)
print "Attempting to change RF2A by " + str(deltaRF2A) + " V."
newRF2A = windowValue( hc.RF2AttCentre - deltaRF2A, hc.RF2AttStep, 5 - hc.RF2AttStep )
hc.SetRF2AttCentre( newRF2A )
# RFF locks
deltaRF1F = - (1.0/4.0) * (rf1fValue / dbValue) * kRFFVoltsPerCal
deltaRF1F = windowValue(deltaRF1F, -kRFFMaxChange, kRFFMaxChange)
print "Attempting to change RF1F by " + str(deltaRF1F) + " V."
newRF1F = windowValue( hc.RF1FMCentre - deltaRF1F, hc.RF1FMStep, 5 - hc.RF1FMStep)
hc.SetRF1FMCentre( newRF1F )
#
deltaRF2F = - (1.0/4.0) * (rf2fValue / dbValue) * kRFFVoltsPerCal
deltaRF2F = windowValue(deltaRF2F, -kRFFMaxChange, kRFFMaxChange)
print "Attempting to change RF2F by " + str(deltaRF2F) + " V."
newRF2F = windowValue( hc.RF2FMCentre - deltaRF2F, hc.RF2FMStep, 5 - hc.RF2FMStep )
hc.SetRF2FMCentre( newRF2F )
# Laser frequency lock (-ve multiplier in f0 mode and +ve in f1)
deltaLF1 = 1.25 * (lf1Value / dbValue) # I think this should be +ve (but that doesn't work)
deltaLF1 = windowValue(deltaLF1, -0.1, 0.1)
print "Attempting to change LF1 by " + str(deltaLF1) + " V."
newLF1 = windowValue( hc.FLPZTVoltage - deltaLF1, hc.FLPZTStep, 5 - hc.FLPZTStep )
hc.SetFLPZTVoltage( newLF1 )
def windowValue(value, minValue, maxValue):
if ( (value < maxValue) & (value > minValue) ):
return value
else:
if (value < minValue):
return minValue
else:
return maxValue
kTargetRotationPeriod = 10
kReZeroLeakageMonitorsPeriod = 10
r = Random()
def EDMGo():
# Setup
f = None
fileSystem = Environs.FileSystem
dataPath = fileSystem.GetDataDirectory(fileSystem.Paths["edmDataPath"])
settingsPath = fileSystem.Paths["settingsPath"] + "\\BlockHead\\"
print("Data directory is : " + dataPath)
print("")
suggestedClusterName = fileSystem.GenerateNextDataFileName()
sm.SelectProfile("Scan B")
# User inputs data
cluster = prompt("Cluster name [" + suggestedClusterName +"]: ")
if cluster == "":
cluster = suggestedClusterName
print("Using cluster " + suggestedClusterName)
eState = hc.EManualState
print("E-state: " + str(eState))
bState = hc.BManualState
print("B-state: " + str(bState))
rfState = hc.RFManualState
print("rf-state: " + str(rfState))
# this is to make sure the B current monitor is in a sensible state
hc.UpdateBCurrentMonitor()
# randomise Ramsey phase
scramblerV = 0.724774 * r.NextDouble()
hc.SetScramblerVoltage(scramblerV)
# randomise polarizations
probePolAngle = 360.0 * r.NextDouble()
hc.SetProbePolarizerAngle(probePolAngle)
pumpPolAngle = 360.0 * r.NextDouble()
hc.SetPumpPolarizerAngle(pumpPolAngle)
bc = measureParametersAndMakeBC(cluster, eState, bState, rfState, scramblerV, probePolAngle, pumpPolAngle)
# loop and take data
blockIndex = 0
maxBlockIndex = 10000
while blockIndex < maxBlockIndex:
print("Acquiring block " + str(blockIndex) + " ...")
# save the block config and load into blockhead
print("Saving temp config.")
bc.Settings["clusterIndex"] = blockIndex
tempConfigFile ='%(p)stemp%(c)s_%(i)s.xml' % {'p': settingsPath, 'c': cluster, 'i': blockIndex}
saveBlockConfig(tempConfigFile, bc)
System.Threading.Thread.Sleep(500)
print("Loading temp config.")
bh.LoadConfig(tempConfigFile)
# take the block and save it
print("Running ...")
bh.AcquireAndWait()
print("Done.")
blockPath = '%(p)s%(c)s_%(i)s.zip' % {'p': dataPath, 'c': cluster, 'i': blockIndex}
bh.SaveBlock(blockPath)
print("Saved block "+ str(blockIndex) + ".")
# give mma a chance to analyse the block
print("Notifying Mathematica and waiting ...")
writeLatestBlockNotificationFile(cluster, blockIndex)
System.Threading.Thread.Sleep(5000)
print("Done.")
# increment and loop
File.Delete(tempConfigFile)
checkYAGAndFix()
blockIndex = blockIndex + 1
updateLocks(bState)
# randomise Ramsey phase
scramblerV = 0.724774 * r.NextDouble()
hc.SetScramblerVoltage(scramblerV)
# randomise polarizations
probePolAngle = 360.0 * r.NextDouble()
hc.SetProbePolarizerAngle(probePolAngle)
pumpPolAngle = 360.0 * r.NextDouble()
hc.SetPumpPolarizerAngle(pumpPolAngle)
bc = measureParametersAndMakeBC(cluster, eState, bState, rfState, scramblerV, probePolAngle, pumpPolAngle)
hc.StepTarget(1)
# do things that need periodically doing
# if ((blockIndex % kTargetRotationPeriod) == 0):
# print("Rotating target.")
# hc.StepTarget(10)
pmtChannelValues = bh.DBlock.ChannelValues[0]
dbIndex = pmtChannelValues.GetChannelIndex(("DB",))
dbValue = pmtChannelValues.GetValue(dbIndex)
if (dbValue < 8.4):
print("Dodgy spot target rotation.")
hc.StepTarget(5)
if ((blockIndex % kReZeroLeakageMonitorsPeriod) == 0):
print("Recalibrating leakage monitors.")
hc.EnableEField( False )
System.Threading.Thread.Sleep(10000)
hc.EnableBleed( True )
System.Threading.Thread.Sleep(1000)
hc.EnableBleed( False )
System.Threading.Thread.Sleep(5000)
hc.CalibrateIMonitors()
hc.EnableEField( True )
bh.StopPattern()
def run_script():
EDMGo()
|
jstammers/EDMSuite
|
EDMScripts/EDMLoop_neg_slope.py
|
Python
|
mit
| 14,423
|
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Blogs
{
internal enum BlogPostCommentPolicy
{
None = 100000000,
Open = 100000001,
OpenToAuthenticatedUsers = 100000002,
Moderated = 100000003,
Closed = 100000004,
Inherit = 100000005,
}
}
|
Adoxio/xRM-Portals-Community-Edition
|
Framework/Adxstudio.Xrm/Blogs/BlogPostCommentPolicy.cs
|
C#
|
mit
| 485
|
/**
* @module gallery-linkedlist
*/
/**********************************************************************
* Iterator for LinkedList. Stable except when the next item is removed by
* calling list.remove() instead of iter.removeNext(). When items are
* inserted into an empty list, the pointer remains at the end, not the
* beginning.
*
* @class LinkedListIterator
* @method constructor
* @private
* @param list {LinkedList}
*/
function LinkedListIterator(
/* LinkedList */ list)
{
this._list = list;
this.moveToBeginning();
}
LinkedListIterator.prototype =
{
/**
* @method atBeginning
* @return {Boolean} true if at the beginning
*/
atBeginning: function()
{
return (!this._next || (!this._at_end && !this._next._prev));
},
/**
* @method atEnd
* @return {Boolean} true if at the end
*/
atEnd: function()
{
return (!this._next || this._at_end);
},
/**
* Move to the beginning of the list.
*
* @method moveToBeginning
*/
moveToBeginning: function()
{
this._next = this._list._head;
this._at_end = !this._next;
},
/**
* Move to the end of the list.
*
* @method moveToEnd
*/
moveToEnd: function()
{
this._next = this._list._tail;
this._at_end = true;
},
/**
* @method next
* @return {Mixed} next value in the list or undefined if at the end
*/
next: function()
{
if (this._at_end)
{
return;
}
var result = this._next;
if (this._next && this._next._next)
{
this._next = this._next._next;
}
else
{
this._at_end = true;
}
if (result)
{
return result.value;
}
},
/**
* @method prev
* @return {Mixed} previous value in the list or undefined if at the beginning
*/
prev: function()
{
var result;
if (this._at_end)
{
this._at_end = false;
result = this._next;
}
else if (this._next)
{
result = this._next._prev;
if (result)
{
this._next = result;
}
}
if (result)
{
return result.value;
}
},
/**
* Insert the given value at the iteration position. The inserted item
* will be returned by next().
*
* @method insert
* @param value {Mixed} value to insert
* @return {LinkedListItem} inserted item
*/
insert: function(
/* object */ value)
{
if (this._at_end || !this._next)
{
this._next = this._list.append(value);
}
else
{
this._next = this._list.insertBefore(value, this._next);
}
return this._next;
},
/**
* Remove the previous item from the list.
*
* @method removePrev
* @return {LinkedListItem} removed item or undefined if at the end
*/
removePrev: function()
{
var result;
if (this._at_end)
{
result = this._next;
if (this._next)
{
this._next = this._next._prev;
}
}
else if (this._next)
{
result = this._next._prev;
}
if (result)
{
this._list.remove(result);
return result;
}
},
/**
* Remove the next item from the list.
*
* @method removeNext
* @return {LinkedListItem} removed item or undefined if at the end
*/
removeNext: function()
{
var result;
if (this._next && !this._at_end)
{
result = this._next;
if (this._next && this._next._next)
{
this._next = this._next._next;
}
else
{
this._next = this._next ? this._next._prev : null;
this._at_end = true;
}
}
if (result)
{
this._list.remove(result);
return result;
}
}
};
|
inikoo/fact
|
libs/yui/yui3-gallery/src/gallery-linkedlist/js/LinkedListIterator.js
|
JavaScript
|
mit
| 3,399
|
package org.elkoserver.foundation.net.zmq.test;
import org.elkoserver.foundation.json.JSONMethod;
import org.elkoserver.foundation.json.MessageHandlerException;
import org.elkoserver.foundation.net.Connection;
import org.elkoserver.foundation.net.zmq.ZMQOutbound;
import org.elkoserver.json.EncodeControl;
import org.elkoserver.json.JSONLiteral;
import org.elkoserver.server.context.ContextMod;
import org.elkoserver.server.context.Contextor;
import org.elkoserver.server.context.Mod;
import org.elkoserver.server.context.ObjectCompletionWatcher;
import org.elkoserver.server.context.User;
import org.elkoserver.util.trace.Trace;
/**
* Context mod to test ZMQ outbound connections
*/
public class ZMQSendMod
extends Mod
implements ContextMod, ObjectCompletionWatcher
{
/** Name of static object that will deliver outbound ZMQ messages */
private String myOutboundName;
/** The connection to send outbound messages on */
private Connection myConnection;
/** Trace object for logging */
private Trace tr;
/**
* JSON-driven constructor.
*/
@JSONMethod("outbound")
public ZMQSendMod(String outboundName) {
myOutboundName = outboundName;
}
/**
* Encode this mod for transmission or persistence.
*
* @param control Encode control determining what flavor of encoding
* should be done.
*
* @return a JSON literal representing this mod.
*/
public JSONLiteral encode(EncodeControl control) {
if (!control.toClient()) {
JSONLiteral result = new JSONLiteral("zmqsendmod", control);
result.addParameter("outbound", myOutboundName);
result.finish();
return result;
} else {
return null;
}
}
/**
* Handle the 'log' verb. Logs an arbitrary string to the ZMQ connection
*
* @param str String to log
*/
@JSONMethod("str")
public void log(User from, String str) throws MessageHandlerException {
ensureInContext(from);
JSONLiteral msg = new JSONLiteral("logger", "log");
msg.addParameter("str", str);
msg.finish();
if (myConnection != null) {
myConnection.sendMsg(msg);
} else {
tr.errorm("uninitialized outbound connection");
}
}
public void objectIsComplete() {
Contextor contextor = object().contextor();
tr = contextor.appTrace();
ZMQOutbound outbound =
(ZMQOutbound) contextor.getStaticObject(myOutboundName);
myConnection = outbound.getConnection();
}
}
|
frandallfarmer/Elko
|
ZeroMQ/java/org/elkoserver/foundation/net/zmq/test/ZMQSendMod.java
|
Java
|
mit
| 2,622
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bxf;
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using Microsoft.Phone.Controls;
namespace WpUI
{
public class MainWindowPresenter : DependencyObject
{
public MainWindowPresenter()
{
var presenter = (IPresenter)Shell.Instance;
presenter.OnShowError += (message, title) =>
{
MessageBox.Show(message, title, MessageBoxButton.OK);
};
presenter.OnShowStatus += (status) =>
{
};
presenter.OnShowView += (view, region) =>
{
PivotItem panel = GetPanel(int.Parse(region));
var vm = view.Model as IViewModel;
if (vm != null)
panel.Header = vm.Header;
else
panel.Header = string.Empty;
panel.Content = view.ViewInstance;
};
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
try
{
Shell.Instance.ShowView(
typeof(OrderEdit).AssemblyQualifiedName,
"orderVmViewSource",
new OrderVm(),
"1");
}
catch (Exception ex)
{
Shell.Instance.ShowError(ex.Message, "Startup error");
}
}
}
private PivotItem GetPanel(int id)
{
while (Panels.Count < id) Panels.Add(new PivotItem());
return Panels[id - 1];
}
public static readonly DependencyProperty PanelsProperty =
DependencyProperty.Register("Panels", typeof(ObservableCollection<PivotItem>), typeof(MainWindowPresenter),
new PropertyMetadata(new ObservableCollection<PivotItem>()));
public ObservableCollection<PivotItem> Panels
{
get { return (ObservableCollection<PivotItem>)GetValue(PanelsProperty); }
set { SetValue(PanelsProperty, value); }
}
}
}
|
BrettJaner/csla
|
Samples/NET/cs/SimpleNTier/WpUI/MainWindowPresenter.cs
|
C#
|
mit
| 1,925
|
module Gitlab
module Sherlock
# Rack middleware used for tracking request metrics.
class Middleware
CONTENT_TYPES = %r{text/html|application/json}i
IGNORE_PATHS = %r{^/sherlock}
def initialize(app)
@app = app
end
# env - A Hash containing Rack environment details.
def call(env)
if instrument?(env)
call_with_instrumentation(env)
else
@app.call(env)
end
end
def call_with_instrumentation(env)
trans = transaction_from_env(env)
retval = trans.run { @app.call(env) }
Sherlock.collection.add(trans)
retval
end
def instrument?(env)
!!(env['HTTP_ACCEPT'] =~ CONTENT_TYPES &&
env['REQUEST_URI'] !~ IGNORE_PATHS)
end
def transaction_from_env(env)
Transaction.new(env['REQUEST_METHOD'], env['REQUEST_URI'])
end
end
end
end
|
jirutka/gitlabhq
|
lib/gitlab/sherlock/middleware.rb
|
Ruby
|
mit
| 928
|
#include "zerosInFactorial.c"
|
zonxin/expandC
|
clib/b/zerosInFactorial.h
|
C
|
mit
| 30
|
/* @flow */
/*eslint-disable no-undef, no-unused-vars, no-console*/
import _, { compose, pipe, curry, filter, find, repeat, zipWith } from 'ramda'
const ns: Array<number> = [ 1, 2, 3, 4, 5 ]
const ss: Array<string> = [ 'one', 'two', 'three', 'four' ]
const obj: {[k:string]:number} = { a: 1, c: 2 }
const objMixed: {[k:string]:mixed} = { a: 1, c: 'd' }
const os: Array<{[k:string]: number|string}> = [ { a: 1, c: 'd' }, { b: 2 } ]
const str: string = 'hello world'
// List
{
const xs: Array<number> = _.adjust(x => x + 1, 2, ns)
const xs1: Array<number> = _.adjust(x => x + 1, 2)(ns)
//$FlowExpectedError
const xs3: Array<string> = _.adjust(x => x + 1)(2)(ns)
const as: boolean = _.all(x => x > 1, ns)
const asf: (s: Array<string>) => boolean = _.any(x => x.length > 1)
const as1: boolean = asf(ss)
const aps: Array<Array<number>> = _.aperture(2, ns)
const aps2: Array<Array<string>> = _.aperture(2)(ss)
const newXs: Array<string> = _.append('one', ss)
const newXs1: Array<number> = _.prepend(1)(ns)
const concatxs1: Array<number> = _.concat([ 4, 5, 6 ], [ 1, 2, 3 ])
const concatxs2: string = _.concat('ABC', 'DEF')
const cont1: boolean = _.contains('s', ss)
const dropxs: Array<string> = _.drop(4, ss)
const dropxs1: string = _.drop(3)(str)
const dropxs2: Array<string> = _.dropLast(4, ss)
const dropxs3: string = _.dropLast(3)(str)
const dropxs4: Array<number> = _.dropLastWhile(x => x <= 3, ns)
const dropxs5: Array<string> = _.dropRepeats(ss)
const dropxs6: Array<number> = _.dropRepeatsWith(_.eqBy(Math.abs), ns)
const dropxs7: Array<number> = _.dropWhile(x => x === 1, ns)
const findxs:?{[k:string]:number|string} = _.find(_.propEq('a', 2), os)
const findxs1:?{[k:string]:number|string} = _.find(_.propEq('a', 4))(os)
const findxs2:?{[k:string]:number|string} = _.findLast(_.propEq('a', 2), os)
const findxs3:?{[k:string]:number|string} = _.findLast(_.propEq('a', 4))(os)
const findxs4: number = _.findIndex(_.propEq('a', 2), os)
const findxs5:number = _.findIndex(_.propEq('a', 4))(os)
const findxs6:number = _.findLastIndex(_.propEq('a', 2), os)
const findxs7:number = _.findLastIndex(_.propEq('a', 4))(os)
const forEachObj = _.forEachObjIndexed((value, key) => {}, {x: 1, y: 2})
const s: Array<number> = filter(x => x > 1, [ 1, 2 ])
const s1: Array<string> = _.filter(x => x === '2', [ '2', '3' ])
const s3: {[key: string]: string} = _.filter(x => x === '2', { a:'2', b:'3' })
const s4 = _.find(x => x === '2', [ '1', '2' ])
//$FlowExpectedError
const s5: ?{[key: string]: string} = _.find(x => x === '2', { a: 1, b: 2 })
const s6: number = _.findIndex(x => x === '2', [ '1', '2' ])
const s7: number = _.findIndex(x => x === '2', { a:'1', b:'2' })
const forEachxs = _.forEach(x => console.log(x), ns)
const groupedBy: {[k: string]: Array<number>} = _.groupBy(x => x > 1 ? 'more' : 'less' , ns)
//$FlowExpectedError
const groupedBy1: {[k: string]: Array<string>} = _.groupBy(x => x > 1 ? 'more' : 'less')(ns)
const groupedWith: Array<Array<number>> = _.groupWith(x => x > 1, ns)
const groupedWith1: Array<Array<string>> = _.groupWith(x => x === 'one')(ss)
const xOfXs: ?number = _.head(ns)
const xOfXs2: ?number = _.head(ns)
const xOfStr: string = _.head(str)
const transducer = _.compose(_.map(_.add(1)), _.take(2))
const txs: Array<number> = _.into([], transducer, ns)
//$FlowExpectedError
const txs1: string = _.into([], transducer, ns)
//$FlowExpectedError
const txs2: string = _.into([], transducer, ss)
const ind: number = _.indexOf(1, ns)
const ind1: number = _.indexOf(str)(ss)
const ind2:{[key: string]:{[k: string]: number|string}} = _.indexBy(x => 's', os)
const ind3:{[key: string]:{[k: string]: number|string}} = _.indexBy(x => 's')(os)
const insxs: Array<number> = _.insert(1, 2, ns)
const insxs2: Array<string> = _.insert(1, '2', ss)
const insxs3: Array<number> = _.insertAll(1, [ 2, 3 ], ns)
// this is disgusting — don't do this :)
// Technically it's a tuple with arbitrary size
const insxs4: Array<number|boolean|string> = _.insertAll(1, [ '2', false ], ns)
const insxs5: Array<string|number> = _.insertAll(1, [ 2 ], ss)
const joinxs: string = _.join('|', ns)
const lastxs: ?number = _.last(ns)
const laststr: string = _.last(str)
const lasti: number = _.lastIndexOf(3, [ -1,3,3,0,1,2,3,4 ])
const mapxs: Array<number>= _.map(x => x + 1, ns)
const someObj: { a: string, b: number } = { a: 'a', b: 2 }
const someMap: { [string]: { a: string, b: number } } = { so: someObj }
const mapObj: { [string]: string } = _.map((x: { a: string, b: number }): string => x.a)(someMap)
const functor = {
x: 1,
map(f) {
return f(this.x)
},
}
// Doesn't typecheck (yet) but at least doesn't break
const mapFxs = _.map(_.toString, functor)
const double = x => x * 2
const dxs: Array<number> = _.map(double, [ 1, 2, 3 ])
const dos: $Shape<typeof obj> = _.map(double, obj)
const appender = (a, b) => [ a + b, a + b ]
const mapacc:[number, Array<number>] = _.mapAccum(appender, 0, ns)
const mapacc1:[number, Array<number>] = _.mapAccumRight(appender, 0, ns)
const nxs: boolean = _.none(x => x > 1, ns)
const nthxs: ?string = _.nth(2, [ 'curry' ])
const nthxs1: ?string = _.nth(2)([ 'curry' ])
//$FlowExpectedError
const nthxs2: string = _.nth(2, [ 1, 2, 3 ])
const xxs: Array<number> = _.append(1, [ 1, 2, 3 ])
const xxxs: Array<number> = _.intersperse(1, [ 1, 2, 3 ])
const pairxs:[number,string] = _.pair(2, 'str')
const partxs:[Array<string>,Array<string>] = _.partition(_.contains('s'), [ 'sss', 'ttt', 'foo', 'bars' ])
const partxs1: [{[k:string]:string}, {[k:string]:string}] = _.partition(_.contains('s'), { a: 'sss', b: 'ttt', foo: 'bars' })
const pl:Array<number|string> = _.pluck('a')([ { a: '1' }, { a: 2 } ])
const pl1:Array<number> = _.pluck(0)([ [ 1, 2 ], [ 3, 4 ] ])
const rxs: Array<number> = _.range(1, 10)
const remxs: Array<string> = _.remove(0, 2, ss)
const remxs1: Array<string> = _.remove(0, 2)(ss)
const remxs2: Array<string> = _.remove(0)(2)(ss)
const remxs3: Array<string> = _.remove(0)(2, ss)
const ys4: Array<string> = _.repeat('1', 10)
const ys5: Array<number> = _.repeat(1, 10)
const redxs: number = _.reduce(_.add, 10, ns)
const redxs1: string = _.reduce(_.concat, '', ss)
const redxs2: Array<string> = _.reduce(_.concat, [])(_.map(x => [ x ], ss))
const redxs3: number = _.reduceRight(_.add, 10, ns)
const redxs4: string = _.reduceRight(_.concat, '', ss)
const redxs5: Array<string> = _.reduceRight(_.concat, [])(_.map(x => [ x ], ss))
const redxs6: number = _.scan(_.add, 10, ns)
const redxs7: string = _.scan(_.concat, '', ss)
const redxs8: Array<string> = _.scan(_.concat, [])(_.map(x => [ x ], ss))
const reduceToNamesBy = _.reduceBy((acc, student) => acc.concat(student.name), [])
const namesByGrade = reduceToNamesBy((student) => {
const score = student.score
return score < 65 ? 'F' : score < 70 ? 'D' : score < 80 ? 'C' : score < 90 ? 'B' : 'A'
})
const students = [
{ name: 'Lucy', score: 92 },
{ name: 'Drew', score: 85 },
{ name: 'Bart', score: 62 },
]
const names1: {[k: string]: Array<string>} = namesByGrade(students)
const spl: Array<string> = _.split(/\./, 'a.b.c.xyz.d')
const spl1: [Array<number>,Array<number>] = _.splitAt(1, [ 1, 2, 3 ])
const spl2: [string, string] = _.splitAt(5, 'hello world')
const spl3: [string, string]= _.splitAt(-1, 'foobar')
const spl4: Array<Array<number>> = _.splitEvery(3, [ 1, 2, 3, 4, 5, 6, 7 ])
const spl5: Array<string> = _.splitEvery(3, 'foobarbaz')
const spl6: [Array<number>,Array<number>] = _.splitWhen(_.equals(2))([ 1, 2, 3, 1, 2, 3 ])
const slixs: Array<string> = _.slice(0, 2, ss)
const slixs1: Array<string> = _.slice(0, 2)(ss)
const slixs2: Array<string> = _.slice(0)(2)(ss)
const slixs3: Array<string> = _.slice(0)(2, ss)
const diff = function (a, b) { return a - b }
const sortxs: Array<number> = _.sort(diff, [ 4,2,7,5 ])
const timesxs: Array<number> = _.times(_.identity, 5)
const unf: (x: string) => Array<string> = _.unfold((x: string) => x.length > 10 || [ x, x + '0' ])
const unf1: Array<number> = _.unfold(x => x > 10 || [ x, x + 1 ], 0)
const f = n => n > 50 ? false : [ -n, n + 10 ]
const unf11: Array<number> = _.unfold(f, 10)
//$FlowExpectedError
const unf2 = _.unfold(x => x.length > 10 || [ x, x + '0' ], 2)
const unby: Array<number> = _.uniqBy(Math.abs)([ -1, -5, 2, 10, 1, 2 ])
const strEq = _.eqBy(String)
const strEq2 = _.eqBy(String, 1, 2)
const unw = _.uniqWith(strEq)([ 1, '1', 2, 1 ])
const unw1 = _.uniqWith(strEq)([ {}, {} ])
const unw2 = _.uniqWith(strEq)([ 1, '1', 1 ])
const unw3 = _.uniqWith(strEq)([ '1', 1, 1 ])
//$FlowExpectedError
const ys6: {[key: string]: string} = _.fromPairs([ [ 'h', 2 ] ])
const withoutxs: Array<number> = _.without([ 1, 2 ], ns)
const withoutxs1: Array<string> = _.without([ 'a' ], ss)
const xprodxs: Array<[ number, string ]> = _.xprod([ 1, 2 ], [ 'a', 'b', 'c' ])
const xprodxs1: Array<[ boolean, string ]> = _.xprod([ true, false ])([ 'a', 'b' ])
const zipxs: Array<[ number, string ]> = _.zip([ 1, 2, 3 ], [ 'a', 'b', 'c' ])
//$FlowExpectedError
const zipxs1: Array<[ number, string ]> = _.zip([ true, false ])([ 'a', 'b' ])
const zipos: {[k:string]:number} = _.zipObj([ 'a', 'b', 'c' ], [ 1, 2, 3 ])
const ys9: {[k:string]: number} = _.zipObj([ 'me', 'you' ], [ 1, 2 ])
const zipped: Array<{s: number, y: string}> = zipWith((a, b) => ({ s: a, y: b }), [ 1, 2, 3 ], [ '1', '2', '3' ])
const zipped2: Array<{s: number, y: string}> = _.zipWith((a, b) => ({ s: a, y: b }), [ 1, 2, 3 ])([ '1', '2', '3' ])
const zipped3: Array<{s: number, y: string}> = _.zipWith((a, b) => ({ s: a, y: b }))([ 1, 2, 3 ])([ '1', '2', '3' ])
}
|
flowtype/flow-typed
|
definitions/npm/ramda_v0.x.x/flow_v0.28.x-v0.30.x/test_ramda_v0.x.x_list.js
|
JavaScript
|
mit
| 9,896
|
---
title: "Sobota pred Sinajem"
date: 24/05/2021
---
Rekel jim je: »To je tisto, kar je naročil Gospod: Jutri je praznik počitka, sobota, posvečena Gospodu; specite, kar je treba speči, in skuhajte, kar je treba skuhati; vse pa, kar ostane, denite na stran, da se prihrani do jutra!« 2 Mz 16,23
**Preleti 2 Mz 16, kjer je opisan dogodek z mano. Bodi pozoren na naslednje**:
`1. Izraelci so vsak dan dobili toliko mane, kolikor je je zadoščalo za en dan, toda šesti dan v tednu so prejeli dvojno količino.`
`2. V soboto Gospod ni poslal mane z neba.`
`3. Dodatna količina mane za soboto je nepokvarjena počakala šesti in sedmi dan, medtem ko se je druge dni v tednu čez noč pokvarila.`
`Kaj nam ta dogodek razodeva o svetosti sobote, še preden je Bog dal Izraelcem svoj zakon na Sinaju? Glej 2 Mz 16,23-28.`
»Enačenje sobote s sedmim dnem, izjava, da je Gospod Izraelcem dal soboto, in zapis, da je ljudstvo po Božji zapovedi sedmi dan počivalo, nezmotljivo kažejo na to, da je bila sobota kot ustanova določena že ob stvarjenju.« /G. F. Waterman, The Zondervan Pictorial Encyclopedia of the Bible, vol. 5, str. 184./
**V 2 Mz 16 se skriva veliko več, kot je opaziti na prvi pogled.**
`1. Kateri dan je »dan priprave« na soboto?`
`2. Kateri dan v tednu je sobota?`
`3. Od kod izvira sobota?`
`4. Kakšen dan bi morala biti sobota?`
`5. Ali je sobota dan, ko moramo postiti?`
`6. Ali je sobota preizkus naše zvestobe Bogu?`
`Kako se tvoje trenutno razumevanje sobote sklada s tem, kar o njej beremo v 2 Mz 16?`
|
imasaru/sabbath-school-lessons
|
src/sl/2021-02/09/03.md
|
Markdown
|
mit
| 1,555
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Bin;
use Buildable;
use Container;
use Widget;
use ffi;
use glib;
use glib::StaticType;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::mem;
use std::mem::transmute;
use std::ptr;
glib_wrapper! {
pub struct Alignment(Object<ffi::GtkAlignment, ffi::GtkAlignmentClass>): Bin, Container, Widget, Buildable;
match fn {
get_type => || ffi::gtk_alignment_get_type(),
}
}
impl Alignment {
#[cfg_attr(feature = "v3_14", deprecated)]
pub fn new(xalign: f32, yalign: f32, xscale: f32, yscale: f32) -> Alignment {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_alignment_new(xalign, yalign, xscale, yscale)).downcast_unchecked()
}
}
}
pub trait AlignmentExt {
#[cfg_attr(feature = "v3_14", deprecated)]
fn get_padding(&self) -> (u32, u32, u32, u32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn set(&self, xalign: f32, yalign: f32, xscale: f32, yscale: f32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn set_padding(&self, padding_top: u32, padding_bottom: u32, padding_left: u32, padding_right: u32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn get_property_bottom_padding(&self) -> u32;
#[cfg_attr(feature = "v3_14", deprecated)]
fn set_property_bottom_padding(&self, bottom_padding: u32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn get_property_left_padding(&self) -> u32;
#[cfg_attr(feature = "v3_14", deprecated)]
fn set_property_left_padding(&self, left_padding: u32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn get_property_right_padding(&self) -> u32;
#[cfg_attr(feature = "v3_14", deprecated)]
fn set_property_right_padding(&self, right_padding: u32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn get_property_top_padding(&self) -> u32;
#[cfg_attr(feature = "v3_14", deprecated)]
fn set_property_top_padding(&self, top_padding: u32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn get_property_xalign(&self) -> f32;
#[cfg_attr(feature = "v3_14", deprecated)]
fn set_property_xalign(&self, xalign: f32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn get_property_xscale(&self) -> f32;
#[cfg_attr(feature = "v3_14", deprecated)]
fn set_property_xscale(&self, xscale: f32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn get_property_yalign(&self) -> f32;
#[cfg_attr(feature = "v3_14", deprecated)]
fn set_property_yalign(&self, yalign: f32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn get_property_yscale(&self) -> f32;
#[cfg_attr(feature = "v3_14", deprecated)]
fn set_property_yscale(&self, yscale: f32);
#[cfg_attr(feature = "v3_14", deprecated)]
fn connect_property_bottom_padding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
#[cfg_attr(feature = "v3_14", deprecated)]
fn connect_property_left_padding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
#[cfg_attr(feature = "v3_14", deprecated)]
fn connect_property_right_padding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
#[cfg_attr(feature = "v3_14", deprecated)]
fn connect_property_top_padding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
#[cfg_attr(feature = "v3_14", deprecated)]
fn connect_property_xalign_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
#[cfg_attr(feature = "v3_14", deprecated)]
fn connect_property_xscale_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
#[cfg_attr(feature = "v3_14", deprecated)]
fn connect_property_yalign_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
#[cfg_attr(feature = "v3_14", deprecated)]
fn connect_property_yscale_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<Alignment> + IsA<glib::object::Object>> AlignmentExt for O {
fn get_padding(&self) -> (u32, u32, u32, u32) {
unsafe {
let mut padding_top = mem::uninitialized();
let mut padding_bottom = mem::uninitialized();
let mut padding_left = mem::uninitialized();
let mut padding_right = mem::uninitialized();
ffi::gtk_alignment_get_padding(self.to_glib_none().0, &mut padding_top, &mut padding_bottom, &mut padding_left, &mut padding_right);
(padding_top, padding_bottom, padding_left, padding_right)
}
}
fn set(&self, xalign: f32, yalign: f32, xscale: f32, yscale: f32) {
unsafe {
ffi::gtk_alignment_set(self.to_glib_none().0, xalign, yalign, xscale, yscale);
}
}
fn set_padding(&self, padding_top: u32, padding_bottom: u32, padding_left: u32, padding_right: u32) {
unsafe {
ffi::gtk_alignment_set_padding(self.to_glib_none().0, padding_top, padding_bottom, padding_left, padding_right);
}
}
fn get_property_bottom_padding(&self) -> u32 {
unsafe {
let mut value = Value::from_type(<u32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "bottom-padding".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_bottom_padding(&self, bottom_padding: u32) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "bottom-padding".to_glib_none().0, Value::from(&bottom_padding).to_glib_none().0);
}
}
fn get_property_left_padding(&self) -> u32 {
unsafe {
let mut value = Value::from_type(<u32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "left-padding".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_left_padding(&self, left_padding: u32) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "left-padding".to_glib_none().0, Value::from(&left_padding).to_glib_none().0);
}
}
fn get_property_right_padding(&self) -> u32 {
unsafe {
let mut value = Value::from_type(<u32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "right-padding".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_right_padding(&self, right_padding: u32) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "right-padding".to_glib_none().0, Value::from(&right_padding).to_glib_none().0);
}
}
fn get_property_top_padding(&self) -> u32 {
unsafe {
let mut value = Value::from_type(<u32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "top-padding".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_top_padding(&self, top_padding: u32) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "top-padding".to_glib_none().0, Value::from(&top_padding).to_glib_none().0);
}
}
fn get_property_xalign(&self) -> f32 {
unsafe {
let mut value = Value::from_type(<f32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "xalign".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_xalign(&self, xalign: f32) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "xalign".to_glib_none().0, Value::from(&xalign).to_glib_none().0);
}
}
fn get_property_xscale(&self) -> f32 {
unsafe {
let mut value = Value::from_type(<f32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "xscale".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_xscale(&self, xscale: f32) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "xscale".to_glib_none().0, Value::from(&xscale).to_glib_none().0);
}
}
fn get_property_yalign(&self) -> f32 {
unsafe {
let mut value = Value::from_type(<f32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "yalign".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_yalign(&self, yalign: f32) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "yalign".to_glib_none().0, Value::from(&yalign).to_glib_none().0);
}
}
fn get_property_yscale(&self) -> f32 {
unsafe {
let mut value = Value::from_type(<f32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "yscale".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_yscale(&self, yscale: f32) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "yscale".to_glib_none().0, Value::from(&yscale).to_glib_none().0);
}
}
fn connect_property_bottom_padding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::bottom-padding",
transmute(notify_bottom_padding_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_left_padding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::left-padding",
transmute(notify_left_padding_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_right_padding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::right-padding",
transmute(notify_right_padding_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_top_padding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::top-padding",
transmute(notify_top_padding_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_xalign_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::xalign",
transmute(notify_xalign_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_xscale_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::xscale",
transmute(notify_xscale_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_yalign_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::yalign",
transmute(notify_yalign_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_yscale_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::yscale",
transmute(notify_yscale_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
}
unsafe extern "C" fn notify_bottom_padding_trampoline<P>(this: *mut ffi::GtkAlignment, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Alignment> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Alignment::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_left_padding_trampoline<P>(this: *mut ffi::GtkAlignment, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Alignment> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Alignment::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_right_padding_trampoline<P>(this: *mut ffi::GtkAlignment, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Alignment> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Alignment::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_top_padding_trampoline<P>(this: *mut ffi::GtkAlignment, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Alignment> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Alignment::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_xalign_trampoline<P>(this: *mut ffi::GtkAlignment, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Alignment> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Alignment::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_xscale_trampoline<P>(this: *mut ffi::GtkAlignment, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Alignment> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Alignment::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_yalign_trampoline<P>(this: *mut ffi::GtkAlignment, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Alignment> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Alignment::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_yscale_trampoline<P>(this: *mut ffi::GtkAlignment, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Alignment> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Alignment::from_glib_borrow(this).downcast_unchecked())
}
|
EPashkin/rust-gnome-gtk
|
src/auto/alignment.rs
|
Rust
|
mit
| 14,952
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class App\Http\Kernel</title>
<link rel="stylesheet" href="resources/style.css?c2f33731c1948fbed7c333554678bfa68d4817da">
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li class="active">
<a href="namespace-App.html">
App<span></span>
</a>
<ul>
<li>
<a href="namespace-App.Console.html">
Console<span></span>
</a>
<ul>
<li>
<a href="namespace-App.Console.Commands.html">
Commands </a>
</li>
</ul></li>
<li>
<a href="namespace-App.Events.html">
Events </a>
</li>
<li>
<a href="namespace-App.Exceptions.html">
Exceptions </a>
</li>
<li class="active">
<a href="namespace-App.Http.html">
Http<span></span>
</a>
<ul>
<li>
<a href="namespace-App.Http.Controllers.html">
Controllers<span></span>
</a>
<ul>
<li>
<a href="namespace-App.Http.Controllers.Auth.html">
Auth </a>
</li>
</ul></li>
<li>
<a href="namespace-App.Http.Middleware.html">
Middleware </a>
</li>
<li>
<a href="namespace-App.Http.Requests.html">
Requests </a>
</li>
</ul></li>
<li>
<a href="namespace-App.Jobs.html">
Jobs </a>
</li>
<li>
<a href="namespace-App.Providers.html">
Providers </a>
</li>
</ul></li>
</ul>
</div>
<hr>
<div id="elements">
<h3>Classes</h3>
<ul>
<li class="active"><a href="class-App.Http.Kernel.html">Kernel</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="">
<input type="hidden" name="ie" value="UTF-8">
<input type="text" name="q" class="text" placeholder="Search">
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li>
<a href="namespace-App.Http.html" title="Summary of App\Http"><span>Namespace</span></a>
</li>
<li class="active">
<span>Class</span> </li>
</ul>
<ul>
</ul>
<ul>
</ul>
</div>
<div id="content" class="class">
<h1>Class Kernel</h1>
<dl class="tree">
<dd style="padding-left:0px">
Illuminate\Foundation\Http\Kernel
</dd>
<dd style="padding-left:30px">
<img src="resources/inherit.png" alt="Extended by">
<b><span>App\Http\Kernel</span></b>
</dd>
</dl>
<div class="info">
<b>Namespace:</b> <a href="namespace-App.html">App</a>\<a href="namespace-App.Http.html">Http</a><br>
<b>Located at</b> <a href="source-class-App.Http.Kernel.html#7-33" title="Go to source code">Http/Kernel.php</a>
<br>
</div>
<table class="summary properties" id="properties">
<caption>Properties summary</caption>
<tr data-order="middleware" id="$middleware">
<td class="attributes"><code>
protected
array
</code></td>
<td class="name">
<a href="source-class-App.Http.Kernel.html#9-21" title="Go to source code"><var>$middleware</var></a>
<div class="description short">
<p>The application's global HTTP middleware stack.</p>
</div>
<div class="description detailed hidden">
<p>The application's global HTTP middleware stack.</p>
</div>
</td>
<td class="value">
<div>
<a href="#$middleware" class="anchor">#</a>
<code>[
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::<span class="php-keyword1">class</span>,
\App\Http\Middleware\EncryptCookies::<span class="php-keyword1">class</span>,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::<span class="php-keyword1">class</span>,
\Illuminate\Session\Middleware\StartSession::<span class="php-keyword1">class</span>,
\Illuminate\View\Middleware\ShareErrorsFromSession::<span class="php-keyword1">class</span>,
\App\Http\Middleware\VerifyCsrfToken::<span class="php-keyword1">class</span>,
]</code>
</div>
</td>
</tr>
<tr data-order="routeMiddleware" id="$routeMiddleware">
<td class="attributes"><code>
protected
array
</code></td>
<td class="name">
<a href="source-class-App.Http.Kernel.html#23-32" title="Go to source code"><var>$routeMiddleware</var></a>
<div class="description short">
<p>The application's route middleware.</p>
</div>
<div class="description detailed hidden">
<p>The application's route middleware.</p>
</div>
</td>
<td class="value">
<div>
<a href="#$routeMiddleware" class="anchor">#</a>
<code>[
<span class="php-quote">'auth'</span> => \App\Http\Middleware\Authenticate::<span class="php-keyword1">class</span>,
<span class="php-quote">'auth.basic'</span> => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::<span class="php-keyword1">class</span>,
<span class="php-quote">'guest'</span> => \App\Http\Middleware\RedirectIfAuthenticated::<span class="php-keyword1">class</span>,
]</code>
</div>
</td>
</tr>
</table>
</div>
<div id="footer">
API documentation generated by <a href="http://apigen.org">ApiGen</a>
</div>
</div>
</div>
<script src="resources/combined.js"></script>
<script src="elementlist.js"></script>
</body>
</html>
|
alexbonavila/Auth
|
docs/api/class-App.Http.Kernel.html
|
HTML
|
mit
| 5,465
|
/* Task Description */
/*
* Create an object domElement, that has the following properties and methods:
* use prototypal inheritance, without function constructors
* method init() that gets the domElement type
* i.e. `Object.create(domElement).init('div')`
* property type that is the type of the domElement
* a valid type is any non-empty string that contains only Latin letters and digits
* property innerHTML of type string
* gets the domElement, parsed as valid HTML
* <type attr1="value1" attr2="value2" ...> .. content / children's.innerHTML .. </type>
* property content of type string
* sets the content of the element
* works only if there are no children
* property attributes
* each attribute has name and value
* a valid attribute has a non-empty string for a name that contains only Latin letters and digits or dashes (-)
* property children
* each child is a domElement or a string
* property parent
* parent is a domElement
* method appendChild(domElement / string)
* appends to the end of children list
* method addAttribute(name, value)
* throw Error if type is not valid
* // method removeAttribute(attribute)
*/
/* Example
var meta = Object.create(domElement)
.init('meta')
.addAttribute('charset', 'utf-8');
var head = Object.create(domElement)
.init('head')
.appendChild(meta)
var div = Object.create(domElement)
.init('div')
.addAttribute('style', 'font-size: 42px');
div.content = 'Hello, world!';
var body = Object.create(domElement)
.init('body')
.appendChild(div)
.addAttribute('id', 'cuki')
.addAttribute('bgcolor', '#012345');
var root = Object.create(domElement)
.init('html')
.appendChild(head)
.appendChild(body);
console.log(root.innerHTML);
Outputs:
<html><head><meta charset="utf-8"></meta></head><body bgcolor="#012345" id="cuki"><div style="font-size: 42px">Hello, world!</div></body></html>
*/
function solve() {
var domElement = (function () {
var domElement = {};
function validateType(type){
if (type.match(/^[a-zA-Z0-9]+$/) === null){
throw new Error;
}
}
function validateAttributeName(type){
if (type.match(/^[a-zA-Z0-9\-]+$/) === null){
throw new Error;
}
}
Object.defineProperties(domElement,{
init: {
value: function (type) {
this.type = type;
this.attributes = [];
this.result = '';
this.isFromChild = false;
this.content = '';
this.parent = {};
this.children = [];
this.visited = false;
return this;
}
},
type: {
get: function () {
return this._type;
},
set: function (type) {
validateType(type);
this._type = type;
}
},
content: {
get: function () {
return this._content;
},
set: function (content) {
this._content = content;
}
},
parent:{
get: function () {
return this._parent;
},
set: function (parent) {
this._parent = parent;
}
},
visited: {
get: function () {
return this._visited;
},
set: function (value) {
this._visited = value;
}
},
appendChild:{
value: function (child) {
if (typeof child === "object") {
this.children.push(child);
child.parent = this;
} else {
this.children.push(child);
}
return this;
}
},
addAttribute: {
value: function (name, value) {
validateAttributeName(name);
if (this.attributes.length > 0) {
for (var attributeCheckCount = 0; attributeCheckCount < this.attributes.length; attributeCheckCount += 1) {
if (this.attributes[attributeCheckCount].attributeName === name) {
this.attributes.splice(attributeCheckCount, 1);
}
}
}
this.attributes.push({attributeName: name, attributeContent: value});
function compare(a, b) {
if (a.attributeName < b.attributeName)
return -1;
if (a.attributeName > b.attributeName)
return 1;
return 0;
}
this.attributes.sort(compare);
return this;
}
},
removeAttribute: {
value: function (attributeForRemoving) {
if (this.attributes.length > 0) {
for (var attributeCheckCount = 0; attributeCheckCount < this.attributes.length; attributeCheckCount += 1) {
if (this.attributes[attributeCheckCount].attributeName === attributeForRemoving) {
this.attributes.splice(attributeCheckCount, 1);
break;
}
if (attributeCheckCount === this.attributes.length - 1) {
throw new Error;
}
}
} else {
throw new Error;
}
return this;
}
},
innerHTML: {
get: function () {
var end = '',
obj = this,
front = '',
self = this, startObject = this;
obj.result = (function getText(currentObject) {
function getFront() {
front = front + '<' + currentObject.type
for (var attributeCounter = 0, len = currentObject.attributes.length; attributeCounter < len; attributeCounter += 1) {
front = front + ' ' + currentObject.attributes[attributeCounter].attributeName + '="' + currentObject.attributes[attributeCounter].attributeContent + '"';
}
front = front + '>';
return front;
}
if ((currentObject.visited === false &&
currentObject.children.length === 0)) {
front = getFront();
end = '</' + currentObject.type + '>' + end;
currentObject.result = front + currentObject.content + end;
//
front = '';
end = '';
currentObject.visited = true;
return currentObject.result;
} else {
for (var childrenCounter = 0, numberOfChildren = currentObject.children.length; childrenCounter < numberOfChildren; childrenCounter += 1) {
if (typeof currentObject.children[childrenCounter] === "object") {
currentObject.result = currentObject.result + getText(currentObject.children[childrenCounter]);
} else {
currentObject.result = currentObject.result + currentObject.children[childrenCounter];
}
if (childrenCounter === currentObject.children.length - 1) {
end = '</' + currentObject.type + '>' + end;
front = getFront();
currentObject.result = front + currentObject.result + end;
front = '';
end = '';
currentObject.visited = true;
return currentObject.result;
}
}
}
}(obj));
return obj.result;
}
}
});
return domElement;
} ());
return domElement;
}
module.exports = solve;
//var meta = Object.create(domElement)
// .init('meta')
// .addAttribute('charset', 'utf-8');
//
//var head = Object.create(domElement)
// .init('head')
// .appendChild(meta)
//
//var div = Object.create(domElement)
// .init('div')
// .addAttribute('style', 'font-size: 42px');
//
//div.content = 'Hello, world!';
//
//var body = Object.create(domElement)
// .init('body')
// .appendChild(div)
// .addAttribute('id', 'cuki')
// .addAttribute('bgcolor', '#012345');
//
//var root = Object.create(domElement)
// .init('html')
// .appendChild(head)
// .appendChild(body);
//
//
//console.log(root.innerHTML);
//
//it('expect correct HTML when having both string and domElement children', function() {
// var text = 'the text you SEE!',
// root = Object.create(domElement).init('p'),
// child1 = Object.create(domElement).init('b'),
// child2 = Object.create(domElement).init('s');
// root.appendChild(text);
// root.appendChild(child1);
// root.appendChild(text);
// root.appendChild(child2);
// root.appendChild(text);
// console.log(root.innerHTML)
//.to.eql('<p>' + text + '<b></b>' + text + '<s></s>' + text + '</p>');
//});
//Object.create(domElement).init('hi');
//Object.create(domElement).init('hello!');
|
tddold/Telerik-Academy-2
|
JavaScriptOOP/04.PrototypalOOP/tasks/task-1-2nd.js
|
JavaScript
|
mit
| 10,250
|
Person Type: {{PersonType}} <br />
Person Id: {{PersonId}}
|
Nitij/JsMvc
|
Source/JsMvc/JsMvc/Views/person.html
|
HTML
|
mit
| 61
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DLaB.Xrm.Entities
{
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")]
public enum ImportFile_StatusCode
{
[System.Runtime.Serialization.EnumMemberAttribute()]
Completed = 4,
[System.Runtime.Serialization.EnumMemberAttribute()]
Failed = 5,
[System.Runtime.Serialization.EnumMemberAttribute()]
Importing = 3,
[System.Runtime.Serialization.EnumMemberAttribute()]
Parsing = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
Submitted = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Transforming = 2,
}
}
|
daryllabar/XrmUnitTest
|
DLaB.Xrm.Entities/OptionSets/ImportFile_StatusCode.cs
|
C#
|
mit
| 1,014
|
#include "mlfe/operators/impl/cpu/broadcast.cc"
|
shi510/mlfe
|
mlfe/operators/impl/xnnpack/broadcast.cc
|
C++
|
mit
| 48
|
/*****************************************************************************
* This file is part of the Prolog Development Tool (PDT)
*
* WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start
* Mail: pdt@lists.iai.uni-bonn.de
* Copyright (C): 2004-2012, CS Dept. III, University of Bonn
*
* All rights reserved. This program is made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
****************************************************************************/
:- module(parse_util, [ generate_facts/1,
update_facts/2,
assert_new_node/4,
cleanup_nodes/0,
cleanup_nodes/1,
cleanup_computed_facts/0]).
:- reexport('pdt_factbase.pl').
:- ensure_loaded('util/walking_prolog_files.pl').
:- use_module(preparser).
:- use_module(predicates).
:- use_module(load_graph).
:- use_module(modules_and_visibility).
:- use_module(literal_parser).
:- use_module(cross_reference_builder).
generate_facts(Project):-
cleanup_nodes,
walking_file_list(Project,parse,1),
build_load_graph,
derive_all_predicates,
derive_directive_collections,
compute_all_predicate_properties,
compute_visibility_graph,
parse_bodies,
derive_edges.
%generate_facts(Project):-
% writeln('cleaning up'),
% cleanup_nodes,
% writeln('start parsing clauses'),
% time(walking_file_list(Project,parse,1)),
% writeln('generating loadgraph'),
% time(build_load_graph),
% writeln('generating predicates'),
% time(derive_all_predicates),
% writeln('genereating directive collections'),
% time(derive_directive_collections),
% writeln('compute_predicate_properties'),
% time(compute_all_predicate_properties),
% writeln('compute_visibilities'),
% time(compute_visibility_graph),
% writeln('parse literals'),
% time(parse_bodies),
% writeln('generate edges'),
% time(derive_edges).
update_facts(File, Project):-
cleanup_nodes(File),
cleanup_computed_facts,
walking_file_list([File|Project],parse,1),
build_load_graph,
derive_predicates_of_files([File|Project]),
derive_directive_collection_of_files([File|Project]),
compute_predicate_properties_for_files([File|Project]),
compute_visibility_graph,
parse_bodies,
derive_edges.
%update_facts(File, Project):-
% format('cleaning up facts for ~w~n',File),
% cleanup_nodes(File),
% cleanup_computed_facts,
% writeln('start parsing clauses'),
% time(walking_file_list(Project,parse,1)),
% writeln('generating loadgraph'),
% time(build_load_graph),
% writeln('generating predicates'),
% time(derive_all_predicates),
% writeln('genereating directive collections'),
% time(derive_onloads),
% writeln('compute_predicate_properties'),
% time(compute_all_predicate_properties),
% writeln('compute_visibilities'),
% time(compute_visibility_graph),
% writeln('parse literals'),
% time(parse_bodies),
% writeln('generate edges'),
% time(derive_edges).
/*
* cleanup_nodes/0 isdet
* retracts everything a former run of parse_util:generate_facts/1 could have asserted.
**/
cleanup_nodes:-
retractall(fileT(_,_,_)),
retractall(literalT(_,_,_,_,_,_)),
retractall(metaT(_,_,_,_,_,_)),
retractall(headT(_,_,_,_,_)),
retractall(clauseT(_,_,_,_,_)),
retractall(directiveT(_,_,_)),
retractall(operatorT(_,_,_,_,_,_,_,_)),
retractall(predicateT(_,_,_,_,_)),
retractall(onloadT(_,_,_)),
retractall(dynamicT(_,_)),
retractall(load_dir(_,_,_)),
retractall(import_dir(_,_)),
retractall(export_dir(_,_)),
retractall(library_dir(_,_,_)),
retractall(property_dir(_,_,_)),
retractall(transparentT(_,_)),
retractall(multifileT(_,_)),
retractall(meta_predT(_,_)),
retractall(termT(_,_)),
retractall(filePosT(_,_,_)),
retractall(literalT_ri(_,_,_,_)),
retractall(fileT_ri(_,_)),
retractall(predicateT_ri(_,_,_,_)),
retractall(pred_edge(_,_)),
retractall(onload_edge(_,_)),
retractall(pos_and_vars(_,_,_)),
retractall(error(_,_,_)),
retractall(warning(_,_,_)),
cleanup_computed_facts,
ctc_id_init_pdt.
cleanup_computed_facts:-
retractall(call_edge(_,_)),
retractall(load_edge(_,_,_,_)),
retractall(call_built_in(_,_,_,_)),
retractall(meta_predT(_,found)).
cleanup_nodes(File):-
fileT_ri(File,Id), !,
clean_file_entries(Id),
retractall(fileT_ri(File,Id)),
retractall(fileT(Id,_,_)),
retractall(error(_,_,Id)). %TODO: gegebenenfalls zu clean_general_references_to/1 schieben
cleanup_nodes(_).
clean_file_entries(FileId):-
directiveT(DirId,FileId,_),
termT(DirId,_),
clean_directives(DirId),
% retractall(directiveT(DirId,_,_)),
% retractall(import_dir(_,DirId)),
% retractall(export_dir(_,DirId)),
% retractall(load_dir(DirId,_,_)),
clean_general_references_to(DirId),
retractall(directiveT(DirId,_,_)),
fail.
clean_file_entries(FileId):-
clauseT(ClauseId,FileId,_,_,_),
clean_clause_references(ClauseId),
clean_general_references_to(ClauseId),
retractall(clauseT(ClauseId,_,_,_,_)),
fail.
clean_file_entries(FileId):-
predicateT(PredId,FileId,_,_,_),
retractall(predicateT(PredId,_,_,_,_)),
retractall(predicateT_ri(_,_,_,PredId)),
fail.
clean_file_entries(FileId):-
onloadT(Id,FileId,_),
retractall(onloadT(Id,_,_)),
fail.
clean_file_entries(_).
clean_clause_references(ClauseId):-
headT(HeadId,ClauseId,_,_,_),
clean_clause_references(HeadId),
retractall(headT(HeadId,_,_,_,_,_)),
fail.
clean_clause_references(ClauseId):-
literalT(LitId,_,ClauseId,_,_,_),
clean_clause_references(LitId),
retractall(literalT(LitId,_,ClauseId,M,F,A)),
retractall(literalT_ri(F,A,M,LitId)),
retractall(metaT(LitId,_,ClauseId,_,_,_)),
retractall(pred_edge(ClauseId,_)),
fail.
clean_clause_references(_).
clean_directives(DirectiveId):-
retractall(import_dir(_,DirectiveId)),
retractall(export_dir(_,DirectiveId)),
retractall(load_dir(DirectiveId,_,_)),
retractall(property_dir(DirectiveId,_,_)),
retractall(library_dir(_,_,DirectiveId)),
retractall(meta_pred(_,DirectiveId)),
retractall(onload_edge(DirectiveId,_)).
clean_general_references_to(Id):-
retractall(termT(Id,_)),
retractall(filePosT(Id,_,_)),
retractall(warning(Id,_,_)),
retractall(pos_and_vars(Id,_,_)).
/*
* assert_new_node(+Term,+From,+To,-Id)
* creates new identity Arg4 and asserts termT and filePosT with the information given
* by Arg1-Arg3 to this identity.
* the Arg6.
*/
assert_new_node(Term,From,To,Id):-
new_node_id_pdt(Id),
assert(termT(Id,Term)),
Length is To - From,
assert(filePosT(Id,From,Length)).
|
TeamSPoon/logicmoo_base
|
prolog/logicmoo/pdt_server/pdt.builder/prolog-src/parse_util.pl
|
Perl
|
mit
| 6,653
|
model_search = "http://api.nytimes.com/svc/search/v2/" + \
"articlesearch.response-format?" + \
"[q=search term&" + \
"fq=filter-field:(filter-term)&additional-params=values]" + \
"&api-key=9key"
"""http://api.nytimes.com/svc/search/v2/articlesearch.json?q=terrorism+OR+terrorist
&begin_date=19900102&end_date=19900103&sort=newest&api-key=
key"""
search = "http://api.nytimes.com/svc/search/v2/" + \
"articlesearch.json?" + \
"[q=terror]" + \
"&api-key=key"
precise_search = "http://api.nytimes.com/svc/search/v2/" + \
"articlesearch.json"
terms = "?q=terrorism+OR+terrorist"
api = "&api-key=key"
print(precise_search+terms+dates+api)
"""
aggressive for looping in order to overcome the ten article limit. instead search each key word PER JOUR, and then concat the jsons into a nice pandas dataframe, and then eventually a csv.
"""
months_list = ["%.2d" % i for i in range(1,2)]
days_list = ["%.2d" % i for i in range(1,32)]
json_files = []
print(months_list)
for x in months_list:
month_s = x
month_e = x
for y in days_list:
day_s = y
day_e = str(int(y)+1).zfill(2)
year_s = "1990"
year_e = "1990"
start = year_s + month_s + day_s
end = year_e + month_e + day_e
dates = "&begin_date="+start+"&end_date="+end+"&sort=newest"
#print(start + " "+end + "\n" +dates)
r = requests.get(precise_search+terms+dates+api)
original_json = json.loads(r.text)
response_json = original_json['response']
json_file = response_json['docs']
json_files.append(json_file)
frames = []
for x in json_files:
df = pd.DataFrame.from_dict(x)
frames.append(df)
#print(frames)
result = pd.concat(frames)
result
|
polypmer/scrape
|
new-york-times/nytimes-scrape.py
|
Python
|
mit
| 1,833
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
/**
* Represents a cookie.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class Cookie
{
public const SAMESITE_NONE = 'none';
public const SAMESITE_LAX = 'lax';
public const SAMESITE_STRICT = 'strict';
protected $name;
protected $value;
protected $domain;
protected $expire;
protected $path;
protected $secure;
protected $httpOnly;
private bool $raw;
private ?string $sameSite = null;
private bool $secureDefault = false;
private const RESERVED_CHARS_LIST = "=,; \t\r\n\v\f";
private const RESERVED_CHARS_FROM = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"];
private const RESERVED_CHARS_TO = ['%3D', '%2C', '%3B', '%20', '%09', '%0D', '%0A', '%0B', '%0C'];
/**
* Creates cookie from raw header string.
*/
public static function fromString(string $cookie, bool $decode = false): static
{
$data = [
'expires' => 0,
'path' => '/',
'domain' => null,
'secure' => false,
'httponly' => false,
'raw' => !$decode,
'samesite' => null,
];
$parts = HeaderUtils::split($cookie, ';=');
$part = array_shift($parts);
$name = $decode ? urldecode($part[0]) : $part[0];
$value = isset($part[1]) ? ($decode ? urldecode($part[1]) : $part[1]) : null;
$data = HeaderUtils::combine($parts) + $data;
$data['expires'] = self::expiresTimestamp($data['expires']);
if (isset($data['max-age']) && ($data['max-age'] > 0 || $data['expires'] > time())) {
$data['expires'] = time() + (int) $data['max-age'];
}
return new static($name, $value, $data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly'], $data['raw'], $data['samesite']);
}
public static function create(string $name, string $value = null, int|string|\DateTimeInterface $expire = 0, ?string $path = '/', string $domain = null, bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = self::SAMESITE_LAX): self
{
return new self($name, $value, $expire, $path, $domain, $secure, $httpOnly, $raw, $sameSite);
}
/**
* @param string $name The name of the cookie
* @param string|null $value The value of the cookie
* @param int|string|\DateTimeInterface $expire The time the cookie expires
* @param string $path The path on the server in which the cookie will be available on
* @param string|null $domain The domain that the cookie is available to
* @param bool|null $secure Whether the client should send back the cookie only over HTTPS or null to auto-enable this when the request is already using HTTPS
* @param bool $httpOnly Whether the cookie will be made accessible only through the HTTP protocol
* @param bool $raw Whether the cookie value should be sent with no url encoding
* @param string|null $sameSite Whether the cookie will be available for cross-site requests
*
* @throws \InvalidArgumentException
*/
public function __construct(string $name, string $value = null, int|string|\DateTimeInterface $expire = 0, ?string $path = '/', string $domain = null, bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = 'lax')
{
// from PHP source code
if ($raw && false !== strpbrk($name, self::RESERVED_CHARS_LIST)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name));
}
if (empty($name)) {
throw new \InvalidArgumentException('The cookie name cannot be empty.');
}
$this->name = $name;
$this->value = $value;
$this->domain = $domain;
$this->expire = self::expiresTimestamp($expire);
$this->path = empty($path) ? '/' : $path;
$this->secure = $secure;
$this->httpOnly = $httpOnly;
$this->raw = $raw;
$this->sameSite = $this->withSameSite($sameSite)->sameSite;
}
/**
* Creates a cookie copy with a new value.
*/
public function withValue(?string $value): static
{
$cookie = clone $this;
$cookie->value = $value;
return $cookie;
}
/**
* Creates a cookie copy with a new domain that the cookie is available to.
*/
public function withDomain(?string $domain): static
{
$cookie = clone $this;
$cookie->domain = $domain;
return $cookie;
}
/**
* Creates a cookie copy with a new time the cookie expires.
*/
public function withExpires(int|string|\DateTimeInterface $expire = 0): static
{
$cookie = clone $this;
$cookie->expire = self::expiresTimestamp($expire);
return $cookie;
}
/**
* Converts expires formats to a unix timestamp.
*/
private static function expiresTimestamp(int|string|\DateTimeInterface $expire = 0): int
{
// convert expiration time to a Unix timestamp
if ($expire instanceof \DateTimeInterface) {
$expire = $expire->format('U');
} elseif (!is_numeric($expire)) {
$expire = strtotime($expire);
if (false === $expire) {
throw new \InvalidArgumentException('The cookie expiration time is not valid.');
}
}
return 0 < $expire ? (int) $expire : 0;
}
/**
* Creates a cookie copy with a new path on the server in which the cookie will be available on.
*/
public function withPath(string $path): static
{
$cookie = clone $this;
$cookie->path = '' === $path ? '/' : $path;
return $cookie;
}
/**
* Creates a cookie copy that only be transmitted over a secure HTTPS connection from the client.
*/
public function withSecure(bool $secure = true): static
{
$cookie = clone $this;
$cookie->secure = $secure;
return $cookie;
}
/**
* Creates a cookie copy that be accessible only through the HTTP protocol.
*/
public function withHttpOnly(bool $httpOnly = true): static
{
$cookie = clone $this;
$cookie->httpOnly = $httpOnly;
return $cookie;
}
/**
* Creates a cookie copy that uses no url encoding.
*/
public function withRaw(bool $raw = true): static
{
if ($raw && false !== strpbrk($this->name, self::RESERVED_CHARS_LIST)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $this->name));
}
$cookie = clone $this;
$cookie->raw = $raw;
return $cookie;
}
/**
* Creates a cookie copy with SameSite attribute.
*/
public function withSameSite(?string $sameSite): static
{
if ('' === $sameSite) {
$sameSite = null;
} elseif (null !== $sameSite) {
$sameSite = strtolower($sameSite);
}
if (!\in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE, null], true)) {
throw new \InvalidArgumentException('The "sameSite" parameter value is not valid.');
}
$cookie = clone $this;
$cookie->sameSite = $sameSite;
return $cookie;
}
/**
* Returns the cookie as a string.
*/
public function __toString(): string
{
if ($this->isRaw()) {
$str = $this->getName();
} else {
$str = str_replace(self::RESERVED_CHARS_FROM, self::RESERVED_CHARS_TO, $this->getName());
}
$str .= '=';
if ('' === (string) $this->getValue()) {
$str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0';
} else {
$str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
if (0 !== $this->getExpiresTime()) {
$str .= '; expires='.gmdate('D, d-M-Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
}
}
if ($this->getPath()) {
$str .= '; path='.$this->getPath();
}
if ($this->getDomain()) {
$str .= '; domain='.$this->getDomain();
}
if (true === $this->isSecure()) {
$str .= '; secure';
}
if (true === $this->isHttpOnly()) {
$str .= '; httponly';
}
if (null !== $this->getSameSite()) {
$str .= '; samesite='.$this->getSameSite();
}
return $str;
}
/**
* Gets the name of the cookie.
*/
public function getName(): string
{
return $this->name;
}
/**
* Gets the value of the cookie.
*/
public function getValue(): ?string
{
return $this->value;
}
/**
* Gets the domain that the cookie is available to.
*/
public function getDomain(): ?string
{
return $this->domain;
}
/**
* Gets the time the cookie expires.
*/
public function getExpiresTime(): int
{
return $this->expire;
}
/**
* Gets the max-age attribute.
*/
public function getMaxAge(): int
{
$maxAge = $this->expire - time();
return 0 >= $maxAge ? 0 : $maxAge;
}
/**
* Gets the path on the server in which the cookie will be available on.
*/
public function getPath(): string
{
return $this->path;
}
/**
* Checks whether the cookie should only be transmitted over a secure HTTPS connection from the client.
*/
public function isSecure(): bool
{
return $this->secure ?? $this->secureDefault;
}
/**
* Checks whether the cookie will be made accessible only through the HTTP protocol.
*/
public function isHttpOnly(): bool
{
return $this->httpOnly;
}
/**
* Whether this cookie is about to be cleared.
*/
public function isCleared(): bool
{
return 0 !== $this->expire && $this->expire < time();
}
/**
* Checks if the cookie value should be sent with no url encoding.
*/
public function isRaw(): bool
{
return $this->raw;
}
/**
* Gets the SameSite attribute.
*/
public function getSameSite(): ?string
{
return $this->sameSite;
}
/**
* @param bool $default The default value of the "secure" flag when it is set to null
*/
public function setSecureDefault(bool $default): void
{
$this->secureDefault = $default;
}
}
|
OskarStark/symfony
|
src/Symfony/Component/HttpFoundation/Cookie.php
|
PHP
|
mit
| 11,145
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Javadoc API documentation for Fresco." />
<link rel="shortcut icon" type="image/x-icon" href="../../../../../favicon.ico" />
<title>
AnimatedDrawableFrameInfo - Fresco API
| Fresco
</title>
<link href="../../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />
<script src="../../../../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script>
<script src="../../../../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
setToRoot("../../../../../", "../../../../../../assets/");
</script>
<script src="../../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script>
<script src="../../../../../../assets/navtree_data.js" type="text/javascript"></script>
<script src="../../../../../../assets/customizations.js" type="text/javascript"></script>
<noscript>
<style type="text/css">
html,body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
</head>
<body class="">
<div id="header">
<div id="headerLeft">
<span id="masthead-title"><a href="../../../../../packages.html">Fresco</a></span>
</div>
<div id="headerRight">
<div id="search" >
<div id="searchForm">
<form accept-charset="utf-8" class="gsc-search-box"
onsubmit="return submit_search()">
<table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
<tr>
<td class="gsc-input">
<input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
title="search developer docs" name="q"
value="search developer docs"
onFocus="search_focus_changed(this, true)"
onBlur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../')" />
<div id="search_filtered_div" class="no-display">
<table id="search_filtered" cellspacing=0>
</table>
</div>
</td>
<!-- <td class="gsc-search-button">
<input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
</td>
<td class="gsc-clear-button">
<div title="clear results" class="gsc-clear-button"> </div>
</td> -->
</tr></tbody>
</table>
</form>
</div><!-- searchForm -->
</div><!-- search -->
</div>
</div><!-- header -->
<div class="g-section g-tpl-240" id="body-content">
<div class="g-unit g-first side-nav-resizable" id="side-nav">
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav">
<div id="index-links">
<a href="../../../../../packages.html" >Packages</a> |
<a href="../../../../../classes.html" >Classes</a>
</div>
<ul>
<li class="api apilevel-">
<a href="../../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/animated/giflite/package-summary.html">com.facebook.animated.giflite</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/animated/giflite/decoder/package-summary.html">com.facebook.animated.giflite.decoder</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/animated/giflite/draw/package-summary.html">com.facebook.animated.giflite.draw</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/animated/giflite/drawable/package-summary.html">com.facebook.animated.giflite.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/animated/webpdrawable/package-summary.html">com.facebook.animated.webpdrawable</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/callercontext/package-summary.html">com.facebook.callercontext</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/backends/pipeline/debug/package-summary.html">com.facebook.drawee.backends.pipeline.debug</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/backends/pipeline/info/package-summary.html">com.facebook.drawee.backends.pipeline.info</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/backends/pipeline/info/internal/package-summary.html">com.facebook.drawee.backends.pipeline.info.internal</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/debug/listener/package-summary.html">com.facebook.drawee.debug.listener</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/bitmap/preparation/package-summary.html">com.facebook.fresco.animation.bitmap.preparation</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/middleware/package-summary.html">com.facebook.fresco.middleware</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/ui/common/package-summary.html">com.facebook.fresco.ui.common</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li>
<li class="selected api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/debug/package-summary.html">com.facebook.imagepipeline.debug</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/drawable/package-summary.html">com.facebook.imagepipeline.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/filter/package-summary.html">com.facebook.imagepipeline.filter</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/instrumentation/package-summary.html">com.facebook.imagepipeline.instrumentation</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/multiuri/package-summary.html">com.facebook.imagepipeline.multiuri</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/systrace/package-summary.html">com.facebook.imagepipeline.systrace</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/transcoder/package-summary.html">com.facebook.imagepipeline.transcoder</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/transformation/package-summary.html">com.facebook.imagepipeline.transformation</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li>
</ul><br/>
</div> <!-- end packages -->
</div> <!-- end resize-packages -->
<div id="classes-nav">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableBackend.html">AnimatedDrawableBackend</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedImage.html">AnimatedImage</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedImageFrame.html">AnimatedImageFrame</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="selected api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html">AnimatedDrawableFrameInfo</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableOptions.html">AnimatedDrawableOptions</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableOptionsBuilder.html">AnimatedDrawableOptionsBuilder</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedImageResult.html">AnimatedImageResult</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedImageResultBuilder.html">AnimatedImageResultBuilder</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/DelegatingAnimatedDrawableBackend.html">DelegatingAnimatedDrawableBackend</a></li>
</ul>
</li>
<li><h2>Enums</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.BlendOperation.html">AnimatedDrawableFrameInfo.BlendOperation</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.DisposalMethod.html">AnimatedDrawableFrameInfo.DisposalMethod</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none">
<div id="index-links">
<a href="../../../../../packages.html" >Packages</a> |
<a href="../../../../../classes.html" >Classes</a>
</div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
</div> <!-- end side-nav -->
<script>
if (!isMobile) {
//$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav");
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../");
} else {
addLoadEvent(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
}
//$("#swapper").css({borderBottom:"2px solid #aaa"});
} else {
swapNav(); // tree view should be used on mobile
}
</script>
<div class="g-unit" id="doc-content">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#nestedclasses">Nested Classes</a>
| <a href="#lfields">Fields</a>
| <a href="#pubctors">Ctors</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
class
<h1>AnimatedDrawableFrameInfo</h1>
extends Object<br/>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell">java.lang.Object</td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.facebook.imagepipeline.animated.base.AnimatedDrawableFrameInfo</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p>Info per frame returned by <code><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableBackend.html">AnimatedDrawableBackend</a></code>. </p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- ======== NESTED CLASS SUMMARY ======== -->
<table id="nestedclasses" class="jd-sumtable"><tr><th colspan="12">Nested Classes</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
enum</td>
<td class="jd-linkcol"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.BlendOperation.html">AnimatedDrawableFrameInfo.BlendOperation</a></td>
<td class="jd-descrcol" width="100%">Indicates how transparent pixels of the current frame are blended with those of the previous
canvas. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
enum</td>
<td class="jd-linkcol"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.DisposalMethod.html">AnimatedDrawableFrameInfo.DisposalMethod</a></td>
<td class="jd-descrcol" width="100%">How to dispose of the current frame before rendering the next frame. </td>
</tr>
</table>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
public
final
<a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.BlendOperation.html">AnimatedDrawableFrameInfo.BlendOperation</a></td>
<td class="jd-linkcol"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html#blendOperation">blendOperation</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
public
final
<a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.DisposalMethod.html">AnimatedDrawableFrameInfo.DisposalMethod</a></td>
<td class="jd-linkcol"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html#disposalMethod">disposalMethod</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
public
final
int</td>
<td class="jd-linkcol"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html#frameNumber">frameNumber</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
public
final
int</td>
<td class="jd-linkcol"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html#height">height</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
public
final
int</td>
<td class="jd-linkcol"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html#width">width</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
public
final
int</td>
<td class="jd-linkcol"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html#xOffset">xOffset</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
public
final
int</td>
<td class="jd-linkcol"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html#yOffset">yOffset</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html#AnimatedDrawableFrameInfo(int, int, int, int, int, com.facebook.imagepipeline.animated.base.AnimatedDrawableFrameInfo.BlendOperation, com.facebook.imagepipeline.animated.base.AnimatedDrawableFrameInfo.DisposalMethod)">AnimatedDrawableFrameInfo</a></span>(int frameNumber, int xOffset, int yOffset, int width, int height, <a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.BlendOperation.html">AnimatedDrawableFrameInfo.BlendOperation</a> blendOperation, <a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.DisposalMethod.html">AnimatedDrawableFrameInfo.DisposalMethod</a> disposalMethod)
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
java.lang.Object
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Object
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">clone</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">equals</span>(Object arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">finalize</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
Class<?>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getClass</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">hashCode</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notify</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notifyAll</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
String
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">toString</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0, int arg1)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>()
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- ========= FIELD DETAIL ======== -->
<h2>Fields</h2>
<a id="blendOperation"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
final
<a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.BlendOperation.html">AnimatedDrawableFrameInfo.BlendOperation</a>
</span>
blendOperation
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="disposalMethod"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
final
<a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.DisposalMethod.html">AnimatedDrawableFrameInfo.DisposalMethod</a>
</span>
disposalMethod
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="frameNumber"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
final
int
</span>
frameNumber
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="height"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
final
int
</span>
height
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="width"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
final
int
</span>
width
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="xOffset"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
final
int
</span>
xOffset
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="yOffset"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
final
int
</span>
yOffset
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2>Public Constructors</h2>
<a id="AnimatedDrawableFrameInfo(int, int, int, int, int, com.facebook.imagepipeline.animated.base.AnimatedDrawableFrameInfo.BlendOperation, com.facebook.imagepipeline.animated.base.AnimatedDrawableFrameInfo.DisposalMethod)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">AnimatedDrawableFrameInfo</span>
<span class="normal">(int frameNumber, int xOffset, int yOffset, int width, int height, <a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.BlendOperation.html">AnimatedDrawableFrameInfo.BlendOperation</a> blendOperation, <a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.DisposalMethod.html">AnimatedDrawableFrameInfo.DisposalMethod</a> disposalMethod)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<a id="navbar_top"></a>
<div id="footer">
+Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>.
+</div> <!-- end footer - @generated -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script type="text/javascript">
init(); /* initialize doclava-developer-docs.js */
</script>
</body>
</html>
|
facebook/fresco
|
docs/javadoc/reference/com/facebook/imagepipeline/animated/base/AnimatedDrawableFrameInfo.html
|
HTML
|
mit
| 37,011
|
# This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from flask import session
from indico.core.db import db
from indico.modules.events.logs import EventLogKind, EventLogRealm
from indico.modules.events.tracks import logger
from indico.modules.events.tracks.models.groups import TrackGroup
from indico.modules.events.tracks.models.tracks import Track
from indico.modules.events.tracks.settings import track_settings
def create_track(event, data):
track = Track(event=event)
track.populate_from_dict(data)
db.session.flush()
logger.info('Track %r created by %r', track, session.user)
event.log(EventLogRealm.management, EventLogKind.positive, 'Tracks',
'Track "{}" has been created.'.format(track.title), session.user)
return track
def update_track(track, data):
track.populate_from_dict(data)
db.session.flush()
logger.info('Track %r modified by %r', track, session.user)
track.event.log(EventLogRealm.management, EventLogKind.change, 'Tracks',
'Track "{}" has been modified.'.format(track.title), session.user)
def delete_track(track):
db.session.delete(track)
logger.info('Track deleted by %r: %r', session.user, track)
def update_program(event, data):
track_settings.set_multi(event, data)
logger.info('Program of %r updated by %r', event, session.user)
event.log(EventLogRealm.management, EventLogKind.change, 'Tracks', 'The program has been updated', session.user)
def create_track_group(event, data):
track_group = TrackGroup()
track_group.event = event
track_group.populate_from_dict(data)
db.session.flush()
logger.info('Track group %r created by %r', track_group, session.user)
event.log(EventLogRealm.management, EventLogKind.positive, 'Track Groups',
'Track group "{}" has been created.'.format(track_group.title), session.user)
def update_track_group(track_group, data):
track_group.populate_from_dict(data)
db.session.flush()
logger.info('Track group %r updated by %r', track_group, session.user)
track_group.event.log(EventLogRealm.management, EventLogKind.positive, 'Track Groups',
'Track group "{}" has been updated.'.format(track_group.title), session.user)
def delete_track_group(track_group):
db.session.delete(track_group)
logger.info('Track group deleted by %r: %r', session.user, track_group)
|
mvidalgarcia/indico
|
indico/modules/events/tracks/operations.py
|
Python
|
mit
| 2,614
|
#include <io.h>
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
#define read(...) _read(__VA_ARGS__)
#define write(...) _write(__VA_ARGS__)
#define isatty(...) _isatty(__VA_ARGS__)
|
LIJI32/SameBoy
|
Windows/unistd.h
|
C
|
mit
| 205
|
/**
* 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.
*
* @flow
* @format
*/
'use strict';
const readRelayQueryData = require('../../store/readRelayQueryData');
const warning = require('warning');
const {recycleNodesInto, RelayProfiler} = require('relay-runtime');
import type RelayQuery from '../../query/RelayQuery';
import type RelayStoreData from '../../store/RelayStoreData';
import type {ChangeSubscription, StoreReaderData} from '../../tools/RelayTypes';
import type {DataID} from 'relay-runtime';
type DataIDSet = {[dataID: DataID]: any};
/**
* @internal
*
* Resolves data from fragment pointers.
*
* The supplied `callback` will be invoked whenever data returned by the last
* invocation to `resolve` has changed.
*/
class GraphQLStoreQueryResolver {
_callback: Function;
_fragment: RelayQuery.Fragment;
_resolver: ?(
| GraphQLStorePluralQueryResolver
| GraphQLStoreSingleQueryResolver
);
_storeData: RelayStoreData;
constructor(
storeData: RelayStoreData,
fragment: RelayQuery.Fragment,
callback: Function,
) {
this.dispose();
this._callback = callback;
this._fragment = fragment;
this._resolver = null;
this._storeData = storeData;
}
/**
* disposes the resolver's internal state such that future `resolve()` results
* will not be `===` to previous results, and unsubscribes any subscriptions.
*/
dispose(): void {
if (this._resolver) {
this._resolver.dispose();
}
}
resolve(
fragment: RelayQuery.Fragment,
dataIDs: DataID | Array<DataID>,
): ?(StoreReaderData | Array<?StoreReaderData>) {
// Warn but don't crash if resolved with the wrong fragment.
if (
this._fragment.getConcreteFragmentID() !==
fragment.getConcreteFragmentID()
) {
warning(
false,
'GraphQLStoreQueryResolver: Expected `resolve` to be called with the ' +
'same concrete fragment as the constructor. The resolver was created ' +
'with fragment `%s` but resolved with fragment `%s`.',
this._fragment.getDebugName(),
fragment.getDebugName(),
);
}
// Rather than crash on mismatched plurality of fragment/ids just warn
// and resolve as if the fragment's pluarity matched the format of the ids.
// Note that the inverse - attempt to resolve based on fragment plurarity -
// doesn't work because there's no way convert plural ids to singular w/o
// losing data.
if (Array.isArray(dataIDs)) {
// Fragment should be plural if data is pluaral.
warning(
fragment.isPlural(),
'GraphQLStoreQueryResolver: Expected id/fragment plurality to be ' +
'consistent: got plural ids for singular fragment `%s`.',
fragment.getDebugName(),
);
let resolver = this._resolver;
if (resolver instanceof GraphQLStoreSingleQueryResolver) {
resolver.dispose();
resolver = null;
}
if (!resolver) {
resolver = new GraphQLStorePluralQueryResolver(
this._storeData,
this._callback,
);
}
this._resolver = resolver;
return resolver.resolve(fragment, dataIDs);
} else {
// Fragment should be singular if data is singular.
warning(
!fragment.isPlural(),
'GraphQLStoreQueryResolver: Expected id/fragment plurality to be ' +
'consistent: got a singular id for plural fragment `%s`.',
fragment.getDebugName(),
);
let resolver = this._resolver;
if (resolver instanceof GraphQLStorePluralQueryResolver) {
resolver.dispose();
resolver = null;
}
if (!resolver) {
resolver = new GraphQLStoreSingleQueryResolver(
this._storeData,
this._callback,
);
}
this._resolver = resolver;
return resolver.resolve(fragment, dataIDs);
}
}
}
/**
* Resolves plural fragments.
*/
class GraphQLStorePluralQueryResolver {
_callback: Function;
_resolvers: Array<GraphQLStoreSingleQueryResolver>;
_results: Array<?StoreReaderData>;
_storeData: RelayStoreData;
constructor(storeData: RelayStoreData, callback: Function) {
this.dispose();
this._callback = callback;
this._storeData = storeData;
}
dispose(): void {
if (this._resolvers) {
this._resolvers.forEach(resolver => resolver.dispose());
}
this._resolvers = [];
this._results = [];
}
/**
* Resolves a plural fragment pointer into an array of records.
*
* If the data, order, and number of resolved records has not changed since
* the last call to `resolve`, the same array will be returned. Otherwise, a
* new array will be returned.
*/
resolve(
fragment: RelayQuery.Fragment,
nextIDs: Array<DataID>,
): Array<?StoreReaderData> {
const prevResults = this._results;
let nextResults;
const prevLength = prevResults.length;
const nextLength = nextIDs.length;
const resolvers = this._resolvers;
// Ensure that we have exactly `nextLength` resolvers.
while (resolvers.length < nextLength) {
resolvers.push(
new GraphQLStoreSingleQueryResolver(this._storeData, this._callback),
);
}
while (resolvers.length > nextLength) {
resolvers.pop().dispose();
}
// Allocate `nextResults` if and only if results have changed.
if (prevLength !== nextLength) {
nextResults = [];
}
for (let ii = 0; ii < nextLength; ii++) {
const nextResult = resolvers[ii].resolve(fragment, nextIDs[ii]);
if (nextResults || ii >= prevLength || nextResult !== prevResults[ii]) {
nextResults = nextResults || prevResults.slice(0, ii);
nextResults.push(nextResult);
}
}
if (nextResults) {
this._results = nextResults;
}
return this._results;
}
}
/**
* Resolves non-plural fragments.
*/
class GraphQLStoreSingleQueryResolver {
_callback: Function;
_fragment: ?RelayQuery.Fragment;
_hasDataChanged: boolean;
_result: ?StoreReaderData;
_resultID: ?DataID;
_storeData: RelayStoreData;
_subscribedIDs: DataIDSet;
_subscription: ?ChangeSubscription;
constructor(storeData: RelayStoreData, callback: Function) {
this.dispose();
this._callback = callback;
this._storeData = storeData;
this._subscribedIDs = {};
}
dispose(): void {
if (this._subscription) {
this._subscription.remove();
}
this._hasDataChanged = false;
this._fragment = null;
this._result = null;
this._resultID = null;
this._subscription = null;
this._subscribedIDs = {};
}
/**
* Resolves data for a single fragment pointer.
*/
resolve(nextFragment: RelayQuery.Fragment, nextID: DataID): ?StoreReaderData {
const prevFragment = this._fragment;
const prevID = this._resultID;
let nextResult;
const prevResult = this._result;
let subscribedIDs;
if (
prevFragment != null &&
prevID != null &&
this._getCanonicalID(prevID) === this._getCanonicalID(nextID)
) {
if (
prevID !== nextID ||
this._hasDataChanged ||
!nextFragment.isEquivalent(prevFragment)
) {
// same canonical ID,
// but the data, call(s), route, and/or variables have changed
[nextResult, subscribedIDs] = this._resolveFragment(
nextFragment,
nextID,
);
nextResult = recycleNodesInto(prevResult, nextResult);
} else {
// same id, route, variables, and data
nextResult = prevResult;
}
} else {
// Pointer has a different ID or is/was fake data.
[nextResult, subscribedIDs] = this._resolveFragment(nextFragment, nextID);
}
// update subscriptions whenever results change
if (prevResult !== nextResult) {
if (this._subscription) {
this._subscription.remove();
this._subscription = null;
}
if (subscribedIDs) {
// always subscribe to the root ID
subscribedIDs[nextID] = true;
const changeEmitter = this._storeData.getChangeEmitter();
this._subscription = changeEmitter.addListenerForIDs(
Object.keys(subscribedIDs),
this._handleChange.bind(this),
);
this._subscribedIDs = subscribedIDs;
}
this._resultID = nextID;
this._result = nextResult;
}
this._hasDataChanged = false;
this._fragment = nextFragment;
return this._result;
}
/**
* Ranges publish events for the entire range, not the specific view of that
* range. For example, if "client:1" is a range, the event is on "client:1",
* not "client:1_first(5)".
*/
_getCanonicalID(id: DataID): DataID {
return this._storeData.getRangeData().getCanonicalClientID(id);
}
_handleChange(): void {
if (!this._hasDataChanged) {
this._hasDataChanged = true;
this._callback();
}
}
_resolveFragment(
fragment: RelayQuery.Fragment,
dataID: DataID,
): [?StoreReaderData, DataIDSet] {
const {data, dataIDs} = readRelayQueryData(
this._storeData,
fragment,
dataID,
);
return [data, dataIDs];
}
}
RelayProfiler.instrumentMethods(GraphQLStoreQueryResolver.prototype, {
resolve: 'GraphQLStoreQueryResolver.resolve',
});
module.exports = GraphQLStoreQueryResolver;
|
dbslone/relay
|
packages/react-relay/classic/legacy/store/GraphQLStoreQueryResolver.js
|
JavaScript
|
mit
| 9,474
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>nodejs™ console </title>
<link rel="stylesheet" rev="stylesheet" media="all" type="text/css" href="style.css" />
<link rel="stylesheet" rev="stylesheet" media="all" type="text/css" href="./fonts/stylesheet.css" />
<link rel="stylesheet" rev="stylesheet" media="all" type="text/css" href="style.light.css" />
<link rel="stylesheet" rev="stylesheet" media="all" type="text/css" href="style.dark.css" id="dark_ui" />
<link rel="icon" type="image/vnd.microsoft.icon" href="./images/favicon.ico"/>
<link rel="shortcut icon" type="image/x-icon" href="./images/favicon.ico"/>
<script type="text/javascript" src="libraries/jq.js"></script>
<script type="text/javascript" src="libraries/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" src="libraries/jq.cookie.js"></script>
<script type="text/javascript" src="libraries/jq.hotkeys.js"></script>
<script type="text/javascript" src="libraries/jq.tabby.js"></script>
<script type="text/javascript" src="libraries/jq.unsel.js"></script>
<script type="text/javascript" src="libraries/jq.storage.js"></script>
<script type="text/javascript" src="libraries/dragscrollable.js"></script>
<script type="text/javascript" src="scripts/localtree.js"></script>
<script type="text/javascript" src="scripts/history.js"></script>
<script type="text/javascript" src="scripts/sse.js"></script>
<script type="text/javascript" src="scripts/suggest.js"></script>
<script type="text/javascript" src="scripts/console.js"></script>
<script type="text/javascript" src="scripts/tools.js"></script>
</head>
<body>
<div class="tool">
<a class="nosel">nodejs™ console</a>
<b class="r"><a target="_blank" title="nodejs on twitter" href="http://www.twitter.com/nodejs">t</a></b>
<b class="r"><a target="_blank" title="nodejs manual" href="http://yand.info/"><small>H</small></a></b>
<a class="r nosel"> </a>
<a class="r t_dark_ui">Dark</a>
<a class="r t_light_ui">Light</a>
<a class="r nosel"> </a>
<a class="r iScroll" title="Dragging will scroll">Panning</a>
</div>
<div id="wrap">
<div id="output_wrappr"><div id="output_viewer"></div></div>
<div id="formwrap"><form method="post" action="/" id="inp_form">
<span id="commandhint">Don't know what to do? Type `global` and hit Enter.</span>
<textarea name="command" id="command"></textarea>
<div class="sugpos"></div>
<span id="cursor">></span>
</form></div>
</div>
<div class="tool tool-bottom">
<b class="show-write-area" title="Show / hide console input">_</b>
<b class="clear-console" title="Clear all messages">×</b>
<b class="autoexpand" title="Expand object roots automatically"><small>³</small></b>
<b class="dotstruct" title="Highlight hovered object members"><small>p</small></b>
<b class="preserve" title="Preserve input when sending commands">w</b>
<a class="nosel constat"> <span class="eicon">W</span> <span class="msg">Disconnected</span></a>
<b class="r new-window" title="Duplicate current console window"><small>D</small></b>
<b class="r reload" title="Refresh console window">V</b>
<a class="r collapse-all " title="Collapse all objects' properties">Collapse all</a>
<a class="r expand-all" title="Expand all objects' properties">Expand all</a>
</div>
</body>
</html>
|
Silviu-Marian/node-codein
|
src/client/index.html
|
HTML
|
mit
| 3,523
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<title>mersocarlin-template Demo</title>
</head>
<body>
<div id="main"></div>
<script type="text/javascript" src="cordova.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.2/react.js"></script>
<script src="./build/phonegap-upload.js"></script>
</body>
</html>
|
mersocarlin/phonegap-upload
|
hybrid/PhonegapUpload/www/index.html
|
HTML
|
mit
| 797
|
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Test\Unit\Model\Service;
/**
* Class OrderUnHoldTest
*/
class OrderServiceTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Sales\Model\Service\OrderService
*/
protected $orderService;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\OrderRepositoryInterface
*/
protected $orderRepositoryMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\OrderStatusHistoryRepositoryInterface
*/
protected $orderStatusHistoryRepositoryMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\SearchCriteriaBuilder
*/
protected $searchCriteriaBuilderMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\SearchCriteria
*/
protected $searchCriteriaMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\FilterBuilder
*/
protected $filterBuilderMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\Filter
*/
protected $filterMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\OrderNotifier
*/
protected $orderNotifierMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order
*/
protected $orderMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order\Status\History
*/
protected $orderStatusHistoryMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\Data\OrderStatusHistorySearchResultInterface
*/
protected $orderSearchResultMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event\ManagerInterface
*/
protected $eventManagerMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order\Email\Sender\OrderCommentSender
*/
protected $orderCommentSender;
protected function setUp()
{
$this->orderRepositoryMock = $this->getMockBuilder(
'Magento\Sales\Api\OrderRepositoryInterface'
)
->disableOriginalConstructor()
->getMock();
$this->orderStatusHistoryRepositoryMock = $this->getMockBuilder(
'Magento\Sales\Api\OrderStatusHistoryRepositoryInterface'
)
->disableOriginalConstructor()
->getMock();
$this->searchCriteriaBuilderMock = $this->getMockBuilder(
'Magento\Framework\Api\SearchCriteriaBuilder'
)
->disableOriginalConstructor()
->getMock();
$this->searchCriteriaMock = $this->getMockBuilder(
'Magento\Framework\Api\SearchCriteria'
)
->disableOriginalConstructor()
->getMock();
$this->filterBuilderMock = $this->getMockBuilder(
'Magento\Framework\Api\FilterBuilder'
)
->disableOriginalConstructor()
->getMock();
$this->filterMock = $this->getMockBuilder(
'Magento\Framework\Api\Filter'
)
->disableOriginalConstructor()
->getMock();
$this->orderNotifierMock = $this->getMockBuilder(
'Magento\Sales\Model\OrderNotifier'
)
->disableOriginalConstructor()
->getMock();
$this->orderMock = $this->getMockBuilder(
'Magento\Sales\Model\Order'
)
->disableOriginalConstructor()
->getMock();
$this->orderStatusHistoryMock = $this->getMockBuilder(
'Magento\Sales\Model\Order\Status\History'
)
->disableOriginalConstructor()
->getMock();
$this->orderSearchResultMock = $this->getMockBuilder(
'Magento\Sales\Api\Data\OrderStatusHistorySearchResultInterface'
)
->disableOriginalConstructor()
->getMock();
$this->eventManagerMock = $this->getMockBuilder(
'Magento\Framework\Event\ManagerInterface'
)
->disableOriginalConstructor()
->getMock();
$this->orderCommentSender = $this->getMockBuilder(
'Magento\Sales\Model\Order\Email\Sender\OrderCommentSender'
)
->disableOriginalConstructor()
->getMock();
$this->orderService = new \Magento\Sales\Model\Service\OrderService(
$this->orderRepositoryMock,
$this->orderStatusHistoryRepositoryMock,
$this->searchCriteriaBuilderMock,
$this->filterBuilderMock,
$this->orderNotifierMock,
$this->eventManagerMock,
$this->orderCommentSender
);
}
/**
* test for Order::cancel()
*/
public function testCancel()
{
$this->orderRepositoryMock->expects($this->once())
->method('get')
->with(123)
->willReturn($this->orderMock);
$this->orderMock->expects($this->once())
->method('cancel')
->willReturn($this->orderMock);
$this->assertTrue($this->orderService->cancel(123));
}
public function testGetCommentsList()
{
$this->filterBuilderMock->expects($this->once())
->method('setField')
->with('parent_id')
->willReturnSelf();
$this->filterBuilderMock->expects($this->once())
->method('setValue')
->with(123)
->willReturnSelf();
$this->filterBuilderMock->expects($this->once())
->method('setConditionType')
->with('eq')
->willReturnSelf();
$this->filterBuilderMock->expects($this->once())
->method('create')
->willReturn($this->filterMock);
$this->searchCriteriaBuilderMock->expects($this->once())
->method('addFilters')
->with([$this->filterMock])
->willReturn($this->filterBuilderMock);
$this->searchCriteriaBuilderMock->expects($this->once())
->method('create')
->willReturn($this->searchCriteriaMock);
$this->orderStatusHistoryRepositoryMock->expects($this->once())
->method('getList')
->with($this->searchCriteriaMock)
->willReturn($this->orderSearchResultMock);
$this->assertEquals($this->orderSearchResultMock, $this->orderService->getCommentsList(123));
}
public function testAddComment()
{
$clearComment = "Comment text here...";
$this->orderRepositoryMock->expects($this->once())
->method('get')
->with(123)
->willReturn($this->orderMock);
$this->orderMock->expects($this->once())
->method('addStatusHistory')
->with($this->orderStatusHistoryMock)
->willReturn($this->orderMock);
$this->orderStatusHistoryMock->expects($this->once())
->method('getComment')
->willReturn("<h1>" . $clearComment);
$this->orderRepositoryMock->expects($this->once())
->method('save')
->with($this->orderMock)
->willReturn([]);
$this->orderCommentSender->expects($this->once())
->method('send')
->with($this->orderMock, false, $clearComment);
$this->assertTrue($this->orderService->addComment(123, $this->orderStatusHistoryMock));
}
public function testNotify()
{
$this->orderRepositoryMock->expects($this->once())
->method('get')
->with(123)
->willReturn($this->orderMock);
$this->orderNotifierMock->expects($this->once())
->method('notify')
->with($this->orderMock)
->willReturn(true);
$this->assertTrue($this->orderService->notify(123));
}
public function testGetStatus()
{
$this->orderRepositoryMock->expects($this->once())
->method('get')
->with(123)
->willReturn($this->orderMock);
$this->orderMock->expects($this->once())
->method('getStatus')
->willReturn('test-status');
$this->assertEquals('test-status', $this->orderService->getStatus(123));
}
public function testHold()
{
$this->orderRepositoryMock->expects($this->once())
->method('get')
->with(123)
->willReturn($this->orderMock);
$this->orderRepositoryMock->expects($this->once())
->method('save')
->with($this->orderMock)
->willReturn($this->orderMock);
$this->orderMock->expects($this->once())
->method('hold')
->willReturn($this->orderMock);
$this->assertTrue($this->orderService->hold(123));
}
public function testUnHold()
{
$this->orderRepositoryMock->expects($this->once())
->method('get')
->with(123)
->willReturn($this->orderMock);
$this->orderRepositoryMock->expects($this->once())
->method('save')
->with($this->orderMock)
->willReturn($this->orderMock);
$this->orderMock->expects($this->once())
->method('unHold')
->willReturn($this->orderMock);
$this->assertTrue($this->orderService->unHold(123));
}
}
|
j-froehlich/magento2_wk
|
vendor/magento/module-sales/Test/Unit/Model/Service/OrderServiceTest.php
|
PHP
|
mit
| 9,539
|
# ProgressiveRender [](http://badge.fury.io/rb/progressive_render) #

Slow content got you down? Load it later! Use this gem to defer loading of portions of your page until after load. They will be fetched via AJAX and placed on the page when ready.
For a quick start, see [Drifting Ruby #033 - Progressive Render](https://www.driftingruby.com/episodes/progressive-render) based on version 0.3.0. Note the controller changes are no longer required in 0.4.0.
## Why? ##
You wrote all your code and it got a bit slow with all that production data. Or perhaps you have less important content that you want on the view, but it's not worth blocking the entire page for. With this gem there's almost no developer work to make this happen. All requests go through your controller and your normal filters so you're permissions are respected. The only added overhead is an additional round-trip for each partial and duplicated rendering of the main view.
## State of Project ##
[](https://travis-ci.org/johnsonj/progressive_render) [](https://codeclimate.com/github/johnsonj/progressive_load) [](https://codeclimate.com/github/johnsonj/progressive_load/coverage)
This gem follows semantic versioning. The important part of that being the API will not make breaking changes except for major version numbers. Please use released versions via RubyGems for production applications. Old versions do not have a maintenance plan. [See open issues](https://github.com/johnsonj/progressive_render/issues). Report any issues you have!
## Installation ##
Add this line to your application's Gemfile and run `bundle install`
```ruby
gem 'progressive_render'
```
Then add the following to your `application.js`:
```javascript
//= require progressive_render
```
If you plan on using the default placeholder, add this to your `application.css`:
```css
/*
*= require progressive_render
*/
```
## Basic Usage ##
Wrap slow content in your view with a call to `progressive_render`:
```erb
<%=progressive_render do %>
<h1>Content!</h1>
<% sleep 5 %>
<% end %>
```
## Example Application ##
For a more in-depth example, see the test application located within this repository in `spec/dummy`
## Customizing the Placeholder ##
Each `progressive_render` call in the view can specify its own placeholder by providing a path to the partial you'd like to initially display to the user:
```erb
<%=progressive_render placeholder: 'shared/loading' do %>
<h1>Content!</h1>
<% sleep 5 %>
<% end %>
```
The placeholder defaults to rendering the partial `progressive_render/placeholder` so if you'd like to override it globally create the file `app/views/progressive_render/_placeholder.html.erb`. It will also work at the controller level, eg, `app/views/users/progressive_render/_placeholder.html.erb`
## Development ##
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rspec` to run the tests. There is a dummy application located in `spec/dummy/` that demonstrates a sample integration and can be used for interactive testing.
## CI Environment ##
Travis.ci is used to validate changes to the github project. The CI build runs the gem against multiple versions of rails/ruby. When making a change to any dependencies or the version number of the application, be sure to run `appraisal` to update the dependent Gemfile.locks.
## Contributing ##
Bug reports and pull requests are welcome on [GitHub](https://github.com/johnsonj/progressive_render). Any contribution should not decrease test coverage significantly. Please feel free to [reach out](johnsonjeff@gmail.com) if you have an issues contributing.
## Release Process ##
```bash
gem install gem-release
gem bump --version [major, minor, patch]
cd spec/dummy
bundle install
cd ../../
appraisal install
git add spec/dummy/Gemfile.lock
git add gemfiles/*.lock
git commit -am "Bumping collateral for new gem version"
gem release --tag
```
## License ##
[MIT License](http://opensource.org/licenses/MIT).
|
johnsonj/progressive_load
|
README.md
|
Markdown
|
mit
| 4,373
|
package models
import java.util.{ Date }
import play.api.db._
import play.api.Play.current
import anorm._
import anorm.SqlParser._
case class Tag(id: Pk[Long] = NotAssigned, name: String, added: Date, enabled: Boolean, tuid: String)
object Tag {
/* A pretty ugly way to keep some sort of "haschanged" discriminator for the lock when looking for new data */
@volatile var revision = 1
def increaseRevision() = {
if(revision >= 100) {
revision = 1
} else revision = revision+1
}
// -- Parsers
/**
* Parse an Entry from a ResultSet
*/
val simple = {
get[Pk[Long]]("tag.id") ~
get[String]("tag.name") ~
get[Date]("tag.added") ~
get[Boolean]("tag.enabled") ~
get[String]("tag.tuid") map {
case id ~ name ~ added ~ enabled ~ tuid => Tag(id, name, added, enabled, tuid)
}
}
// -- Queries
def defaultTag = Tag.findById(1).get
/**
* Retrieve a tag from the id.
*/
def findById(id: Long): Option[Tag] = {
DB.withConnection { implicit connection =>
SQL("SELECT * FROM tag WHERE id = {id}").on('id -> id).as(Tag.simple.singleOpt)
}
}
/**
* Retrieve a tag from the uid.
*/
def findByUid(id: String): Option[Tag] = {
DB.withConnection { implicit connection =>
SQL("SELECT * FROM tag WHERE tuid = {id}").on('id -> id).as(Tag.simple.singleOpt)
}
}
/**
* Lists enabled tags
*/
def listEnabled: Seq[Tag] = {
DB.withConnection { implicit connection =>
SQL(
"""
SELECT * FROM tag
WHERE tag.enabled = TRUE
""").as(Tag.simple *)
}
}
/**
* Return a page of Tag.
*
* @param page Page to display
* @param pageSize Number of entries per page
* @param orderBy Entry property used for sorting
* @param filter Filter applied on the name column
*/
def list(page: Int = 0, pageSize: Int = 10, orderBy: Int = 1, filter: String = "%"): Page[Tag] = {
val offest = pageSize * page
val mode = if(orderBy < 0) "DESC" else "ASC"
DB.withConnection { implicit connection =>
val entries = SQL(
"""
SELECT * FROM tag
WHERE tag.name LIKE {filter}
ORDER BY %d %s nulls LAST
LIMIT {pageSize} OFFSET {offset}
""".format(scala.math.abs(orderBy), mode)).on(
'pageSize -> pageSize,
'offset -> offest,
'filter -> filter).as(Tag.simple *)
val totalRows = SQL(
"""
SELECT COUNT(*) FROM tag
WHERE tag.name ILIKE {filter}
""").on(
'filter -> filter).as(scalar[Long].single)
Page(entries, page, offest, totalRows)
}
}
/**
* Update a tag.
*
* @param id The computer id
* @param tag The tag values.
*/
def update(id: Long, tag: Tag) = {
increaseRevision()
DB.withConnection { implicit connection =>
SQL(
"""
UPDATE tag
SET name = {name}, enabled = {enabled}, tuid = {tuid}
WHERE id = {id}
""").on(
'id -> id,
'name -> tag.name,
'enabled -> tag.enabled,
'tuid -> tag.tuid).executeUpdate()
}
}
/**
* Insert a new tag.
*
* @param tag The tag values.
*/
def insert(tag: Tag) = {
increaseRevision()
DB.withConnection { implicit connection =>
SQL(
"""
INSERT INTO tag (name,added,enabled,tuid) VALUES (
{name}, NOW(), {enabled}, {tuid}
)
""").on(
'name -> tag.name,
'enabled -> tag.enabled,
'tuid -> tag.tuid).executeUpdate()
}
}
/**
* Delete a tag.
*
* @param id Id of the tag to delete.
*/
def delete(id: Long) = {
increaseRevision()
DB.withConnection { implicit connection =>
SQL("DELETE FROM tag WHERE ID = {id}").on('id -> id).executeUpdate()
}
}
}
|
CapeSepias/rfidlock
|
web/app/models/Tag.scala
|
Scala
|
mit
| 3,898
|
<div>
Only consider luminance; ignore chroma (color) in the comparison
</div>
|
marcelerz/visual-diff-plugin
|
src/main/resources/org/jenkinsci/plugins/visual_diff/comparison/PerceptualDiff/help-luminanceOnly.html
|
HTML
|
mit
| 82
|
<?php
namespace SmartByte\Bundle\WebBundle\Form\Type\Filter;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Products filter form type.
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
class OrderItemFilterType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'required' => false,
'label' => 'sylius.form.product_filter.name',
'attr' => array(
'placeholder' => 'sylius.form.product_filter.name'
)
))
/*->add('sku', 'text', array(
'required' => false,
'label' => 'sylius.form.product_filter.sku',
'attr' => array(
'placeholder' => 'sylius.form.product_filter.sku'
)
))*/
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setDefaults(array(
'data_class' => null
))
;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'sylius_order_item_filter';
}
}
|
jakublech/sylius
|
src/SmartByte/Bundle/WebBundle/Form/Type/Filter/OrderItemFilterType.php
|
PHP
|
mit
| 1,424
|
/* iCheck plugin Minimal skin, green
----------------------------------- */
.icheckbox_minimal-green,
.iradio_minimal-green {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 18px;
height: 18px;
background: url(green.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_minimal-green {
background-position: 0 0;
}
.icheckbox_minimal-green.hover {
background-position: -20px 0;
}
.icheckbox_minimal-green.checked {
background-position: -40px 0;
}
.icheckbox_minimal-green.disabled {
background-position: -60px 0;
cursor: default;
}
.icheckbox_minimal-green.checked.disabled {
background-position: -80px 0;
}
.iradio_minimal-green {
background-position: -100px 0;
}
.iradio_minimal-green.hover {
background-position: -120px 0;
}
.iradio_minimal-green.checked {
background-position: -140px 0;
}
.iradio_minimal-green.disabled {
background-position: -160px 0;
cursor: default;
}
.iradio_minimal-green.checked.disabled {
background-position: -180px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_minimal-green,
.iradio_minimal-green {
background-image: url(green@2x.png);
-webkit-background-size: 200px 20px;
background-size: 200px 20px;
}
}
|
ViraxDev/centrale_referencement
|
src/BackendBundle/Resources/public/css/iCheck/minimal/green.css
|
CSS
|
mit
| 1,421
|
##############################################################################
# tpkg package management system
# License: MIT (http://www.opensource.org/licenses/mit-license.php)
##############################################################################
# Exclude standard libraries and gems from the warnings induced by
# running ruby with the -w flag. If any of these had warnings there's
# nothing we could do to fix that.
require 'tpkg/silently'
Silently.silently do
require 'thread'
begin
require 'fastthread'
rescue LoadError
# $stderr.puts "Using the ruby-core thread implementation"
end
end
class ThreadPool
class Worker
def initialize(thread_queue)
@block = nil
@mutex = Mutex.new
@cv = ConditionVariable.new
@queue = thread_queue
@running = true
@thread = Thread.new do
@mutex.synchronize do
while @running
@cv.wait(@mutex)
block = get_block
if block
@mutex.unlock
block.call
@mutex.lock
reset_block
end
@queue << self
end
end
end
end
def name
@thread.inspect
end
def get_block
@block
end
def set_block(block)
@mutex.synchronize do
raise RuntimeError, "Thread already busy." if @block
@block = block
# Signal the thread in this class, that there's a job to be done
@cv.signal
end
end
def reset_block
@block = nil
end
def busy?
@mutex.synchronize { !@block.nil? }
end
def stop
@mutex.synchronize do
@running = false
@cv.signal
end
@thread.join
end
end
attr_accessor :max_size
def initialize(max_size = 10)
@max_size = max_size
@queue = Queue.new
@workers = []
end
def size
@workers.size
end
def busy?
@queue.size < @workers.size
end
def shutdown
@workers.each { |w| w.stop }
@workers = []
end
alias :join :shutdown
def process(block=nil,&blk)
block = blk if block_given?
worker = get_worker
worker.set_block(block)
end
private
def get_worker
if !@queue.empty? or @workers.size == @max_size
return @queue.pop
else
worker = Worker.new(@queue)
@workers << worker
worker
end
end
end
|
tpkg/client
|
lib/tpkg/thread_pool.rb
|
Ruby
|
mit
| 2,389
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.ConceptualDocuments
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.IO;
using Microsoft.DocAsCode.Build.Common;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.DataContracts.Common;
using Microsoft.DocAsCode.Plugins;
[Export(nameof(ConceptualDocumentProcessor), typeof(IDocumentBuildStep))]
public class BuildConceptualDocument : BaseDocumentBuildStep, ISupportIncrementalBuildStep
{
private const string ConceptualKey = Constants.PropertyName.Conceptual;
private const string DocumentTypeKey = "documentType";
public override string Name => nameof(BuildConceptualDocument);
public override int BuildOrder => 0;
public override void Build(FileModel model, IHostService host)
{
if (model.Type != DocumentType.Article)
{
return;
}
var content = (Dictionary<string, object>)model.Content;
var markdown = (string)content[ConceptualKey];
var result = host.Markup(markdown, model.OriginalFileAndType, false, true);
var htmlInfo = HtmlDocumentUtility.SeparateHtml(result.Html);
content["rawTitle"] = htmlInfo.RawTitle;
if (!string.IsNullOrEmpty(htmlInfo.RawTitle))
{
model.ManifestProperties.rawTitle = htmlInfo.RawTitle;
}
content[ConceptualKey] = htmlInfo.Content;
if (result.YamlHeader?.Count > 0)
{
foreach (var item in result.YamlHeader)
{
HandleYamlHeaderPair(item.Key, item.Value);
}
}
(content[Constants.PropertyName.Title], model.Properties.IsUserDefinedTitle) = GetTitle(result.YamlHeader, htmlInfo);
model.LinkToFiles = result.LinkToFiles.ToImmutableHashSet();
model.LinkToUids = result.LinkToUids;
model.FileLinkSources = result.FileLinkSources;
model.UidLinkSources = result.UidLinkSources;
model.Properties.XrefSpec = null;
if (model.Uids.Length > 0)
{
var title = content[Constants.PropertyName.Title] as string;
model.Properties.XrefSpec = new XRefSpec
{
Uid = model.Uids[0].Name,
Name = string.IsNullOrEmpty(title) ? model.Uids[0].Name : title,
Href = ((RelativePath)model.File).GetPathFromWorkingFolder()
};
}
foreach (var d in result.Dependency)
{
host.ReportDependencyTo(model, d, DependencyTypeName.Include);
}
void HandleYamlHeaderPair(string key, object value)
{
switch (key)
{
case Constants.PropertyName.Uid:
var uid = value as string;
if (!string.IsNullOrWhiteSpace(uid))
{
model.Uids = new[] { new UidDefinition(uid, model.LocalPathFromRoot) }.ToImmutableArray();
content[Constants.PropertyName.Uid] = value;
}
break;
case DocumentTypeKey:
content[key] = value;
model.DocumentType = value as string;
break;
case Constants.PropertyName.OutputFileName:
content[key] = value;
var outputFileName = value as string;
if (!string.IsNullOrWhiteSpace(outputFileName))
{
string fn = null;
try
{
fn = Path.GetFileName(outputFileName);
}
catch (ArgumentException) { }
if (fn == outputFileName)
{
model.File = (RelativePath)model.File + (RelativePath)outputFileName;
}
else
{
Logger.LogWarning($"Invalid output file name in yaml header: {outputFileName}, skip rename output file.");
}
}
break;
default:
content[key] = value;
break;
}
}
(string title, bool isUserDefined) GetTitle(ImmutableDictionary<string, object> yamlHeader, SeparatedHtmlInfo info)
{
// title from YAML header
if (yamlHeader != null
&& TryGetStringValue(yamlHeader, Constants.PropertyName.Title, out var yamlHeaderTitle))
{
return (yamlHeaderTitle, true);
}
// title from metadata/titleOverwriteH1
if (TryGetStringValue(content, Constants.PropertyName.TitleOverwriteH1, out var titleOverwriteH1))
{
return (titleOverwriteH1, true);
}
// title from H1
if (!string.IsNullOrEmpty(info.Title))
{
return (info.Title, false);
}
// title from globalMetadata or fileMetadata
if (TryGetStringValue(content, Constants.PropertyName.Title, out var title))
{
return (title, true);
}
return default;
}
bool TryGetStringValue(IDictionary<string, object> dictionary, string key, out string strValue)
{
if (dictionary.TryGetValue(key, out var value) && value is string str && !string.IsNullOrEmpty(str))
{
strValue = str;
return true;
}
else
{
strValue = null;
return false;
}
}
}
#region ISupportIncrementalBuildStep Members
public bool CanIncrementalBuild(FileAndType fileAndType) => true;
public string GetIncrementalContextHash() => null;
public IEnumerable<DependencyType> GetDependencyTypesToRegister() => null;
#endregion
}
}
|
superyyrrzz/docfx
|
src/Microsoft.DocAsCode.Build.ConceptualDocuments/BuildConceptualDocument.cs
|
C#
|
mit
| 6,835
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>The Quaternionic Exponential</title>
<link rel="stylesheet" href="../math.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../index.html" title="Math Toolkit 1.9.0">
<link rel="up" href="../quaternions.html" title="Chapter 9. Quaternions">
<link rel="prev" href="quat_tests.html" title="Test Program">
<link rel="next" href="acknowledgement.html" title="Acknowledgements">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="quat_tests.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../quaternions.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="acknowledgement.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="math_toolkit.exp"></a><a class="link" href="exp.html" title="The Quaternionic Exponential">The Quaternionic Exponential</a>
</h2></div></div></div>
<p>
Please refer to the following PDF's:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
<a href="../../../quaternion/TQE.pdf" target="_top">The Quaternionic Exponential (and
beyond)</a>
</li>
<li class="listitem">
<a href="../../../quaternion/TQE_EA.pdf" target="_top">The Quaternionic Exponential (and
beyond) ERRATA & ADDENDA</a>
</li>
</ul></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2006-2010, 2012, 2013 Nikhar Agrawal, Anton Bikineev,
Paul A. Bristow, Christopher Kormanyos, Hubert Holin, Bruno Lalande, John Maddock,
Johan Råde, Gautam Sewani, Benjamin Sobotta, Thijs van den Berg, Daryle Walker
and Xiaogang Zhang<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="quat_tests.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../quaternions.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="acknowledgement.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
rkq/cxxexp
|
third-party/src/boost_1_56_0/libs/math/doc/html/math_toolkit/exp.html
|
HTML
|
mit
| 3,564
|
/**
* @license AngularJS v1.2.13-build.2242+sha.e645f7c
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
var $resourceMinErr = angular.$$minErr('$resource');
// Helper functions and regex to lookup a dotted path on an object
// stopping at undefined/null. The path must be composed of ASCII
// identifiers (just like $parse)
var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/;
function isValidDottedPath(path) {
return (path != null && path !== '' && path !== 'hasOwnProperty' &&
MEMBER_NAME_REGEX.test('.' + path));
}
function lookupDottedPath(obj, path) {
if (!isValidDottedPath(path)) {
throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
}
var keys = path.split('.');
for (var i = 0, ii = keys.length; i < ii && obj !== undefined; i++) {
var key = keys[i];
obj = (obj !== null) ? obj[key] : undefined;
}
return obj;
}
/**
* Create a shallow copy of an object and clear other fields from the destination
*/
function shallowClearAndCopy(src, dst) {
dst = dst || {};
angular.forEach(dst, function(value, key){
delete dst[key];
});
for (var key in src) {
if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc overview
* @name ngResource
* @description
*
* # ngResource
*
* The `ngResource` module provides interaction support with RESTful services
* via the $resource service.
*
* {@installModule resource}
*
* <div doc-module-components="ngResource"></div>
*
* See {@link ngResource.$resource `$resource`} for usage.
*/
/**
* @ngdoc object
* @name ngResource.$resource
* @requires $http
*
* @description
* A factory which creates a resource object that lets you interact with
* [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
*
* The returned resource object has action methods which provide high-level behaviors without
* the need to interact with the low level {@link ng.$http $http} service.
*
* Requires the {@link ngResource `ngResource`} module to be installed.
*
* @param {string} url A parametrized URL template with parameters prefixed by `:` as in
* `/user/:username`. If you are using a URL with a port number (e.g.
* `http://example.com:8080/api`), it will be respected.
*
* If you are using a url with a suffix, just add the suffix, like this:
* `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`
* or even `$resource('http://example.com/resource/:resource_id.:format')`
* If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
* collapsed down to a single `.`. If you need this sequence to appear and not collapse then you
* can escape it with `/\.`.
*
* @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
* `actions` methods. If any of the parameter value is a function, it will be executed every time
* when a param value needs to be obtained for a request (unless the param was overridden).
*
* Each key value in the parameter object is first bound to url template if present and then any
* excess keys are appended to the url search query after the `?`.
*
* Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
* URL `/path/greet?salutation=Hello`.
*
* If the parameter value is prefixed with `@` then the value of that parameter is extracted from
* the data object (useful for non-GET operations).
*
* @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the
* default set of resource actions. The declaration should be created in the format of {@link
* ng.$http#usage_parameters $http.config}:
*
* {action1: {method:?, params:?, isArray:?, headers:?, ...},
* action2: {method:?, params:?, isArray:?, headers:?, ...},
* ...}
*
* Where:
*
* - **`action`** – {string} – The name of action. This name becomes the name of the method on
* your resource object.
* - **`method`** – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`,
* `DELETE`, and `JSONP`.
* - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of
* the parameter value is a function, it will be executed every time when a param value needs to
* be obtained for a request (unless the param was overridden).
* - **`url`** – {string} – action specific `url` override. The url templating is supported just
* like for the resource-level urls.
* - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,
* see `returns` section.
* - **`transformRequest`** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* - **`transformResponse`** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body and headers and returns its transformed (typically deserialized) version.
* - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **`timeout`** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that
* should abort the request when resolved.
* - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
* requests with credentials} for more information.
* - **`responseType`** - `{string}` - see {@link
* https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}.
* - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
* `response` and `responseError`. Both `response` and `responseError` interceptors get called
* with `http response` object. See {@link ng.$http $http interceptors}.
*
* @returns {Object} A resource "class" object with methods for the default set of resource actions
* optionally extended with custom `actions`. The default set contains these actions:
*
* { 'get': {method:'GET'},
* 'save': {method:'POST'},
* 'query': {method:'GET', isArray:true},
* 'remove': {method:'DELETE'},
* 'delete': {method:'DELETE'} };
*
* Calling these methods invoke an {@link ng.$http} with the specified http method,
* destination and parameters. When the data is returned from the server then the object is an
* instance of the resource class. The actions `save`, `remove` and `delete` are available on it
* as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
* read, update, delete) on server-side data like this:
* <pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It is important to realize that invoking a $resource object method immediately returns an
* empty reference (object or array depending on `isArray`). Once the data is returned from the
* server the existing reference is populated with the actual data. This is a useful trick since
* usually the resource is assigned to a model which is then rendered by the view. Having an empty
* object results in no rendering, once the data arrives from the server then the object is
* populated with the data and the view automatically re-renders itself showing the new data. This
* means that in most cases one never has to write a callback function for the action methods.
*
* The action methods on the class object or instance object can be invoked with the following
* parameters:
*
* - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
* - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
* - non-GET instance actions: `instance.$action([parameters], [success], [error])`
*
* Success callback is called with (value, responseHeaders) arguments. Error callback is called
* with (httpResponse) argument.
*
* Class actions return empty instance (with additional properties below).
* Instance actions return promise of the action.
*
* The Resource instances and collection have these additional properties:
*
* - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
* instance or collection.
*
* On success, the promise is resolved with the same resource instance or collection object,
* updated with data from server. This makes it easy to use in
* {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
* rendering until the resource(s) are loaded.
*
* On failure, the promise is resolved with the {@link ng.$http http response} object, without
* the `resource` property.
*
* - `$resolved`: `true` after first server interaction is completed (either with success or
* rejection), `false` before that. Knowing if the Resource has been resolved is useful in
* data-binding.
*
* @example
*
* # Credit card resource
*
* <pre>
// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
});
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'0123', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
* </pre>
*
* The object returned from this function execution is a resource "class" which has "static" method
* for each action in the definition.
*
* Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
* `headers`.
* When the data is returned from the server then the object is an instance of the resource type and
* all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
* operations (create, read, update, delete) on server-side data.
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It's worth noting that the success callback for `get`, `query` and other methods gets passed
* in the response that came from the server as well as $http header getter function, so one
* could rewrite the above example and get access to http headers as:
*
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u, getResponseHeaders){
u.abc = true;
u.$save(function(u, putResponseHeaders) {
//u => saved user object
//putResponseHeaders => $http header getter
});
});
</pre>
* # Creating a custom 'PUT' request
* In this example we create a custom method on our resource to make a PUT request
* <pre>
* var app = angular.module('app', ['ngResource', 'ngRoute']);
*
* // Some APIs expect a PUT request in the format URL/object/ID
* // Here we are creating an 'update' method
* app.factory('Notes', ['$resource', function($resource) {
* return $resource('/notes/:id', null,
* {
* 'update': { method:'PUT' }
* });
* }]);
*
* // In our controller we get the ID from the URL using ngRoute and $routeParams
* // We pass in $routeParams and our Notes factory along with $scope
* app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
function($scope, $routeParams, Notes) {
* // First get a note object from the factory
* var note = Notes.get({ id:$routeParams.id });
* $id = note.id;
*
* // Now call update passing in the ID first then the object you are updating
* Notes.update({ id:$id }, note);
*
* // This will PUT /notes/ID with the note object in the request payload
* }]);
* </pre>
*/
angular.module('ngResource', ['ng']).
factory('$resource', ['$http', '$q', function($http, $q) {
var DEFAULT_ACTIONS = {
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
var noop = angular.noop,
forEach = angular.forEach,
extend = angular.extend,
copy = angular.copy,
isFunction = angular.isFunction;
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a
* custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
* have to be encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
function Route(template, defaults) {
this.template = template;
this.defaults = defaults || {};
this.urlParams = {};
}
Route.prototype = {
setUrlParams: function(config, params, actionUrl) {
var self = this,
url = actionUrl || self.template,
val,
encodedVal;
var urlParams = self.urlParams = {};
forEach(url.split(/\W/), function(param){
if (param === 'hasOwnProperty') {
throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
}
if (!(new RegExp("^\\d+$").test(param)) && param &&
(new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
urlParams[param] = true;
}
});
url = url.replace(/\\:/g, ':');
params = params || {};
forEach(self.urlParams, function(_, urlParam){
val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
if (angular.isDefined(val) && val !== null) {
encodedVal = encodeUriSegment(val);
url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
return encodedVal + p1;
});
} else {
url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
leadingSlashes, tail) {
if (tail.charAt(0) == '/') {
return tail;
} else {
return leadingSlashes + tail;
}
});
}
});
// strip trailing slashes and set the url
url = url.replace(/\/+$/, '') || '/';
// then replace collapse `/.` if found in the last URL path segment before the query
// E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
url = url.replace(/\/\.(?=\w+($|\?))/, '.');
// replace escaped `/\.` with `/.`
config.url = url.replace(/\/\\\./, '/.');
// set params - delegate param encoding to $http
forEach(params, function(value, key){
if (!self.urlParams[key]) {
config.params = config.params || {};
config.params[key] = value;
}
});
}
};
function resourceFactory(url, paramDefaults, actions) {
var route = new Route(url);
actions = extend({}, DEFAULT_ACTIONS, actions);
function extractParams(data, actionParams){
var ids = {};
actionParams = extend({}, paramDefaults, actionParams);
forEach(actionParams, function(value, key){
if (isFunction(value)) { value = value(); }
ids[key] = value && value.charAt && value.charAt(0) == '@' ?
lookupDottedPath(data, value.substr(1)) : value;
});
return ids;
}
function defaultResponseInterceptor(response) {
return response.resource;
}
function Resource(value){
shallowClearAndCopy(value || {}, this);
}
forEach(actions, function(action, name) {
var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
Resource[name] = function(a1, a2, a3, a4) {
var params = {}, data, success, error;
/* jshint -W086 */ /* (purposefully fall through case statements) */
switch(arguments.length) {
case 4:
error = a4;
success = a3;
//fallthrough
case 3:
case 2:
if (isFunction(a2)) {
if (isFunction(a1)) {
success = a1;
error = a2;
break;
}
success = a2;
error = a3;
//fallthrough
} else {
params = a1;
data = a2;
success = a3;
break;
}
case 1:
if (isFunction(a1)) success = a1;
else if (hasBody) data = a1;
else params = a1;
break;
case 0: break;
default:
throw $resourceMinErr('badargs',
"Expected up to 4 arguments [params, data, success, error], got {0} arguments",
arguments.length);
}
/* jshint +W086 */ /* (purposefully fall through case statements) */
var isInstanceCall = this instanceof Resource;
var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
var httpConfig = {};
var responseInterceptor = action.interceptor && action.interceptor.response ||
defaultResponseInterceptor;
var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
undefined;
forEach(action, function(value, key) {
if (key != 'params' && key != 'isArray' && key != 'interceptor') {
httpConfig[key] = copy(value);
}
});
if (hasBody) httpConfig.data = data;
route.setUrlParams(httpConfig,
extend({}, extractParams(data, action.params || {}), params),
action.url);
var promise = $http(httpConfig).then(function(response) {
var data = response.data,
promise = value.$promise;
if (data) {
// Need to convert action.isArray to boolean in case it is undefined
// jshint -W018
if (angular.isArray(data) !== (!!action.isArray)) {
throw $resourceMinErr('badcfg', 'Error in resource configuration. Expected ' +
'response to contain an {0} but got an {1}',
action.isArray?'array':'object', angular.isArray(data)?'array':'object');
}
// jshint +W018
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
value.push(new Resource(item));
});
} else {
shallowClearAndCopy(data, value);
value.$promise = promise;
}
}
value.$resolved = true;
response.resource = value;
return response;
}, function(response) {
value.$resolved = true;
(error||noop)(response);
return $q.reject(response);
});
promise = promise.then(
function(response) {
var value = responseInterceptor(response);
(success||noop)(value, response.headers);
return value;
},
responseErrorInterceptor);
if (!isInstanceCall) {
// we are creating instance / collection
// - set the initial promise
// - return the instance / collection
value.$promise = promise;
value.$resolved = false;
return value;
}
// instance call
return promise;
};
Resource.prototype['$' + name] = function(params, success, error) {
if (isFunction(params)) {
error = success; success = params; params = {};
}
var result = Resource[name].call(this, params, this, success, error);
return result.$promise || result;
};
});
Resource.bind = function(additionalParamDefaults){
return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
};
return Resource;
}
return resourceFactory;
}]);
})(window, window.angular);
|
tacone/larry
|
public/bower_components/angular-resource/angular-resource.js
|
JavaScript
|
mit
| 23,517
|
require 'spec_helper'
describe Newgistics::Client do
context '#create_product' do
it 'creates products in newgistics' do
products = 5.times.map do |i|
Newgistics::Product.new.tap do |p|
p.sku = "SKU-#{i.to_s * 4}"
end
end
client = Newgistics::Client.new
response = client.create_products(products)
expect(response.products.size).to eq(products.size)
end
end
context '#create_shipment' do
end
context '#create_return' do
end
context '#list_manifests' do
end
end
|
20jeans/newgistics
|
spec/lib/newgistics/client_spec.rb
|
Ruby
|
mit
| 544
|
package net.glowstone.entity;
import com.flowpowered.networking.Message;
import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.glowstone.*;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.blocktype.BlockBed;
import net.glowstone.block.entity.TileEntity;
import net.glowstone.constants.*;
import net.glowstone.entity.meta.ClientSettings;
import net.glowstone.entity.meta.MetadataIndex;
import net.glowstone.entity.meta.MetadataMap;
import net.glowstone.entity.meta.profile.PlayerProfile;
import net.glowstone.entity.objects.GlowItem;
import net.glowstone.inventory.GlowInventory;
import net.glowstone.inventory.InventoryMonitor;
import net.glowstone.io.PlayerDataService;
import net.glowstone.net.GlowSession;
import net.glowstone.net.message.login.LoginSuccessMessage;
import net.glowstone.net.message.play.entity.AnimateEntityMessage;
import net.glowstone.net.message.play.entity.DestroyEntitiesMessage;
import net.glowstone.net.message.play.entity.EntityMetadataMessage;
import net.glowstone.net.message.play.entity.EntityVelocityMessage;
import net.glowstone.net.message.play.game.*;
import net.glowstone.net.message.play.inv.*;
import net.glowstone.net.message.play.player.PlayerAbilitiesMessage;
import net.glowstone.net.message.play.player.ResourcePackSendMessage;
import net.glowstone.net.message.play.player.UseBedMessage;
import net.glowstone.net.protocol.ProtocolType;
import net.glowstone.scoreboard.GlowScoreboard;
import net.glowstone.scoreboard.GlowTeam;
import net.glowstone.util.StatisticMap;
import net.glowstone.util.TextMessage;
import net.glowstone.util.nbt.CompoundTag;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.bukkit.*;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.configuration.serialization.DelegateDeserialization;
import org.bukkit.conversations.Conversation;
import org.bukkit.conversations.ConversationAbandonedEvent;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.*;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.map.MapView;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.messaging.StandardMessenger;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.title.Title;
import org.bukkit.title.TitleOptions;
import org.bukkit.util.BlockVector;
import org.bukkit.util.Vector;
import org.json.simple.JSONObject;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.logging.Level;
/**
* Represents an in-game player.
*
* @author Graham Edgecombe
*/
@DelegateDeserialization(GlowOfflinePlayer.class)
public final class GlowPlayer extends GlowHumanEntity implements Player {
/**
* A static entity id to use when telling the client about itself.
*/
private static final int SELF_ID = 0;
/**
* This player's session.
*/
private final GlowSession session;
/**
* The entities that the client knows about.
*/
private final Set<GlowEntity> knownEntities = new HashSet<>();
/**
* The entities that are hidden from the client.
*/
private final Set<UUID> hiddenEntities = new HashSet<>();
/**
* The chunks that the client knows about.
*/
private final Set<GlowChunk.Key> knownChunks = new HashSet<>();
/**
* A queue of BlockChangeMessages to be sent.
*/
private final List<BlockChangeMessage> blockChanges = new LinkedList<>();
/**
* A queue of messages that should be sent after block changes are processed.
* Used for sign updates and other situations where the block must be sent first.
*/
private final List<Message> afterBlockChanges = new LinkedList<>();
/**
* The set of plugin channels this player is listening on
*/
private final Set<String> listeningChannels = new HashSet<>();
/**
* The player's statistics, achievements, and related data.
*/
private final StatisticMap stats = new StatisticMap();
/**
* Whether the player has played before (will be false on first join).
*/
private final boolean hasPlayedBefore;
/**
* The time the player first played, or 0 if unknown.
*/
private final long firstPlayed;
/**
* The time the player last played, or 0 if unknown.
*/
private final long lastPlayed;
/**
* The time the player joined.
*/
private long joinTime;
/**
* The settings sent by the client.
*/
private ClientSettings settings = ClientSettings.DEFAULT;
/**
* The lock used to prevent chunks from unloading near the player.
*/
private ChunkManager.ChunkLock chunkLock;
/**
* The tracker for changes to the currently open inventory.
*/
private InventoryMonitor invMonitor;
/**
* The display name of this player, for chat purposes.
*/
private String displayName;
/**
* The name a player has in the player list
*/
private String playerListName;
/**
* Cumulative amount of experience points the player has collected.
*/
private int totalExperience = 0;
/**
* The current level (or skill point amount) of the player.
*/
private int level = 0;
/**
* The progress made to the next level, from 0 to 1.
*/
private float experience = 0;
/**
* The human entity's current food level
*/
private int food = 20;
/**
* The player's current exhaustion level.
*/
private float exhaustion = 0;
/**
* The player's current saturation level.
*/
private float saturation = 0;
/**
* Whether to perform special scaling of the player's health.
*/
private boolean healthScaled = false;
/**
* The scale at which to display the player's health.
*/
private double healthScale = 20;
/**
* This player's current time offset.
*/
private long timeOffset = 0;
/**
* Whether the time offset is relative.
*/
private boolean timeRelative = true;
/**
* The player-specific weather, or null for normal weather.
*/
private WeatherType playerWeather = null;
/**
* The player's compass target.
*/
private Location compassTarget;
/**
* Whether this player's sleeping state is ignored when changing time.
*/
private boolean sleepingIgnored;
/**
* The bed in which the player currently lies
*/
private GlowBlock bed;
/**
* The bed spawn location of a player
*/
private Location bedSpawn;
/**
* Whether to use the bed spawn even if there is no bed block.
*/
private boolean bedSpawnForced;
/**
* The location of the sign the player is currently editing, or null.
*/
private Location signLocation;
/**
* Whether the player is permitted to fly.
*/
private boolean canFly;
/**
* Whether the player is currently flying.
*/
private boolean flying;
/**
* The player's base flight speed.
*/
private float flySpeed = 0.1f;
/**
* The player's base walking speed.
*/
private float walkSpeed = 0.2f;
/**
* The scoreboard the player is currently subscribed to.
*/
private GlowScoreboard scoreboard;
/**
* The player's current title, if any
*/
private Title currentTitle = new Title();
/**
* The player's current title options
*/
private TitleOptions titleOptions = new TitleOptions();
/**
* Creates a new player and adds it to the world.
*
* @param session The player's session.
* @param profile The player's profile with name and UUID information.
* @param reader The PlayerReader to be used to initialize the player.
*/
public GlowPlayer(GlowSession session, PlayerProfile profile, PlayerDataService.PlayerReader reader) {
super(initLocation(session, reader), profile);
setBoundingBox(0.6, 1.8);
this.session = session;
chunkLock = world.newChunkLock(getName());
// enable compression if needed
int compression = session.getServer().getCompressionThreshold();
if (compression > 0) {
session.enableCompression(compression);
}
// send login response
session.send(new LoginSuccessMessage(profile.getUniqueId().toString(), profile.getName()));
session.setProtocol(ProtocolType.PLAY);
// read data from player reader
hasPlayedBefore = reader.hasPlayedBefore();
if (hasPlayedBefore) {
firstPlayed = reader.getFirstPlayed();
lastPlayed = reader.getLastPlayed();
bedSpawn = reader.getBedSpawnLocation();
} else {
firstPlayed = 0;
lastPlayed = 0;
}
//creates InventoryMonitor to avoid NullPointerException
invMonitor = new InventoryMonitor(getOpenInventory());
updateInventory(); // send inventory contents
}
public void join(GlowSession session, PlayerDataService.PlayerReader reader) {
// send join game
// in future, handle hardcore, difficulty, and level type
String type = world.getWorldType().getName().toLowerCase();
int gameMode = getGameMode().getValue();
if (server.isHardcore()) {
gameMode |= 0x8;
}
session.send(new JoinGameMessage(SELF_ID, gameMode, world.getEnvironment().getId(), world.getDifficulty().getValue(), session.getServer().getMaxPlayers(), type, world.getGameRuleMap().getBoolean("reducedDebugInfo")));
setGameModeDefaults();
// send server brand and supported plugin channels
session.send(PluginMessage.fromString("MC|Brand", server.getName()));
sendSupportedChannels();
joinTime = System.currentTimeMillis();
reader.readData(this);
reader.close();
// Add player to list of online players
getServer().setPlayerOnline(this, true);
// save data back out
saveData();
streamBlocks(); // stream the initial set of blocks
setCompassTarget(world.getSpawnLocation()); // set our compass target
sendTime();
sendWeather();
sendRainDensity();
sendSkyDarkness();
sendAbilities();
scoreboard = server.getScoreboardManager().getMainScoreboard();
scoreboard.subscribe(this);
invMonitor = new InventoryMonitor(getOpenInventory());
updateInventory(); // send inventory contents
// send initial location
session.send(new PositionRotationMessage(location));
if (!server.getResourcePackURL().isEmpty()) {
setResourcePack(server.getResourcePackURL(), server.getResourcePackHash());
}
}
/**
* Read the location from a PlayerReader for entity initialization. Will
* fall back to a reasonable default rather than returning null.
*
* @param session The player's session.
* @param reader The PlayerReader to get the location from.
* @return The location to spawn the player.
*/
private static Location initLocation(GlowSession session, PlayerDataService.PlayerReader reader) {
if (reader.hasPlayedBefore()) {
Location loc = reader.getLocation();
if (loc != null) {
return loc;
}
}
return session.getServer().getWorlds().get(0).getSpawnLocation();
}
@Override
public String toString() {
return "GlowPlayer{name=" + getName() + "}";
}
////////////////////////////////////////////////////////////////////////////
// Damages
@Override
public void damage(double amount) {
if (getGameMode().equals(GameMode.CREATIVE)) {
return;
}
damage(amount, DamageCause.CUSTOM);
}
@Override
public void damage(double amount, Entity cause) {
if (getGameMode().equals(GameMode.CREATIVE)) {
return;
}
super.damage(amount, cause);
sendHealth();
}
@Override
public void damage(double amount, DamageCause cause) {
if (getGameMode().equals(GameMode.CREATIVE) && !cause.equals(DamageCause.VOID)) {
return;
}
super.damage(amount, cause);
sendHealth();
}
////////////////////////////////////////////////////////////////////////////
// Internals
/**
* Get the network session attached to this player.
*
* @return The GlowSession of the player.
*/
public GlowSession getSession() {
return session;
}
/**
* Get the join time in milliseconds, to be saved as last played time.
*
* @return The player's join time.
*/
public long getJoinTime() {
return joinTime;
}
/**
* Destroys this entity by removing it from the world and marking it as not
* being active.
*/
@Override
public void remove() {
knownChunks.clear();
chunkLock.clear();
saveData();
getInventory().removeViewer(this);
getInventory().getCraftingInventory().removeViewer(this);
permissions.clearPermissions();
getServer().setPlayerOnline(this, false);
if (scoreboard != null) {
scoreboard.unsubscribe(this);
scoreboard = null;
}
super.remove();
}
@Override
public boolean shouldSave() {
return false;
}
@Override
public void pulse() {
super.pulse();
// stream world
streamBlocks();
processBlockChanges();
// add to playtime
incrementStatistic(Statistic.PLAY_ONE_TICK);
// update inventory
for (InventoryMonitor.Entry entry : invMonitor.getChanges()) {
sendItemChange(entry.slot, entry.item);
}
// send changed metadata
List<MetadataMap.Entry> changes = metadata.getChanges();
if (changes.size() > 0) {
session.send(new EntityMetadataMessage(SELF_ID, changes));
}
// update or remove entities
List<Integer> destroyIds = new LinkedList<>();
for (Iterator<GlowEntity> it = knownEntities.iterator(); it.hasNext(); ) {
GlowEntity entity = it.next();
if (isWithinDistance(entity)) {
for (Message msg : entity.createUpdateMessage()) {
session.send(msg);
}
} else {
destroyIds.add(entity.getEntityId());
it.remove();
}
}
if (destroyIds.size() > 0) {
session.send(new DestroyEntitiesMessage(destroyIds));
}
// add entities
for (GlowEntity entity : world.getEntityManager()) {
if (entity != this && isWithinDistance(entity) &&
!knownEntities.contains(entity) && !hiddenEntities.contains(entity.getUniqueId())) {
knownEntities.add(entity);
for (Message msg : entity.createSpawnMessage()) {
session.send(msg);
}
}
}
getAttributeManager().sendMessages(session);
}
/**
* Process and send pending BlockChangeMessages.
*/
private void processBlockChanges() {
List<BlockChangeMessage> messages = new ArrayList<>(blockChanges);
blockChanges.clear();
// separate messages by chunk
// inner map is used to only send one entry for same coordinates
Map<GlowChunk.Key, Map<BlockVector, BlockChangeMessage>> chunks = new HashMap<>();
for (BlockChangeMessage message : messages) {
GlowChunk.Key key = new GlowChunk.Key(message.getX() >> 4, message.getZ() >> 4);
if (canSeeChunk(key)) {
Map<BlockVector, BlockChangeMessage> map = chunks.get(key);
if (map == null) {
map = new HashMap<>();
chunks.put(key, map);
}
map.put(new BlockVector(message.getX(), message.getY(), message.getZ()), message);
}
}
// send away
for (Map.Entry<GlowChunk.Key, Map<BlockVector, BlockChangeMessage>> entry : chunks.entrySet()) {
GlowChunk.Key key = entry.getKey();
List<BlockChangeMessage> value = new ArrayList<>(entry.getValue().values());
if (value.size() == 1) {
session.send(value.get(0));
} else if (value.size() > 1) {
session.send(new MultiBlockChangeMessage(key.getX(), key.getZ(), value));
}
}
// now send post-block-change messages
List<Message> postMessages = new ArrayList<>(afterBlockChanges);
afterBlockChanges.clear();
for (Message message : postMessages) {
session.send(message);
}
}
/**
* Streams chunks to the player's client.
*/
private void streamBlocks() {
Set<GlowChunk.Key> previousChunks = new HashSet<>(knownChunks);
ArrayList<GlowChunk.Key> newChunks = new ArrayList<>();
int centralX = location.getBlockX() >> 4;
int centralZ = location.getBlockZ() >> 4;
int radius = Math.min(server.getViewDistance(), 1 + settings.getViewDistance());
for (int x = (centralX - radius); x <= (centralX + radius); x++) {
for (int z = (centralZ - radius); z <= (centralZ + radius); z++) {
GlowChunk.Key key = new GlowChunk.Key(x, z);
if (knownChunks.contains(key)) {
previousChunks.remove(key);
} else {
newChunks.add(key);
}
}
}
// early end if there's no changes
if (newChunks.size() == 0 && previousChunks.size() == 0) {
return;
}
// sort chunks by distance from player - closer chunks sent first
Collections.sort(newChunks, new Comparator<GlowChunk.Key>() {
@Override
public int compare(GlowChunk.Key a, GlowChunk.Key b) {
double dx = 16 * a.getX() + 8 - location.getX();
double dz = 16 * a.getZ() + 8 - location.getZ();
double da = dx * dx + dz * dz;
dx = 16 * b.getX() + 8 - location.getX();
dz = 16 * b.getZ() + 8 - location.getZ();
double db = dx * dx + dz * dz;
return Double.compare(da, db);
}
});
// populate then send chunks to the player
// done in two steps so that all the new chunks are finalized before any of them are sent
// this prevents sending a chunk then immediately sending block changes in it because
// one of its neighbors has populated
// first step: force population then acquire lock on each chunk
for (GlowChunk.Key key : newChunks) {
world.getChunkManager().forcePopulation(key.getX(), key.getZ());
knownChunks.add(key);
chunkLock.acquire(key);
}
// second step: package chunks into bulk packets
final int maxSize = 0x1fffef; // slightly under protocol max size of 0x200000
final boolean skylight = world.getEnvironment() == World.Environment.NORMAL;
List<ChunkDataMessage> messages = new LinkedList<>();
int bulkSize = 6; // size of bulk header
// split the chunks into bulk packets based on how many fit
for (GlowChunk.Key key : newChunks) {
GlowChunk chunk = world.getChunkAt(key.getX(), key.getZ());
ChunkDataMessage message = chunk.toMessage(skylight);
// 10 bytes of header in bulk packet, plus data length
int messageSize = 10 + message.getData().length;
// if this chunk would make the message too big,
if (bulkSize + messageSize > maxSize) {
// send out what we have so far
session.send(new ChunkBulkMessage(skylight, messages));
messages = new LinkedList<>();
bulkSize = 6;
}
bulkSize += messageSize;
messages.add(message);
}
// send the leftovers
if (!messages.isEmpty()) {
session.send(new ChunkBulkMessage(skylight, messages));
}
// send visible tile entity data
for (GlowChunk.Key key : newChunks) {
GlowChunk chunk = world.getChunkAt(key.getX(), key.getZ());
for (TileEntity entity : chunk.getRawTileEntities()) {
entity.update(this);
}
}
// and remove old chunks
for (GlowChunk.Key key : previousChunks) {
session.send(ChunkDataMessage.empty(key.getX(), key.getZ()));
knownChunks.remove(key);
chunkLock.release(key);
}
previousChunks.clear();
}
/**
* Spawn the player at the given location after they have already joined.
* Used for changing worlds and respawning after death.
*
* @param location The location to place the player.
*/
private void spawnAt(Location location) {
// switch worlds
GlowWorld oldWorld = world;
world.getEntityManager().unregister(this);
world = (GlowWorld) location.getWorld();
world.getEntityManager().register(this);
// switch chunk set
// no need to send chunk unload messages - respawn unloads all chunks
knownChunks.clear();
chunkLock.clear();
chunkLock = world.newChunkLock(getName());
// spawn into world
String type = world.getWorldType().getName().toLowerCase();
session.send(new RespawnMessage(world.getEnvironment().getId(), world.getDifficulty().getValue(), getGameMode().getValue(), type));
setRawLocation(location); // take us to spawn position
streamBlocks(); // stream blocks
setCompassTarget(world.getSpawnLocation()); // set our compass target
session.send(new PositionRotationMessage(location));
sendWeather();
sendRainDensity();
sendSkyDarkness();
sendTime();
updateInventory();
// fire world change if needed
if (oldWorld != world) {
EventFactory.callEvent(new PlayerChangedWorldEvent(this, oldWorld));
}
}
/**
* Respawn the player after they have died.
*/
public void respawn() {
// restore health
setHealth(getMaxHealth());
// determine spawn destination
boolean spawnAtBed = true;
Location dest = getBedSpawnLocation();
if (dest == null) {
dest = world.getSpawnLocation();
spawnAtBed = false;
if (bedSpawn != null) {
setBedSpawnLocation(null);
sendMessage("Your home bed was missing or obstructed");
}
}
// fire event and perform spawn
PlayerRespawnEvent event = new PlayerRespawnEvent(this, dest, spawnAtBed);
EventFactory.callEvent(event);
if (event.getRespawnLocation().getWorld().equals(getWorld()) && knownEntities.size() > 0) {
// we need to manually reset all known entities if the player respawns in the same world
List<Integer> entityIds = new ArrayList<>(knownEntities.size());
for (GlowEntity e : knownEntities) {
entityIds.add(e.getEntityId());
}
session.send(new DestroyEntitiesMessage(entityIds));
knownEntities.clear();
}
spawnAt(event.getRespawnLocation());
// just in case any items are left in their inventory after they respawn
updateInventory();
}
/**
* Checks whether the player can see the given chunk.
*
* @return If the chunk is known to the player's client.
*/
public boolean canSeeChunk(GlowChunk.Key chunk) {
return knownChunks.contains(chunk);
}
/**
* Checks whether the player can see the given entity.
*
* @return If the entity is known to the player's client.
*/
public boolean canSeeEntity(GlowEntity entity) {
return knownEntities.contains(entity);
}
/**
* Open the sign editor interface at the specified location.
*
* @param loc The location to open the editor at
*/
public void openSignEditor(Location loc) {
signLocation = loc.clone();
signLocation.setX(loc.getBlockX());
signLocation.setY(loc.getBlockY());
signLocation.setZ(loc.getBlockZ());
session.send(new SignEditorMessage(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
/**
* Check that the specified location matches that of the last opened sign
* editor, and if so, clears the last opened sign editor.
*
* @param loc The location to check
* @return Whether the location matched.
*/
public boolean checkSignLocation(Location loc) {
if (loc.equals(signLocation)) {
signLocation = null;
return true;
} else {
return false;
}
}
/**
* Get a UserListItemMessage entry representing adding this player.
*
* @return The entry (action ADD_PLAYER) with this player's information.
*/
public UserListItemMessage.Entry getUserListEntry() {
TextMessage displayName = null;
if (playerListName != null && !playerListName.isEmpty()) {
displayName = new TextMessage(playerListName);
}
return UserListItemMessage.add(getProfile(), getGameMode().getValue(), 0, displayName);
}
/**
* Send a UserListItemMessage to every player that can see this player.
* @param updateMessage The message to send.
*/
private void updateUserListEntries(UserListItemMessage updateMessage) {
for (GlowPlayer player : server.getOnlinePlayers()) {
if (player.canSee(this)) {
player.getSession().send(updateMessage);
}
}
}
@Override
public void setVelocity(Vector velocity) {
PlayerVelocityEvent event = EventFactory.callEvent(new PlayerVelocityEvent(this, velocity));
if (!event.isCancelled()) {
velocity = event.getVelocity();
super.setVelocity(velocity);
session.send(new EntityVelocityMessage(SELF_ID, velocity));
}
}
/**
* Set the client settings for this player.
*
* @param settings The new client settings.
*/
public void setSettings(ClientSettings settings) {
this.settings = settings;
metadata.set(MetadataIndex.PLAYER_SKIN_FLAGS, settings.getSkinFlags());
}
/**
* Get this player's client settings.
*
* @return The player's client settings.
*/
public ClientSettings getSettings() {
return settings;
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> ret = new HashMap<>();
ret.put("name", getName());
return ret;
}
////////////////////////////////////////////////////////////////////////////
// Basic stuff
@Override
public EntityType getType() {
return EntityType.PLAYER;
}
@Override
public InetSocketAddress getAddress() {
return session.getAddress();
}
@Override
public boolean isOnline() {
return session.isActive() && session.isOnline();
}
@Override
public boolean isBanned() {
return server.getBanList(BanList.Type.NAME).isBanned(getName());
}
@Override
@Deprecated
public void setBanned(boolean banned) {
server.getBanList(BanList.Type.NAME).addBan(getName(), null, null, null);
}
@Override
public boolean isWhitelisted() {
return server.getWhitelist().containsProfile(new PlayerProfile(getName(), getUniqueId()));
}
@Override
public void setWhitelisted(boolean value) {
if (value) {
server.getWhitelist().add(this);
} else {
server.getWhitelist().remove(new PlayerProfile(getName(), getUniqueId()));
}
}
@Override
public Player getPlayer() {
return this;
}
@Override
public boolean hasPlayedBefore() {
return hasPlayedBefore;
}
@Override
public long getFirstPlayed() {
return firstPlayed;
}
@Override
public long getLastPlayed() {
return lastPlayed;
}
////////////////////////////////////////////////////////////////////////////
// HumanEntity overrides
@Override
public boolean isOp() {
return getServer().getOpsList().containsUUID(getUniqueId());
}
@Override
public void setOp(boolean value) {
if (value) {
getServer().getOpsList().add(this);
} else {
getServer().getOpsList().remove(new PlayerProfile(getName(), getUniqueId()));
}
permissions.recalculatePermissions();
}
@Override
public List<Message> createSpawnMessage() {
List<Message> result = super.createSpawnMessage();
if (bed != null) {
result.add(new UseBedMessage(getEntityId(), bed.getX(), bed.getY(), bed.getZ()));
}
return result;
}
////////////////////////////////////////////////////////////////////////////
// Editable properties
@Override
public String getDisplayName() {
if (displayName != null) {
return displayName;
}
GlowTeam team = (GlowTeam) getScoreboard().getPlayerTeam(this);
if (team != null) {
return team.getPlayerDisplayName(getName());
}
return getName();
}
@Override
public void setDisplayName(String name) {
displayName = name;
}
@Override
public String getPlayerListName() {
return playerListName == null || playerListName.isEmpty() ? getName() : playerListName;
}
@Override
public void setPlayerListName(String name) {
// update state
playerListName = name;
// send update message
TextMessage displayName = null;
if (playerListName != null && !playerListName.isEmpty()) {
displayName = new TextMessage(playerListName);
}
updateUserListEntries(UserListItemMessage.displayNameOne(getUniqueId(), displayName));
}
@Override
public Location getCompassTarget() {
return compassTarget;
}
@Override
public void setCompassTarget(Location loc) {
compassTarget = loc;
session.send(new SpawnPositionMessage(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
/**
* Returns whether the player spawns at their bed even if there is no bed block.
* @return Whether the player is forced to spawn at their bed.
*/
public boolean isBedSpawnForced() {
return bedSpawnForced;
}
@Override
public Location getBedSpawnLocation() {
if (bedSpawn == null) {
return null;
}
// Find head of bed
GlowBlock block = (GlowBlock) bedSpawn.getBlock();
GlowBlock head = BlockBed.getHead(block);
GlowBlock foot = BlockBed.getFoot(block);
// If there is a bed, try to find an empty spot next to the bed
if (head != null && head.getType() == Material.BED_BLOCK) {
Block spawn = BlockBed.getExitLocation(head, foot);
return spawn == null ? null : spawn.getLocation().add(0.5, 0.1, 0.5);
} else {
// If there is no bed and spawning is forced and there is space to spawn
if (bedSpawnForced) {
Material bottom = head.getType();
Material top = head.getRelative(BlockFace.UP).getType();
// Do not check floor when forcing spawn
if (BlockBed.isValidSpawn(bottom) && BlockBed.isValidSpawn(top)) {
return bedSpawn.clone().add(0.5, 0.1, 0.5); // No blocks are blocking the spawn
}
}
return null;
}
}
@Override
public void setBedSpawnLocation(Location bedSpawn) {
setBedSpawnLocation(bedSpawn, false);
}
@Override
public void setBedSpawnLocation(Location location, boolean force) {
this.bedSpawn = location;
this.bedSpawnForced = force;
}
@Override
public boolean isSleepingIgnored() {
return sleepingIgnored;
}
@Override
public void setSleepingIgnored(boolean isSleeping) {
sleepingIgnored = isSleeping;
}
@Override
public void setGameMode(GameMode mode) {
if (getGameMode() != mode) {
PlayerGameModeChangeEvent event = new PlayerGameModeChangeEvent(this, mode);
if (EventFactory.callEvent(event).isCancelled()) {
return;
}
super.setGameMode(mode);
updateUserListEntries(UserListItemMessage.gameModeOne(getUniqueId(), mode.getValue()));
session.send(new StateChangeMessage(StateChangeMessage.Reason.GAMEMODE, mode.getValue()));
}
setGameModeDefaults();
}
private void setGameModeDefaults() {
GameMode mode = getGameMode();
setAllowFlight(mode == GameMode.CREATIVE || mode == GameMode.SPECTATOR);
metadata.setBit(MetadataIndex.STATUS, MetadataIndex.StatusFlags.INVISIBLE, mode == GameMode.SPECTATOR);
}
////////////////////////////////////////////////////////////////////////////
// Entity status
@Override
public boolean isSneaking() {
return metadata.getBit(MetadataIndex.STATUS, MetadataIndex.StatusFlags.SNEAKING);
}
@Override
public void setSneaking(boolean sneak) {
if (EventFactory.callEvent(new PlayerToggleSneakEvent(this, sneak)).isCancelled()) {
return;
}
metadata.setBit(MetadataIndex.STATUS, MetadataIndex.StatusFlags.SNEAKING, sneak);
}
@Override
public boolean isSprinting() {
return metadata.getBit(MetadataIndex.STATUS, MetadataIndex.StatusFlags.SPRINTING);
}
@Override
public void setSprinting(boolean sprinting) {
if (EventFactory.callEvent(new PlayerToggleSprintEvent(this, sprinting)).isCancelled()) {
return;
}
metadata.setBit(MetadataIndex.STATUS, MetadataIndex.StatusFlags.SPRINTING, sprinting);
}
@Override
public double getEyeHeight() {
return getEyeHeight(false);
}
@Override
public double getEyeHeight(boolean ignoreSneaking) {
// Height of player's eyes above feet. Matches CraftBukkit.
if (ignoreSneaking || !isSneaking()) {
return 1.62;
} else {
return 1.54;
}
}
////////////////////////////////////////////////////////////////////////////
// Player capabilities
@Override
public boolean getAllowFlight() {
return canFly;
}
@Override
public void setAllowFlight(boolean flight) {
canFly = flight;
if (!canFly) flying = false;
sendAbilities();
}
@Override
public boolean isFlying() {
return flying;
}
@Override
public void setFlying(boolean value) {
flying = value && canFly;
sendAbilities();
}
@Override
public float getFlySpeed() {
return flySpeed;
}
@Override
public void setFlySpeed(float value) throws IllegalArgumentException {
flySpeed = value;
sendAbilities();
}
@Override
public float getWalkSpeed() {
return walkSpeed;
}
@Override
public void setWalkSpeed(float value) throws IllegalArgumentException {
walkSpeed = value;
sendAbilities();
}
private void sendAbilities() {
boolean creative = getGameMode() == GameMode.CREATIVE;
int flags = (creative ? 8 : 0) | (canFly ? 4 : 0) | (flying ? 2 : 0) | (creative ? 1 : 0);
// division is conversion from Bukkit to MC units
session.send(new PlayerAbilitiesMessage(flags, flySpeed / 2f, walkSpeed / 2f));
}
////////////////////////////////////////////////////////////////////////////
// Experience and levelling
@Override
public int getLevel() {
return level;
}
@Override
public void setLevel(int level) {
this.level = Math.max(level, 0);
sendExperience();
}
@Override
public int getTotalExperience() {
return totalExperience;
}
@Override
public void setTotalExperience(int exp) {
this.totalExperience = Math.max(exp, 0);
sendExperience();
}
@Override
public void giveExp(int xp) {
totalExperience += xp;
// gradually award levels based on xp points
float value = 1.0f / getExpToLevel();
for (int i = 0; i < xp; ++i) {
experience += value;
if (experience >= 1) {
experience -= 1;
value = 1.0f / getExpToLevel(++level);
}
}
sendExperience();
}
@Override
public float getExp() {
return experience;
}
@Override
public void setExp(float percentToLevel) {
experience = Math.min(Math.max(percentToLevel, 0), 1);
sendExperience();
}
@Override
public int getExpToLevel() {
return getExpToLevel(level);
}
private int getExpToLevel(int level) {
if (level >= 30) {
return 62 + (level - 30) * 7;
} else if (level >= 15) {
return 17 + (level - 15) * 3;
} else {
return 17;
}
}
@Override
public void giveExpLevels(int amount) {
setLevel(getLevel() + amount);
}
private void sendExperience() {
session.send(new ExperienceMessage(getExp(), getLevel(), getTotalExperience()));
}
////////////////////////////////////////////////////////////////////////////
// Health and food handling
@Override
public void setHealth(double health) {
super.setHealth(health);
sendHealth();
}
@Override
public void setMaxHealth(double health) {
super.setMaxHealth(health);
sendHealth();
}
@Override
public boolean isHealthScaled() {
return healthScaled;
}
@Override
public void setHealthScaled(boolean scale) {
healthScaled = scale;
sendHealth();
}
@Override
public double getHealthScale() {
return healthScale;
}
@Override
public Entity getSpectatorTarget() {
return null;
}
@Override
public void setSpectatorTarget(Entity entity) {
}
@Override
public void sendTitle(String title, String subtitle) {
}
@Override
public void setHealthScale(double scale) throws IllegalArgumentException {
healthScaled = true;
healthScale = scale;
sendHealth();
}
@Override
public int getFoodLevel() {
return food;
}
@Override
public void setFoodLevel(int food) {
this.food = Math.min(food, 20);
sendHealth();
}
@Override
public float getExhaustion() {
return exhaustion;
}
@Override
public void setExhaustion(float value) {
exhaustion = value;
}
@Override
public float getSaturation() {
return saturation;
}
@Override
public void setSaturation(float value) {
saturation = value;
sendHealth();
}
private void sendHealth() {
float finalHealth = (float) (getHealth() / getMaxHealth() * getHealthScale());
session.send(new HealthMessage(finalHealth, getFoodLevel(), getSaturation()));
}
////////////////////////////////////////////////////////////////////////////
// Actions
/**
* Teleport the player.
*
* @param location The destination to teleport to.
* @return Whether the teleport was a success.
*/
@Override
public boolean teleport(Location location) {
return teleport(location, TeleportCause.UNKNOWN);
}
@Override
public boolean teleport(Location location, TeleportCause cause) {
Validate.notNull(location, "location cannot be null");
Validate.notNull(location.getWorld(), "location's world cannot be null");
Validate.notNull(cause, "cause cannot be null");
if (this.location != null && this.location.getWorld() != null) {
PlayerTeleportEvent event = new PlayerTeleportEvent(this, this.location, location, cause);
if (EventFactory.callEvent(event).isCancelled()) {
return false;
}
location = event.getTo();
}
if (location.getWorld() != world) {
spawnAt(location);
} else {
session.send(new PositionRotationMessage(location));
setRawLocation(location);
}
teleported = true;
return true;
}
@Override
protected boolean teleportToSpawn() {
Location target = getBedSpawnLocation();
if (target == null) {
target = server.getWorlds().get(0).getSpawnLocation();
}
PlayerPortalEvent event = EventFactory.callEvent(new PlayerPortalEvent(this, location.clone(), target, null));
if (event.isCancelled()) {
return false;
}
target = event.getTo();
spawnAt(target);
teleported = true;
awardAchievement(Achievement.THE_END, false);
return true;
}
@Override
protected boolean teleportToEnd() {
if (!server.getAllowEnd()) {
return false;
}
Location target = null;
for (World world : server.getWorlds()) {
if (world.getEnvironment() == Environment.THE_END) {
target = world.getSpawnLocation();
break;
}
}
if (target == null) {
return false;
}
PlayerPortalEvent event = EventFactory.callEvent(new PlayerPortalEvent(this, location.clone(), target, null));
if (event.isCancelled()) {
return false;
}
target = event.getTo();
spawnAt(target);
teleported = true;
awardAchievement(Achievement.END_PORTAL, false);
return true;
}
/**
* This player enters the specified bed and is marked as sleeping.
* @param block the bed
*/
public void enterBed(GlowBlock block) {
Validate.notNull(block, "Bed block cannot be null");
Preconditions.checkState(bed == null, "Player already in bed");
GlowBlock head = BlockBed.getHead(block);
GlowBlock foot = BlockBed.getFoot(block);
if (EventFactory.callEvent(new PlayerBedEnterEvent(this, head)).isCancelled()) {
return;
}
// Occupy the bed
BlockBed.setOccupied(head, foot, true);
bed = head;
sleeping = true;
setRawLocation(head.getLocation());
getSession().send(new UseBedMessage(SELF_ID, head.getX(), head.getY(), head.getZ()));
UseBedMessage msg = new UseBedMessage(getEntityId(), head.getX(), head.getY(), head.getZ());
for (GlowPlayer p : world.getRawPlayers()) {
if (p != this && p.canSeeEntity(this)) {
p.getSession().send(msg);
}
}
}
/**
* This player leaves their bed causing them to quit sleeping.
* @param setSpawn Whether to set the bed spawn of the player
*/
public void leaveBed(boolean setSpawn) {
Preconditions.checkState(bed != null, "Player is not in bed");
GlowBlock head = BlockBed.getHead(bed);;
GlowBlock foot = BlockBed.getFoot(bed);
// Determine exit location
Block exitBlock = BlockBed.getExitLocation(head, foot);
if (exitBlock == null) { // If no empty blocks were found fallback to block above bed
exitBlock = head.getRelative(BlockFace.UP);
}
Location exitLocation = exitBlock.getLocation().add(0.5, 0.1, 0.5); // Use center of block
// Set their spawn (normally omitted if their bed gets destroyed instead of them leaving it)
if (setSpawn) {
setBedSpawnLocation(head.getLocation());
}
// Empty the bed
BlockBed.setOccupied(head, foot, false);
bed = null;
sleeping = false;
// And eject the player
setRawLocation(exitLocation);
teleported = true;
// Call event
EventFactory.callEvent(new PlayerBedLeaveEvent(this, head));
getSession().send(new AnimateEntityMessage(SELF_ID, AnimateEntityMessage.OUT_LEAVE_BED));
AnimateEntityMessage msg = new AnimateEntityMessage(getEntityId(), AnimateEntityMessage.OUT_LEAVE_BED);
for (GlowPlayer p : world.getRawPlayers()) {
if (p != this && p.canSeeEntity(this)) {
p.getSession().send(msg);
}
}
}
@Override
public void sendMessage(String message) {
sendRawMessage(message);
}
@Override
public void sendMessage(String[] messages) {
for (String line : messages) {
sendMessage(line);
}
}
@Override
public void sendRawMessage(String message) {
// old-style formatting to json conversion is in TextMessage
session.send(new ChatMessage(message));
}
@Override
@SuppressWarnings("unchecked")
public void sendActionBarMessage(String message) {
// "old" formatting workaround because apparently "new" styling doesn't work as of 01/18/2015
JSONObject json = new JSONObject();
json.put("text", message);
session.send(new ChatMessage(new TextMessage(json), 2));
}
@Override
public void kickPlayer(String message) {
session.disconnect(message == null ? "" : message);
}
@Override
public boolean performCommand(String command) {
return getServer().dispatchCommand(this, command);
}
@Override
public void chat(String text) {
chat(text, false);
}
/**
* Says a message (or runs a command).
*
* @param text message sent by the player.
* @param async whether the message was received asynchronously.
*/
public void chat(final String text, boolean async) {
if (text.startsWith("/")) {
Runnable task = new Runnable() {
@Override
public void run() {
server.getLogger().info(getName() + " issued command: " + text);
try {
PlayerCommandPreprocessEvent event = new PlayerCommandPreprocessEvent(GlowPlayer.this, text);
if (!EventFactory.callEvent(event).isCancelled()) {
server.dispatchCommand(GlowPlayer.this, event.getMessage().substring(1));
}
} catch (Exception ex) {
sendMessage(ChatColor.RED + "An internal error occurred while executing your command.");
server.getLogger().log(Level.SEVERE, "Exception while executing command: " + text, ex);
}
}
};
// if async is true, this task should happen synchronously
// otherwise, we're sync already, it can happen here
if (async) {
server.getScheduler().runTask(null, task);
} else {
task.run();
}
} else {
AsyncPlayerChatEvent event = EventFactory.onPlayerChat(async, this, text);
if (event.isCancelled()) {
return;
}
String message = String.format(event.getFormat(), getDisplayName(), event.getMessage());
getServer().getLogger().info(message);
for (Player recipient : event.getRecipients()) {
recipient.sendMessage(message);
}
}
}
@Override
public void saveData() {
saveData(true);
}
public void saveData(boolean async) {
if (async) {
server.getScheduler().runTaskAsynchronously(null, new Runnable() {
@Override
public void run() {
server.getPlayerDataService().writeData(GlowPlayer.this);
}
});
} else {
server.getPlayerDataService().writeData(this);
}
}
@Override
public void loadData() {
server.getPlayerDataService().readData(this);
}
@Override
@Deprecated
public void setTexturePack(String url) {
setResourcePack(url);
}
@Override
public void setResourcePack(String url) {
setResourcePack(url, "");
}
@Override
public void setResourcePack(String url, String hash) {
session.send(new ResourcePackSendMessage(url, hash));
}
////////////////////////////////////////////////////////////////////////////
// Effect and data transmission
@Override
public void playNote(Location loc, Instrument instrument, Note note) {
Sound sound;
switch (instrument) {
case PIANO:
sound = Sound.NOTE_PIANO;
break;
case BASS_DRUM:
sound = Sound.NOTE_BASS_DRUM;
break;
case SNARE_DRUM:
sound = Sound.NOTE_SNARE_DRUM;
break;
case STICKS:
sound = Sound.NOTE_STICKS;
break;
case BASS_GUITAR:
sound = Sound.NOTE_BASS_GUITAR;
break;
default:
throw new IllegalArgumentException("Invalid instrument");
}
playSound(loc, sound, 3.0f, note.getId());
}
@Override
public void playNote(Location loc, byte instrument, byte note) {
playNote(loc, Instrument.getByType(instrument), new Note(note));
}
@Override
public void playEffect(Location loc, Effect effect, int data) {
int id = effect.getId();
boolean ignoreDistance = effect.isDistanceIgnored();
session.send(new PlayEffectMessage(id, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), data, ignoreDistance));
}
private void playEffect_(Location loc, Effect effect, int data) { // fix name collision with Spigot below
this.playEffect(loc, effect, data);
}
@Override
public <T> void playEffect(Location loc, Effect effect, T data) {
playEffect(loc, effect, GlowEffect.getDataValue(effect, data));
}
@Override
public void playSound(Location location, Sound sound, float volume, float pitch) {
playSound(location, GlowSound.getName(sound), volume, pitch);
}
@Override
public void playSound(Location location, String sound, float volume, float pitch) {
if (location == null || sound == null) return;
// the loss of precision here is a bit unfortunate but it's what CraftBukkit does
double x = location.getBlockX() + 0.5;
double y = location.getBlockY() + 0.5;
double z = location.getBlockZ() + 0.5;
session.send(new PlaySoundMessage(sound, x, y, z, volume, pitch));
}
private final Player.Spigot spigot = new Player.Spigot() {
@Override
public void playEffect(Location location, Effect effect, int id, int data, float offsetX, float offsetY, float offsetZ, float speed, int particleCount, int radius) {
if (effect.getType() == Effect.Type.PARTICLE) {
MaterialData material = new MaterialData(id, (byte) data);
showParticle(location, effect, material, offsetX, offsetY, offsetZ, speed, particleCount);
} else {
playEffect_(location, effect, data);
}
}
};
@Override
public Player.Spigot spigot() {
return spigot;
}
//@Override
public void showParticle(Location loc, Effect particle, MaterialData material, float offsetX, float offsetY, float offsetZ, float speed, int amount) {
if (location == null || particle == null || particle.getType() != Effect.Type.PARTICLE) return;
int id = GlowParticle.getId(particle);
boolean longDistance = GlowParticle.isLongDistance(particle);
float x = (float) loc.getX();
float y = (float) loc.getY();
float z = (float) loc.getZ();
int[] extData = GlowParticle.getData(particle, material);
session.send(new PlayParticleMessage(id, longDistance, x, y, z, offsetX, offsetY, offsetZ, speed, amount, extData));
}
@Override
public void sendBlockChange(Location loc, Material material, byte data) {
sendBlockChange(loc, material.getId(), data);
}
@Override
public void sendBlockChange(Location loc, int material, byte data) {
sendBlockChange(new BlockChangeMessage(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), material, data));
}
public void sendBlockChange(BlockChangeMessage message) {
// only send message if the chunk is within visible range
GlowChunk.Key key = new GlowChunk.Key(message.getX() >> 4, message.getZ() >> 4);
if (canSeeChunk(key)) {
blockChanges.add(message);
}
}
@Override
public boolean sendChunkChange(Location loc, int sx, int sy, int sz, byte[] data) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void sendSignChange(Location location, String[] lines) throws IllegalArgumentException {
Validate.notNull(location, "location cannot be null");
Validate.notNull(lines, "lines cannot be null");
Validate.isTrue(lines.length == 4, "lines.length must equal 4");
afterBlockChanges.add(UpdateSignMessage.fromPlainText(location.getBlockX(), location.getBlockY(), location.getBlockZ(), lines));
}
/**
* Send a sign change, similar to {@link #sendSignChange(Location, String[])},
* but using complete TextMessages instead of strings.
* @param location the location of the sign
* @param lines the new text on the sign or null to clear it
* @throws IllegalArgumentException if location is null
* @throws IllegalArgumentException if lines is non-null and has a length less than 4
*/
public void sendSignChange(Location location, TextMessage[] lines) {
Validate.notNull(location, "location cannot be null");
Validate.notNull(lines, "lines cannot be null");
Validate.isTrue(lines.length == 4, "lines.length must equal 4");
afterBlockChanges.add(new UpdateSignMessage(location.getBlockX(), location.getBlockY(), location.getBlockZ(), lines));
}
/**
* Send a block entity change to the given location.
* @param location The location of the block entity.
* @param type The type of block entity being sent.
* @param nbt The NBT structure to send to the client.
*/
public void sendBlockEntityChange(Location location, GlowBlockEntity type, CompoundTag nbt) {
Validate.notNull(location, "Location cannot be null");
Validate.notNull(type, "Type cannot be null");
Validate.notNull(nbt, "NBT cannot be null");
afterBlockChanges.add(new UpdateBlockEntityMessage(location.getBlockX(), location.getBlockY(), location.getBlockZ(), type.getValue(), nbt));
}
@Override
public void sendMap(MapView map) {
throw new UnsupportedOperationException("Not supported yet.");
}
////////////////////////////////////////////////////////////////////////////
// Achievements and statistics
@Override
public boolean hasAchievement(Achievement achievement) {
return stats.hasAchievement(achievement);
}
@Override
public void awardAchievement(Achievement achievement) {
awardAchievement(achievement, true);
}
/**
* Awards the given achievement if the player already has the parent achievement,
* otherwise does nothing. If {@code awardParents} is true, award the player all
* parent achievements and the given achievement, making this method equivalent
* to {@link #awardAchievement(Achievement)}.
* @param achievement the achievement to award.
* @param awardParents whether parent achievements should be awarded.
* @return {@code true} if the achievement was awarded, {@code false} otherwise
*/
public boolean awardAchievement(Achievement achievement, boolean awardParents) {
if (hasAchievement(achievement)) return false;
Achievement parent = achievement.getParent();
if (parent != null && !hasAchievement(parent)) {
if (!awardParents || !awardAchievement(parent, true)) {
// does not have or failed to award required parent achievement
return false;
}
}
PlayerAchievementAwardedEvent event = new PlayerAchievementAwardedEvent(this, achievement);
if (EventFactory.callEvent(event).isCancelled()) {
return false; // event was cancelled
}
stats.setAchievement(achievement, true);
sendAchievement(achievement, true);
if (server.getAnnounceAchievements()) {
// todo: make message fancier (hover, translated names)
server.broadcastMessage(getName() + " has just earned the achievement " + ChatColor.GREEN + "[" + GlowAchievement.getFancyName(achievement) + "]");
}
return true;
}
@Override
public void removeAchievement(Achievement achievement) {
if (!hasAchievement(achievement)) return;
stats.setAchievement(achievement, false);
sendAchievement(achievement, false);
}
private void sendAchievement(Achievement achievement, boolean has) {
Map<String, Integer> values = new HashMap<>();
values.put(GlowAchievement.getName(achievement), has ? 1 : 0);
session.send(new StatisticMessage(values));
}
@Override
public int getStatistic(Statistic statistic) throws IllegalArgumentException {
return stats.get(statistic);
}
@Override
public int getStatistic(Statistic statistic, Material material) throws IllegalArgumentException {
return stats.get(statistic, material);
}
@Override
public int getStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException {
return stats.get(statistic, entityType);
}
@Override
public void setStatistic(Statistic statistic, int newValue) throws IllegalArgumentException {
stats.set(statistic, newValue);
}
@Override
public void setStatistic(Statistic statistic, Material material, int newValue) throws IllegalArgumentException {
stats.set(statistic, material, newValue);
}
@Override
public void setStatistic(Statistic statistic, EntityType entityType, int newValue) {
stats.set(statistic, entityType, newValue);
}
@Override
public void incrementStatistic(Statistic statistic) {
stats.add(statistic, 1);
}
@Override
public void incrementStatistic(Statistic statistic, int amount) {
stats.add(statistic, amount);
}
@Override
public void incrementStatistic(Statistic statistic, Material material) {
stats.add(statistic, material, 1);
}
@Override
public void incrementStatistic(Statistic statistic, Material material, int amount) {
stats.add(statistic, material, amount);
}
@Override
public void incrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException {
stats.add(statistic, entityType, 1);
}
@Override
public void incrementStatistic(Statistic statistic, EntityType entityType, int amount) throws IllegalArgumentException {
stats.add(statistic, entityType, amount);
}
@Override
public void decrementStatistic(Statistic statistic) throws IllegalArgumentException {
stats.add(statistic, -1);
}
@Override
public void decrementStatistic(Statistic statistic, int amount) throws IllegalArgumentException {
stats.add(statistic, -amount);
}
@Override
public void decrementStatistic(Statistic statistic, Material material) throws IllegalArgumentException {
stats.add(statistic, material, -1);
}
@Override
public void decrementStatistic(Statistic statistic, Material material, int amount) throws IllegalArgumentException {
stats.add(statistic, material, -amount);
}
@Override
public void decrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException {
stats.add(statistic, entityType, -1);
}
@Override
public void decrementStatistic(Statistic statistic, EntityType entityType, int amount) {
stats.add(statistic, entityType, -amount);
}
public void sendStats() {
session.send(stats.toMessage());
}
////////////////////////////////////////////////////////////////////////////
// Inventory
@Override
public void updateInventory() {
session.send(new SetWindowContentsMessage(invMonitor.getId(), invMonitor.getContents()));
}
public void sendItemChange(int slot, ItemStack item) {
session.send(new SetWindowSlotMessage(invMonitor.getId(), slot, item));
}
@Override
public void setItemOnCursor(ItemStack item) {
super.setItemOnCursor(item);
session.send(new SetWindowSlotMessage(-1, -1, item));
}
@Override
public boolean setWindowProperty(InventoryView.Property prop, int value) {
if (!super.setWindowProperty(prop, value)) return false;
session.send(new WindowPropertyMessage(invMonitor.getId(), prop.getId(), value));
return true;
}
@Override
public void openInventory(InventoryView view) {
session.send(new CloseWindowMessage(invMonitor.getId()));
super.openInventory(view);
invMonitor = new InventoryMonitor(getOpenInventory());
int viewId = invMonitor.getId();
if (viewId != 0) {
String title = view.getTitle();
boolean defaultTitle = view.getType().getDefaultTitle().equals(title);
if (view.getTopInventory() instanceof PlayerInventory && defaultTitle) {
title = ((PlayerInventory) view.getTopInventory()).getHolder().getName();
}
Message open = new OpenWindowMessage(viewId, invMonitor.getType(), title, ((GlowInventory) view.getTopInventory()).getRawSlots());
session.send(open);
}
updateInventory();
}
@Override
public GlowItem drop(ItemStack stack) {
GlowItem dropping = super.drop(stack);
if (dropping != null) {
PlayerDropItemEvent event = new PlayerDropItemEvent(this, dropping);
EventFactory.callEvent(event);
if (event.isCancelled()) {
dropping.remove();
dropping = null;
}
}
return dropping;
}
////////////////////////////////////////////////////////////////////////////
// Player-specific time and weather
@Override
public void setPlayerTime(long time, boolean relative) {
timeOffset = (time % GlowWorld.DAY_LENGTH + GlowWorld.DAY_LENGTH) % GlowWorld.DAY_LENGTH;
timeRelative = relative;
sendTime();
}
@Override
public long getPlayerTime() {
if (timeRelative) {
// add timeOffset ticks to current time
return (world.getTime() + timeOffset) % GlowWorld.DAY_LENGTH;
} else {
// return time offset
return timeOffset;
}
}
@Override
public long getPlayerTimeOffset() {
return timeOffset;
}
@Override
public boolean isPlayerTimeRelative() {
return timeRelative;
}
@Override
public void resetPlayerTime() {
setPlayerTime(0, true);
}
public void sendTime() {
long time = getPlayerTime();
if (!timeRelative || !world.getGameRuleMap().getBoolean("doDaylightCycle")) {
time = -time; // negative value indicates fixed time
}
session.send(new TimeMessage(world.getFullTime(), time));
}
@Override
public void setPlayerWeather(WeatherType type) {
playerWeather = type;
sendWeather();
}
@Override
public WeatherType getPlayerWeather() {
return playerWeather;
}
@Override
public void resetPlayerWeather() {
playerWeather = null;
sendWeather();
sendRainDensity();
sendSkyDarkness();
}
public void sendWeather() {
boolean stormy = playerWeather == null ? getWorld().hasStorm() : playerWeather == WeatherType.DOWNFALL;
session.send(new StateChangeMessage(stormy ? StateChangeMessage.Reason.START_RAIN : StateChangeMessage.Reason.STOP_RAIN, 0));
}
public void sendRainDensity() {
session.send(new StateChangeMessage(StateChangeMessage.Reason.RAIN_DENSITY, getWorld().getRainDensity()));
}
public void sendSkyDarkness() {
session.send(new StateChangeMessage(StateChangeMessage.Reason.SKY_DARKNESS, getWorld().getSkyDarkness()));
}
////////////////////////////////////////////////////////////////////////////
// Player visibility
@Override
public void hidePlayer(Player player) {
Validate.notNull(player, "player cannot be null");
if (equals(player) || !player.isOnline() || !session.isActive()) return;
if (hiddenEntities.contains(player.getUniqueId())) return;
hiddenEntities.add(player.getUniqueId());
if (knownEntities.remove((GlowEntity) player)) {
session.send(new DestroyEntitiesMessage(Arrays.asList(player.getEntityId())));
}
session.send(UserListItemMessage.removeOne(player.getUniqueId()));
}
@Override
public void showPlayer(Player player) {
Validate.notNull(player, "player cannot be null");
if (equals(player) || !player.isOnline() || !session.isActive()) return;
if (!hiddenEntities.contains(player.getUniqueId())) return;
hiddenEntities.remove(player.getUniqueId());
session.send(new UserListItemMessage(UserListItemMessage.Action.ADD_PLAYER, ((GlowPlayer) player).getUserListEntry()));
}
@Override
public boolean canSee(Player player) {
return !hiddenEntities.contains(player.getUniqueId());
}
/**
* Called when a player hidden to this player disconnects.
* This is necessary so the player is visible again after they reconnected.
*
* @param player The disconnected player
*/
public void stopHidingDisconnectedPlayer(Player player) {
hiddenEntities.remove(player.getUniqueId());
}
////////////////////////////////////////////////////////////////////////////
// Scoreboard
@Override
public Scoreboard getScoreboard() {
return scoreboard;
}
@Override
public void setScoreboard(Scoreboard scoreboard) throws IllegalArgumentException, IllegalStateException {
Validate.notNull(scoreboard, "Scoreboard must not be null");
if (!(scoreboard instanceof GlowScoreboard)) {
throw new IllegalArgumentException("Scoreboard must be GlowScoreboard");
}
if (this.scoreboard == null) {
throw new IllegalStateException("Player has not loaded or is already offline");
}
this.scoreboard.unsubscribe(this);
this.scoreboard = (GlowScoreboard) scoreboard;
this.scoreboard.subscribe(this);
}
////////////////////////////////////////////////////////////////////////////
// Conversable
@Override
public boolean isConversing() {
return false;
}
@Override
public void acceptConversationInput(String input) {
}
@Override
public boolean beginConversation(Conversation conversation) {
return false;
}
@Override
public void abandonConversation(Conversation conversation) {
}
@Override
public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) {
}
////////////////////////////////////////////////////////////////////////////
// Plugin messages
@Override
public void sendPluginMessage(Plugin source, String channel, byte[] message) {
StandardMessenger.validatePluginMessage(getServer().getMessenger(), source, channel, message);
if (listeningChannels.contains(channel)) {
// only send if player is listening for it
session.send(new PluginMessage(channel, message));
}
}
@Override
public Set<String> getListeningPluginChannels() {
return Collections.unmodifiableSet(listeningChannels);
}
/**
* Add a listening channel to this player.
*
* @param channel The channel to add.
*/
public void addChannel(String channel) {
if (listeningChannels.add(channel)) {
EventFactory.callEvent(new PlayerRegisterChannelEvent(this, channel));
}
}
/**
* Remove a listening channel from this player.
*
* @param channel The channel to remove.
*/
public void removeChannel(String channel) {
if (listeningChannels.remove(channel)) {
EventFactory.callEvent(new PlayerUnregisterChannelEvent(this, channel));
}
}
/**
* Send the supported plugin channels to the client.
*/
private void sendSupportedChannels() {
Set<String> listening = server.getMessenger().getIncomingChannels();
if (!listening.isEmpty()) {
// send NUL-separated list of channels we support
ByteBuf buf = Unpooled.buffer(16 * listening.size());
for (String channel : listening) {
buf.writeBytes(channel.getBytes(StandardCharsets.UTF_8));
buf.writeByte(0);
}
session.send(new PluginMessage("REGISTER", buf.array()));
if (buf.refCnt() > 0) {
buf.release(buf.refCnt());
}
}
}
public void enchanted(int clicked) {
this.level -= clicked + 1;
if (level < 0) {
this.level = 0;
this.experience = 0;
this.totalExperience = 0;
}
setLevel(level);
setXpSeed(new Random().nextInt()); //TODO use entity's random instance?
}
////////////////////////////////////////////////////////////////////////////
// Titles
@Override
public Title getTitle() {
return currentTitle.clone();
}
@Override
public TitleOptions getTitleOptions() {
return titleOptions.clone();
}
@Override
public void setTitle(Title title) {
setTitle(title, false);
}
@Override
public void setTitle(Title title, boolean forceUpdate) {
Validate.notNull(title, "Title cannot be null");
String oldHeading = currentTitle.getHeading();
currentTitle = title;
if (forceUpdate || !StringUtils.equals(oldHeading, currentTitle.getHeading())) {
session.sendAll(TitleMessage.fromTitle(currentTitle));
}
}
@Override
public void setTitleOptions(TitleOptions options) {
if (options == null) {
options = new TitleOptions();
}
titleOptions = options;
session.send(TitleMessage.fromOptions(titleOptions));
}
@Override
public void clearTitle() {
currentTitle = new Title();
session.send(new TitleMessage(TitleMessage.Action.CLEAR));
}
@Override
public void resetTitle() {
currentTitle = new Title(currentTitle.getHeading());
titleOptions = new TitleOptions();
session.send(new TitleMessage(TitleMessage.Action.RESET));
}
}
|
keke142/GlowstonePlusPlus
|
src/main/java/net/glowstone/entity/GlowPlayer.java
|
Java
|
mit
| 72,781
|
from pytest import approx, raises
from fastats.maths.gamma import gammaln
def test_gamma_ints():
assert gammaln(10) == approx(12.801827480081469, rel=1e-6)
assert gammaln(5) == approx(3.1780538303479458, rel=1e-6)
assert gammaln(19) == approx(36.39544520803305, rel=1e-6)
def test_gamma_floats():
assert gammaln(3.141) == approx(0.8271155090776673, rel=1e-6)
assert gammaln(8.8129) == approx(10.206160943471318, rel=1e-6)
assert gammaln(12.001) == approx(17.50475055100354, rel=1e-6)
assert gammaln(0.007812) == approx(4.847635060148693, rel=1e-6)
assert gammaln(86.13) == approx(296.3450079998172, rel=1e-6)
def test_gamma_negative():
raises(AssertionError, gammaln, -1)
raises(AssertionError, gammaln, -0.023)
raises(AssertionError, gammaln, -10.9)
if __name__ == '__main__':
import pytest
pytest.main([__file__])
|
dwillmer/fastats
|
tests/maths/test_gamma.py
|
Python
|
mit
| 878
|
#ifndef __BARRIER_SYNC_CLIENT_H__
#define __BARRIER_SYNC_CLIENT_H__
#include "fixed_types.h"
#include "clock_skew_minimization_object.h"
#include "packetize.h"
#include "subsecond_time.h"
// Forward Decls
class Core;
class BarrierSyncClient : public ClockSkewMinimizationClient
{
private:
Core* m_core;
SubsecondTime m_barrier_interval;
SubsecondTime m_next_sync_time;
UInt32 m_num_outstanding;
public:
BarrierSyncClient(Core* core);
~BarrierSyncClient();
void enable() {}
void disable() {}
void synchronize(SubsecondTime time, bool ignore_time, bool abort_func(void*) = NULL, void* abort_arg = NULL);
};
#endif /* __BARRIER_SYNC_CLIENT_H__ */
|
abanaiyan/sniper
|
common/system/barrier_sync_client.h
|
C
|
mit
| 713
|
/*
*= require font_awesome
*= require bootstrap
*= require grayscale/grayscale.css
*= require_self
*/
|
MartinN13/frontend-generators
|
assets/grayscale/app/assets/stylesheets/grayscale/manifest.css
|
CSS
|
mit
| 107
|
/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
/* Copyright 2008 litl, LLC. */
/**
* The tween list object. Stores all of the properties and information that pertain to individual tweens.
*
* @author Nate Chatellier, Zeh Fernando
* @version 1.0.4
* @private
*/
/*
Licensed under the MIT License
Copyright (c) 2006-2007 Zeh Fernando and Nate Chatellier
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.
http://code.google.com/p/tweener/
http://code.google.com/p/tweener/wiki/License
*/
function TweenList(scope, timeStart, timeComplete,
useFrames, transition, transitionParams) {
this._init(scope, timeStart, timeComplete, useFrames, transition,
transitionParams);
}
TweenList.prototype = {
_init: function(scope, timeStart, timeComplete,
userFrames, transition, transitionParams) {
this.scope = scope;
this.timeStart = timeStart;
this.timeComplete = timeComplete;
this.userFrames = userFrames;
this.transition = transition;
this.transitionParams = transitionParams;
/* Other default information */
this.properties = new Object();
this.isPaused = false;
this.timePaused = undefined;
this.isCaller = false;
this.updatesSkipped = 0;
this.timesCalled = 0;
this.skipUpdates = 0;
this.hasStarted = false;
},
clone: function(omitEvents) {
var tween = new TweenList(this.scope, this.timeStart, this.timeComplete, this.userFrames,
this.transition, this.transitionParams);
tween.properties = new Array();
for (let name in this.properties) {
tween.properties[name] = this.properties[name];
}
tween.skipUpdates = this.skipUpdates;
tween.updatesSkipped = this.updatesSkipped;
if (!omitEvents) {
tween.onStart = this.onStart;
tween.onUpdate = this.onUpdate;
tween.onComplete = this.onComplete;
tween.onOverwrite = this.onOverwrite;
tween.onError = this.onError;
tween.onStartParams = this.onStartParams;
tween.onUpdateParams = this.onUpdateParams;
tween.onCompleteParams = this.onCompleteParams;
tween.onOverwriteParams = this.onOverwriteParams;
tween.onStartScope = this.onStartScope;
tween.onUpdateScope = this.onUpdateScope;
tween.onCompleteScope = this.onCompleteScope;
tween.onOverwriteScope = this.onOverwriteScope;
tween.onErrorScope = this.onErrorScope;
}
tween.rounded = this.rounded;
tween.min = this.min;
tween.max = this.max;
tween.isPaused = this.isPaused;
tween.timePaused = this.timePaused;
tween.isCaller = this.isCaller;
tween.count = this.count;
tween.timesCalled = this.timesCalled;
tween.waitFrames = this.waitFrames;
tween.hasStarted = this.hasStarted;
return tween;
}
};
function makePropertiesChain(obj) {
/* Tweener has a bunch of code here to get all the properties of all
* the objects we inherit from (the objects in the 'base' property).
* I don't think that applies to JavaScript...
*/
return obj;
};
|
mtwebster/cjs
|
modules/tweener/tweenList.js
|
JavaScript
|
mit
| 4,334
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(:default, Rails.env)
class Application < Rails::Application
config.generators do |g|
g.test_framework :rspec, fixture: false
g.view_specs false
g.integration_specs false
g.stylesheets = false
g.javascripts = false
g.helper = false
end
config.exceptions_app = self.routes
end
|
sheerun/githubsocial
|
config/application.rb
|
Ruby
|
mit
| 391
|
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\MXF;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class PulldownSequence extends AbstractTag
{
protected $Id = '060e2b34.0101.0101.04010801.01000000';
protected $Name = 'PulldownSequence';
protected $FullName = 'MXF::Main';
protected $GroupName = 'MXF';
protected $g0 = 'MXF';
protected $g1 = 'MXF';
protected $g2 = 'Video';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Pulldown Sequence';
}
|
bburnichon/PHPExiftool
|
lib/PHPExiftool/Driver/Tag/MXF/PulldownSequence.php
|
PHP
|
mit
| 817
|
module Dragonfly
module ActiveModelExtensions
module InstanceMethods
def attachments
@attachments ||= self.class.dragonfly_apps_for_attributes.inject({}) do |hash, (attribute, app)|
hash[attribute] = Attachment.new(app, self, attribute)
hash
end
end
private
def save_attachments
attachments.each do |attribute, attachment|
attachment.save!
end
end
def destroy_attachments
attachments.each do |attribute, attachment|
attachment.destroy!
end
end
end
end
end
|
jrtoocool/geo_ushelf
|
rmagick/ruby/1.8/gems/dragonfly-0.7.7/lib/dragonfly/active_model_extensions/instance_methods.rb
|
Ruby
|
mit
| 626
|
<?php
/**
* @file include/security.php
*
* Some security related functions.
*/
/**
* @param int $user_record The account_id
* @param bool $login_initial default false
* @param bool $interactive default false
* @param bool $return
* @param bool $update_lastlog
*/
function authenticate_success($user_record, $login_initial = false, $interactive = false, $return = false, $update_lastlog = false) {
$a = get_app();
$_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
if(x($user_record, 'account_id')) {
$a->account = $user_record;
$_SESSION['account_id'] = $user_record['account_id'];
$_SESSION['authenticated'] = 1;
if($login_initial || $update_lastlog) {
q("update account set account_lastlog = '%s' where account_id = %d",
dbesc(datetime_convert()),
intval($_SESSION['account_id'])
);
$a->account['account_lastlog'] = datetime_convert();
call_hooks('logged_in', $a->account);
}
$uid_to_load = (((x($_SESSION,'uid')) && (intval($_SESSION['uid'])))
? intval($_SESSION['uid'])
: intval($a->account['account_default_channel'])
);
if($uid_to_load) {
change_channel($uid_to_load);
}
}
if($login_initial) {
call_hooks('logged_in', $user_record);
// might want to log success here
}
if($return || x($_SESSION, 'workflow')) {
unset($_SESSION['workflow']);
return;
}
if(($a->module !== 'home') && x($_SESSION,'login_return_url') && strlen($_SESSION['login_return_url'])) {
$return_url = $_SESSION['login_return_url'];
// don't let members get redirected to a raw ajax page update - this can happen
// if DHCP changes the IP address at an unfortunate time and paranoia is turned on
if(strstr($return_url,'update_'))
$return_url = '';
unset($_SESSION['login_return_url']);
goaway($a->get_baseurl() . '/' . $return_url);
}
/* This account has never created a channel. Send them to new_channel by default */
if($a->module === 'login') {
$r = q("select count(channel_id) as total from channel where channel_account_id = %d and channel_removed = 0 ",
intval($a->account['account_id'])
);
if(($r) && (! $r[0]['total']))
goaway(z_root() . '/new_channel');
}
/* else just return */
}
/**
* @brief Change to another channel with current logged-in account.
*
* @param int $change_channel The channel_id of the channel you want to change to
*
* @return bool|array false or channel record of the new channel
*/
function change_channel($change_channel) {
$ret = false;
if($change_channel) {
$r = q("select channel.*, xchan.* from channel left join xchan on channel.channel_hash = xchan.xchan_hash where channel_id = %d and channel_account_id = %d and channel_removed = 0 limit 1",
intval($change_channel),
intval(get_account_id())
);
// It's not there. Is this an administrator, and is this the sys channel?
if (is_developer()) {
if (! $r) {
if (is_site_admin()) {
$r = q("select channel.*, xchan.* from channel left join xchan on channel.channel_hash = xchan.xchan_hash where channel_id = %d and channel_system = 1 and channel_removed = 0 limit 1",
intval($change_channel)
);
}
}
}
if($r) {
$hash = $r[0]['channel_hash'];
$_SESSION['uid'] = intval($r[0]['channel_id']);
get_app()->set_channel($r[0]);
$_SESSION['theme'] = $r[0]['channel_theme'];
$_SESSION['mobile_theme'] = get_pconfig(local_channel(),'system', 'mobile_theme');
date_default_timezone_set($r[0]['channel_timezone']);
$ret = $r[0];
}
$x = q("select * from xchan where xchan_hash = '%s' limit 1",
dbesc($hash)
);
if($x) {
$_SESSION['my_url'] = $x[0]['xchan_url'];
$_SESSION['my_address'] = $r[0]['channel_address'] . '@' . substr(get_app()->get_baseurl(), strpos(get_app()->get_baseurl(), '://') + 3);
get_app()->set_observer($x[0]);
get_app()->set_perms(get_all_perms(local_channel(), $hash));
}
if(! is_dir('store/' . $r[0]['channel_address']))
@os_mkdir('store/' . $r[0]['channel_address'], STORAGE_DEFAULT_PERMISSIONS,true);
}
return $ret;
}
/**
* @brief Creates an additional SQL where statement to check permissions.
*
* @param int $owner_id
* @param bool $remote_observer - if unset use current observer
*
* @return string additional SQL where statement
*/
function permissions_sql($owner_id, $remote_observer = null) {
$local_channel = local_channel();
/**
* Construct permissions
*
* default permissions - anonymous user
*/
$sql = " AND allow_cid = ''
AND allow_gid = ''
AND deny_cid = ''
AND deny_gid = ''
";
/**
* Profile owner - everything is visible
*/
if(($local_channel) && ($local_channel == $owner_id)) {
$sql = '';
}
/**
* Authenticated visitor. Unless pre-verified,
* check that the contact belongs to this $owner_id
* and load the groups the visitor belongs to.
* If pre-verified, the caller is expected to have already
* done this and passed the groups into this function.
*/
else {
$observer = (($remote_observer) ? $remote_observer : get_observer_hash());
if($observer) {
$groups = init_groups_visitor($observer);
$gs = '<<>>'; // should be impossible to match
if(is_array($groups) && count($groups)) {
foreach($groups as $g)
$gs .= '|<' . $g . '>';
}
$regexop = db_getfunc('REGEXP');
$sql = sprintf(
" AND ( NOT (deny_cid like '%s' OR deny_gid $regexop '%s')
AND ( allow_cid like '%s' OR allow_gid $regexop '%s' OR ( allow_cid = '' AND allow_gid = '') )
)
",
dbesc(protect_sprintf( '%<' . $observer . '>%')),
dbesc($gs),
dbesc(protect_sprintf( '%<' . $observer . '>%')),
dbesc($gs)
);
}
}
return $sql;
}
/**
* @brief Creates an addiontal SQL where statement to check permissions for an item.
*
* @param int $owner_id
* @param bool $remote_observer, use current observer if unset
*
* @return string additional SQL where statement
*/
function item_permissions_sql($owner_id, $remote_observer = null) {
$local_channel = local_channel();
/**
* Construct permissions
*
* default permissions - anonymous user
*/
$sql = " AND item_private = 0 ";
/**
* Profile owner - everything is visible
*/
if(($local_channel) && ($local_channel == $owner_id)) {
$sql = '';
}
/**
* Authenticated visitor. Unless pre-verified,
* check that the contact belongs to this $owner_id
* and load the groups the visitor belongs to.
* If pre-verified, the caller is expected to have already
* done this and passed the groups into this function.
*/
else {
$observer = (($remote_observer) ? $remote_observer : get_observer_hash());
if($observer) {
$s = scopes_sql($owner_id,$observer);
$groups = init_groups_visitor($observer);
$gs = '<<>>'; // should be impossible to match
if(is_array($groups) && count($groups)) {
foreach($groups as $g)
$gs .= '|<' . $g . '>';
}
$regexop = db_getfunc('REGEXP');
$sql = sprintf(
" AND (( NOT (deny_cid like '%s' OR deny_gid $regexop '%s')
AND ( allow_cid like '%s' OR allow_gid $regexop '%s' OR ( allow_cid = '' AND allow_gid = '' AND item_private = 0 ))
) OR ( item_private = 1 $s ))
",
dbesc(protect_sprintf( '%<' . $observer . '>%')),
dbesc($gs),
dbesc(protect_sprintf( '%<' . $observer . '>%')),
dbesc($gs)
);
}
}
return $sql;
}
/**
* Remote visitors also need to be checked against the public_scope parameter if item_private is set.
* This function checks the various permutations of that field for any which apply to this observer.
*
*/
function scopes_sql($uid,$observer) {
$str = " and ( public_policy = 'authenticated' ";
if(! is_foreigner($observer))
$str .= " or public_policy = 'network: red' ";
if(local_channel())
$str .= " or public_policy = 'site: " . get_app()->get_hostname() . "' ";
$ab = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1",
dbesc($observer),
intval($uid)
);
if(! $ab)
return $str . " ) ";
if($ab[0]['abook_pending'])
$str .= " or public_policy = 'any connections' ";
$str .= " or public_policy = 'contacts' ) ";
return $str;
}
/**
* @param string $observer_hash
*
* @return string additional SQL where statement
*/
function public_permissions_sql($observer_hash) {
//$observer = get_app()->get_observer();
$groups = init_groups_visitor($observer_hash);
$gs = '<<>>'; // should be impossible to match
if(is_array($groups) && count($groups)) {
foreach($groups as $g)
$gs .= '|<' . $g . '>';
}
$sql = '';
if($observer_hash) {
$regexop = db_getfunc('REGEXP');
$sql = sprintf(
" OR (( NOT (deny_cid like '%s' OR deny_gid $regexop '%s')
AND ( allow_cid like '%s' OR allow_gid $regexop '%s' OR ( allow_cid = '' AND allow_gid = '' AND item_private = 0 ) )
))
",
dbesc(protect_sprintf( '%<' . $observer_hash . '>%')),
dbesc($gs),
dbesc(protect_sprintf( '%<' . $observer_hash . '>%')),
dbesc($gs)
);
}
return $sql;
}
/*
* Functions used to protect against Cross-Site Request Forgery
* The security token has to base on at least one value that an attacker can't know - here it's the session ID and the private key.
* In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
* or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
* The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
* A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
* If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
* Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
* so this mechanism brings in some damage control (the attacker would be able to forge a request to a form of this type, but not to forms of other types).
*/
function get_form_security_token($typename = '') {
$a = get_app();
$timestamp = time();
$sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
return $timestamp . '.' . $sec_hash;
}
function check_form_security_token($typename = '', $formname = 'form_security_token') {
if (!x($_REQUEST, $formname)) return false;
$hash = $_REQUEST[$formname];
$max_livetime = 10800; // 3 hours
$a = get_app();
$x = explode('.', $hash);
if (time() > (IntVal($x[0]) + $max_livetime)) return false;
$sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
return ($sec_hash == $x[1]);
}
function check_form_security_std_err_msg() {
return t('The form security token was not correct. This probably happened because the form has been opened for too long (>3 hours) before submitting it.') . EOL;
}
function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token') {
if (!check_form_security_token($typename, $formname)) {
$a = get_app();
logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
notice( check_form_security_std_err_msg() );
goaway($a->get_baseurl() . $err_redirect );
}
}
function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token') {
if (!check_form_security_token($typename, $formname)) {
$a = get_app();
logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
header('HTTP/1.1 403 Forbidden');
killme();
}
}
// Returns an array of group hash id's on this entire site (across all channels) that this connection is a member of.
// var $contact_id = xchan_hash of connection
function init_groups_visitor($contact_id) {
$groups = array();
$r = q("SELECT hash FROM `groups` left join group_member on groups.id = group_member.gid WHERE xchan = '%s' ",
dbesc($contact_id)
);
if(count($r)) {
foreach($r as $rr)
$groups[] = $rr['hash'];
}
return $groups;
}
// This is used to determine which uid have posts which are visible to the logged in user (from the API) for the
// public_timeline, and we can use this in a community page by making
// $perms = (PERMS_NETWORK|PERMS_PUBLIC) unless logged in.
// Collect uids of everybody on this site who has opened their posts to everybody on this site (or greater visibility)
// We always include yourself if logged in because you can always see your own posts
// resolving granular permissions for the observer against every person and every post on the site
// will likely be too expensive.
// Returns a string list of comma separated channel_ids suitable for direct inclusion in a SQL query
function stream_perms_api_uids($perms = NULL, $limit = 0, $rand = 0 ) {
$perms = is_null($perms) ? (PERMS_SITE|PERMS_NETWORK|PERMS_PUBLIC) : $perms;
$ret = array();
$limit_sql = (($limit) ? " LIMIT " . intval($limit) . " " : '');
$random_sql = (($rand) ? " ORDER BY " . db_getfunc('RAND') . " " : '');
if(local_channel())
$ret[] = local_channel();
$r = q("select channel_id from channel where channel_r_stream > 0 and ( channel_r_stream & %d )>0 and ( channel_pageflags & %d ) = 0 and channel_system = 0 and channel_removed = 0 $random_sql $limit_sql ",
intval($perms),
intval(PAGE_ADULT|PAGE_CENSORED)
);
if($r) {
foreach($r as $rr)
if(! in_array($rr['channel_id'], $ret))
$ret[] = $rr['channel_id'];
}
$str = '';
if($ret) {
foreach($ret as $rr) {
if($str)
$str .= ',';
$str .= intval($rr);
}
}
else
$str = "''";
logger('stream_perms_api_uids: ' . $str, LOGGER_DEBUG);
return $str;
}
function stream_perms_xchans($perms = NULL ) {
$perms = is_null($perms) ? (PERMS_SITE|PERMS_NETWORK|PERMS_PUBLIC) : $perms;
$ret = array();
if(local_channel())
$ret[] = get_observer_hash();
$r = q("select channel_hash from channel where channel_r_stream > 0 and (channel_r_stream & %d)>0 and not (channel_pageflags & %d)>0 and channel_system = 0 and channel_removed = 0 ",
intval($perms),
intval(PAGE_ADULT|PAGE_CENSORED)
);
if($r) {
foreach($r as $rr)
if(! in_array($rr['channel_hash'], $ret))
$ret[] = $rr['channel_hash'];
}
$str = '';
if($ret) {
foreach($ret as $rr) {
if($str)
$str .= ',';
$str .= "'" . dbesc($rr) . "'";
}
}
else
$str = "''";
logger('stream_perms_xchans: ' . $str, LOGGER_DEBUG);
return $str;
}
|
bashrc/hubzilla-debian
|
src/include/security.php
|
PHP
|
mit
| 14,745
|
<?php //@codingStandardsIgnoreFile ?>
<i class="fa-<?php echo $icon ?><?php if (isset($icon_class)): ?> <?php echo $icon_class ?><?php endif ?>"></i>
|
Djamy/platform
|
src/Oro/Bundle/LayoutBundle/Resources/views/Layout/php/icon_block.html.php
|
PHP
|
mit
| 150
|
/**
* @ngdoc service
* @name $ionicModal
* @module ionic
* @description
*
* Related: {@link ionic.controller:ionicModal ionicModal controller}.
*
* The Modal is a content pane that can go over the user's main view
* temporarily. Usually used for making a choice or editing an item.
*
* Put the content of the modal inside of an `<ion-modal-view>` element.
*
* **Notes:**
* - A modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating
* scope, passing in itself as an event argument. Both the modal.removed and modal.hidden events are
* called when the modal is removed.
*
* - This example assumes your modal is in your main index file or another template file. If it is in its own
* template file, remove the script tags and call it by file name.
*
* @usage
* ```html
* <script id="my-modal.html" type="text/ng-template">
* <ion-modal-view>
* <ion-header-bar>
* <h1 class="title">My Modal title</h1>
* </ion-header-bar>
* <ion-content>
* Hello!
* </ion-content>
* </ion-modal-view>
* </script>
* ```
* ```js
* angular.module('testApp', ['ionic'])
* .controller('MyController', function($scope, $ionicModal) {
* $ionicModal.fromTemplateUrl('my-modal.html', {
* scope: $scope,
* animation: 'slide-in-up'
* }).then(function(modal) {
* $scope.modal = modal;
* });
* $scope.openModal = function() {
* $scope.modal.show();
* };
* $scope.closeModal = function() {
* $scope.modal.hide();
* };
* //Cleanup the modal when we're done with it!
* $scope.$on('$destroy', function() {
* $scope.modal.remove();
* });
* // Execute action on hide modal
* $scope.$on('modal.hidden', function() {
* // Execute action
* });
* // Execute action on remove modal
* $scope.$on('modal.removed', function() {
* // Execute action
* });
* });
* ```
*/
IonicModule
.factory('$ionicModal', [
'$rootScope',
'$ionicBody',
'$compile',
'$timeout',
'$ionicPlatform',
'$ionicTemplateLoader',
'$q',
'$log',
function($rootScope, $ionicBody, $compile, $timeout, $ionicPlatform, $ionicTemplateLoader, $q, $log) {
/**
* @ngdoc controller
* @name ionicModal
* @module ionic
* @description
* Instantiated by the {@link ionic.service:$ionicModal} service.
*
* Be sure to call [remove()](#remove) when you are done with each modal
* to clean it up and avoid memory leaks.
*
* Note: a modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating
* scope, passing in itself as an event argument. Note: both modal.removed and modal.hidden are
* called when the modal is removed.
*/
var ModalView = ionic.views.Modal.inherit({
/**
* @ngdoc method
* @name ionicModal#initialize
* @description Creates a new modal controller instance.
* @param {object} options An options object with the following properties:
* - `{object=}` `scope` The scope to be a child of.
* Default: creates a child of $rootScope.
* - `{string=}` `animation` The animation to show & hide with.
* Default: 'slide-in-up'
* - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of
* the modal when shown. Default: false.
* - `{boolean=}` `backdropClickToClose` Whether to close the modal on clicking the backdrop.
* Default: true.
* - `{boolean=}` `hardwareBackButtonClose` Whether the modal can be closed using the hardware
* back button on Android and similar devices. Default: true.
*/
initialize: function(opts) {
ionic.views.Modal.prototype.initialize.call(this, opts);
this.animation = opts.animation || 'slide-in-up';
},
/**
* @ngdoc method
* @name ionicModal#show
* @description Show this modal instance.
* @returns {promise} A promise which is resolved when the modal is finished animating in.
*/
show: function(target) {
var self = this;
if(self.scope.$$destroyed) {
$log.error('Cannot call ' + self.viewType + '.show() after remove(). Please create a new ' + self.viewType + ' instance.');
return;
}
var modalEl = jqLite(self.modalEl);
self.el.classList.remove('hide');
$timeout(function(){
$ionicBody.addClass(self.viewType + '-open');
}, 400);
if(!self.el.parentElement) {
modalEl.addClass(self.animation);
$ionicBody.append(self.el);
}
if(target && self.positionView) {
self.positionView(target, modalEl);
}
modalEl.addClass('ng-enter active')
.removeClass('ng-leave ng-leave-active');
self._isShown = true;
self._deregisterBackButton = $ionicPlatform.registerBackButtonAction(
self.hardwareBackButtonClose ? angular.bind(self, self.hide) : angular.noop,
PLATFORM_BACK_BUTTON_PRIORITY_MODAL
);
self._isOpenPromise = $q.defer();
ionic.views.Modal.prototype.show.call(self);
$timeout(function(){
modalEl.addClass('ng-enter-active');
ionic.trigger('resize');
self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.shown', self);
self.el.classList.add('active');
}, 20);
return $timeout(function() {
//After animating in, allow hide on backdrop click
self.$el.on('click', function(e) {
if (self.backdropClickToClose && e.target === self.el) {
self.hide();
}
});
}, 400);
},
/**
* @ngdoc method
* @name ionicModal#hide
* @description Hide this modal instance.
* @returns {promise} A promise which is resolved when the modal is finished animating out.
*/
hide: function() {
var self = this;
var modalEl = jqLite(self.modalEl);
self.el.classList.remove('active');
modalEl.addClass('ng-leave');
$timeout(function(){
modalEl.addClass('ng-leave-active')
.removeClass('ng-enter ng-enter-active active');
}, 20);
self.$el.off('click');
self._isShown = false;
self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.hidden', self);
self._deregisterBackButton && self._deregisterBackButton();
ionic.views.Modal.prototype.hide.call(self);
return $timeout(function(){
$ionicBody.removeClass(self.viewType + '-open');
self.el.classList.add('hide');
}, self.hideDelay || 320);
},
/**
* @ngdoc method
* @name ionicModal#remove
* @description Remove this modal instance from the DOM and clean up.
* @returns {promise} A promise which is resolved when the modal is finished animating out.
*/
remove: function() {
var self = this;
self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.removed', self);
return self.hide().then(function() {
self.scope.$destroy();
self.$el.remove();
});
},
/**
* @ngdoc method
* @name ionicModal#isShown
* @returns boolean Whether this modal is currently shown.
*/
isShown: function() {
return !!this._isShown;
}
});
var createModal = function(templateString, options) {
// Create a new scope for the modal
var scope = options.scope && options.scope.$new() || $rootScope.$new(true);
options.viewType = options.viewType || 'modal';
extend(scope, {
$hasHeader: false,
$hasSubheader: false,
$hasFooter: false,
$hasSubfooter: false,
$hasTabs: false,
$hasTabsTop: false
});
// Compile the template
var element = $compile('<ion-' + options.viewType + '>' + templateString + '</ion-' + options.viewType + '>')(scope);
options.$el = element;
options.el = element[0];
options.modalEl = options.el.querySelector('.' + options.viewType);
var modal = new ModalView(options);
modal.scope = scope;
// If this wasn't a defined scope, we can assign the viewType to the isolated scope
// we created
if(!options.scope) {
scope[ options.viewType ] = modal;
}
return modal;
};
return {
/**
* @ngdoc method
* @name $ionicModal#fromTemplate
* @param {string} templateString The template string to use as the modal's
* content.
* @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.
* @returns {object} An instance of an {@link ionic.controller:ionicModal}
* controller.
*/
fromTemplate: function(templateString, options) {
var modal = createModal(templateString, options || {});
return modal;
},
/**
* @ngdoc method
* @name $ionicModal#fromTemplateUrl
* @param {string} templateUrl The url to load the template from.
* @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.
* options object.
* @returns {promise} A promise that will be resolved with an instance of
* an {@link ionic.controller:ionicModal} controller.
*/
fromTemplateUrl: function(url, options, _) {
var cb;
//Deprecated: allow a callback as second parameter. Now we return a promise.
if (angular.isFunction(options)) {
cb = options;
options = _;
}
return $ionicTemplateLoader.load(url).then(function(templateString) {
var modal = createModal(templateString, options || {});
cb && cb(modal);
return modal;
});
}
};
}]);
|
redspy/ClearProject
|
platforms/android/assets/www/lib/ionic/js/angular/service/modal.js
|
JavaScript
|
mit
| 9,667
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_55) on Fri Jun 20 06:34:27 EDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.client.solrj.request.CollectionAdminRequest.Reload (Solr 4.9.0 API)</title>
<meta name="date" content="2014-06-20">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.client.solrj.request.CollectionAdminRequest.Reload (Solr 4.9.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/solr/client/solrj/request/CollectionAdminRequest.Reload.html" title="class in org.apache.solr.client.solrj.request">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/solr/client/solrj/request/class-use/CollectionAdminRequest.Reload.html" target="_top">Frames</a></li>
<li><a href="CollectionAdminRequest.Reload.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.client.solrj.request.CollectionAdminRequest.Reload" class="title">Uses of Class<br>org.apache.solr.client.solrj.request.CollectionAdminRequest.Reload</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.client.solrj.request.CollectionAdminRequest.Reload</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/solr/client/solrj/request/CollectionAdminRequest.Reload.html" title="class in org.apache.solr.client.solrj.request">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/solr/client/solrj/request/class-use/CollectionAdminRequest.Reload.html" target="_top">Frames</a></li>
<li><a href="CollectionAdminRequest.Reload.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
|
knittledan/Location_Search_Prediction
|
thirdParty/solrSrc/docs/solr-solrj/org/apache/solr/client/solrj/request/class-use/CollectionAdminRequest.Reload.html
|
HTML
|
mit
| 5,292
|
import Dashboard from './components/Dashboard'
export function dashboardPlugin(context) {
context.on('application:routes', opts => {
console.info('dashboardPlugin - application:routes')
console.log('dashboardPlugin - application:routes', opts)
opts.nextState.routes.push({
id: 'dashboard',
entries: [
{
path: 'dashboard',
name: 'dashboard',
component: Dashboard,
}
]
})
console.log('dashboardPlugin - application:routes - return', opts)
return opts
})
return {
getName: () => 'dashboardPlugin'
}
}
|
anthonny/dev.hubpress.io
|
hubpress-plugins/dashboard/index.js
|
JavaScript
|
mit
| 602
|
//
// ELCodable_osx.h
// ELCodable_osx
//
// Created by Brandon Sneed on 6/16/16.
// Copyright © 2016 WalmartLabs. All rights reserved.
//
#import <Cocoa/Cocoa.h>
//! Project version number for ELCodable_osx.
FOUNDATION_EXPORT double ELCodable_osxVersionNumber;
//! Project version string for ELCodable_osx.
FOUNDATION_EXPORT const unsigned char ELCodable_osxVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <ELCodable_osx/PublicHeader.h>
|
modulo-dm/modulo
|
Modules/ELCodable/ELCodable_osx/ELCodable_osx.h
|
C
|
mit
| 526
|
-- selectA.test
--
-- execsql {
-- SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
-- ORDER BY a,c,b
-- }
SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1
ORDER BY a,c,b
|
bkiers/sqlite-parser
|
src/test/resources/selectA.test_18.sql
|
SQL
|
mit
| 185
|
/** @type {import("../../../../").Configuration} */
module.exports = {
name: "compiler-name",
module: {
rules: [
{
test: /a\.js$/,
compiler: "compiler",
use: "./loader"
},
{
test: /b\.js$/,
compiler: "other-compiler",
use: "./loader"
}
]
}
};
|
webpack/webpack
|
test/configCases/rule-set/compiler/webpack.config.js
|
JavaScript
|
mit
| 286
|
/*jshint node:true*/
module.exports = {
description: '<%= name %>',
normalizeEntityName: function () {},
afterInstall: function(options) {
return this.addPackagesToProject([{
name: 'ember-jsonapi-resources',
target: '~1.1.2'
}]);
}
};
|
proteamer/ember-jsonapi-resources
|
blueprints/jsonapi-blueprint/files/blueprints/__name__/index.js
|
JavaScript
|
mit
| 265
|
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by SpecFlow (http://www.specflow.org/).
// SpecFlow Version:3.0.0.0
// SpecFlow Generator Version:3.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#region Designer generated code
#pragma warning disable
namespace BddTraining.Specs.Features.Files
{
using TechTalk.SpecFlow;
[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "3.0.0.0")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[TechTalk.SpecRun.FeatureAttribute("Add To Cart", Description="\tIn order to place an order\r\n\tAs an online shopper\r\n\tI want to add products to my" +
" shopping cart", SourceFile="Files\\Add to Cart.feature", SourceLine=0)]
public partial class AddToCartFeature
{
private TechTalk.SpecFlow.ITestRunner testRunner;
#line 1 "Add to Cart.feature"
#line hidden
[TechTalk.SpecRun.FeatureInitialize()]
public virtual void FeatureSetup()
{
testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Add To Cart", "\tIn order to place an order\r\n\tAs an online shopper\r\n\tI want to add products to my" +
" shopping cart", ProgrammingLanguage.CSharp, ((string[])(null)));
testRunner.OnFeatureStart(featureInfo);
}
[TechTalk.SpecRun.FeatureCleanup()]
public virtual void FeatureTearDown()
{
testRunner.OnFeatureEnd();
testRunner = null;
}
public virtual void TestInitialize()
{
}
[TechTalk.SpecRun.ScenarioCleanup()]
public virtual void ScenarioTearDown()
{
testRunner.OnScenarioEnd();
}
public virtual void ScenarioInitialize(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
{
testRunner.OnScenarioInitialize(scenarioInfo);
}
public virtual void ScenarioStart()
{
testRunner.OnScenarioStart();
}
public virtual void ScenarioCleanup()
{
testRunner.CollectScenarioErrors();
}
[TechTalk.SpecRun.ScenarioAttribute("Add to Cart", SourceLine=5)]
public virtual void AddToCart()
{
TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Add to Cart", null, ((string[])(null)));
#line 6
this.ScenarioInitialize(scenarioInfo);
this.ScenarioStart();
#line hidden
TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"price",
"isimported",
"type"});
table1.AddRow(new string[] {
"Domain Driven Design",
"500",
"false",
"Book"});
#line 7
testRunner.Given("I have the following product:", ((string)(null)), table1, "Given ");
#line 10
testRunner.When("I add the product to my cart", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"price",
"quantity"});
table2.AddRow(new string[] {
"Domain Driven Design",
"500",
"1"});
#line 11
testRunner.Then("My cart item should look like the following:", ((string)(null)), table2, "Then ");
#line hidden
this.ScenarioCleanup();
}
[TechTalk.SpecRun.TestRunCleanup()]
public virtual void TestRunCleanup()
{
TechTalk.SpecFlow.TestRunnerManager.GetTestRunner().OnTestRunEnd();
}
}
}
#pragma warning restore
#endregion
|
frankwang0/bdd-tdd-starter-kit
|
ShoppingCart/BddTraining.Specs.Features/Files/Add to Cart.feature.cs
|
C#
|
mit
| 4,349
|
from i3pystatus import IntervalModule
from i3pystatus.core.util import internet, require
from datetime import datetime
from urllib.request import urlopen
import json
import re
GEOLOOKUP_URL = 'http://api.wunderground.com/api/%s/geolookup%s/q/%s.json'
STATION_QUERY_URL = 'http://api.wunderground.com/api/%s/%s/q/%s.json'
class Wunderground(IntervalModule):
'''
This module retrieves weather data using the Weather Underground API.
.. note::
A Weather Underground API key is required to use this module, you can
sign up for a developer API key free at
https://www.wunderground.com/weather/api/
A developer API key is allowed 500 queries per day, and no more than 10
in a given minute. Therefore, it is recommended to be conservative when
setting the update interval.
Valid values for ``location_code`` include:
* **State/City_Name** - CA/San_Francisco
* **Country/City** - France/Paris
* **Geolocation by IP** - autoip
* **Zip or Postal Code** - 60616
* **ICAO Airport Code** - icao:LAX
* **Latitude/Longitude** - 41.8301943,-87.6342619
* **Personal Weather Station (PWS)** - pws:KILCHICA30
When not using a ``pws`` or ``icao`` station ID, the location will be
queried, and the closest station will be used. For a list of PWS
station IDs, visit the following URL:
http://www.wunderground.com/weatherstation/ListStations.asp
.. _weather-usage-wunderground:
.. rubric:: Usage example
.. code-block:: python
from i3pystatus import Status
from i3pystatus.weather import wunderground
status = Status()
status.register(
'weather',
format='{condition} {current_temp}{temp_unit}{icon}[ Hi: {high_temp}] Lo: {low_temp}',
colorize=True,
backend=wunderground.Wunderground(
api_key='dbafe887d56ba4ad',
location_code='pws:MAT645',
units='imperial',
),
)
status.run()
See :ref:`here <weather-formatters>` for a list of formatters which can be
used.
'''
interval = 300
settings = (
('api_key', 'Weather Underground API key'),
('location_code', 'Location code from wunderground.com'),
('units', '\'metric\' or \'imperial\''),
('use_pws', 'Set to False to use only airport stations'),
('forecast', 'Set to ``True`` to check forecast (generates one '
'additional API request per weather update). If set to '
'``False``, then the ``low_temp`` and ``high_temp`` '
'formatters will be set to empty strings.'),
)
required = ('api_key', 'location_code')
api_key = None
location_code = None
units = 'metric'
use_pws = True
forecast = False
# These will be set once weather data has been checked
station_id = None
forecast_url = None
@require(internet)
def api_request(self, url):
'''
Execute an HTTP POST to the specified URL and return the content
'''
with urlopen(url) as content:
try:
content_type = dict(content.getheaders())['Content-Type']
charset = re.search(r'charset=(.*)', content_type).group(1)
except AttributeError:
charset = 'utf-8'
response = json.loads(content.read().decode(charset))
try:
raise Exception(response['response']['error']['description'])
except KeyError:
pass
return response
@require(internet)
def geolookup(self):
'''
Use the location_code to perform a geolookup and find the closest
station. If the location is a pws or icao station ID, no lookup will be
peformed.
'''
if self.station_id is None:
try:
for no_lookup in ('pws', 'icao'):
sid = self.location_code.partition(no_lookup + ':')[-1]
if sid:
self.station_id = self.location_code
return
except AttributeError:
# Numeric or some other type, either way we'll just stringify
# it below and perform a lookup.
pass
extra_opts = '/pws:0' if not self.use_pws else ''
api_url = GEOLOOKUP_URL % (self.api_key,
extra_opts,
self.location_code)
response = self.api_request(api_url)
station_type = 'pws' if self.use_pws else 'airport'
try:
stations = response['location']['nearby_weather_stations']
nearest = stations[station_type]['station'][0]
except (KeyError, IndexError):
raise Exception('No locations matched location_code %s'
% self.location_code)
if self.use_pws:
nearest_pws = nearest.get('id', '')
if not nearest_pws:
raise Exception('No id entry for station')
self.station_id = 'pws:%s' % nearest_pws
else:
nearest_airport = nearest.get('icao', '')
if not nearest_airport:
raise Exception('No icao entry for station')
self.station_id = 'icao:%s' % nearest_airport
@require(internet)
def get_forecast(self):
'''
If configured to do so, make an API request to retrieve the forecast
data for the configured/queried weather station, and return the low and
high temperatures. Otherwise, return two empty strings.
'''
if self.forecast:
query_url = STATION_QUERY_URL % (self.api_key,
'forecast',
self.station_id)
try:
response = self.api_request(query_url)['forecast']
response = response['simpleforecast']['forecastday'][0]
except (KeyError, IndexError, TypeError):
raise Exception('No forecast data found for %s' % self.station_id)
unit = 'celsius' if self.units == 'metric' else 'fahrenheit'
low_temp = response.get('low', {}).get(unit, '')
high_temp = response.get('high', {}).get(unit, '')
return low_temp, high_temp
else:
return '', ''
@require(internet)
def weather_data(self):
'''
Query the configured/queried station and return the weather data
'''
# If necessary, do a geolookup to set the station_id
self.geolookup()
query_url = STATION_QUERY_URL % (self.api_key,
'conditions',
self.station_id)
try:
response = self.api_request(query_url)['current_observation']
self.forecast_url = response.pop('ob_url', None)
except KeyError:
raise Exception('No weather data found for %s' % self.station_id)
low_temp, high_temp = self.get_forecast()
if self.units == 'metric':
temp_unit = 'c'
speed_unit = 'kph'
distance_unit = 'km'
pressure_unit = 'mb'
else:
temp_unit = 'f'
speed_unit = 'mph'
distance_unit = 'mi'
pressure_unit = 'in'
def _find(key, data=None):
data = data or response
return data.get(key, 'N/A')
try:
observation_time = int(_find('observation_epoch'))
except TypeError:
observation_time = 0
return dict(
city=_find('city', response['observation_location']),
condition=_find('weather'),
observation_time=datetime.fromtimestamp(observation_time),
current_temp=_find('temp_' + temp_unit),
low_temp=low_temp,
high_temp=high_temp,
temp_unit='°' + temp_unit.upper(),
feelslike=_find('feelslike_' + temp_unit),
dewpoint=_find('dewpoint_' + temp_unit),
wind_speed=_find('wind_' + speed_unit),
wind_unit=speed_unit,
wind_direction=_find('wind_dir'),
wind_gust=_find('wind_gust_' + speed_unit),
pressure=_find('pressure_' + pressure_unit),
pressure_unit=pressure_unit,
pressure_trend=_find('pressure_trend'),
visibility=_find('visibility_' + distance_unit),
visibility_unit=distance_unit,
humidity=_find('relative_humidity').rstrip('%'),
uv_index=_find('uv'),
)
|
eBrnd/i3pystatus
|
i3pystatus/weather/wunderground.py
|
Python
|
mit
| 8,899
|
// Try CodeIQ Q3264
// author: Leonardone @ NEETSDKASU
package main
import (
"fmt"
"strings"
)
func Solve(target string, words []string) (ans []string) {
for _, w := range words {
switch {
case w == target:
ans = append(ans, "["+w+"]")
case strings.Contains(w, target):
ans = append(ans, strings.Replace(w, target, "="+target+"=", -1))
default:
ans = append(ans, w)
}
}
return
}
func main() {
var target string
fmt.Scan(&target)
words := make([]string, 0, 100)
for {
var w string
if _, err := fmt.Scan(&w); err != nil {
break
}
words = append(words, w)
}
ans := Solve(target, words)
for i, w := range ans {
if i > 0 {
fmt.Print(" ")
}
fmt.Print(w)
}
fmt.Println()
}
|
neetsdkasu/CodeIQ-MySolutions
|
Q3264_Colorize/main.go
|
GO
|
mit
| 721
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Slokas extends CI_Controller
{
var $currentModule="";
var $title="";
public function __construct()
{
global $menudata;
parent:: __construct();
$this->load->helper("url");
$this->load->library('form_validation');
if($this->uri->segment(2)!="" && $this->uri->segment(2)!="submit" && !in_array($this->uri->segment(2), $this->skipActions))
$title=$this->uri->segment(2); //Second segment of uri for action,In case of edit,view,add etc.
else
$title=$this->master_arr['index'];
$this->currentModule=$this->uri->segment(1);
$this->data['currentModule']=$this->currentModule;
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->load->model('Slokas_model');
//print_r($this->get_menu_data()); die;
}
public function index()
{
$this->load->view('header',$this->data);
$this->data['slokas_details']=$this->Slokas_model->get_slokas_details();
$this->load->view('Slokas/view',$this->data);
$this->load->view('footer');
}
public function view()
{
$this->load->view('header',$this->data);
$this->data['slokas_details']=$this->Slokas_model->get_slokas_details();
$this->load->view('Slokas/view',$this->data);
$this->load->view('footer');
}
public function add()
{
$this->load->view('header',$this->data);
$this->data['slokas_details']=$this->Slokas_model->get_slokas_details();
$this->load->view('Slokas/add',$this->data);
$this->load->view('footer');
}
public function submit()
{
$config=array(
array('field' => 'title',
'label' => 'Title',
'rules' => 'trim|required'
),
array('field' => 'description',
'label' => 'Description',
'rules' => 'trim|required'
)
);
$this->form_validation->set_rules($config);
$id=$this->input->post('id');
$target_dir = "uploads/slokas/";
$target_file = $target_dir .basename($_FILES["attachment"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($id=="")
{
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header');
$this->load->view('Slokas/add', $this->data);
$this->load->view('footer');
}
else
{
// print_r($_FILES); die;
// $target_dir = "uploads/slokas/";
// $target_file = $target_dir .basename($_FILES["attachment"]["name"]);
// $uploadOk = 1;
// $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
// $check = getimagesize($_FILES["attachment"]["tmp_name"]);
// if($check !== false) {
// echo "File is an image - " . $check["mime"] . ".";
// $uploadOk = 1;
// } else {
// echo "File is not an image.";
// $uploadOk = 0;
// }
// Check if file already exists
// if (file_exists($target_file)) {
// echo "Sorry, file already exists.";
// $uploadOk = 0;
// }
// // Check file size
// if ($_FILES["attachment"]["size"] > 500000)
// {
// echo "Sorry, your file is too large.";
// $uploadOk = 0;
// }
// // Allow certain file formats
// if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
// {
// echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
// $uploadOk = 0;
// }
// Check if $uploadOk is set to 0 by an error
// if ($uploadOk == 0)
// {
// echo "Sorry, your file was not uploaded.";
// // if everything is ok, try to upload file
// }
// else
// {
if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_file))
{
//echo "The file ". basename( $_FILES["attachment"]["name"]). " has been uploaded.";
}
// }
$title=$this->input->post("title");
$description= ($this->input->post("description"));
$attachment=$_FILES["attachment"]["name"];
$insert_array=array("title"=>$title,"description"=>$description,"attachment"=>$attachment,"inserted_by"=>$this->session->userdata("uid"),"inserted_datetime"=>date("Y-m-d H:i:s"));
$this->db->insert('slokas_master', $insert_array);
$last_inserted_id=$this->db->insert_id();
if($last_inserted_id)
{
redirect(base_url("Slokas/view?error=0"));
}
else
{
redirect(base_url("Slokas/view?error=1"));
}
}
}
else
{
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header');
//print_r($this->input->post()); die;
$slok_id=$this->input->post("id");
$this->data['slokas_details']= array_shift($this->Slokas_model->get_slokas_details($slok_id));
$this->load->view('Slokas/edit', $this->data);
$this->load->view('footer');
}
else
{
if($_FILES["attachment"]["name"]!="")
{
@move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_file);
}
$sid=$this->input->post("id");
$title=$this->input->post("title");
$description=$this->input->post("description");
$attachment=$_FILES["attachment"]["name"];
$update_array=array("title"=>$title,"description"=>$description,"updated_by"=>$this->session->userdata("uid"),"updated_datetime"=>date("Y-m-d H:i:s"));
if($_FILES["attachment"]["name"]!="")
{
$update_array["attachment"]=$attachment;
}
$where=array("sid"=>$sid);
$this->db->where($where);
if($this->db->update('slokas_master', $update_array))
{
redirect(base_url("Slokas/view?error=0"));
}
else
{
redirect(base_url("Slokas/view?error=1"));
}
$this->db->update('slokas_master', $update_array,"sid='".$id."'");
redirect(base_url("Location/view"));
}
}
}
public function edit()
{
$this->load->view('header');
$slok_id=$this->uri->segment(3);
$this->data['slokas_details']= array_shift($this->Slokas_model->get_slokas_details($slok_id));
$this->load->view('Slokas/edit',$this->data);
$this->load->view('footer');
}
public function disable()
{
ini_set("display_errors", "on");
$this->load->view('header');
$slok_id=$this->uri->segment(3);
// $update_array=array("status"=>"N","updated_datetime"=>date("Y-m-d H:i:s"));
$update_array=array("status"=>"N");
$where=array("sid"=>$slok_id);
$this->db->where($where);
if($this->db->update('slokas_master', $update_array))
{
redirect(base_url("Slokas/view?error=0"));
}
else
{
redirect(base_url("Slokas/view?error=1"));
}
$this->load->view('footer');
}
public function enable()
{
$this->load->view('header');
$slok_id=$this->uri->segment(3);
$update_array=array("status"=>"Y","updated_datetime"=>date("Y-m-d H:i:s"));
$where=array("sid"=>$slok_id);
$this->db->where($where);
if($this->db->update('slokas_master', $update_array))
{
redirect(base_url("Slokas/view?error=0"));
}
else
{
redirect(base_url("Slokas/view?error=1"));
}
$this->load->view('footer');
}
public function search()
{
$title=$this->input->post("title");
$slokas_details= $this->Slokas_model->get_slokas_details_search($title);
echo json_encode(array("slokas_details"=>$slokas_details));
}
}
|
jugalrathore/gradeupfinal
|
application/controllers/Slokas.php
|
PHP
|
mit
| 9,731
|
##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
#
# frozen_string_literal: true
module Twilio
module REST
class Pricing < Domain
class V1 < Version
class PhoneNumberList < ListResource
##
# Initialize the PhoneNumberList
# @param [Version] version Version that contains the resource
# @return [PhoneNumberList] PhoneNumberList
def initialize(version)
super(version)
# Path Solution
@solution = {}
# Components
@countries = nil
end
##
# Access the countries
# @param [String] iso_country The {ISO country
# code}[http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2] of the pricing
# information to fetch.
# @return [CountryList]
# @return [CountryContext] if iso_country was passed.
def countries(iso_country=:unset)
raise ArgumentError, 'iso_country cannot be nil' if iso_country.nil?
if iso_country != :unset
return CountryContext.new(@version, iso_country, )
end
@countries ||= CountryList.new(@version, )
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Pricing.V1.PhoneNumberList>'
end
end
class PhoneNumberPage < Page
##
# Initialize the PhoneNumberPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [PhoneNumberPage] PhoneNumberPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of PhoneNumberInstance
# @param [Hash] payload Payload response from the API
# @return [PhoneNumberInstance] PhoneNumberInstance
def get_instance(payload)
PhoneNumberInstance.new(@version, payload, )
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Pricing.V1.PhoneNumberPage>'
end
end
class PhoneNumberInstance < InstanceResource
##
# Initialize the PhoneNumberInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @return [PhoneNumberInstance] PhoneNumberInstance
def initialize(version, payload)
super(version)
# Marshaled Properties
@properties = {'name' => payload['name'], 'url' => payload['url'], 'links' => payload['links'], }
end
##
# @return [String] The name
def name
@properties['name']
end
##
# @return [String] The url
def url
@properties['url']
end
##
# @return [String] The links
def links
@properties['links']
end
##
# Provide a user friendly representation
def to_s
"<Twilio.Pricing.V1.PhoneNumberInstance>"
end
##
# Provide a detailed, user friendly representation
def inspect
"<Twilio.Pricing.V1.PhoneNumberInstance>"
end
end
end
end
end
end
|
philnash/twilio-ruby
|
lib/twilio-ruby/rest/pricing/v1/phone_number.rb
|
Ruby
|
mit
| 3,668
|
/*******************************************************************************
** ArrayOperations.h
** Part of the mutual information toolbox
**
** Contains functions to floor arrays, and to merge arrays into a joint
** state.
**
** Author: Adam Pocock
** Created 17/2/2010
** Updated - 22/02/2014 - Added checking on calloc, and an increment array function.
**
** Copyright 2010,2014 Adam Pocock, The University Of Manchester
** www.cs.manchester.ac.uk
**
** This file is part of MIToolbox, licensed under the 3-clause BSD license.
*******************************************************************************/
#ifndef __ArrayOperations_H
#define __ArrayOperations_H
#ifdef __cplusplus
extern "C" {
#endif
/*******************************************************************************
** A version of calloc which checks to see if memory was allocated.
*******************************************************************************/
void* checkedCalloc(size_t vectorLength, size_t sizeOfType);
/*******************************************************************************
** Increments each value in a double array
*******************************************************************************/
void incrementVector(double* vector, int vectorLength);
/*******************************************************************************
** Simple print functions for debugging
*******************************************************************************/
void printDoubleVector(double *vector, int vectorlength);
void printIntVector(int *vector, int vectorLength);
/*******************************************************************************
** numberOfUniqueValues finds the number of unique values in an array by
** repeatedly iterating through the array and checking if a value has been
** seen previously
*******************************************************************************/
int numberOfUniqueValues(double *featureVector, int vectorLength);
/*******************************************************************************
** normaliseArray takes an input vector and writes an output vector
** which is a normalised version of the input, and returns the number of states
** A normalised array has min value = 0, max value = number of states
** and all values are integers
**
** length(inputVector) == length(outputVector) == vectorLength otherwise there
** is a memory leak
*******************************************************************************/
int normaliseArray(double *inputVector, int *outputVector, int vectorLength);
/*******************************************************************************
** mergeArrays takes in two arrays and writes the joint state of those arrays
** to the output vector
**
** the length of the vectors must be the same and equal to vectorLength
*******************************************************************************/
int mergeArrays(double *firstVector, double *secondVector, double *outputVector, int vectorLength);
int mergeArraysArities(double *firstVector, int numFirstStates, double *secondVector, int numSecondStates, double *outputVector, int vectorLength);
/*******************************************************************************
** mergeMultipleArrays takes in a matrix and repeatedly merges the matrix using
** merge arrays and writes the joint state of that matrix
** to the output vector
**
** the length of the vectors must be the same and equal to vectorLength
** matrixWidth = the number of columns in the matrix
*******************************************************************************/
int mergeMultipleArrays(double *inputMatrix, double *outputVector, int matrixWidth, int vectorLength);
int mergeMultipleArraysArities(double *inputMatrix, double *outputVector, int matrixWidth, int *arities, int vectorLength);
#ifdef __cplusplus
}
#endif
#endif
|
chappers/sklearn-recipes
|
streaming_take2/LOFS_Octave/source_codes/ArrayOperations.h
|
C
|
mit
| 3,884
|
/**
* Module for filters
*/
(function () {
'use strict';
angular.module('<%= appName %>.filters', []);
})();
|
michikono/generator-angular-enterprise
|
generators/app/templates/%CLIENTSIDEFOLDER%/%APPSUBFOLDER%/filters/filters.module.js
|
JavaScript
|
mit
| 116
|
<?php
/**
* Author: Hassletauf <hassletauf@gmail.com>
* Date: 10/6/2016
* Time: 6:28 PM
*/
namespace Konnektive\Tests\Request;
use Illuminate\Validation\ValidationException;
use Konnektive\Request\Customer\AddCustomerNoteRequest;
use Konnektive\Request\Customer\QueryCustomerHistoryRequest;
use Konnektive\Request\Customer\QueryCustomersRequest;
use Konnektive\Request\Customer\UpdateCustomerRequest;
use Konnektive\Request\LandingPage\ImportClickRequest;
use Konnektive\Request\Membership\CancelClubMembership;
use Konnektive\Request\Membership\QueryClubMembersRequest;
use Konnektive\Request\Membership\ReactiveClubMembership;
use Konnektive\Request\Order\CancelOrderRequest;
use Konnektive\Request\Order\ConfirmOrderRequest;
use Konnektive\Request\Order\ImportLeadRequest;
use Konnektive\Request\Order\ImportOrderRequest;
use Konnektive\Request\Order\ImportUpsaleRequest;
use Konnektive\Request\Order\OrderQARequest;
use Konnektive\Request\Order\PreauthOrderRequest;
use Konnektive\Request\Order\QueryOrderRequest;
use Konnektive\Request\Order\RefundOrderRequest;
use Konnektive\Request\Order\RerunDeclinedSaleRequest;
use Konnektive\Request\Order\UpdateFulfillmentRequest;
use Konnektive\Request\Purchase\CancelPurchaseRequest;
use Konnektive\Request\Purchase\QueryPurchasesRequest;
use Konnektive\Request\Purchase\RefundPurchaseRequest;
use Konnektive\Request\Purchase\UpdatePurchaseRequest;
use Konnektive\Request\Report\QueryCampaignRequest;
use Konnektive\Request\Report\QueryMidSummaryReportRequest;
use Konnektive\Request\Report\QueryRetentionReportRequest;
use Konnektive\Request\Request;
use Konnektive\Request\Transaction\QueryTransactionsRequest;
use Konnektive\Request\Transaction\UpdateTransactionRequest;
use Konnektive\Tests\TestCase;
class RequestTest extends TestCase
{
private $testClasses = [
//Customer
AddCustomerNoteRequest::class,
QueryCustomerHistoryRequest::class,
QueryCustomersRequest::class,
UpdateCustomerRequest::class,
//Landing Page
ImportClickRequest::class,
//Membership
CancelClubMembership::class,
QueryClubMembersRequest::class,
ReactiveClubMembership::class,
//Order
CancelOrderRequest::class,
ConfirmOrderRequest::class,
ImportLeadRequest::class,
ImportOrderRequest::class,
ImportUpsaleRequest::class,
OrderQARequest::class,
PreauthOrderRequest::class,
QueryOrderRequest::class,
RefundOrderRequest::class,
UpdateFulfillmentRequest::class,
RerunDeclinedSaleRequest::class,
//Purchase
CancelPurchaseRequest::class,
QueryPurchasesRequest::class,
RefundPurchaseRequest::class,
UpdatePurchaseRequest::class,
//Report
QueryCampaignRequest::class,
QueryMidSummaryReportRequest::class,
QueryRetentionReportRequest::class,
//Transaction
QueryTransactionsRequest::class,
UpdateTransactionRequest::class
];
private function getValidFillData()
{
return [
"achAccountNumber" => "22222222222222",
"achAccountType" => "CHECKING",
"achRoutingNumber" => "111111111",
"action" => "APPROVE",
"address1" => "123 Fake St.",
"address2" => "Suite 12",
"affId" => "TestAff",
"affiliateId" => "TestAff",
"afterNextBill",
"billNow",
"billShipSame" => "0",
"billingIntervalDays",
"callCenterId",
"campaignId" => "22",
"campaignName" => "Test Face Cream",
"campaignType",
"cancelReason" => "I don't like stuff",
"cardBin" => "444444",
"cardExpiryDate" => "02/2020",
"cardLast4" => "1111",
"cardMonth" => "02",
"cardNumber" => "4111111111111111",
"cardSecurityCode" => "123",
"cardYear" => "2020",
"chargebackAmount" => "20.02",
"chargebackDate" => "02/15/2020",
"chargebackNote" => "Chargebacking for some reason",
"chargebackReasonCode" => "666",
"city" => "Denver",
"clubId" => "200",
"companyName" => "TestCompany",
"country" => "US",
"couponCode" => "Testcoupon",
"custom1" => "Customization",
"custom2" => "Customization",
"custom3" => "Customization",
"custom4" => "Customization",
"custom5" => "Customization",
"customerId" => "123123",
"dateRangeType",
"dateReturned" => '02/15/2002',
"dateShipped" => "02/15/2020",
"emailAddress" => "test@email.com",
"endDate" => "02/15/2019",
"errorRedirectsTo" => "http://localhost",
"finalBillingCycle",
"firstName" => "TestFirst",
"forceQA",
"fulfillmentId" => "999",
"fulfillmentStatus" => "SHIPPED", //SHIPPED,RMA_PENDING,RETURNED,CANCELLED
"fullRefund" => true,
"include",
"insureShipment",
"ipAddress" => "192.168.0.1",
"isChargedback",
"isDeclineSave",
"lastName" => "TestLast",
"loginId" => "SomeValidStringForID",
"maxCycles",
"memberId" => "444",
"merchantId" => "555",
"merchantTxnId" => "666",
"message" => "TestMessage",
"midId" => "123123",
"newMerchantId" => "834384",
"nextBillDate",
"orderId" => "10",
"orderStatus",
"page",
"pageType" => "thankyouPage", //presellPage,leadPage,checkoutPage,upsellPage1,upsellPage2,upsellPage3,upsellPage4,thankyouPage
"password" => "SomeValidPassword",
"paySource" => "CREDITCARD", //CREDITCARD,CHECK,ACCTONFILE,PREPAID
"phoneNumber" => "8018888888",
"postalCode" => "80188",
"preAuthBillerId",
"preAuthMerchantTxnId",
"price",
'product1_id' => '1',
'product1_qty' => '2',
'product1_price' => '2.00',
'product1_shipPrice' => '1.00',
"productId" => "123123123",
"productPrice",
"productQty",
"productSalesTax",
"productShipPrice",
"purchaseId" => "1000001",
"reactivate",
"redirectsTo",
"refundAmount" => "10.00",
"replaceProductId",
"reportType" => "campaign", //campaign,source,mid
"requestUri" => "http://localhost",
"responseType",
"resultsPerPage",
"rmaNumber" => "123123123",
"salesTax",
"sessionId" => "454545",
"shipAddress1" => "123 Fake St.",
"shipAddress2",
"shipCarrier",
"shipCity" => "Salt Lake City",
"shipCompanyName" => "Fake shipping company",
"shipCountry" => "US",
"shipFirstName" => "Test",
"shipLastName" => "Tester",
"shipMethod",
"shipPostalCode" => "84040",
"shipProfileId",
"shipState" => "TN",
"shippingPrice",
"sortDir",
"sourceValue1",
"sourceValue2",
"sourceValue3",
"sourceValue4",
"sourceValue5",
"startDate" => "02/15/2002",
"state" => "UT",
"status",
"trackingNumber" => "AA123456789AA",
"transactionId" => "123123123",
"txnType",
"userAgent" => "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
];
}
public function testRequestValidationSuccess()
{
$data = $this->getValidFillData();
foreach ($this->testClasses as $class) {
/**
* @var $request Request
*/
$request = new $class();
switch ($class) {
case QueryTransactionsRequest::class:
$data['achAccountNumber'] = substr($data['achAccountNumber'], -4, 4);
break;
}
$this->fillModel($request, $data);
$this->assertValid($request);
}
}
private function fillModel(&$request, $data = null)
{
if (!isset($data) || !is_array($data)) {
$data = $this->getValidFillData();
}
switch (get_class($request)) {
case QueryTransactionsRequest::class:
$data['achAccountNumber'] = substr($data['achAccountNumber'], -4, 4);
break;
}
foreach ($request->rules() as $key => $rule) {
if (isset($data[$key])) {
$request->$key = $data[$key];
}
}
}
public function testDynamicProductsInOrderRequestSuccess()
{
$request = new ImportOrderRequest();
$this->fillModel($request);
$request->product2_id = "20";
$request->product2_price = "2.00";
$this->assertValid($request);
}
public function testDynamicProductsWithJustProductId(){
$request = new ImportOrderRequest();
$this->fillModel($request);
$request->product1_id = "10";
$request->product2_id = "20";
$this->assertValid($request);
}
public function testDynamicProductsInOrderRequestFailure()
{
$request = new ImportOrderRequest();
$this->fillModel($request);
//Should fail with product2_id being required
$request->product2_price = "2.00";
$this->assertInvalid($request);
}
public function testLeadsImportBillShipNotSame()
{
$request = new ImportLeadRequest();
$this->fillModel($request);
$request->billShipSame = false;
$this->assertValid($request);
}
public function testImportOrderBillShipNotSame()
{
$request = new ImportOrderRequest();
$this->fillModel($request);
$request->billShipSame = false;
$this->assertValid($request);
}
public function testImportOrderCheckPaySource()
{
$request = new ImportOrderRequest();
$this->fillModel($request);
$request->paySource = "CHECK";
$this->assertValid($request);
}
public function testImportOrderCreditCardPaySource()
{
$request = new ImportOrderRequest();
$this->fillModel($request);
$request->paySource = "CREDITCARD";
$this->assertValid($request);
}
public function testOrderQueryMissingCustomerAndOrder()
{
$request = new QueryOrderRequest();
$this->fillModel($request);
$request->customerId = null;
$request->orderId = null;
$this->assertValid($request);
}
public function testRefundOrderFullRefundFalse()
{
$request = new RefundOrderRequest();
$this->fillModel($request);
$request->fullRefund = false;
$this->assertValid($request);
}
public function testUpdateFulfillmentMissingFulfillmentId()
{
$request = new UpdateFulfillmentRequest();
$this->fillModel($request);
$request->fulfillmentId = null;
$this->assertValid($request);
}
public function testUpdateFulfillmentMissingOrderId()
{
$request = new UpdateFulfillmentRequest();
$this->fillModel($request);
$request->orderId = null;
$this->assertValid($request);
}
public function testUpdateFulfillmentShippedStatus()
{
$request = new UpdateFulfillmentRequest();
$this->fillModel($request);
$request->fulfillmentStatus = 'SHIPPED';
$this->assertValid($request);
}
public function testUpdateFulfillmentRmaPendingStatus()
{
$request = new UpdateFulfillmentRequest();
$this->fillModel($request);
$request->fulfillmentStatus = 'RMA_PENDING';
$this->assertValid($request);
}
public function testUpdateFulfillmentReturnedStatus()
{
$request = new UpdateFulfillmentRequest();
$this->fillModel($request);
$request->fulfillmentStatus = 'RETURNED';
$this->assertValid($request);
}
public function testImportClickMissingSessionId()
{
$request = new ImportClickRequest();
$this->fillModel($request);
$request->sessionId = null;
$this->assertValid($request);
}
public function testQueryPurchasesMissingCustomerAndPurchaseAndOrder()
{
$request = new QueryPurchasesRequest();
$this->fillModel($request);
$request->purchaseId = null;
$request->orderId = null;
$this->assertValid($request);
}
public function testRefundPurchaseNotFullRefund()
{
$request = new RefundPurchaseRequest();
$this->fillModel($request);
$request->fullRefund = false;
$this->assertValid($request);
}
public function testQueryCustomerHistoryMissingCustomer(){
$request = new QueryCustomerHistoryRequest();
$this->fillModel($request);
$request->customerId = null;
$this->assertValid($request);
}
public function testQueryClubMembersMissingMemberId(){
$request = new QueryClubMembersRequest();
$this->fillModel($request);
$request->memberId = null;
$this->assertValid($request);
}
public function testQueryClubMembersMissingPurchaseId(){
$request = new QueryClubMembersRequest();
$this->fillModel($request);
$request->purchaseId = null;
$this->assertValid($request);
}
public function testQueryClubMembersMissingOrderId(){
$request = new QueryClubMembersRequest();
$this->fillModel($request);
$request->orderId = null;
$this->assertValid($request);
}
public function testTransactionQueryMissingPurchaseId(){
$request = new QueryTransactionsRequest();
$this->fillModel($request);
$request->purchaseId = null;
$this->assertValid($request);
}
public function testTransactionQueryMissingOrderId(){
$request = new QueryTransactionsRequest();
$this->fillModel($request);
$request->orderId = null;
$this->assertValid($request);
}
public function assertValid(Request $request)
{
try {
$request->validate();
} catch (ValidationException $v) {
$this->fail("Failed to validate " . get_class($request) . ": " . json_encode($v->validator->failed()));
}
}
public function assertInvalid(Request $request)
{
try {
$request->validate();
} catch (ValidationException $v) {
$this->assertTrue(true);
return true;
}
$this->fail("Unexpected valid data in " . get_class($request));
}
}
|
HassleTauf/konnektive-crm
|
tests/Request/RequestTest.php
|
PHP
|
mit
| 15,175
|
'use strict';
const { createController } = require('../controller');
describe('Default Controller', () => {
test('Creates Collection Type default actions', () => {
const service = {};
const contentType = {
modelName: 'testModel',
kind: 'collectionType',
};
const controller = createController({ service, contentType });
expect(controller).toEqual({
find: expect.any(Function),
findOne: expect.any(Function),
create: expect.any(Function),
update: expect.any(Function),
delete: expect.any(Function),
});
});
test('Creates Single Type default actions', () => {
const service = {};
const contentType = {
modelName: 'testModel',
kind: 'singleType',
};
const controller = createController({ service, contentType });
expect(controller).toEqual({
find: expect.any(Function),
update: expect.any(Function),
delete: expect.any(Function),
});
});
});
|
wistityhq/strapi
|
packages/core/strapi/lib/core-api/__tests__/controller.test.js
|
JavaScript
|
mit
| 973
|
import { combineReducers } from 'redux';
import loginStatus from './loginStatus';
import getModuleStatusReducer from '../../lib/getModuleStatusReducer';
export function getLoginStatusReducer(types) {
return (state = null, { type, loggedIn, refreshTokenValid }) => {
switch (type) {
case types.login:
return loginStatus.loggingIn;
case types.loginSuccess:
case types.refreshSuccess:
case types.cancelLogout:
return loginStatus.loggedIn;
case types.loginError:
case types.logoutSuccess:
case types.logoutError:
return loginStatus.notLoggedIn;
case types.refreshError:
return refreshTokenValid ? state : loginStatus.notLoggedIn;
case types.logout:
return loginStatus.loggingOut;
case types.beforeLogout:
return loginStatus.beforeLogout;
case types.initSuccess:
case types.tabSync:
return loggedIn ? loginStatus.loggedIn : loginStatus.notLoggedIn;
default:
return state;
}
};
}
export function getTokenReducer(types) {
return (state = {}, { type, token, refreshTokenValid }) => {
switch (type) {
case types.loginSuccess:
case types.refreshSuccess:
return {
ownerId: token.owner_id,
endpointId: token.endpoint_id,
accessToken: token.access_token,
expireTime: token.expire_time,
expiresIn: token.expires_in,
};
case types.loginError:
case types.logoutSuccess:
case types.logoutError:
return {};
case types.refreshError:
if (refreshTokenValid) {
return state;
}
return {};
case types.initSuccess:
case types.tabSync:
if (token) {
return {
ownerId: token.owner_id,
endpointId: token.endpoint_id,
accessToken: token.access_token,
expireTime: token.expire_time,
expiresIn: token.expires_in,
};
}
return {};
default:
return state;
}
};
}
export function getFreshLoginReducer(types) {
return (state = null, { type, loggedIn }) => {
switch (type) {
case types.initSuccess:
case types.tabSync:
return loggedIn ? false : null;
case types.login:
return true;
case types.loginError:
case types.refreshError:
case types.logoutSuccess:
case types.logoutError:
return null;
default:
return state;
}
};
}
export default function getAuthReducer(types) {
return combineReducers({
status: getModuleStatusReducer(types),
loginStatus: getLoginStatusReducer(types),
freshLogin: getFreshLoginReducer(types),
token: getTokenReducer(types),
});
}
|
ringcentral/ringcentral-js-integration-commons
|
src/modules/Auth/getAuthReducer.js
|
JavaScript
|
mit
| 2,784
|
using System.Collections.Generic;
using System.IO;
namespace Nuxleus.WebService {
public struct PutObjectResponse : IResponse {
public KeyValuePair<string, string>[] Headers { get; set; }
public MemoryStream Response { get; set; }
}
}
|
Microsoft/vsminecraft
|
dependencies/protobuf-net/SilverlightExtended/Nuxleus.WebService/PutObjectResponse.cs
|
C#
|
mit
| 264
|
'use strict';
import * as ev from 'events';
import * as vsc from 'vscode';
import * as dcdUtil from './dcd/util';
import * as dscannerUtil from './dscanner/util';
import * as misc from './misc';
import Dub from './dub';
import Server from './dcd/server';
import Client from './dcd/client';
import Dfmt from './dfmt';
import Dscanner from './dscanner/dscanner';
export default class Provider extends ev.EventEmitter implements
vsc.CompletionItemProvider,
vsc.SignatureHelpProvider,
vsc.DefinitionProvider,
vsc.HoverProvider,
vsc.DocumentFormattingEditProvider,
vsc.DocumentSymbolProvider,
vsc.WorkspaceSymbolProvider,
vsc.CodeActionProvider,
vsc.TaskProvider {
public provideCompletionItems(
document: vsc.TextDocument,
position: vsc.Position,
token: vsc.CancellationToken
): Promise<any> {
return this.dcdProvide(document, position, token, dcdUtil.Operation.Completion);
}
public provideSignatureHelp(
document: vsc.TextDocument,
position: vsc.Position,
token: vsc.CancellationToken
): Promise<any> {
return this.dcdProvide(document, position, token, dcdUtil.Operation.Calltips);
}
public provideDefinition(
document: vsc.TextDocument,
position: vsc.Position,
token: vsc.CancellationToken
): Promise<any> {
return this.dcdProvide(document, position, token, dcdUtil.Operation.Definition);
}
public provideHover(
document: vsc.TextDocument,
position: vsc.Position,
token: vsc.CancellationToken
): Promise<any> {
return this.dcdProvide(document, position, token, dcdUtil.Operation.Documentation);
}
public provideDocumentFormattingEdits(
document: vsc.TextDocument,
options: vsc.FormattingOptions,
token: vsc.CancellationToken
): Promise<vsc.TextEdit[]> {
let dfmt = new Dfmt(document, options, token);
return new Promise(dfmt.execute.bind(dfmt));
}
public provideDocumentSymbols(
document: vsc.TextDocument,
token: vsc.CancellationToken
): Promise<vsc.SymbolInformation[]> {
let dscanner = new Dscanner(document, token, dscannerUtil.Operation.DocumentSymbols);
return new Promise(dscanner.execute.bind(dscanner));
}
public provideWorkspaceSymbols(
query: string,
token: vsc.CancellationToken
): Promise<vsc.SymbolInformation[]> {
return new Promise((resolve, reject) => {
vsc.workspace.findFiles('**/*.d*', null).then((uris) => {
let promises: PromiseLike<vsc.SymbolInformation[]>[] = uris.map((uri) => {
return vsc.workspace.openTextDocument(uri).then((document) => {
if (document && document.languageId === 'd') {
let dscanner = new Dscanner(document, token, dscannerUtil.Operation.WorkspaceSymbols);
return new Promise<vsc.SymbolInformation[]>(dscanner.execute.bind(dscanner));
}
});
});
Promise.all(promises).then((symbolInformationLists) =>
resolve(symbolInformationLists.reduce((previous, current) =>
current ? (previous || []).concat(current) : previous)));
});
});
}
public provideCodeActions(
document: vsc.TextDocument,
range: vsc.Range,
context: vsc.CodeActionContext,
token: vsc.CancellationToken
) {
let filteredDiagnostics = context.diagnostics
.filter((d) => d.range.isEqual(range))
.filter((d) => dscannerUtil.fixes.get(<string>d.code));
let actions = filteredDiagnostics
.filter((d) => dscannerUtil.fixes.get(<string>d.code).command)
.map((d) => {
let fix = dscannerUtil.fixes.get(<string>d.code);
return Object.assign({ arguments: [d, ...fix.getArgs(document, range)] }, fix.command);
});
let disablers = vsc.workspace.workspaceFolders
? filteredDiagnostics
.filter((d) => dscannerUtil.fixes.get(<string>d.code).checkName)
.map((d) => ({
title: 'Disable Check: ' + d.code,
command: 'dlang.actions.config',
arguments: [d.code]
}))
: [];
return actions.concat(disablers);
}
public provideTasks(token?: vsc.CancellationToken) {
let tasks = ['build', 'clean', 'test']
.map((name) => new vsc.Task({ type: 'dub', task: name }, name, 'dub',
new vsc.ProcessExecution(Dub.executable, [name], { cwd: misc.getRootPath() }),
['$dub-build', '$dub-test']));
tasks[0].group = vsc.TaskGroup.Build;
tasks[1].group = vsc.TaskGroup.Clean;
tasks[2].group = vsc.TaskGroup.Test;
return tasks;
}
public resolveTask(task: vsc.Task, token?: vsc.CancellationToken) {
return undefined;
}
private dcdProvide(
document: vsc.TextDocument,
position: vsc.Position,
token: vsc.CancellationToken,
operation: dcdUtil.Operation
) {
let client = new Client(document, position, token, operation);
client.on('error', () => {
if (!Server.instanceLaunched) {
this.emit('restart');
}
});
return new Promise(client.execute.bind(client));
}
};
|
dlang-vscode/dlang-vscode
|
src/provider.ts
|
TypeScript
|
mit
| 5,569
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Queue;
using Orleans.AzureUtils;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Tester;
using TestExtensions;
using Xunit;
namespace UnitTests.StorageTests
{
public class AzureQueueDataManagerTests : IClassFixture<AzureStorageBasicTestFixture>, IDisposable
{
private readonly Logger logger;
public static string DeploymentId = "aqdatamanagertests".ToLower();
private string queueName;
public AzureQueueDataManagerTests()
{
ClientConfiguration config = new ClientConfiguration();
config.TraceFilePattern = null;
LogManager.Initialize(config);
logger = LogManager.GetLogger("AzureQueueDataManagerTests", LoggerType.Application);
}
public void Dispose()
{
AzureQueueDataManager manager = GetTableManager(queueName).Result;
manager.DeleteQueue().Wait();
}
private async Task<AzureQueueDataManager> GetTableManager(string qName)
{
AzureQueueDataManager manager = new AzureQueueDataManager(qName, DeploymentId, TestDefaultConfiguration.DataConnectionString);
await manager.InitQueueAsync();
return manager;
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage"), TestCategory("AzureQueue")]
public async Task AQ_Standalone_1()
{
queueName = "Test-1-".ToLower() + Guid.NewGuid();
AzureQueueDataManager manager = await GetTableManager(queueName);
Assert.Equal(0, await manager.GetApproximateMessageCount());
CloudQueueMessage inMessage = new CloudQueueMessage("Hello, World");
await manager.AddQueueMessage(inMessage);
//Nullable<int> count = manager.ApproximateMessageCount;
Assert.Equal(1, await manager.GetApproximateMessageCount());
CloudQueueMessage outMessage1 = await manager.PeekQueueMessage();
logger.Info("PeekQueueMessage 1: {0}", AzureStorageUtils.PrintCloudQueueMessage(outMessage1));
Assert.Equal(inMessage.AsString, outMessage1.AsString);
CloudQueueMessage outMessage2 = await manager.PeekQueueMessage();
logger.Info("PeekQueueMessage 2: {0}", AzureStorageUtils.PrintCloudQueueMessage(outMessage2));
Assert.Equal(inMessage.AsString, outMessage2.AsString);
CloudQueueMessage outMessage3 = await manager.GetQueueMessage();
logger.Info("GetQueueMessage 3: {0}", AzureStorageUtils.PrintCloudQueueMessage(outMessage3));
Assert.Equal(inMessage.AsString, outMessage3.AsString);
Assert.Equal(1, await manager.GetApproximateMessageCount());
CloudQueueMessage outMessage4 = await manager.GetQueueMessage();
Assert.Null(outMessage4);
Assert.Equal(1, await manager.GetApproximateMessageCount());
await manager.DeleteQueueMessage(outMessage3);
Assert.Equal(0, await manager.GetApproximateMessageCount());
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage"), TestCategory("AzureQueue")]
public async Task AQ_Standalone_2()
{
queueName = "Test-2-".ToLower() + Guid.NewGuid();
AzureQueueDataManager manager = await GetTableManager(queueName);
IEnumerable<CloudQueueMessage> msgs = await manager.GetQueueMessages();
Assert.True(msgs == null || msgs.Count() == 0);
int numMsgs = 10;
List<Task> promises = new List<Task>();
for (int i = 0; i < numMsgs; i++)
{
promises.Add(manager.AddQueueMessage(new CloudQueueMessage(i.ToString())));
}
Task.WaitAll(promises.ToArray());
Assert.Equal(numMsgs, await manager.GetApproximateMessageCount());
msgs = new List<CloudQueueMessage>(await manager.GetQueueMessages(numMsgs));
Assert.Equal(numMsgs, msgs.Count());
Assert.Equal(numMsgs, await manager.GetApproximateMessageCount());
promises = new List<Task>();
foreach (var msg in msgs)
{
promises.Add(manager.DeleteQueueMessage(msg));
}
Task.WaitAll(promises.ToArray());
Assert.Equal(0, await manager.GetApproximateMessageCount());
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage"), TestCategory("AzureQueue")]
public async Task AQ_Standalone_3_Init_MultipleThreads()
{
queueName = "Test-4-".ToLower() + Guid.NewGuid();
const int NumThreads = 100;
Task<bool>[] promises = new Task<bool>[NumThreads];
for (int i = 0; i < NumThreads; i++)
{
promises[i] = Task.Run<bool>(async () =>
{
AzureQueueDataManager manager = await GetTableManager(queueName);
return true;
});
}
await Task.WhenAll(promises);
}
}
}
|
shayhatsor/orleans
|
test/TesterInternal/StorageTests/AzureQueueDataManagerTests.cs
|
C#
|
mit
| 5,269
|
#ifndef _LINUX_TYPES_H
#define _LINUX_TYPES_H
#include <asm/types.h>
#ifndef __ASSEMBLY__
#ifdef __KERNEL__
#define DECLARE_BITMAP(name,bits) \
unsigned long name[BITS_TO_LONGS(bits)]
#else
#ifndef __EXPORTED_HEADERS__
#warning "Attempt to use kernel headers from user space, see http://kernelnewbies.org/KernelHeaders"
#endif /* __EXPORTED_HEADERS__ */
#endif
#include <linux/posix_types.h>
#ifdef __KERNEL__
typedef __u32 __kernel_dev_t;
typedef __kernel_fd_set fd_set;
typedef __kernel_dev_t dev_t;
typedef __kernel_ino_t ino_t;
typedef __kernel_mode_t mode_t;
typedef unsigned short umode_t;
typedef __u32 nlink_t;
typedef __kernel_off_t off_t;
typedef __kernel_pid_t pid_t;
typedef __kernel_daddr_t daddr_t;
typedef __kernel_key_t key_t;
typedef __kernel_suseconds_t suseconds_t;
typedef __kernel_timer_t timer_t;
typedef __kernel_clockid_t clockid_t;
typedef __kernel_mqd_t mqd_t;
typedef _Bool bool;
typedef __kernel_uid32_t uid_t;
typedef __kernel_gid32_t gid_t;
typedef __kernel_uid16_t uid16_t;
typedef __kernel_gid16_t gid16_t;
typedef unsigned long uintptr_t;
#ifdef CONFIG_UID16
/* This is defined by include/asm-{arch}/posix_types.h */
typedef __kernel_old_uid_t old_uid_t;
typedef __kernel_old_gid_t old_gid_t;
#endif /* CONFIG_UID16 */
#if defined(__GNUC__)
typedef __kernel_loff_t loff_t;
#endif
/*
* The following typedefs are also protected by individual ifdefs for
* historical reasons:
*/
#ifndef _SIZE_T
#define _SIZE_T
typedef __kernel_size_t size_t;
#endif
#ifndef _SSIZE_T
#define _SSIZE_T
typedef __kernel_ssize_t ssize_t;
#endif
#ifndef _PTRDIFF_T
#define _PTRDIFF_T
typedef __kernel_ptrdiff_t ptrdiff_t;
#endif
#ifndef _TIME_T
#define _TIME_T
typedef __kernel_time_t time_t;
#endif
#ifndef _CLOCK_T
#define _CLOCK_T
typedef __kernel_clock_t clock_t;
#endif
#ifndef _CADDR_T
#define _CADDR_T
typedef __kernel_caddr_t caddr_t;
#endif
/* bsd */
typedef unsigned char u_char;
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
/* sysv */
typedef unsigned char unchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
#ifndef __BIT_TYPES_DEFINED__
#define __BIT_TYPES_DEFINED__
typedef __u8 u_int8_t;
typedef __s8 int8_t;
typedef __u16 u_int16_t;
typedef __s16 int16_t;
typedef __u32 u_int32_t;
typedef __s32 int32_t;
#endif /* !(__BIT_TYPES_DEFINED__) */
typedef __u8 uint8_t;
typedef __u16 uint16_t;
typedef __u32 uint32_t;
typedef __u64 uint64_t;
typedef __u64 u_int64_t;
typedef __signed__ long long int64_t;
/* this is a special 64bit data type that is 8-byte aligned */
#define aligned_u64 __u64 __attribute__((aligned(8)))
#define aligned_be64 __be64 __attribute__((aligned(8)))
#define aligned_le64 __le64 __attribute__((aligned(8)))
/**
* The type used for indexing onto a disc or disc partition.
*
* Linux always considers sectors to be 512 bytes long independently
* of the devices real block size.
*
* blkcnt_t is the type of the inode's block count.
*/
#ifdef CONFIG_LBDAF
typedef u64 sector_t;
typedef u64 blkcnt_t;
#else
typedef unsigned long sector_t;
typedef unsigned long blkcnt_t;
#endif
/*
* The type of an index into the pagecache. Use a #define so asm/types.h
* can override it.
*/
#ifndef pgoff_t
#define pgoff_t unsigned long
#endif
#ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
typedef u64 dma_addr_t;
#else
typedef u32 dma_addr_t;
#endif /* dma_addr_t */
#endif /* __KERNEL__ */
/*
* Below are truly Linux-specific types that should never collide with
* any application/library that wants linux/types.h.
*/
#ifdef __CHECKER__
#define __bitwise__ __attribute__((bitwise))
#else
#define __bitwise__
#endif
#ifdef __CHECK_ENDIAN__
#define __bitwise __bitwise__
#else
#define __bitwise
#endif
typedef __u16 __bitwise __le16;
typedef __u16 __bitwise __be16;
typedef __u32 __bitwise __le32;
typedef __u32 __bitwise __be32;
typedef __u64 __bitwise __le64;
typedef __u64 __bitwise __be64;
typedef __u16 __bitwise __sum16;
typedef __u32 __bitwise __wsum;
/*
* aligned_u64 should be used in defining kernel<->userspace ABIs to avoid
* common 32/64-bit compat problems.
* 64-bit values align to 4-byte boundaries on x86_32 (and possibly other
* architectures) and to 8-byte boundaries on 64-bit architetures. The new
* aligned_64 type enforces 8-byte alignment so that structs containing
* aligned_64 values have the same alignment on 32-bit and 64-bit architectures.
* No conversions are necessary between 32-bit user-space and a 64-bit kernel.
*/
#define __aligned_u64 __u64 __attribute__((aligned(8)))
#define __aligned_be64 __be64 __attribute__((aligned(8)))
#define __aligned_le64 __le64 __attribute__((aligned(8)))
#ifdef __KERNEL__
typedef unsigned __bitwise__ gfp_t;
typedef unsigned __bitwise__ fmode_t;
#ifdef CONFIG_PHYS_ADDR_T_64BIT
typedef u64 phys_addr_t;
#else
typedef u32 phys_addr_t;
#endif
typedef phys_addr_t resource_size_t;
typedef struct {
int counter;
} atomic_t;
#ifdef CONFIG_64BIT
typedef struct {
long counter;
} atomic64_t;
#endif
struct list_head {
struct list_head *next, *prev;
};
struct hlist_head {
struct hlist_node *first;
};
struct hlist_node {
struct hlist_node *next, **pprev;
};
struct ustat {
__kernel_daddr_t f_tfree;
__kernel_ino_t f_tinode;
char f_fname[6];
char f_fpack[6];
};
#endif /* __KERNEL__ */
#endif /* __ASSEMBLY__ */
typedef unsigned char u8_t;
typedef unsigned short u16_t;
typedef unsigned long u32_t;
typedef unsigned long long u64_t;
typedef unsigned int addr_t;
typedef unsigned int count_t;
#define false 0
#define true 1
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#define BITS_PER_LONG 32
#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
#define BUILD_BUG_ON_ZERO(e) (sizeof(char[1 - 2 * !!(e)]) - 1)
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
#define MTRR_TYPE_UNCACHABLE 0
#define MTRR_TYPE_WRCOMB 1
#define MTRR_TYPE_WRTHROUGH 4
#define MTRR_TYPE_WRPROT 5
#define MTRR_TYPE_WRBACK 6
#define MTRR_NUM_TYPES 7
int dbgprintf(const char* format, ...);
#define GFP_KERNEL 0
#define GFP_ATOMIC 0
//#include <stdio.h>
int snprintf(char *str, size_t size, const char *format, ...);
//#include <string.h>
void* memcpy(void *s1, const void *s2, size_t n);
void* memset(void *s, int c, size_t n);
size_t strlen(const char *s);
char *strcpy(char *s1, const char *s2);
char *strncpy (char *dst, const char *src, size_t len);
void *malloc(size_t size);
void* realloc(void* oldmem, size_t bytes);
#define kfree free
static inline void *krealloc(void *p, size_t new_size, gfp_t flags)
{
return realloc(p, new_size);
}
static inline void *kzalloc(size_t size, uint32_t flags)
{
void *ret = malloc(size);
memset(ret, 0, size);
return ret;
}
#define kmalloc(s,f) kzalloc((s), (f))
struct drm_file;
#define PAGE_SHIFT 12
#define PAGE_SIZE (1UL << PAGE_SHIFT)
#define PAGE_MASK (~(PAGE_SIZE-1))
#define ENTER() dbgprintf("enter %s\n",__FUNCTION__)
#define LEAVE() dbgprintf("leave %s\n",__FUNCTION__)
struct timeval
{
__kernel_time_t tv_sec; /* seconds */
__kernel_suseconds_t tv_usec; /* microseconds */
};
#define PCI_DEVICE_ID_ATI_RADEON_QY 0x5159
#ifndef __read_mostly
#define __read_mostly
#endif
/**
* struct callback_head - callback structure for use with RCU and task_work
* @next: next update requests in a list
* @func: actual update function to call after the grace period.
*/
struct callback_head {
struct callback_head *next;
void (*func)(struct callback_head *head);
};
#define rcu_head callback_head
#endif /* _LINUX_TYPES_H */
|
devlato/kolibrios-llvm
|
drivers/include/linux/types.h
|
C
|
mit
| 7,888
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Mailer;
use Symfony\Component\Mailer\Messenger\SendEmailMessage;
use Symfony\Component\Mailer\Transport\TransportInterface;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Mime\RawMessage;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class Mailer implements MailerInterface
{
private $transport;
private $bus;
public function __construct(TransportInterface $transport, MessageBusInterface $bus = null)
{
$this->transport = $transport;
$this->bus = $bus;
}
public function send(RawMessage $message, SmtpEnvelope $envelope = null): void
{
if (null === $this->bus) {
$this->transport->send($message, $envelope);
return;
}
$this->bus->dispatch(new SendEmailMessage($message, $envelope));
}
}
|
arjenm/symfony
|
src/Symfony/Component/Mailer/Mailer.php
|
PHP
|
mit
| 1,095
|
/* global describe, it */
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* 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.
*/
'use strict';
// Here to quiet down Connect logging errors
process.env.NODE_ENV = 'test';
// Indicate to swagger-tools that we're in testing mode
process.env.RUNNING_SWAGGER_TOOLS_TESTS = 'true';
var _ = require('lodash-compat');
var assert = require('assert');
var helpers = require('../helpers');
var request = require('supertest');
var petJson = _.cloneDeep(require('../../samples/1.2/pet.json'));
var rlJson = _.cloneDeep(require('../../samples/1.2/resource-listing.json'));
var storeJson = _.cloneDeep(require('../../samples/1.2/store.json'));
var userJson = _.cloneDeep(require('../../samples/1.2/user.json'));
var SecurityDef = function (allow, delay) {
var self = this;
if (allow === undefined) {
allow = true;
}
if (delay === undefined) {
delay = 0;
}
this.called = false;
this.func = function (request, securityDefinition, scopes, cb) {
assert(Array.isArray(scopes));
self.called = true;
setTimeout(function() {
cb(allow ? null : new Error('disallowed'));
}, delay);
};
};
var ApiKeySecurityDef = function() {
var self = this;
this.apiKey = undefined;
this.func = function(request, securityDefinition, key, cb) {
assert(key);
self.apiKey = key;
cb();
};
};
// Create security definitions
rlJson.authorizations.local = rlJson.authorizations.local2 = {
grantTypes: {
'authorization_code': {
tokenEndpoint: {
tokenName: 'auth_code',
url: 'http://petstore.swagger.wordnik.com/oauth/token'
},
tokenRequestEndpoint: {
clientIdName: 'client_id',
clientSecretName: 'client_secret',
url: 'http://petstore.swagger.wordnik.com/oauth/requestToken'
}
},
implicit: {
loginEndpoint: {
url: 'http://petstore.swagger.wordnik.com/oauth/dialog'
},
tokenName: 'access_token'
}
},
scopes: [
{
description: 'Modify pets in your account',
scope: 'write:pets'
},
{
description: 'Read your pets',
scope: 'read:pets'
},
{
description: 'Anything (testing)',
scope: 'test:anything'
}
],
type: 'oauth2'
};
rlJson.authorizations.apiKeyHeader = {
type: 'apiKey',
passAs: 'header',
keyname: 'X-API-KEY'
};
rlJson.authorizations.apiKeyQuery = {
type: 'apiKey',
passAs: 'query',
keyname: 'apiKey'
};
// Create paths
// Create paths
var swaggerRouterOptions = {
controllers: {}
};
_.forEach([
'secured',
'securedAnd',
'securedOr',
'unsecured',
'securedApiKeyQuery',
'securedApiKeyHeader'], function (name) {
var cApiDef = _.cloneDeep(petJson.apis[4]);
var authorizations;
var operation;
// Delete all but the 'GET' operation
_.forEach(cApiDef.operations, function (opDef, index) {
if (opDef.method !== 'GET') {
delete cApiDef.operations[index];
} else {
operation = opDef;
}
});
// Set the path
cApiDef.path = '/' + name;
// Add security
switch (name) {
case 'secured':
authorizations = {
local: [
{
description: 'Read your',
scope: 'read:pets'
}
]
};
break;
case 'securedAnd':
authorizations = {
local: [
{
description: 'Read your',
scope: 'read:pets'
}
],
local2: [
{
description: 'Read your',
scope: 'read:pets'
}
]
};
break;
case 'securedOr':
authorizations = {
local: [
{
description: 'Read your',
scope: 'read:pets'
}
],
local2: [
{
description: 'Read your',
scope: 'read:pets'
}
]
};
break;
case 'securedApiKeyQuery':
authorizations = {
apiKeyQuery: []
};
break;
case 'securedApiKeyHeader':
authorizations = {
apiKeyHeader: []
};
}
if (_.isUndefined(authorizations)) {
delete cApiDef.authorizations;
} else {
operation.authorizations = authorizations;
}
// Set the operation properties
operation.nickname = name;
// Make parameter optional
operation.parameters[0].required = false;
// Add the path
petJson.apis.push(cApiDef);
// Create handler
swaggerRouterOptions.controllers[name] = function (req, res) {
res.end('OK');
};
});
// Delete global security
delete petJson.authorizations;
describe('Swagger Security Middleware v1.2', function () {
it('should call middleware when secured', function(done) {
var localDef = new SecurityDef();
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: localDef.func
}
}, function (app) {
request(app)
.get('/api/secured')
.expect(200)
.end(function(err, res) {
helpers.expectContent('OK')(err, res);
assert(localDef.called);
done();
});
});
});
it('should not call middleware when unsecured', function (done) {
var localDef = new SecurityDef();
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: localDef.func
}
}, function (app) {
request(app)
.get('/api/unsecured')
.expect(200)
.end(function(err, res) {
helpers.expectContent('OK')(err, res);
assert(!localDef.called);
done();
});
});
});
it('should not authorize if handler denies', function(done) {
var localDef = new SecurityDef(false);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: localDef.func
}
}, function (app) {
request(app)
.get('/api/secured')
.expect(403)
.end(done);
});
});
// Not possible due to https://github.com/swagger-api/swagger-spec/issues/159
// describe('with global requirements', function () {
// it('should call global middleware when unsecured locally', function (done) {
// var cPetJson = _.cloneDeep(petJson);
// var globalDef = new SecurityDef();
// var localDef = new SecurityDef();
//
// cPetJson.authorizations = {
// oauth2: [
// {
// description: 'Read your pets',
// scope: 'read:pets'
// }
// ]
// };
//
// helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], {
// swaggerSecurityOptions: {
// oauth2: globalDef.func,
// local: localDef.func
// }
// }, function (app) {
// request(app)
// .get('/api/unsecured')
// .expect(200)
// .end(function(err) {
// if (err) { return done(err); }
//
// assert(globalDef.called);
// assert(!localDef.called);
//
// done();
// });
// });
// });
//
// it('should call local middleware when secured locally', function (done) {
// var cPetJson = _.cloneDeep(petJson);
// var globalDef = new SecurityDef();
// var localDef = new SecurityDef();
//
// cPetJson.authorizations = {
// oauth2: [
// {
// description: 'Read your pets',
// scope: 'read:pets'
// }
// ]
// };
//
// helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], {
// swaggerSecurityOptions: {
// oauth2: globalDef.func,
// local: localDef.func
// }
// }, function (app) {
// request(app)
// .get('/api/secured')
// .expect(200)
// .end(function(err) {
// if (err) { return done(err); }
//
// assert(localDef.called);
// assert(!globalDef.called);
//
// done();
// });
// });
// });
//
// it('should not authorize if handler denies', function (done) {
// var cPetJson = _.cloneDeep(petJson);
// var globalDef = new SecurityDef(false);
// var localDef = new SecurityDef(true);
//
// cPetJson.authorizations = {
// oauth2: [
// {
// description: 'Read your pets',
// scope: 'read:pets'
// }
// ]
// };
//
// helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], {
// swaggerSecurityOptions: {
// oauth2: globalDef.func,
// local: localDef.func
// }
// }, function (app) {
// request(app)
// .get('/api/unsecured')
// .expect(403)
// .end(done);
// });
// });
// });
describe('API Key support', function() {
it('in header', function (done) {
var security = new ApiKeySecurityDef();
var API_KEY = 'abc123';
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
apiKeyHeader: security.func
}
},
function(app) {
request(app)
.get('/api/securedApiKeyHeader')
.set({ 'X-API-KEY': API_KEY })
.expect(200)
.end(function(err) {
if (err) { return done(err); }
assert(security.apiKey === API_KEY);
done();
});
});
});
it('in query', function (done) {
var security = new ApiKeySecurityDef();
var API_KEY = 'abc123';
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
apiKeyQuery: security.func
}
},
function(app) {
request(app)
.get('/api/securedApiKeyQuery')
.query({ apiKey: API_KEY })
.expect(200)
.end(function(err) {
if (err) { return done(err); }
assert(security.apiKey === API_KEY);
done();
});
});
});
});
describe('AND requirements', function() {
it('should authorize if both are true', function (done) {
var local = new SecurityDef(true);
var local2 = new SecurityDef(true);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: local.func,
local2: local2.func
}
}, function (app) {
request(app)
.get('/api/securedAnd')
.expect(200)
.end(helpers.expectContent('OK', done));
});
});
it('should not authorize if first is false', function (done) {
var local = new SecurityDef(false);
var local2 = new SecurityDef(true);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: local.func,
local2: local2.func
}
}, function (app) {
request(app)
.get('/api/securedAnd')
.expect(200)
.end(helpers.expectContent('OK', done));
});
});
it('should not authorize if second is false', function (done) {
var local = new SecurityDef(true);
var local2 = new SecurityDef(false);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: local.func,
local2: local2.func
}
}, function (app) {
request(app)
.get('/api/securedAnd')
.expect(200)
.end(helpers.expectContent('OK', done));
});
});
it('should not authorize if both are false', function(done) {
var local = new SecurityDef(false);
var local2 = new SecurityDef(false);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: local.func,
local2: local2.func
}
}, function (app) {
request(app)
.get('/api/securedAnd')
.expect(403)
.end(done);
});
});
});
describe('OR requirements', function() {
it('should authorize if both are true', function(done) {
var local = new SecurityDef(true);
var local2 = new SecurityDef(true);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: local.func,
local2: local2.func
}
}, function (app) {
request(app)
.get('/api/securedOr')
.expect(200)
.end(helpers.expectContent('OK', done));
});
});
it('should authorize first if both are true', function(done) {
var local = new SecurityDef(true, 400);
var local2 = new SecurityDef(true);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: local.func,
local2: local2.func
}
}, function (app) {
request(app)
.get('/api/securedOr')
.expect(200)
.end(function(err, res) {
helpers.expectContent('OK')(err, res);
assert(!local2.called);
done();
});
});
});
it('should authorize if first is true', function(done) {
var local = new SecurityDef(true);
var local2 = new SecurityDef(false);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: local.func,
local2: local2.func
}
}, function (app) {
request(app)
.get('/api/securedOr')
.expect(200)
.end(helpers.expectContent('OK', done));
});
});
it('should authorize if second is true', function(done) {
var local = new SecurityDef(false);
var local2 = new SecurityDef(true);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: local.func,
local2: local2.func
}
}, function (app) {
request(app)
.get('/api/securedOr')
.expect(200)
.end(helpers.expectContent('OK', done));
});
});
it('should not authorize if both are false', function(done) {
var local = new SecurityDef(false);
var local2 = new SecurityDef(false);
helpers.createServer([rlJson, [petJson, storeJson, userJson]], {
swaggerRouterOptions: swaggerRouterOptions,
swaggerSecurityOptions: {
local: local.func,
local2: local2.func
}
}, function (app) {
request(app)
.get('/api/securedOr')
.expect(403)
.end(done);
});
});
});
});
|
MaxKramnik/swagger-tools
|
test/1.2/test-middleware-swagger-security.js
|
JavaScript
|
mit
| 16,860
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pages extends Model
{
//
}
|
amravazzi/knock-knock
|
app/Pages.php
|
PHP
|
mit
| 101
|
module.exports = utest;
utest.Collection = require('./lib/Collection');
utest.TestCase = require('./lib/TestCase');
utest.BashReporter = require('./lib/reporter/BashReporter');
var collection;
var reporter;
function utest(name, tests) {
if (!collection) {
collection = new utest.Collection();
reporter = new utest.BashReporter({collection: collection});
}
var testCase = new utest.TestCase({name: name, tests: tests});
collection.add(testCase);
};
|
Metadas/Drone-Control
|
node_modules/urun/node_modules/utest/index.js
|
JavaScript
|
mit
| 478
|
# Microsoft.Activities.Build.Validation
``` diff
+namespace Microsoft.Activities.Build.Validation {
+ public class DeferredValidationTask : Task {
+ public DeferredValidationTask();
+ public string DeferredValidationErrorsFilePath { get; set; }
+ public override bool Execute();
+ }
+ public class ReportDeferredValidationErrorsTask : Task {
+ public ReportDeferredValidationErrorsTask();
+ public string DeferredValidationErrorsFilePath { get; set; }
+ public override bool Execute();
+ }
+}
```
|
ericstj/standard
|
docs/comparisons/netstandard2.0_vs_net461/Microsoft.Activities.Build.Validation.md
|
Markdown
|
mit
| 553
|
/* Orange Color */
a, a:visited{
color: #ff8421;
}
a:hover{
color: #ff9641;
}
.color{
color: #ff9641;
}
.button a, .button a:visited{
background:#ff9641;
}
.button a:hover{
background:#ff8421;
}
/* Header */
header .hlinks > span{
background: #ff9641;
border: 1px solid #ff8421;
}
/* Navigation */
.navbar{
background:#ff9641;
border-top: 1px solid #ff8421;
border-bottom: 1px solid #ff8421;
}
.navbar button{
background: #ff8421;
}
.navbar button:hover{
background: #ff8421;
}
.navbar .nav{
border-left: 1px solid #ff8421;
}
.navbar .nav > li > a{
border-right: 1px solid #ff8421;
}
.navbar .nav > li > a:hover{
background: #ff8421 !important;
}
.navbar .nav .active > a,
.navbar .nav .active > a:hover,
.navbar .nav .active > a:focus {
background: #ff8421 !important;
}
.dropdown-toggle{
background: #ff9641 !important;
}
.nav-collapse .nav > li > a{
background: #ff9641 !important;
}
.nav .open>a, .nav .open>a:hover, .nav .open>a:focus {
border-color: #ff8421;
}
/* Sidebar nav */
#nav > li > a {
border-left: 3px solid #ff9641;
}
/* Sidebar page navigation */
#navi > li > a {
border-left: 3px solid #ff9641;
}
/* Title */
.title i{
color: #ff9641;
}
/* Recent posts carousel */
.recent-news .item h4 a span{
color:#ff9641;
}
.recent-news .custom-nav a i{
background: #ff9641;
}
/* Blog */
.posts .tags a{
background:#ff9641;
border:1px solid #ff8421;
}
.posts .tags a:hover{
background:#ff8421;
border:1px solid #ff8421;
}
.paging a:hover{
background: #ff9641;
border:1px solid #ff8421;
}
.paging .current{
background: #ff9641;
border:1px solid #ff8421;
}
/* Sidebar */
.sidebar .widget{
border-top: 1px solid #ff9641;
}
/* Career */
.nav-tabs > li > a:hover{
background: #ff9641;
}
/* Back to top */
.totop a, .totop a:visited{
background: #ff9641;
}
.totop a:hover{
background: #ff8421;
}
/* Footer */
footer{
border-top: 4px solid #ff9641;
}
|
lesario/tiketbaik.com
|
assets/css/orange.css
|
CSS
|
mit
| 1,926
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.